Verious improvements
[simple-upload.git] / index.php
1 <?php
2         /*
3                 This program is free software: you can redistribute it and/or modify
4                 it under the terms of the GNU General Public License as published by
5                 the Free Software Foundation, either version 3 of the License, or
6                 (at your option) any later version.
7
8                 This program is distributed in the hope that it will be useful,
9                 but WITHOUT ANY WARRANTY; without even the implied warranty of
10                 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11                 GNU General Public License for more details.
12
13                 You should have received a copy of the GNU General Public License
14                 along with this program.  If not, see <http://www.gnu.org/licenses/>.
15         */
16
17         // =============={ Configuration Begin }==============
18         $settings = array(
19
20                 // Website title
21                 title => 'strace.club',
22
23                 // Directory to store uploaded files
24                 uploaddir => '.',
25
26                 // Display list uploaded files
27                 listfiles => true,
28
29                 // Allow users to delete files that they have uploaded (will enable sessions)
30                 allow_deletion => true,
31
32                 // Allow users to mark files as hidden
33                 allow_private => true,
34
35                 // Display file sizes
36                 listfiles_size => true,
37
38                 // Display file dates
39                 listfiles_date => true,
40
41                 // Display file dates format
42                 listfiles_date_format => 'F d Y H:i:s',
43
44                 // Randomize file names (number of 'false')
45                 random_name_len => 8,
46
47                 // Keep filetype information (if random name is activated)
48                 random_name_keep_type => true,
49
50                 // Random file name letters
51                 random_name_alphabet => 'qazwsxedcrfvtgbyhnujmikolp1234567890',
52
53                 // Display debugging information
54                 debug => false,
55
56                 // Complete URL to your directory (including tracing slash)
57                 url => 'http://strace.club/'
58
59                 // Amount of seconds that each file should be stored for (0 for no limit)
60                 time_limit => 0,
61
62                 // Files that will be ignored
63                 ignores = array('.', '..', 'LICENSE', 'README.md'),
64         );
65         // =============={ Configuration End }==============
66
67         $data = array();
68
69         // Name of this file
70         $data['scriptname'] = pathinfo(__FILE__, PATHINFO_BASENAME);
71
72         // Adding current script name to ignore list
73         $data['ignores'][] = $data['scriptname'];
74
75         // Use canonized path
76         $data['uploaddir'] = realpath($settings['uploaddir']);
77
78         // Maximum upload size, set by system
79         $data['max_upload_size'] = ini_get('upload_max_filesize');
80
81         // If file deletion or private files are allowed, starting a session.
82         // This is required for user authentification
83         if ($settings['allow_deletion'] || $settings['allow_private']) {
84                 session_start();
85
86                 // 'User ID'
87                 if (!isset($_SESSION['upload_user_id']))
88                         $_SESSION['upload_user_id'] = rand(100000, 999999);
89
90                 // List of filenames that were uploaded by this user
91                 if (!isset($_SESSION['upload_user_files']))
92                         $_SESSION['upload_user_files'] = array();
93         }
94
95         // If debug is enabled, logging all variables
96         if ($settings['debug']) {
97
98                 // Enabling error reporting
99                 error_reporting(E_ALL);
100                 error_reporting(1);
101
102                 // Displaying debug information
103                 echo '<h2>Settings:</h2>';
104                 echo '<pre>';
105                 print_r($settings);
106                 echo '</pre>';
107
108                 // Displaying debug information
109                 echo '<h2>Data:</h2>';
110                 echo '<pre>';
111                 print_r($data);
112                 echo '</pre>';
113                 echo '</pre>';
114
115                 // Displaying debug information
116                 echo '<h2>SESSION:</h2>';
117                 echo '<pre>';
118                 print_r($_SESSION);
119                 echo '</pre>';
120         }
121
122         // Format file size
123         function FormatSize ($bytes) {
124                 $units = array('B', 'KB', 'MB', 'GB', 'TB');
125
126                 $bytes = max($bytes, 0);
127                 $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
128                 $pow = min($pow, count($units) - 1);
129
130                 $bytes /= pow(1024, $pow);
131
132                 return ceil($bytes) . ' ' . $units[$pow];
133         }
134
135         // Rotating a two-dimensional array
136         function DiverseArray ($vector) {
137                 $result = array();
138                 foreach ($vector as $key1 => $value1)
139                         foreach ($value1 as $key2 => $value2)
140                                 $result[$key2][$key1] = $value2;
141                 return $result;
142         }
143
144         // Handling file upload
145         function UploadFile ($file_data) {
146                 global $settings;
147                 global $data;
148                 global $_SESSION;
149
150                 $data['uploaded_file_name'] = basename($file_data['name']);
151                 $data['target_file_name'] = $file_data['uploaded_file_name'];
152
153                 // Generating random file name
154                 if ($settings['random_name_len'] !== false) {
155                         do {
156                                 $data['target_file_name'] = '';
157                                 while (strlen($data['target_file_name']) < $settings['random_name_len'])
158                                         $data['target_file_name'] .= $settings['random_name_alphabet'][rand(0, strlen($settings['random_name_alphabet']) - 1)];
159                                 if ($settings['random_name_keep_type'])
160                                         $data['target_file_name'] .= '.' . pathinfo($data['uploaded_file_name'], PATHINFO_EXTENSION);
161                         } while (file_exists($data['target_file_name']));
162                 }
163                 $data['upload_target_file'] = $data['uploaddir'] . DIRECTORY_SEPARATOR . $data['target_file_name'];
164
165                 // Do now allow to overwriting files
166                 if (file_exists($data['upload_target_file'])) {
167                         echo 'File name already exists' . "\n";
168                         return;
169                 }
170
171                 // Moving uploaded file OK
172                 if (move_uploaded_file($file_data['tmp_name'], $data['upload_target_file'])) {
173                         if ($settings['allow_deletion'] || $settings['allow_private'])
174                                 $_SESSION['upload_user_files'][] = $data['target_file_name'];
175                         echo $settings['url'] .  $data['target_file_name'] . "\n";
176                 } else {
177                         echo 'Error: unable to upload the file.';
178                 }
179         }
180
181
182         // Files are being POSEed. Uploading them one by one.
183         if (isset($_FILES['file'])) {
184                 header('Content-type: text/plain');
185                 if (is_array($_FILES['file'])) {
186                         $file_array = DiverseArray($_FILES['file']);
187                         foreach ($file_array as $file_data)
188                                 UploadFile($file_data);
189                 } else
190                         UploadFile($_FILES['file']);
191                 exit;
192         }
193
194         // Other file functions (delete, private).
195         if (isset($_POST)) {
196                 if ($settings['allow_deletion'])
197                         if ($_POST['action'] === 'delete')
198                                 if (in_array(substr($_POST['target'], 1), $_SESSION['upload_user_files']) || in_array($_POST['target'], $_SESSION['upload_user_files']))
199                                         if (file_exists($_POST['target'])) {
200                                                 unlink($_POST['target']);
201                                                 echo 'File has been removed';
202                                                 exit;
203                                         }
204
205                 if ($settings['allow_private'])
206                         if ($_POST['action'] === 'privatetoggle')
207                                 if (in_array(substr($_POST['target'], 1), $_SESSION['upload_user_files']) || in_array($_POST['target'], $_SESSION['upload_user_files']))
208                                         if (file_exists($_POST['target'])) {
209                                                 if ($_POST['target'][0] === '.') {
210                                                         rename($_POST['target'], substr($_POST['target'], 1));
211                                                         echo 'File has been made visible';
212                                                 } else {
213                                                         rename($_POST['target'], '.' . $_POST['target']);
214                                                         echo 'File has been hidden';
215                                                 }
216                                                 exit;
217                                         }
218         }
219
220         // List files in a given directory, excluding certain files
221         function ListFiles ($dir, $exclude) {
222                 $file_array = array();
223                 $dh = opendir($dir);
224                         while (false !== ($filename = readdir($dh)))
225                                 if (is_file($filename) && !in_array($filename, $exclude))
226                                         $file_array[filemtime($filename)] = $filename;
227                 ksort($file_array);
228                 $file_array = array_reverse($file_array, true);
229                 return $file_array;
230         }
231
232 ?>
233 <html lang="en-GB">
234         <head>
235                 <meta charset="utf-8">
236                 <title><?=$settings['title']?></title>
237                 <style media="screen">
238                         body {
239                                 background: #111;
240                                 margin: 0;
241                                 color: #ddd;
242                                 font-family: sans-serif;
243                         }
244
245                         body > h1 {
246                                 display: block;
247                                 background: rgba(255, 255, 255, 0.05);
248                                 padding: 8px 16px;
249                                 text-align: center;
250                                 margin: 0;
251                         }
252
253                         body > form {
254                                 display: block;
255                                 background: rgba(255, 255, 255, 0.075);
256                                 padding: 16px 16px;
257                                 margin: 0;
258                                 text-align: center;
259                         }
260
261                         body > ul {
262                                 display: block;
263                                 padding: 0;
264                                 max-width: 1000px;
265                                 margin: 32px auto;
266                         }
267
268                         body > ul > li {
269                                 display: block;
270                                 margin: 0;
271                                 padding: 0;
272                         }
273
274                         body > ul > li > a {
275                                 display: block;
276                                 margin: 0 0 1px 0;
277                                 list-style: none;
278                                 background: rgba(255, 255, 255, 0.1);
279                                 padding: 8px 16px;
280                                 text-decoration: none;
281                                 color: inherit;
282                                 opacity: 0.5;
283                         }
284
285                         body > ul > li > a:hover {
286                                 opacity: 1;
287                         }
288
289                         body > ul > li > a:active {
290                                 opacity: 0.5;
291                         }
292
293                         body > ul > li > a > span {
294                                 float: right;
295                                 font-size: 90%;
296                         }
297
298                         body > ul > li > form {
299                                 display: inline-block;
300                                 padding: 0;
301                                 margin: 0;
302                         }
303
304                         body > ul > li.owned {
305                                 margin: 8px;
306                         }
307
308                         body > ul > li > form > button {
309                                 opacity: 0.5;
310                                 display: inline-block;
311                                 padding: 4px 16px;
312                                 margin: 0;
313                                 border: 0;
314                                 background: rgba(255, 255, 255, 0.1);
315                                 color: inherit;
316                         }
317
318                         body > ul > li > form > button:hover {
319                                 opacity: 1;
320                         }
321
322                         body > ul > li > form > button:active {
323                                 opacity: 0.5;
324                         }
325
326                         body > ul > li.uploading {
327                                 animation: upanim 2s linear 0s infinite alternate;
328                         }
329
330                         @keyframes upanim {
331                                 from {
332                                         opacity: 0.3;
333                                 }
334                                 to {
335                                         opacity: 0.8;
336                                 }
337                         }
338                 </style>
339         </head>
340         <body>
341                 <h1><?=$settings['title']?></h1>
342                 <form action="<?= $data['scriptname'] ?>" method="POST" enctype="multipart/form-data" class="dropzone" id="simpleupload-form">
343                         Maximum upload size: <?php echo $data['max_upload_size']; ?><br />
344                         <input type="file" name="file[]" multiple required id="simpleupload-input"/>
345                 </form>
346                 <?php if ($settings['listfiles']) { ?>
347                         <ul id="simpleupload-ul">
348                                 <?php
349                                         $file_array = ListFiles($settings['uploaddir'], $data['ignores']);
350                                         foreach ($file_array as $mtime => $filename) {
351                                                 $file_info = array();
352                                                 $file_owner = false;
353                                                 $file_private = $filename[0] === '.';
354
355                                                 if ($settings['listfiles_size'])
356                                                         $file_info[] = FormatSize(filesize($filename));
357
358                                                 if ($settings['listfiles_size'])
359                                                         $file_info[] = date($settings['listfiles_date_format'], $mtime);
360
361                                                 if ($settings['allow_deletion'] || $settings['allow_private'])
362                                                         if (in_array(substr($filename, 1), $_SESSION['upload_user_files']) || in_array($filename, $_SESSION['upload_user_files']))
363                                                                 $file_owner = true;
364
365                                                 $file_info = implode(', ', $file_info);
366
367                                                 if (strlen($file_info) > 0)
368                                                         $file_info = ' (' . $file_info . ')';
369
370                                                 $class = '';
371                                                 if ($file_owner)
372                                                         $class = 'owned';
373
374                                                 if (!$file_private || $file_owner) {
375                                                         echo "<li class=\"' . $class . '\">";
376
377                                                         echo "<a href=\"$filename\" target=\"_blank\">$filename<span>$file_info</span></a>";
378
379                                                         if ($file_owner) {
380                                                                 if ($settings['allow_deletion'])
381                                                                         echo '<form action="' . $data['scriptname'] . '" method="POST"><input type="hidden" name="target" value="' . $filename . '" /><input type="hidden" name="action" value="delete" /><button type="submit">delete</button></form>';
382
383                                                                 if ($settings['allow_private'])
384                                                                         if ($file_private)
385                                                                                 echo '<form action="' . $data['scriptname'] . '" method="POST"><input type="hidden" name="target" value="' . $filename . '" /><input type="hidden" name="action" value="privatetoggle" /><button type="submit">make public</button></form>';
386                                                                         else
387                                                                                 echo '<form action="' . $data['scriptname'] . '" method="POST"><input type="hidden" name="target" value="' . $filename . '" /><input type="hidden" name="action" value="privatetoggle" /><button type="submit">make private</button></form>';
388                                                         }
389
390                                                         echo "</li>";
391                                                 }
392                                         }
393                                 ?>
394                         </ul>
395                 <?php } ?>
396                 <a href="https://github.com/muchweb/simple-php-upload"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"></a>
397                 <script charset="utf-8">
398                         var target_form = document.getElementById('simpleupload-form'),
399                                 target_ul = document.getElementById('simpleupload-ul'),
400                                 target_input = document.getElementById('simpleupload-input');
401
402                         target_form.addEventListener('dragover', function (event) {
403                                 event.preventDefault();
404                         }, false);
405
406                         function AddFileLi (name, info) {
407                                 target_form.style.display = 'none';
408
409                                 var new_li = document.createElement('li');
410                                 new_li.className = 'uploading';
411
412                                 var new_a = document.createElement('a');
413                                 new_a.innerHTML = name;
414                                 new_li.appendChild(new_a);
415
416                                 var new_span = document.createElement('span');
417                                 new_span.innerHTML = info;
418                                 new_a.appendChild(new_span);
419
420                                 target_ul.insertBefore(new_li, target_ul.firstChild);
421                         }
422
423                         function HandleFiles (event) {
424                                 event.preventDefault();
425
426                                 var i = 0,
427                                         files = event.dataTransfer.files,
428                                         len = files.length;
429
430                                 var form = new FormData();
431
432                                 for (; i < len; i++) {
433                                         form.append('file[]', files[i]);
434                                         AddFileLi(files[i].name, files[i].size + ' bytes');
435                                 }
436
437                                 var xhr = new XMLHttpRequest();
438                                 xhr.onload = function() {
439                                         window.location.reload();
440                                 };
441
442                                 xhr.open('post', '<?php echo $data['scriptname']; ?>', true);
443                                 xhr.send(form);
444                         }
445
446                         target_form.addEventListener('drop', HandleFiles, false);
447
448                         document.getElementById('simpleupload-input').onchange = function () {
449                                 AddFileLi('Uploading...', '');
450                                 target_form.submit();
451                         };
452                 </script>
453         </body>
454 </html>