fileupload.class.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. <?php
  2. /* Copyright (C) 2011-2022 Regis Houssin <regis.houssin@inodbox.com>
  3. * Copyright (C) 2011-2012 Laurent Destailleur <eldy@users.sourceforge.net>
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. /**
  19. * \file htdocs/core/class/fileupload.class.php
  20. * \brief File to return Ajax response on file upload
  21. */
  22. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  23. require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  24. /**
  25. * This class is used to manage file upload using ajax
  26. */
  27. class FileUpload
  28. {
  29. protected $options;
  30. protected $fk_element;
  31. protected $element;
  32. /**
  33. * Constructor
  34. *
  35. * @param array $options Options array
  36. * @param int $fk_element fk_element
  37. * @param string $element element
  38. */
  39. public function __construct($options = null, $fk_element = null, $element = null)
  40. {
  41. global $db, $conf;
  42. global $object;
  43. global $hookmanager;
  44. $hookmanager->initHooks(array('fileupload'));
  45. $this->fk_element = $fk_element;
  46. $this->element = $element;
  47. $pathname = $filename = $element;
  48. if (preg_match('/^([^_]+)_([^_]+)/i', $element, $regs)) {
  49. $pathname = $regs[1];
  50. $filename = $regs[2];
  51. }
  52. $parentForeignKey = '';
  53. // For compatibility
  54. if ($element == 'propal') {
  55. $pathname = 'comm/propal';
  56. $dir_output = $conf->$element->dir_output;
  57. } elseif ($element == 'facture') {
  58. $pathname = 'compta/facture';
  59. $dir_output = $conf->$element->dir_output;
  60. } elseif ($element == 'project') {
  61. $element = $pathname = 'projet';
  62. $dir_output = $conf->$element->dir_output;
  63. } elseif ($element == 'project_task') {
  64. $pathname = 'projet';
  65. $filename = 'task';
  66. $dir_output = $conf->project->dir_output;
  67. $parentForeignKey = 'fk_project';
  68. $parentClass = 'Project';
  69. $parentElement = 'projet';
  70. $parentObject = 'project';
  71. } elseif ($element == 'fichinter') {
  72. $element = 'ficheinter';
  73. $dir_output = $conf->$element->dir_output;
  74. } elseif ($element == 'order_supplier') {
  75. $pathname = 'fourn';
  76. $filename = 'fournisseur.commande';
  77. $dir_output = $conf->fournisseur->commande->dir_output;
  78. } elseif ($element == 'invoice_supplier') {
  79. $pathname = 'fourn';
  80. $filename = 'fournisseur.facture';
  81. $dir_output = $conf->fournisseur->facture->dir_output;
  82. } elseif ($element == 'product') {
  83. $dir_output = $conf->product->multidir_output[$conf->entity];
  84. } elseif ($element == 'productbatch') {
  85. $dir_output = $conf->productbatch->multidir_output[$conf->entity];
  86. } elseif ($element == 'action') {
  87. $pathname = 'comm/action';
  88. $filename = 'actioncomm';
  89. $dir_output = $conf->agenda->dir_output;
  90. } elseif ($element == 'chargesociales') {
  91. $pathname = 'compta/sociales';
  92. $filename = 'chargesociales';
  93. $dir_output = $conf->tax->dir_output;
  94. } else {
  95. $dir_output = $conf->$element->dir_output;
  96. }
  97. dol_include_once('/'.$pathname.'/class/'.$filename.'.class.php');
  98. $classname = ucfirst($filename);
  99. if ($element == 'order_supplier') {
  100. $classname = 'CommandeFournisseur';
  101. } elseif ($element == 'invoice_supplier') {
  102. $classname = 'FactureFournisseur';
  103. }
  104. $object = new $classname($db);
  105. $object->fetch($fk_element);
  106. if (!empty($parentForeignKey)) {
  107. dol_include_once('/'.$parentElement.'/class/'.$parentObject.'.class.php');
  108. $parent = new $parentClass($db);
  109. $parent->fetch($object->$parentForeignKey);
  110. if (!empty($parent->socid)) {
  111. $parent->fetch_thirdparty();
  112. }
  113. $object->$parentObject = clone $parent;
  114. } else {
  115. $object->fetch_thirdparty();
  116. }
  117. $object_ref = dol_sanitizeFileName($object->ref);
  118. if ($element == 'invoice_supplier') {
  119. $object_ref = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$object_ref;
  120. } elseif ($element == 'project_task') {
  121. $object_ref = $object->project->ref.'/'.$object_ref;
  122. }
  123. $this->options = array(
  124. 'script_url' => $_SERVER['PHP_SELF'],
  125. 'upload_dir' => $dir_output.'/'.$object_ref.'/',
  126. 'upload_url' => DOL_URL_ROOT.'/document.php?modulepart='.$element.'&attachment=1&file=/'.$object_ref.'/',
  127. 'param_name' => 'files',
  128. // Set the following option to 'POST', if your server does not support
  129. // DELETE requests. This is a parameter sent to the client:
  130. 'delete_type' => 'DELETE',
  131. // The php.ini settings upload_max_filesize and post_max_size
  132. // take precedence over the following max_file_size setting:
  133. 'max_file_size' => null,
  134. 'min_file_size' => 1,
  135. 'accept_file_types' => '/.+$/i',
  136. // The maximum number of files for the upload directory:
  137. 'max_number_of_files' => null,
  138. // Image resolution restrictions:
  139. 'max_width' => null,
  140. 'max_height' => null,
  141. 'min_width' => 1,
  142. 'min_height' => 1,
  143. // Set the following option to false to enable resumable uploads:
  144. 'discard_aborted_uploads' => true,
  145. 'image_versions' => array(
  146. // Uncomment the following version to restrict the size of
  147. // uploaded images. You can also add additional versions with
  148. // their own upload directories:
  149. /*
  150. 'large' => array(
  151. 'upload_dir' => dirname($_SERVER['SCRIPT_FILENAME']).'/files/',
  152. 'upload_url' => $this->getFullUrl().'/files/',
  153. 'max_width' => 1920,
  154. 'max_height' => 1200,
  155. 'jpeg_quality' => 95
  156. ),
  157. */
  158. 'thumbnail' => array(
  159. 'upload_dir' => $dir_output.'/'.$object_ref.'/thumbs/',
  160. 'upload_url' => DOL_URL_ROOT.'/document.php?modulepart='.$element.'&attachment=1&file=/'.$object_ref.'/thumbs/',
  161. 'max_width' => 80,
  162. 'max_height' => 80
  163. )
  164. )
  165. );
  166. global $action;
  167. $hookmanager->executeHooks(
  168. 'overrideUploadOptions',
  169. array(
  170. 'options' => &$options,
  171. 'element' => $element
  172. ),
  173. $object,
  174. $action
  175. );
  176. if ($options) {
  177. $this->options = array_replace_recursive($this->options, $options);
  178. }
  179. }
  180. /**
  181. * Return full URL
  182. *
  183. * @return string URL
  184. */
  185. protected function getFullUrl()
  186. {
  187. $https = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
  188. return
  189. ($https ? 'https://' : 'http://').
  190. (!empty($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'].'@' : '').
  191. (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME'].
  192. ($https && $_SERVER['SERVER_PORT'] === 443 ||
  193. $_SERVER['SERVER_PORT'] === 80 ? '' : ':'.$_SERVER['SERVER_PORT']))).
  194. substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], '/'));
  195. }
  196. /**
  197. * Set delete url
  198. *
  199. * @param object $file Filename
  200. * @return void
  201. */
  202. protected function setFileDeleteUrl($file)
  203. {
  204. $file->delete_url = $this->options['script_url']
  205. .'?file='.urlencode($file->name).'&fk_element='.urlencode($this->fk_element).'&element='.urlencode($this->element);
  206. $file->delete_type = $this->options['delete_type'];
  207. if ($file->delete_type !== 'DELETE') {
  208. $file->delete_url .= '&_method=DELETE';
  209. }
  210. }
  211. /**
  212. * getFileObject
  213. *
  214. * @param string $file_name Filename
  215. * @return stdClass|null
  216. */
  217. protected function getFileObject($file_name)
  218. {
  219. $file_path = $this->options['upload_dir'].$file_name;
  220. if (is_file($file_path) && $file_name[0] !== '.') {
  221. $file = new stdClass();
  222. $file->name = $file_name;
  223. $file->mime = dol_mimetype($file_name, '', 2);
  224. $file->size = filesize($file_path);
  225. $file->url = $this->options['upload_url'].rawurlencode($file->name);
  226. foreach ($this->options['image_versions'] as $version => $options) {
  227. if (is_file($options['upload_dir'].$file_name)) {
  228. $tmp = explode('.', $file->name);
  229. $file->{$version.'_url'} = $options['upload_url'].rawurlencode($tmp[0].'_mini.'.$tmp[1]);
  230. }
  231. }
  232. $this->setFileDeleteUrl($file);
  233. return $file;
  234. }
  235. return null;
  236. }
  237. /**
  238. * getFileObjects
  239. *
  240. * @return array Array of objects
  241. */
  242. protected function getFileObjects()
  243. {
  244. return array_values(array_filter(array_map(array($this, 'getFileObject'), scandir($this->options['upload_dir']))));
  245. }
  246. /**
  247. * Create thumbs of a file uploaded. Only the "mini" thumb is generated.
  248. *
  249. * @param string $file_name Filename
  250. * @param string $options is array('max_width', 'max_height')
  251. * @return boolean
  252. */
  253. protected function createScaledImage($file_name, $options)
  254. {
  255. global $maxwidthmini, $maxheightmini;
  256. $file_path = $this->options['upload_dir'].$file_name;
  257. $new_file_path = $options['upload_dir'].$file_name;
  258. if (dol_mkdir($options['upload_dir']) >= 0) {
  259. list($img_width, $img_height) = @getimagesize($file_path);
  260. if (!$img_width || !$img_height) {
  261. return false;
  262. }
  263. $res = vignette($file_path, $maxwidthmini, $maxheightmini, '_mini'); // We don't use ->addThumbs here because there is no object and we don't need all thumbs, only the "mini".
  264. if (preg_match('/error/i', $res)) {
  265. return false;
  266. }
  267. return true;
  268. } else {
  269. return false;
  270. }
  271. }
  272. /**
  273. * Enter description here ...
  274. *
  275. * @param string $uploaded_file Uploade file
  276. * @param object $file File
  277. * @param string $error Error
  278. * @param string $index Index
  279. * @return boolean True if OK, False if KO
  280. */
  281. protected function validate($uploaded_file, $file, $error, $index)
  282. {
  283. if ($error) {
  284. $file->error = $error;
  285. return false;
  286. }
  287. if (!$file->name) {
  288. $file->error = 'missingFileName';
  289. return false;
  290. }
  291. if (!preg_match($this->options['accept_file_types'], $file->name)) {
  292. $file->error = 'acceptFileTypes';
  293. return false;
  294. }
  295. if ($uploaded_file && is_uploaded_file($uploaded_file)) {
  296. $file_size = filesize($uploaded_file);
  297. } else {
  298. $file_size = $_SERVER['CONTENT_LENGTH'];
  299. }
  300. if ($this->options['max_file_size'] && (
  301. $file_size > $this->options['max_file_size'] ||
  302. $file->size > $this->options['max_file_size'])
  303. ) {
  304. $file->error = 'maxFileSize';
  305. return false;
  306. }
  307. if ($this->options['min_file_size'] &&
  308. $file_size < $this->options['min_file_size']) {
  309. $file->error = 'minFileSize';
  310. return false;
  311. }
  312. if (is_numeric($this->options['max_number_of_files']) && (
  313. count($this->getFileObjects()) >= $this->options['max_number_of_files'])
  314. ) {
  315. $file->error = 'maxNumberOfFiles';
  316. return false;
  317. }
  318. list($img_width, $img_height) = @getimagesize($uploaded_file);
  319. if (is_numeric($img_width)) {
  320. if ($this->options['max_width'] && $img_width > $this->options['max_width'] ||
  321. $this->options['max_height'] && $img_height > $this->options['max_height']) {
  322. $file->error = 'maxResolution';
  323. return false;
  324. }
  325. if ($this->options['min_width'] && $img_width < $this->options['min_width'] ||
  326. $this->options['min_height'] && $img_height < $this->options['min_height']) {
  327. $file->error = 'minResolution';
  328. return false;
  329. }
  330. }
  331. return true;
  332. }
  333. /**
  334. * Enter description here ...
  335. *
  336. * @param int $matches ???
  337. * @return string ???
  338. */
  339. protected function upcountNameCallback($matches)
  340. {
  341. $index = isset($matches[1]) ? intval($matches[1]) + 1 : 1;
  342. $ext = isset($matches[2]) ? $matches[2] : '';
  343. return ' ('.$index.')'.$ext;
  344. }
  345. /**
  346. * Enter description here ...
  347. *
  348. * @param string $name ???
  349. * @return string ???
  350. */
  351. protected function upcountName($name)
  352. {
  353. return preg_replace_callback('/(?:(?: \(([\d]+)\))?(\.[^.]+))?$/', array($this, 'upcountNameCallback'), $name, 1);
  354. }
  355. /**
  356. * trimFileName
  357. *
  358. * @param string $name Filename
  359. * @param string $type ???
  360. * @param string $index ???
  361. * @return string
  362. */
  363. protected function trimFileName($name, $type, $index)
  364. {
  365. // Remove path information and dots around the filename, to prevent uploading
  366. // into different directories or replacing hidden system files.
  367. // Also remove control characters and spaces (\x00..\x20) around the filename:
  368. $file_name = trim(basename(stripslashes($name)), ".\x00..\x20");
  369. // Add missing file extension for known image types:
  370. if (strpos($file_name, '.') === false &&
  371. preg_match('/^image\/(gif|jpe?g|png)/', $type, $matches)) {
  372. $file_name .= '.'.$matches[1];
  373. }
  374. if ($this->options['discard_aborted_uploads']) {
  375. while (is_file($this->options['upload_dir'].$file_name)) {
  376. $file_name = $this->upcountName($file_name);
  377. }
  378. }
  379. return $file_name;
  380. }
  381. /**
  382. * handleFileUpload
  383. *
  384. * @param string $uploaded_file Uploade file
  385. * @param string $name Name
  386. * @param int $size Size
  387. * @param string $type Type
  388. * @param string $error Error
  389. * @param string $index Index
  390. * @return stdClass
  391. */
  392. protected function handleFileUpload($uploaded_file, $name, $size, $type, $error, $index)
  393. {
  394. $file = new stdClass();
  395. $file->name = $this->trimFileName($name, $type, $index);
  396. $file->mime = dol_mimetype($file->name, '', 2);
  397. $file->size = intval($size);
  398. $file->type = $type;
  399. if ($this->validate($uploaded_file, $file, $error, $index) && dol_mkdir($this->options['upload_dir']) >= 0) {
  400. $file_path = $this->options['upload_dir'].$file->name;
  401. $append_file = !$this->options['discard_aborted_uploads'] && is_file($file_path) && $file->size > filesize($file_path);
  402. clearstatcache();
  403. if ($uploaded_file && is_uploaded_file($uploaded_file)) {
  404. // multipart/formdata uploads (POST method uploads)
  405. if ($append_file) {
  406. file_put_contents($file_path, fopen($uploaded_file, 'r'), FILE_APPEND);
  407. } else {
  408. dol_move_uploaded_file($uploaded_file, $file_path, 1, 0, 0, 0, 'userfile');
  409. }
  410. } else {
  411. // Non-multipart uploads (PUT method support)
  412. file_put_contents($file_path, fopen('php://input', 'r'), $append_file ? FILE_APPEND : 0);
  413. }
  414. $file_size = filesize($file_path);
  415. if ($file_size === $file->size) {
  416. $file->url = $this->options['upload_url'].rawurlencode($file->name);
  417. foreach ($this->options['image_versions'] as $version => $options) {
  418. if ($this->createScaledImage($file->name, $options)) {
  419. $tmp = explode('.', $file->name);
  420. $file->{$version.'_url'} = $options['upload_url'].rawurlencode($tmp[0].'_mini.'.$tmp[1]);
  421. }
  422. }
  423. } elseif ($this->options['discard_aborted_uploads']) {
  424. unlink($file_path);
  425. $file->error = 'abort';
  426. }
  427. $file->size = $file_size;
  428. $this->setFileDeleteUrl($file);
  429. }
  430. return $file;
  431. }
  432. /**
  433. * Output data
  434. *
  435. * @return void
  436. */
  437. public function get()
  438. {
  439. $file_name = isset($_REQUEST['file']) ?
  440. basename(stripslashes($_REQUEST['file'])) : null;
  441. if ($file_name) {
  442. $info = $this->getFileObject($file_name);
  443. } else {
  444. $info = $this->getFileObjects();
  445. }
  446. header('Content-type: application/json');
  447. echo json_encode($info);
  448. }
  449. /**
  450. * Output data
  451. *
  452. * @return void
  453. */
  454. public function post()
  455. {
  456. if (isset($_REQUEST['_method']) && $_REQUEST['_method'] === 'DELETE') {
  457. return $this->delete();
  458. }
  459. $upload = isset($_FILES[$this->options['param_name']]) ?
  460. $_FILES[$this->options['param_name']] : null;
  461. $info = array();
  462. if ($upload && is_array($upload['tmp_name'])) {
  463. // param_name is an array identifier like "files[]",
  464. // $_FILES is a multi-dimensional array:
  465. foreach ($upload['tmp_name'] as $index => $value) {
  466. $info[] = $this->handleFileUpload(
  467. $upload['tmp_name'][$index],
  468. isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : $upload['name'][$index],
  469. isset($_SERVER['HTTP_X_FILE_SIZE']) ? $_SERVER['HTTP_X_FILE_SIZE'] : $upload['size'][$index],
  470. isset($_SERVER['HTTP_X_FILE_TYPE']) ? $_SERVER['HTTP_X_FILE_TYPE'] : $upload['type'][$index],
  471. $upload['error'][$index],
  472. $index
  473. );
  474. }
  475. } elseif ($upload || isset($_SERVER['HTTP_X_FILE_NAME'])) {
  476. // param_name is a single object identifier like "file",
  477. // $_FILES is a one-dimensional array:
  478. $info[] = $this->handleFileUpload(
  479. isset($upload['tmp_name']) ? $upload['tmp_name'] : null,
  480. isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : (isset($upload['name']) ? $upload['name'] : null),
  481. isset($_SERVER['HTTP_X_FILE_SIZE']) ? $_SERVER['HTTP_X_FILE_SIZE'] : (isset($upload['size']) ? $upload['size'] : null),
  482. isset($_SERVER['HTTP_X_FILE_TYPE']) ? $_SERVER['HTTP_X_FILE_TYPE'] : (isset($upload['type']) ? $upload['type'] : null),
  483. isset($upload['error']) ? $upload['error'] : null,
  484. 0
  485. );
  486. }
  487. header('Vary: Accept');
  488. $json = json_encode($info);
  489. $redirect = isset($_REQUEST['redirect']) ?
  490. stripslashes($_REQUEST['redirect']) : null;
  491. if ($redirect) {
  492. header('Location: '.sprintf($redirect, rawurlencode($json)));
  493. return;
  494. }
  495. if (isset($_SERVER['HTTP_ACCEPT']) &&
  496. (strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false)) {
  497. header('Content-type: application/json');
  498. } else {
  499. header('Content-type: text/plain');
  500. }
  501. echo $json;
  502. }
  503. /**
  504. * Delete uploaded file
  505. *
  506. * @return string
  507. */
  508. public function delete()
  509. {
  510. $file_name = isset($_REQUEST['file']) ?
  511. basename(stripslashes($_REQUEST['file'])) : null;
  512. $file_path = $this->options['upload_dir'].$file_name;
  513. $success = is_file($file_path) && $file_name[0] !== '.' && unlink($file_path);
  514. if ($success) {
  515. foreach ($this->options['image_versions'] as $version => $options) {
  516. $file = $options['upload_dir'].$file_name;
  517. if (is_file($file)) {
  518. unlink($file);
  519. }
  520. }
  521. }
  522. header('Content-type: application/json');
  523. echo json_encode($success);
  524. }
  525. }