UploadHandler.php 52 KB

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