UploadHandler.php 54 KB

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