Jelajahi Sumber

Merge branch 'V3_INTERNAL_API' into V3_INTERNAL

Iñigo Valentin 9 tahun lalu
induk
melakukan
3c8fdebf61

+ 33 - 0
www-admin/API/v3/auth.php

@@ -0,0 +1,33 @@
+ <?php
+    // Gasteizko Margolariak API v3 //
+
+    // $_POST valid parameters
+    define('POST_USER', 'user');
+    define('POST_PASS', 'pass');
+
+    // Error messages
+    define('ERR_USER', '-USER:');
+
+    include('functions.php');
+    $con = startdb();
+
+    // Error control
+    $error = "";
+
+    // Get params
+    $user = mysqli_real_escape_string($con, $_POST[POST_USER]);
+    $pass = mysqli_real_escape_string($con, $_POST[POST_PASS]);
+
+    //Validate user
+    $uid = login($con, $user, $pass);
+    if ($uid == -1){
+        error_log(":SECURITY: Reporting location with wrong credentials (IP $_SERVER[REMOTE_ADDR])");
+        $error = $error . ERR_USER . mysqli_real_escape_string($con, $_POST[GET_USER]);
+        error_log($error);
+        http_response_code(403); // Forbidden
+        exit(-1);
+    }
+    else{
+        http_response_code(204); // No content
+    }
+?>

+ 188 - 0
www-admin/API/v3/functions.php

@@ -0,0 +1,188 @@
+<?php
+
+    $IMG_SIZE_PREVIEW = 600;
+    $IMG_SIZE_MINIATURE = 200;
+
+    /*****************************************************
+     * Finds out the protocol the user is connecting to  *
+     * the site with (http or https)                     *
+     * @return: (string): "http://" or "https://".       *
+     ****************************************************/
+    function getProtocol(){
+        if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
+                $protocol = 'https://';
+        }
+        else {
+                $protocol = 'http://';
+        }
+        return $protocol;
+    }
+
+    /*****************************************************
+     * Connects to the database, in 'r' or 'rw' mode.    *
+     * @params:                                          *
+     *    mode: (string) Indicates required permissions  *
+     *          on database. 'ro' gives read             *
+     *          permissions, and 'rw' read and write     *
+     *          permissions. Other values will result in *
+     *          errors.                                  *
+     * @return: (db connection): The connection handler. *
+     *****************************************************/
+    function startdb($mode = 'ro'){
+        //Include the db configuration file. It's somehow like this
+        /*
+        <?php
+            $host = 'XXXX';
+            $db_name = 'XXXX';
+            $username_ro = 'XXXX';
+            $username_rw = 'XXXX';
+            $pass_ro = 'XXXX';
+            $pass_rw = 'XXXX';
+        ?>
+        */
+        include('../../../www/.htpasswd');
+
+        //Connect to to database
+        if ($mode == 'ro')
+            $con = mysqli_connect($host, $username_ro, $pass_ro, $db_name);
+        else if ($mode == 'rw')
+            $con = mysqli_connect($host, $username_rw, $pass_rw, $db_name);
+
+        // Check connection
+        if (mysqli_connect_errno()){
+            error_log("Failed to connect to database: " . mysqli_connect_error());
+            return -1;
+        }
+
+        //Set encoding options
+        mysqli_set_charset($con, 'utf-8');
+        header('Content-Type: text/html; charset=utf8');
+        mysqli_query($con, 'SET NAMES utf8;');
+
+        //Return the db connection
+        return $con;
+    }
+
+
+    /*****************************************************
+     * This function closes all the opened HTML tags in  *
+     * a given string.                                   *
+     *                                                   *
+     * @params:                                          *
+     *    html: (string): The string with HTML tags      *
+     *****************************************************/
+    function closeTags($html) {
+        preg_match_all('#<(?!meta|img|br|hr|input\b)\b([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $html, $result);
+        $openedtags = $result[1];
+        preg_match_all('#</([a-z]+)>#iU', $html, $result);
+        $closedtags = $result[1];
+        $len_opened = count($openedtags);
+        if (count($closedtags) == $len_opened) {
+            return $html;
+        }
+        $openedtags = array_reverse($openedtags);
+        for ($i=0; $i < $len_opened; $i++) {
+            if (!in_array($openedtags[$i], $closedtags)) {
+                $html .= '</'.$openedtags[$i].'>';
+            } else {
+                unset($closedtags[array_search($openedtags[$i], $closedtags)]);
+            }
+        }
+        return $html;
+    }
+
+    /*****************************************************
+     * Text shortener. Given a string, it trims in the   *
+     * proximity of the desired streng, ut to the next   *
+     * white character. If indicated, it will append a   *
+     * link to the full text.                            *
+     *                                                   *
+     * @params:                                          *
+     *    text: (string): The text to shorten.           *
+     *    length: (int): The desired length.             *
+     *    linktext: (string): Text fot the link.         *
+     *    link: (string): URI of the full text.          *
+     *****************************************************/
+     function cutText($text, $length, $linktext, $link){
+        if (strlen($text) < $length){
+            return $text;
+        }
+        $cut = substr($text, 0, strpos($text, " ", $length));
+        $cut = closeTags($cut);
+        if (strlen($cut) == 0){
+            $cut = $text;
+        }
+        if (strlen($text) != strlen($cut)){
+            $cut = $cut . "... <a href='$link'>$linktext</a>";
+        }
+        return $cut;
+    }
+
+    /*****************************************************
+     * Generates a URL-valid string from a regular one.  *
+     *                                                   *
+     * @params:                                          *
+     *    text: (string): Original string.               *
+     * @return: (string): URL-valid string.              *
+     *****************************************************/
+    function permalink($text){
+        $unwanted_array = array('Š'=>'S', 'š'=>'s', 'Ž'=>'Z', 'ž'=>'z', 'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
+                            'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O', 'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U',
+                            'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss', 'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c',
+                            'è'=>'e', 'é'=>'e', 'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'õ'=>'o',
+                            'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'þ'=>'b', 'ÿ'=>'y' );
+        $str = strtr( $text, $unwanted_array );
+        $str = preg_replace('/[^\da-zA-Z ]/i', '', $str);
+        $str = str_replace(' ', '-', $str);
+        return $str;
+    }
+
+
+    /*****************************************************
+     * Validates a user/password combo.                  *
+     *                                                   *
+     * @params:                                          *
+     *    con: (Mysql connectrion): DB connection.       *
+     *    user: (string): Username.                      *
+     *    pass: (string): Password.                      *
+     * @return: (int): User id, or -1 if the user and    *
+	 *          pass didn't match.                       *
+     *****************************************************/
+    function login($con, $user, $pass){
+        session_start();
+        $q = mysqli_query($con,"SELECT id, salt, username AS username, sha1(salt) AS s FROM user WHERE (lower(username) = lower('$user') OR lower(email) = lower('$user')) AND password = sha1(concat('$pass', sha1(salt)));");
+        if (mysqli_num_rows($q) == 1){
+            $r = mysqli_fetch_array($q);
+            $_SESSION['id'] = $r['id'];
+            $_SESSION['salt'] = $r['s'];
+            $_SESSION['name'] = $r['username'];
+            return $r['id'];
+        }
+        else{
+            error_log("Invalid login. username = $user, id = $_SESSION[id]");
+            return -1;
+        }
+    }
+
+    /*****************************************************
+     * Finds out the IP address of the client.           *
+     *                                                   *
+     * @return: (String): Client IP address.             *
+     *****************************************************/
+    function getUserIP(){
+        $client  = @$_SERVER["HTTP_CLIENT_IP"];
+        $forward = @$_SERVER["HTTP_X_FORWARDED_FOR"];
+        $remote  = $_SERVER["REMOTE_ADDR"];
+        if(filter_var($client, FILTER_VALIDATE_IP)){
+            $ip = $client;
+        }
+        elseif(filter_var($forward, FILTER_VALIDATE_IP)){
+            $ip = $forward;
+        }
+        else{
+            $ip = $remote;
+        }
+        return $ip;
+    }
+
+?>

+ 13 - 47
www/API/v3/sendlocation.php → www-admin/API/v3/sendlocation.php

@@ -1,8 +1,9 @@
 <?php
+    // Gasteizko Margolariak API v3 //
 
     // $_GET valid parameters
-    define('GET_USER', 'user');
-    define('GET_PASS', 'pass');
+    define('POST_USER', 'user');
+    define('POST_PASS', 'pass');
     define('GET_ACTION', 'action');
     define('GET_LAT', 'lat');
     define('GET_LON', 'lon');
@@ -18,64 +19,29 @@
     define('ERR_ACTION', '-ACTION:');
     define('ERR_LOCATION', '-TITLE:');
 
-    /****************************************************
-    * This function is called from almost everywhere at *
-    * the beggining of the page. It initializes the     *
-    * session variables, connect to the db, enabling    *
-    * the variable $con for futher use everywhere in    *
-    * the php code, and populates the arrays $user      *
-    * and $permission, with info about the user.        *
-    *                                                   *
-    * @return: (db connection): The connection handler. *
-    ****************************************************/
-    function startdb(){
-        //Include the db configuration file. It's somehow like this
-        /*
-         <?php
-          $host = 'XXXX';
-          $db_name = 'XXXX';
-          $username_ro = 'XXXX';
-          $username_rw = 'XXXX';
-          $pass_ro = 'XXXX';
-          $pass_rw = 'XXXX';
-         ?>
-        */
-        include('../../.htpasswd');
-
-        //Connect to to database
-        $con = mysqli_connect($host, $username_rw, $pass_rw, $db_name);
-
-        //Set encoding options
-        mysqli_set_charset($con, 'utf-8');
-        header('Content-Type: text/html; charset=utf8');
-        mysqli_query($con, 'SET NAMES utf8;');
-
-        //Return the db connection
-        return $con;
-    }
+    include('functions.php');
 
     $con = startdb('rw');
     $error = "";
 
     //Get fields
-    $user = mysqli_real_escape_string($con, $_GET[GET_USER]);
-    $pass = mysqli_real_escape_string($con, $_GET[GET_PASS]);
+    
+    $user = mysqli_real_escape_string($con, $_POST[POST_USER]);
+    $pass = mysqli_real_escape_string($con, $_POST[POST_PASS]);
+    
     $lat = mysqli_real_escape_string($con, $_GET[GET_LAT]);
     $lon = mysqli_real_escape_string($con, $_GET[GET_LON]);
     $action = mysqli_real_escape_string($con, $_GET[GET_ACTION]);
-
+    
     //Validate user
-    $q = mysqli_query($con, "SELECT id FROM user WHERE (lower(username) = lower('$user') OR lower(email) = lower('$user')) AND password = sha1(concat('$pass', sha1(salt)))");
-    if (mysqli_num_rows($q) == 0){
+	$uid = login($con, $user, $pass);
+    if ($uid == -1){
         error_log(":SECURITY: Reporting location with wrong credentials (IP $_SERVER[REMOTE_ADDR])");
-        http_response_code(403); // Forbidden
-        $error = $error . ERR_USER . mysqli_real_escape_string($con, $_GET[GET_USER]);
+        $error = $error . ERR_USER . mysqli_real_escape_string($con, $user);
         error_log($error);
+        http_response_code(403); // Forbidden
         exit(-1);
     }
-    // Get id
-    $r = mysqli_fetch_array($q);
-    $uid = $r['id'];
 
     //Validate fields
     if (!in_array($action, $actions)){

+ 23 - 59
www/API/v3/sendnotification.php → www-admin/API/v3/sendnotification.php

@@ -1,10 +1,9 @@
 <?php
-    //include("../functions.php");
-    //$con = startdb('rw');
+    // Gasteizko Margolariak API v3 //
 
-    // $_GET valid parameters
-    define('GET_USER', 'user');
-    define('GET_PASS', 'pass');
+    // $_GET and $_POST valid parameters
+    define('POST_USER', 'user');
+    define('POST_PASS', 'pass');
     define('GET_TITLE_ES', 'title_es');
     define('GET_TITLE_EN', 'title_en');
     define('GET_TITLE_EU', 'title_eu');
@@ -18,16 +17,16 @@
     define('GET_GM', 'gm');
 
     // Valid values
-    define('ACTION_TEXT', 'mensaje');
+    define('ACTION_TEXT', 'text');
     define('ACTION_BLOG', 'blog');
-    define('ACTION_ACTIVITIES', 'actividades');
-    define('ACTION_GALLERY', 'galeria');
-    define('ACTION_LOCALIZATION', 'localizacion');
+    define('ACTION_ACTIVITIES', 'activities');
+    define('ACTION_GALLERY', 'gallery');
+    define('ACTION_LOCATION', 'location');
     define('ACTION_LABLANCA', 'lablanca');
-    define('ACTION_SCHEDULE', 'programa');
-    define('ACTION_GM_SCHEDULE', 'gprograma');
-    define('ACTION_US', 'nosotros');
-    $actions = [ACTION_TEXT, ACTION_BLOG, ACTION_ACTIVITIES, ACTION_GALLERY, ACTION_LOCALIZATION, ACTION_LABLANCA, ACTION_SCHEDULE, ACTION_GM_SCHEDULE, ACTION_US];
+    define('ACTION_SCHEDULE_CITY', 'schedule_city');
+    define('ACTION_SCHEDULE_GM', 'schedule_gm');
+    define('ACTION_US', 'us');
+    $actions = [ACTION_TEXT, ACTION_BLOG, ACTION_ACTIVITIES, ACTION_GALLERY, ACTION_LOCATION, ACTION_LABLANCA, ACTION_SCHEDULE_CITY, ACTION_SCHEDULE_GM, ACTION_US];
 
     // Default values
     define('DEF_GM', 0);
@@ -43,47 +42,13 @@
     define('ERR_PERM', '-PERM:');
     define('ERR_ID', '-ID:');
 
-    /****************************************************
-    * This function is called from almost everywhere at *
-    * the beggining of the page. It initializes the     *
-    * session variables, connect to the db, enabling    *
-    * the variable $con for futher use everywhere in    *
-    * the php code, and populates the arrays $user      *
-    * and $permission, with info about the user.        *
-    *                                                   *
-    * @return: (db connection): The connection handler. *
-    ****************************************************/
-    function startdb(){
-        //Include the db configuration file. It's somehow like this
-        /*
-         <?php
-          $host = 'XXXX';
-          $db_name = 'XXXX';
-          $username_ro = 'XXXX';
-          $username_rw = 'XXXX';
-          $pass_ro = 'XXXX';
-          $pass_rw = 'XXXX';
-         ?>
-        */
-        include('../../.htpasswd');
+    include('functions.php');
 
-        //Connect to to database
-        $con = mysqli_connect($host, $username_rw, $pass_rw, $db_name);
-
-        //Set encoding options
-        mysqli_set_charset($con, 'utf-8');
-        header('Content-Type: text/html; charset=utf8');
-        mysqli_query($con, 'SET NAMES utf8;');
-
-        //Return the db connection
-        return $con;
-    }
-
-    $con = startdb();
+    $con = startdb('rw');
 
     // Get fields
-    $user = mysqli_real_escape_string($con, $_GET[GET_USER]);
-    $pass = mysqli_real_escape_string($con, $_GET[GET_PASS]);
+    $user = mysqli_real_escape_string($con, $_POST[POST_USER]);
+	$pass = mysqli_real_escape_string($con, $_POST[POST_PASS]);
     $title_es = urldecode(mysqli_real_escape_string($con, $_GET[GET_TITLE_ES]));
     $title_en = urldecode(mysqli_real_escape_string($con, $_GET[GET_TITLE_EN]));
     $title_eu = urldecode(mysqli_real_escape_string($con, $_GET[GET_TITLE_EU]));
@@ -100,16 +65,14 @@
     $error = "";
 
     // Validate user/pass
-    $q = mysqli_query($con, "SELECT id FROM user WHERE (lower(username) = lower('$user') OR lower(email) = lower('$user')) AND password = sha1(concat('$pass', sha1(salt)))");
-    if (mysqli_num_rows($q) == 0){
+    $uid = login($con, $user, $pass);
+    if ($uid == -1){
         error_log(":SECURITY: Reporting location with wrong credentials (IP $_SERVER[REMOTE_ADDR])");
-        http_response_code(403); // Forbidden
-        $error = $error . ERR_USER . mysqli_real_escape_string($con, $_GET[GET_USER]);
+        $error = $error . ERR_USER . mysqli_real_escape_string($con, $_POST[POST_USER]);
         error_log($error);
+        http_response_code(403); // Forbidden
         exit(-1);
     }
-    $r = mysqli_fetch_array($q);
-    $uid = $r['id'];
 
     //Validate fields
     if (strlen($title_es) == 0){
@@ -156,12 +119,13 @@
 
     //Insert
     if (strlen($error) == 0){
-        error_log("INSERT INTO notification (user, title_es, title_en, title_eu, text_es, text_en, text_eu, action, duration) VALUES ($uid, '$title_es', '$title_en', '$title_eu', '$text_es', '$text_en', '$text_eu', '$action', $duration);");
-        mysqli_query($con, "INSERT INTO notification (user, title_es, title_en, title_eu, text_es, text_en, text_eu, action, duration) VALUES ($uid, '$title_es', '$title_en', '$title_eu', '$text_es', '$text_en', '$text_eu', '$action', $duration);");
+        mysqli_query($con, "INSERT INTO notification (user, title_es, title_en, title_eu, text_es, text_en, text_eu, action, duration) VALUES ($_SESSION[id], '$title_es', '$title_en', '$title_eu', '$text_es', '$text_en', '$text_eu', '$action', $duration);");
+        error_log("INSERT INTO notification (user, title_es, title_en, title_eu, text_es, text_en, text_eu, action, duration) VALUES ($_SESSION[id], '$title_es', '$title_en', '$title_eu', '$text_es', '$text_en', '$text_eu', '$action', $duration);");
         http_response_code(204); // No content;
         exit(0);
     }
     else{
+		http_response_code(400); // Bad request
         error_log($error);
         exit(-6);
     }

+ 50 - 0
www-admin/API/v3/sync.php

@@ -0,0 +1,50 @@
+ <?php
+    // Gasteizko Margolariak API v3 //
+
+    // $_GET and $_POST valid parameters
+    define('POST_USER', 'user');
+    define('POST_PASS', 'pass');
+    define('GET_TABLES', 'tables');
+    define('GET_WHERE', 'where');
+
+    // Error messages
+    define('ERR_USER', '-USER:');
+    define('ERR_TABLES', '-TABLES:');
+    define('ERR_WHERE', '-WHERE:');
+
+    include('functions.php');
+    $con = startdb();
+
+    // Error control
+    $error = "";
+
+    // Get params
+    $user = mysqli_real_escape_string($con, $_POST[POST_USER]);
+    $pass = mysqli_real_escape_string($con, $_POST[POST_PASS]);
+
+    $tables = mysqli_real_escape_string($con, $_GET[GET_TABLES]);
+    $where = mysqli_real_escape_string($con, $_GET[GET_WHERE]);
+
+    //Validate user
+    $uid = login($con, $user, $pass);
+    if ($uid == -1){
+        error_log(":SECURITY: Reporting location with wrong credentials (IP $_SERVER[REMOTE_ADDR])");
+        $error = $error . ERR_USER . mysqli_real_escape_string($con, $_POST[GET_USER]);
+        error_log($error);
+        http_response_code(403); // Forbidden
+        exit(-1);
+    }
+
+    // Ask server to create a SQLdump
+    $date = date_create();
+    $fname = date_timestamp_get($date);
+    include('../../../www/.htpasswd');
+    exec("mysqldump --single-transaction gm -u $username_ro -p'$pass_ro' > /var/www-dump/$fname.sql");
+
+    // Ask server to encrypt the dump.
+    $pass = mysqli_real_escape_string($con, $_POST[POST_USER]);
+    exec("gpg --batch --yes --passphrase $pass -o /var/www-admin/dump/$fname.gpg -c /var/www-dump/$fname.sql");
+
+    // Make a redirect.
+    header("Location: /dump/$fname.gpg");
+?>