PageRenderTime 55ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/application/libraries/Uploadhandler.php

https://bitbucket.org/simpfc/shop
PHP | 1330 lines | 1169 code | 65 blank | 96 comment | 188 complexity | d0b8bf60e7319f17eb9b1eab71ea9a59 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /*
  3. * jQuery File Upload Plugin PHP Class 7.1.4
  4. * https://github.com/blueimp/jQuery-File-Upload
  5. *
  6. * Copyright 2010, Sebastian Tschan
  7. * https://blueimp.net
  8. *
  9. * Licensed under the MIT license:
  10. * http://www.opensource.org/licenses/MIT
  11. */
  12. class Uploadhandler
  13. {
  14. protected $options;
  15. // PHP File Upload error message codes:
  16. // http://php.net/manual/en/features.file-upload.errors.php
  17. protected $error_messages = array(
  18. 1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
  19. 2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
  20. 3 => 'The uploaded file was only partially uploaded',
  21. 4 => 'No file was uploaded',
  22. 6 => 'Missing a temporary folder',
  23. 7 => 'Failed to write file to disk',
  24. 8 => 'A PHP extension stopped the file upload',
  25. 'post_max_size' => 'The uploaded file exceeds the post_max_size directive in php.ini',
  26. 'max_file_size' => 'File is too big',
  27. 'min_file_size' => 'File is too small',
  28. 'accept_file_types' => 'Filetype not allowed',
  29. 'max_number_of_files' => 'Maximum number of files exceeded',
  30. 'max_width' => 'Image exceeds maximum width',
  31. 'min_width' => 'Image requires a minimum width',
  32. 'max_height' => 'Image exceeds maximum height',
  33. 'min_height' => 'Image requires a minimum height',
  34. 'abort' => 'File upload aborted',
  35. 'image_resize' => 'Failed to resize image'
  36. );
  37. protected $image_objects = array();
  38. function __construct($options = null, $initialize = true, $error_messages = null) {
  39. $this->options = array(
  40. 'script_url' => $this->get_full_url().'/upload/do_upload',
  41. 'upload_dir' => dirname($this->get_server_var('SCRIPT_FILENAME')).'/files/',
  42. 'upload_url' => $this->get_full_url().'/files/',
  43. 'user_dirs' => false,
  44. 'mkdir_mode' => 0755,
  45. 'param_name' => 'files',
  46. // Set the following option to 'POST', if your server does not support
  47. // DELETE requests. This is a parameter sent to the client:
  48. 'delete_type' => 'DELETE',
  49. 'access_control_allow_origin' => '*',
  50. 'access_control_allow_credentials' => false,
  51. 'access_control_allow_methods' => array(
  52. 'OPTIONS',
  53. 'HEAD',
  54. 'GET',
  55. 'POST',
  56. 'PUT',
  57. 'PATCH',
  58. 'DELETE'
  59. ),
  60. 'access_control_allow_headers' => array(
  61. 'Content-Type',
  62. 'Content-Range',
  63. 'Content-Disposition'
  64. ),
  65. // Enable to provide file downloads via GET requests to the PHP script:
  66. // 1. Set to 1 to download files via readfile method through PHP
  67. // 2. Set to 2 to send a X-Sendfile header for lighttpd/Apache
  68. // 3. Set to 3 to send a X-Accel-Redirect header for nginx
  69. // If set to 2 or 3, adjust the upload_url option to the base path of
  70. // the redirect parameter, e.g. '/files/'.
  71. 'download_via_php' => false,
  72. // Read files in chunks to avoid memory limits when download_via_php
  73. // is enabled, set to 0 to disable chunked reading of files:
  74. 'readfile_chunk_size' => 10 * 1024 * 1024, // 10 MiB
  75. // Defines which files can be displayed inline when downloaded:
  76. 'inline_file_types' => '/\.(gif|jpe?g|png|mp3)$/i',
  77. // Defines which files (based on their names) are accepted for upload:
  78. 'accept_file_types' => '/.+$/i',
  79. // The php.ini settings upload_max_filesize and post_max_size
  80. // take precedence over the following max_file_size setting:
  81. 'max_file_size' => null,
  82. 'min_file_size' => 1,
  83. // The maximum number of files for the upload directory:
  84. 'max_number_of_files' => null,
  85. // Defines which files are handled as image files:
  86. 'image_file_types' => '/\.(gif|jpe?g|png)$/i',
  87. // Image resolution restrictions:
  88. 'max_width' => null,
  89. 'max_height' => null,
  90. 'min_width' => 1,
  91. 'min_height' => 1,
  92. // Set the following option to false to enable resumable uploads:
  93. 'discard_aborted_uploads' => true,
  94. // Set to 0 to use the GD library to scale and orient images,
  95. // set to 1 to use imagick (if installed, falls back to GD),
  96. // set to 2 to use the ImageMagick convert binary directly:
  97. 'image_library' => 1,
  98. // Uncomment the following to define an array of resource limits
  99. // for imagick:
  100. /*
  101. 'imagick_resource_limits' => array(
  102. imagick::RESOURCETYPE_MAP => 32,
  103. imagick::RESOURCETYPE_MEMORY => 32
  104. ),
  105. */
  106. // Command or path for to the ImageMagick convert binary:
  107. 'convert_bin' => 'convert',
  108. // Uncomment the following to add parameters in front of each
  109. // ImageMagick convert call (the limit constraints seem only
  110. // to have an effect if put in front):
  111. /*
  112. 'convert_params' => '-limit memory 32MiB -limit map 32MiB',
  113. */
  114. // Command or path for to the ImageMagick identify binary:
  115. 'identify_bin' => 'identify',
  116. 'image_versions' => array(
  117. // The empty image version key defines options for the original image:
  118. '' => array(
  119. // Automatically rotate images based on EXIF meta data:
  120. 'auto_orient' => true
  121. ),
  122. // Uncomment the following to create medium sized images:
  123. /*
  124. 'medium' => array(
  125. 'max_width' => 800,
  126. 'max_height' => 600
  127. ),
  128. */
  129. 'thumbnail' => array(
  130. // Uncomment the following to use a defined directory for the thumbnails
  131. // instead of a subdirectory based on the version identifier.
  132. // Make sure that this directory doesn't allow execution of files if you
  133. // don't pose any restrictions on the type of uploaded files, e.g. by
  134. // copying the .htaccess file from the files directory for Apache:
  135. //'upload_dir' => dirname($this->get_server_var('SCRIPT_FILENAME')).'/thumb/',
  136. //'upload_url' => $this->get_full_url().'/thumb/',
  137. // Uncomment the following to force the max
  138. // dimensions and e.g. create square thumbnails:
  139. //'crop' => true,
  140. 'max_width' => 80,
  141. 'max_height' => 80
  142. )
  143. )
  144. );
  145. if ($options) {
  146. $this->options = $options + $this->options;
  147. }
  148. if ($error_messages) {
  149. $this->error_messages = $error_messages + $this->error_messages;
  150. }
  151. if ($initialize) {
  152. $this->initialize();
  153. }
  154. }
  155. protected function initialize() {
  156. switch ($this->get_server_var('REQUEST_METHOD')) {
  157. case 'OPTIONS':
  158. case 'HEAD':
  159. $this->head();
  160. break;
  161. case 'GET':
  162. $this->get();
  163. break;
  164. case 'PATCH':
  165. case 'PUT':
  166. case 'POST':
  167. $this->post();
  168. break;
  169. case 'DELETE':
  170. $this->delete();
  171. break;
  172. default:
  173. $this->header('HTTP/1.1 405 Method Not Allowed');
  174. }
  175. }
  176. protected function get_full_url() {
  177. $https = !empty($_SERVER['HTTPS']) && strcasecmp($_SERVER['HTTPS'], 'on') === 0;
  178. return
  179. ($https ? 'https://' : 'http://').
  180. (!empty($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'].'@' : '').
  181. (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME'].
  182. ($https && $_SERVER['SERVER_PORT'] === 443 ||
  183. $_SERVER['SERVER_PORT'] === 80 ? '' : ':'.$_SERVER['SERVER_PORT']))).
  184. substr($_SERVER['SCRIPT_NAME'],0, strrpos($_SERVER['SCRIPT_NAME'], '/'));
  185. }
  186. protected function get_user_id() {
  187. @session_start();
  188. return session_id();
  189. }
  190. protected function get_user_path() {
  191. if ($this->options['user_dirs']) {
  192. return $this->get_user_id().'/';
  193. }
  194. return '';
  195. }
  196. protected function get_upload_path($file_name = null, $version = null) {
  197. $file_name = $file_name ? $file_name : '';
  198. if (empty($version)) {
  199. $version_path = '';
  200. } else {
  201. $version_dir = @$this->options['image_versions'][$version]['upload_dir'];
  202. if ($version_dir) {
  203. return $version_dir.$this->get_user_path().$file_name;
  204. }
  205. $version_path = $version.'/';
  206. }
  207. return $this->options['upload_dir'].$this->get_user_path()
  208. .$version_path.$file_name;
  209. }
  210. protected function get_query_separator($url) {
  211. return strpos($url, '?') === false ? '?' : '&';
  212. }
  213. protected function get_download_url($file_name, $version = null, $direct = false) {
  214. if (!$direct && $this->options['download_via_php']) {
  215. $url = $this->options['script_url']
  216. .$this->get_query_separator($this->options['script_url'])
  217. .$this->get_singular_param_name()
  218. .'='.rawurlencode($file_name);
  219. if ($version) {
  220. $url .= '&version='.rawurlencode($version);
  221. }
  222. return $url.'&download=1';
  223. }
  224. if (empty($version)) {
  225. $version_path = '';
  226. } else {
  227. $version_url = @$this->options['image_versions'][$version]['upload_url'];
  228. if ($version_url) {
  229. return $version_url.$this->get_user_path().rawurlencode($file_name);
  230. }
  231. $version_path = rawurlencode($version).'/';
  232. }
  233. return $this->options['upload_url'].$this->get_user_path()
  234. .$version_path.rawurlencode($file_name);
  235. }
  236. protected function set_additional_file_properties($file) {
  237. $file->deleteUrl = $this->options['script_url']
  238. .$this->get_query_separator($this->options['script_url'])
  239. .$this->get_singular_param_name()
  240. .'='.rawurlencode($file->name);
  241. $file->deleteType = $this->options['delete_type'];
  242. if ($file->deleteType !== 'DELETE') {
  243. $file->deleteUrl .= '&_method=DELETE';
  244. }
  245. if ($this->options['access_control_allow_credentials']) {
  246. $file->deleteWithCredentials = true;
  247. }
  248. }
  249. // Fix for overflowing signed 32 bit integers,
  250. // works for sizes up to 2^32-1 bytes (4 GiB - 1):
  251. protected function fix_integer_overflow($size) {
  252. if ($size < 0) {
  253. $size += 2.0 * (PHP_INT_MAX + 1);
  254. }
  255. return $size;
  256. }
  257. protected function get_file_size($file_path, $clear_stat_cache = false) {
  258. if ($clear_stat_cache) {
  259. if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
  260. clearstatcache(true, $file_path);
  261. } else {
  262. clearstatcache();
  263. }
  264. }
  265. return $this->fix_integer_overflow(filesize($file_path));
  266. }
  267. protected function is_valid_file_object($file_name) {
  268. $file_path = $this->get_upload_path($file_name);
  269. if (is_file($file_path) && $file_name[0] !== '.') {
  270. return true;
  271. }
  272. return false;
  273. }
  274. protected function get_file_object($file_name) {
  275. if ($this->is_valid_file_object($file_name)) {
  276. $file = new stdClass();
  277. $file->name = $file_name;
  278. $file->size = $this->get_file_size(
  279. $this->get_upload_path($file_name)
  280. );
  281. $file->url = $this->get_download_url($file->name);
  282. foreach($this->options['image_versions'] as $version => $options) {
  283. if (!empty($version)) {
  284. if (is_file($this->get_upload_path($file_name, $version))) {
  285. $file->{$version.'Url'} = $this->get_download_url(
  286. $file->name,
  287. $version
  288. );
  289. }
  290. }
  291. }
  292. $this->set_additional_file_properties($file);
  293. return $file;
  294. }
  295. return null;
  296. }
  297. protected function get_file_objects($iteration_method = 'get_file_object') {
  298. $upload_dir = $this->get_upload_path();
  299. if (!is_dir($upload_dir)) {
  300. return array();
  301. }
  302. return array_values(array_filter(array_map(
  303. array($this, $iteration_method),
  304. scandir($upload_dir)
  305. )));
  306. }
  307. protected function count_file_objects() {
  308. return count($this->get_file_objects('is_valid_file_object'));
  309. }
  310. protected function get_error_message($error) {
  311. return array_key_exists($error, $this->error_messages) ?
  312. $this->error_messages[$error] : $error;
  313. }
  314. function get_config_bytes($val) {
  315. $val = trim($val);
  316. $last = strtolower($val[strlen($val)-1]);
  317. switch($last) {
  318. case 'g':
  319. $val *= 1024;
  320. case 'm':
  321. $val *= 1024;
  322. case 'k':
  323. $val *= 1024;
  324. }
  325. return $this->fix_integer_overflow($val);
  326. }
  327. protected function validate($uploaded_file, $file, $error, $index) {
  328. if ($error) {
  329. $file->error = $this->get_error_message($error);
  330. return false;
  331. }
  332. $content_length = $this->fix_integer_overflow(intval(
  333. $this->get_server_var('CONTENT_LENGTH')
  334. ));
  335. $post_max_size = $this->get_config_bytes(ini_get('post_max_size'));
  336. if ($post_max_size && ($content_length > $post_max_size)) {
  337. $file->error = $this->get_error_message('post_max_size');
  338. return false;
  339. }
  340. if (!preg_match($this->options['accept_file_types'], $file->name)) {
  341. $file->error = $this->get_error_message('accept_file_types');
  342. return false;
  343. }
  344. if ($uploaded_file && is_uploaded_file($uploaded_file)) {
  345. $file_size = $this->get_file_size($uploaded_file);
  346. } else {
  347. $file_size = $content_length;
  348. }
  349. if ($this->options['max_file_size'] && (
  350. $file_size > $this->options['max_file_size'] ||
  351. $file->size > $this->options['max_file_size'])
  352. ) {
  353. $file->error = $this->get_error_message('max_file_size');
  354. return false;
  355. }
  356. if ($this->options['min_file_size'] &&
  357. $file_size < $this->options['min_file_size']) {
  358. $file->error = $this->get_error_message('min_file_size');
  359. return false;
  360. }
  361. if (is_int($this->options['max_number_of_files']) &&
  362. ($this->count_file_objects() >= $this->options['max_number_of_files']) &&
  363. // Ignore additional chunks of existing files:
  364. !is_file($this->get_upload_path($file->name))) {
  365. $file->error = $this->get_error_message('max_number_of_files');
  366. return false;
  367. }
  368. $max_width = @$this->options['max_width'];
  369. $max_height = @$this->options['max_height'];
  370. $min_width = @$this->options['min_width'];
  371. $min_height = @$this->options['min_height'];
  372. if (($max_width || $max_height || $min_width || $min_height)) {
  373. list($img_width, $img_height) = $this->get_image_size($uploaded_file);
  374. }
  375. if (!empty($img_width)) {
  376. if ($max_width && $img_width > $max_width) {
  377. $file->error = $this->get_error_message('max_width');
  378. return false;
  379. }
  380. if ($max_height && $img_height > $max_height) {
  381. $file->error = $this->get_error_message('max_height');
  382. return false;
  383. }
  384. if ($min_width && $img_width < $min_width) {
  385. $file->error = $this->get_error_message('min_width');
  386. return false;
  387. }
  388. if ($min_height && $img_height < $min_height) {
  389. $file->error = $this->get_error_message('min_height');
  390. return false;
  391. }
  392. }
  393. return true;
  394. }
  395. protected function upcount_name_callback($matches) {
  396. $index = isset($matches[1]) ? intval($matches[1]) + 1 : 1;
  397. $ext = isset($matches[2]) ? $matches[2] : '';
  398. return ' ('.$index.')'.$ext;
  399. }
  400. protected function upcount_name($name) {
  401. return preg_replace_callback(
  402. '/(?:(?: \(([\d]+)\))?(\.[^.]+))?$/',
  403. array($this, 'upcount_name_callback'),
  404. $name,
  405. 1
  406. );
  407. }
  408. protected function get_unique_filename($file_path, $name, $size, $type, $error,
  409. $index, $content_range) {
  410. while(is_dir($this->get_upload_path($name))) {
  411. $name = $this->upcount_name($name);
  412. }
  413. // Keep an existing filename if this is part of a chunked upload:
  414. $uploaded_bytes = $this->fix_integer_overflow(intval($content_range[1]));
  415. while(is_file($this->get_upload_path($name))) {
  416. if ($uploaded_bytes === $this->get_file_size(
  417. $this->get_upload_path($name))) {
  418. break;
  419. }
  420. $name = $this->upcount_name($name);
  421. }
  422. return $name;
  423. }
  424. protected function trim_file_name($file_path, $name, $size, $type, $error,
  425. $index, $content_range) {
  426. // Remove path information and dots around the filename, to prevent uploading
  427. // into different directories or replacing hidden system files.
  428. // Also remove control characters and spaces (\x00..\x20) around the filename:
  429. $name = trim(basename(stripslashes($name)), ".\x00..\x20");
  430. // Use a timestamp for empty filenames:
  431. if (!$name) {
  432. $name = str_replace('.', '-', microtime(true));
  433. }
  434. // Add missing file extension for known image types:
  435. if (strpos($name, '.') === false &&
  436. preg_match('/^image\/(gif|jpe?g|png)/', $type, $matches)) {
  437. $name .= '.'.$matches[1];
  438. }
  439. if (function_exists('exif_imagetype')) {
  440. switch(@exif_imagetype($file_path)){
  441. case IMAGETYPE_JPEG:
  442. $extensions = array('jpg', 'jpeg');
  443. break;
  444. case IMAGETYPE_PNG:
  445. $extensions = array('png');
  446. break;
  447. case IMAGETYPE_GIF:
  448. $extensions = array('gif');
  449. break;
  450. }
  451. // Adjust incorrect image file extensions:
  452. if (!empty($extensions)) {
  453. $parts = explode('.', $name);
  454. $extIndex = count($parts) - 1;
  455. $ext = strtolower(@$parts[$extIndex]);
  456. if (!in_array($ext, $extensions)) {
  457. $parts[$extIndex] = $extensions[0];
  458. $name = implode('.', $parts);
  459. }
  460. }
  461. }
  462. return $name;
  463. }
  464. protected function get_file_name($file_path, $name, $size, $type, $error,
  465. $index, $content_range) {
  466. return $this->get_unique_filename(
  467. $file_path,
  468. $this->trim_file_name($file_path, $name, $size, $type, $error,
  469. $index, $content_range),
  470. $size,
  471. $type,
  472. $error,
  473. $index,
  474. $content_range
  475. );
  476. }
  477. protected function handle_form_data($file, $index) {
  478. // Handle form data, e.g. $_REQUEST['description'][$index]
  479. }
  480. protected function get_scaled_image_file_paths($file_name, $version) {
  481. $file_path = $this->get_upload_path($file_name);
  482. if (!empty($version)) {
  483. $version_dir = $this->get_upload_path(null, $version);
  484. if (!is_dir($version_dir)) {
  485. mkdir($version_dir, $this->options['mkdir_mode'], true);
  486. }
  487. $new_file_path = $version_dir.'/'.$file_name;
  488. } else {
  489. $new_file_path = $file_path;
  490. }
  491. return array($file_path, $new_file_path);
  492. }
  493. protected function gd_get_image_object($file_path, $func, $no_cache = false) {
  494. if (empty($this->image_objects[$file_path]) || $no_cache) {
  495. $this->gd_destroy_image_object($file_path);
  496. $this->image_objects[$file_path] = $func($file_path);
  497. }
  498. return $this->image_objects[$file_path];
  499. }
  500. protected function gd_set_image_object($file_path, $image) {
  501. $this->gd_destroy_image_object($file_path);
  502. $this->image_objects[$file_path] = $image;
  503. }
  504. protected function gd_destroy_image_object($file_path) {
  505. $image = @$this->image_objects[$file_path];
  506. return $image && imagedestroy($image);
  507. }
  508. protected function gd_imageflip($image, $mode) {
  509. if (function_exists('imageflip')) {
  510. return imageflip($image, $mode);
  511. }
  512. $new_width = $src_width = imagesx($image);
  513. $new_height = $src_height = imagesy($image);
  514. $new_img = imagecreatetruecolor($new_width, $new_height);
  515. $src_x = 0;
  516. $src_y = 0;
  517. switch ($mode) {
  518. case '1': // flip on the horizontal axis
  519. $src_y = $new_height - 1;
  520. $src_height = -$new_height;
  521. break;
  522. case '2': // flip on the vertical axis
  523. $src_x = $new_width - 1;
  524. $src_width = -$new_width;
  525. break;
  526. case '3': // flip on both axes
  527. $src_y = $new_height - 1;
  528. $src_height = -$new_height;
  529. $src_x = $new_width - 1;
  530. $src_width = -$new_width;
  531. break;
  532. default:
  533. return $image;
  534. }
  535. imagecopyresampled(
  536. $new_img,
  537. $image,
  538. 0,
  539. 0,
  540. $src_x,
  541. $src_y,
  542. $new_width,
  543. $new_height,
  544. $src_width,
  545. $src_height
  546. );
  547. return $new_img;
  548. }
  549. protected function gd_orient_image($file_path, $src_img) {
  550. if (!function_exists('exif_read_data')) {
  551. return false;
  552. }
  553. $exif = @exif_read_data($file_path);
  554. if ($exif === false) {
  555. return false;
  556. }
  557. $orientation = intval(@$exif['Orientation']);
  558. if ($orientation < 2 || $orientation > 8) {
  559. return false;
  560. }
  561. switch ($orientation) {
  562. case 2:
  563. $new_img = $this->gd_imageflip(
  564. $src_img,
  565. defined('IMG_FLIP_VERTICAL') ? IMG_FLIP_VERTICAL : 2
  566. );
  567. break;
  568. case 3:
  569. $new_img = imagerotate($src_img, 180, 0);
  570. break;
  571. case 4:
  572. $new_img = $this->gd_imageflip(
  573. $src_img,
  574. defined('IMG_FLIP_HORIZONTAL') ? IMG_FLIP_HORIZONTAL : 1
  575. );
  576. break;
  577. case 5:
  578. $tmp_img = $this->gd_imageflip(
  579. $src_img,
  580. defined('IMG_FLIP_HORIZONTAL') ? IMG_FLIP_HORIZONTAL : 1
  581. );
  582. $new_img = imagerotate($tmp_img, 270, 0);
  583. imagedestroy($tmp_img);
  584. break;
  585. case 6:
  586. $new_img = imagerotate($src_img, 270, 0);
  587. break;
  588. case 7:
  589. $tmp_img = $this->gd_imageflip(
  590. $src_img,
  591. defined('IMG_FLIP_VERTICAL') ? IMG_FLIP_VERTICAL : 2
  592. );
  593. $new_img = imagerotate($tmp_img, 270, 0);
  594. imagedestroy($tmp_img);
  595. break;
  596. case 8:
  597. $new_img = imagerotate($src_img, 90, 0);
  598. break;
  599. default:
  600. return false;
  601. }
  602. $this->gd_set_image_object($file_path, $new_img);
  603. return true;
  604. }
  605. protected function gd_create_scaled_image($file_name, $version, $options) {
  606. if (!function_exists('imagecreatetruecolor')) {
  607. error_log('Function not found: imagecreatetruecolor');
  608. return false;
  609. }
  610. list($file_path, $new_file_path) =
  611. $this->get_scaled_image_file_paths($file_name, $version);
  612. $type = strtolower(substr(strrchr($file_name, '.'), 1));
  613. switch ($type) {
  614. case 'jpg':
  615. case 'jpeg':
  616. $src_func = 'imagecreatefromjpeg';
  617. $write_func = 'imagejpeg';
  618. $image_quality = isset($options['jpeg_quality']) ?
  619. $options['jpeg_quality'] : 75;
  620. break;
  621. case 'gif':
  622. $src_func = 'imagecreatefromgif';
  623. $write_func = 'imagegif';
  624. $image_quality = null;
  625. break;
  626. case 'png':
  627. $src_func = 'imagecreatefrompng';
  628. $write_func = 'imagepng';
  629. $image_quality = isset($options['png_quality']) ?
  630. $options['png_quality'] : 9;
  631. break;
  632. default:
  633. return false;
  634. }
  635. $src_img = $this->gd_get_image_object(
  636. $file_path,
  637. $src_func,
  638. !empty($options['no_cache'])
  639. );
  640. $image_oriented = false;
  641. if (!empty($options['auto_orient']) && $this->gd_orient_image(
  642. $file_path,
  643. $src_img
  644. )) {
  645. $image_oriented = true;
  646. $src_img = $this->gd_get_image_object(
  647. $file_path,
  648. $src_func
  649. );
  650. }
  651. $max_width = $img_width = imagesx($src_img);
  652. $max_height = $img_height = imagesy($src_img);
  653. if (!empty($options['max_width'])) {
  654. $max_width = $options['max_width'];
  655. }
  656. if (!empty($options['max_height'])) {
  657. $max_height = $options['max_height'];
  658. }
  659. $scale = min(
  660. $max_width / $img_width,
  661. $max_height / $img_height
  662. );
  663. if ($scale >= 1) {
  664. if ($image_oriented) {
  665. return $write_func($src_img, $new_file_path, $image_quality);
  666. }
  667. if ($file_path !== $new_file_path) {
  668. return copy($file_path, $new_file_path);
  669. }
  670. return true;
  671. }
  672. if (empty($options['crop'])) {
  673. $new_width = $img_width * $scale;
  674. $new_height = $img_height * $scale;
  675. $dst_x = 0;
  676. $dst_y = 0;
  677. $new_img = imagecreatetruecolor($new_width, $new_height);
  678. } else {
  679. if (($img_width / $img_height) >= ($max_width / $max_height)) {
  680. $new_width = $img_width / ($img_height / $max_height);
  681. $new_height = $max_height;
  682. } else {
  683. $new_width = $max_width;
  684. $new_height = $img_height / ($img_width / $max_width);
  685. }
  686. $dst_x = 0 - ($new_width - $max_width) / 2;
  687. $dst_y = 0 - ($new_height - $max_height) / 2;
  688. $new_img = imagecreatetruecolor($max_width, $max_height);
  689. }
  690. // Handle transparency in GIF and PNG images:
  691. switch ($type) {
  692. case 'gif':
  693. case 'png':
  694. imagecolortransparent($new_img, imagecolorallocate($new_img, 0, 0, 0));
  695. case 'png':
  696. imagealphablending($new_img, false);
  697. imagesavealpha($new_img, true);
  698. break;
  699. }
  700. $success = imagecopyresampled(
  701. $new_img,
  702. $src_img,
  703. $dst_x,
  704. $dst_y,
  705. 0,
  706. 0,
  707. $new_width,
  708. $new_height,
  709. $img_width,
  710. $img_height
  711. ) && $write_func($new_img, $new_file_path, $image_quality);
  712. $this->gd_set_image_object($file_path, $new_img);
  713. return $success;
  714. }
  715. protected function imagick_get_image_object($file_path, $no_cache = false) {
  716. if (empty($this->image_objects[$file_path]) || $no_cache) {
  717. $this->imagick_destroy_image_object($file_path);
  718. $image = new Imagick();
  719. if (!empty($this->options['imagick_resource_limits'])) {
  720. foreach ($this->options['imagick_resource_limits'] as $type => $limit) {
  721. $image->setResourceLimit($type, $limit);
  722. }
  723. }
  724. $image->readImage($file_path);
  725. $this->image_objects[$file_path] = $image;
  726. }
  727. return $this->image_objects[$file_path];
  728. }
  729. protected function imagick_set_image_object($file_path, $image) {
  730. $this->imagick_destroy_image_object($file_path);
  731. $this->image_objects[$file_path] = $image;
  732. }
  733. protected function imagick_destroy_image_object($file_path) {
  734. $image = @$this->image_objects[$file_path];
  735. return $image && $image->destroy();
  736. }
  737. protected function imagick_orient_image($image) {
  738. $orientation = $image->getImageOrientation();
  739. $background = new ImagickPixel('none');
  740. switch ($orientation) {
  741. case imagick::ORIENTATION_TOPRIGHT: // 2
  742. $image->flopImage(); // horizontal flop around y-axis
  743. break;
  744. case imagick::ORIENTATION_BOTTOMRIGHT: // 3
  745. $image->rotateImage($background, 180);
  746. break;
  747. case imagick::ORIENTATION_BOTTOMLEFT: // 4
  748. $image->flipImage(); // vertical flip around x-axis
  749. break;
  750. case imagick::ORIENTATION_LEFTTOP: // 5
  751. $image->flopImage(); // horizontal flop around y-axis
  752. $image->rotateImage($background, 270);
  753. break;
  754. case imagick::ORIENTATION_RIGHTTOP: // 6
  755. $image->rotateImage($background, 90);
  756. break;
  757. case imagick::ORIENTATION_RIGHTBOTTOM: // 7
  758. $image->flipImage(); // vertical flip around x-axis
  759. $image->rotateImage($background, 270);
  760. break;
  761. case imagick::ORIENTATION_LEFTBOTTOM: // 8
  762. $image->rotateImage($background, 270);
  763. break;
  764. default:
  765. return false;
  766. }
  767. $image->setImageOrientation(imagick::ORIENTATION_TOPLEFT); // 1
  768. return true;
  769. }
  770. protected function imagick_create_scaled_image($file_name, $version, $options) {
  771. list($file_path, $new_file_path) =
  772. $this->get_scaled_image_file_paths($file_name, $version);
  773. $image = $this->imagick_get_image_object(
  774. $file_path,
  775. !empty($options['no_cache'])
  776. );
  777. if ($image->getImageFormat() === 'GIF') {
  778. // Handle animated GIFs:
  779. $images = $image->coalesceImages();
  780. foreach ($images as $frame) {
  781. $image = $frame;
  782. $this->imagick_set_image_object($file_name, $image);
  783. break;
  784. }
  785. }
  786. $image_oriented = false;
  787. if (!empty($options['auto_orient'])) {
  788. $image_oriented = $this->imagick_orient_image($image);
  789. }
  790. $new_width = $max_width = $img_width = $image->getImageWidth();
  791. $new_height = $max_height = $img_height = $image->getImageHeight();
  792. if (!empty($options['max_width'])) {
  793. $new_width = $max_width = $options['max_width'];
  794. }
  795. if (!empty($options['max_height'])) {
  796. $new_height = $max_height = $options['max_height'];
  797. }
  798. if (!($image_oriented || $max_width < $img_width || $max_height < $img_height)) {
  799. if ($file_path !== $new_file_path) {
  800. return copy($file_path, $new_file_path);
  801. }
  802. return true;
  803. }
  804. $crop = !empty($options['crop']);
  805. if ($crop) {
  806. $x = 0;
  807. $y = 0;
  808. if (($img_width / $img_height) >= ($max_width / $max_height)) {
  809. $new_width = 0; // Enables proportional scaling based on max_height
  810. $x = ($img_width / ($img_height / $max_height) - $max_width) / 2;
  811. } else {
  812. $new_height = 0; // Enables proportional scaling based on max_width
  813. $y = ($img_height / ($img_width / $max_width) - $max_height) / 2;
  814. }
  815. }
  816. $success = $image->resizeImage(
  817. $new_width,
  818. $new_height,
  819. isset($options['filter']) ? $options['filter'] : imagick::FILTER_LANCZOS,
  820. isset($options['blur']) ? $options['blur'] : 1,
  821. $new_width && $new_height // fit image into constraints if not to be cropped
  822. );
  823. if ($success && $crop) {
  824. $success = $image->cropImage(
  825. $max_width,
  826. $max_height,
  827. $x,
  828. $y
  829. );
  830. if ($success) {
  831. $success = $image->setImagePage($max_width, $max_height, 0, 0);
  832. }
  833. }
  834. $type = strtolower(substr(strrchr($file_name, '.'), 1));
  835. switch ($type) {
  836. case 'jpg':
  837. case 'jpeg':
  838. if (!empty($options['jpeg_quality'])) {
  839. $image->setImageCompression(Imagick::COMPRESSION_JPEG);
  840. $image->setImageCompressionQuality($options['jpeg_quality']);
  841. }
  842. break;
  843. }
  844. if (!empty($options['strip'])) {
  845. $image->stripImage();
  846. }
  847. return $success && $image->writeImage($new_file_path);
  848. }
  849. protected function imagemagick_create_scaled_image($file_name, $version, $options) {
  850. list($file_path, $new_file_path) =
  851. $this->get_scaled_image_file_paths($file_name, $version);
  852. $resize = @$options['max_width']
  853. .(empty($options['max_height']) ? '' : 'x'.$options['max_height']);
  854. if (!$resize && empty($options['auto_orient'])) {
  855. if ($file_path !== $new_file_path) {
  856. return copy($file_path, $new_file_path);
  857. }
  858. return true;
  859. }
  860. $cmd = $this->options['convert_bin'];
  861. if (!empty($this->options['convert_params'])) {
  862. $cmd .= ' '.$this->options['convert_params'];
  863. }
  864. $cmd .= ' '.escapeshellarg($file_path);
  865. if (!empty($options['auto_orient'])) {
  866. $cmd .= ' -auto-orient';
  867. }
  868. if ($resize) {
  869. // Handle animated GIFs:
  870. $cmd .= ' -coalesce';
  871. if (empty($options['crop'])) {
  872. $cmd .= ' -resize '.escapeshellarg($resize.'>');
  873. } else {
  874. $cmd .= ' -resize '.escapeshellarg($resize.'^');
  875. $cmd .= ' -gravity center';
  876. $cmd .= ' -crop '.escapeshellarg($resize.'+0+0');
  877. }
  878. // Make sure the page dimensions are correct (fixes offsets of animated GIFs):
  879. $cmd .= ' +repage';
  880. }
  881. if (!empty($options['convert_params'])) {
  882. $cmd .= ' '.$options['convert_params'];
  883. }
  884. $cmd .= ' '.escapeshellarg($new_file_path);
  885. exec($cmd, $output, $error);
  886. if ($error) {
  887. error_log(implode('\n', $output));
  888. return false;
  889. }
  890. return true;
  891. }
  892. protected function get_image_size($file_path) {
  893. if ($this->options['image_library']) {
  894. if (extension_loaded('imagick')) {
  895. $image = new Imagick();
  896. try {
  897. if (@$image->pingImage($file_path)) {
  898. $dimensions = array($image->getImageWidth(), $image->getImageHeight());
  899. $image->destroy();
  900. return $dimensions;
  901. }
  902. return false;
  903. } catch (Exception $e) {
  904. error_log($e->getMessage());
  905. }
  906. }
  907. if ($this->options['image_library'] === 2) {
  908. $cmd = $this->options['identify_bin'];
  909. $cmd .= ' -ping '.escapeshellarg($file_path);
  910. exec($cmd, $output, $error);
  911. if (!$error && !empty($output)) {
  912. // image.jpg JPEG 1920x1080 1920x1080+0+0 8-bit sRGB 465KB 0.000u 0:00.000
  913. $infos = preg_split('/\s+/', $output[0]);
  914. $dimensions = preg_split('/x/', $infos[2]);
  915. return $dimensions;
  916. }
  917. return false;
  918. }
  919. }
  920. if (!function_exists('getimagesize')) {
  921. error_log('Function not found: getimagesize');
  922. return false;
  923. }
  924. return @getimagesize($file_path);
  925. }
  926. protected function create_scaled_image($file_name, $version, $options) {
  927. if ($this->options['image_library'] === 2) {
  928. return $this->imagemagick_create_scaled_image($file_name, $version, $options);
  929. }
  930. if ($this->options['image_library'] && extension_loaded('imagick')) {
  931. return $this->imagick_create_scaled_image($file_name, $version, $options);
  932. }
  933. return $this->gd_create_scaled_image($file_name, $version, $options);
  934. }
  935. protected function destroy_image_object($file_path) {
  936. if ($this->options['image_library'] && extension_loaded('imagick')) {
  937. return $this->imagick_destroy_image_object($file_path);
  938. }
  939. }
  940. protected function is_valid_image_file($file_path) {
  941. if (!preg_match($this->options['image_file_types'], $file_path)) {
  942. return false;
  943. }
  944. if (function_exists('exif_imagetype')) {
  945. return @exif_imagetype($file_path);
  946. }
  947. $image_info = $this->get_image_size($file_path);
  948. return $image_info && $image_info[0] && $image_info[1];
  949. }
  950. protected function handle_image_file($file_path, $file) {
  951. $failed_versions = array();
  952. foreach($this->options['image_versions'] as $version => $options) {
  953. if ($this->create_scaled_image($file->name, $version, $options)) {
  954. if (!empty($version)) {
  955. $file->{$version.'Url'} = $this->get_download_url(
  956. $file->name,
  957. $version
  958. );
  959. } else {
  960. $file->size = $this->get_file_size($file_path, true);
  961. }
  962. } else {
  963. $failed_versions[] = $version ? $version : 'original';
  964. }
  965. }
  966. if (count($failed_versions)) {
  967. $file->error = $this->get_error_message('image_resize')
  968. .' ('.implode($failed_versions,', ').')';
  969. }
  970. // Free memory:
  971. $this->destroy_image_object($file_path);
  972. }
  973. protected function handle_file_upload($uploaded_file, $name, $size, $type, $error,
  974. $index = null, $content_range = null) {
  975. $file = new stdClass();
  976. $file->name = $this->get_file_name($uploaded_file, $name, $size, $type, $error,
  977. $index, $content_range);
  978. $file->size = $this->fix_integer_overflow(intval($size));
  979. $file->type = $type;
  980. if ($this->validate($uploaded_file, $file, $error, $index)) {
  981. $this->handle_form_data($file, $index);
  982. $upload_dir = $this->get_upload_path();
  983. if (!is_dir($upload_dir)) {
  984. mkdir($upload_dir, $this->options['mkdir_mode'], true);
  985. }
  986. $file_path = $this->get_upload_path($file->name);
  987. $append_file = $content_range && is_file($file_path) &&
  988. $file->size > $this->get_file_size($file_path);
  989. if ($uploaded_file && is_uploaded_file($uploaded_file)) {
  990. // multipart/formdata uploads (POST method uploads)
  991. if ($append_file) {
  992. file_put_contents(
  993. $file_path,
  994. fopen($uploaded_file, 'r'),
  995. FILE_APPEND
  996. );
  997. } else {
  998. move_uploaded_file($uploaded_file, $file_path);
  999. }
  1000. } else {
  1001. // Non-multipart uploads (PUT method support)
  1002. file_put_contents(
  1003. $file_path,
  1004. fopen('php://input', 'r'),
  1005. $append_file ? FILE_APPEND : 0
  1006. );
  1007. }
  1008. $file_size = $this->get_file_size($file_path, $append_file);
  1009. if ($file_size === $file->size) {
  1010. $file->url = $this->get_download_url($file->name);
  1011. if ($this->is_valid_image_file($file_path)) {
  1012. $this->handle_image_file($file_path, $file);
  1013. }
  1014. } else {
  1015. $file->size = $file_size;
  1016. if (!$content_range && $this->options['discard_aborted_uploads']) {
  1017. unlink($file_path);
  1018. $file->error = $this->get_error_message('abort');
  1019. }
  1020. }
  1021. $this->set_additional_file_properties($file);
  1022. }
  1023. return $file;
  1024. }
  1025. protected function readfile($file_path) {
  1026. $file_size = $this->get_file_size($file_path);
  1027. $chunk_size = $this->options['readfile_chunk_size'];
  1028. if ($chunk_size && $file_size > $chunk_size) {
  1029. $handle = fopen($file_path, 'rb');
  1030. while (!feof($handle)) {
  1031. echo fread($handle, $chunk_size);
  1032. ob_flush();
  1033. flush();
  1034. }
  1035. fclose($handle);
  1036. return $file_size;
  1037. }
  1038. return readfile($file_path);
  1039. }
  1040. protected function body($str) {
  1041. echo $str;
  1042. }
  1043. protected function header($str) {
  1044. header($str);
  1045. }
  1046. protected function get_server_var($id) {
  1047. return isset($_SERVER[$id]) ? $_SERVER[$id] : '';
  1048. }
  1049. protected function generate_response($content, $print_response = true) {
  1050. if ($print_response) {
  1051. $json = json_encode($content);
  1052. $redirect = isset($_REQUEST['redirect']) ?
  1053. stripslashes($_REQUEST['redirect']) : null;
  1054. if ($redirect) {
  1055. $this->header('Location: '.sprintf($redirect, rawurlencode($json)));
  1056. return;
  1057. }
  1058. $this->head();
  1059. if ($this->get_server_var('HTTP_CONTENT_RANGE')) {
  1060. $files = isset($content[$this->options['param_name']]) ?
  1061. $content[$this->options['param_name']] : null;
  1062. if ($files && is_array($files) && is_object($files[0]) && $files[0]->size) {
  1063. $this->header('Range: 0-'.(
  1064. $this->fix_integer_overflow(intval($files[0]->size)) - 1
  1065. ));
  1066. }
  1067. }
  1068. $this->body($json);
  1069. }
  1070. return $content;
  1071. }
  1072. protected function get_version_param() {
  1073. return isset($_GET['version']) ? basename(stripslashes($_GET['version'])) : null;
  1074. }
  1075. protected function get_singular_param_name() {
  1076. return substr($this->options['param_name'], 0, -1);
  1077. }
  1078. protected function get_file_name_param() {
  1079. $name = $this->get_singular_param_name();
  1080. return isset($_GET[$name]) ? basename(stripslashes($_GET[$name])) : null;
  1081. }
  1082. protected function get_file_names_params() {
  1083. $params = isset($_GET[$this->options['param_name']]) ?
  1084. $_GET[$this->options['param_name']] : array();
  1085. foreach ($params as $key => $value) {
  1086. $params[$key] = basename(stripslashes($value));
  1087. }
  1088. return $params;
  1089. }
  1090. protected function get_file_type($file_path) {
  1091. switch (strtolower(pathinfo($file_path, PATHINFO_EXTENSION))) {
  1092. case 'jpeg':
  1093. case 'jpg':
  1094. return 'image/jpeg';
  1095. case 'png':
  1096. return 'image/png';
  1097. case 'gif':
  1098. return 'image/gif';
  1099. default:
  1100. return '';
  1101. }
  1102. }
  1103. protected function download() {
  1104. switch ($this->options['download_via_php']) {
  1105. case 1:
  1106. $redirect_header = null;
  1107. break;
  1108. case 2:
  1109. $redirect_header = 'X-Sendfile';
  1110. break;
  1111. case 3:
  1112. $redirect_header = 'X-Accel-Redirect';
  1113. break;
  1114. default:
  1115. return $this->header('HTTP/1.1 403 Forbidden');
  1116. }
  1117. $file_name = $this->get_file_name_param();
  1118. if (!$this->is_valid_file_object($file_name)) {
  1119. return $this->header('HTTP/1.1 404 Not Found');
  1120. }
  1121. if ($redirect_header) {
  1122. return $this->header(
  1123. $redirect_header.': '.$this->get_download_url(
  1124. $file_name,
  1125. $this->get_version_param(),
  1126. true
  1127. )
  1128. );
  1129. }
  1130. $file_path = $this->get_upload_path($file_name, $this->get_version_param());
  1131. // Prevent browsers from MIME-sniffing the content-type:
  1132. $this->header('X-Content-Type-Options: nosniff');
  1133. if (!preg_match($this->options['inline_file_types'], $file_name)) {
  1134. $this->header('Content-Type: application/octet-stream');
  1135. $this->header('Content-Disposition: attachment; filename="'.$file_name.'"');
  1136. } else {
  1137. $this->header('Content-Type: '.$this->get_file_type($file_path));
  1138. $this->header('Content-Disposition: inline; filename="'.$file_name.'"');
  1139. }
  1140. $this->header('Content-Length: '.$this->get_file_size($file_path));
  1141. $this->header('Last-Modified: '.gmdate('D, d M Y H:i:s T', filemtime($file_path)));
  1142. $this->readfile($file_path);
  1143. }
  1144. protected function send_content_type_header() {
  1145. $this->header('Vary: Accept');
  1146. if (strpos($this->get_server_var('HTTP_ACCEPT'), 'application/json') !== false) {
  1147. $this->header('Content-type: application/json');
  1148. } else {
  1149. $this->header('Content-type: text/plain');
  1150. }
  1151. }
  1152. protected function send_access_control_headers() {
  1153. $this->header('Access-Control-Allow-Origin: '.$this->options['access_control_allow_origin']);
  1154. $this->header('Access-Control-Allow-Credentials: '
  1155. .($this->options['access_control_allow_credentials'] ? 'true' : 'false'));
  1156. $this->header('Access-Control-Allow-Methods: '
  1157. .implode(', ', $this->options['access_control_allow_methods']));
  1158. $this->header('Access-Control-Allow-Headers: '
  1159. .implode(', ', $this->options['access_control_allow_headers']));
  1160. }
  1161. public function head() {
  1162. $this->header('Pragma: no-cache');
  1163. $this->header('Cache-Control: no-store, no-cache, must-revalidate');
  1164. $this->header('Content-Disposition: inline; filename="files.json"');
  1165. // Prevent Internet Explorer from MIME-sniffing the content-type:
  1166. $this->header('X-Content-Type-Options: nosniff');
  1167. if ($this->options['access_control_allow_origin']) {
  1168. $this->send_access_control_headers();
  1169. }
  1170. $this->send_content_type_header();
  1171. }
  1172. public function get($print_response = true) {
  1173. if ($print_response && isset($_GET['download'])) {
  1174. return $this->download();
  1175. }
  1176. $file_name = $this->get_file_name_param();
  1177. if ($file_name) {
  1178. $response = array(
  1179. $this->get_singular_param_name() => $this->get_file_object($file_name)
  1180. );
  1181. } else {
  1182. $response = array(
  1183. $this->options['param_name'] => $this->get_file_objects()
  1184. );
  1185. }
  1186. return $this->generate_response($response, $print_response);
  1187. }
  1188. public function post($print_response = true) {
  1189. if (isset($_REQUEST['_method']) && $_REQUEST['_method'] === 'DELETE') {
  1190. return $this->delete($print_response);
  1191. }
  1192. $upload = isset($_FILES[$this->options['param_name']]) ?
  1193. $_FILES[$this->options['param_name']] : null;
  1194. // Parse the Content-Disposition header, if available:
  1195. $file_name = $this->get_server_var('HTTP_CONTENT_DISPOSITION') ?
  1196. rawurldecode(preg_replace(
  1197. '/(^[^"]+")|("$)/',
  1198. '',
  1199. $this->get_server_var('HTTP_CONTENT_DISPOSITION')
  1200. )) : null;
  1201. // Parse the Content-Range header, which has the following form:
  1202. // Content-Range: bytes 0-524287/2000000
  1203. $content_range = $this->get_server_var('HTTP_CONTENT_RANGE') ?
  1204. preg_split('/[^0-9]+/', $this->get_server_var('HTTP_CONTENT_RANGE')) : null;
  1205. $size = $content_range ? $content_range[3] : null;
  1206. $files = array();
  1207. if ($upload && is_array($upload['tmp_name'])) {
  1208. // param_name is an array identifier like "files[]",
  1209. // $_FILES is a multi-dimensional array:
  1210. foreach ($upload['tmp_name'] as $index => $value) {
  1211. $files[] = $this->handle_file_upload(
  1212. $upload['tmp_name'][$

Large files files are truncated, but you can click here to view the full file