UploadHandler.php 59 KB

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