· 9 years ago · Jul 07, 2017, 05:38 AM
1<?php
2
3error_reporting(E_ALL | E_STRICT);
4
5class uploader
6{
7 const REMOTE_URL_UPLOAD_FEEDBACK_CHUNKS_BYTES = 200000; // how often to supply feedback on the url uploader
8
9 public $options;
10 public $nextFeedbackTracker;
11 public $rowId;
12 public $fileUpload = null;
13
14 function __construct($options = null)
15 {
16 // get accepted file types
17 $acceptedFileTypes = UserPeer::getAcceptedFileTypes();
18
19 // get blocked file types
20 $blockedFileTypes = UserPeer::getBlockedFileTypes();
21
22 // get blocked file keywords
23 $blockedFileKeywords = UserPeer::getBlockedFilenameKeywords();
24
25 if (isset($options['max_chunk_size']))
26 {
27 $this->options['max_chunk_size'] = (int) $options['max_chunk_size'];
28 }
29
30 // get logged in user details
31 $Auth = Auth::getAuth();
32 $userId = null;
33 if ($Auth->loggedIn())
34 {
35 $userId = $Auth->id;
36 }
37
38 // default options
39 $this->options = array(
40 'script_url' => $_SERVER['PHP_SELF'],
41 'upload_dir' => _CONFIG_FILE_STORAGE_PATH,
42 'upload_url' => dirname($_SERVER['PHP_SELF']) . '/files/',
43 'param_name' => 'files',
44 'delete_hash' => '',
45 'max_file_size' => $this->getMaxUploadSize(),
46 'min_file_size' => 1,
47 'accept_file_types' => COUNT($acceptedFileTypes) ? ('/(\.|\/)(' . str_replace(".", "", implode("|", $acceptedFileTypes)) . ')$/i') : '/.+$/i',
48 'block_file_types' => COUNT($blockedFileTypes) ? ('/(\.|\/)(' . str_replace(".", "", implode("|", $blockedFileTypes)) . ')$/i') : '',
49 'block_file_keywords' => $blockedFileKeywords,
50 'max_number_of_files' => null,
51 'discard_aborted_uploads' => true,
52 'max_chunk_size' => 0,
53 'folder_id' => 0,
54 'user_id' => $userId,
55 'fail_zero_bytes' => true,
56 'upload_source' => 'direct',
57 'background_queue_id' => null,
58 );
59
60 if ($options)
61 {
62 $this->options = array_replace_recursive($this->options, $options);
63 }
64 }
65
66 public function getMaxUploadSize()
67 {
68 // max allowed upload size
69 return UserPeer::getMaxUploadFilesize();
70 }
71
72 public function getAvailableStorage()
73 {
74 // initialize current user
75 $Auth = Auth::getAuth();
76
77 // available storage
78 $availableStorage = UserPeer::getAvailableFileStorage($Auth->id);
79
80 return $availableStorage;
81 }
82
83 public function getFileObject($file_name)
84 {
85 $file_path = $this->options['upload_dir'] . $file_name;
86 if (is_file($file_path) && $file_name[0] !== '.')
87 {
88 $file = new stdClass();
89 $file->name = $file_name;
90 $file->size = filesize($file_path);
91 $file->url = $this->options['upload_url'] . rawurlencode($file->name);
92 $file->delete_url = '~d?' . $this->options['delete_hash'];
93 $file->info_url = '~i?' . $this->options['delete_hash'];
94 $file->delete_type = 'DELETE';
95 $file->delete_hash = $this->options['delete_hash'];
96
97 return $file;
98 }
99
100 return null;
101 }
102
103 public function getFileObjects()
104 {
105 return array_values(array_filter(array_map(
106 array($this, 'getFileObject'), scandir($this->options['upload_dir'])
107 )));
108 }
109
110 public function hasError($uploaded_file, $file, $error = null)
111 {
112 // make sure uploading hasn't been disabled
113 if(uploader::uploadingDisabled() == true)
114 {
115 return t('uploader_all_blocked', 'Uploading is currently disabled on the site, please try again later.');
116 }
117
118 if ($error)
119 {
120 return $error;
121 }
122
123 if (!preg_match($this->options['accept_file_types'], $file->name))
124 {
125 return 'acceptFileTypes';
126 }
127
128 if($this->options['block_file_types'])
129 {
130 if (preg_match($this->options['block_file_types'], $file->name))
131 {
132 return t('uploader_blocked_filetype', 'File could not be uploaded due to that file type being banned by the site admin');
133 }
134 }
135
136 // check for blocked strings within the filename
137 if(COUNT($this->options['block_file_keywords']))
138 {
139 foreach($this->options['block_file_keywords'] AS $keyword)
140 {
141 if(stripos($file->name, $keyword) !== false)
142 {
143 return t('uploader_blocked_file_keyword', 'File could not be uploaded as the filename was blocked');
144 }
145 }
146 }
147
148 // check for blocked file hashes
149 $md5FileHash = md5_file($uploaded_file);
150 $isBlocked = file::checkFileHashBlocked($md5FileHash);
151 if($isBlocked)
152 {
153 return t('uploader_blocked_file_hash_content', 'File content has been blocked from being uploaded.');
154 }
155
156 if ($uploaded_file && file_exists($uploaded_file))
157 {
158 $file_size = filesize($uploaded_file);
159 }
160 else
161 {
162 $file_size = $_SERVER['CONTENT_LENGTH'];
163 }
164 if ($this->options['max_file_size'] && ($file_size > $this->options['max_file_size'] || $file->size > $this->options['max_file_size']))
165 {
166 return 'maxFileSize';
167 }
168 if ($this->options['min_file_size'] && $file_size < $this->options['min_file_size'])
169 {
170 return 'minFileSize';
171 }
172 if (is_int($this->options['max_number_of_files']) && (count($this->getFileObjects()) >= $this->options['max_number_of_files']))
173 {
174 return 'maxNumberOfFiles';
175 }
176
177 return null;
178 }
179
180 static function checkBannedFiles($fileHash, $fileSize)
181 {
182 // get database connection
183 $db = Database::getDatabase();
184 $isFileBanned = $db->getRow("SELECT * FROM banned_files WHERE fileHash = '".$db->escape($fileHash)."' AND fileSize = '".$db->escape($fileSize)."'");
185
186 if(is_array($isFileBanned))
187 {
188 return true;
189 }
190 return false;
191 }
192
193 public function handleFileUpload($uploadedFile, $name, $size, $type, $error, $index = null, $contentRange = null, $chunkTracker = null)
194 {
195 $fileUpload = new stdClass();
196 $fileUpload->name = stripslashes($name);
197 $fileUpload->size = intval($size);
198 $fileUpload->type = $type;
199 $fileUpload->error = null;
200
201 // save file locally is chunked upload
202 if ($contentRange)
203 {
204 $localTempStore = self::getLocalTempStorePath();
205 $tmpFilename = MD5($fileUpload->name);
206 $tmpFilePath = $localTempStore . $tmpFilename;
207
208 // if first chunk
209 if ($contentRange[1] == 0)
210 {
211 // ensure the tmp file does not already exist
212 if (file_exists($tmpFilePath))
213 {
214 unlink($tmpFilePath);
215 }
216
217 // clean up any old chunks while we're here
218 $this->cleanLeftOverChunks();
219 }
220
221 // ensure we have the chunk
222 if ($uploadedFile && file_exists($uploadedFile))
223 {
224 // multipart/formdata uploads (POST method uploads)
225 $fp = fopen($uploadedFile, 'r');
226 file_put_contents($tmpFilePath, $fp, FILE_APPEND);
227 fclose($fp);
228
229 // check if this is not the last chunk
230 if ($contentRange[3] != filesize($tmpFilePath))
231 {
232 // exit
233 return $fileUpload;
234 }
235
236 // otherwise assume we have the whole file
237 $uploadedFile = $tmpFilePath;
238 $fileUpload->size = filesize($tmpFilePath);
239 }
240 else
241 {
242 // exit
243 return $fileUpload;
244 }
245 }
246
247 $fileUpload->error = $this->hasError($uploadedFile, $fileUpload, $error);
248 if (!$fileUpload->error)
249 {
250 if (strlen(trim($fileUpload->name)) == 0)
251 {
252 $fileUpload->error = t('classuploader_filename_not_found', 'Filename not found.');
253 }
254 }
255 elseif ((intval($size) == 0) && ($this->options['fail_zero_bytes'] == true))
256 {
257 $fileUpload->error = t('classuploader_file_received_has_zero_size', 'File received has zero size. This is likely an issue with the maximum permitted size within PHP');
258 }
259 elseif (intval($size) > $this->options['max_file_size'])
260 {
261 $fileUpload->error = t('classuploader_file_received_larger_than_permitted', 'File received is larger than permitted. (max [[[MAX_FILESIZE]]])', array('MAX_FILESIZE' => coreFunctions::formatSize($this->options['max_file_size'])));
262 }
263
264 if (!$fileUpload->error && $fileUpload->name)
265 {
266 $fileUpload = $this->moveIntoStorage($fileUpload, $uploadedFile);
267 }
268
269 // no error, add success html
270 if ($fileUpload->error === null)
271 {
272 $fileUpload->url_html = '<a href="' . $fileUpload->url . '" target="_blank" title="' . t('view_image_on', 'View image on') . ' ' . SITE_CONFIG_SITE_NAME . '">' . t('view', 'View') . ' ' . $fileUpload->name . ' ' . t('on', 'on') . ' ' . SITE_CONFIG_SITE_NAME . '</a>';
273 $fileUpload->url_bbcode = '[url]' . $fileUpload->url . '[/url]';
274 $fileUpload->success_result_html = self::generateSuccessHtml($fileUpload, $this->options['upload_source']);
275 }
276 else
277 {
278 $fileUpload->error_result_html = self::generateErrorHtml($fileUpload);
279 }
280
281 return $fileUpload;
282 }
283
284 public function get()
285 {
286 $file_name = isset($_REQUEST['file']) ?
287 basename(stripslashes($_REQUEST['file'])) : null;
288 if ($file_name)
289 {
290 $info = $this->getFileObject($file_name);
291 }
292 else
293 {
294 $info = $this->getFileObjects();
295 }
296 header('Content-type: application/json');
297 echo json_encode($info);
298 }
299
300 public function post()
301 {
302 $upload = isset($_FILES[$this->options['param_name']]) ?
303 $_FILES[$this->options['param_name']] : array(
304 'tmp_name' => null,
305 'name' => null,
306 'size' => null,
307 'type' => null,
308 'error' => null
309 );
310
311 // parse the Content-Disposition header, if available:
312 $file_name = $this->getServerVar('HTTP_CONTENT_DISPOSITION') ?
313 rawurldecode(preg_replace(
314 '/(^[^"]+")|("$)/', '', $this->getServerVar('HTTP_CONTENT_DISPOSITION')
315 )) : null;
316
317 // parse the Content-Range header, which has the following form:
318 // Content-Range: bytes 0-524287/2000000
319 $content_range = $this->getServerVar('HTTP_CONTENT_RANGE') ?
320 preg_split('/[^0-9]+/', $this->getServerVar('HTTP_CONTENT_RANGE')) : null;
321 $size = $content_range ? $content_range[3] : null;
322
323 $info = array();
324 if (is_array($upload['tmp_name']))
325 {
326 foreach ($upload['tmp_name'] as $index => $value)
327 {
328 $info[] = $this->handleFileUpload(
329 $upload['tmp_name'][$index], isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : $upload['name'][$index], isset($_SERVER['HTTP_X_FILE_SIZE']) ? $_SERVER['HTTP_X_FILE_SIZE'] : $upload['size'][$index], isset($_SERVER['HTTP_X_FILE_TYPE']) ? $_SERVER['HTTP_X_FILE_TYPE'] : $upload['type'][$index], $upload['error'][$index], $index, $content_range, isset($_REQUEST['cTracker']) ? $_REQUEST['cTracker'] : null
330 );
331 }
332 }
333 else
334 {
335 $info[] = $this->handleFileUpload(
336 $upload['tmp_name'], isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : $upload['name'], isset($_SERVER['HTTP_X_FILE_SIZE']) ? $_SERVER['HTTP_X_FILE_SIZE'] : $upload['size'], isset($_SERVER['HTTP_X_FILE_TYPE']) ? $_SERVER['HTTP_X_FILE_TYPE'] : $upload['type'], $upload['error'], null, $content_range, isset($_REQUEST['cTracker']) ? $_REQUEST['cTracker'] : null
337 );
338 }
339 header('Vary: Accept');
340 if (isset($_SERVER['HTTP_ACCEPT']) &&
341 (strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false))
342 {
343 header('Content-type: application/json');
344 }
345 else
346 {
347 header('Content-type: text/plain');
348 }
349 echo json_encode($info);
350 }
351
352 public function handleRemoteUrlUpload($url, $rowId = 0)
353 {
354 $this->rowId = $rowId;
355 $this->nextFeedbackTracker = self::REMOTE_URL_UPLOAD_FEEDBACK_CHUNKS_BYTES;
356
357 $this->fileUpload = new stdClass();
358
359 // filename
360 $realFilename = trim(end(explode('/', $url)));
361
362 // remove anything before a question mark
363 $realFilename = trim(current(explode('?', $realFilename)));
364 $realFilename = trim(current(explode(';', $realFilename)));
365 if (strlen($realFilename) == 0)
366 {
367 $realFilename = 'file.txt';
368 }
369 // decode filename
370 $realFilename = urldecode($realFilename);
371 $this->fileUpload->name = $realFilename;
372
373 $this->fileUpload->size = 0;
374 $this->fileUpload->type = '';
375 $this->fileUpload->error = null;
376 $this->fileUpload->rowId = $rowId;
377 $this->fileUpload->requestUrl = $url;
378
379 $remoteFileDetails = $this->getRemoteFileDetails($url);
380 $remoteFilesize = (int) $remoteFileDetails['bytes'];
381 if ($remoteFilesize > $this->options['max_file_size'])
382 {
383 $this->fileUpload->error = t('classuploader_file_larger_than_permitted', 'File is larger than permitted. (max [[[MAX_FILESIZE]]])', array('MAX_FILESIZE' => coreFunctions::formatSize($this->options['max_file_size'])));
384 }
385 else
386 {
387 // look for real filename if passed in headers
388 if (strlen($remoteFileDetails['real_filename']))
389 {
390 $realFilename = trim(current(explode(';', $remoteFileDetails['real_filename'])));
391 if(strlen($realFilename))
392 {
393 $this->fileUpload->name = $realFilename;
394 }
395 }
396
397 // try to get the file locally
398 $localFile = $this->downloadRemoteFile($url, true);
399
400 // reconnect db if it's gone away
401 $db = Database::getDatabase(true);
402 $db->close();
403 $db = Database::getDatabase(true);
404
405 if ($localFile === false)
406 {
407 $this->fileUpload->error = t('classuploader_could_not_get_remote_file', 'Could not get remote file. [[[FILE_URL]]]', array('FILE_URL' => $url));
408 }
409 else
410 {
411 $size = (int) filesize($localFile);
412 $this->fileUpload->error = $this->hasError($localFile, $this->fileUpload);
413 if (!$this->fileUpload->error)
414 {
415 if (strlen(trim($this->fileUpload->name)) == 0)
416 {
417 $this->fileUpload->error = t('classuploader_filename_not_found', 'Filename not found.');
418 }
419 }
420 elseif (intval($size) == 0)
421 {
422 $this->fileUpload->error = t('classuploader_file_has_zero_size', 'File received has zero size.');
423 }
424 elseif (intval($size) > $this->options['max_file_size'])
425 {
426 $this->fileUpload->error = t('classuploader_file_received_larger_than_permitted', 'File received is larger than permitted. (max [[[MAX_FILESIZE]]])', array('MAX_FILESIZE' => coreFunctions::formatSize($this->options['max_file_size'])));
427 }
428
429 if (!$this->fileUpload->error && $this->fileUpload->name)
430 {
431 // filesize
432 $this->fileUpload->size = filesize($localFile);
433
434 // get mime type
435 $mimeType = file::estimateMimeTypeFromExtension($this->fileUpload->name, 'application/octet-stream');
436 if (($mimeType == 'application/octet-stream') && (class_exists('finfo', false)))
437 {
438 $finfo = new finfo;
439 $mimeType = $finfo->file($localFile, FILEINFO_MIME);
440 }
441 $this->fileUpload->type = $mimeType;
442
443 // save into permanent storage
444 $this->fileUpload = $this->moveIntoStorage($this->fileUpload, $localFile);
445 }
446 else
447 {
448 @unlink($localFile);
449 }
450 }
451 }
452
453 // no error, add success html
454 if ($this->fileUpload->error === null)
455 {
456 $this->fileUpload->url_html = '<a href="' . $this->fileUpload->url . '" target="_blank" title="' . t('view_image_on', 'View image on') . ' ' . SITE_CONFIG_SITE_NAME . '">' . t('view', 'View') . ' ' . $this->fileUpload->name . ' ' . t('on', 'on') . ' ' . SITE_CONFIG_SITE_NAME . '</a>';
457 $this->fileUpload->url_bbcode = '[url]' . $this->fileUpload->url . '[/url]';
458 $this->fileUpload->success_result_html = self::generateSuccessHtml($this->fileUpload, $this->options['upload_source']);
459 }
460 else
461 {
462 $this->fileUpload->error_result_html = self::generateErrorHtml($this->fileUpload);
463 }
464
465 $this->remote_url_event_callback(array("done" => $this->fileUpload));
466 }
467
468 public function getRemoteFileDetails($url)
469 {
470 $rs = array();
471 $rs['bytes'] = 0;
472 $rs['real_filename'] = null;
473 if (function_exists('curl_init'))
474 {
475 // initialize curl with given url
476 if ($ch === null)
477 {
478 $ch = curl_init();
479 }
480 curl_setopt($ch, CURLOPT_URL, $url);
481 curl_setopt($ch, CURLOPT_HEADER, true);
482 curl_setopt($ch, CURLOPT_NOBODY, true);
483 curl_setopt($ch, CURLOPT_REFERER, $url);
484 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
485 curl_setopt($ch, CURLOPT_MAXREDIRS, 15);
486 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
487 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
488 curl_setopt($ch, CURLOPT_FAILONERROR, true);
489 $execute = curl_exec($ch);
490
491 // check if any error occured
492 if (!curl_errno($ch))
493 {
494 $rs['bytes'] = (int) curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
495
496 // this catches filenames between quotes
497 if(preg_match('/.*filename=[\'\"]([^\'\"]+)/', $execute, $matches))
498 {
499 $rs['real_filename'] = $matches[1];
500 }
501 // if filename is not quoted, we take all until the next space
502 elseif(preg_match("/.*filename=([^ ]+)/", $execute, $matches))
503 {
504 $rs['real_filename'] = $matches[1];
505 }
506
507 // make sure there are no quotes
508 $rs['real_filename'] = str_replace('"', '', $rs['real_filename']);
509 }
510
511 curl_close($ch);
512 }
513 else
514 {
515 uploader::exitWithError(t('classuploader_curl_module_not_found', 'Curl module not found. Please enable within PHP to enable remote uploads.'));
516 }
517
518 return $rs;
519 }
520
521 static public function getLocalTempStorePath()
522 {
523 $tmpDir = _CONFIG_FILE_STORAGE_PATH . '_tmp/';
524 if (!file_exists($tmpDir))
525 {
526 @mkdir($tmpDir);
527 }
528
529 if (!file_exists($tmpDir))
530 {
531 uploader::exitWithError(t('classuploader_failed_creating_tmp_storage_folder', 'Failed creating tmp storage folder for chunked uploads. Ensure the parent folder has write permissions: [[[TMP_DIR]]]', array('TMP_DIR' => $tmpDir)));
532 }
533
534 if (!is_writable($tmpDir))
535 {
536 uploader::exitWithError(t('classuploader_temp_storage_folder_for_uploads_not_writable', 'Temp storage folder for uploads is not writable. Ensure it has CHMOD 755 or 777 permissions: [[[TMP_DIR]]]', array('TMP_DIR' => $tmpDir)));
537 }
538
539 return $tmpDir;
540 }
541
542 public function getUrlParts($url)
543 {
544 return parse_url($url);
545 }
546
547 public function downloadRemoteFile($url, $streamResponse = false)
548 {
549 // save locally
550 $tmpDir = self::getLocalTempStorePath();
551 $tmpName = MD5($url . microtime());
552 $tmpFullPath = $tmpDir . $tmpName;
553
554 // extract username and password, if available
555 $urlParts = self::getUrlParts($url);
556 $urlUser = null;
557 $urlPass = null;
558 if((isset($urlParts['user'])) && (strlen($urlParts['user'])))
559 {
560 $urlUser = $urlParts['user'];
561 }
562 if((isset($urlParts['pass'])) && (strlen($urlParts['pass'])))
563 {
564 $urlPass = $urlParts['pass'];
565 }
566
567 // use curl
568 if (function_exists('curl_init'))
569 {
570 // get file via curl
571 $fp = fopen($tmpFullPath, 'w+');
572 if ($ch === null)
573 {
574 $ch = curl_init();
575 }
576
577 curl_setopt($ch, CURLOPT_URL, $url);
578 curl_setopt($ch, CURLOPT_NOBODY, false);
579 curl_setopt($ch, CURLOPT_REFERER, $url);
580 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
581 curl_setopt($ch, CURLOPT_MAXREDIRS, 15);
582 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
583 curl_setopt($ch, CURLOPT_TIMEOUT, 60 * 60 * 24); // 24 hours
584 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15); // 15 seconds
585 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
586 curl_setopt($ch, CURLOPT_HEADER, false);
587 // allow for http auth
588 if($urlUser != null)
589 {
590 curl_setopt($ch, CURLOPT_USERPWD, $urlUser.':'.$urlPass);
591 }
592 if ($streamResponse === true)
593 {
594 curl_setopt($ch, CURLOPT_NOPROGRESS, false);
595 curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, array($this, 'remoteUrlCurlProgressCallback'));
596 }
597 //curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
598 curl_setopt($ch, CURLOPT_FILE, $fp);
599 if (curl_exec($ch) === false)
600 {
601 // log error
602 log::error('Failed getting url. Error: ' . curl_error($ch) . ' (' . $url . ')');
603 return false;
604 }
605 $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
606 curl_close($ch);
607 fclose($fp);
608
609 // remove if no a valid status code
610 if (($status === 404) || ($status === 401))
611 {
612 @unlink($tmpFullPath);
613 }
614 }
615 // use file_get_contents
616 else
617 {
618 if (function_exists('stream_context_create'))
619 {
620 $httpArr = array(
621 'timeout' => 15, // 15 seconds
622 );
623
624 if ($streamResponse === true)
625 {
626 $httpArr['notification'] = array($this, 'remoteUrlCurlProgressCallback');
627 }
628
629 if($urlUser != null)
630 {
631 $httpArr['header'] = "Authorization: Basic " . base64_encode($urlUser.':'.$urlPass);
632 }
633
634 $ctx = stream_context_create(array('http' =>
635 $httpArr
636 ));
637 }
638
639 // get file content
640 $fileData = @file_get_contents($url);
641 @file_put_contents($tmpFullPath, $fileData);
642 }
643
644 // test to see if we saved the file
645 if ((file_exists($tmpFullPath)) && (filesize($tmpFullPath) > 0))
646 {
647 return $tmpFullPath;
648 }
649
650 // clear blank file
651 if (file_exists($tmpFullPath))
652 {
653 @unlink($tmpFullPath);
654 }
655
656 return false;
657 }
658
659 function remote_url_event_callback($message)
660 {
661 echo "<script>parent.updateUrlProgress(" . json_encode($message) . ");</script>";
662 ob_flush();
663 flush();
664 }
665
666 function remote_url_stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max)
667 {
668 if ($notification_code == STREAM_NOTIFY_PROGRESS)
669 {
670 if ($bytes_transferred)
671 {
672 if ($bytes_transferred > $this->nextFeedbackTracker)
673 {
674 $this->remote_url_event_callback(array("progress" => array("loaded" => $bytes_transferred, "total" => $bytes_max, "rowId" => $this->rowId)));
675 $this->nextFeedbackTracker = $this->nextFeedbackTracker + self::REMOTE_URL_UPLOAD_FEEDBACK_CHUNKS_BYTES;
676 }
677 }
678 }
679 }
680
681 function remoteUrlCurlProgressCallback($download_size, $downloaded_size, $upload_size, $uploaded_size, $other = null)
682 {
683 // allow for the new option added AT THE BEGINNING! in PHP v5.5
684 if (is_resource($download_size))
685 {
686 $download_size = $downloaded_size;
687 $downloaded_size = $upload_size;
688 $upload_size = $uploaded_size;
689 $uploaded_size = $other;
690 }
691
692 // log in the database or on screen
693 if((int)$this->options['background_queue_id'])
694 {
695 $db = Database::getDatabase(true);
696 $percent = ceil(($downloaded_size/$download_size)*100);
697 $db->query('UPDATE remote_url_download_queue SET downloaded_size='.$db->escape($downloaded_size).', total_size='.$db->escape($download_size).', download_percent='.(int)$percent.' WHERE id='.(int)$this->options['background_queue_id'].' LIMIT 1');
698
699 // stop loads of loops
700 $next = self::REMOTE_URL_UPLOAD_FEEDBACK_CHUNKS_BYTES;
701 if($download_size > 0)
702 {
703 $next = ceil($download_size/100);
704 }
705 $this->nextFeedbackTracker = $this->nextFeedbackTracker + $next;
706 }
707 elseif ($downloaded_size > $this->nextFeedbackTracker)
708 {
709 $this->remote_url_event_callback(array("progress" => array("loaded" => $downloaded_size, "total" => $download_size, "rowId" => $this->rowId)));
710
711 // stop loads of loops
712 $this->nextFeedbackTracker = $this->nextFeedbackTracker + self::REMOTE_URL_UPLOAD_FEEDBACK_CHUNKS_BYTES;
713 }
714 }
715
716 public function moveIntoStorage($fileUpload, $tmpFile, $keepOriginal = false)
717 {
718 if ($fileUpload->name[0] === '.')
719 {
720 $fileUpload->name = substr($fileUpload->name, 1);
721 }
722 $fileUpload->name = trim($fileUpload->name);
723 if (strlen($fileUpload->name) == 0)
724 {
725 $fileUpload->name = date('Ymdhi');
726 }
727 $parts = explode(".", $fileUpload->name);
728 $lastPart = end($parts);
729 $extension = strtolower($lastPart);
730
731 // figure out upload type
732 $file_size = 0;
733
734 // store the actual file
735 $rs = $this->_storeFile($fileUpload, $tmpFile, $keepOriginal);
736 $file_size = $rs['file_size'];
737 $file_path = $rs['file_path'];
738 $uploadServerId = $rs['uploadServerId'];
739 $fileUpload = $rs['fileUpload'];
740 $newFilename = $rs['newFilename'];
741 $fileHash = $rs['fileHash'];
742
743 // reset the connection to the database so mysql doesn't time out
744 $db = Database::getDatabase(true);
745 $db->close();
746 $db = Database::getDatabase(true);
747
748 // check filesize uploaded matches tmp uploaded
749 if (($file_size == $fileUpload->size) && (!$fileUpload->error))
750 {
751 $fileUpload->url = $this->options['upload_url'] . rawurlencode($fileUpload->name);
752
753 // insert into the db
754 $fileUpload->size = $file_size;
755 $fileUpload->delete_url = '~d?' . $this->options['delete_hash'];
756 $fileUpload->info_url = '~i?' . $this->options['delete_hash'];
757 $fileUpload->delete_type = 'DELETE';
758 $fileUpload->delete_hash = $this->options['delete_hash'];
759
760 // create delete hash, make sure it's unique
761 $deleteHash = md5($fileUpload->name . coreFunctions::getUsersIPAddress() . microtime());
762
763 // get database connection
764 $db = Database::getDatabase(true);
765
766 // setup folder id for file
767 $folderId = NULL;
768 if (((int) $this->options['folder_id'] > 0) && ((int) $this->options['user_id'] > 0))
769 {
770 // make sure the current user owns the folder
771 $validFolder = (int) $db->getValue('SELECT COUNT(id) FROM file_folder WHERE userId = ' . (int) $this->options['user_id'] . ' AND id=' . (int) $this->options['folder_id'] . ' LIMIT 1');
772 if ($validFolder > 0)
773 {
774 $folderId = (int) $this->options['folder_id'];
775 }
776 }
777 if ((int) $folderId == 0)
778 {
779 $folderId = NULL;
780 }
781
782 // make sure the original filename is unique in the selected folder
783 $originalFilename = $fileUpload->name;
784 if ((int) $this->options['user_id'] > 0)
785 {
786 $foundExistingFile = 1;
787 $tracker = 2;
788 while ($foundExistingFile >= 1)
789 {
790 $foundExistingFile = (int) $db->getValue('SELECT COUNT(id) FROM file WHERE originalFilename = ' . $db->quote($originalFilename) . ' AND statusId = 1 AND userId = ' . (int) $this->options['user_id'] . ' AND folderId ' . ($folderId === NULL ? 'IS NULL' : ('= ' . $folderId)));
791 if ($foundExistingFile >= 1)
792 {
793 $originalFilename = substr($fileUpload->name, 0, strlen($fileUpload->name) - strlen($extension) - 1) . ' (' . $tracker . ').' . $extension;
794 $tracker++;
795 }
796 }
797 }
798 $fileUpload->name = $originalFilename;
799 $fileUpload->hash = md5_file($tmpFile);
800
801 if($this->checkBannedFiles($fileUpload->hash, $fileUpload->size))
802 {
803 $fileUpload->error = t('classuploader_file_is_banned', 'File is banned from being uploaded to this website.');
804 }
805
806 if (!$fileUpload->error)
807 {
808 // store in db
809 $dbInsert = new DBObject("file", array("originalFilename", "shortUrl", "fileType", "extension", "fileSize", "localFilePath", "userId", "totalDownload", "uploadedIP", "uploadedDate", "statusId", "deleteHash", "serverId", "fileHash", "adminNotes", "folderId", "uploadSource", "keywords", "unique_hash"));
810
811 $dbInsert->originalFilename = $fileUpload->name;
812 $dbInsert->shortUrl = 'temp';
813 $dbInsert->fileType = $fileUpload->type;
814 $dbInsert->extension = strtolower($extension);
815 $dbInsert->fileSize = $fileUpload->size;
816 $dbInsert->localFilePath = (substr($file_path, 0, strlen($this->options['upload_dir'])) == $this->options['upload_dir']) ? substr($file_path, strlen($this->options['upload_dir'])) : $file_path;
817
818 // add user id if user is logged in
819 $dbInsert->userId = $this->options['user_id'];
820 $dbInsert->totalDownload = 0;
821 $dbInsert->uploadedIP = coreFunctions::getUsersIPAddress();
822 $dbInsert->uploadedDate = coreFunctions::sqlDateTime();
823 $dbInsert->statusId = 1;
824 $dbInsert->deleteHash = $deleteHash;
825 $dbInsert->serverId = $uploadServerId;
826 $dbInsert->fileHash = $fileHash;
827 $dbInsert->adminNotes = '';
828 $dbInsert->folderId = $folderId;
829 $dbInsert->uploadSource = $this->options['upload_source'];
830 $dbInsert->keywords = substr(implode(',', file::getKeywordArrFromString($originalFilename)), 0, 255);
831 $dbInsert->unique_hash = file::createUniqueFileHashString();
832
833 if (!$dbInsert->insert())
834 {
835 $fileUpload->error = t('classuploader_failed_adding_to_database', 'Failed adding to database. [[[ERROR_MSG]]]', array('ERROR_MSG' => $dbInsert->errorMsg));
836 }
837 else
838 {
839 // create short url
840 $tracker = 1;
841 $shortUrl = file::createShortUrlPart($tracker . $dbInsert->id);
842 $fileTmp = file::loadByShortUrl($shortUrl);
843 while ($fileTmp)
844 {
845 $shortUrl = file::createShortUrlPart($tracker . $dbInsert->id);
846 $fileTmp = file::loadByShortUrl($shortUrl);
847 $tracker++;
848 }
849
850 // update short url
851 file::updateShortUrl($dbInsert->id, $shortUrl);
852
853 // update fileUpload with file location
854 $file = file::loadByShortUrl($shortUrl);
855 $fileUpload->url = $file->getFullShortUrl();
856 $fileUpload->delete_url = $file->getDeleteUrl();
857 $fileUpload->info_url = $file->getInfoUrl();
858 $fileUpload->stats_url = $file->getStatisticsUrl();
859 $fileUpload->delete_hash = $file->deleteHash;
860 $fileUpload->short_url = $shortUrl;
861 $fileUpload->file_id = $file->id;
862 $fileUpload->unique_hash = $dbInsert->unique_hash;
863
864 // update storage stats
865 file::updateFileServerStorageStats();
866
867 // include any plugins
868 pluginHelper::includeAppends('class_uploader_success.inc.php', array('file' => $file, 'tmpFile' => $tmpFile));
869 }
870 }
871 }
872 else if ($this->options['discard_aborted_uploads'])
873 {
874 //@TODO - make ftp compatible
875 @unlink($file_path);
876 @unlink($tmpFile);
877 if (!isset($fileUpload->error))
878 {
879 $fileUpload->error = t('classuploader_general_upload_error', 'General upload error, please contact support. Expected size: [[[FILE_SIZE]]]. Received size: [[[FILE_UPLOAD_SIZE]]].', array('FILE_SIZE' => $file_size, 'FILE_UPLOAD_SIZE' => $fileUpload->size));
880 }
881 }
882
883 return $fileUpload;
884 }
885
886 public function _storeFile($fileUpload, $tmpFile, $keepOriginal = false)
887 {
888 // setup new filename
889 $newFilename = MD5(microtime());
890
891 // refresh db connection
892 $db = Database::getDatabase(true);
893 $db->close();
894 $db = Database::getDatabase(true);
895
896 // select server from pool
897 $uploadServerDetails = file::getCurrentServerDetails();
898 if (($uploadServerDetails === false) || ($uploadServerDetails['serverType'] != 'direct'))
899 {
900 $uploadServerId = fileServer::getAvailableServerId();
901 $uploadServerDetails = $db->getRow('SELECT * FROM file_server WHERE id = ' . $db->quote($uploadServerId));
902 }
903 else
904 {
905 $uploadServerId = $uploadServerDetails['id'];
906 }
907
908 // override storage path
909 if (strlen($uploadServerDetails['storagePath']))
910 {
911 $this->options['upload_dir'] = $uploadServerDetails['storagePath'];
912 if (substr($this->options['upload_dir'], strlen($this->options['upload_dir']) - 1, 1) == '/')
913 {
914 $this->options['upload_dir'] = substr($this->options['upload_dir'], 0, strlen($this->options['upload_dir']) - 1);
915 }
916 $this->options['upload_dir'] .= '/';
917 }
918
919 // create file hash
920 $fileHash = md5_file($tmpFile);
921
922 // check if the file hash already exists
923 $fileExists = false;
924 if ($fileUpload->size > 0)
925 {
926 $findFile = $db->getRow("SELECT * FROM file WHERE fileHash=" . $db->quote($fileHash) . " AND statusId=1 AND fileSize=" . (int) $fileUpload->size . " LIMIT 1");
927 if (COUNT($findFile) > 1)
928 {
929 $fileExists = true;
930 }
931 }
932
933 if ($fileExists == false)
934 {
935 // include any plugins for other storage methods
936 $params = pluginHelper::includeAppends('class_uploader_move_into_storage.inc.php', array('actioned' => false, 'file_path' => '', 'uploadServerDetails' => $uploadServerDetails, 'fileUpload' => $fileUpload, 'newFilename' => $newFilename, 'tmpFile' => $tmpFile, 'uploader' => $this));
937 if ($params['actioned'] == true)
938 {
939 $fileUpload = $params['fileUpload'];
940 $file_path = $params['file_path'];
941 $file_size = $params['file_size'];
942 }
943 // local, direct or ftp storage methods
944 else
945 {
946 // move remotely via ftp
947 if ($uploadServerDetails['serverType'] == 'ftp')
948 {
949 // connect ftp
950 $conn_id = ftp_connect($uploadServerDetails['ipAddress'], $uploadServerDetails['ftpPort'], 30);
951 if ($conn_id === false)
952 {
953 $fileUpload->error = t('classuploader_could_not_connect_file_server', 'Could not connect to file server [[[IP_ADDRESS]]]', array('IP_ADDRESS' => $uploadServerDetails['ipAddress']));
954 }
955
956 // authenticate
957 if (!$fileUpload->error)
958 {
959 $login_result = ftp_login($conn_id, $uploadServerDetails['ftpUsername'], $uploadServerDetails['ftpPassword']);
960 if ($login_result === false)
961 {
962 $fileUpload->error = t('classuploader_could_not_authenticate_with_file_server', 'Could not authenticate with file server [[[IP_ADDRESS]]]', array('IP_ADDRESS' => $uploadServerDetails['ipAddress']));
963 }
964 }
965
966 // create the upload folder
967 if (!$fileUpload->error)
968 {
969 $uploadPathDir = $this->options['upload_dir'] . substr($newFilename, 0, 2);
970 if (!ftp_mkdir($conn_id, $uploadPathDir))
971 {
972 // Error reporting removed for now as it causes issues with existing folders. Need to add a check in before here
973 // to see if the folder exists, then create if not.
974 // $fileUpload->error = 'There was a problem creating the storage folder on '.$uploadServerDetails['ipAddress'];
975 }
976 }
977
978 // upload via ftp
979 if (!$fileUpload->error)
980 {
981 $file_path = $uploadPathDir . '/' . $newFilename;
982 clearstatcache();
983 if ($tmpFile)
984 {
985 // initiate ftp
986 $ret = ftp_nb_put($conn_id, $file_path, $tmpFile, FTP_BINARY, FTP_AUTORESUME);
987 while ($ret == FTP_MOREDATA)
988 {
989 // continue uploading
990 $ret = ftp_nb_continue($conn_id);
991 }
992
993 if ($ret != FTP_FINISHED)
994 {
995 $fileUpload->error = t('classuploader_there_was_problem_uploading_file', 'There was a problem uploading the file to [[[IP_ADDRESS]]]', array('IP_ADDRESS' => $uploadServerDetails['ipAddress']));
996 }
997 else
998 {
999 $file_size = filesize($tmpFile);
1000 if ($keepOriginal == false)
1001 {
1002 @unlink($tmpFile);
1003 }
1004 }
1005 }
1006 }
1007
1008 // close ftp connection
1009 ftp_close($conn_id);
1010 }
1011 // move into local storage
1012 else
1013 {
1014 // check the upload folder
1015 if (($uploadServerDetails['serverType'] == 'direct') || (!file_exists($this->options['upload_dir'])))
1016 {
1017 $this->options['upload_dir'] = _CONFIG_SCRIPT_ROOT . '/' . $this->options['upload_dir'];
1018 }
1019
1020 // fallback
1021 if(!file_exists($this->options['upload_dir']))
1022 {
1023 $this->options['upload_dir'] = _CONFIG_FILE_STORAGE_PATH;
1024 }
1025
1026 // create the upload folder
1027 $uploadPathDir = $this->options['upload_dir'] . substr($newFilename, 0, 2);
1028 @mkdir($uploadPathDir);
1029 @chmod($uploadPathDir, 0777);
1030
1031 $file_path = $uploadPathDir . '/' . $newFilename;
1032 clearstatcache();
1033 $rs = false;
1034 if ($tmpFile)
1035 {
1036 if ($keepOriginal == true)
1037 {
1038 $rs = copy($tmpFile, $file_path);
1039 }
1040 else
1041 {
1042 $rs = rename($tmpFile, $file_path);
1043 }
1044 if ($rs)
1045 {
1046 @chmod($file_path, 0777);
1047 }
1048 }
1049
1050 if ($rs == false)
1051 {
1052 $fileUpload->error = t('classuploader_could_not_move_file_into_storage_on_x', 'Could not move the file into storage on [[[SERVER]]], possibly a permissions issue with the file storage directory.', array('SERVER' => _CONFIG_SITE_HOST_URL)).' - '.$tmpFile.' - '.$file_path;
1053 }
1054 $file_size = filesize($file_path);
1055 }
1056 }
1057 }
1058 else
1059 {
1060 $file_size = $findFile['fileSize'];
1061 $file_path = $this->options['upload_dir'] . $findFile['localFilePath'];
1062 $uploadServerId = $findFile['serverId'];
1063 }
1064
1065 $rs = array();
1066 $rs['file_size'] = $file_size;
1067 $rs['file_path'] = $file_path;
1068 $rs['uploadServerId'] = $uploadServerId;
1069 $rs['fileUpload'] = $fileUpload;
1070 $rs['newFilename'] = $newFilename;
1071 $rs['relative_file_path'] = (substr($file_path, 0, strlen($this->options['upload_dir'])) == $this->options['upload_dir']) ? substr($file_path, strlen($this->options['upload_dir'])) : $file_path;
1072 $rs['fileHash'] = $fileHash;
1073
1074 return $rs;
1075 }
1076
1077 /*
1078 * Removes any old files left over from failed chunked uploads
1079 */
1080 private function cleanLeftOverChunks()
1081 {
1082 // loop local tmp folder and clear any older than 3 days old
1083 $localTempStore = self::getLocalTempStorePath();
1084 foreach (glob($localTempStore . "*") as $file)
1085 {
1086 // protect the filename
1087 if (filemtime($file) < time() - 60 * 60 * 24 * 3)
1088 {
1089 // double check we're in the file store
1090 if (substr($file, 0, strlen(_CONFIG_FILE_STORAGE_PATH)) == _CONFIG_FILE_STORAGE_PATH)
1091 {
1092 @unlink($file);
1093 }
1094 }
1095 }
1096 }
1097
1098 protected function getServerVar($id)
1099 {
1100 return isset($_SERVER[$id]) ? $_SERVER[$id] : '';
1101 }
1102
1103 static function generateSuccessHtml($fileUpload, $uploadSource = 'direct')
1104 {
1105 // get auth for later
1106 $Auth = Auth::getAuth();
1107
1108 // load user folders for later
1109 $userFolders = fileFolder::loadAllByAccount($Auth->id);
1110
1111 // generate html
1112 $success_result_html = '';
1113 $success_result_html .= '<td class="cancel">';
1114 $success_result_html .= ' <img src="' . coreFunctions::getCoreSitePath() . '/themes/' . SITE_CONFIG_SITE_THEME . '/images/green_tick_small.png" height="16" width="16" alt="success"/>';
1115 $success_result_html .= '</td>';
1116 $success_result_html .= '<td class="name">';
1117 $success_result_html .= $fileUpload->name;
1118 $success_result_html .= '<div class="sliderContent" style="display: none;">';
1119 $success_result_html .= ' <!-- popup content -->';
1120 $success_result_html .= ' <table width="100%">';
1121 $success_result_html .= ' <tr>';
1122 $success_result_html .= ' <td class="odd" style="width: 90px; border-top:1px solid #fff;">';
1123 $success_result_html .= ' <label>' . t('download_url', 'Download Url') . ':</label>';
1124 $success_result_html .= ' </td>';
1125 $success_result_html .= ' <td class="odd ltrOverride" style="border-top:1px solid #fff;">';
1126 $success_result_html .= ' <a href="' . $fileUpload->url . '" target="_blank">' . $fileUpload->url . '</a>';
1127 $success_result_html .= ' </td>';
1128 $success_result_html .= ' </tr>';
1129 $success_result_html .= ' <tr>';
1130 $success_result_html .= ' <td class="even">';
1131 $success_result_html .= ' <label>' . t('html_code', 'HTML Code') . ':</label>';
1132 $success_result_html .= ' </td>';
1133 $success_result_html .= ' <td class="even htmlCode ltrOverride" onClick="return false;">';
1134 $success_result_html .= ' <a href="' . $fileUpload->info_url . '" target="_blank" title="' . t('download from', 'Download From') . ' ' . SITE_CONFIG_SITE_NAME . '">' . t('download', 'Download') . ' ' . $fileUpload->name . ' ' . t('from', 'from') . ' ' . SITE_CONFIG_SITE_NAME . '</a>';
1135 $success_result_html .= ' </td>';
1136 $success_result_html .= ' </tr>';
1137 $success_result_html .= ' <tr>';
1138 $success_result_html .= ' <td class="odd">';
1139 $success_result_html .= ' <label>' . t('forum_code', 'Forum Code') . ':</label>';
1140 $success_result_html .= ' </td>';
1141 $success_result_html .= ' <td class="odd htmlCode ltrOverride">';
1142 $success_result_html .= ' [url]' . $fileUpload->url . '[/url]';
1143 $success_result_html .= ' </td>';
1144 $success_result_html .= ' </tr>';
1145 $success_result_html .= ' <tr>';
1146 $success_result_html .= ' <td class="even">';
1147 $success_result_html .= ' <label>' . t('stats_url', 'Stats Url') . ':</label>';
1148 $success_result_html .= ' </td>';
1149 $success_result_html .= ' <td class="even ltrOverride">';
1150 $success_result_html .= ' <a href="' . $fileUpload->stats_url . '" target="_blank">' . $fileUpload->stats_url . '</a>';
1151 $success_result_html .= ' </td>';
1152 $success_result_html .= ' </tr>';
1153 $success_result_html .= ' <tr>';
1154 $success_result_html .= ' <td class="odd">';
1155 $success_result_html .= ' <label>' . t('delete_url', 'Delete Url') . ':</label>';
1156 $success_result_html .= ' </td>';
1157 $success_result_html .= ' <td class="odd ltrOverride">';
1158 $success_result_html .= ' <a href="' . $fileUpload->delete_url . '" target="_blank">' . $fileUpload->delete_url . '</a>';
1159 $success_result_html .= ' </td>';
1160 $success_result_html .= ' </tr>';
1161 $success_result_html .= ' <tr>';
1162 $success_result_html .= ' <td class="even">';
1163 $success_result_html .= ' <label>' . t('full_info', 'Full Info') . ':</label>';
1164 $success_result_html .= ' </td>';
1165 $success_result_html .= ' <td class="even htmlCode ltrOverride">';
1166 $success_result_html .= ' <a href="' . $fileUpload->info_url . '" target="_blank" onClick="window.open(\'' . $fileUpload->info_url . '\'); return false;">[' . t('click_here', 'click here') . ']</a>';
1167 $success_result_html .= ' </td>';
1168 $success_result_html .= ' </tr>';
1169
1170 /*
1171 if ($Auth->loggedIn() && COUNT($userFolders))
1172 {
1173 $success_result_html .= ' <tr>';
1174 $success_result_html .= ' <td class="odd">';
1175 $success_result_html .= ' <label>' . t('save_to_folder',
1176 'Save To Folder') . ':</label>';
1177 $success_result_html .= ' </td>';
1178 $success_result_html .= ' <td class="odd">';
1179 $success_result_html .= ' <form>';
1180 $success_result_html .= ' <select name="folderId" id="folderId" class="saveToFolder" onChange="saveFileToFolder(this); return false;">';
1181 $success_result_html .= ' <option value="">- ' . t('none',
1182 'none') . ' -</option>';
1183 foreach ($userFolders AS $userFolder)
1184 {
1185 $success_result_html .= ' <option value="' . $userFolder['id'] . '">' . htmlentities($userFolder['folderName']) . '</option>';
1186 }
1187 $success_result_html .= ' </select>';
1188 $success_result_html .= ' </form>';
1189 $success_result_html .= ' </td>';
1190 $success_result_html .= ' </tr>';
1191 }
1192 *
1193 */
1194
1195 $success_result_html .= ' </table>';
1196 $success_result_html .= ' <input type="hidden" value="' . $fileUpload->short_url . '" name="shortUrlHidden" class="shortUrlHidden"/>';
1197 $success_result_html .= ' </div>';
1198 $success_result_html .= '</td>';
1199 $success_result_html .= '<td class="rightArrow"><img src="' . coreFunctions::getCoreSitePath() . '/themes/' . SITE_CONFIG_SITE_THEME . '/images/blue_right_arrow.png" width="8" height="6" /></td>';
1200 $success_result_html .= '<td class="url urlOff">';
1201 $success_result_html .= ' <a href="' . $fileUpload->url . '" target="_blank">' . $fileUpload->url . '</a>';
1202 $success_result_html .= ' <div class="fileUrls hidden">' . $fileUpload->url . '</div>';
1203 $success_result_html .= '</td>';
1204
1205 // check plugins so the resulting html can be overwritten if set
1206 $params = pluginHelper::includeAppends('class_uploader_success_result_html.php', array('success_result_html' => $success_result_html, 'fileUpload' => $fileUpload, 'userFolders' => $userFolders, 'uploadSource'=>$uploadSource));
1207 $success_result_html = $params['success_result_html'];
1208
1209 return $success_result_html;
1210 }
1211
1212 static function generateErrorHtml($fileUpload)
1213 {
1214 // get auth for later
1215 $Auth = Auth::getAuth();
1216
1217 // generate html
1218 $error_result_html = '';
1219 $error_result_html .= '<td class="cancel">';
1220 $error_result_html .= ' <img src="' . coreFunctions::getCoreSitePath() . '/themes/' . SITE_CONFIG_SITE_THEME . '/images/red_error_small.png" height="16" width="16" alt="error"/>';
1221 $error_result_html .= '</td>';
1222
1223 $error_result_html .= '<td class="name">' . $fileUpload->name . '</td>';
1224
1225 $error_result_html .= '<td class="error" colspan="2">' . t('classuploader_error', 'Error') . ': ';
1226 $error_result_html .= self::translateError($fileUpload->error);
1227 $error_result_html .= '</td>';
1228
1229 // check plugins so the resulting html can be overwritten if set
1230 $params = pluginHelper::includeAppends('class_uploader_error_result_html.php', array('error_result_html' => $error_result_html, 'fileUpload' => $fileUpload));
1231 $error_result_html = $params['error_result_html'];
1232
1233 return $error_result_html;
1234 }
1235
1236 static function translateError($error)
1237 {
1238 switch ($error)
1239 {
1240 case 1:
1241 return t('file_exceeds_upload_max_filesize_php_ini_directive', 'File exceeds upload_max_filesize (php.ini directive)');
1242 case 2:
1243 return t('file_exceeds_max_file_size_html_form_directive', 'File exceeds MAX_FILE_SIZE (HTML form directive)');
1244 case 3:
1245 return t('file_was_only_partially_uploaded', 'File was only partially uploaded');
1246 case 4:
1247 return t('no_file_was_uploaded', 'No File was uploaded');
1248 case 5:
1249 return t('missing_a_temporary_folder', 'Missing a temporary folder');
1250 case 6:
1251 return t('failed_to_write_file_to_disk', 'Failed to write file to disk');
1252 case 7:
1253 return t('file_upload_stopped_by_extension', 'File upload stopped by extension');
1254 case 'maxFileSize':
1255 return t('file_is_too_big', 'File is too big');
1256 case 'minFileSize':
1257 return t('file_is_too_small', 'File is too small');
1258 case 'acceptFileTypes':
1259 return t('filetype_is_not_allowed', 'Filetype not allowed');
1260 case 'maxNumberOfFiles':
1261 return t('max_number_of_files_exceeded', 'Max number of files exceeded');
1262 case 'uploadedBytes':
1263 return t('uploaded_bytes_exceed_file_size', 'Uploaded bytes exceed file size');
1264 case 'emptyResult':
1265 return t('empty_file_upload_result', 'Empty file upload result');
1266 default:
1267 return $error;
1268 }
1269 }
1270
1271 static function exitWithError($errorStr)
1272 {
1273 // log
1274 log::error('class.uploader.php: ' . $errorStr);
1275
1276 $fileUpload = new stdClass();
1277 $fileUpload->error = $errorStr;
1278 $errorHtml = uploader::generateErrorHtml($fileUpload);
1279 $fileUpload->error_result_html = $errorHtml;
1280 echo json_encode(array($fileUpload));
1281 exit;
1282 }
1283
1284 static function addUrlToBackgroundQueue($url, $userId, $folderId = null)
1285 {
1286 // make sure we have a user id
1287 if($userId == 0)
1288 {
1289 return false;
1290 }
1291
1292 // database connection
1293 $db = Database::getDatabase(true);
1294
1295 // current file server if
1296 $currentFileServerId = file::getCurrentServerId();
1297
1298 // make sure it's not already queued for this user
1299 $found = $db->getValue('SELECT id FROM remote_url_download_queue WHERE user_id='.(int)$userId.' AND url='.$db->quote($url).' AND (job_status=\'downloading\' OR job_status=\'pending\' OR job_status=\'processing\') LIMIT 1');
1300 if($found)
1301 {
1302 return true;
1303 }
1304
1305 // add to backgroud queue
1306 return $db->query("INSERT INTO remote_url_download_queue (user_id, url, file_server_id, created, folder_id) VALUES (:user_id, :url, :file_server_id, NOW(), :folder_id)", array('user_id' => (int)$userId, 'url' => $url, 'file_server_id' => $currentFileServerId, 'folder_id' => $folderId));
1307 }
1308
1309 static function uploadingDisabled()
1310 {
1311 // check for admin user
1312 $Auth = Auth::getAuth();
1313 if ($Auth->loggedIn())
1314 {
1315 if($Auth->level_id == 20)
1316 {
1317 return false;
1318 }
1319 }
1320
1321 if(defined('SITE_CONFIG_UPLOADS_BLOCK_ALL') && (SITE_CONFIG_UPLOADS_BLOCK_ALL == 'yes'))
1322 {
1323 return true;
1324 }
1325
1326 return false;
1327 }
1328}