UploadHandler.php 54 KB

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