]> jfr.im git - uguu.git/blame - static/php/upload.php
change desc
[uguu.git] / static / php / upload.php
CommitLineData
d8c46ff7
GJ
1<?php
2/**
3 * Require the settings and DB files.
4 */
5require_once 'classes/Response.class.php';
6require_once 'classes/UploadException.class.php';
7require_once 'classes/UploadedFile.class.php';
8require_once 'includes/database.inc.php';
9
10/**
11 * Generates name and checks in DB
12 * Also adds to DB.
13 */
14function generateName($file)
15{
16 global $db;
17 global $doubledots;
18
19 // We start at N retries, and --N until we give up
b1d3139a
GJ
20 $tries = UGUU_FILES_RETRIES;
21 $length = UGUU_FILES_LENGTH;
d8c46ff7
GJ
22 //Get EXT
23 $ext = pathinfo($file->name, PATHINFO_EXTENSION);
24 //Get mime
25 $finfo = finfo_open(FILEINFO_MIME_TYPE);
26 $type_mime = finfo_file($finfo, $file->tempfile);
27 finfo_close($finfo);
28
29 // Check if extension is a double-dot extension and, if true, override $ext
30 $revname = strrev($file->name);
31 foreach ($doubledots as $ddot) {
32 if (stripos($revname, $ddot) === 0) {
33 $ext = strrev($ddot);
34 }
35 }
36
37 do {
38 // Iterate until we reach the maximum number of retries
39 if ($tries-- === 0) {
40 throw new Exception(
41 'Gave up trying to find an unused name',
42 500
43 ); // HTTP status code "500 Internal Server Error"
44 }
45
46 $chars = ID_CHARSET;
47 $name = '';
48 for ($i = 0; $i < $length; ++$i) {
49 $name .= $chars[mt_rand(0, strlen($chars))];
50 }
51
52 // Add the extension to the file name
53 if (isset($ext) && $ext !== '') {
54 $name .= '.'.$ext;
55 }
56
57 //Check if mime is blacklisted
58 if (in_array($type_mime, unserialize(CONFIG_BLOCKED_MIME))) {
180e8018 59 throw new Exception('Filetype not allowed!');
d8c46ff7
GJ
60 exit(0);
61 }
62
63 //Check if EXT is blacklisted
64 if (in_array($ext, unserialize(CONFIG_BLOCKED_EXTENSIONS))) {
180e8018 65 throw new Exception('Filetype not allowed!');
d8c46ff7
GJ
66 exit(0);
67 }
68
69 // Check if a file with the same name does already exist in the database
70 $q = $db->prepare('SELECT COUNT(filename) FROM files WHERE filename = (:name)');
71 $q->bindValue(':name', $name, PDO::PARAM_STR);
72 $q->execute();
73 $result = $q->fetchColumn();
74 // If it does, generate a new name
75 } while ($result > 0);
76
77 return $name;
78}
79
80/**
81 * Handles the uploading and db entry for a file.
82 *
83 * @param UploadedFile $file
84 *
85 * @return array
86 */
87function uploadFile($file)
88{
89 global $db;
90 global $FILTER_MODE;
91 global $FILTER_MIME;
92
93 // Handle file errors
94 if ($file->error) {
95 throw new UploadException($file->error);
96 }
97
98 // Generate a name for the file
99 $newname = generateName($file);
100
101 // Store the file's full file path in memory
b1d3139a 102 $uploadFile = UGUU_FILES_ROOT.$newname;
d8c46ff7
GJ
103
104 // Attempt to move it to the static directory
105 if (!move_uploaded_file($file->tempfile, $uploadFile)) {
106 throw new Exception(
107 'Failed to move file to destination',
108 500
109 ); // HTTP status code "500 Internal Server Error"
110 }
111
112 // Need to change permissions for the new file to make it world readable
113 if (!chmod($uploadFile, 0644)) {
114 throw new Exception(
115 'Failed to change file permissions',
116 500
117 ); // HTTP status code "500 Internal Server Error"
118 }
119
120 // Add it to the database
121 $q = $db->prepare('INSERT INTO files (hash, originalname, filename, size, date) VALUES (:hash, :orig, :name, :size, :date)');
122
123 // Common parameters binding
124 $q->bindValue(':hash', $file->getSha1(), PDO::PARAM_STR);
125 $q->bindValue(':orig', strip_tags($file->name), PDO::PARAM_STR);
126 $q->bindValue(':name', $newname, PDO::PARAM_STR);
127 $q->bindValue(':size', $file->size, PDO::PARAM_INT);
128 $q->bindValue(':date', time(), PDO::PARAM_INT);
129 $q->execute();
130
131 return [
132 'hash' => $file->getSha1(),
133 'name' => $file->name,
b1d3139a 134 'url' => UGUU_URL.rawurlencode($newname),
d8c46ff7
GJ
135 'size' => $file->size,
136 ];
137}
138
139/**
140 * Reorder files array by file.
141 *
142 * @return array
143 */
144function diverseArray($files)
145{
146 $result = [];
147
148 foreach ($files as $key1 => $value1) {
149 foreach ($value1 as $key2 => $value2) {
150 $result[$key2][$key1] = $value2;
151 }
152 }
153
154 return $result;
155}
156
157/**
158 * Reorganize the $_FILES array into something saner.
159 *
160 * @return array
161 */
162function refiles($files)
163{
164 $result = [];
165 $files = diverseArray($files);
166
167 foreach ($files as $file) {
168 $f = new UploadedFile();
169 $f->name = $file['name'];
170 $f->mime = $file['type'];
171 $f->size = $file['size'];
172 $f->tempfile = $file['tmp_name'];
173 $f->error = $file['error'];
174 $result[] = $f;
175 }
176
177 return $result;
178}
179
180$type = isset($_GET['output']) ? $_GET['output'] : 'json';
181$response = new Response($type);
182
183if (isset($_FILES['files'])) {
184 $uploads = refiles($_FILES['files']);
185
186 try {
187 foreach ($uploads as $upload) {
188 $res[] = uploadFile($upload);
189 }
190 $response->send($res);
191 } catch (Exception $e) {
192 $response->error($e->getCode(), $e->getMessage());
193 }
194} else {
195 $response->error(400, 'No input file(s)');
196}