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