fileupload.class.php 17 KB

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