SHARE
TWEET

Untitled

a guest Apr 2nd, 2019 146 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2. require_once('vendor/autoload.php');
  3. use \Firebase\JWT\JWT;
  4.  
  5. date_default_timezone_set('Europe/Copenhagen');
  6.  
  7. class Ssas {
  8.  
  9.     private static $mysqlServer = 'localhost';
  10.     private static $mysqlUser = 'root';
  11.     private static $mysqlPass = 'ssas';
  12.     private static $mysqlDb = 'ssas';
  13.     private static $key = "sUp3r5ecr3t";
  14.     private static $data;
  15.     private static $image_dir = "/var/www/html/uploads/";
  16.     //private static $db;
  17.     //private static $db = mysqli_connect(self::$mysqlServer, self::$mysqlUser, self::$mysqlPass, self::$mysqlDb);
  18.  
  19.     function __construct(){
  20.         $link = mysql_connect(self::$mysqlServer, self::$mysqlUser, self::$mysqlPass);
  21.         $db_selected = mysql_select_db(self::$mysqlDb, $link);
  22.         //db = mysqli_connect(self::$mysqlServer, self::$mysqlUser, self::$mysqlPass, self::$mysqlDb);
  23.     }
  24.  
  25.     // Custom implementaion of MySQL query execution in PHP.
  26.     // Someone mentioned that an "improved" version exists, but this works for now...
  27.     function execute($query_str, $split = false){
  28.         $result;
  29.         if ($split) $query_str = explode(';', $query_str);
  30.         else $query_str = str_split($query_str, strlen($query_str));
  31.         foreach ($query_str as &$query) {
  32.             if($query) $result = mysql_query($query);
  33.         }
  34.         return $result;
  35.     }
  36.  
  37.     // This function will authenticate a user based on the token cookie.
  38.     // returns true if the user is authenticated, otherwise return false
  39.     // if the token is invalid or has expired the method will call exit() and not return anything
  40.     function authenticate(){
  41.         if(isset($_COOKIE['token'])){
  42.             try{
  43.                 //Retrieves the JWT token from the cookie
  44.                 $token = $_COOKIE['token'];
  45.  
  46.                 //Decrypts the token. This call will throw an exception if the token is invalid
  47.                 $token = (array) JWT::decode($token,self::$key,array('HS512'));
  48.  
  49.                 //Extracts the user data from the token
  50.                 self::$data = (array) $token['data'];
  51.  
  52.                 //Check that the user actually exists (could have been removed)
  53.                 $uid = self::getUid();
  54.                 $uname = self::getUsername();
  55.                 if (self::verifyInput($uname)) {
  56.                     //$query = "SELECT id FROM user WHERE id = ".$uid." AND username = '".$uname."';";
  57.                     $query = sprintf("SELECT id FROM user WHERE id = '%d' AND username = '%s';",
  58. mysql_real_escape_string($uid),
  59. mysql_real_escape_string($uname));
  60. //echo $query;
  61.                     $result = self::execute($query);
  62.  
  63.                     if (mysql_num_rows($result) > 0) return true;
  64.                 }
  65.                
  66.                 //If the query did not succeed, then there is something wrong!
  67.                 throw new Exception('Authentication failed!');
  68.  
  69.             } catch (Exception $e){
  70.  
  71.                 //This will happend if
  72.                 //  1) The token has expired
  73.                 //  2) The token is not valid
  74.                 //  3) No user matching the user data exists
  75.  
  76.                 self::logout();
  77.                 header("Location: index.php");
  78.                 exit(); //Just to be sure
  79.  
  80.             }
  81.         }
  82.        return false; //Could not authenticate
  83.     }
  84.  
  85.     // This function will destroy the token cookie if it exists
  86.     function logout(){
  87.         if(isset($_COOKIE['token'])){
  88.             unset($_COOKIE['token']);
  89.             setcookie('token', '', time() - 3600);
  90.         }
  91.     }
  92.  
  93.     // This function will check if the user is logged in
  94.     // If the user is not authenticated, the the method will try to authenticate.
  95.     // returns true if the user is logged in otherwise false
  96.     function isUserLoggedIn(){
  97.         if(!isset(self::$data) && isset($_COOKIE['token'])) self::authenticate();
  98.         return isset(self::$data);
  99.     }
  100.  
  101.     // This function will return to logged in users id (if authenticated)
  102.     function &getUid(){
  103.     if(self::isUserLoggedIn()) return self::$data['uid'];
  104.     }
  105.  
  106.     // This function will return to logged in users username (if authenticated)
  107.     function &getUsername(){
  108.     if(self::isUserLoggedIn()) return self::$data['username'];
  109.     }
  110.  
  111.     // This function will create a new user with the given username password combo
  112.     // returns true if the user was created, otherwise error message
  113.     function createUser($username, $password){
  114.         if($username == "") return "username can't be empty";
  115.         if($password == "") return "password can't be empty";
  116.  
  117.         if (!(self::verifyInput($username) && self::verifyInput($password))) {
  118.             // Bad user input, like illegal character/byte
  119.             return "bad character";    
  120.         }
  121.  
  122.         //Inserts username and password into the database
  123.         //$query = "INSERT INTO user(username,password) VALUES ('".$username."','".$password."');";
  124. $query = sprintf("INSERT INTO user(username,password) VALUES ('%s','%s');",
  125. mysql_real_escape_string($username),
  126. mysql_real_escape_string($password));
  127.         self::execute($query, false);
  128.  
  129.         //If exactly one row was affected then we know that the user was inserted.
  130.         if (mysql_affected_rows() == 1) return true;
  131.         return "user could not be created";
  132.     }
  133.  
  134.     // This function will login with the given username password combo
  135.     // returns true if the login was successful, otherwise error message
  136.     function login($username, $password){
  137.  
  138.         //Query to get the username and real password,
  139.         //$query = "SELECT id,password FROM user WHERE username = '".$username."';";
  140. $query = sprintf("SELECT id,password FROM user WHERE username = '%s';",
  141. mysql_real_escape_string($username));
  142.         $result = self::execute($query);
  143.  
  144.         if (mysql_num_rows($result) > 0) {
  145.             $row = mysql_fetch_assoc($result);
  146.             $uid = $row['id'];
  147.             $password_real = $row['password'];
  148.         } else {
  149.             return "username and password does not match";
  150.         }
  151.  
  152.         // If the real password matches the one given, then the login succeeds.
  153.         if(isset($password_real) && ($password === $password_real)){
  154.             //Generates random tokenid
  155.             //TODO Maybe store some of this server side... (Stateful or stateless?)
  156.             $tokenId = base64_encode(mcrypt_create_iv(32,MCRYPT_DEV_URANDOM));
  157.  
  158.             $issuedAt = time(); //time of issue
  159.             $notBefore = $issuedAt; //can be used to say that a token is not valid before a given time (not used)
  160.             $expire = $notBefore + 3600 * 24 * 90; //token expires in 90 days
  161.             $data = [
  162.                 'iat' => $issuedAt,
  163.                 'jti' => $tokenId,
  164.                 'nbf' => $notBefore,
  165.                 'exp' => $expire,
  166.                 'data' => [
  167.                     'uid' => $uid,
  168.                     'username' => $username
  169.                 ]
  170.             ];
  171.  
  172.             //Computes the encrypted token
  173.             $jwt = JWT::encode($data,self::$key,'HS512');
  174.  
  175.             //Sets to cookie to never expire as the token itself contains the expiration date (Mimimum exposure)
  176.             setcookie("token", $jwt, -1);
  177.             return true;
  178.         } else return "username and password does not match";
  179.  
  180.         return "could not login";
  181.     }
  182.  
  183.     // This function uploads the given image
  184.     // returns true if the image was successfully uploaded, otherwise error message.
  185.     function uploadImage($img){
  186.         if(self::isUserLoggedIn()){
  187.             $uid = self::getUid();
  188.             //$query = "INSERT INTO image(owner_id) VALUES(".$uid.");"
  189. $query = sprintf("INSERT INTO image(owner_id) VALUES('%d');",
  190. mysql_real_escape_string($uid));
  191.             $result = self::execute($query);
  192.             if($result) {
  193.                 $iid = mysql_insert_id();
  194.                 self::save_image($img, $iid);
  195.                 return true;
  196.             }            
  197.             return "Image could not be uploaded";
  198.         }
  199.         return "Image could not be uploaded2";
  200.     }
  201.  
  202.     // This function will lookup a users id given the username
  203.     // returns the user id if exists, otherwise false
  204.     private function getUserId($username){
  205.  
  206.         //$query = "SELECT id FROM user WHERE username = '".$username."';";
  207. $query = sprintf("SELECT id FROM user WHERE username = '%s';",
  208. mysql_real_escape_string($username));
  209.         $result = self::execute($query);
  210.         if (mysql_num_rows($result) > 0) {
  211.             $row = mysql_fetch_assoc($result);
  212.             return $row['id'];
  213.         }
  214.         return false;
  215.     }
  216.  
  217.     // This function will remove sharing with the given user for the given image
  218.     // returns true if the operation was successful, otherwise false
  219.     function removeShare($iid, $username){
  220.  
  221.         if(self::isUserLoggedIn() && self::isOwner($iid)){
  222.             $uid = self::getUserId($username);
  223.             if($uid == false) return false;
  224.  
  225.             //Removing sharing of image from database
  226.             //$query = "DELETE FROM shared_image WHERE image_id = ".$iid." AND user_id = ".$uid.";";
  227. $query = sprintf("DELETE FROM shared_image WHERE image_id = '%d' AND user_id = '%d';",
  228. mysql_real_escape_string($iid),
  229. mysql_real_escape_string($uid));
  230.             self::execute($query);
  231.  
  232.             return mysql_affected_rows() == 1;
  233.         }
  234.         return false;
  235.     }
  236.  
  237.     // This function will share the given image with the given user
  238.     // returns true if the image was shared, otherwise false
  239.     function shareImage($iid, $username)
  240.     {
  241.         //The user must be owner of the image to share it
  242.         if(self::isUserLoggedIn() && self::isOwner($iid)){
  243.  
  244.             //Getting uid from username
  245.             $uid = self::getUserId($username);
  246.  
  247.             //Inserting sharing of image into database
  248.             //$query = "INSERT INTO shared_image VALUES (".$uid.",".$iid.");";
  249. $query = sprintf("INSERT INTO shared_image VALUES ('%d','%d');",
  250. mysql_real_escape_string($uid),
  251. mysql_real_escape_string($iid));
  252.             self::execute($query);
  253.  
  254.             return mysql_affected_rows() == 1;
  255.         }
  256.         return false;
  257.     }
  258.  
  259.     // This function returns a list of users whom the given image can be shared with
  260.     // returns a list of users if successful, otherwise false
  261.     function getUsersToShareWith($iid){
  262.         if(self::isUserLoggedIn()){//&& self::isOwner($iid)){
  263.             $users = array();
  264.  
  265.             // Query database for users to share with, which is everyone but the owner
  266.             // and those whom the image is already shared with.
  267.             $uid = self::getUid();
  268.             //$query = "SELECT id,username FROM user WHERE id <> ".$uid." AND id NOT IN (SELECT user_id FROM shared_image WHERE image_id = ".$iid.");";
  269. $query = sprintf("SELECT id,username FROM user WHERE id <> '%d' AND id NOT IN (SELECT user_id FROM shared_image WHERE image_id = '%d');",
  270. mysql_real_escape_string($uid),
  271. mysql_real_escape_string($iid));
  272.             $result = self::execute($query);
  273.  
  274.             if (mysql_num_rows($result) > 0) {
  275.                 while ($row = mysql_fetch_assoc($result)) {
  276.                     $users[] = new user($row['id'], $row['username']);
  277.                 }
  278.             } else {
  279.                 return "No users to share this with.";
  280.             }          
  281.  
  282.             return $users;
  283.         }
  284.         return false;
  285.     }
  286.  
  287.     // This function returns a list of users whom the given image is shared with.
  288.     // returns a list of users if successful, otherwise false
  289.     function sharedWith($iid){
  290.         if(self::isUserLoggedIn()) {
  291.             $users = array();
  292.            
  293.             //$query = "SELECT id,username FROM user INNER JOIN shared_image ON id = user_id WHERE image_id = ".$iid.";";
  294. $query = sprintf("SELECT id,username FROM user INNER JOIN shared_image ON id = user_id WHERE image_id = '%d';",
  295. mysql_real_escape_string($iid));
  296.             $result = self::execute($query);
  297.  
  298.             if (mysql_num_rows($result) > 0) {
  299.                 while ($row = mysql_fetch_assoc($result)) {
  300.                     $users[] = new user($row['id'], $row['username']);
  301.                 }
  302.             }
  303.  
  304.             return $users;
  305.         }
  306.         return false;
  307.     }
  308.  
  309.     // This function saves the image to a file with the corresponding image id as the name.
  310.     // TODO: Find out how to handle the file permissions.
  311.     function save_image($img, $iid){
  312.         $data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $img));
  313.         $file = self::$image_dir.$iid;
  314.         file_put_contents($file, $data);
  315.         chmod($file, 0777); // This works for now, but probably isn't necessary... right?
  316.     }
  317.  
  318.     // This function loads the image file with the corresponding image id.
  319.     // TODO: Find out how to handle the file permissions.
  320.     function loadImage($iid){
  321.         $file = self::$image_dir.$iid;
  322.         $type = pathinfo($file, PATHINFO_EXTENSION);   
  323.         $data = file_get_contents($file);
  324.         $img = 'data:image/' . $type . ';base64,' . base64_encode($data);      
  325.         return $img;
  326.     }
  327.  
  328.     // This function returns a list of all images shared with the loggedin user
  329.     // returns a list of images if successful, otherwise false
  330.     function getImages(){
  331.         if(self::isUserLoggedIn()){
  332.             $images = array();
  333.            
  334.             // The images to display should either be those owned by the user
  335.             // or those ahred with the user and should not be duplicated.
  336.             $uid = self::getUid();
  337.             //$query = "SELECT DISTINCT image.id,owner_id,username,createdDate FROM image INNER JOIN user on user.id = owner_id LEFT JOIN shared_image ON image_id = image.id WHERE user_id = ".$uid." OR owner_id = ".$uid." ORDER BY createdDate DESC";
  338. $query = sprintf("SELECT DISTINCT image.id,owner_id,username,createdDate FROM image INNER JOIN user on user.id = owner_id LEFT JOIN shared_image ON image_id = image.id WHERE user_id = '%d' OR owner_id = '%d' ORDER BY createdDate DESC",
  339. mysql_real_escape_string($uid),
  340. mysql_real_escape_string($uid));
  341.             $result = self::execute($query);
  342.  
  343.             if (mysql_num_rows($result) > 0) {
  344.                 while ($row = mysql_fetch_assoc($result)) {
  345.                     $iid = $row['id'];
  346.                     $img = self::loadImage($iid);
  347.                     $images[] = new Image($iid, $row['owner_id'], $row['username'], $img, $row['createdDate']);
  348.                 }
  349.             }
  350.  
  351.             return $images;
  352.         }
  353.         return false;
  354.     }
  355.  
  356.     // This function returns the given image iff the loggedin user have access to it
  357.     // returns the image if successful, otherwise false
  358.     function getImage($iid)
  359.     {
  360.         if(self::isUserLoggedIn())
  361.         {
  362.             $uid = self::getUid();
  363.             //$query = "SELECT image.id,owner_id,username,createdDate FROM image INNER JOIN user ON user.id = owner_id LEFT JOIN shared_image ON image_id = image.id WHERE (user_id = ".$uid." OR owner_id = ".$uid.") AND image.id = ".$iid.";";
  364. $query = sprintf("SELECT image.id,owner_id,username,createdDate FROM image INNER JOIN user ON user.id = owner_id LEFT JOIN shared_image ON image_id = image.id WHERE (user_id = '%d' OR owner_id = '%d') AND image.id = '%d';",
  365. mysql_real_escape_string($uid),
  366. mysql_real_escape_string($uid),
  367. mysql_real_escape_string($iid));
  368.             $result = self::execute($query);
  369.            
  370.             if (mysql_num_rows($result) > 0) {
  371.                 $row = mysql_fetch_assoc($result);
  372.            
  373.                 $img = self::loadImage($iid);
  374.                 return new Image($iid, $row['owner_id'], $row['username'], $img, $row['createdDate']);
  375.             }
  376.             return null;
  377.         }
  378.  
  379.         return false;
  380.     }
  381.  
  382.     // This function will post given comment to given image iff the loggedin user has access to post
  383.     // returns true if successful, otherwise false
  384.     function comment($iid, $comment)
  385.     {
  386.         if(self::isUserLoggedIn() && self::verifyShare(self::getUid(), $iid))
  387.         {
  388.             $uid = self::getUid();
  389.             //$query = "INSERT INTO post(text, user_id, image_id) VALUES ('".$comment."',".$uid.",".$iid.")";
  390. $query = sprintf("INSERT INTO post(text, user_id, image_id) VALUES ('%s','%d','%d')",
  391. mysql_real_escape_string($comment),
  392. mysql_real_escape_string($uid),
  393. mysql_real_escape_string($iid));
  394.             $result = self::execute($query);
  395.             return mysql_affected_rows() == 1;
  396.         }
  397.         return false;
  398.     }
  399.  
  400.     // This function gets all comments for the given image
  401.     // returns a list of comments if successful, otherwise false
  402.     function getComments($iid)
  403.     {
  404.         if(self::isUserLoggedIn() && self::verifyShare(self::getUid(), $iid))
  405.         {          
  406.             $comments = array();
  407.  
  408.             $query = "SELECT post.id,username,text,createdDate FROM post INNER JOIN user ON user_id = user.id WHERE image_id = ".$iid." ORDER BY createdDate ASC;";
  409. $query = sprintf("SELECT post.id,username,text,createdDate FROM post INNER JOIN user ON user_id = user.id WHERE image_id = '%d' ORDER BY createdDate ASC;",
  410. mysql_real_escape_string($iid));
  411.             $result = self::execute($query);
  412.  
  413.             if (mysql_num_rows($result) > 0) {
  414.                 while ($row = mysql_fetch_assoc($result)) {
  415.                     // Only include verified comments
  416.                     $text = $row['text'];
  417.                     if ((self::verifyInput($text))) {
  418.                         $comments[] = new Comment($row['id'], $row['username'], $text, $row['createdDate']);
  419.                     }
  420.                 }
  421.             }
  422.  
  423.             return $comments;
  424.         }
  425.         return false;
  426.     }
  427.  
  428.     // This function checks if the loggedin user is owner of the given image
  429.     // returns true if the loggedin user is owner, otherwise false
  430.     function isOwner($iid){
  431.         $uid = self::getUid();
  432.         //$query = "SELECT id FROM image WHERE owner_id = ".$uid." AND id = ".$iid.";";
  433. $query = sprintf("SELECT id FROM image WHERE owner_id = '%d' AND id = '%d';",
  434. mysql_real_escape_string($uid),
  435. mysql_real_escape_string($iid));
  436.         $result = self::execute($query);
  437.         return mysql_num_rows($result) > 0;
  438.     }
  439.  
  440.     // This function will verify whether the given user input is bad.
  441.     // This is to prevent malicious users from sending bad input, e.g. NULL,
  442.     // which would cause the MySQL service to crash.
  443.     // Returns true if no bad input is detected, otherwise false.
  444.     function verifyInput($input) {
  445.         $valid = !(eval('"'.$input.'"===NULL;') || eval('"'.$input.'"==="\0";'));
  446.         return $valid;
  447.     }
  448.  
  449.     // This function checks if the loggedin user is either owner or has access to the given image
  450.     // returns true if the loggedin user has access, otherwise false
  451.     function verifyShare($uid, $iid)
  452.     {
  453.         //$query = "SELECT id FROM image LEFT JOIN shared_image ON image_id = id WHERE (user_id = ".$uid." OR owner_id = ".$uid.") AND id = ".$iid.";";
  454. $query = sprintf("SELECT id FROM image LEFT JOIN shared_image ON image_id = id WHERE (user_id = '%d' OR owner_id = '%d') AND id = '%d';",
  455. mysql_real_escape_string($uid),
  456. mysql_real_escape_string($uid),
  457. mysql_real_escape_string($iid));
  458.         $result = self::execute($query);
  459.         return mysql_num_rows($result) > 0;
  460.     }
  461. }
  462.  
  463. class User{
  464.     private $_id;
  465.     private $_name;
  466.  
  467.     public function __construct($id, $name){
  468.         $this -> _id = $id;
  469.         $this -> _name = $name;
  470.     }
  471.  
  472.     public function getName(){ return $this -> _name; }
  473.     public function getId(){ return $this -> _id; }
  474. }
  475.  
  476. // This class is kind of obsolete, but still used.
  477. // Might be used in the future to, like, maybe store images in a database?
  478. class Image{
  479.  
  480.     private $_id;
  481.     private $_ownerId;
  482.     private $_image;
  483.     private $_username;
  484.     private $_datetime;
  485.  
  486.     public function __construct($id, $ownerId, $username, $image, $datetime){
  487.         $this -> _id = $id;
  488.         $this -> _ownerId = $ownerId;
  489.         $this -> _image = $image;
  490.         $this -> _username = $username;
  491.         $this -> _datetime = new DateTime($datetime);
  492.     }
  493.  
  494.     public function getId() { return $this -> _id; }
  495.     public function getOwnerId() { return $this -> _ownerId; }
  496.     public function getUser() { return $this -> _username; }
  497.     public function getImage() { return $this -> _image; }
  498.     public function getAge() {
  499.         $date = $this -> _datetime;
  500.         $currentDate = new DateTime();
  501.         $dateDiff = $date -> diff($currentDate);
  502.         $years = $dateDiff -> y;
  503.         $months = $dateDiff -> m;
  504.         $days = $dateDiff -> d;
  505.         $hours = $dateDiff -> h;
  506.         $minutes = $dateDiff -> i;
  507.         $seconds = $dateDiff -> s;
  508.  
  509.  
  510.         if($years > 1) return $years .' years';
  511.         if($years > 0) return $years .' year';
  512.         if($months > 1) return $months .' months';
  513.         if($months > 0) return $months .' month';
  514.         if($days > 1) return $days .' days';
  515.         if($days > 0) return $days .' day';
  516.         if($hours > 1) return $hours .' hours';
  517.         if($hours > 0) return $hours .' hour';
  518.         if($minutes > 1) return $minutes .' minutes';
  519.         if($minutes > 0) return $minutes .' minute';
  520.         if($seconds > 1) return $seconds .' seconds';
  521.         if($seconds >= 0) return $seconds .' second';
  522.         return "Error!";
  523.     }
  524. }
  525.  
  526. class Comment{
  527.     private $_id;
  528.     private $_userName;
  529.     private $_text;
  530.     private $_datetime;
  531.  
  532.     public function __construct($id, $userName, $text, $datetime){
  533.         $this -> _id = $id;
  534.         $this -> _userName = $userName;
  535.         $this -> _text = $text;
  536.         $this -> _datetime = new DateTime($datetime);
  537.     }
  538.  
  539.     public function getId() { return $this -> _id; }
  540.     public function getUser() { return $this -> _userName; }
  541.     public function getText() { return $this -> _text; }
  542.     public function getAge() {
  543.         $date = $this -> _datetime;
  544.         $currentDate = new DateTime();
  545.         $dateDiff = $date -> diff($currentDate);
  546.         $years = $dateDiff -> y;
  547.         $months = $dateDiff -> m;
  548.         $days = $dateDiff -> d;
  549.         $hours = $dateDiff -> h;
  550.         $minutes = $dateDiff -> i;
  551.         $seconds = $dateDiff -> s;
  552.  
  553.  
  554.         if($years > 1) return $years .' years';
  555.         if($years > 0) return $years .' year';
  556.         if($months > 1) return $months .' months';
  557.         if($months > 0) return $months .' month';
  558.         if($days > 1) return $days .' days';
  559.         if($days > 0) return $days .' day';
  560.         if($hours > 1) return $hours .' hours';
  561.         if($hours > 0) return $hours .' hour';
  562.         if($minutes > 1) return $minutes .' minutes';
  563.         if($minutes > 0) return $minutes .' minute';
  564.         if($seconds > 1) return $seconds .' seconds';
  565.         if($seconds >= 0) return $seconds .' second';
  566.         return "Error!";
  567.     }
  568. }
  569. ?>
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top