Introduced isReadableFile() which encapsulates checking if the given file
[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                 // Default 30 days
61                 'time_limit' => 60 * 60 * 24 * 30,
62
63                 // Files that will be ignored
64                 'ignores' => array('.', '..', 'LICENSE', 'README.md'),
65
66                 // Language code
67                 'lang' => 'en',
68
69                 // Language direction
70                 'lang_dir' => 'ltr',
71
72                 // Remove old files?
73                 'remove_old_files' => true,
74         );
75         // =============={ Configuration End }==============
76
77         // Is the local config file there?
78         if (isReadableFile('config-local.php')) {
79                 // Load it then
80                 include('config-local.php');
81         }
82
83         // Enabling error reporting
84         if ($settings['debug']) {
85                 error_reporting(E_ALL);
86                 ini_set('display_startup_errors',1);
87                 ini_set('display_errors',1);
88         }
89
90         $data = array();
91
92         // Name of this file
93         $data['scriptname'] = pathinfo(__FILE__, PATHINFO_BASENAME);
94
95         // Adding current script name to ignore list
96         $data['ignores'] = $settings['ignores'];
97         $data['ignores'][] = $data['scriptname'];
98
99         // Use canonized path
100         $data['uploaddir'] = realpath(dirname(__FILE__) . DIRECTORY_SEPARATOR . $settings['uploaddir']);
101
102         // Maximum upload size, set by system
103         $data['max_upload_size'] = ini_get('upload_max_filesize');
104
105         // If file deletion or private files are allowed, starting a session.
106         // This is required for user authentification
107         if ($settings['allow_deletion'] || $settings['allow_private']) {
108                 session_start();
109
110                 // 'User ID'
111                 if (!isset($_SESSION['upload_user_id']))
112                         $_SESSION['upload_user_id'] = mt_rand(100000, 999999);
113
114                 // List of filenames that were uploaded by this user
115                 if (!isset($_SESSION['upload_user_files']))
116                         $_SESSION['upload_user_files'] = array();
117         }
118
119         // If debug is enabled, logging all variables
120         if ($settings['debug']) {
121                 // Displaying debug information
122                 echo '<h2>Settings:</h2>';
123                 echo '<pre>';
124                 print_r($settings);
125                 echo '</pre>';
126
127                 // Displaying debug information
128                 echo '<h2>Data:</h2>';
129                 echo '<pre>';
130                 print_r($data);
131                 echo '</pre>';
132                 echo '</pre>';
133
134                 // Displaying debug information
135                 echo '<h2>SESSION:</h2>';
136                 echo '<pre>';
137                 print_r($_SESSION);
138                 echo '</pre>';
139         }
140
141         // Format file size
142         function formatSize ($bytes) {
143                 $units = array('B', 'KB', 'MB', 'GB', 'TB');
144
145                 $bytes = max($bytes, 0);
146                 $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
147                 $pow = min($pow, count($units) - 1);
148
149                 $bytes /= pow(1024, $pow);
150
151                 return ceil($bytes) . ' ' . $units[$pow];
152         }
153
154         // Rotating a two-dimensional array
155         function diverseArray ($vector) {
156                 $result = array();
157                 foreach ($vector as $key1 => $value1)
158                         foreach ($value1 as $key2 => $value2)
159                                 $result[$key2][$key1] = $value2;
160                 return $result;
161         }
162
163         // Handling file upload
164         function uploadFile ($file_data) {
165                 global $settings, $data;
166
167                 $file_data['uploaded_file_name'] = basename($file_data['name']);
168                 $file_data['target_file_name'] = $file_data['uploaded_file_name'];
169
170                 // Generating random file name
171                 if ($settings['random_name_len'] !== false) {
172                         do {
173                                 $file_data['target_file_name'] = '';
174                                 while (strlen($file_data['target_file_name']) < $settings['random_name_len'])
175                                         $file_data['target_file_name'] .= $settings['random_name_alphabet'][mt_rand(0, strlen($settings['random_name_alphabet']) - 1)];
176                                 if ($settings['random_name_keep_type'])
177                                         $file_data['target_file_name'] .= '.' . pathinfo($file_data['uploaded_file_name'], PATHINFO_EXTENSION);
178                         } while (isReadableFile($file_data['target_file_name']));
179                 }
180                 $file_data['upload_target_file'] = $data['uploaddir'] . DIRECTORY_SEPARATOR . $file_data['target_file_name'];
181
182                 // Do now allow to overwriting files
183                 if (isReadableFile($file_data['upload_target_file'])) {
184                         echo 'File name already exists' . "\n";
185                         return;
186                 }
187
188                 // Moving uploaded file OK
189                 if (move_uploaded_file($file_data['tmp_name'], $file_data['upload_target_file'])) {
190                         if ($settings['allow_deletion'] || $settings['allow_private'])
191                                 $_SESSION['upload_user_files'][] = $file_data['target_file_name'];
192                         echo $settings['url'] .  $file_data['target_file_name'] . "\n";
193                 } else {
194                         echo 'Error: unable to upload the file.';
195                 }
196         }
197
198         // Delete file
199         function deleteFile ($file) {
200                 global $data;
201
202                 if (in_array(substr($file, 1), $_SESSION['upload_user_files']) || in_array($file, $_SESSION['upload_user_files'])) {
203                         $fqfn = $data['uploaddir'] . DIRECTORY_SEPARATOR . $file;
204                         if (!in_array($file, $data['ignores']) && isReadableFile($fqfn)) {
205                                 unlink($fqfn);
206                                 echo 'File has been removed';
207                                 exit;
208                         }
209                 }
210         }
211
212         // Mark/unmark file as hidden
213         function markUnmarkHidden ($file) {
214                 global $data;
215
216                 if (in_array(substr($file, 1), $_SESSION['upload_user_files']) || in_array($file, $_SESSION['upload_user_files'])) {
217                         $fqfn = $data['uploaddir'] . DIRECTORY_SEPARATOR . $file;
218                         if (!in_array($file, $data['ignores']) && isReadableFile($fqfn)) {
219                                 if (substr($file, 0, 1) === '.') {
220                                         rename($fqfn, substr($fqfn, 1));
221                                         echo 'File has been made visible';
222                                 } else {
223                                         rename($fqfn, $data['uploaddir'] . DIRECTORY_SEPARATOR . '.' . $file);
224                                         echo 'File has been hidden';
225                                 }
226                                 exit;
227                         }
228                 }
229         }
230
231         // Checks if the given file is a file and is readable
232         function isReadableFile ($file) {
233                 return (is_file($file) && is_readable($file));
234         }
235
236         // Files are being POSEed. Uploading them one by one.
237         if (isset($_FILES['file'])) {
238                 header('Content-type: text/plain');
239                 if (is_array($_FILES['file'])) {
240                         $file_array = diverseArray($_FILES['file']);
241                         foreach ($file_array as $file_data)
242                                 uploadFile($file_data);
243                 } else
244                         uploadFile($_FILES['file']);
245                 exit;
246         }
247
248         // Other file functions (delete, private).
249         if (isset($_POST)) {
250                 if ($settings['allow_deletion'] && (isset($_POST['target'])) && isset($_POST['action']) && $_POST['action'] === 'delete')
251                         deleteFile($_POST['target']);
252
253                 if ($settings['allow_private'] && (isset($_POST['target'])) && isset($_POST['action']) && $_POST['action'] === 'privatetoggle')
254                         markUnmarkHidden($_POST['target']);
255         }
256
257         // List files in a given directory, excluding certain files
258         function createArrayFromPath ($dir) {
259                 global $data;
260
261                 $file_array = array();
262                 $dh = opendir($dir);
263                         while ($filename = readdir($dh)) {
264                                 $fqfn = $dir . DIRECTORY_SEPARATOR . $filename;
265                                 if (isReadableFile($fqfn) && !in_array($filename, $data['ignores']))
266                                         $file_array[filemtime($fqfn)] = $filename;
267                         }
268
269                 ksort($file_array);
270                 $file_array = array_reverse($file_array, true);
271                 return $file_array;
272         }
273
274         // Removes old files
275         function removeOldFiles ($dir) {
276                 global $file_array, $settings;
277
278                 foreach ($file_array as $file) {
279                         $fqfn = $dir . DIRECTORY_SEPARATOR . $file;
280                         if ($settings['time_limit'] < time() - filemtime($fqfn))
281                                 unlink($fqfn);
282                 }
283         }
284
285         // Only read files if the feature is enabled
286         if ($settings['listfiles']) {
287                 $file_array = createArrayFromPath($data['uploaddir']);
288
289                 // Removing old files
290                 if ($settings['remove_old_files'])
291                         removeOldFiles($data['uploaddir']);
292
293                 $file_array = createArrayFromPath($data['uploaddir']);
294         }
295 ?>
296 <!DOCTYPE html>
297 <html lang="<?=$settings['lang']?>" dir="<?=$settings['lang_dir']?>">
298         <head>
299                 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
300                 <meta http-equiv="Content-Script-Type" content="text/javascript">
301                 <meta name="robots" content="noindex">
302                 <meta name="referrer" content="origin-when-crossorigin">
303                 <title><?=$settings['title']?></title>
304                 <style media="screen">
305                 <!--
306                         body {
307                                 background: #111;
308                                 margin: 0;
309                                 color: #ddd;
310                                 font-family: sans-serif;
311                         }
312
313                         body > h1 {
314                                 display: block;
315                                 background: rgba(255, 255, 255, 0.05);
316                                 padding: 8px 16px;
317                                 text-align: center;
318                                 margin: 0;
319                         }
320
321                         body > form {
322                                 display: block;
323                                 background: rgba(255, 255, 255, 0.075);
324                                 padding: 16px 16px;
325                                 margin: 0;
326                                 text-align: center;
327                         }
328
329                         body > ul {
330                                 display: block;
331                                 padding: 0;
332                                 max-width: 1000px;
333                                 margin: 32px auto;
334                         }
335
336                         body > ul > li {
337                                 display: block;
338                                 margin: 0;
339                                 padding: 0;
340                         }
341
342                         body > ul > li > a {
343                                 display: block;
344                                 margin: 0 0 1px 0;
345                                 list-style: none;
346                                 background: rgba(255, 255, 255, 0.1);
347                                 padding: 8px 16px;
348                                 text-decoration: none;
349                                 color: inherit;
350                                 opacity: 0.5;
351                         }
352
353                         body > ul > li > a:hover {
354                                 opacity: 1;
355                         }
356
357                         body > ul > li > a:active {
358                                 opacity: 0.5;
359                         }
360
361                         body > ul > li > a > span {
362                                 float: right;
363                                 font-size: 90%;
364                         }
365
366                         body > ul > li > form {
367                                 display: inline-block;
368                                 padding: 0;
369                                 margin: 0;
370                         }
371
372                         body > ul > li.owned {
373                                 margin: 8px;
374                         }
375
376                         body > ul > li > form > button {
377                                 opacity: 0.5;
378                                 display: inline-block;
379                                 padding: 4px 16px;
380                                 margin: 0;
381                                 border: 0;
382                                 background: rgba(255, 255, 255, 0.1);
383                                 color: inherit;
384                         }
385
386                         body > ul > li > form > button:hover {
387                                 opacity: 1;
388                         }
389
390                         body > ul > li > form > button:active {
391                                 opacity: 0.5;
392                         }
393
394                         body > ul > li.uploading {
395                                 animation: upanim 2s linear 0s infinite alternate;
396                         }
397
398                         @keyframes upanim {
399                                 from {
400                                         opacity: 0.3;
401                                 }
402                                 to {
403                                         opacity: 0.8;
404                                 }
405                         }
406                 //-->
407                 </style>
408         </head>
409         <body>
410                 <h1><?=$settings['title']?></h1>
411                 <form action="<?= $data['scriptname'] ?>" method="POST" enctype="multipart/form-data" class="dropzone" id="simpleupload-form">
412                         Maximum upload size: <?php echo $data['max_upload_size']; ?><br />
413                         <input type="file" name="file[]" multiple required id="simpleupload-input"/>
414                 </form>
415                 <?php if ($settings['listfiles']) { ?>
416                         <ul id="simpleupload-ul">
417                                 <?php
418                                         foreach ($file_array as $mtime => $filename) {
419                                                 $fqfn = $data['uploaddir'] . DIRECTORY_SEPARATOR . $filename;
420                                                 $file_info = array();
421                                                 $file_owner = false;
422                                                 $file_private = $filename[0] === '.';
423
424                                                 if ($settings['listfiles_size'])
425                                                         $file_info[] = formatSize(filesize($fqfn));
426
427                                                 if ($settings['listfiles_size'])
428                                                         $file_info[] = date($settings['listfiles_date_format'], $mtime);
429
430                                                 if ($settings['allow_deletion'] || $settings['allow_private'])
431                                                         if (in_array(substr($filename, 1), $_SESSION['upload_user_files']) || in_array($filename, $_SESSION['upload_user_files']))
432                                                                 $file_owner = true;
433
434                                                 $file_info = implode(', ', $file_info);
435
436                                                 if (strlen($file_info) > 0)
437                                                         $file_info = ' (' . $file_info . ')';
438
439                                                 $class = '';
440                                                 if ($file_owner)
441                                                         $class = 'owned';
442
443                                                 if (!$file_private || $file_owner) {
444                                                         echo "<li class=\"' . $class . '\">";
445
446                                                         $url = str_replace('/./', '/', sprintf('%s%s/%s', $settings['url'], $settings['uploaddir'], $filename));
447
448                                                         echo "<a href=\"$url\" target=\"_blank\">$filename<span>$file_info</span></a>";
449
450                                                         if ($file_owner) {
451                                                                 if ($settings['allow_deletion'])
452                                                                         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>';
453
454                                                                 if ($settings['allow_private'])
455                                                                         if ($file_private)
456                                                                                 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>';
457                                                                         else
458                                                                                 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>';
459                                                         }
460
461                                                         echo "</li>";
462                                                 }
463                                         }
464                                 ?>
465                         </ul>
466                 <?php } ?>
467                 <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>
468                 <script type="text/javascript">
469                 <!--
470                         var target_form = document.getElementById('simpleupload-form'),
471                                 target_ul = document.getElementById('simpleupload-ul'),
472                                 target_input = document.getElementById('simpleupload-input');
473
474                         target_form.addEventListener('dragover', function (event) {
475                                 event.preventDefault();
476                         }, false);
477
478                         function AddFileLi (name, info) {
479                                 target_form.style.display = 'none';
480
481                                 var new_li = document.createElement('li');
482                                 new_li.className = 'uploading';
483
484                                 var new_a = document.createElement('a');
485                                 new_a.innerHTML = name;
486                                 new_li.appendChild(new_a);
487
488                                 var new_span = document.createElement('span');
489                                 new_span.innerHTML = info;
490                                 new_a.appendChild(new_span);
491
492                                 target_ul.insertBefore(new_li, target_ul.firstChild);
493                         }
494
495                         function HandleFiles (event) {
496                                 event.preventDefault();
497
498                                 var i = 0,
499                                         files = event.dataTransfer.files,
500                                         len = files.length;
501
502                                 var form = new FormData();
503
504                                 for (; i < len; i++) {
505                                         form.append('file[]', files[i]);
506                                         AddFileLi(files[i].name, files[i].size + ' bytes');
507                                 }
508
509                                 var xhr = new XMLHttpRequest();
510                                 xhr.onload = function() {
511                                         window.location.reload();
512                                 };
513
514                                 xhr.open('post', '<?php echo $data['scriptname']; ?>', true);
515                                 xhr.send(form);
516                         }
517
518                         target_form.addEventListener('drop', HandleFiles, false);
519
520                         document.getElementById('simpleupload-input').onchange = function () {
521                                 AddFileLi('Uploading...', '');
522                                 target_form.submit();
523                         };
524                 //-->
525                 </script>
526         </body>
527 </html>