UploadHandler.php 54 KB

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