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',
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|doc|docx|jpe?g|png|tiff)$/i',
72 // Defines which files (based on their names) are accepted for upload:
73 'accept_file_types' => '/\.(pdf|doc|docx|jpe?g|png|tiff)$/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' => '10000000',
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 if ($this->validate($uploaded_file, $file, $error, $index)) {
464 $this->handle_form_data($file, $index);
465 $upload_dir = $this->get_upload_path();
466 if (!is_dir($upload_dir)) {
467 mkdir($upload_dir, $this->options['mkdir_mode']);
469 $file_path = $this->get_upload_path($file->name);
470 $append_file = $content_range && is_file($file_path) &&
471 $file->size > $this->get_file_size($file_path);
472 if ($uploaded_file && is_uploaded_file($uploaded_file)) {
473 // multipart/formdata uploads (POST method uploads)
474 if (file_exists($file_path))
481 fopen($uploaded_file, 'r'),
485 move_uploaded_file($uploaded_file, $file_path);
488 // Non-multipart uploads (PUT method support)
491 fopen('php://input', 'r'),
492 $append_file ? FILE_APPEND : 0
495 $file_size = $this->get_file_size($file_path, $append_file);
496 //if ($file_size === $file->size) {
498 if ($this->options['orient_image']) {
499 $this->orient_image($file_path);
501 $file->url = $this->get_download_url($file->name);
502 $em = \Utility\Registry::getEntityManager();
503 $oAttachment = new \Utility\Entity\Attachment();
504 $parts = explode('/', $file_path);
505 $oAttachment->filename = array_pop($parts);
506 $oAttachment->mimeType = $type;
507 $em->persist($oAttachment);
509 $file->id = $oAttachment->id;
510 } else if (!$content_range && $this->options['discard_aborted_uploads']) {
512 $file->error = 'abort';
514 $file->size = $file_size;
515 $this->set_file_delete_properties($file);
520 protected function generate_response($content, $print_response = true) {
521 if ($print_response) {
522 $json = json_encode($content);
523 $redirect = isset($_REQUEST['redirect']) ?
524 stripslashes($_REQUEST['redirect']) : null;
526 header('Location: '.sprintf($redirect, rawurlencode($json)));
530 if (isset($_SERVER['HTTP_CONTENT_RANGE']) && is_array($content) &&
531 is_object($content[0]) && $content[0]->size) {
532 header('Range: 0-'.($this->fix_integer_overflow(intval($content[0]->size)) - 1));
539 protected function get_version_param() {
540 return isset($_GET['version']) ? basename(stripslashes($_GET['version'])) : null;
543 protected function get_file_name_param() {
544 return isset($_GET['file']) ? basename(stripslashes($_GET['file'])) : null;
547 protected function get_file_type($file_path) {
548 switch (strtolower(pathinfo($file_path, PATHINFO_EXTENSION))) {
561 protected function download() {
562 if (!$this->options['download_via_php']) {
563 header('HTTP/1.1 403 Forbidden');
566 $file_name = $this->get_file_name_param();
567 if ($this->is_valid_file_object($file_name)) {
568 $file_path = $this->get_upload_path($file_name, $this->get_version_param());
569 if (is_file($file_path)) {
570 if (!preg_match($this->options['inline_file_types'], $file_name)) {
571 header('Content-Description: File Transfer');
572 header('Content-Type: application/octet-stream');
573 header('Content-Disposition: attachment; filename="'.$file_name.'"');
574 header('Content-Transfer-Encoding: binary');
576 // Prevent Internet Explorer from MIME-sniffing the content-type:
577 header('X-Content-Type-Options: nosniff');
578 header('Content-Type: '.$this->get_file_type($file_path));
579 header('Content-Disposition: inline; filename="'.$file_name.'"');
581 header('Content-Length: '.$this->get_file_size($file_path));
582 header('Last-Modified: '.gmdate('D, d M Y H:i:s T', filemtime($file_path)));
583 readfile($file_path);
588 protected function send_content_type_header() {
589 header('Vary: Accept');
590 if (isset($_SERVER['HTTP_ACCEPT']) &&
591 (strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false)) {
592 header('Content-type: application/json');
594 header('Content-type: text/plain');
598 protected function send_access_control_headers() {
599 header('Access-Control-Allow-Origin: '.$this->options['access_control_allow_origin']);
600 header('Access-Control-Allow-Credentials: '
601 .($this->options['access_control_allow_credentials'] ? 'true' : 'false'));
602 header('Access-Control-Allow-Methods: '
603 .implode(', ', $this->options['access_control_allow_methods']));
604 header('Access-Control-Allow-Headers: '
605 .implode(', ', $this->options['access_control_allow_headers']));
608 public function head() {
609 header('Pragma: no-cache');
610 header('Cache-Control: no-store, no-cache, must-revalidate');
611 header('Content-Disposition: inline; filename="files.json"');
612 // Prevent Internet Explorer from MIME-sniffing the content-type:
613 header('X-Content-Type-Options: nosniff');
614 if ($this->options['access_control_allow_origin']) {
615 $this->send_access_control_headers();
617 $this->send_content_type_header();
620 public function get($print_response = true) {
621 if ($print_response && isset($_GET['download'])) {
622 return $this->download();
624 $file_name = $this->get_file_name_param();
626 $info = $this->get_file_object($file_name);
628 $info = $this->get_file_objects();
630 return $this->generate_response($info, $print_response);
633 public function post($print_response = true) {
634 if (isset($_REQUEST['_method']) && $_REQUEST['_method'] === 'DELETE') {
635 return $this->delete($print_response);
637 $upload = isset($_FILES[$this->options['param_name']]) ?
638 $_FILES[$this->options['param_name']] : null;
639 // Parse the Content-Disposition header, if available:
640 $file_name = isset($_SERVER['HTTP_CONTENT_DISPOSITION']) ?
641 rawurldecode(preg_replace(
644 $_SERVER['HTTP_CONTENT_DISPOSITION']
646 $file_type = isset($_SERVER['HTTP_CONTENT_DESCRIPTION']) ?
647 $_SERVER['HTTP_CONTENT_DESCRIPTION'] : null;
648 // Parse the Content-Range header, which has the following form:
649 // Content-Range: bytes 0-524287/2000000
650 $content_range = isset($_SERVER['HTTP_CONTENT_RANGE']) ?
651 preg_split('/[^0-9]+/', $_SERVER['HTTP_CONTENT_RANGE']) : null;
652 $size = $content_range ? $content_range[3] : null;
654 if ($upload && is_array($upload['tmp_name'])) {
655 // param_name is an array identifier like "files[]",
656 // $_FILES is a multi-dimensional array:
657 foreach ($upload['tmp_name'] as $index => $value) {
658 $info[] = $this->handle_file_upload(
659 $upload['tmp_name'][$index],
660 $file_name ? $file_name : $upload['name'][$index],
661 $size ? $size : $upload['size'][$index],
662 $file_type ? $file_type : $upload['type'][$index],
663 $upload['error'][$index],
669 // param_name is a single object identifier like "file",
670 // $_FILES is a one-dimensional array:
671 $info[] = $this->handle_file_upload(
672 isset($upload['tmp_name']) ? $upload['tmp_name'] : null,
673 $file_name ? $file_name : (isset($upload['name']) ?
674 $upload['name'] : null),
675 $size ? $size : (isset($upload['size']) ?
676 $upload['size'] : $_SERVER['CONTENT_LENGTH']),
677 $file_type ? $file_type : (isset($upload['type']) ?
678 $upload['type'] : $_SERVER['CONTENT_TYPE']),
679 isset($upload['error']) ? $upload['error'] : null,
684 return $this->generate_response($info, $print_response);
687 public function delete($print_response = true) {
688 $file_name = $this->get_file_name_param();
689 $file_path = $this->get_upload_path($file_name);
690 $success = is_file($file_path) && $file_name[0] !== '.' && unlink($file_path);
692 foreach($this->options['image_versions'] as $version => $options) {
693 if (!empty($version)) {
694 $file = $this->get_upload_path($file_name, $version);
695 if (is_file($file)) {
701 return $this->generate_response($success, $print_response);