Advertisement
Guest User

backend.php

a guest
Dec 19th, 2014
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 11.69 KB | None | 0 0
  1. <?php
  2.  
  3. /*
  4. todo: delete this step-by-step and any other todos in this document. Use PHP storm 'TODO' panel on the bottom to locate the todos in this document to make sure theyre all gone before pasting it to ralph
  5. ******************
  6.  
  7. 1. html finishes loading
  8. 2. $.getJSON called
  9. 3. request is made to this file parsing $_GET['f'] (e.g. database.php?f=[function name])
  10. 4. the $_GET['f'] parameter is used to call the specified function
  11. 5. sql statements are executed and directories read and put into array form
  12. 6. array and code of succession is then parsed into JSON format using json_encode()
  13. 7. response json is then set as the contents of this file
  14. 8. once this file is loaded, the jquery $.getJSON().success(response) function is called parsing the response as the contents of this file
  15. 9. jquery then interprets the response and gives a client response such as an alert message or creates html based on the json data
  16.  
  17. ******************
  18.  
  19.  */
  20.  
  21. /*
  22. todo: this is the sql to create the user table that stores...
  23.  
  24. CREATE TABLE `users` (
  25.   `user_id` int(11) NOT NULL AUTO_INCREMENT,
  26.   `user_email` varchar(200) NOT NULL,
  27.   `user_name` varchar(200) NOT NULL,
  28.   `user_password` varchar(200) NOT NULL,
  29.   PRIMARY KEY (`user_id`)
  30. ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=13 ;
  31.  
  32. --
  33. -- Dumping data for table `users`
  34. --
  35.  
  36. INSERT INTO `users` VALUES(10, 'michael@cloud.com', 'michael', 'pass');
  37. INSERT INTO `users` VALUES(11, 'craig@cloud.com', 'craig', 'pass');
  38. INSERT INTO `users` VALUES(12, 'lois@cloud.com', 'lois', 'pass');
  39.  
  40.  
  41.  */
  42.  
  43.  
  44.  
  45. /******todo:this is the sql server configuration used to connect with mysql database hosted online.*****/
  46. define("DB_TYPE","mysql");
  47. define("DB_HOST","StudentCloud.db.11698469.hostedresource.com");//todo: used an existing database provided by friend so i wouldnt have to use sign up for free hosting
  48. define("DB_NAME","StudentCloud");
  49. define("DB_USER","StudentCloud");
  50. define("DB_PWD","CMT3313db!");
  51.  
  52.  
  53.  
  54. class DB extends PDO {
  55.  
  56.     //todo:this class was from an example found online to allow me to use PDO connection object without having to set the user and login credentials everytime i instantiate the object.
  57.  
  58.  
  59.  
  60.  
  61.     public function __construct() {//TODO: Possibly allow argument to state the connection type
  62.  
  63.         parent::__construct(DB_TYPE.':host='.DB_HOST.';charset=utf8;dbname='.DB_NAME, DB_USER, DB_PWD);
  64.  
  65.  
  66.     }
  67.  
  68.     public function prepare($stmt,$options=array()) {
  69.  
  70.         return parent::prepare($stmt,$options);
  71.  
  72.     }
  73.  
  74.  
  75. }
  76.  
  77.  
  78. session_start();//todo:start session to allow user detail variables to be set and accessed
  79.  
  80.  
  81.  
  82.  
  83.  
  84.  
  85. /***************************library**********************************/
  86.  
  87. //todo: created this object to make sure that my code was kept clean and i could set private functions that could only be accessed by functions within the class
  88. class CloudSystem
  89. {
  90.  
  91.  
  92.     public function __construct() {
  93.  
  94.     }
  95.     public function respondJSON($code = 1, $data = array())
  96.     {
  97.         //todo: used this function to give a json formatted response that could be easily read using $.getJSON function in my jquery script
  98.         $r = array();
  99.  
  100.         $r['code'] = $code;//todo: code for identifying the response
  101.         $r['data'] = $data;//todo: data for holding the file list and any other detail that can be read by my html page
  102.  
  103.         throw new Exception(json_encode($r));//todo: used a thrown exception to make sure that other code isnt ran because i couldnt get PHP's 'exit' to work
  104.  
  105.     }
  106.  
  107.     public function setUserDetails($user_id, $user_name)
  108.     {
  109.         //todo: this function is to set and store the users credentials in http cookies. This is so the users login status is saved and they dont have to login everytime the page is refreshed.
  110.  
  111.  
  112.         //throw new Exception("userid: {$user_id} name: {$user_name}");
  113.         setcookie('user_id',$user_id,null,'/');
  114.         setcookie('user_name',$user_name,null,'/');
  115.  
  116.         ////
  117.  
  118.  
  119.  
  120.         //throw new Exception(print_r($_COOKIE,true));
  121.  
  122.  
  123.     }
  124.  
  125.     private function getUserDetails()
  126.     {
  127.  
  128.  
  129.         $details = array();
  130.  
  131.         $details['user_id'] = isset($_COOKIE['user_id']) ? $_COOKIE['user_id'] : 0;
  132.  
  133.         $details['user_name'] = isset($_COOKIE['user_name']) ? $_COOKIE['user_name'] : 0;
  134.  
  135.         if (empty($details['user_id']) || empty($details['user_name'])) return false;else return $details;//todo: this function is for grabbing the user details from cookies and then put them in readable array
  136.  
  137.  
  138.     }
  139.  
  140.     /***************************library**********************************/
  141.  
  142.  
  143.     public function uploadFile()
  144.     {
  145.  
  146.  
  147.         $userDetail = $this->getUserDetails();
  148.         $valid_file = false;
  149.  
  150.  
  151.  
  152.  
  153.  
  154.         $code = 0;
  155.  
  156.  
  157.         if (!isset($_FILES['myFile'])) $this->respondJSON(77);else {//todo: make sure user specified a  file
  158.  
  159.  
  160.  
  161.                     if (!file_exists('files/' . $userDetail['user_id'] . "/")) mkdir('files/' . $userDetail['user_id'] . "/");//todo: create user's folder if it doesnt exist yet
  162.  
  163.  
  164.                     move_uploaded_file($_FILES['myFile']['tmp_name'], 'files/' . $userDetail['user_id'] . "/" . $_FILES['myFile']['name']);
  165.                     //todo: when the user selects a file to be uploaded, it is first moved to their temporary folder on their own computer.
  166.                     //todo: This function then accesses that file in the temporary directory and transfers
  167.  
  168.  
  169.  
  170.  
  171.                     $code = 1;
  172.         }
  173.  
  174.  
  175.         //$this->respondJSON($code);
  176.  
  177.  
  178.         if ($code) echo "Upload success!"; else echo "File not specified";
  179.  
  180.     }
  181.  
  182.     public function loginUser()
  183.     {
  184.  
  185.         $db = new DB();//todo: create an instance of the database PDO object to be used with manipulating mysql database
  186.  
  187.  
  188.  
  189.         //todo: setup sql query ready to be executed, which obtains the users details based on the email and password specified from the users login form
  190.         $query = $db->prepare("SELECT COUNT(*) as count,user_id,user_email,user_name FROM users WHERE user_email=:user_email AND user_password=:user_password");
  191.  
  192.  
  193.         //todo: make sure the email and password forms have submitted their values
  194.         if (!isset($_POST['user_email'], $_POST['user_password'])) $this->respondJSON(44);
  195.  
  196.  
  197.         //todo: parse in the values from the users login post and bind it with the values within the prepared sql statement
  198.         if (!$query->execute(array('user_email' => $_POST['user_email'], "user_password" => $_POST['user_password']))) {
  199.             $this->respondJSON(118,array("error"=>$query->errorInfo()));
  200.  
  201.         }
  202.  
  203.  
  204.  
  205.  
  206.  
  207.         $data=$query->fetchAll(PDO::FETCH_ASSOC);//todo: get the entire array of results into one variable
  208.  
  209.  
  210.  
  211.         $count = $data[0]['count'];//todo: get the number of entries that the sql found
  212.  
  213.  
  214.  
  215.         //todo: get the user id and name of the user that just signed in
  216.         $user_id=$data[0]['user_id'];
  217.         $user_name=$data[0]['user_name'];
  218.  
  219.  
  220.  
  221.         if ($count <= 0) $this->respondJSON(888);//todo: if (NO USERS FOUND WITH SPECIFIED EMAIL AND PASSWORD IN TABLE) respond with code 888
  222.  
  223.  
  224.  
  225.  
  226.  
  227.  
  228.         $this->setUserDetails($user_id, $user_name);//todo: call this method to store the user details as cookies
  229.  
  230.  
  231.  
  232.         $this->respondJSON(1);//todo: respond with code 1 to say the user has been successfully logged in
  233.  
  234.  
  235.     }
  236.  
  237.     public function logout() {
  238.  
  239.         //todo: clear the stored user details (set the cookie to an empty string to delete it)
  240.         setcookie('user_id','',null,'/');
  241.         setcookie('user_name','',null,'/');
  242.  
  243.  
  244.     }
  245.     public function registerUser()
  246.     {
  247.  
  248.  
  249.         $this->logout();//todo: ensure that there is no stored user details before registering
  250.  
  251.         $db = new DB();
  252.  
  253.  
  254.         $query = $db->prepare("INSERT INTO users (user_email,user_name,user_password) VALUES (:user_email,:user_name,:user_password)");
  255.  
  256.  
  257.         if (!isset($_POST['user_email'], $_POST['user_name'],$_POST['user_password'])) $this->respondJSON(44);
  258.  
  259.  
  260.  
  261.  
  262.  
  263.         //todo: respond with json and data entry that details the invalid field to tell the user what to change
  264.         if (strlen($_POST['user_email'])<3||!filter_var($_POST['user_email'], FILTER_VALIDATE_EMAIL)) $this->respondJSON(78,array("invalid"=>"Invalid Email specified"));//todo: ensure the posted email is a valid email
  265.         if (strlen($_POST['user_name'])<3) $this->respondJSON(78,array("invalid"=>"Invalid name specified"));
  266.         if (strlen($_POST['user_password'])<3||strlen($_POST['user_password'])>25) $this->respondJSON(78,array("invalid"=>"Invalid password specified"));
  267.         if ($_POST['user_password']!=$_POST['user_confirm_password']) $this->respondJSON(78,array("invalid"=>"Passwords dont match love"));//todo: check if password and confirm password values match
  268.  
  269.  
  270.  
  271.         //todo: bing in the required values into the sql statement for insertion into the table
  272.         if (!$query->execute(array(
  273.  
  274.             'user_email' => $_POST['user_email'],
  275.             "user_name" => $_POST['user_name'],
  276.             "user_password" => $_POST['user_password']
  277.  
  278.         ))
  279.         ) {
  280.  
  281.             $this->respondJSON(118);//todo: respond with code 118 that represents a registration success
  282.  
  283.         }
  284.  
  285.  
  286.  
  287.  
  288.  
  289.  
  290.  
  291.  
  292.         $this->setUserDetails($db->lastInsertId(),$_POST['user_name']);//todo: login the user by storing their credentials in cookie
  293.  
  294.  
  295.  
  296.         $this->respondJSON(1, array('user_id' => $db->lastInsertId()));//todo: respond with a success code and include the user id of user registered for future developments
  297.  
  298.  
  299.     }
  300.  
  301.     public function getFileList()
  302.     {
  303.  
  304.  
  305.         $userDetail = $this->getUserDetails();
  306.  
  307.         if ($userDetail==false) $this->respondJSON(999);
  308.  
  309.         if (!file_exists('files/' . $userDetail['user_id'] . "/")) {//todo: check if the user has a dedicated directory
  310.  
  311.             mkdir('files/'.  $userDetail['user_id']);//todo: if they dont, create one for the user
  312.             $this->respondJSON(333);//
  313.         }
  314.  
  315.  
  316.  
  317.         $dir_list = scandir('files/' . $userDetail['user_id'] . "/");///todo: get an array of files that resides in the users dedicated directory
  318.  
  319.         $this->respondJSON(1, array("user_id"=>$userDetail['user_id'],"file_list"=>$dir_list));//todo: respond with the file list in json format
  320.  
  321.  
  322.     }
  323.     public function deleteFile() {
  324.  
  325.         $userDetail = $this->getUserDetails();
  326.  
  327.         if ($userDetail==false) $this->respondJSON(999);//todo: if user is not logged in, return and respond with 999 code
  328.  
  329.         if (!isset($_GET['file'])) $this->respondJSON(0);//todo: if the file has not been specified correctly, return and respond with 0 code
  330.  
  331.         if (file_exists('files/' . $userDetail['user_id'] . "/".$_GET['file'])) {//todo: check if the file exists first before attempting to delete
  332.             if (unlink('files/' . $userDetail['user_id'] . "/".$_GET['file'])) $this->respondJSON(1);else $this->respondJSON(956);//todo: delete file
  333.  
  334.         }
  335.  
  336.  
  337.  
  338.     }
  339.    
  340. }
  341.  
  342.  
  343.  
  344.  
  345. try {
  346.  
  347.  
  348.     $s = new CloudSystem();//todo: create an instance of the cloud system to be able to access the methods inside
  349.  
  350.     if (isset($_GET['f'])) {//todo: make sure f query string has been set
  351.  
  352.  
  353.         $s->{$_GET['f']}();//todo: call the method within the CloudSystem object
  354.  
  355.  
  356.     }
  357. }catch(Exception $e) {
  358.     header("Content-type: application/json");//todo:set the return type
  359.  
  360.  
  361.     print $e->getMessage();//todo: get the message that was parsed through exception (i.e. new Exception([message])...this gets the [message])
  362.  
  363.     exit;//todo: make sure no other php code is executed
  364.  
  365. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement