UploadHandler.php 54 KB

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