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