UploadHandler.php 59 KB

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