UploadHandler.php 52 KB

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