fileupload.class.php 18 KB

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