PageRenderTime 62ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/library/UploadHandler_old.php

https://bitbucket.org/bggsk-admin/go-yug
PHP | 1383 lines | 1175 code | 103 blank | 105 comment | 185 complexity | 4af57fa42b47aad5de8151a0e3f76b9e MD5 | raw file

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

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

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