2 namespace Utility\Upload;
7 * jQuery File Upload Plugin PHP Class 5.18.3
8 * https://github.com/blueimp/jQuery-File-Upload
10 * Copyright 2010, Sebastian Tschan
13 * Licensed under the MIT license:
14 * http://www.opensource.org/licenses/MIT
20 // PHP File Upload error message codes:
21 // http://php.net/manual/en/features.file-upload.errors.php
22 protected $error_messages = array(
23 1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
24 2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
25 3 => 'The uploaded file was only partially uploaded',
26 4 => 'No file was uploaded',
27 6 => 'Missing a temporary folder',
28 7 => 'Failed to write file to disk',
29 8 => 'A PHP extension stopped the file upload',
30 'post_max_size' => 'The uploaded file exceeds the post_max_size directive in php.ini',
31 'max_file_size' => 'File is too big.',
32 'min_file_size' => 'File is too small.',
33 'accept_file_types' => 'Filetype not allowed. Files can be either a Word document, PDF, JPG, GIF or TIFF image.',
34 'max_number_of_files' => 'Maximum number of files exceeded.',
35 'max_width' => 'Image exceeds maximum width',
36 'min_width' => 'Image requires a minimum width',
37 'max_height' => 'Image exceeds maximum height',
38 'min_height' => 'Image requires a minimum height'
41 function __construct($options = null, $initialize = true) {
42 $this->options = array(
43 'script_url' => $this->get_full_url().'/',
44 'upload_dir' => \Utility\Registry::getConfigParam('DocumentPath'),
45 'upload_url' => \Utility\Registry::getConfigParam('DocumentUrl'),
48 'param_name' => 'files',
49 // Set the following option to 'POST', if your server does not support
50 // DELETE requests. This is a parameter sent to the client:
51 'delete_type' => 'DELETE',
52 'access_control_allow_origin' => '*',
53 'access_control_allow_credentials' => false,
54 'access_control_allow_methods' => array(
62 'access_control_allow_headers' => array(
65 'Content-Disposition',
68 // Enable to provide file downloads via GET requests to the PHP script:
69 'download_via_php' => false,
70 // Defines which files can be displayed inline when downloaded:
71 'inline_file_types' => '/\.(pdf|docx?|csv|zip|jpe?g|png|tif?f|gif)$/i',
72 // Defines which files (based on their names) are accepted for upload:
73 'accept_file_types' => '/\.(pdf|docx?|csv|zip|jpe?g|png|tif?f|gif)$/i',
74 // The php.ini settings upload_max_filesize and post_max_size
75 // take precedence over the following max_file_size setting:
76 'max_file_size' => '50000000',
78 // The maximum number of files for the upload directory:
79 'max_number_of_files' => null,
80 // Image resolution restrictions:
85 // Set the following option to false to enable resumable uploads:
86 'discard_aborted_uploads' => true,
87 // Set to true to rotate images based on EXIF meta data, if available:
88 'orient_image' => false,
89 'image_versions' => array()
92 $this->options = array_merge($this->options, $options);
99 protected function initialize() {
100 switch ($_SERVER['REQUEST_METHOD']) {
115 header('HTTP/1.1 405 Method Not Allowed');
119 protected function get_full_url() {
120 $https = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
122 ($https ? 'https://' : 'http://').
123 (!empty($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'].'@' : '').
124 (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME'].
125 ($https && $_SERVER['SERVER_PORT'] === 443 ||
126 $_SERVER['SERVER_PORT'] === 80 ? '' : ':'.$_SERVER['SERVER_PORT']))).
127 substr($_SERVER['SCRIPT_NAME'],0, strrpos($_SERVER['SCRIPT_NAME'], '/'));
130 protected function get_user_id() {
135 protected function get_user_path() {
136 if ($this->options['user_dirs']) {
137 return $this->get_user_id().'/';
142 protected function get_upload_path($file_name = null, $version = null) {
143 $file_name = $file_name ? $file_name : '';
144 $version_path = empty($version) ? '' : $version.'/';
145 return $this->options['upload_dir'].$this->get_user_path()
146 .$version_path.$file_name;
149 protected function get_download_url($file_name, $version = null) {
150 if ($this->options['download_via_php']) {
151 $url = $this->options['script_url'].'?file='.rawurlencode($file_name);
153 $url .= '&version='.rawurlencode($version);
155 return $url.'&download=1';
157 $version_path = empty($version) ? '' : rawurlencode($version).'/';
158 return $this->options['upload_url'].$this->get_user_path()
159 .$version_path.rawurlencode($file_name);
162 protected function set_file_delete_properties($file) {
163 $file->delete_url = $this->options['script_url']
164 .'?file='.rawurlencode($file->name);
165 $file->delete_type = $this->options['delete_type'];
166 if ($file->delete_type !== 'DELETE') {
167 $file->delete_url .= '&_method=DELETE';
169 if ($this->options['access_control_allow_credentials']) {
170 $file->delete_with_credentials = true;
174 // Fix for overflowing signed 32 bit integers,
175 // works for sizes up to 2^32-1 bytes (4 GiB - 1):
176 protected function fix_integer_overflow($size) {
178 $size += 2.0 * (PHP_INT_MAX + 1);
183 protected function get_file_size($file_path, $clear_stat_cache = false) {
184 if ($clear_stat_cache) {
187 return $this->fix_integer_overflow(@filesize($file_path));
191 protected function is_valid_file_object($file_name) {
192 $file_path = $this->get_upload_path($file_name);
193 if (is_file($file_path) && $file_name[0] !== '.') {
199 protected function get_file_object($file_name) {
200 if ($this->is_valid_file_object($file_name)) {
201 $file = new \stdClass();
202 $file->name = $file_name;
203 $file->size = $this->get_file_size(
204 $this->get_upload_path($file_name)
206 $file->url = $this->get_download_url($file->name);
207 foreach($this->options['image_versions'] as $version => $options) {
208 if (!empty($version)) {
209 if (is_file($this->get_upload_path($file_name, $version))) {
210 $file->{$version.'_url'} = $this->get_download_url(
217 $this->set_file_delete_properties($file);
223 protected function get_file_objects($iteration_method = 'get_file_object') {
224 $upload_dir = $this->get_upload_path();
225 if (!is_dir($upload_dir)) {
226 mkdir($upload_dir, $this->options['mkdir_mode']);
228 return array_values(array_filter(array_map(
229 array($this, $iteration_method),
234 protected function count_file_objects() {
235 return count($this->get_file_objects('is_valid_file_object'));
238 protected function create_scaled_image($file_name, $version, $options) {
239 $file_path = $this->get_upload_path($file_name);
240 if (!empty($version)) {
241 $version_dir = $this->get_upload_path(null, $version);
242 if (!is_dir($version_dir)) {
243 mkdir($version_dir, $this->options['mkdir_mode']);
245 $new_file_path = $version_dir.'/'.$file_name;
247 $new_file_path = $file_path;
249 list($img_width, $img_height) = @getimagesize($file_path);
250 if (!$img_width || !$img_height) {
254 $options['max_width'] / $img_width,
255 $options['max_height'] / $img_height
258 if ($file_path !== $new_file_path) {
259 return copy($file_path, $new_file_path);
263 $new_width = $img_width * $scale;
264 $new_height = $img_height * $scale;
265 $new_img = @imagecreatetruecolor($new_width, $new_height);
266 switch (strtolower(substr(strrchr($file_name, '.'), 1))) {
269 $src_img = @imagecreatefromjpeg($file_path);
270 $write_image = 'imagejpeg';
271 $image_quality = isset($options['jpeg_quality']) ?
272 $options['jpeg_quality'] : 75;
275 @imagecolortransparent($new_img, @imagecolorallocate($new_img, 0, 0, 0));
276 $src_img = @imagecreatefromgif($file_path);
277 $write_image = 'imagegif';
278 $image_quality = null;
281 @imagecolortransparent($new_img, @imagecolorallocate($new_img, 0, 0, 0));
282 @imagealphablending($new_img, false);
283 @imagesavealpha($new_img, true);
284 $src_img = @imagecreatefrompng($file_path);
285 $write_image = 'imagepng';
286 $image_quality = isset($options['png_quality']) ?
287 $options['png_quality'] : 9;
292 $success = $src_img && @imagecopyresampled(
300 ) && $write_image($new_img, $new_file_path, $image_quality);
301 // Free up memory (imagedestroy does not delete files):
302 @imagedestroy($src_img);
303 @imagedestroy($new_img);
307 protected function get_error_message($error) {
308 return array_key_exists($error, $this->error_messages) ?
309 $this->error_messages[$error] : $error;
312 function get_config_bytes($val) {
314 $last = strtolower($val[strlen($val)-1]);
323 return $this->fix_integer_overflow($val);
326 protected function validate($uploaded_file, $file, $error, $index) {
328 $file->error = $this->get_error_message($error);
331 $content_length = $this->fix_integer_overflow(intval($_SERVER['CONTENT_LENGTH']));
332 if ($content_length > $this->get_config_bytes(ini_get('post_max_size'))) {
333 $file->error = $this->get_error_message('post_max_size');
336 if (!preg_match($this->options['accept_file_types'], $file->name)) {
337 $file->error = $this->get_error_message('accept_file_types');
340 if ($uploaded_file && is_uploaded_file($uploaded_file)) {
341 $file_size = $this->get_file_size($uploaded_file);
343 $file_size = $content_length;
345 if ($this->options['max_file_size'] && (
346 $file_size > $this->options['max_file_size'] ||
347 $file->size > $this->options['max_file_size'])
349 $file->error = $this->get_error_message('max_file_size');
352 if ($this->options['min_file_size'] &&
353 $file_size < $this->options['min_file_size']) {
354 $file->error = $this->get_error_message('min_file_size');
357 if (is_int($this->options['max_number_of_files']) && (
358 $this->count_file_objects() >= $this->options['max_number_of_files'])
360 $file->error = $this->get_error_message('max_number_of_files');
363 list($img_width, $img_height) = @getimagesize($uploaded_file);
364 if (is_int($img_width)) {
365 if ($this->options['max_width'] && $img_width > $this->options['max_width']) {
366 $file->error = $this->get_error_message('max_width');
369 if ($this->options['max_height'] && $img_height > $this->options['max_height']) {
370 $file->error = $this->get_error_message('max_height');
373 if ($this->options['min_width'] && $img_width < $this->options['min_width']) {
374 $file->error = $this->get_error_message('min_width');
377 if ($this->options['min_height'] && $img_height < $this->options['min_height']) {
378 $file->error = $this->get_error_message('min_height');
385 protected function upcount_name_callback($matches) {
386 $index = isset($matches[1]) ? intval($matches[1]) + 1 : 1;
387 $ext = isset($matches[2]) ? $matches[2] : '';
388 return ' ('.$index.')'.$ext;
391 protected function upcount_name($name) {
392 return preg_replace_callback(
393 '/(?:(?: \(([\d]+)\))?(\.[^.]+))?$/',
394 array($this, 'upcount_name_callback'),
400 protected function trim_file_name($name, $type, $index, $content_range) {
401 // Remove path information and dots around the filename, to prevent uploading
402 // into different directories or replacing hidden system files.
403 // Also remove control characters and spaces (\x00..\x20) around the filename:
404 $file_name = trim(basename(stripslashes($name)), ".\x00..\x20");
405 // Add missing file extension for known image types:
406 if (strpos($file_name, '.') === false &&
407 preg_match('/^image\/(gif|jpe?g|png)/', $type, $matches)) {
408 $file_name .= '.'.$matches[1];
410 while(is_dir($this->get_upload_path($file_name))) {
411 $file_name = $this->upcount_name($file_name);
413 $uploaded_bytes = $this->fix_integer_overflow(intval($content_range[1]));
414 while(is_file($this->get_upload_path($file_name))) {
415 if ($uploaded_bytes === $this->get_file_size(
416 $this->get_upload_path($file_name))) {
419 $file_name = $this->upcount_name($file_name);
424 protected function handle_form_data($file, $index) {
425 // Handle form data, e.g. $_REQUEST['description'][$index]
428 protected function orient_image($file_path) {
429 $exif = @exif_read_data($file_path);
430 if ($exif === false) {
433 $orientation = intval(@$exif['Orientation']);
434 if (!in_array($orientation, array(3, 6, 8))) {
437 $image = @imagecreatefromjpeg($file_path);
438 switch ($orientation) {
440 $image = @imagerotate($image, 180, 0);
443 $image = @imagerotate($image, 270, 0);
446 $image = @imagerotate($image, 90, 0);
451 $success = imagejpeg($image, $file_path);
452 // Free up memory (imagedestroy does not delete files):
453 @imagedestroy($image);
457 protected function handle_file_upload($uploaded_file, $name, $size, $type, $error,
458 $index = null, $content_range = null) {
459 $file = new \stdClass();
460 $file->name = $this->trim_file_name($name, $type, $index, $content_range);
461 $file->size = $this->fix_integer_overflow(intval($size));
463 $em = \Utility\Registry::getEntityManager();
464 $oDocument = new \Utility\Entity\Document();
465 $oDocument->filename = $file->name;
466 $oDocument->mimeType = $type;
467 $em->persist($oDocument);
469 $parts = explode('.', $file->name);
470 $file->name = $oDocument->id . '.' . array_pop($parts);
471 $oDocument->filename = $file->name;
473 if ($this->validate($uploaded_file, $file, $error, $index)) {
474 $this->handle_form_data($file, $index);
475 $upload_dir = $this->get_upload_path();
476 if (!is_dir($upload_dir)) {
477 mkdir($upload_dir, $this->options['mkdir_mode']);
479 $file_path = $this->get_upload_path($file->name);
480 $append_file = $content_range && is_file($file_path) &&
481 $file->size > $this->get_file_size($file_path);
482 if ($uploaded_file && is_uploaded_file($uploaded_file)) {
483 // multipart/formdata uploads (POST method uploads)
484 if (file_exists($file_path))
491 fopen($uploaded_file, 'r'),
495 move_uploaded_file($uploaded_file, $file_path);
498 // Non-multipart uploads (PUT method support)
501 fopen('php://input', 'r'),
502 $append_file ? FILE_APPEND : 0
505 $file_size = $this->get_file_size($file_path, $append_file);
506 //if ($file_size === $file->size) {
508 if ($this->options['orient_image']) {
509 $this->orient_image($file_path);
511 $file->url = $this->get_download_url($file->name);
512 $file->id = $oDocument->id;
513 $file->name = $oDocument->filename;
514 } else if (!$content_range && $this->options['discard_aborted_uploads']) {
516 $file->error = 'abort';
518 $file->size = $file_size;
519 $this->set_file_delete_properties($file);
524 protected function generate_response($content, $print_response = true) {
525 if ($print_response) {
526 $json = json_encode($content);
527 $redirect = isset($_REQUEST['redirect']) ?
528 stripslashes($_REQUEST['redirect']) : null;
530 header('Location: '.sprintf($redirect, rawurlencode($json)));
534 if (isset($_SERVER['HTTP_CONTENT_RANGE']) && is_array($content) &&
535 is_object($content[0]) && $content[0]->size) {
536 header('Range: 0-'.($this->fix_integer_overflow(intval($content[0]->size)) - 1));
543 protected function get_version_param() {
544 return isset($_GET['version']) ? basename(stripslashes($_GET['version'])) : null;
547 protected function get_file_name_param() {
548 return isset($_GET['file']) ? basename(stripslashes($_GET['file'])) : null;
551 protected function get_file_type($file_path) {
552 switch (strtolower(pathinfo($file_path, PATHINFO_EXTENSION))) {
565 protected function download() {
566 if (!$this->options['download_via_php']) {
567 header('HTTP/1.1 403 Forbidden');
570 $file_name = $this->get_file_name_param();
571 if ($this->is_valid_file_object($file_name)) {
572 $file_path = $this->get_upload_path($file_name, $this->get_version_param());
573 if (is_file($file_path)) {
574 if (!preg_match($this->options['inline_file_types'], $file_name)) {
575 header('Content-Description: File Transfer');
576 header('Content-Type: application/octet-stream');
577 header('Content-Disposition: attachment; filename="'.$file_name.'"');
578 header('Content-Transfer-Encoding: binary');
580 // Prevent Internet Explorer from MIME-sniffing the content-type:
581 header('X-Content-Type-Options: nosniff');
582 header('Content-Type: '.$this->get_file_type($file_path));
583 header('Content-Disposition: inline; filename="'.$file_name.'"');
585 header('Content-Length: '.$this->get_file_size($file_path));
586 header('Last-Modified: '.gmdate('D, d M Y H:i:s T', filemtime($file_path)));
587 readfile($file_path);
592 protected function send_content_type_header() {
593 header('Vary: Accept');
594 if (isset($_SERVER['HTTP_ACCEPT']) &&
595 (strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false)) {
596 header('Content-type: application/json');
598 header('Content-type: text/plain');
602 protected function send_access_control_headers() {
603 header('Access-Control-Allow-Origin: '.$this->options['access_control_allow_origin']);
604 header('Access-Control-Allow-Credentials: '
605 .($this->options['access_control_allow_credentials'] ? 'true' : 'false'));
606 header('Access-Control-Allow-Methods: '
607 .implode(', ', $this->options['access_control_allow_methods']));
608 header('Access-Control-Allow-Headers: '
609 .implode(', ', $this->options['access_control_allow_headers']));
612 public function head() {
613 header('Pragma: no-cache');
614 header('Cache-Control: no-store, no-cache, must-revalidate');
615 header('Content-Disposition: inline; filename="files.json"');
616 // Prevent Internet Explorer from MIME-sniffing the content-type:
617 header('X-Content-Type-Options: nosniff');
618 if ($this->options['access_control_allow_origin']) {
619 $this->send_access_control_headers();
621 $this->send_content_type_header();
624 public function get($print_response = true) {
625 if ($print_response && isset($_GET['download'])) {
626 return $this->download();
628 $file_name = $this->get_file_name_param();
630 $info = $this->get_file_object($file_name);
632 $info = $this->get_file_objects();
634 return $this->generate_response($info, $print_response);
637 public function post($print_response = true) {
638 if (isset($_REQUEST['_method']) && $_REQUEST['_method'] === 'DELETE') {
639 return $this->delete($print_response);
641 $upload = isset($_FILES[$this->options['param_name']]) ?
642 $_FILES[$this->options['param_name']] : null;
643 // Parse the Content-Disposition header, if available:
644 $file_name = isset($_SERVER['HTTP_CONTENT_DISPOSITION']) ?
645 rawurldecode(preg_replace(
648 $_SERVER['HTTP_CONTENT_DISPOSITION']
650 $file_type = isset($_SERVER['HTTP_CONTENT_DESCRIPTION']) ?
651 $_SERVER['HTTP_CONTENT_DESCRIPTION'] : null;
652 // Parse the Content-Range header, which has the following form:
653 // Content-Range: bytes 0-524287/2000000
654 $content_range = isset($_SERVER['HTTP_CONTENT_RANGE']) ?
655 preg_split('/[^0-9]+/', $_SERVER['HTTP_CONTENT_RANGE']) : null;
656 $size = $content_range ? $content_range[3] : null;
658 if ($upload && is_array($upload['tmp_name'])) {
659 // param_name is an array identifier like "files[]",
660 // $_FILES is a multi-dimensional array:
661 foreach ($upload['tmp_name'] as $index => $value) {
662 $info[] = $this->handle_file_upload(
663 $upload['tmp_name'][$index],
664 $file_name ? $file_name : $upload['name'][$index],
665 $size ? $size : $upload['size'][$index],
666 $file_type ? $file_type : $upload['type'][$index],
667 $upload['error'][$index],
673 // param_name is a single object identifier like "file",
674 // $_FILES is a one-dimensional array:
675 $info[] = $this->handle_file_upload(
676 isset($upload['tmp_name']) ? $upload['tmp_name'] : null,
677 $file_name ? $file_name : (isset($upload['name']) ?
678 $upload['name'] : null),
679 $size ? $size : (isset($upload['size']) ?
680 $upload['size'] : $_SERVER['CONTENT_LENGTH']),
681 $file_type ? $file_type : (isset($upload['type']) ?
682 $upload['type'] : $_SERVER['CONTENT_TYPE']),
683 isset($upload['error']) ? $upload['error'] : null,
688 return $this->generate_response($info, $print_response);
691 public function delete($print_response = true) {
692 $file_name = $this->get_file_name_param();
693 $file_path = $this->get_upload_path($file_name);
694 $success = is_file($file_path) && $file_name[0] !== '.' && unlink($file_path);
696 foreach($this->options['image_versions'] as $version => $options) {
697 if (!empty($version)) {
698 $file = $this->get_upload_path($file_name, $version);
699 if (is_file($file)) {
705 return $this->generate_response($success, $print_response);