UploadHandler.php 54 KB

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