From 5b77a4eaab418836820b2a0bad7c88f0b88136a0 Mon Sep 17 00:00:00 2001 From: cenci0 Date: Tue, 3 Feb 2015 21:39:47 +0100 Subject: Minor code refactoring and updates DATABASE UPDATE: `orginalname` renamed to `originalname` (run update.sql to update `files` table). Run `update.sql` to update your database, no data will be lost (if you don't update it, pomf won't work properly). `schema.sql` - `id`s are now unsigned to double the maximum number of supported indexes - `size` and `user` columns are unsigned too (we can't have a negative file size or a negative user id) `static/classes/Response.class.php` New class to manage responses and errors. Using a class for responses makes the code cleaner and easier to add new response type handlers in the future. - The response type is declared while a new variable is initialized and the `error` and `send` methods will print a proper output according to it - The header for the response is also set accordingly to the response type (`text/plain` for `csv`/`gyazo` output, `application/json` for `json` output) `static/classes/UploadException.class.php` `Exception` class extension to manage errors that may have occurred while uploading files to the server. This way every error is reported in detail. `static/includes/settings.inc.php` - `POMF_URL`: add an option to set the domain of the url to prepend to the newly generated filename (before it was hardcoded and it was `http://a.pomf.se/`) [this option is currently used only when the output is set to `gyazo`] `upload.php` - Add functions calls at the beginning to enable the output compression if possible (gzipped output) - Include new classes - `generate_name ()` --- The new name generation algorithm is basically the same of the old one, but it's easier to add/remove characters if needed (eg. lower-case letters isn't enough and you need to add capital-case letters or digits) --- Check directly the database instead of the filesystem to see if a generated filename is already in use - `upload_file ()` --- File errors generate a `UploadException` instead of a normal `Exception` --- Move common code outside the `if` to avoid useless code repetition (only the query is now inside the condition) --- Change file permissions of a file after moving it to the new directory (if the user didn't set a mask previouly these files wouldn't be world readable, we make sure they are) - `diverse_array ()` --- Function to reorder initial `$_FILES` array (easier to handle for `refiles`) - `refiles ()` --- Use a `foreach` cicle instead of a `for` one, easier to understand - Create a new response object and set its response type (`csv`, `gyazo` or default to `json`) - Edit response handling according to the new response class --- static/classes/Response.class.php | 98 ++++++++++ static/classes/UploadException.class.php | 45 +++++ static/classes/UploadedFile.class.php | 13 +- static/includes/settings.inc.php | 17 +- static/upload.php | 316 +++++++++++++------------------ 5 files changed, 294 insertions(+), 195 deletions(-) create mode 100755 static/classes/Response.class.php create mode 100755 static/classes/UploadException.class.php (limited to 'static') diff --git a/static/classes/Response.class.php b/static/classes/Response.class.php new file mode 100755 index 0000000..41f946c --- /dev/null +++ b/static/classes/Response.class.php @@ -0,0 +1,98 @@ +type = $response_type; + break; + default: + header('Content-Type: application/json; charset=UTF-8'); + $this->type = 'json'; + break; + } + } + + public function error ($code, $desc) { + $response = null; + + switch ($this->type) { + case 'csv': + $response = $this->csv_error($desc); + break; + case 'gyazo': + $response = $this->gyazo_error($code, $desc); + break; + default: + $response = $this->json_error($code, $desc); + break; + } + + http_response_code($code); + echo $response; + } + + public function send ($files) { + $response = null; + + switch ($this->type) { + case 'csv': + $response = $this->csv_success($files); + break; + case 'gyazo': + $response = $this->gyazo_success($files); + break; + default: + $response = $this->json_success($files); + break; + } + + http_response_code(200); + echo $response; + } + + private static function csv_error ($description) { + return "error\n" . $description . "\n"; + } + + private static function csv_success ($files) { + $result = "name,url,hash,size\n"; + foreach ($files as $file) { + $result .= $file['name'] . "," . + $file['url'] . "," . + $file['hash'] . "," . + $file['size'] . "\n"; + } + + return $result; + } + + private static function gyazo_error ($code, $description) { + return "ERROR: (" . $code . ") " . $description; + } + + private static function gyazo_success ($files) { + return POMF_URL . $files[0]['url']; + } + + private static function json_error ($code, $description) { + return json_encode(array( + 'success' => false, + 'errorcode' => $code, + 'description' => $description + )); + } + + private static function json_success ($files) { + return json_encode(array( + 'success' => true, + 'files' => $files + )); + } +} + +?> \ No newline at end of file diff --git a/static/classes/UploadException.class.php b/static/classes/UploadException.class.php new file mode 100755 index 0000000..b1b4839 --- /dev/null +++ b/static/classes/UploadException.class.php @@ -0,0 +1,45 @@ +codeToMessage($code); + parent::__construct($message, 500); + } + + private function codeToMessage($code) { + switch ($code) { + case UPLOAD_ERR_INI_SIZE: + $message = "The uploaded file exceeds the upload_max_filesize directive in php.ini"; + break; + case UPLOAD_ERR_FORM_SIZE: + $message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was " . + "specified in the HTML form"; + break; + case UPLOAD_ERR_PARTIAL: + $message = "The uploaded file was only partially uploaded"; + break; + case UPLOAD_ERR_NO_FILE: + $message = "No file was uploaded"; + break; + case UPLOAD_ERR_NO_TMP_DIR: + $message = "Missing a temporary folder"; + break; + case UPLOAD_ERR_CANT_WRITE: + $message = "Failed to write file to disk"; + break; + case UPLOAD_ERR_EXTENSION: + $message = "File upload stopped by extension"; + break; + + default: + $message = "Unknown upload error"; + break; + } + return $message; + } +} + +?> \ No newline at end of file diff --git a/static/classes/UploadedFile.class.php b/static/classes/UploadedFile.class.php index 5b7ba9b..102d6d9 100644 --- a/static/classes/UploadedFile.class.php +++ b/static/classes/UploadedFile.class.php @@ -4,9 +4,9 @@ class UploadedFile { /* Public attributes */ public $name; public $mime; + public $size; public $tempfile; public $error; - public $size; /* Cached checksums */ private $sha1; @@ -14,17 +14,24 @@ class UploadedFile { /** * Generates the SHA1 or returns the cached SHA1 hash for the file. + * + * @return string */ public function get_sha1 () { - if (! $this->sha1) $this->sha1 = sha1_file($this->tempfile); + if (!$this->sha1) + $this->sha1 = sha1_file($this->tempfile); return $this->sha1; } + /** * Generates the CRC32 or returns the cached CRC32 hash for the file. + * + * @return string */ public function get_crc32 () { - if (! $this->crc32) $this->crc32 = hash_file('crc32b', $this->tempfile); + if (!$this->crc32) + $this->crc32 = hash_file('crc32b', $this->tempfile); return $this->crc32; } diff --git a/static/includes/settings.inc.php b/static/includes/settings.inc.php index 70c7aec..cb152e8 100644 --- a/static/includes/settings.inc.php +++ b/static/includes/settings.inc.php @@ -1,26 +1,19 @@ name, PATHINFO_EXTENSION); - // And if we realize it's actually a doubledot - // we just override $ext + $ext = pathinfo($file->name, PATHINFO_EXTENSION); + + // Check if extension is a double-dot extension and, if true, override $ext $revname = strrev($file->name); foreach ($doubledots as $ddot) { if (stripos($revname, $ddot) === 0) { $ext = strrev($ddot); } } + + do { - // If we run out of tries, throw an exception. Should be caught and JSONified. - if ($tries-- == 0) throw new Exception('Gave up trying to find an unused name'); - //Random filename generator - $newname=''; - $startNumber = ord('a'); - $endNumber = ord('z'); + // Iterate until we reach the maximum number of retries + if ($tries-- == 0) throw new Exception('Gave up trying to find an unused name', 500); + + $chars = 'abcdefghijklmnopqrstuvwxyz'; + $name = ''; for ($i = 0; $i < 6; $i++) { - $newname .= chr(mt_rand($startNumber, $endNumber)); + $name .= $chars[mt_rand(0, 25)]; + // $chars string length is hardcoded, should use a variable to store it? } - // To add a dot or not after a file which has no extension - if ($ext != '') $newname .= '.' . strip_tags($ext); - } while (file_exists(POMF_FILES_ROOT . $newname)); // TODO: check the database instead? - return $newname; + + // Add the extension to the file name + if (isset($ext) && $ext !== '') + $name .= '.' . strip_tags($ext); + + // Check if a file with the same name does already exist in the database + $q = $db->prepare('SELECT COUNT(name) FROM pomf WHERE name = (:name)'); + $q->bindValue(':name', $name, PDO::PARAM_STR); + $q->execute(); + $result = $q->fetchColumn(); + // If it does, generate a new name + } while($result > 0); + + return $name; } + /** * Handles the uploading and db entry for a file * - * @param UploadedFile $file + * @param UploadedFile $file * @return array */ function upload_file ($file) { global $db; - // If the file has an error attached, we just throw it as an exception. - if ($file->error) throw new Exception($file->error); - // Check if we have a file with that hash in the db - if(empty($_SESSION['id'])){ - $q = $db->prepare("SELECT hash, filename, size FROM files WHERE hash = (:hash) AND user = (:user)"); - $q->bindValue('hash', $file->get_sha1()); - $q->bindValue('user', '0'); + + // Handle file errors + if ($file->error) throw new UploadException($file->error); + + // Check if a file with the same hash and size (a file which is the same) does already exist in + // the database; if it does, delete the file just uploaded and return the proper link and data. + $q = $db->prepare('SELECT filename, COUNT(*) AS count FROM files WHERE hash = (:hash) ' . + 'AND size = (:size)'); + $q->bindValue(':hash', $file->get_sha1(), PDO::PARAM_STR); + $q->bindValue(':size', $file->size, PDO::PARAM_INT); $q->execute(); $result = $q->fetch(); - // If we found a file with the same checksums, then we can assume it's a dupe - // so we don't bother with it, and just unlink (delete) the tmpfile and return - // the previous data. - if ($result['hash'] === $file->get_sha1()) { + if ($result['count'] > 0) { unlink($file->tempfile); return array( - 'hash' => $result['hash'], + 'hash' => $file->get_sha1(), 'name' => $file->name, - 'url' => $result['filename'], - 'size' => $result['size'] + 'url' => $result['filename'], + 'size' => $file->size ); - } else { - // Generate a name for the file - $newname = generate_name($file); - // Attempt to move it to the static directory - if (move_uploaded_file($file->tempfile, POMF_FILES_ROOT . $newname)) { + } + + // Generate a name for the file + $newname = generate_name($file); + + // Attempt to move it to the static directory + if (move_uploaded_file($file->tempfile, POMF_FILES_ROOT . $newname)) { + // Need to change permissions for the new file to make it world readable + if (chmod(POMF_FILES_ROOT . $newname, 0644)) { // Add it to the database - $q = $db->prepare('INSERT INTO files (hash, orginalname, filename, size, date, expire, delid)' . - 'VALUES (:hash, :orig, :name, :size, :date, :expires, :delid)'); - $q->bindValue(':hash', $file->get_sha1()); - $q->bindValue(':orig', strip_tags($file->name)); - $q->bindValue(':name', $newname); - $q->bindValue(':size', $file->size); - $q->bindValue(':date', date('Y-m-d')); - $q->bindValue(':expires', null); - $q->bindValue(':delid', sha1($file->tempfile)); + if (empty($_SESSION['id'])) { + // Query if user is NOT logged in + $q = $db->prepare('INSERT INTO files (hash, originalname, filename, size, date, ' . + 'expire, delid) VALUES (:hash, :orig, :name, :size, :date, ' . + ':exp, :del)'); + } else { + // Query if user is logged in (insert user id together with other data) + $q = $db->prepare('INSERT INTO files (hash, originalname, filename, size, date, ' . + 'expire, delid, user) VALUES (:hash, :orig, :name, :size, ' . + ':date, :expires, :delid, :user)'); + $q->bindValue(':user', $_SESSION['id'], PDO::PARAM_INT); + } + + // Common parameters binding + $q->bindValue(':hash', $file->get_sha1(), PDO::PARAM_STR); + $q->bindValue(':orig', strip_tags($file->name), PDO::PARAM_STR); + $q->bindValue(':name', $newname, PDO::PARAM_STR); + $q->bindValue(':size', $file->size, PDO::PARAM_INT); + $q->bindValue(':date', date('Y-m-d'), PDO::PARAM_STR); + $q->bindValue(':exp', null, PDO::PARAM_STR); + $q->bindValue(':del', sha1($file->tempfile), PDO::PARAM_STR); $q->execute(); + return array( 'hash' => $file->get_sha1(), 'name' => $file->name, - 'url' => $newname, + 'url' => $newname, 'size' => $file->size ); } else { - throw new Exception('Failed to move file to destination'); + throw new Exception('Failed to change file permissions', 500); } - } -}else{//if session exists - $q = $db->prepare("SELECT hash, filename, size FROM files WHERE hash = (:hash) AND user = (:user)"); - $q->bindValue('hash', $file->get_sha1()); - $q->bindValue('user', $_SESSION['id']); - $q->execute(); - $result = $q->fetch(); - // If we found a file with the same checksums, then we can assume it's a dupe - // so we don't bother with it, and just unlink (delete) the tmpfile and return - // the previous data. - if ($result['hash'] === $file->get_sha1()) { - unlink($file->tempfile); - return array( - 'hash' => $result['hash'], - 'name' => $file->name, - 'url' => $result['filename'], - 'size' => $result['size'] - ); - } else { - // Generate a name for the file - $newname = generate_name($file); - // Attempt to move it to the static directory - if (move_uploaded_file($file->tempfile, POMF_FILES_ROOT . $newname)) { - // Add it to the database - $q = $db->prepare('INSERT INTO files (hash, orginalname, filename, size, date, expire, delid, user)' . - 'VALUES (:hash, :orig, :name, :size, :date, :expires, :delid, :user)'); - $q->bindValue(':hash', $file->get_sha1()); - $q->bindValue(':orig', strip_tags($file->name)); - $q->bindValue(':name', $newname); - $q->bindValue(':size', $file->size); - $q->bindValue(':date', date('Y-m-d')); - $q->bindValue(':expires', null); - $q->bindValue(':delid', sha1($file->tempfile)); - $q->bindValue(':user', $_SESSION['id']); - $q->execute(); - return array( - 'hash' => $file->get_sha1(), - 'name' => $file->name, - 'url' => $newname, - 'size' => $file->size - ); - } else { - throw new Exception('Failed to move file to destination'); - } - } -} -} -/** - * Reorganize the $_FILES array into something saner - * - * @param $_FILES - */ -function refiles ($files) { - $out = array(); - for ($i = 0, $n = count($files['name']); $i < $n; ++$i) { - // We create a new UploadedFile instance - $file = new UploadedFile(); - // And fill it with our shit - $file->name = $files['name'][$i]; - $file->mime = $files['type'][$i]; - $file->tempfile = $files['tmp_name'][$i]; - $file->error = $files['error'][$i]; - $file->size = $files['size'][$i]; - $file->expire = $files['expire'][$i]; - $out[] = $file; - } - return $out; -} -/** - * Give a response that gyazo understands - */ -function respond_gyazo ($code, $files) { - if ($files instanceof Exception) { - echo "ERROR: " . $files->getMessage(); } else { - echo 'http://a.pomf.se/' . $files[0]['url']; + throw new Exception('Failed to move file to destination', 500); } } + /** - * Responds to a request in CSV form. + * Reorder files array by file + * + * @param $_FILES + * @return array */ -function respond_csv ($code, $files) { - if ($files instanceof Exception) { - echo "error\n"; - echo $files->getMessage() . "\n"; - } else { - echo "name,url,hash,size\n"; - foreach ($files as $file) { - echo "${file['name']},${file['url']},${file['hash']},${file['size']}\n"; - } - } +function diverse_array ($files) { + $result = array(); + foreach ($files as $key1 => $value1) + foreach ($value1 as $key2 => $value2) + $result[$key2][$key1] = $value2; + + return $result; } + /** - * Responds to a request in JSON form. - */ -function respond_json ($code, $files) { - // Now we send the response based on the type - if ($files instanceof Exception) { - // If it's an Exception, we put the message in the error field - echo json_encode(array( - 'success' => false, - 'error' => $files->getMessage() - )); - } elseif (is_array($files)) { - echo json_encode(array( - 'success' => true, - 'error' => null, - 'files' => $files - )); - } -} -/** - * Determines the proper response function based on $_GET['output] + * Reorganize the $_FILES array into something saner + * + * @param $_FILES + * @return array */ -function respond ($code, $files = null) { - if (is_int($code)) { // If the code is an integer, we assume it's a response code - http_response_code($code); - } else { // Otherwise we just use the default and shift - http_response_code(200); - $files = $code; - } - $format = array_key_exists('output', $_GET) ? $_GET['output'] : 'json'; - switch ($format) { - case 'gyazo': - respond_gyazo($code, $files); - break; - case 'csv': - respond_csv($code, $files); - break; - case 'json': - respond_json($code, $files); - break; +function refiles ($files) { + $result = array(); + $files = diverse_array($files); + + foreach ($files as $file) { + $f = new UploadedFile(); + $f->name = $file['name']; + $f->mime = $file['type']; + $f->size = $file['size']; + $f->tempfile = $file['tmp_name']; + $f->error = $file['error']; + // 'expire' doesn't exist neither in $_FILES nor in UploadedFile; + // commented out for future implementation + //$f->expire = $file['expire']; + $result[] = $f; } + + return $result; } + + + +$type = isset($_GET['output']) ? $_GET['output'] : 'json'; +$response = new Response($type); if (isset($_FILES['files'])) { + $uploads = refiles($_FILES['files']); try { - $uploads = refiles($_FILES['files']); - foreach ($uploads as $upload) { - $out[] = upload_file($upload); - } - respond($out); + foreach ($uploads as $upload) + $res[] = upload_file($upload); + $response->send($res); } catch (Exception $e) { - respond(500, $e); + $response->error($e->getCode(), $e->getMessage()); } } else { - respond(500, new Exception('Nigga what you doin\' here?')); + $response->error(400, 'No input file(s)'); } + ?> -- cgit v1.2.3