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