UploadHandler.php 53 KB

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