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