Renaming (hide/unhide) of files rewritten so failures can be caught.
[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                 // Description for this website
24                 'description' => '',
25
26                 // Base path (auto-detection)
27                 'base_path' => dirname(__FILE__) . DIRECTORY_SEPARATOR,
28
29                 // Directory to store uploaded files (relative to base_path)
30                 'uploaddir' => '.',
31
32                 // Display list uploaded files
33                 'listfiles' => true,
34
35                 // Allow users to delete files that they have uploaded (will enable sessions)
36                 'allow_deletion' => true,
37
38                 // Allow users to mark files as hidden
39                 'allow_private' => true,
40
41                 // Display file sizes
42                 'listfiles_size' => true,
43
44                 // Display file dates
45                 'listfiles_date' => true,
46
47                 // Display file dates format
48                 'listfiles_date_format' => 'F d Y H:i:s',
49
50                 // Randomize file names (number of 'false')
51                 'random_name_len' => 8,
52
53                 // Keep filetype information (if random name is activated)
54                 'random_name_keep_type' => true,
55
56                 // Random file name letters
57                 'random_name_alphabet' => 'qazwsxedcrfvtgbyhnujmikolp1234567890',
58
59                 // Add original name (but cleaned) to file name if random file name feature is enabled?
60                 'suffix_original_name' => false,
61
62                 // Display debugging information
63                 'debug' => false,
64
65                 // Complete URL to your directory (including tracing slash, leave for auto-detection)
66                 'url' => detectServerUrl(),
67
68                 // Amount of seconds that each file should be stored for (0 for no limit)
69                 // Default 30 days
70                 'time_limit' => 60 * 60 * 24 * 30,
71
72                 // Files that will be ignored
73                 'ignores' => array('.', '..', 'LICENSE', 'README.md'),
74
75                 // Language code
76                 'lang' => 'en',
77
78                 // Language direction
79                 'lang_dir' => 'ltr',
80
81                 // Remove old files?
82                 'remove_old_files' => true,
83
84                 // Privacy: Allow external references (the "fork me" ribbon)
85                 'allow_external_refs' => true,
86         );
87         // =============={ Configuration End }==============
88
89         // Is the local config file there?
90         if (isReadableFile('config-local.php')) {
91                 // Load it then
92                 include('config-local.php');
93         }
94
95         // Enabling error reporting
96         if ($settings['debug']) {
97                 error_reporting(E_ALL);
98                 ini_set('display_startup_errors',1);
99                 ini_set('display_errors',1);
100         }
101
102         $data = array();
103
104         // Name of this file
105         $data['scriptname'] = $settings['url'] . pathinfo(__FILE__, PATHINFO_BASENAME);
106
107         // Adding current script name to ignore list
108         $data['ignores'] = $settings['ignores'];
109         $data['ignores'][] = basename($data['scriptname']);
110
111         // Use canonized path
112         $data['uploaddir'] = realpath($settings['base_path'] . $settings['uploaddir']);
113
114         // Maximum upload size, set by system
115         $data['max_upload_size'] = ini_get('upload_max_filesize');
116
117         // If file deletion or private files are allowed, starting a session.
118         // This is required for user authentification
119         if ($settings['allow_deletion'] || $settings['allow_private']) {
120                 session_start();
121
122                 // 'User ID'
123                 if (!isset($_SESSION['upload_user_id']))
124                         $_SESSION['upload_user_id'] = mt_rand(100000, 999999);
125
126                 // List of filenames that were uploaded by this user
127                 if (!isset($_SESSION['upload_user_files']))
128                         $_SESSION['upload_user_files'] = array();
129         }
130
131         // If debug is enabled, logging all variables
132         if ($settings['debug']) {
133                 // Displaying debug information
134                 echo '<h2>Settings:</h2>';
135                 echo '<pre>';
136                 print_r($settings);
137                 echo '</pre>';
138
139                 // Displaying debug information
140                 echo '<h2>Data:</h2>';
141                 echo '<pre>';
142                 print_r($data);
143                 echo '</pre>';
144                 echo '</pre>';
145
146                 // Displaying debug information
147                 echo '<h2>SESSION:</h2>';
148                 echo '<pre>';
149                 print_r($_SESSION);
150                 echo '</pre>';
151         }
152
153         // Format file size
154         function formatSize ($bytes) {
155                 $units = array('B', 'KB', 'MB', 'GB', 'TB');
156
157                 $bytes = max($bytes, 0);
158                 $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
159                 $pow = min($pow, count($units) - 1);
160
161                 $bytes /= pow(1024, $pow);
162
163                 return ceil($bytes) . ' ' . $units[$pow];
164         }
165
166         // Rotating a two-dimensional array
167         function diverseArray ($vector) {
168                 $result = array();
169                 foreach ($vector as $key1 => $value1)
170                         foreach ($value1 as $key2 => $value2)
171                                 $result[$key2][$key1] = $value2;
172                 return $result;
173         }
174
175         // Handling file upload
176         function uploadFile ($file_data) {
177                 global $settings, $data;
178
179                 $file_data['uploaded_file_name'] = basename($file_data['name']);
180                 $file_data['target_file_name'] = $file_data['uploaded_file_name'];
181
182                 // Generating random file name
183                 if ($settings['random_name_len'] !== false) {
184                         do {
185                                 $file_data['target_file_name'] = '';
186                                 while (strlen($file_data['target_file_name']) < $settings['random_name_len'])
187                                         $file_data['target_file_name'] .= $settings['random_name_alphabet'][mt_rand(0, strlen($settings['random_name_alphabet']) - 1)];
188                                 if ($settings['suffix_original_name'])
189                                         $file_data['target_file_name'] .= '_' . preg_replace('/[^0-9a-zA-Z_-]/', '', pathinfo($file_data['uploaded_file_name'], PATHINFO_BASENAME));
190                                 if ($settings['random_name_keep_type'])
191                                         $file_data['target_file_name'] .= '.' . pathinfo($file_data['uploaded_file_name'], PATHINFO_EXTENSION);
192                         } while (isReadableFile($file_data['target_file_name']));
193                 }
194                 $file_data['upload_target_file'] = $data['uploaddir'] . DIRECTORY_SEPARATOR . $file_data['target_file_name'];
195
196                 // Do now allow to overwriting files
197                 if (isReadableFile($file_data['upload_target_file'])) {
198                         echo 'File name already exists' . "\n";
199                         return false;
200                 }
201
202                 // Moving uploaded file OK
203                 if (move_uploaded_file($file_data['tmp_name'], $file_data['upload_target_file'])) {
204                         if ($settings['listfiles'] && ($settings['allow_deletion'] || $settings['allow_private']))
205                                 $_SESSION['upload_user_files'][] = $file_data['target_file_name'];
206                         echo $settings['url'] .  $file_data['target_file_name'] . "\n";
207
208                         // Return target file name for later handling
209                         return $file_data['upload_target_file'];
210                 } else {
211                         echo 'Error: unable to upload the file.';
212                         return false;
213                 }
214         }
215
216         // Delete file
217         function deleteFile ($file) {
218                 global $data;
219
220                 if (in_array(substr($file, 1), $_SESSION['upload_user_files']) || in_array($file, $_SESSION['upload_user_files'])) {
221                         $fqfn = $data['uploaddir'] . DIRECTORY_SEPARATOR . $file;
222                         if (!in_array($file, $data['ignores']) && isReadableFile($fqfn)) {
223                                 unlink($fqfn);
224                                 echo 'File has been removed';
225                                 exit;
226                         }
227                 }
228         }
229
230         // Mark/unmark file as hidden
231         function markUnmarkHidden ($file) {
232                 global $data;
233
234                 if (in_array(substr($file, 1), $_SESSION['upload_user_files']) || in_array($file, $_SESSION['upload_user_files'])) {
235                         $sourceFile = $data['uploaddir'] . DIRECTORY_SEPARATOR . $file;
236                         if (!in_array($file, $data['ignores']) && isReadableFile($sourceFile)) {
237                                 if (substr($file, 0, 1) === '.') {
238                                         $targetFile = $data['uploaddir'] . DIRECTORY_SEPARATOR . substr($file, 1);
239                                         $successMessage = 'File has been made public';
240                                         $failedMessage = 'File has NOT been made public';
241                                 } else {
242                                         $targetFile = $data['uploaddir'] . DIRECTORY_SEPARATOR . '.' . $file;
243                                         $successMessage = 'File has been hidden';
244                                         $failedMessage = 'File has NOT been hidden';
245                                 }
246                                 if (rename($sourceFile, $targetFile)) {
247                                         echo $successMessage;
248                                 } else {
249                                         echo $failedMessage;
250                                 }
251                                 exit;
252                         }
253                 }
254         }
255
256         // Checks if the given file is a file and is readable
257         function isReadableFile ($file) {
258                 return (is_file($file) && is_readable($file));
259         }
260
261         // Detects full URL of installation
262         function detectServerUrl () {
263                 // Is "cache" there?
264                 if (!isset($GLOBALS[__FUNCTION__])) {
265                         // Default protocol is HTTP
266                         $protocol = 'http';
267
268                         // Is SSL given?
269                         if (((isset($_SERVER['HTTPS'])) && (strtolower($_SERVER['HTTPS']) == 'on')) || ((isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) && (strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https'))) {
270                                 // Protocol is HTTPS
271                                 $protocol = 'https';
272                         } // END - if
273
274                         // Construct full URL
275                         $GLOBALS[__FUNCTION__] = str_replace("\\", '', sprintf('%s://%s%s/', $protocol, $_SERVER['SERVER_NAME'], dirname($_SERVER['SCRIPT_NAME'])));
276                 } // END - if
277
278                 // Return cached value
279                 return $GLOBALS[__FUNCTION__];
280         }
281
282         // Files are being POSEed. Uploading them one by one.
283         if (isset($_FILES['file'])) {
284                 header('Content-type: text/plain');
285                 if (is_array($_FILES['file'])) {
286                         $file_array = diverseArray($_FILES['file']);
287                         foreach ($file_array as $file_data) {
288                                 $targetFile = uploadFile($file_data);
289                         }
290                 } else {
291                         $targetFile = uploadFile($_FILES['file']);
292                 }
293                 exit;
294         }
295
296         // Other file functions (delete, private).
297         if (isset($_POST)) {
298                 if ($settings['allow_deletion'] && (isset($_POST['target'])) && isset($_POST['action']) && $_POST['action'] === 'delete')
299                         deleteFile($_POST['target']);
300
301                 if ($settings['allow_private'] && (isset($_POST['target'])) && isset($_POST['action']) && $_POST['action'] === 'privatetoggle')
302                         markUnmarkHidden($_POST['target']);
303         }
304
305         // List files in a given directory, excluding certain files
306         function createArrayFromPath ($dir) {
307                 global $data;
308
309                 $file_array = array();
310
311                 $dh = opendir($dir);
312
313                 while ($filename = readdir($dh)) {
314                         $fqfn = $dir . DIRECTORY_SEPARATOR . $filename;
315                         if (isReadableFile($fqfn) && !in_array($filename, $data['ignores']))
316                                 $file_array[filemtime($fqfn)] = $filename;
317                 }
318
319                 ksort($file_array);
320
321                 $file_array = array_reverse($file_array, true);
322
323                 return $file_array;
324         }
325
326         // Removes old files
327         function removeOldFiles ($dir) {
328                 global $file_array, $settings;
329
330                 foreach ($file_array as $file) {
331                         $fqfn = $dir . DIRECTORY_SEPARATOR . $file;
332                         if ($settings['time_limit'] < time() - filemtime($fqfn))
333                                 unlink($fqfn);
334                 }
335         }
336
337         // Only read files if the feature is enabled
338         if ($settings['listfiles']) {
339                 $file_array = createArrayFromPath($data['uploaddir']);
340
341                 // Removing old files
342                 if ($settings['remove_old_files'])
343                         removeOldFiles($data['uploaddir']);
344
345                 $file_array = createArrayFromPath($data['uploaddir']);
346         }
347 ?>
348 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
349 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?=$settings['lang']?>" lang="<?=$settings['lang']?>" dir="<?=$settings['lang_dir']?>">
350         <head>
351                 <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
352                 <meta http-equiv="content-style-type" content="text/css" />
353                 <meta http-equiv="content-script-type" content="text/javascript" />
354                 <meta http-equiv="language" content="de" />
355
356                 <meta name="robots" content="noindex" />
357                 <meta name="referrer" content="origin-when-crossorigin" />
358                 <title><?=$settings['title']?></title>
359                 <style type="text/css" media="screen">
360                         body {
361                                 background: #111;
362                                 margin: 0;
363                                 color: #ddd;
364                                 font-family: sans-serif;
365                         }
366
367                         body > h1 {
368                                 display: block;
369                                 background: rgba(255, 255, 255, 0.05);
370                                 padding: 8px 16px;
371                                 text-align: center;
372                                 margin: 0;
373                         }
374
375                         body > form {
376                                 display: block;
377                                 background: rgba(255, 255, 255, 0.075);
378                                 padding: 16px 16px;
379                                 margin: 0;
380                                 text-align: center;
381                         }
382
383                         body > ul {
384                                 display: block;
385                                 padding: 0;
386                                 max-width: 1000px;
387                                 margin: 32px auto;
388                         }
389
390                         body > ul > li {
391                                 display: block;
392                                 margin: 0;
393                                 padding: 0;
394                         }
395
396                         body > ul > li > a {
397                                 display: block;
398                                 margin: 0 0 1px 0;
399                                 list-style: none;
400                                 background: rgba(255, 255, 255, 0.1);
401                                 padding: 8px 16px;
402                                 text-decoration: none;
403                                 color: inherit;
404                                 opacity: 0.5;
405                         }
406
407                         body > ul > li > a:hover {
408                                 opacity: 1;
409                         }
410
411                         body > ul > li > a:active {
412                                 opacity: 0.5;
413                         }
414
415                         body > ul > li > a > span {
416                                 float: right;
417                                 font-size: 90%;
418                         }
419
420                         body > ul > li > form {
421                                 display: inline-block;
422                                 padding: 0;
423                                 margin: 0;
424                         }
425
426                         body > ul > li.owned {
427                                 margin: 8px;
428                         }
429
430                         body > ul > li > form > button {
431                                 opacity: 0.5;
432                                 display: inline-block;
433                                 padding: 4px 16px;
434                                 margin: 0;
435                                 border: 0;
436                                 background: rgba(255, 255, 255, 0.1);
437                                 color: inherit;
438                         }
439
440                         body > ul > li > form > button:hover {
441                                 opacity: 1;
442                         }
443
444                         body > ul > li > form > button:active {
445                                 opacity: 0.5;
446                         }
447
448                         body > ul > li.uploading {
449                                 animation: upanim 2s linear 0s infinite alternate;
450                         }
451
452                         @keyframes upanim {
453                                 from {
454                                         opacity: 0.3;
455                                 }
456                                 to {
457                                         opacity: 0.8;
458                                 }
459                         }
460                 </style>
461         </head>
462         <body>
463                 <h1><?=$settings['title']?></h1>
464                 <p><?=$settings['description']?></p>
465                 <form action="<?= $data['scriptname'] ?>" method="post" enctype="multipart/form-data" class="dropzone" id="simpleupload-form">
466                         Maximum upload size: <?php echo $data['max_upload_size']; ?><br />
467                         <input type="file" name="file[]" id="simpleupload-input" />
468                 </form>
469                 <?php if ($settings['listfiles']) { ?>
470                         <ul id="simpleupload-ul">
471                                 <?php
472                                         foreach ($file_array as $mtime => $filename) {
473                                                 $fqfn = $data['uploaddir'] . DIRECTORY_SEPARATOR . $filename;
474                                                 $file_info = array();
475                                                 $file_owner = false;
476                                                 $file_private = $filename[0] === '.';
477
478                                                 if ($settings['listfiles_size'])
479                                                         $file_info[] = formatSize(filesize($fqfn));
480
481                                                 if ($settings['listfiles_size'])
482                                                         $file_info[] = date($settings['listfiles_date_format'], $mtime);
483
484                                                 if ($settings['allow_deletion'] || $settings['allow_private'])
485                                                         if (in_array(substr($filename, 1), $_SESSION['upload_user_files']) || in_array($filename, $_SESSION['upload_user_files']))
486                                                                 $file_owner = true;
487
488                                                 $file_info = implode(', ', $file_info);
489
490                                                 if (strlen($file_info) > 0)
491                                                         $file_info = ' (' . $file_info . ')';
492
493                                                 $class = '';
494                                                 if ($file_owner)
495                                                         $class = 'owned';
496
497                                                 if (!$file_private || $file_owner) {
498                                                         echo "<li class=\"' . $class . '\">";
499
500                                                         // Create full-qualified URL and clean it a bit
501                                                         $url = str_replace('/./', '/', sprintf('%s%s/%s', $settings['url'], $settings['uploaddir'], $filename));
502
503                                                         echo "<a href=\"$url\" target=\"_blank\">$filename<span>$file_info</span></a>";
504
505                                                         if ($file_owner) {
506                                                                 if ($settings['allow_deletion'])
507                                                                         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>';
508
509                                                                 if ($settings['allow_private'])
510                                                                         if ($file_private)
511                                                                                 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>';
512                                                                         else
513                                                                                 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>';
514                                                         }
515
516                                                         echo "</li>";
517                                                 }
518                                         }
519                                 ?>
520                         </ul>
521                 <?php
522                 }
523
524                 if ($settings['allow_external_refs']) {
525                 ?>
526                         <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>
527                 <?php
528                 } else {
529                 ?>
530                         <a href="https://github.com/muchweb/simple-php-upload" target="_blank">Fork me on GitHub</a>
531                 <?php
532                 }
533                 ?>
534                 <script type="text/javascript">
535                 <!--
536                         // Init some variales to shorten code
537                         var target_form        = document.getElementById('simpleupload-form');
538                         var target_ul          = document.getElementById('simpleupload-ul');
539                         var target_input       = document.getElementById('simpleupload-input');
540                         var settings_listfiles = <?=($settings['listfiles'] ? 'true' : 'false')?>;
541
542                         /**
543                          * Initializes the upload form
544                          */
545                         function init () {
546                                 // Register drag-over event listener
547                                 target_form.addEventListener('dragover', function (event) {
548                                         event.preventDefault();
549                                 }, false);
550
551                                 // ... and the drop event listener
552                                 target_form.addEventListener('drop', handleFiles, false);
553
554                                 // Register onchange-event function
555                                 target_input.onchange = function () {
556                                         addFileLi('Uploading...', '');
557                                         target_form.submit();
558                                 };
559                         }
560
561                         /**
562                          * Adds given file in a new li-tag to target_ul list
563                          *
564                          * @param name Name of the file
565                          * @param info Some more informations
566                          */
567                         function addFileLi (name, info) {
568                                 if (settings_listfiles == false) {
569                                         return;
570                                 }
571
572                                 target_form.style.display = 'none';
573
574                                 var new_li = document.createElement('li');
575                                 new_li.className = 'uploading';
576
577                                 var new_a = document.createElement('a');
578                                 new_a.innerHTML = name;
579                                 new_li.appendChild(new_a);
580
581                                 var new_span = document.createElement('span');
582                                 new_span.innerHTML = info;
583                                 new_a.appendChild(new_span);
584
585                                 target_ul.insertBefore(new_li, target_ul.firstChild);
586                         }
587
588                         /**
589                          * Handles given event for file upload
590                          *
591                          * @param event Event to handle file upload for
592                          */
593                         function handleFiles (event) {
594                                 event.preventDefault();
595
596                                 var files = event.dataTransfer.files;
597
598                                 var form = new FormData();
599
600                                 for (var i = 0; i < files.length; i++) {
601                                         form.append('file[]', files[i]);
602                                         addFileLi(files[i].name, files[i].size + ' bytes');
603                                 }
604
605                                 var xhr = new XMLHttpRequest();
606                                 xhr.onload = function() {
607                                         window.location.reload();
608                                 };
609
610                                 xhr.open('post', '<?php echo $data['scriptname']; ?>', true);
611                                 xhr.send(form);
612                         }
613
614                         // Initialize upload form
615                         init();
616
617                 //-->
618                 </script>
619         </body>
620 </html>