Return file name or FALSE on error.
[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'] = $settings['url'] . '/' . pathinfo(__FILE__, PATHINFO_BASENAME);
97
98         // Adding current script name to ignore list
99         $data['ignores'] = $settings['ignores'];
100         $data['ignores'][] = basename($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 false;
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
197                         // Return target file name for later handling
198                         return $file_data['upload_target_file'];
199                 } else {
200                         echo 'Error: unable to upload the file.';
201                         return false;
202                 }
203         }
204
205         // Delete file
206         function deleteFile ($file) {
207                 global $data;
208
209                 if (in_array(substr($file, 1), $_SESSION['upload_user_files']) || in_array($file, $_SESSION['upload_user_files'])) {
210                         $fqfn = $data['uploaddir'] . DIRECTORY_SEPARATOR . $file;
211                         if (!in_array($file, $data['ignores']) && isReadableFile($fqfn)) {
212                                 unlink($fqfn);
213                                 echo 'File has been removed';
214                                 exit;
215                         }
216                 }
217         }
218
219         // Mark/unmark file as hidden
220         function markUnmarkHidden ($file) {
221                 global $data;
222
223                 if (in_array(substr($file, 1), $_SESSION['upload_user_files']) || in_array($file, $_SESSION['upload_user_files'])) {
224                         $fqfn = $data['uploaddir'] . DIRECTORY_SEPARATOR . $file;
225                         if (!in_array($file, $data['ignores']) && isReadableFile($fqfn)) {
226                                 if (substr($file, 0, 1) === '.') {
227                                         rename($fqfn, substr($fqfn, 1));
228                                         echo 'File has been made visible';
229                                 } else {
230                                         rename($fqfn, $data['uploaddir'] . DIRECTORY_SEPARATOR . '.' . $file);
231                                         echo 'File has been hidden';
232                                 }
233                                 exit;
234                         }
235                 }
236         }
237
238         // Checks if the given file is a file and is readable
239         function isReadableFile ($file) {
240                 return (is_file($file) && is_readable($file));
241         }
242
243         // Files are being POSEed. Uploading them one by one.
244         if (isset($_FILES['file'])) {
245                 header('Content-type: text/plain');
246                 if (is_array($_FILES['file'])) {
247                         $file_array = diverseArray($_FILES['file']);
248                         foreach ($file_array as $file_data)
249                                 uploadFile($file_data);
250                 } else {
251                         uploadFile($_FILES['file']);
252                 }
253                 exit;
254         }
255
256         // Other file functions (delete, private).
257         if (isset($_POST)) {
258                 if ($settings['allow_deletion'] && (isset($_POST['target'])) && isset($_POST['action']) && $_POST['action'] === 'delete')
259                         deleteFile($_POST['target']);
260
261                 if ($settings['allow_private'] && (isset($_POST['target'])) && isset($_POST['action']) && $_POST['action'] === 'privatetoggle')
262                         markUnmarkHidden($_POST['target']);
263         }
264
265         // List files in a given directory, excluding certain files
266         function createArrayFromPath ($dir) {
267                 global $data;
268
269                 $file_array = array();
270
271                 $dh = opendir($dir);
272
273                 while ($filename = readdir($dh)) {
274                         $fqfn = $dir . DIRECTORY_SEPARATOR . $filename;
275                         if (isReadableFile($fqfn) && !in_array($filename, $data['ignores']))
276                                 $file_array[filemtime($fqfn)] = $filename;
277                 }
278
279                 ksort($file_array);
280
281                 $file_array = array_reverse($file_array, true);
282
283                 return $file_array;
284         }
285
286         // Removes old files
287         function removeOldFiles ($dir) {
288                 global $file_array, $settings;
289
290                 foreach ($file_array as $file) {
291                         $fqfn = $dir . DIRECTORY_SEPARATOR . $file;
292                         if ($settings['time_limit'] < time() - filemtime($fqfn))
293                                 unlink($fqfn);
294                 }
295         }
296
297         // Only read files if the feature is enabled
298         if ($settings['listfiles']) {
299                 $file_array = createArrayFromPath($data['uploaddir']);
300
301                 // Removing old files
302                 if ($settings['remove_old_files'])
303                         removeOldFiles($data['uploaddir']);
304
305                 $file_array = createArrayFromPath($data['uploaddir']);
306         }
307 ?>
308 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
309 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?=$settings['lang']?>" lang="<?=$settings['lang']?>" dir="<?=$settings['lang_dir']?>">
310         <head>
311                 <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
312                 <meta http-equiv="content-style-type" content="text/css" />
313                 <meta http-equiv="content-script-type" content="text/javascript" />
314                 <meta http-equiv="language" content="de" />
315
316                 <meta name="robots" content="noindex" />
317                 <meta name="referrer" content="origin-when-crossorigin" />
318                 <title><?=$settings['title']?></title>
319                 <style type="text/css" media="screen">
320                         body {
321                                 background: #111;
322                                 margin: 0;
323                                 color: #ddd;
324                                 font-family: sans-serif;
325                         }
326
327                         body > h1 {
328                                 display: block;
329                                 background: rgba(255, 255, 255, 0.05);
330                                 padding: 8px 16px;
331                                 text-align: center;
332                                 margin: 0;
333                         }
334
335                         body > form {
336                                 display: block;
337                                 background: rgba(255, 255, 255, 0.075);
338                                 padding: 16px 16px;
339                                 margin: 0;
340                                 text-align: center;
341                         }
342
343                         body > ul {
344                                 display: block;
345                                 padding: 0;
346                                 max-width: 1000px;
347                                 margin: 32px auto;
348                         }
349
350                         body > ul > li {
351                                 display: block;
352                                 margin: 0;
353                                 padding: 0;
354                         }
355
356                         body > ul > li > a {
357                                 display: block;
358                                 margin: 0 0 1px 0;
359                                 list-style: none;
360                                 background: rgba(255, 255, 255, 0.1);
361                                 padding: 8px 16px;
362                                 text-decoration: none;
363                                 color: inherit;
364                                 opacity: 0.5;
365                         }
366
367                         body > ul > li > a:hover {
368                                 opacity: 1;
369                         }
370
371                         body > ul > li > a:active {
372                                 opacity: 0.5;
373                         }
374
375                         body > ul > li > a > span {
376                                 float: right;
377                                 font-size: 90%;
378                         }
379
380                         body > ul > li > form {
381                                 display: inline-block;
382                                 padding: 0;
383                                 margin: 0;
384                         }
385
386                         body > ul > li.owned {
387                                 margin: 8px;
388                         }
389
390                         body > ul > li > form > button {
391                                 opacity: 0.5;
392                                 display: inline-block;
393                                 padding: 4px 16px;
394                                 margin: 0;
395                                 border: 0;
396                                 background: rgba(255, 255, 255, 0.1);
397                                 color: inherit;
398                         }
399
400                         body > ul > li > form > button:hover {
401                                 opacity: 1;
402                         }
403
404                         body > ul > li > form > button:active {
405                                 opacity: 0.5;
406                         }
407
408                         body > ul > li.uploading {
409                                 animation: upanim 2s linear 0s infinite alternate;
410                         }
411
412                         @keyframes upanim {
413                                 from {
414                                         opacity: 0.3;
415                                 }
416                                 to {
417                                         opacity: 0.8;
418                                 }
419                         }
420                 </style>
421         </head>
422         <body>
423                 <h1><?=$settings['title']?></h1>
424                 <form action="<?= $data['scriptname'] ?>" method="post" enctype="multipart/form-data" class="dropzone" id="simpleupload-form">
425                         Maximum upload size: <?php echo $data['max_upload_size']; ?><br />
426                         <input type="file" name="file[]" id="simpleupload-input" />
427                 </form>
428                 <?php if ($settings['listfiles']) { ?>
429                         <ul id="simpleupload-ul">
430                                 <?php
431                                         foreach ($file_array as $mtime => $filename) {
432                                                 $fqfn = $data['uploaddir'] . DIRECTORY_SEPARATOR . $filename;
433                                                 $file_info = array();
434                                                 $file_owner = false;
435                                                 $file_private = $filename[0] === '.';
436
437                                                 if ($settings['listfiles_size'])
438                                                         $file_info[] = formatSize(filesize($fqfn));
439
440                                                 if ($settings['listfiles_size'])
441                                                         $file_info[] = date($settings['listfiles_date_format'], $mtime);
442
443                                                 if ($settings['allow_deletion'] || $settings['allow_private'])
444                                                         if (in_array(substr($filename, 1), $_SESSION['upload_user_files']) || in_array($filename, $_SESSION['upload_user_files']))
445                                                                 $file_owner = true;
446
447                                                 $file_info = implode(', ', $file_info);
448
449                                                 if (strlen($file_info) > 0)
450                                                         $file_info = ' (' . $file_info . ')';
451
452                                                 $class = '';
453                                                 if ($file_owner)
454                                                         $class = 'owned';
455
456                                                 if (!$file_private || $file_owner) {
457                                                         echo "<li class=\"' . $class . '\">";
458
459                                                         // Create full-qualified URL and clean it a bit
460                                                         $url = str_replace('/./', '/', sprintf('%s%s/%s', $settings['url'], $settings['uploaddir'], $filename));
461
462                                                         echo "<a href=\"$url\" target=\"_blank\">$filename<span>$file_info</span></a>";
463
464                                                         if ($file_owner) {
465                                                                 if ($settings['allow_deletion'])
466                                                                         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>';
467
468                                                                 if ($settings['allow_private'])
469                                                                         if ($file_private)
470                                                                                 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>';
471                                                                         else
472                                                                                 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>';
473                                                         }
474
475                                                         echo "</li>";
476                                                 }
477                                         }
478                                 ?>
479                         </ul>
480                 <?php
481                 }
482
483                 if ($settings['allow_external_refs']) {
484                 ?>
485                         <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>
486                 <?php
487                 } else {
488                 ?>
489                         <a href="https://github.com/muchweb/simple-php-upload" target="_blank">Fork me on GitHub</a>
490                 <?php
491                 }
492                 ?>
493                 <script type="text/javascript">
494                 <!--
495                         // Init some variales to shorten code
496                         var target_form        = document.getElementById('simpleupload-form');
497                         var target_ul          = document.getElementById('simpleupload-ul');
498                         var target_input       = document.getElementById('simpleupload-input');
499                         var settings_listfiles = <?=($settings['listfiles'] ? 'true' : 'false')?>;
500
501                         /**
502                          * Initializes the upload form
503                          */
504                         function init () {
505                                 // Register drag-over event listener
506                                 target_form.addEventListener('dragover', function (event) {
507                                         event.preventDefault();
508                                 }, false);
509
510                                 // ... and the drop event listener
511                                 target_form.addEventListener('drop', handleFiles, false);
512
513                                 // Register onchange-event function
514                                 target_input.onchange = function () {
515                                         addFileLi('Uploading...', '');
516                                         target_form.submit();
517                                 };
518                         }
519
520                         /**
521                          * Adds given file in a new li-tag to target_ul list
522                          *
523                          * @param name Name of the file
524                          * @param info Some more informations
525                          */
526                         function addFileLi (name, info) {
527                                 if (settings_listfiles == false) {
528                                         return;
529                                 }
530
531                                 target_form.style.display = 'none';
532
533                                 var new_li = document.createElement('li');
534                                 new_li.className = 'uploading';
535
536                                 var new_a = document.createElement('a');
537                                 new_a.innerHTML = name;
538                                 new_li.appendChild(new_a);
539
540                                 var new_span = document.createElement('span');
541                                 new_span.innerHTML = info;
542                                 new_a.appendChild(new_span);
543
544                                 target_ul.insertBefore(new_li, target_ul.firstChild);
545                         }
546
547                         /**
548                          * Handles given event for file upload
549                          *
550                          * @param event Event to handle file upload for
551                          */
552                         function handleFiles (event) {
553                                 event.preventDefault();
554
555                                 var files = event.dataTransfer.files;
556
557                                 var form = new FormData();
558
559                                 for (var i = 0; i < files.length; i++) {
560                                         form.append('file[]', files[i]);
561                                         addFileLi(files[i].name, files[i].size + ' bytes');
562                                 }
563
564                                 var xhr = new XMLHttpRequest();
565                                 xhr.onload = function() {
566                                         window.location.reload();
567                                 };
568
569                                 xhr.open('post', '<?php echo $data['scriptname']; ?>', true);
570                                 xhr.send(form);
571                         }
572
573                         // Initialize upload form
574                         init();
575
576                 //-->
577                 </script>
578         </body>
579 </html>