UploadHandler.php 54 KB

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