ソースを参照

Merge branch 'V3_API' into V3

Iñigo Valentin 8 年 前
コミット
756f85a934

+ 2 - 2
www/.htaccess

@@ -48,8 +48,8 @@ RewriteRule ^traducir/en[\/]?$ /traducir/index.php?l=en [NC]
 
 #API redirections
 #TODO: This changes the url in the browser
-RewriteRule ^API/V([{0-9}]+)/help/([A-Z\-a-z0-9{3,}]+)$ /API/V$1/help/$2.php [NC,QSA,L]
-RewriteRule ^API/V([{0-9}]+)/help/([A-Z\-a-z0-9{3,}]+)/$ /API/V$1/help/$2.php [L,NC]
+#RewriteRule ^API/V([{0-9}]+)/help/([A-Z\-a-z0-9{3,}]+)$ /API/V$1/help/$2.php [NC,QSA,L]
+#RewriteRule ^API/V([{0-9}]+)/help/([A-Z\-a-z0-9{3,}]+)/$ /API/V$1/help/$2.php [L,NC]
 
 #Force https TODO
 RewriteCond %{HTTPS} !=on

+ 85 - 58
www/API/v3/comment.php

@@ -1,15 +1,25 @@
 <?php
-    // Gasteizko Margolariak API v3 //
-
-    //Posible comment target
+    /**
+     * Gasteizko Margolariak API v3 - Comment
+     *
+     * Used to post comments from apps.
+     * This file is to be called directly from a URL request.
+     *
+     * https://margolariak.com/API/v3/help/
+     *
+     * @since 1.0.0
+     */
+
+
+    // Valid comment target
     define('TARGET_PHOTO', 'photo');
     define('TARGET_POST', 'post');
     define('TARGET_ACTIVITY', 'activity');
 
-    //Default target
+    // Default target
     define('DEF_TARGET', TARGET_ALL);
 
-    //$_GET valid parameters
+    // $_GET valid parameters
     define('GET_CLIENT', 'client');
     define('GET_USER', 'user');
     define('GET_TARGET', 'target');
@@ -20,14 +30,15 @@
     define('GET_LANG', 'lang');
 
 
-    /*****************************************************
-     * This function is called from almost everywhere at *
-     * the beggining of the page. It initializes the     *
-     * session variables and connects to the db.         *
-     *                                                   *
-     * @return: (MySQL server connection): The           *
-     *           connection handler.                     *
-     ****************************************************/
+    /**
+     * Initializes the MySQL database connection.
+     * 
+     * Called at the beggining of the script. It connects to the database using the
+     * parameters in the .htpasswd file. It also sets database and page encodings.
+     * 
+     * @since 1.0.0
+     * @return object Database connection.
+     */
     function startdb(){
         //Include the db configuration file. It's somehow like this
         /*
@@ -55,14 +66,16 @@
     }
 
 
-    /****************************************************
-    * This function selects the language for the        *
-    * comment if it has not been provided. It tries to  *
-    * detect the language cookie.                       *
-    *                                                   *
-    * @return: (string): Two letter language code or    *
-    * null.                                             *
-    ****************************************************/
+    /**
+     * Detects client language.
+     *
+     * Tries to detect the client language by detecting language cookie. It is
+     * not to be used from external apps, only from the site. Only detects
+     * spanish, basque or english.
+     * 
+     * @since 3.0.0
+     * @return string Two letter language code ('es', 'en' 'eu') or null.
+     */
     function detect_language(){
         //Try to read cookie.
         header('Cache-control: private');
@@ -78,23 +91,34 @@
     }
 
 
-    /*****************************************************
-     * Gets information about the comment from the get   *
-     * paameters and the browser info.                   *
-     *                                                   *
-     * @params:                                          *
-     *    con: (MySQL server connection) Db connector.   *
-     *    get: (string array) Contains the GET           *
-     *         parameters.                               *
-     * @return: (string array): Array with the keys      *
-     *           'client', 'user', 'target', 'id',       *
-     *           'permalink', 'username', 'text', 'lang' *
-     *           and 'status'. 'status' will contain a   *
-     *           4XX status code if some parameter is    *
-     *           missing, invalid, or the comment can't  *
-     *           be posted.                              *
-     *****************************************************/
-    function get_comment_info($con, $get){
+    /**
+     * Gets information about the comment.
+     *
+     * Gets all the information about the comment and the client from the
+     * request parameters and the browser info and packs it into an array.
+     * It also validates the data and check the permissions for posting the
+     * comment.
+     * 
+     * @since 3.0.0
+     * @param object $con Open database connection.
+     * @param array $get Optional. Array with the request parameters. Default
+     *                   is $_GET.
+     * @return array {
+     *     @type string client Client identifier. Empty if not provided.
+     *     @type string user User identifier. Empty if not provided.
+     *     @type string target The kind of content that the comment is meant
+     *                         to. 'photo', 'post' or 'activity'.
+     *     @type int id Photo, post, or activity ID.
+     *     @type string permalink Optional. Photo, post, or activity permalink.
+     *     @type string username Poster username.
+     *     @type string text Comment text.
+     *     @type string lang Two letter language code.
+     *     @type string status Request status to be returned based on comment 
+     *                  content. 204 (all good), 400 (bad data) or 403 (good
+     *                  data, but comments in the content are closed).
+     * }
+     */
+    function get_comment_info($con, $get = $_GET){
 
         $comment = array();
 
@@ -259,14 +283,12 @@
 
         //9th case: Comment for activity, id and no permalink.
         elseif ($comment["target"] == TARGET_ACTIVITY && strlen($comment["id"]) >= 1 && strlen($comment["permalink"]) < 1){
-        
             //Check if activity exists...
             $q = mysqli_query($con, "SELECT id, comments FROM activity WHERE visible = 1 AND id = $comment[id];");
             if (mysqli_num_rows($q) == 0){
                 $comment["status"] = 400; // Bad request status code.
             }
             else{
-            
                 //... and if it does, check if can be commented.
                 $r = mysqli_fetch_array($q);
                 $item_id = $r['id'];
@@ -275,17 +297,15 @@
                 }
             }
         }
-        
+
         //10th case: Comment for activity, permalink and id.
         elseif ($comment["target"] == TARGET_ACTIVITY && strlen($comment["id"]) >= 1 && strlen($comment["permalink"]) >= 1){
-        
             //Check if activity exists...
             $q = mysqli_query($con, "SELECT id, comments FROM activity WHERE visible = 1 AND permalink = '$comment[permalink]' AND id = $comment[id] ;");
             if (mysqli_num_rows($q) == 0){
                 $comment["status"] = 400; // Bad request status code.
             }
             else{
-            
                 //... and if it does, check if can be commented.
                 $r = mysqli_fetch_array($q);
                 $item_id = $r['id'];
@@ -297,16 +317,16 @@
     }
 
 
-    /*****************************************************
-     * Inserts the comment into the database.            *
-     *                                                   *
-     * @params:                                          *
-     *    con: (MySQL server connection) Db connector.   *
-     *    comment: (string array)  Array with the keys   *
-     *             'client', 'user', 'target', 'id',     *
-     *             'permalink', 'username', 'text',      *
-     *             'lang' and 'status'.                  *
-     *****************************************************/
+    /**
+     * Inserts the comment into the database.
+     * 
+     * Inserts the comment in the database. The table will be post_comment,
+     * photo_comment or activity_comment.
+     *
+     * @since 3.0.0
+     * @param object $con Open database connection.
+     * @param array $comment As returned by {@see get_comment_info($con, $get)}.
+     */
     function insert_comment($con, $comment){
         $query = "INSERT INTO ";
         switch ($comment["target"]){
@@ -330,14 +350,21 @@
         mysqli_query($con, $query);
     }
 
+
+    // SCRIPT START
+
+
     //Connect to the database
     $con = startdb('rw');
+    // Get all the info
     $comment = get_comment_info($con, $_GET);
-    if ($comment["status"] >= 400){ // 4XX or 5XX are errors.
-        http_response_code($comment["status"]);
+    // Set return status
+    http_response_code($comment["status"]);
+    // Save comment or exit badly.
+    if ($comment["status"] == 204){ // 4XX or 5XX are errors.
+        insert_comment($con, $comment);
+    }
+    else{
         exit(-1);
     }
-    insert_comment($con, $comment);
-    http_response_code(204);
-
 ?>

+ 222 - 140
www/API/v3/fastsync.php

@@ -1,5 +1,17 @@
  <?php
-    // Gasteizko Margolariak API v3 //
+    /**
+     * Gasteizko Margolariak API v3 - Fast Sync
+     *
+     * Used to sync data with apps with persistent storage (i.e. no web apps).
+     * This file is to be called directly from a URL request.
+     *
+     * It is intended to sync only the most important tables, as in an app
+     * initial sync.
+     *
+     * @link https://margolariak.com/API/v3/help/
+     *
+     * @since 3.0.0
+     */
 
     //Database section identifiers
     define('SEC_ALL', 'all');
@@ -36,7 +48,12 @@
     //Error messages
     define('ERR_CLIENT', 'CLIENT');
 
-    //List of all tables to sync, sorted by priority.
+
+    /**
+     * List of all tables that can be synced, sorted by priority / dependencies.
+     * 
+     * @var string $tab_list
+     */
     $tab_list = array(TAB_SETTINGS,             TAB_PLACE,          TAB_ROUTE_POINT,
                       TAB_ROUTE,                TAB_PEOPLE,         TAB_FESTIVAL_EVENT_GM,
                       TAB_FESTIVAL,             TAB_FESTIVAL_DAY,   TAB_FESTIVAL_OFFER,
@@ -44,24 +61,38 @@
                       TAB_ACTIVITY_ITINERARY,   TAB_SPONSOR,        TAB_ALBUM,
                       TAB_PHOTO,                TAB_PHOTO_ALBUM,    TAB_POST,
                       TAB_POST_IMAGE);
-                      
+
+
+    /**
+     * List of tables with content considered important.
+     * 
+     * @var string $tab_list
+     */
     $fast_tables = array(TAB_FESTIVAL_EVENT_GM,  TAB_FESTIVAL,             TAB_FESTIVAL_DAY,
                          TAB_FESTIVAL_OFFER,     TAB_FESTIVAL_EVENT_CITY,  TAB_ACTIVITY,
                          TAB_ACTIVITY_IMAGE,     TAB_ACTIVITY_ITINERARY,   TAB_PHOTO,
                          TAB_PHOTO_ALBUM,        TAB_POST,                 TAB_POST_IMAGE);
-    
+
+
+    /**
+     * List of tables with not-so-much relevant data.
+     * 
+     * @var string $tab_list
+     */
     $slow_tables = array(TAB_SETTINGS,  TAB_PLACE,  TAB_ROUTE_POINT,
                          TAB_ROUTE,     TAB_PEOPLE, TAB_SPONSOR,  
                          TAB_ALBUM);
 
-    /*****************************************************
-     * This function is called from almost everywhere at *
-     * the beggining of the page. It initializes the     *
-     * session variables and connects to the db.         *
-     *                                                   *
-     * @return: (MySQL server connection): The           *
-     *           connection handler.                     *
-     ****************************************************/
+
+    /**
+     * Initializes the MySQL database connection.
+     * 
+     * Called at the beggining of the script. It connects to the database using the
+     * parameters in the .htpasswd file. It also sets database and page encodings.
+     * 
+     * @since 3.0.0
+     * @return object Database connection.
+     */
     function startdb(){
         //Include the db configuration file. It's somehow like this
         /*
@@ -87,19 +118,19 @@
         //Return the db connection
         return $con;
     }
-    /*****************************************************
-     * Selects the value of a parameter from the list of *
-     * GET arguments. It also sanitizes it to prevent    *
-     * SQL injections.                                   *
-     *                                                   *
-     * @params:                                          *
-     *    con: (MySQL server connection) Db connector.   *
-     *    get: (string array) Contains the GET           *
-     *         parameters.                               *
-     *    param: (string) Name of the parameter.         *
-     * @return: (string): Value of the parameter or an   *
-     *          empty string if it was not passed.       *
-     *****************************************************/
+
+
+    /**
+     * Extracts a request parameter.
+     * 
+     * Extracts the value of a parameter from the list of GET parameters,
+     * sanitizing it to prevent SQL injections.
+     * 
+     * @since 3.0.0
+     * @param object $con Open database connection.
+     * @param string $param Key of the parameter to retrieve.
+     * @return string Value of the parameter or an empty string if it was not found.
+     */
     function extract_param($con, $get, $param){
         if(isset($_GET[$param])){
             return mysqli_real_escape_string($con, $_GET[$param]);
@@ -109,23 +140,28 @@
         }
     }
 
-    /*****************************************************
-     * Gets information about the API call and the       *
-     * assocciated client. If some mandatory parameter   *
-     * is not provided, a error log entry is registered  *
-     *                                                   *
-     * @params:                                          *
-     *    con: (MySQL server connection) Db connector.   *
-     *    get: (string array) Contains the GET           *
-     *         parameters.                               *
-     * @return: (string array): Array with the keys      *
-     *           'client', 'user', 'foreground', 'ip',   *
-     *           'os', 'browser', 'uagent' and 'error'.  *
-     *           'error' will contain the key of a       *
-     *           mandatory value if it has not been      *
-     *           provided, or will be empty if there     *
-     *           were no problem.                        *
-     *****************************************************/
+    /**
+     * Gets request info.
+     * 
+     * Gets information about the request by reading it's parameters.
+     * 
+     * @since 3.0.0
+     * @param object $con Open database connection.
+     * @param array $get Array with the request parameters.
+     * @return array {
+     *     @type string client Client identifier. Empty if not provided.
+     *     @type string user User identifier. Empty if not provided.
+     *     @type int foreground 1 if the sync is being made in the app
+     *                          foreground, 0 otherwise.
+     *     @type string ip Client IP.
+     *     @type string os Client operating system identifier. Empty if not
+     *                     found.
+     *     @type string browser Client browser identifier. Empty if not found.
+     *     @type string uagent Client user agent. Empty if not found.
+     *     @type string error Will contain ERR_CLIENT if the client was not
+     *                        specified, empty otherwise.
+     * }
+     */
     function get_user_info($con, $get){
         $info = array();
         $error = "";
@@ -148,18 +184,22 @@
         return $info;
     }
 
-    /*****************************************************
-     * Reads the version of the tables reported by the   *
-     * user as GET parameters.                           *
-     *                                                   *
-     * @params:                                          *
-     *    con: (MySQL server connection) Db connector.   *
-     *    get: (string array) Contains the GET           *
-     *         parameters.                               *
-     * @return: (int array): Array with the version of   *
-     *           the tables in the user app, keyed with  *
-     *           the table names.                        *
-     *****************************************************/
+
+    /**
+     * Reads the table version in the client app.
+     * 
+     * Reads the version of the tables reported by the user as GET parameters.
+     * Those parameters must be the same as the table names listed in 
+     * {@see $tab_list}.
+     * 
+     * @since 3.0.0
+     * @global array $tab_list Array with the names of the tables to sync.
+     * @param object $con Open database connection.
+     * @param array $get Array with the request parameters.
+     * @return array Integer array with the version of the tables reported in
+     *               the request, keyed with the table names. If no table
+     *               version was specified, the array will be empty.
+     */
     function get_user_versions($con, $get){
         global $tab_list;
         $versions = array();
@@ -169,21 +209,21 @@
         return $versions;
     }
 
-    /*****************************************************
-     * Reads the version of the tables reported by the   *
-     * user as GET parameters.                           *
-     *                                                   *
-     * @params:                                          *
-     *    con: (MySQL server connection) RO mode enough. *
-     *         parameters.                               *
-     * @return: (int array): Array with the version of   *
-     *           the tables in the server, keyed with    *
-     *           the table names.                        *
-     *****************************************************/
-    function get_server_versions($con){
 
+    /**
+     * Reads the table version in the server.
+     * 
+     * Reads from the database the version of the tables that sync with the
+     * clients and have important data.
+     * 
+     * @since 3.0.0
+     * @global array $fast_tables Array with the names of the tables to sync.
+     * @param object $con Open database connection.
+     * @return array Integer array with the version of the tables in the
+     *               database, keyed with the table names.
+     */
+    function get_server_versions($con){
         global $fast_tables;
-
         $versions = array();
         $q = mysqli_query($con, "SELECT section, version FROM version;");
 
@@ -198,17 +238,24 @@
         return $versions;
     }
 
-    /*****************************************************
-     * Select the tables that need to be synced.         *
-     *                                                   *
-     * @params:                                          *
-     *    user: (int array) Versions of tables in the    *
-     *          user app.                                *
-     *    server: (int array) Versions of tables in the  *
-     *            server.                                *
-     * @return: (string array): Array with the names of  *
-     *           the tables that need to be synced.      *
-     *****************************************************/
+
+    /**
+     * Select the tables that need to be synced.
+     * 
+     * Determines the tables in {@see $tab_list} that are out of sync between
+     * the server and the client.
+     *
+     * @since 3.0.0
+     * @global array $tab_list Array with the names of the tables that sync
+     *                         whit clients.
+     * @param object $con Open database connection.
+     * @param array $user Integer array with the version of the tables reported
+     *                    in the request, keyed with the table names.
+     * @param array $server Integer array with the version of the tables in the
+     *                      database, keyed with the table names.
+     * @return array String array with the name of the tables present in $user whose
+     *               versions are lower than the ones in $server.
+     */
     function select_tables($user, $server){
         global $tab_list;
         $tables = array();
@@ -220,20 +267,26 @@
         return $tables;
     }
 
-    /*****************************************************
-     * Formats the contents of ther 'versions' table,    *
-     * Only for the tables that will be synced.          *
-     *                                                   *
-     * @params:                                          *
-     *    con: (MySQL server connection) Db connector.   *
-     *    tables (String array): List of table.          *
-     * @return: (Assoc Array): Data in the table.        *
-     ****************************************************/
+
+    /**
+     * JSON-izes the versions of the tables to sync.
+     * 
+     * Generates a JSON-formatted string with the versions of all the tables
+     * to sync.
+     * 
+     * @since 3.0.0
+     * @global array $fast_tables Array with the names of the tables that sync
+     *                            whit clients and have important data.
+     * @global array $slow_tables Array with the names of the tables that sync
+     *                            whit clients and have less important data.
+     * @param object $con Open database connection.
+     * @param array $tables String array with the names of the tables.
+     * @return string JSON-formatted string with the version of the tables.
+     *                Empty string if no valid table names were passes in $tables.
+     */
     function get_table_version($con, $tables){
-    
         global $fast_tables;
         global $slow_tables;
-        
         // Build query, showing only tables to sync
         $s = "SELECT section, version FROM version WHERE ";
         foreach($tables as $table){
@@ -242,14 +295,12 @@
             }
         }
         $s = $s . "1 = 2 ";
-        
         $s =  $s . "UNION SELECT section, 0 AS version FROM version WHERE ";
         foreach($tables as $table){
             if (in_array($table, $fast_tables)){
                 $s = $s . "section = '$table' OR ";
             }
         }
-        
         $s = $s . "1 = 2;";
          $q = mysqli_query($con, $s);
 
@@ -266,21 +317,24 @@
         }
         $str = rtrim($str,',');
         $str = $str . "],";
-        
+
         return $str;
 
     }
 
-    /*****************************************************
-     * Formats the contents of a table in the database.  *
-     * Inaccessible or sensitive tables or fields are    *
-     * not printed.                                      *
-     *                                                   *
-     * @params:                                          *
-     *    con: (MySQL server connection) RO mode enough. *
-     *    table (string): The name of the table.         *
-     * @return: (Assoc Array): Data in the table.        *
-     ****************************************************/
+
+    /**
+     * JSON-izes the data in a table.
+     * 
+     * Generates a JSON-formatted string with the data in a table. Inaccessible
+     * or sensitive tables or fields are not returned.
+     * 
+     * @since 3.0.0
+     * @param object $con Open database connection.
+     * @param string $table Table name.
+     * @return string JSON-formatted string with the data in the table. Empty
+     *                string if $table was not a valid table name.
+     */
     function get_table($con, $table){
         $year = date("Y");
         $table = strtolower($table);
@@ -329,7 +383,7 @@
                 break;
             case TAB_POST_IMAGE:
                 $q = mysqli_query($con, "SELECT post_image.id AS id, post, image, idx FROM post_image, post WHERE post = post.id AND year(dtime) = $year;");
-                
+
             //Other cases:
             default:
                 $q = mysqli_query($con, "SELECT * FROM $table;");
@@ -351,14 +405,21 @@
         return $str;
     }
 
-    /*****************************************************
-     * Prints out required tables.                       *
-     *                                                   *
-     * @params:                                          *
-     *    con: (MySQL server connection) Db connector.   *
-     *    tables: (String array) List of tables to sync. *
-     * @return: (String): Client IP address.             *
-     *****************************************************/
+
+    /**
+     * Gets the data on the requested tables.
+     * 
+     * Builds a JSON string with the data in all the requested tables.
+     * Inaccessible or sensitive tables or fields are not returned.
+     *
+     * @since 3.0.0
+     * @see get_table($con, $table)
+     * @param object $con Open database connection.
+     * @param array $tables String array with the names of the tables to sync.
+     * @return string JSON-formatted string with the data in the requested
+     *                tables. Empty string if no valid table names were
+     *                provided in $tables.
+     */
     function sync($con, $tables){
         $str = "";
         if(sizeof($tables) > 0){
@@ -375,11 +436,12 @@
         return false;
     }
 
-    /*****************************************************
-     * Gets the IP address of the client.                *
-     *                                                   *
-     * @return: (String): Client IP address.             *
-     *****************************************************/
+     /**
+     * Gets the user IP address.
+     * 
+     * @since 3.0.0
+     * @return string User IP address.
+     */
     function get_user_ip(){
         $client  = @$_SERVER['HTTP_CLIENT_IP'];
         $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
@@ -396,39 +458,59 @@
         return $ip;
     }
 
-    /*****************************************************
-     * Registers the request in the database.            *
-     *                                                   *
-     * @params:                                          *
-     *    con: (MySQL server connection) RO mode enough. *
-     *    user: (String array): Array with, at least,    *
-     *          the keys 'client', 'user', 'foreground', *
-     *          'ip', 'os', 'browser', 'uagent', with    *
-     *          info about the calling app.              *
-     *    synced: (Int): 1 if a sync content was sent, 0 *
-     *            otherwise.                             *
-     *****************************************************/
+
+    /**
+     * Logs a request to the database.
+     * 
+     * Creates an entry in the table 'sync' with the details of the request.
+     *
+     * @since 1.0.0
+     * @param object $con Open database connection.
+     * @param array $user {
+     *     @type string client Client identifier. Empty if not provided.
+     *     @type string user User identifier. Empty if not provided.
+     *     @type int foreground 1 if the sync is being made in the app
+     *                          foreground, 0 otherwise.
+     *     @type string ip Client IP.
+     *     @type string os Client operating system identifier. Empty if not 
+     *                     found.
+     *     @type string browser Client browser identifier. Empty if not found.
+     *     @type string uagent Client user agent. Empty if not found.
+     * }
+     * @param int synced 1 if sync data was finally sent, 0 otherwise.
+     */
     function log_sync($con, $user, $synced){
         mysqli_query($con, "INSERT INTO sync (client, user, fg, synced, ip, os, uagent) VALUES ('$user[client]', '$user[user]', $user[foreground], $synced, '$user[ip]', '$user[os]', '$user[uagent]');");
     }
 
-    /*****************************************************
-     * Registers a failed request in the database.       *
-     *                                                   *
-     * @params:                                          *
-     *    con: (MySQL server connection) RO mode enough. *
-     *    user: (String array): Array with, at least,    *
-     *          the keys 'client', 'user', 'foreground', *
-     *          'ip', 'os', 'browser', 'uagent', and     *
-     *          'error', with info about the calling     *
-     *           app. The 'error' key will contain an    *
-     *           error description.                      *
-     *****************************************************/
+
+    /**
+     * Logs a failed request to the database.
+     * 
+     * Creates an entry in the table 'sync' with the details of the failed request.
+     *
+     * @since 1.0.0
+     * @param object $con Open database connection.
+     * @param array $user {
+     *     @type string client Client identifier. Empty if not provided.
+     *     @type string user User identifier. Empty if not provided.
+     *     @type int foreground 1 if the sync is being made in the app
+     *                          foreground, 0 otherwise.
+     *     @type string ip Client IP.
+     *     @type string os Client operating system identifier. Empty if not 
+     *                     found.
+     *     @type string browser Client browser identifier. Empty if not found.
+     *     @type string uagent Client user agent. Empty if not found.
+     *     @type string error Error code.
+     * }
+     */
     function log_error($con, $user){
         mysqli_query($con, "INSERT INTO sync (client, user, fg, error, ip, os, uagent) VALUES ('$user[client]', '$user[user]', $user[foreground], $user[error], '$user[ip]', '$user[os]', '$user[uagent]');");
     }
 
 
+    // SCRIPT START
+
 
     // Connect to the database
     $con = startdb('rw');

BIN
www/API/v3/help/img/comment.png


BIN
www/API/v3/help/img/location.png


+ 0 - 0
www/img/logo/logo-api.png → www/API/v3/help/img/logo-api.png


BIN
www/API/v3/help/img/notification.png


BIN
www/API/v3/help/img/sync.png


+ 80 - 28
www/API/v3/help/index.php

@@ -1,56 +1,108 @@
-<?php 
-    $http_host = $_SERVER['HTTP_HOST']; 
-    $v = 1;
+<?php
+    $v = 3;
+    session_start();
+    $http_host = $_SERVER["HTTP_HOST"];
+    include("../../../functions.php");
+    $proto = getProtocol();
+    $con = startdb();
+    $server = "$proto$http_host";
+
+    //Language
+    $lang = selectLanguage();
+    include("lang/lang_" . $lang . ".php");
 ?>
 
 <!DOCTYPE html>
 <html>
     <head>
-        <meta content="text/html; charset=utf-8" http-equiv="content-type"/>
-        <meta charset="utf-8"/>
-        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1">
-        <title>Gasteizko Margolariak API v<?php echo($v); ?> Documentation</title>
-        <link rel="shortcut icon" href="<?php echo "http://$http_host/img/logo/favicon.ico";?>">
+        <meta content='text/html; charset=utf-8' http-equiv='content-type'/>
+        <meta charset='utf-8'/>
+        <meta name='viewport' content='width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1'>
+        <title>Gasteizko Margolariak API</title>
+        <link rel='shortcut icon' href='<?=$server?>/img/logo/favicon.ico'>
         <!-- CSS files -->
         <style>
             <?php 
                 include("../../../css/ui.css"); 
                 include("../../../css/index.css");
+                include("styles.css");
             ?>
         </style>
         <!-- CSS for mobile version -->
-        <style media="(max-width : 990px)">
+        <style media='(max-width : 990px)'>
             <?php 
                 include("../../../css/m/ui.css"); 
                 include("../../../css/m/index.css");
+                include("styles-m.css");
             ?>
         </style>
         <!-- Script files -->
-        <script type="text/javascript">
+        <script type='text/javascript'>
             <?php include("../../../script/ui.js"); ?>
         </script>
         <!-- Meta tags -->
-        <link rel="canonical" href="<?php echo "http://$http_host/API/help/V$v"; ?>"/>
-        <link rel="author" href="<?php echo "http://$http_host"; ?>"/>
-        <link rel="publisher" href="<?php echo "http://$http_host"; ?>"/>
-        <meta name="description" content="<?php echo $lng['index_description'];?>"/>
-        <meta property="og:title" content="Gasteizko Margolariak API v<?php echo($v); ?> Documentation"/>
-        <meta property="og:url" content="<?php echo "http://$http_host/API/help/V$v"; ?>"/>
-        <meta property="og:description" content="Gasteizko Margolariak API v<?php echo($v); ?> Documentation - Index page"/>
-        <meta property="og:image" content="<?php echo "http://$http_host/img/logo/logo-api.png";?>"/>
-        <meta property="og:site_name" content="Gasteizko Margolariak"/>
-        <meta property="og:type" content="website"/>
-        <meta property="og:locale" content="en"/>
-        <meta name="twitter:card" content="summary"/>
-        <meta name="twitter:title" content="Gasteizko Margolariak API v<?php echo($v); ?> Documentation""/>
-        <meta name="twitter:description" content="Gasteizko Margolariak API v<?php echo($v); ?> Documentation - Index page"/>
-        <meta name="twitter:image" content="<?php echo "http://$http_host/img/logo/logo-api.png";?>"/>
-        <meta name="twitter:url" content="<?php echo "http://$http_host/API/help/V$v"; ?>"/>
-        <meta name="robots" content="index follow"/>
+        <link rel='canonical' href='<?=$server?>/API/help/V<?=$v?>'/>
+        <link rel='author' href='<?=$server?>'/>
+        <link rel='publisher' href='<?=$server?>'/>
+        <meta name='description' content='Gasteizko Margolariak API v<?=$v?> documentation'/>
+        <meta property='og:title' content='Gasteizko Margolariak API'/>
+        <meta property='og:url' content='<?=$server?>/API/help/V<?=$v?>'/>
+        <meta property='og:description' content='Gasteizko Margolariak API v<?=$v?> documentation'/>
+        <meta property='og:image' content='<?=$server?>/img/logo/logo-api.png'/>
+        <meta property='og:site_name' content='Gasteizko Margolariak'/>
+        <meta property='og:type' content='website'/>
+        <meta property='og:locale' content='en'/>
+        <meta name='twitter:card' content='summary'/>
+        <meta name='twitter:title' content='Gasteizko Margolariak API'/>
+        <meta name='twitter:description' content='Gasteizko Margolariak API v<?=$v?> documentation'/>
+        <meta name='twitter:image' content='<?=$server?>/img/logo/logo-api.png'/>
+        <meta name='twitter:url' content='<?=$server?>/API/help/V<?=$v?>'/>
+        <meta name='robots' content='index follow'/>
     </head>
     <body>
         <?php include("toolbar.php"); ?>
-        <div id="content">
+        <div id='content'>
+            <div class='section'>
+                <h3 class='section_title'>Public APIs</h3>
+                <table id='main'>
+                    <tr>
+                        <td class='entry'>
+                            <h3>
+                                <img src='<?=$server?>/API/V<?=$v?>/help/img/sync.png'/>
+                                Data sync
+                            </h3>
+                            <p>Sync data from our site in your persistant-storage app so your users can use it offline.</p>
+                            <a href='<?=$server?>/API/v<?=$v?>/help/sync/'>Documentation and examples</a>
+                        </td>
+                        <td class='entry'>
+                            <h3>
+                                <img src='<?=$server?>/API/V<?=$v?>/help/img/comment.png'/>
+                                Comments
+                            </h3>
+                            <p>Post comment for the content in our site from your apps.</p>
+                            <a href='<?=$server?>/API/v<?=$v?>/help/comment/'>Documentation and examples</a>
+                        </td>
+                    </tr>
+                    <tr>
+                        <td class='entry'>
+                            <h3>
+                                <img src='<?=$server?>/API/V<?=$v?>/help/img/notification.png'/>
+                                Notifications
+                            </h3>
+                            <p>Get notifications sent to your app.</p>
+                            <a href='<?=$server?>/API/v<?=$v?>/help/notifications/'>Documentation and examples</a>
+                        </td>
+                        <td class='entry'>
+                            <h3>
+                                <img src='<?=$server?>/API/V<?=$v?>/help/img/location.png'/>
+                                Location
+                            </h3>
+                            <p>Be able to follow Gasteizko Margolariak in real time during activities and festivals.</p>
+                            <a href='<?=$server?>/API/v<?=$v?>/help/location/'>Documentation and examples</a>
+                        </td>
+                    </tr>
+                </table>
+            </div> <!-- .section -->
         </div>
     </body>
 </body>

+ 0 - 0
www/API/v3/help/styles-m.css


+ 35 - 0
www/API/v3/help/styles.css

@@ -0,0 +1,35 @@
+table#main{
+    width: 60%;
+    border: 0px;
+    display: block;
+    margin: auto 20% auto 20%;
+    border-spacing: 2em;
+    border-collapse: separate;
+}
+
+table#main tr td{
+    text-align: center;
+    width: 50%;
+    height: 8em;
+    padding: 0.5em;
+}
+
+table#main tr td h3{
+    font-size: 150%;
+}
+
+table#main tr td h3 img{
+    vertical-align: middle;
+    height: 2em;
+}
+
+table#main tr td a{
+    display: block;
+    background-color: #3355ff;
+    border: 0.1em solid #001166;
+    border-radius: 1.2em;
+    margin: 0.6em;
+    padding: 0.6em;
+    font-size: 120%;
+    color: #ffffff;
+}

+ 51 - 30
www/API/v3/help/sync.php

@@ -1,56 +1,77 @@
-<?php 
-    $http_host = $_SERVER['HTTP_HOST']; 
-    $v = 1;
+<?php
+    $v = 3;
+    session_start();
+    $http_host = $_SERVER["HTTP_HOST"];
+    include("../../../functions.php");
+    $proto = getProtocol();
+    $con = startdb();
+    $server = "$proto$http_host";
+
+    //Language
+    $lang = selectLanguage();
+    include("lang/lang_" . $lang . ".php");
 ?>
 
 <!DOCTYPE html>
 <html>
     <head>
-        <meta content="text/html; charset=utf-8" http-equiv="content-type"/>
-        <meta charset="utf-8"/>
-        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1">
-        <title>Gasteizko Margolariak API v<?php echo($v); ?> Documentation</title>
-        <link rel="shortcut icon" href="<?php echo "http://$http_host/img/logo/favicon.ico";?>">
+        <meta content='text/html; charset=utf-8' http-equiv='content-type'/>
+        <meta charset='utf-8'/>
+        <meta name='viewport' content='width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1'>
+        <title>Gasteizko Margolariak API</title>
+        <link rel='shortcut icon' href='<?=$server?>/img/logo/favicon.ico'>
         <!-- CSS files -->
         <style>
             <?php 
                 include("../../../css/ui.css"); 
                 include("../../../css/index.css");
+                include("styles.css");
             ?>
         </style>
         <!-- CSS for mobile version -->
-        <style media="(max-width : 990px)">
+        <style media='(max-width : 990px)'>
             <?php 
                 include("../../../css/m/ui.css"); 
                 include("../../../css/m/index.css");
+                include("styles-m.css");
             ?>
         </style>
         <!-- Script files -->
-        <script type="text/javascript">
+        <script type='text/javascript'>
             <?php include("../../../script/ui.js"); ?>
         </script>
         <!-- Meta tags -->
-        <link rel="canonical" href="<?php echo "http://$http_host/API/help/V$v"; ?>"/>
-        <link rel="author" href="<?php echo "http://$http_host"; ?>"/>
-        <link rel="publisher" href="<?php echo "http://$http_host"; ?>"/>
-        <meta name="description" content="<?php echo $lng['index_description'];?>"/>
-        <meta property="og:title" content="Gasteizko Margolariak API v<?php echo($v); ?> Documentation"/>
-        <meta property="og:url" content="<?php echo "http://$http_host/API/help/V$v"; ?>"/>
-        <meta property="og:description" content="Gasteizko Margolariak API v<?php echo($v); ?> Documentation - Index page"/>
-        <meta property="og:image" content="<?php echo "http://$http_host/img/logo/logo-api.png";?>"/>
-        <meta property="og:site_name" content="Gasteizko Margolariak"/>
-        <meta property="og:type" content="website"/>
-        <meta property="og:locale" content="en"/>
-        <meta name="twitter:card" content="summary"/>
-        <meta name="twitter:title" content="Gasteizko Margolariak API v<?php echo($v); ?> Documentation""/>
-        <meta name="twitter:description" content="Gasteizko Margolariak API v<?php echo($v); ?> Documentation - Index page"/>
-        <meta name="twitter:image" content="<?php echo "http://$http_host/img/logo/logo-api.png";?>"/>
-        <meta name="twitter:url" content="<?php echo "http://$http_host/API/help/V$v"; ?>"/>
-        <meta name="robots" content="index follow"/>
+        <link rel='canonical' href='<?=$server?>/API/help/V<?=$v?>'/>
+        <link rel='author' href='<?=$server?>'/>
+        <link rel='publisher' href='<?=$server?>'/>
+        <meta name='description' content='Gasteizko Margolariak API v<?=$v?> documentation'/>
+        <meta property='og:title' content='Gasteizko Margolariak API'/>
+        <meta property='og:url' content='<?=$server?>/API/help/V<?=$v?>'/>
+        <meta property='og:description' content='Gasteizko Margolariak API v<?=$v?> documentation'/>
+        <meta property='og:image' content='<?=$server?>/img/logo/logo-api.png'/>
+        <meta property='og:site_name' content='Gasteizko Margolariak'/>
+        <meta property='og:type' content='website'/>
+        <meta property='og:locale' content='en'/>
+        <meta name='twitter:card' content='summary'/>
+        <meta name='twitter:title' content='Gasteizko Margolariak API'/>
+        <meta name='twitter:description' content='Gasteizko Margolariak API v<?=$v?> documentation'/>
+        <meta name='twitter:image' content='<?=$server?>/img/logo/logo-api.png'/>
+        <meta name='twitter:url' content='<?=$server?>/API/help/V<?=$v?>'/>
+        <meta name='robots' content='index follow'/>
     </head>
     <body>
         <?php include("toolbar.php"); ?>
-        <div id="content">
-        </div>
+        <div id='content'>
+            <div class='section'>
+                <h3 class='section_title'>Sync API</h3>
+                <div class='entry'>
+                    <img class='api_logo' src=""<?=$server?>/API/help/V<?=$v?>/help/img/sync.png">
+                    <p>
+                        Sync the content of the web site with your storage persistant application. Make it so your users can access the info when they are online.
+                    </P>
+                    <h3>Overview</h3>
+                </div> <!-- .entry -->
+            </div> <!-- .section -->
+        </div> <!-- #content -->
     </body>
-</body>
+</html>

+ 17 - 17
www/API/v3/help/toolbar.php

@@ -1,27 +1,27 @@
- <div id="header" class="desktop">
-    <div id="header_content">
-        <img src="/img/logo/logo-api.png"/>
-        <div id="header_menu">
+ <div id='header' class='desktop'>
+    <div id='header_content'>
+        <img src='<?=$server?>/API/V<?=$v?>/help/img/logo-api.png'/>
+        <div id='header_menu'>
             <table>
                 <tr>
-                    <td><a href="http://<?php echo($http_host . "API/help/V$v/"); ?>">API documentation</a></td>
-                    <td><a href="http://<?php echo($http_host . "API/help/V$v/sync/"); ?>">Sync</a></td>
-                    <td><a href="http://<?php echo($http_host . "API/help/V$v/comment/"); ?>">Comment</a></td>
-                    <td><a href="http://<?php echo($http_host); ?>/">Main page</a></td>
+                    <td><a href='<?=$server?>/API/help/V$v/'>API documentation</a></td>
+                    <td><a href='<?=$server?>/API/help/V$v/sync/'>Sync</a></td>
+                    <td><a href='<?=$server?>/API/help/V$v/comment/'>Comment</a></td>
+                    <td><a href='<?=$server?>/'>Main page</a></td>
                 </tr>
             </table>
         </div>
     </div>
 </div>
-<div id="header_m" class="mobile">
-    <img src="/img/logo/logo-api.png" onClick='toggleMobileMenu();' id='mobile_logo'/>
-    <div id="header_menu_m">
-        <div id='header_m_title' onClick='openMobileMenu();' class='pointer'><span><img src='http://<?php echo $http_host; ?>/img/misc/slid-menu.png'/>&nbsp;&nbsp;&nbsp;&nbsp;<?php echo $cur_section; ?></span></div>
-        <div class='header_m_link'><a href="http://<?php echo($http_host . "API/help/V$v/"); ?>">API documentation</a></div>
-        <div class='header_m_link'><a href="http://<?php echo($http_host . "API/help/V$v/sync/"); ?>">Sync</a></div>
-        <div class='header_m_link'><a href="http://<?php echo($http_host . "API/help/V$v/comment/"); ?>">Comment</a></div>
-        <div class='header_m_link'><a href="http://<?php echo($http_host); ?>/">Main page</a></div>
-        <div id='header_m_slider' onClick='closeMobileMenu();' class='pointer'><span><img src='http://<?php echo $http_host; ?>/img/misc/slid-top.png'/></span></div>
+<div id='header_m' class='mobile'>
+    <img src='/img/logo/logo-api.png' onClick='toggleMobileMenu();' id='mobile_logo'/>
+    <div id='header_menu_m'>
+        <div id='header_m_title' onClick='openMobileMenu();' class='pointer'><span><img src='<?=$server?>/img/misc/slid-menu.png'/>&nbsp;&nbsp;&nbsp;&nbsp;<?=$cur_section?></span></div>
+        <div class='header_m_link'><a href='<?=$server?>/API/help/V$v/'>API documentation</a></div>
+        <div class='header_m_link'><a href='<?=$server?>/API/help/V$v/sync/'>Sync</a></div>
+        <div class='header_m_link'><a href='<?=$server?>/API/help/V$v/comment/'>Comment</a></div>
+        <div class='header_m_link'><a href='<?=$server?>/'>Main page</a></div>
+        <div id='header_m_slider' onClick='closeMobileMenu();' class='pointer'><span><img src='<?=$server?>/img/misc/slid-top.png'/></span></div>
     </div><br/><br/>
 </div>
 

+ 51 - 33
www/API/v3/location.php

@@ -1,14 +1,25 @@
 <?php
-    // Gasteizko Margolariak API v3 //
+    /**
+     * Gasteizko Margolariak API v3 - Location
+     *
+     * Used to get location reports.
+     * This file is to be called directly from a URL request.
+     *
+     * https://margolariak.com/API/v3/help/
+     *
+     * @since 1.0.0
+     */
 
-    /*****************************************************
-     * This function is called from almost everywhere at *
-     * the beggining of the page. It initializes the     *
-     * session variables and connects to the db.         *
-     *                                                   *
-     * @return: (MySQL server connection): The           *
-     *           connection handler.                     *
-     *****************************************************/
+
+    /**
+     * Initializes the MySQL database connection.
+     * 
+     * Called at the beggining of the script. It connects to the database using the
+     * parameters in the .htpasswd file. It also sets database and page encodings.
+     * 
+     * @since 1.0.0
+     * @return object Database connection.
+     */
     function startdb(){
         //Include the db configuration file. It's somehow like this
         /*
@@ -35,16 +46,22 @@
         return $con;
     }
 
-    /*****************************************************
-     * Retrieves the last reported location in the db,   *
-     * only if it was reported in the last 30 mins.      *
-     *                                                   *
-     * @params:                                          *
-     *    con: (MySQL server connection) Db connector.   *
-     * @return: (Double array): array with the 'lat',    *
-     *          'lon' and 'dtime' keys. null if nothing  *
-     *           to report.                              *
-     *****************************************************/
+
+    /**
+     * Retrieves the last location report.
+     *
+     * Retrieves the last reported location in the db, only if it was reported
+     * in the last 30 mins.
+     * 
+     * @since 3.0.0
+     * @param object $con Open database connection.
+     * @return null if there was no location report in the last 30 minutes or
+     *         array{
+     *     @type double lat Last location report latitude component.
+     *     @type double lon Last location report longitude component.
+     *     @type datetime dtime Last location report timestamp.
+     * }
+     */
     function get_location($con){
         $q = mysqli_query($con, "SELECT lat, lon, dtime FROM location WHERE action <> 'F' AND lat IS NOT null AND lon IS NOT null AND dtime > NOW() - INTERVAL 30 MINUTE ORDER BY dtime DESC LIMIT 1;");
         if (mysqli_num_rows($q) > 0){
@@ -58,27 +75,28 @@
         return null;
     }
 
-    /*****************************************************
-     * Prints info about the last location report, in    *
-     * the format:                                       *
-     * [{"lat":"<LAT>","lon":"<LON>","dtime":"<DTIME>"}] *
-     * where <LAT> and <LON> are doubles and <dtime> is  *
-     * the datetime of the report in format:             *
-     * 'YYYY-MM-DD hh:mm:ss'.                            *
-     *                                                   *
-     * @params:                                          *
-     *    con: (MySQL server connection) Db connector.   *
-     * @return: (Double array): array with the 'lat' and *
-     *          'lon' keys. null if nothing to report.   *
-     *****************************************************/
+
+    /**
+     * Prints the last location report.
+     *
+     * Prints info about the last location report, in the format:
+     *   [{"lat":"<LAT>","lon":"<LON>","dtime":"<DTIME>"}]
+     * where <LAT> and <LON> are doubles and <dtime> is the datetime of the
+     * report in format: 'YYYY-MM-DD hh:mm:ss'
+     * 
+     * @since 3.0.0
+     * @params array $location As generated by {@see get_location($con)}.
+     */
     function print_location($location){
         echo("[{\"lat\":\"$location[lat]\",\"lon\":\"$location[lon]\",\"dtime\":\"$location[dtime]\"}]");
     }
 
 
+    // SCRIPT START
+
 
     //Connect to the database
-    $con = startdb('rw');
+    $con = startdb('r');
 
     //Get location
     $location = get_location($con);

+ 65 - 43
www/API/v3/notifications.php

@@ -1,5 +1,15 @@
 <?php
-    // Gasteizko Margolariak API v3 //
+    /**
+     * Gasteizko Margolariak API v3 - Location
+     *
+     * Used to get notifications.
+     * This file is to be called directly from a URL request.
+     *
+     * https://margolariak.com/API/v3/help/
+     *
+     * @since 1.0.0
+     */
+
 
     //Posible notification target
     define('TARGET_ALL', 'all');
@@ -14,13 +24,16 @@
     //Error messages
     define('ERR_TARGET', '-TARGET:');
 
-    /*****************************************************
-     * Initializes the session variables and connects to * 
-     * the db.                                           *
-     *                                                   *
-     * @return: (MySQL server connection): The           *
-     *           connection handler.                     *
-     *****************************************************/
+
+    /**
+     * Initializes the MySQL database connection.
+     * 
+     * Called at the beggining of the script. It connects to the database using the
+     * parameters in the .htpasswd file. It also sets database and page encodings.
+     * 
+     * @since 1.0.0
+     * @return object Database connection.
+     */
     function startdb(){
         //Include the db configuration file. It's somehow like this
         /*
@@ -47,20 +60,23 @@
         return $con;
     }
 
-    /*****************************************************
-     * Discerns the type of notificatios to look for     *
-     * using the parameter 'target' from the list of get *
-     * arguments. Valid values are 'all'or 'gm'. The     *
-     * default is 'all'.                                 *
-     *                                                   *
-     * @params:                                          *
-     *    get: (String array) List of GET parameters.    *
-     * @return: (String): 'all' if it was passed as GET  *
-     *          parameter, 'gm' if it was passed or if   *
-     *          the parameter was not passed, or null if *
-     *          some other value was passed.             *
-     *****************************************************/
-    function get_target($get){
+
+    /**
+     * Discerns the type of notifications requested.
+     *
+     * Determines which notificatios the request is looking for: public
+     * notification or members-only notifications. To do so, it looks for a
+     * request parameter keyed 'target'
+     * 
+     * @since 3.0.0
+     * @param array $get Optional. Array with the request parameters. Default
+     *                   is $_GET.
+     * @return string 'all' or 'gm' if it was passed as the 'target' GET
+     *                parameter. 'gm' if there was no 'target' parameter or
+     *                null if some invalid value was passed as the 'target'
+     *                parameter.
+     */
+    function get_target($get = $_GET){
         $target = $get[GET_TARGET];
         if (strlen($target) < 1){
             return DEF_TARGET;
@@ -75,18 +91,19 @@
         }
     }
 
-    /*****************************************************
-     * Retrieves the notificatios that are still on time *
-     * to be delivered.                                  *
-     *                                                   *
-     * @params:                                          *
-     *    con: (MySQL server connection) Db connector.   *
-     *    target: (String) 'gm' or 'all'.                *
-     * @return: (String): The list of notifications to   *
-     *          be sent to the app, in JSON format, or   *
-     *          null if there are none.                  *
-     *****************************************************/
-    function select_notifications($con, $target){
+
+    /**
+     * Retrieves the notifications
+     *
+     * Retrieves the notificatios for the selected target that are still on
+     * time to be delivered and formats them as a JSON object.
+     * 
+     * @since 3.0.0
+     * @param object $con Open database connection.
+     * @param string $target Optional. 'gm' or 'all'. Default is 'all'.
+     * @return string JSON object with the fetched notifications.
+     */
+    function select_notifications($con, $target = TARGET_ALL){
         if ($target == TARGET_GM){
             $query = "SELECT id, title_es, title_en, title_eu, text_es, text_en, text_eu, dtime, internal AS gm, duration, action, 0 AS seen FROM notification WHERE internal = 1 AND dtime > NOW() - INTERVAL duration MINUTE ORDER BY dtime DESC";
         }
@@ -106,17 +123,23 @@
         }
     }
 
-    /*****************************************************
-     * Prints the notifications.                         *
-     *                                                   *
-     * @params:                                          *
-     *    notifications: (String) Notification list, in  *
-     *                   JSON format.                    *
-     *****************************************************/
+
+    /**
+     * Prints the notifications. 
+     * 
+     * @since 3.0.0
+     * @param string $notifications JSON object with the notifications,
+     *                              as generated by 
+     *                              {@see select_notifications($con, $target)}
+     */
     function print_notifications($notifications){
-        print($notifications);
+        echo($notifications);
     }
 
+
+    // SCRIPT START
+
+
     // Connect to the database
     $con = startdb('rw');
 
@@ -137,5 +160,4 @@
     else{
         print_notifications($notifications);
     }
-
 ?>

+ 212 - 140
www/API/v3/sync.php

@@ -1,13 +1,24 @@
  <?php
-    // Gasteizko Margolariak API v3 //
+    /**
+     * Gasteizko Margolariak API v3 - Sync
+     *
+     * Used to sync data with apps with persistent storage (i.e. no web apps).
+     * This file is to be called directly from a URL request.
+     *
+     * @link https://margolariak.com/API/v3/help/
+     *
+     * @since 1.0.0
+     */
 
-    //Database section identifiers
+
+    // Database section identifiers
     define('SEC_ALL', 'all');
     define('SEC_BLOG', 'blog');
     define('SEC_ACTIVITIES', 'activities');
     define('SEC_GALLERY', 'gallery');
     define('SEC_LABLANCA', 'lablanca');
 
+    // Tables
     define('TAB_ACTIVITY', 'activity');
     define('TAB_ACTIVITY_COMMENT', 'activity_comment');
     define('TAB_ACTIVITY_IMAGE', 'activity_image');
@@ -33,15 +44,20 @@
     define('TAB_SETTINGS', 'settings');
     define('TAB_SPONSOR', 'sponsor');
 
-    //$_GET valid parameters
+    // $_GET key parameters
     define('GET_CLIENT', 'client');
     define('GET_USER', 'user');
     define('GET_FOREGROUND', 'foreground');
 
-    //Error messages
+    // Error messages
     define('ERR_CLIENT', 'CLIENT');
 
-    //List of all tables to sync, sorted by priority.
+
+    /**
+     * List of all tables that can be synced, sorted by priority / dependencies.
+     * 
+     * @var string $tab_list
+     */
     $tab_list = [TAB_SETTINGS,             TAB_PLACE,          TAB_ROUTE_POINT,
                  TAB_ROUTE,                TAB_PEOPLE,         TAB_FESTIVAL_EVENT_GM,
                  TAB_FESTIVAL,             TAB_FESTIVAL_DAY,   TAB_FESTIVAL_OFFER,
@@ -51,14 +67,16 @@
                  TAB_POST_IMAGE,           TAB_PHOTO_COMMENT,  TAB_POST_COMMENT,
                  TAB_ACTIVITY_COMMENT,     TAB_ACTIVITY_TAG,   TAB_POST_TAG];
 
-    /*****************************************************
-     * This function is called from almost everywhere at *
-     * the beggining of the page. It initializes the     *
-     * session variables and connects to the db.         *
-     *                                                   *
-     * @return: (MySQL server connection): The           *
-     *           connection handler.                     *
-     ****************************************************/
+
+    /**
+     * Initializes the MySQL database connection.
+     * 
+     * Called at the beggining of the script. It connects to the database using the
+     * parameters in the .htpasswd file. It also sets database and page encodings.
+     * 
+     * @since 1.0.0
+     * @return object Database connection.
+     */
     function startdb(){
         //Include the db configuration file. It's somehow like this
         /*
@@ -84,20 +102,20 @@
         //Return the db connection
         return $con;
     }
-    /*****************************************************
-     * Selects the value of a parameter from the list of *
-     * GET arguments. It also sanitizes it to prevent    *
-     * SQL injections.                                   *
-     *                                                   *
-     * @params:                                          *
-     *    con: (MySQL server connection) Db connector.   *
-     *    get: (string array) Contains the GET           *
-     *         parameters.                               *
-     *    param: (string) Name of the parameter.         *
-     * @return: (string): Value of the parameter or an   *
-     *          empty string if it was not passed.       *
-     *****************************************************/
-    function extract_param($con, $get, $param){
+
+
+    /**
+     * Extracts a request parameter.
+     * 
+     * Extracts the value of a parameter from the list of GET parameters,
+     * sanitizing it to prevent SQL injections.
+     * 
+     * @since 3.0.0
+     * @param object $con Open database connection.
+     * @param string $param Key of the parameter to retrieve.
+     * @return string Value of the parameter or an empty string if it was not found.
+     */
+    function extract_param($con, $param){
         if(isset($_GET[$param])){
             return mysqli_real_escape_string($con, $_GET[$param]);
         }
@@ -106,33 +124,39 @@
         }
     }
 
-    /*****************************************************
-     * Gets information about the API call and the       *
-     * assocciated client. If some mandatory parameter   *
-     * is not provided, a error log entry is registered  *
-     *                                                   *
-     * @params:                                          *
-     *    con: (MySQL server connection) Db connector.   *
-     *    get: (string array) Contains the GET           *
-     *         parameters.                               *
-     * @return: (string array): Array with the keys      *
-     *           'client', 'user', 'foreground', 'ip',   *
-     *           'os', 'browser', 'uagent' and 'error'.  *
-     *           'error' will contain the key of a       *
-     *           mandatory value if it has not been      *
-     *           provided, or will be empty if there     *
-     *           were no problem.                        *
-     *****************************************************/
+
+    /**
+     * Gets request info.
+     * 
+     * Gets information about the request by reading it's parameters.
+     * 
+     * @since 3.0.0
+     * @param object $con Open database connection.
+     * @param array $get Array with the request parameters.
+     * @return array {
+     *     @type string client Client identifier. Empty if not provided.
+     *     @type string user User identifier. Empty if not provided.
+     *     @type int foreground 1 if the sync is being made in the app
+     *                          foreground, 0 otherwise.
+     *     @type string ip Client IP.
+     *     @type string os Client operating system identifier. Empty if not
+     *                     found.
+     *     @type string browser Client browser identifier. Empty if not found.
+     *     @type string uagent Client user agent. Empty if not found.
+     *     @type string error Will contain ERR_CLIENT if the client was not
+     *                        specified, empty otherwise.
+     * }
+     */
     function get_user_info($con, $get){
         $info = array();
         $error = "";
-        $info["client"] = extract_param($con, $get, GET_CLIENT);
+        $info["client"] = extract_param($con, GET_CLIENT);
         if(strlen($info["client"]) == 0) {
             error_log("SYNC ERROR: Trying to sync with no client name.");
             $error = ERR_CLIENT;
         }
-        $info["user"] = extract_param($con, $get, GET_USER);
-        $info["foreground"] = (int) extract_param($con, $get, GET_FOREGROUND);
+        $info["user"] = extract_param($con, GET_USER);
+        $info["foreground"] = (int) extract_param($con, GET_FOREGROUND);
         if($info["foreground"] != 1){
             $info["foreground"] = 0;
         }
@@ -145,38 +169,43 @@
         return $info;
     }
 
-    /*****************************************************
-     * Reads the version of the tables reported by the   *
-     * user as GET parameters.                           *
-     *                                                   *
-     * @params:                                          *
-     *    con: (MySQL server connection) Db connector.   *
-     *    get: (string array) Contains the GET           *
-     *         parameters.                               *
-     * @return: (int array): Array with the version of   *
-     *           the tables in the user app, keyed with  *
-     *           the table names.                        *
-     *****************************************************/
+
+    /**
+     * Reads the table version in the client app.
+     * 
+     * Reads the version of the tables reported by the user as GET parameters.
+     * Those parameters must be the same as the table names listed in 
+     * {@see $tab_list}.
+     * 
+     * @since 3.0.0
+     * @global array $tab_list Array with the names of the tables to sync.
+     * @param object $con Open database connection.
+     * @param array $get Array with the request parameters.
+     * @return array Integer array with the version of the tables reported in
+     *               the request, keyed with the table names. If no table
+     *               version was specified, the array will be empty.
+     */
     function get_user_versions($con, $get){
         global $tab_list;
         $versions = array();
         foreach($tab_list as $tab){
-            $versions[$tab] = intval(extract_param($con, $get, $tab));
+            $versions[$tab] = intval(extract_param($con, $tab));
         }
         return $versions;
     }
 
-    /*****************************************************
-     * Reads the version of the tables reported by the   *
-     * user as GET parameters.                           *
-     *                                                   *
-     * @params:                                          *
-     *    con: (MySQL server connection) RO mode enough. *
-     *         parameters.                               *
-     * @return: (int array): Array with the version of   *
-     *           the tables in the server, keyed with    *
-     *           the table names.                        *
-     *****************************************************/
+
+    /**
+     * Reads the table version in the server.
+     * 
+     * Reads from the database the version of the tables that sync with the
+     * clients.
+     * 
+     * @since 3.0.0
+     * @param object $con Open database connection.
+     * @return array Integer array with the version of the tables in the
+     *               database, keyed with the table names.
+     */
     function get_server_versions($con){
         $versions = array();
         $q = mysqli_query($con, "SELECT section, version FROM version;");
@@ -186,17 +215,24 @@
         return $versions;
     }
 
-    /*****************************************************
-     * Select the tables that need to be synced.         *
-     *                                                   *
-     * @params:                                          *
-     *    user: (int array) Versions of tables in the    *
-     *          user app.                                *
-     *    server: (int array) Versions of tables in the  *
-     *            server.                                *
-     * @return: (string array): Array with the names of  *
-     *           the tables that need to be synced.      *
-     *****************************************************/
+
+    /**
+     * Select the tables that need to be synced.
+     * 
+     * Determines the tables in {@see $tab_list} that are out of sync between
+     * the server and the client.
+     *
+     * @since 3.0.0
+     * @global array $tab_list Array with the names of the tables that sync
+     *                         whit clients.
+     * @param object $con Open database connection.
+     * @param array $user Integer array with the version of the tables reported
+     *                    in the request, keyed with the table names.
+     * @param array $server Integer array with the version of the tables in the
+     *                      database, keyed with the table names.
+     * @return array String array with the name of the tables present in $user whose
+     *               versions are lower than the ones in $server.
+     */
     function select_tables($user, $server){
         global $tab_list;
         $tables = array();
@@ -208,15 +244,19 @@
         return $tables;
     }
 
-    /*****************************************************
-     * Formats the contents of ther 'versions' table,    *
-     * Only for the tables that will be synced.          *
-     *                                                   *
-     * @params:                                          *
-     *    con: (MySQL server connection) Db connector.   *
-     *    tables (String array): List of table.          *
-     * @return: (Assoc Array): Data in the table.        *
-     ****************************************************/
+
+    /**
+     * JSON-izes the versions of the tables to sync.
+     * 
+     * Generates a JSON-formatted string with the versions of all the tables
+     * to sync.
+     * 
+     * @since 3.0.0
+     * @param object $con Open database connection.
+     * @param array $tables String array with the names of the tables.
+     * @return string JSON-formatted string with the version of the tables.
+     *                Empty string if no valid table names were passes in $tables.
+     */
     function get_table_version($con, $tables){
         // Build query, showing only tables to sync
         $s = "SELECT * FROM version WHERE ";
@@ -224,14 +264,14 @@
             $s = $s . "section = '$table' OR ";
         }
         $s = $s . "1 = 2;";
-         $q = mysqli_query($con, $s);
+        $q = mysqli_query($con, $s);
 
         //If no rows, return
         if (mysqli_num_rows($q) == 0){
             return "";
         }
 
-        //Create result array
+        //Create result JSON
         $str = "";
         $str = $str. "\"version\":[";
         while($r = mysqli_fetch_assoc($q)) {
@@ -243,16 +283,19 @@
 
     }
 
-    /*****************************************************
-     * Formats the contents of a table in the database.  *
-     * Inaccessible or sensitive tables or fields are    *
-     * not printed.                                      *
-     *                                                   *
-     * @params:                                          *
-     *    con: (MySQL server connection) RO mode enough. *
-     *    table (string): The name of the table.         *
-     * @return: (Assoc Array): Data in the table.        *
-     ****************************************************/
+
+    /**
+     * JSON-izes the data in a table.
+     * 
+     * Generates a JSON-formatted string with the data in a table. Inaccessible
+     * or sensitive tables or fields are not returned.
+     * 
+     * @since 1.0.0
+     * @param object $con Open database connection.
+     * @param string $table Table name.
+     * @return string JSON-formatted string with the data in the table. Empty
+     *                string if $table was not a valid table name.
+     */
     function get_table($con, $table){
         $table = strtolower($table);
         switch ($table){
@@ -305,14 +348,21 @@
         return $str;
     }
 
-    /*****************************************************
-     * Prints out required tables.                       *
-     *                                                   *
-     * @params:                                          *
-     *    con: (MySQL server connection) Db connector.   *
-     *    tables: (String array) List of tables to sync. *
-     * @return: (String): Client IP address.             *
-     *****************************************************/
+
+    /**
+     * Gets the data on the requested tables.
+     * 
+     * Builds a JSON string with the data in all the requested tables.
+     * Inaccessible or sensitive tables or fields are not returned.
+     *
+     * @since 1.0.0
+     * @see get_table($con, $table)
+     * @param object $con Open database connection.
+     * @param array $tables String array with the names of the tables to sync.
+     * @return string JSON-formatted string with the data in the requested
+     *                tables. Empty string if no valid table names were
+     *                provided in $tables.
+     */
     function sync($con, $tables){
         $str = "";
         if(sizeof($tables) > 0){
@@ -329,11 +379,13 @@
         return false;
     }
 
-    /*****************************************************
-     * Gets the IP address of the client.                *
-     *                                                   *
-     * @return: (String): Client IP address.             *
-     *****************************************************/
+
+    /**
+     * Gets the user IP address.
+     * 
+     * @since 1.0.0
+     * @return string User IP address.
+     */
     function get_user_ip(){
         $client  = @$_SERVER['HTTP_CLIENT_IP'];
         $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
@@ -350,39 +402,59 @@
         return $ip;
     }
 
-    /*****************************************************
-     * Registers the request in the database.            *
-     *                                                   *
-     * @params:                                          *
-     *    con: (MySQL server connection) RO mode enough. *
-     *    user: (String array): Array with, at least,    *
-     *          the keys 'client', 'user', 'foreground', *
-     *          'ip', 'os', 'browser', 'uagent', with    *
-     *          info about the calling app.              *
-     *    synced: (Int): 1 if a sync content was sent, 0 *
-     *            otherwise.                             *
-     *****************************************************/
+
+    /**
+     * Logs a request to the database.
+     * 
+     * Creates an entry in the table 'sync' with the details of the request.
+     *
+     * @since 1.0.0
+     * @param object $con Open database connection.
+     * @param array $user {
+     *     @type string client Client identifier. Empty if not provided.
+     *     @type string user User identifier. Empty if not provided.
+     *     @type int foreground 1 if the sync is being made in the app
+     *                          foreground, 0 otherwise.
+     *     @type string ip Client IP.
+     *     @type string os Client operating system identifier. Empty if not 
+     *                     found.
+     *     @type string browser Client browser identifier. Empty if not found.
+     *     @type string uagent Client user agent. Empty if not found.
+     * }
+     * @param int synced 1 if sync data was finally sent, 0 otherwise.
+     */
     function log_sync($con, $user, $synced){
         mysqli_query($con, "INSERT INTO sync (client, user, fg, synced, ip, os, uagent) VALUES ('$user[client]', '$user[user]', $user[foreground], $synced, '$user[ip]', '$user[os]', '$user[uagent]');");
     }
 
-    /*****************************************************
-     * Registers a failed request in the database.       *
-     *                                                   *
-     * @params:                                          *
-     *    con: (MySQL server connection) RO mode enough. *
-     *    user: (String array): Array with, at least,    *
-     *          the keys 'client', 'user', 'foreground', *
-     *          'ip', 'os', 'browser', 'uagent', and     *
-     *          'error', with info about the calling     *
-     *           app. The 'error' key will contain an    *
-     *           error description.                      *
-     *****************************************************/
+
+    /**
+     * Logs a failed request to the database.
+     * 
+     * Creates an entry in the table 'sync' with the details of the failed request.
+     *
+     * @since 1.0.0
+     * @param object $con Open database connection.
+     * @param array $user {
+     *     @type string client Client identifier. Empty if not provided.
+     *     @type string user User identifier. Empty if not provided.
+     *     @type int foreground 1 if the sync is being made in the app
+     *                          foreground, 0 otherwise.
+     *     @type string ip Client IP.
+     *     @type string os Client operating system identifier. Empty if not 
+     *                     found.
+     *     @type string browser Client browser identifier. Empty if not found.
+     *     @type string uagent Client user agent. Empty if not found.
+     *     @type string error Error code.
+     * }
+     */
     function log_error($con, $user){
         mysqli_query($con, "INSERT INTO sync (client, user, fg, error, ip, os, uagent) VALUES ('$user[client]', '$user[user]', $user[foreground], $user[error], '$user[ip]', '$user[os]', '$user[uagent]');");
     }
 
 
+    // SCRIPT START
+
 
     // Connect to the database
     $con = startdb('rw');