3 * Handles POST uploads, generates filenames, moves files around and commits
4 * uploaded metadata to database.
6 require_once 'classes/Response.class.php';
7 require_once 'classes/UploadException.class.php';
8 require_once 'classes/UploadedFile.class.php';
9 require_once 'includes/database.inc.php';
12 * Generates a random name for the file, retrying until we get an unused one.
14 * @param UploadedFile $file
18 function generateName($file)
23 // We start at N retries, and --N until we give up
24 $tries = UGUU_FILES_RETRIES
;
25 $length = UGUU_FILES_LENGTH
;
28 $ext = pathinfo($file->name
, PATHINFO_EXTENSION
);
31 $finfo = finfo_open(FILEINFO_MIME_TYPE
);
32 $type_mime = finfo_file($finfo, $file->tempfile
);
35 // Check if extension is a double-dot extension and, if true, override $ext
36 $revname = strrev($file->name
);
37 foreach ($doubledots as $ddot) {
38 if (stripos($revname, $ddot) === 0) {
44 // Iterate until we reach the maximum number of retries
46 http_response_code(500);
48 'Gave up trying to find an unused name',
50 ); // HTTP status code "500 Internal Server Error"
55 for ($i = 0; $i < $length; ++
$i) {
56 $name .= $chars[mt_rand(0, strlen($chars))];
59 // Add the extension to the file name
60 if (isset($ext) && $ext !== '') {
64 // Check if file is whitelisted or blacklisted
65 switch (CONFIG_FILTER_MODE
) {
68 //check if MIME is blacklisted
69 if (in_array($type_mime, unserialize(CONFIG_BLOCKED_MIME
))) {
70 http_response_code(415);
73 //Check if EXT is blacklisted
74 if (in_array($ext, unserialize(CONFIG_BLOCKED_EXTENSIONS
))) {
75 http_response_code(415);
81 //Check if MIME is whitelisted
82 if (!in_array($type_mime, unserialize(CONFIG_BLOCKED_MIME
))) {
83 http_response_code(415);
86 //Check if EXT is whitelisted
87 if (!in_array($ext, unserialize(CONFIG_BLOCKED_EXTENSIONS
))) {
88 http_response_code(415);
94 // Check if a file with the same name does already exist in the database
95 $q = $db->prepare('SELECT COUNT(filename) FROM files WHERE filename = (:name)');
96 $q->bindValue(':name', $name, PDO
::PARAM_STR
);
98 $result = $q->fetchColumn();
99 // If it does, generate a new name
100 } while ($result > 0);
106 * Handles the uploading and db entry for a file.
108 * @param UploadedFile $file
112 function uploadFile($file)
116 // Handle file errors
118 throw new UploadException($file->error
);
122 $lol = $file->getSha1();
124 // Check if a file with the same hash and size (a file which is the same)
125 // does already exist in the database; if it does, return the proper link
126 // and data. PHP deletes the temporary file just uploaded automatically.
128 $q = $db->prepare('SELECT filename, COUNT(*) AS count FROM files WHERE hash = (:hash) AND size = (:size)');
129 $q->bindValue(':hash', $file->getSha1(), PDO
::PARAM_STR
);
130 $q->bindValue(':size', $file->size
, PDO
::PARAM_INT
);
132 $result = $q->fetch();
133 if ($result['count'] > 0) {
135 'hash' => $file->getSha1(),
136 'name' => $file->name
,
137 'url' => UGUU_URL
.rawurlencode($result['filename']),
138 'size' => $file->size
,
143 // Generate a name for the file
144 $newname = generateName($file);
146 // Store the file's full file path in memory
147 $uploadFile = UGUU_FILES_ROOT
.$newname;
149 // Attempt to move it to the static directory
150 if (!move_uploaded_file($file->tempfile
, $uploadFile)) {
151 http_response_code(500);
153 'Failed to move file to destination',
155 ); // HTTP status code "500 Internal Server Error"
158 // Need to change permissions for the new file to make it world readable
159 if (!chmod($uploadFile, 0644)) {
160 http_response_code(500);
162 'Failed to change file permissions',
164 ); // HTTP status code "500 Internal Server Error"
169 $ip = $_SERVER['REMOTE_ADDR'];
174 // Common parameters binding
175 $q = $db->prepare('INSERT INTO files (hash, originalname, filename, size, date, ip) VALUES (:hash, :orig, :name, :size, :date, :ip)');
176 $q->bindValue(':hash', $file->getSha1(), PDO
::PARAM_STR
);
177 $q->bindValue(':orig', strip_tags($file->name
), PDO
::PARAM_STR
);
178 $q->bindValue(':name', $newname, PDO
::PARAM_STR
);
179 $q->bindValue(':size', $file->size
, PDO
::PARAM_INT
);
180 $q->bindValue(':date', time(), PDO
::PARAM_STR
);
181 $q->bindValue(':ip', $ip, PDO
::PARAM_STR
);
185 'hash' => $file->getSha1(),
186 'name' => $file->name
,
187 'url' => UGUU_URL
.rawurlencode($newname),
188 'size' => $file->size
,
193 * Reorder files array by file.
197 function diverseArray($files)
201 foreach ($files as $key1 => $value1) {
202 foreach ($value1 as $key2 => $value2) {
203 $result[$key2][$key1] = $value2;
211 * Reorganize the $_FILES array into something saner.
215 function refiles($files)
218 $files = diverseArray($files);
220 foreach ($files as $file) {
221 $f = new UploadedFile();
222 $f->name
= $file['name'];
223 $f->mime
= $file['type'];
224 $f->size
= $file['size'];
225 $f->tempfile
= $file['tmp_name'];
226 $f->error
= $file['error'];
233 $type = isset($_GET['output']) ? $_GET['output'] : 'json';
234 $response = new Response($type);
236 if (isset($_FILES['files'])) {
237 $uploads = refiles($_FILES['files']);
240 foreach ($uploads as $upload) {
241 $res[] = uploadFile($upload);
243 $response->send($res);
244 } catch (Exception
$e) {
245 $response->error($e->getCode(), $e->getMessage());
248 $response->error(400, 'No input file(s)');