UploadHandler.php 55 KB

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