summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorEric Johansson (neku) <neku@pomf.se>2015-02-05 20:06:08 +0100
committerEric Johansson (neku) <neku@pomf.se>2015-02-05 20:06:08 +0100
commitb816236168e74309be4a298ff0a4644a732dc9f3 (patch)
tree1497dced7d755362dcdfd73b7e11d78b04597f2d
parentc359aa20cd0876e1e497aca1ff19e4c54287b6c2 (diff)
parentfd98101d073805fc42474a00bca640a618f99de6 (diff)
Merge pull request #27 from cenci0/master
Minor code refactoring and improvements
-rw-r--r--Gruntfile.js18
-rw-r--r--README.md11
-rw-r--r--js/pomf.js3
-rw-r--r--schema.sql49
-rwxr-xr-xstatic/classes/Response.class.php98
-rwxr-xr-xstatic/classes/UploadException.class.php45
-rw-r--r--static/classes/UploadedFile.class.php13
-rw-r--r--static/includes/settings.inc.php17
-rw-r--r--static/upload.php316
-rwxr-xr-xupdate.sql16
10 files changed, 364 insertions, 222 deletions
diff --git a/Gruntfile.js b/Gruntfile.js
index 18c6a8b..10e2b2b 100644
--- a/Gruntfile.js
+++ b/Gruntfile.js
@@ -22,6 +22,22 @@ module.exports = function (grunt) {
production: false,
}
},
+ htmlmin: {
+ dist: {
+ options: {
+ removeComments: true,
+ collapseWhitespace: true,
+ conservativeCollapse: true,
+ removeEmptyAttributes: true
+ },
+ files: [{
+ expand: true,
+ cwd: 'dist/',
+ src: '**/*.html',
+ dest: 'dist/'
+ }]
+ }
+ },
uglify: {
options: {
banner: '/*! <%= pkg.name %> (<%= pkg.repository.url %>) @ <%= grunt.template.today("yyyy-mm-dd") %> */\n\n'
@@ -85,5 +101,5 @@ module.exports = function (grunt) {
grunt.loadNpmTasks('grunt-contrib-imagemin');
grunt.loadNpmTasks('grunt-contrib-copy');
- grunt.registerTask('default', ['mkdir', 'swig', 'cssmin', 'uglify', 'imagemin', 'copy']);
+ grunt.registerTask('default', ['mkdir', 'swig', 'htmlmin', 'cssmin', 'uglify', 'imagemin', 'copy']);
};
diff --git a/README.md b/README.md
index 6b930f8..e4f9618 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
# Pomf.se
-Only tested with Nginx + PHP5.5 + MySQL, but should work with newer PHP or any
-other PDO-compatible database.
+Original development environment is Nginx + PHP5.5 + MySQL, but is confirmed to work with Apache 2.4
+and newer PHP versions. Should work with any other PDO-compatible database.
Most of the code is ghetto and easily improved, will clean it up sometime. Modify it as you like.
@@ -25,6 +25,13 @@ $ grunt
```
After this, the pomf site is now compressed and set up inside `dist/`.
+### Apache
+If you are runnging Apache and want to compress your output when serving files, add to your `.htaccess` file:
+```
+AddOutputFilterByType DEFLATE text/html text/plain text/css application/javascript application/x-javascript application/json
+```
+Remember to enable `deflate_module` and `filter_module` modules in your Apache configuration file.
+
## Configuring
The majority of settings are in `static/includes/settings.inc.php`. Read the
comments in that file for more information.
diff --git a/js/pomf.js b/js/pomf.js
index 59017fe..52d03ee 100644
--- a/js/pomf.js
+++ b/js/pomf.js
@@ -135,7 +135,8 @@ $(function () {
break
case 413:
uploadFiles.addClass('error completed')
- totalName.html('onii-chan, y-your upload is t-too big&hellip;')
+ // Terrible work-around, but necessary since otherwise the '&hellip;' entity is left decoded
+ totalName.html($('<div/>').html('onii-chan, y-your upload is t-too big&hellip;').text());
break
default:
uploadFiles.addClass('error completed')
diff --git a/schema.sql b/schema.sql
index 8580f9a..a640e6d 100644
--- a/schema.sql
+++ b/schema.sql
@@ -7,7 +7,7 @@
--
CREATE TABLE `accounts` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
+ `id` int(10) unsigned NOT NULL auto_increment,
`email` varchar(255) NOT NULL,
`pass` varchar(255) NOT NULL,
`level` int(11) NOT NULL,
@@ -19,29 +19,32 @@ CREATE TABLE `accounts` (
--
CREATE TABLE `files` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `hash` char(40) DEFAULT NULL,
- `orginalname` varchar(255) DEFAULT NULL,
- `filename` varchar(30) DEFAULT NULL,
- `size` int(11) DEFAULT NULL,
- `date` date DEFAULT NULL,
- `expire` date DEFAULT NULL,
- `delid` char(40) DEFAULT NULL,
- `user` int(11) DEFAULT '0',
- `dir` int(2) DEFAULT '0',
+ `id` int(10) unsigned NOT NULL auto_increment,
+ `hash` char(40) default NULL,
+ `originalname` varchar(255) default NULL,
+ `filename` varchar(30) default NULL,
+ `size` int(10) unsigned default NULL,
+ `date` date default NULL,
+ `expire` date default NULL,
+ `delid` char(40) default NULL,
+ `user` int(10) unsigned default '0',
+ `dir` int(2) default '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
+-- `filename` length (30) may be a bit excessive, since the average length would be smaller
+-- [6 for the name + the file extension length], but since there is no limit for the file
+-- extension length (at the moment, at least) let's keep it high in order to avoid problems
--
-- Table structure for table `invites`
--
CREATE TABLE `invites` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `email` varchar(50) DEFAULT '0',
- `code` varchar(50) DEFAULT '0',
- `used` int(11) DEFAULT '0',
- `level` int(11) DEFAULT NULL,
+ `id` int(10) unsigned NOT NULL auto_increment,
+ `email` varchar(50) default '0',
+ `code` varchar(50) default '0',
+ `used` int(11) default '0',
+ `level` int(11) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
@@ -50,13 +53,13 @@ CREATE TABLE `invites` (
--
CREATE TABLE `reports` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `hash` char(40) DEFAULT '0',
- `date` date DEFAULT NULL,
- `file` varchar(255) NOT NULL DEFAULT '0',
- `fileid` int(11) DEFAULT '0',
- `reporter` varchar(255) NOT NULL DEFAULT '0',
- `status` int(11) DEFAULT '0',
+ `id` int(10) unsigned NOT NULL auto_increment,
+ `hash` char(40) default '0',
+ `date` date default NULL,
+ `file` varchar(255) NOT NULL default '0',
+ `fileid` int(11) default '0',
+ `reporter` varchar(255) NOT NULL default '0',
+ `status` int(11) default '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
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 @@
+<?php
+
+class Response {
+ private $type;
+
+ public function __construct ($response_type = null) {
+ switch ($response_type) {
+ case 'csv':
+ case 'gyazo':
+ header('Content-Type: text/plain; charset=UTF-8');
+ $this->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 @@
+<?php
+
+// Exception class extension from: http://php.net/manual/en/features.file-upload.errors.php#89374
+// Handles files error returning a proper error description
+
+class UploadException extends Exception {
+ public function __construct($code) {
+ $message = $this->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 @@
<?php
-/**
- * PDO Connection data
- */
+
// PDO socket
// Or using socket would be even faster then 127.0.0.1 :3
define('POMF_DB_CONN', 'mysql:host=127.0.0.1;dbname=pomf');
-// PDO user
+// MySQL user and password
define('POMF_DB_USER', 'pomf');
-// PDO password
define('POMF_DB_PASS', '***');
-/**
- * File stuff
- */
// Root location of files
define('POMF_FILES_ROOT', '/mnt/disk1/pomf/files/');
-// How many times to retry when exists() before giving up
+// Maximum number of iterations while generating a new name
define('POMF_FILES_RETRIES', 15);
+// URL to prepend to output (include trailing slash)
+define('POMF_URL', 'http://a.pomf.se/');
-/**
- * Double-dot extensions
- */
$doubledots = array_map('strrev', array(
'tar.gz',
'tar.bz',
diff --git a/static/upload.php b/static/upload.php
index 43b0c31..7756e03 100644
--- a/static/upload.php
+++ b/static/upload.php
@@ -1,241 +1,197 @@
<?php
+// Check if we can compress our output; if we can, we'll do it
+if (ini_get('zlib.output_compression') !== 'Off'
+ && isset($_SERVER["HTTP_ACCEPT_ENCODING"])
+ && strpos($_SERVER["HTTP_ACCEPT_ENCODING"], 'gzip') !== false)
+ ob_start("ob_gzhandler");
+
session_start();
+include_once 'classes/Response.class.php';
+include_once 'classes/UploadException.class.php';
include_once 'classes/UploadedFile.class.php';
-//include_once 'includes/database.inc.php'; Included in database.inc.php
include_once 'includes/database.inc.php';
+
+
/**
- * Generates a name for the file, retrying until we get an unused one
+ * Generates a random name for the file, retrying until we get an unused one
*
- * @param UploadedFile $file
+ * @param UploadedFile $file
* @return string
*/
function generate_name ($file) {
+ global $db;
global $doubledots;
+
// We start at N retries, and --N until we give up
$tries = POMF_FILES_RETRIES;
- // We rip out the extension using pathinfo
- $ext = pathinfo($file->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)');
}
+
?>
diff --git a/update.sql b/update.sql
new file mode 100755
index 0000000..ac4d548
--- /dev/null
+++ b/update.sql
@@ -0,0 +1,16 @@
+ALTER TABLE `accounts`
+CHANGE COLUMN `id` `id` int(10) unsigned NOT NULL auto_increment;
+
+ALTER TABLE `files`
+CHANGE COLUMN `id` `id` int(10) unsigned NOT NULL auto_increment,
+CHANGE COLUMN `orginalname` `originalname` varchar(255) NULL default NULL,
+CHANGE COLUMN `size` `size` int(10) NULL default NULL,
+CHANGE COLUMN `user` `user` int(10) NULL default '0';
+
+ALTER TABLE `invites`
+CHANGE COLUMN `id` `id` int(10) unsigned NOT NULL auto_increment;
+
+ALTER TABLE `reports`
+CHANGE COLUMN `id` `id` int(10) unsigned NOT NULL auto_increment,
+CHANGE COLUMN `file` `file` varchar(255) NOT NULL,
+CHANGE COLUMN `reporter` `reporter` varchar(255) NOT NULL; \ No newline at end of file