UploadHandler.php 53 KB

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