SHARE
TWEET

Untitled

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