fileupload.class.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. <?php
  2. /* Copyright (C) 2011-2012 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 <http://www.gnu.org/licenses/>.
  17. */
  18. /**
  19. * \file htdocs/core/ajax/fileupload.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. function __construct($options=null,$fk_element=null,$element=null)
  40. {
  41. global $db, $conf;
  42. global $object;
  43. $this->fk_element=$fk_element;
  44. $this->element=$element;
  45. $pathname=$filename=$element;
  46. if (preg_match('/^([^_]+)_([^_]+)/i',$element,$regs))
  47. {
  48. $pathname = $regs[1];
  49. $filename = $regs[2];
  50. }
  51. $parentForeignKey = '';
  52. // For compatibility
  53. if ($element == 'propal') {
  54. $pathname = 'comm/propal';
  55. $dir_output=$conf->$element->dir_output;
  56. }
  57. elseif ($element == 'facture') {
  58. $pathname = 'compta/facture';
  59. $dir_output=$conf->$element->dir_output;
  60. }
  61. elseif ($element == 'project') {
  62. $element = $pathname = 'projet';
  63. $dir_output=$conf->$element->dir_output;
  64. }
  65. elseif ($element == 'project_task') {
  66. $pathname = 'projet'; $filename='task';
  67. $dir_output=$conf->projet->dir_output;
  68. $parentForeignKey = 'fk_project';
  69. $parentClass = 'Project';
  70. $parentElement = 'projet';
  71. $parentObject = 'project';
  72. }
  73. elseif ($element == 'fichinter') {
  74. $element='ficheinter';
  75. $dir_output=$conf->$element->dir_output;
  76. }
  77. elseif ($element == 'order_supplier') {
  78. $pathname = 'fourn'; $filename='fournisseur.commande';
  79. $dir_output=$conf->fournisseur->commande->dir_output;
  80. }
  81. elseif ($element == 'invoice_supplier') {
  82. $pathname = 'fourn'; $filename='fournisseur.facture';
  83. $dir_output=$conf->fournisseur->facture->dir_output;
  84. }
  85. elseif ($element == 'product') {
  86. $dir_output = $conf->product->multidir_output[$conf->entity];
  87. }
  88. elseif ($element == 'productbatch') {
  89. $dir_output = $conf->productbatch->multidir_output[$conf->entity];
  90. }
  91. elseif ($element == 'action') {
  92. $pathname = 'comm/action'; $filename='actioncomm';
  93. $dir_output=$conf->agenda->dir_output;
  94. }
  95. elseif ($element == 'chargesociales') {
  96. $pathname = 'compta/sociales'; $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. } else if ($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. if ($options) {
  171. $this->options = array_replace_recursive($this->options, $options);
  172. }
  173. }
  174. /**
  175. * Return full URL
  176. *
  177. * @return string URL
  178. */
  179. protected function getFullUrl()
  180. {
  181. $https = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
  182. return
  183. ($https ? 'https://' : 'http://').
  184. (!empty($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'].'@' : '').
  185. (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME'].
  186. ($https && $_SERVER['SERVER_PORT'] === 443 ||
  187. $_SERVER['SERVER_PORT'] === 80 ? '' : ':'.$_SERVER['SERVER_PORT']))).
  188. substr($_SERVER['SCRIPT_NAME'],0, strrpos($_SERVER['SCRIPT_NAME'], '/'));
  189. }
  190. /**
  191. * Set delete url
  192. *
  193. * @param string $file Filename
  194. * @return void
  195. */
  196. protected function setFileDeleteUrl($file)
  197. {
  198. $file->delete_url = $this->options['script_url']
  199. .'?file='.rawurlencode($file->name).'&fk_element='.$this->fk_element.'&element='.$this->element;
  200. $file->delete_type = $this->options['delete_type'];
  201. if ($file->delete_type !== 'DELETE') {
  202. $file->delete_url .= '&_method=DELETE';
  203. }
  204. }
  205. /**
  206. * getFileObject
  207. *
  208. * @param string $file_name Filename
  209. * @return stdClass|null
  210. */
  211. protected function getFileObject($file_name)
  212. {
  213. $file_path = $this->options['upload_dir'].$file_name;
  214. if (is_file($file_path) && $file_name[0] !== '.')
  215. {
  216. $file = new stdClass();
  217. $file->name = $file_name;
  218. $file->mime = dol_mimetype($file_name,'',2);
  219. $file->size = filesize($file_path);
  220. $file->url = $this->options['upload_url'].rawurlencode($file->name);
  221. foreach($this->options['image_versions'] as $version => $options) {
  222. if (is_file($options['upload_dir'].$file_name)) {
  223. $tmp=explode('.',$file->name);
  224. $file->{$version.'_url'} = $options['upload_url'].rawurlencode($tmp[0].'_mini.'.$tmp[1]);
  225. }
  226. }
  227. $this->setFileDeleteUrl($file);
  228. return $file;
  229. }
  230. return null;
  231. }
  232. /**
  233. * getFileObjects
  234. *
  235. * @return void
  236. */
  237. protected function getFileObjects()
  238. {
  239. return array_values(array_filter(array_map(array($this, 'getFileObject'), scandir($this->options['upload_dir']))));
  240. }
  241. /**
  242. * Create thumbs of a file uploaded. Only the "mini" thumb is generated.
  243. *
  244. * @param string $file_name Filename
  245. * @param string $options is array('max_width', 'max_height')
  246. * @return boolean
  247. */
  248. protected function createScaledImage($file_name, $options)
  249. {
  250. global $maxwidthmini, $maxheightmini;
  251. $file_path = $this->options['upload_dir'].$file_name;
  252. $new_file_path = $options['upload_dir'].$file_name;
  253. if (dol_mkdir($options['upload_dir']) >= 0)
  254. {
  255. list($img_width, $img_height) = @getimagesize($file_path);
  256. if (!$img_width || !$img_height) {
  257. return false;
  258. }
  259. $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".
  260. if (preg_match('/error/i',$res)) return false;
  261. return true;
  262. }
  263. else
  264. {
  265. return false;
  266. }
  267. }
  268. /**
  269. * Enter description here ...
  270. *
  271. * @param string $uploaded_file Uploade file
  272. * @param string $file File
  273. * @param string $error Error
  274. * @param string $index Index
  275. * @return boolean True if OK, False if KO
  276. */
  277. protected function validate($uploaded_file, $file, $error, $index)
  278. {
  279. if ($error) {
  280. $file->error = $error;
  281. return false;
  282. }
  283. if (!$file->name) {
  284. $file->error = 'missingFileName';
  285. return false;
  286. }
  287. if (!preg_match($this->options['accept_file_types'], $file->name)) {
  288. $file->error = 'acceptFileTypes';
  289. return false;
  290. }
  291. if ($uploaded_file && is_uploaded_file($uploaded_file)) {
  292. $file_size = filesize($uploaded_file);
  293. } else {
  294. $file_size = $_SERVER['CONTENT_LENGTH'];
  295. }
  296. if ($this->options['max_file_size'] && (
  297. $file_size > $this->options['max_file_size'] ||
  298. $file->size > $this->options['max_file_size'])
  299. ) {
  300. $file->error = 'maxFileSize';
  301. return false;
  302. }
  303. if ($this->options['min_file_size'] &&
  304. $file_size < $this->options['min_file_size']) {
  305. $file->error = 'minFileSize';
  306. return false;
  307. }
  308. if (is_numeric($this->options['max_number_of_files']) && (
  309. count($this->getFileObjects()) >= $this->options['max_number_of_files'])
  310. ) {
  311. $file->error = 'maxNumberOfFiles';
  312. return false;
  313. }
  314. list($img_width, $img_height) = @getimagesize($uploaded_file);
  315. if (is_numeric($img_width)) {
  316. if ($this->options['max_width'] && $img_width > $this->options['max_width'] ||
  317. $this->options['max_height'] && $img_height > $this->options['max_height']) {
  318. $file->error = 'maxResolution';
  319. return false;
  320. }
  321. if ($this->options['min_width'] && $img_width < $this->options['min_width'] ||
  322. $this->options['min_height'] && $img_height < $this->options['min_height']) {
  323. $file->error = 'minResolution';
  324. return false;
  325. }
  326. }
  327. return true;
  328. }
  329. /**
  330. * Enter description here ...
  331. *
  332. * @param int $matches ???
  333. * @return string ???
  334. */
  335. protected function upcountNameCallback($matches)
  336. {
  337. $index = isset($matches[1]) ? intval($matches[1]) + 1 : 1;
  338. $ext = isset($matches[2]) ? $matches[2] : '';
  339. return ' ('.$index.')'.$ext;
  340. }
  341. /**
  342. * Enter description here ...
  343. *
  344. * @param string $name ???
  345. * @return string ???
  346. */
  347. protected function upcountName($name)
  348. {
  349. return preg_replace_callback('/(?:(?: \(([\d]+)\))?(\.[^.]+))?$/', array($this, 'upcountNameCallback'), $name, 1);
  350. }
  351. /**
  352. * trimFileName
  353. *
  354. * @param string $name Filename
  355. * @param string $type ???
  356. * @param string $index ???
  357. * @return string
  358. */
  359. protected function trimFileName($name, $type, $index)
  360. {
  361. // Remove path information and dots around the filename, to prevent uploading
  362. // into different directories or replacing hidden system files.
  363. // Also remove control characters and spaces (\x00..\x20) around the filename:
  364. $file_name = trim(basename(stripslashes($name)), ".\x00..\x20");
  365. // Add missing file extension for known image types:
  366. if (strpos($file_name, '.') === false &&
  367. preg_match('/^image\/(gif|jpe?g|png)/', $type, $matches)) {
  368. $file_name .= '.'.$matches[1];
  369. }
  370. if ($this->options['discard_aborted_uploads'])
  371. {
  372. while(is_file($this->options['upload_dir'].$file_name))
  373. {
  374. $file_name = $this->upcountName($file_name);
  375. }
  376. }
  377. return $file_name;
  378. }
  379. /**
  380. * handleFileUpload
  381. *
  382. * @param string $uploaded_file Uploade file
  383. * @param string $name Name
  384. * @param int $size Size
  385. * @param string $type Type
  386. * @param string $error Error
  387. * @param string $index Index
  388. * @return stdClass
  389. */
  390. protected function handleFileUpload($uploaded_file, $name, $size, $type, $error, $index)
  391. {
  392. $file = new stdClass();
  393. $file->name = $this->trimFileName($name, $type, $index);
  394. $file->mime = dol_mimetype($file->name,'',2);
  395. $file->size = intval($size);
  396. $file->type = $type;
  397. if ($this->validate($uploaded_file, $file, $error, $index) && dol_mkdir($this->options['upload_dir']) >= 0)
  398. {
  399. $file_path = $this->options['upload_dir'].$file->name;
  400. $append_file = !$this->options['discard_aborted_uploads'] && is_file($file_path) && $file->size > filesize($file_path);
  401. clearstatcache();
  402. if ($uploaded_file && is_uploaded_file($uploaded_file)) {
  403. // multipart/formdata uploads (POST method uploads)
  404. if ($append_file)
  405. {
  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. }
  411. else
  412. {
  413. // Non-multipart uploads (PUT method support)
  414. file_put_contents($file_path, fopen('php://input', 'r'), $append_file ? FILE_APPEND : 0);
  415. }
  416. $file_size = filesize($file_path);
  417. if ($file_size === $file->size)
  418. {
  419. $file->url = $this->options['upload_url'].rawurlencode($file->name);
  420. foreach($this->options['image_versions'] as $version => $options)
  421. {
  422. if ($this->createScaledImage($file->name, $options))
  423. {
  424. $tmp=explode('.',$file->name);
  425. $file->{$version.'_url'} = $options['upload_url'].rawurlencode($tmp[0].'_mini.'.$tmp[1]);
  426. }
  427. }
  428. }
  429. else if ($this->options['discard_aborted_uploads'])
  430. {
  431. unlink($file_path);
  432. $file->error = 'abort';
  433. }
  434. $file->size = $file_size;
  435. $this->setFileDeleteUrl($file);
  436. }
  437. return $file;
  438. }
  439. /**
  440. * Output data
  441. *
  442. * @return void
  443. */
  444. public function get()
  445. {
  446. $file_name = isset($_REQUEST['file']) ?
  447. basename(stripslashes($_REQUEST['file'])) : null;
  448. if ($file_name)
  449. {
  450. $info = $this->getFileObject($file_name);
  451. }
  452. else
  453. {
  454. $info = $this->getFileObjects();
  455. }
  456. header('Content-type: application/json');
  457. echo json_encode($info);
  458. }
  459. /**
  460. * Output data
  461. *
  462. * @return void
  463. */
  464. public function post()
  465. {
  466. if (isset($_REQUEST['_method']) && $_REQUEST['_method'] === 'DELETE')
  467. {
  468. return $this->delete();
  469. }
  470. $upload = isset($_FILES[$this->options['param_name']]) ?
  471. $_FILES[$this->options['param_name']] : null;
  472. $info = array();
  473. if ($upload && is_array($upload['tmp_name']))
  474. {
  475. // param_name is an array identifier like "files[]",
  476. // $_FILES is a multi-dimensional array:
  477. foreach ($upload['tmp_name'] as $index => $value) {
  478. $info[] = $this->handleFileUpload(
  479. $upload['tmp_name'][$index],
  480. isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : $upload['name'][$index],
  481. isset($_SERVER['HTTP_X_FILE_SIZE']) ? $_SERVER['HTTP_X_FILE_SIZE'] : $upload['size'][$index],
  482. isset($_SERVER['HTTP_X_FILE_TYPE']) ? $_SERVER['HTTP_X_FILE_TYPE'] : $upload['type'][$index],
  483. $upload['error'][$index],
  484. $index
  485. );
  486. }
  487. } elseif ($upload || isset($_SERVER['HTTP_X_FILE_NAME'])) {
  488. // param_name is a single object identifier like "file",
  489. // $_FILES is a one-dimensional array:
  490. $info[] = $this->handleFileUpload(
  491. isset($upload['tmp_name']) ? $upload['tmp_name'] : null,
  492. isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : (isset($upload['name']) ? $upload['name'] : null),
  493. isset($_SERVER['HTTP_X_FILE_SIZE']) ? $_SERVER['HTTP_X_FILE_SIZE'] : (isset($upload['size']) ? $upload['size'] : null),
  494. isset($_SERVER['HTTP_X_FILE_TYPE']) ? $_SERVER['HTTP_X_FILE_TYPE'] : (isset($upload['type']) ? $upload['type'] : null),
  495. isset($upload['error']) ? $upload['error'] : null,
  496. 0
  497. );
  498. }
  499. header('Vary: Accept');
  500. $json = json_encode($info);
  501. $redirect = isset($_REQUEST['redirect']) ?
  502. stripslashes($_REQUEST['redirect']) : null;
  503. if ($redirect) {
  504. header('Location: '.sprintf($redirect, rawurlencode($json)));
  505. return;
  506. }
  507. if (isset($_SERVER['HTTP_ACCEPT']) &&
  508. (strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false)) {
  509. header('Content-type: application/json');
  510. } else {
  511. header('Content-type: text/plain');
  512. }
  513. echo $json;
  514. }
  515. /**
  516. * Delete uploaded file
  517. *
  518. * @return void
  519. */
  520. public function delete()
  521. {
  522. $file_name = isset($_REQUEST['file']) ?
  523. basename(stripslashes($_REQUEST['file'])) : null;
  524. $file_path = $this->options['upload_dir'].$file_name;
  525. $success = is_file($file_path) && $file_name[0] !== '.' && unlink($file_path);
  526. if ($success)
  527. {
  528. foreach($this->options['image_versions'] as $version => $options)
  529. {
  530. $file = $options['upload_dir'].$file_name;
  531. if (is_file($file))
  532. {
  533. unlink($file);
  534. }
  535. }
  536. }
  537. header('Content-type: application/json');
  538. echo json_encode($success);
  539. }
  540. }