Full-qualified path name "detection" added.
[simple-upload.git] / index.php
1 <?php
2         /*
3                 This program is free software: you can redistribute it and/or modify
4                 it under the terms of the GNU General Public License as published by
5                 the Free Software Foundation, either version 3 of the License, or
6                 (at your option) any later version.
7
8                 This program is distributed in the hope that it will be useful,
9                 but WITHOUT ANY WARRANTY; without even the implied warranty of
10                 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11                 GNU General Public License for more details.
12
13                 You should have received a copy of the GNU General Public License
14                 along with this program.  If not, see <http://www.gnu.org/licenses/>.
15         */
16
17         // =============={ Configuration Begin }==============
18         $settings = array(
19
20                 // Website title
21                 'title' => 'strace.club',
22
23                 // Directory to store uploaded files
24                 'uploaddir' => '.',
25
26                 // Display list uploaded files
27                 'listfiles' => true,
28
29                 // Allow users to delete files that they have uploaded (will enable sessions)
30                 'allow_deletion' => true,
31
32                 // Allow users to mark files as hidden
33                 'allow_private' => true,
34
35                 // Display file sizes
36                 'listfiles_size' => true,
37
38                 // Display file dates
39                 'listfiles_date' => true,
40
41                 // Display file dates format
42                 'listfiles_date_format' => 'F d Y H:i:s',
43
44                 // Randomize file names (number of 'false')
45                 'random_name_len' => 8,
46
47                 // Keep filetype information (if random name is activated)
48                 'random_name_keep_type' => true,
49
50                 // Random file name letters
51                 'random_name_alphabet' => 'qazwsxedcrfvtgbyhnujmikolp1234567890',
52
53                 // Display debugging information
54                 'debug' => false,
55
56                 // Complete URL to your directory (including tracing slash)
57                 'url' => 'http://strace.club/',
58
59                 // Amount of seconds that each file should be stored for (0 for no limit)
60                 // Default 30 days
61                 'time_limit' => 60 * 60 * 24 * 30,
62
63                 // Files that will be ignored
64                 'ignores' => array('.', '..', 'LICENSE', 'README.md'),
65
66                 // Language code
67                 'lang' => 'en_GB',
68
69                 // Language direction
70                 'lang_dir' => 'ltr',
71         );
72         // =============={ Configuration End }==============
73
74         // Is the local config file there?
75         if (file_exists('config-local.php')) {
76                 // Load it then
77                 include('config-local.php');
78         }
79
80         // Enabling error reporting
81         if ($settings['debug']) {
82                 error_reporting(E_ALL);
83                 ini_set('display_startup_errors',1);
84                 ini_set('display_errors',1);
85         }
86
87         $data = array();
88
89         // Name of this file
90         $data['scriptname'] = pathinfo(__FILE__, PATHINFO_BASENAME);
91
92         // Adding current script name to ignore list
93         $data['ignores'] = $settings['ignores'];
94         $data['ignores'][] = $data['scriptname'];
95
96         // Use canonized path
97         $data['uploaddir'] = realpath(dirname(__FILE__) . DIRECTORY_SEPARATOR . $settings['uploaddir']);
98
99         // Maximum upload size, set by system
100         $data['max_upload_size'] = ini_get('upload_max_filesize');
101
102         // If file deletion or private files are allowed, starting a session.
103         // This is required for user authentification
104         if ($settings['allow_deletion'] || $settings['allow_private']) {
105                 session_start();
106
107                 // 'User ID'
108                 if (!isset($_SESSION['upload_user_id']))
109                         $_SESSION['upload_user_id'] = mt_rand(100000, 999999);
110
111                 // List of filenames that were uploaded by this user
112                 if (!isset($_SESSION['upload_user_files']))
113                         $_SESSION['upload_user_files'] = array();
114         }
115
116         // If debug is enabled, logging all variables
117         if ($settings['debug']) {
118                 // Displaying debug information
119                 echo '<h2>Settings:</h2>';
120                 echo '<pre>';
121                 print_r($settings);
122                 echo '</pre>';
123
124                 // Displaying debug information
125                 echo '<h2>Data:</h2>';
126                 echo '<pre>';
127                 print_r($data);
128                 echo '</pre>';
129                 echo '</pre>';
130
131                 // Displaying debug information
132                 echo '<h2>SESSION:</h2>';
133                 echo '<pre>';
134                 print_r($_SESSION);
135                 echo '</pre>';
136         }
137
138         // Format file size
139         function formatSize ($bytes) {
140                 $units = array('B', 'KB', 'MB', 'GB', 'TB');
141
142                 $bytes = max($bytes, 0);
143                 $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
144                 $pow = min($pow, count($units) - 1);
145
146                 $bytes /= pow(1024, $pow);
147
148                 return ceil($bytes) . ' ' . $units[$pow];
149         }
150
151         // Rotating a two-dimensional array
152         function diverseArray ($vector) {
153                 $result = array();
154                 foreach ($vector as $key1 => $value1)
155                         foreach ($value1 as $key2 => $value2)
156                                 $result[$key2][$key1] = $value2;
157                 return $result;
158         }
159
160         // Handling file upload
161         function uploadFile ($file_data) {
162                 global $settings;
163                 global $data;
164                 global $_SESSION;
165
166                 $file_data['uploaded_file_name'] = basename($file_data['name']);
167                 $file_data['target_file_name'] = $file_data['uploaded_file_name'];
168
169                 // Generating random file name
170                 if ($settings['random_name_len'] !== false) {
171                         do {
172                                 $file_data['target_file_name'] = '';
173                                 while (strlen($file_data['target_file_name']) < $settings['random_name_len'])
174                                         $file_data['target_file_name'] .= $settings['random_name_alphabet'][mt_rand(0, strlen($settings['random_name_alphabet']) - 1)];
175                                 if ($settings['random_name_keep_type'])
176                                         $file_data['target_file_name'] .= '.' . pathinfo($file_data['uploaded_file_name'], PATHINFO_EXTENSION);
177                         } while (file_exists($file_data['target_file_name']));
178                 }
179                 $file_data['upload_target_file'] = $data['uploaddir'] . DIRECTORY_SEPARATOR . $file_data['target_file_name'];
180
181                 // Do now allow to overwriting files
182                 if (file_exists($file_data['upload_target_file'])) {
183                         echo 'File name already exists' . "\n";
184                         return;
185                 }
186
187                 // Moving uploaded file OK
188                 if (move_uploaded_file($file_data['tmp_name'], $file_data['upload_target_file'])) {
189                         if ($settings['allow_deletion'] || $settings['allow_private'])
190                                 $_SESSION['upload_user_files'][] = $file_data['target_file_name'];
191                         echo $settings['url'] .  $file_data['target_file_name'] . "\n";
192                 } else {
193                         echo 'Error: unable to upload the file.';
194                 }
195         }
196
197
198         // Files are being POSEed. Uploading them one by one.
199         if (isset($_FILES['file'])) {
200                 header('Content-type: text/plain');
201                 if (is_array($_FILES['file'])) {
202                         $file_array = diverseArray($_FILES['file']);
203                         foreach ($file_array as $file_data)
204                                 uploadFile($file_data);
205                 } else
206                         uploadFile($_FILES['file']);
207                 exit;
208         }
209
210         // Other file functions (delete, private).
211         if (isset($_POST)) {
212                 if ($settings['allow_deletion'])
213                         if (isset($_POST['action']) && $_POST['action'] === 'delete')
214                                 if (in_array(substr($_POST['target'], 1), $_SESSION['upload_user_files']) || in_array($_POST['target'], $_SESSION['upload_user_files']))
215                                         if (file_exists($_POST['target'])) {
216                                                 unlink($_POST['target']);
217                                                 echo 'File has been removed';
218                                                 exit;
219                                         }
220
221                 if ($settings['allow_private'])
222                         if (isset($_POST['action']) && $_POST['action'] === 'privatetoggle')
223                                 if (in_array(substr($_POST['target'], 1), $_SESSION['upload_user_files']) || in_array($_POST['target'], $_SESSION['upload_user_files']))
224                                         if (file_exists($_POST['target'])) {
225                                                 if ($_POST['target'][0] === '.') {
226                                                         rename($_POST['target'], substr($_POST['target'], 1));
227                                                         echo 'File has been made visible';
228                                                 } else {
229                                                         rename($_POST['target'], '.' . $_POST['target']);
230                                                         echo 'File has been hidden';
231                                                 }
232                                                 exit;
233                                         }
234         }
235
236         // List files in a given directory, excluding certain files
237         function listFiles ($dir, $exclude) {
238                 $file_array = array();
239                 $dh = opendir($dir);
240                         while (false !== ($filename = readdir($dh)))
241                                 if (is_file($filename) && !in_array($filename, $exclude))
242                                         $file_array[filemtime($filename)] = $filename;
243                 ksort($file_array);
244                 $file_array = array_reverse($file_array, true);
245                 return $file_array;
246         }
247
248         $file_array = listFiles($settings['uploaddir'], $data['ignores']);
249
250         // Removing old files
251         foreach ($file_array as $file)
252                 if ($settings['time_limit'] < time() - filemtime($file))
253                         unlink($file);
254
255         $file_array = listFiles($settings['uploaddir'], $data['ignores']);
256 ?>
257 <!DOCTYPE html>
258 <html lang="<?=$settings['lang']?>" dir="<?=$settings['lang_dir']?>">
259         <head>
260                 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
261                 <meta http-equiv="Content-Script-Type" content="text/javascript">
262                 <meta name="robots" content="noindex">
263                 <meta name="referrer" content="origin-when-crossorigin">
264                 <title><?=$settings['title']?></title>
265                 <style media="screen">
266                 <!--
267                         body {
268                                 background: #111;
269                                 margin: 0;
270                                 color: #ddd;
271                                 font-family: sans-serif;
272                         }
273
274                         body > h1 {
275                                 display: block;
276                                 background: rgba(255, 255, 255, 0.05);
277                                 padding: 8px 16px;
278                                 text-align: center;
279                                 margin: 0;
280                         }
281
282                         body > form {
283                                 display: block;
284                                 background: rgba(255, 255, 255, 0.075);
285                                 padding: 16px 16px;
286                                 margin: 0;
287                                 text-align: center;
288                         }
289
290                         body > ul {
291                                 display: block;
292                                 padding: 0;
293                                 max-width: 1000px;
294                                 margin: 32px auto;
295                         }
296
297                         body > ul > li {
298                                 display: block;
299                                 margin: 0;
300                                 padding: 0;
301                         }
302
303                         body > ul > li > a {
304                                 display: block;
305                                 margin: 0 0 1px 0;
306                                 list-style: none;
307                                 background: rgba(255, 255, 255, 0.1);
308                                 padding: 8px 16px;
309                                 text-decoration: none;
310                                 color: inherit;
311                                 opacity: 0.5;
312                         }
313
314                         body > ul > li > a:hover {
315                                 opacity: 1;
316                         }
317
318                         body > ul > li > a:active {
319                                 opacity: 0.5;
320                         }
321
322                         body > ul > li > a > span {
323                                 float: right;
324                                 font-size: 90%;
325                         }
326
327                         body > ul > li > form {
328                                 display: inline-block;
329                                 padding: 0;
330                                 margin: 0;
331                         }
332
333                         body > ul > li.owned {
334                                 margin: 8px;
335                         }
336
337                         body > ul > li > form > button {
338                                 opacity: 0.5;
339                                 display: inline-block;
340                                 padding: 4px 16px;
341                                 margin: 0;
342                                 border: 0;
343                                 background: rgba(255, 255, 255, 0.1);
344                                 color: inherit;
345                         }
346
347                         body > ul > li > form > button:hover {
348                                 opacity: 1;
349                         }
350
351                         body > ul > li > form > button:active {
352                                 opacity: 0.5;
353                         }
354
355                         body > ul > li.uploading {
356                                 animation: upanim 2s linear 0s infinite alternate;
357                         }
358
359                         @keyframes upanim {
360                                 from {
361                                         opacity: 0.3;
362                                 }
363                                 to {
364                                         opacity: 0.8;
365                                 }
366                         }
367                 //-->
368                 </style>
369         </head>
370         <body>
371                 <h1><?=$settings['title']?></h1>
372                 <form action="<?= $data['scriptname'] ?>" method="POST" enctype="multipart/form-data" class="dropzone" id="simpleupload-form">
373                         Maximum upload size: <?php echo $data['max_upload_size']; ?><br />
374                         <input type="file" name="file[]" multiple required id="simpleupload-input"/>
375                 </form>
376                 <?php if ($settings['listfiles']) { ?>
377                         <ul id="simpleupload-ul">
378                                 <?php
379                                         foreach ($file_array as $mtime => $filename) {
380                                                 $file_info = array();
381                                                 $file_owner = false;
382                                                 $file_private = $filename[0] === '.';
383
384                                                 if ($settings['listfiles_size'])
385                                                         $file_info[] = formatSize(filesize($filename));
386
387                                                 if ($settings['listfiles_size'])
388                                                         $file_info[] = date($settings['listfiles_date_format'], $mtime);
389
390                                                 if ($settings['allow_deletion'] || $settings['allow_private'])
391                                                         if (in_array(substr($filename, 1), $_SESSION['upload_user_files']) || in_array($filename, $_SESSION['upload_user_files']))
392                                                                 $file_owner = true;
393
394                                                 $file_info = implode(', ', $file_info);
395
396                                                 if (strlen($file_info) > 0)
397                                                         $file_info = ' (' . $file_info . ')';
398
399                                                 $class = '';
400                                                 if ($file_owner)
401                                                         $class = 'owned';
402
403                                                 if (!$file_private || $file_owner) {
404                                                         echo "<li class=\"' . $class . '\">";
405
406                                                         echo "<a href=\"$filename\" target=\"_blank\">$filename<span>$file_info</span></a>";
407
408                                                         if ($file_owner) {
409                                                                 if ($settings['allow_deletion'])
410                                                                         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>';
411
412                                                                 if ($settings['allow_private'])
413                                                                         if ($file_private)
414                                                                                 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>';
415                                                                         else
416                                                                                 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>';
417                                                         }
418
419                                                         echo "</li>";
420                                                 }
421                                         }
422                                 ?>
423                         </ul>
424                 <?php } ?>
425                 <a href="https://github.com/muchweb/simple-php-upload"><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>
426                 <script charset="utf-8">
427                         var target_form = document.getElementById('simpleupload-form'),
428                                 target_ul = document.getElementById('simpleupload-ul'),
429                                 target_input = document.getElementById('simpleupload-input');
430
431                         target_form.addEventListener('dragover', function (event) {
432                                 event.preventDefault();
433                         }, false);
434
435                         function AddFileLi (name, info) {
436                                 target_form.style.display = 'none';
437
438                                 var new_li = document.createElement('li');
439                                 new_li.className = 'uploading';
440
441                                 var new_a = document.createElement('a');
442                                 new_a.innerHTML = name;
443                                 new_li.appendChild(new_a);
444
445                                 var new_span = document.createElement('span');
446                                 new_span.innerHTML = info;
447                                 new_a.appendChild(new_span);
448
449                                 target_ul.insertBefore(new_li, target_ul.firstChild);
450                         }
451
452                         function HandleFiles (event) {
453                                 event.preventDefault();
454
455                                 var i = 0,
456                                         files = event.dataTransfer.files,
457                                         len = files.length;
458
459                                 var form = new FormData();
460
461                                 for (; i < len; i++) {
462                                         form.append('file[]', files[i]);
463                                         AddFileLi(files[i].name, files[i].size + ' bytes');
464                                 }
465
466                                 var xhr = new XMLHttpRequest();
467                                 xhr.onload = function() {
468                                         window.location.reload();
469                                 };
470
471                                 xhr.open('post', '<?php echo $data['scriptname']; ?>', true);
472                                 xhr.send(form);
473                         }
474
475                         target_form.addEventListener('drop', HandleFiles, false);
476
477                         document.getElementById('simpleupload-input').onchange = function () {
478                                 AddFileLi('Uploading...', '');
479                                 target_form.submit();
480                         };
481                 </script>
482         </body>
483 </html>