files.lib.php 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028
  1. <?php
  2. /* Copyright (C) 2008-2012 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2012-2015 Regis Houssin <regis.houssin@capnetworks.com>
  4. * Copyright (C) 2012-2016 Juanjo Menent <jmenent@2byte.es>
  5. * Copyright (C) 2015 Marcos García <marcosgdf@gmail.com>
  6. * Copyright (C) 2016 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  7. *
  8. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. * or see http://www.gnu.org/
  21. */
  22. /**
  23. * \file htdocs/core/lib/files.lib.php
  24. * \brief Library for file managing functions
  25. */
  26. /**
  27. * Make a basename working with all page code (default PHP basenamed fails with cyrillic).
  28. * We supose dir separator for input is '/'.
  29. *
  30. * @param string $pathfile String to find basename.
  31. * @return string Basename of input
  32. */
  33. function dol_basename($pathfile)
  34. {
  35. return preg_replace('/^.*\/([^\/]+)$/','$1',rtrim($pathfile,'/'));
  36. }
  37. /**
  38. * Scan a directory and return a list of files/directories.
  39. * Content for string is UTF8 and dir separator is "/".
  40. *
  41. * @param string $path Starting path from which to search
  42. * @param string $types Can be "directories", "files", or "all"
  43. * @param int $recursive Determines whether subdirectories are searched
  44. * @param string $filter Regex filter to restrict list. This regex value must be escaped for '/', since this char is used for preg_match function
  45. * @param array $excludefilter Array of Regex for exclude filter (example: array('(\.meta|_preview\.png)$','^\.'))
  46. * @param string $sortcriteria Sort criteria ("","fullname","name","date","size")
  47. * @param string $sortorder Sort order (SORT_ASC, SORT_DESC)
  48. * @param int $mode 0=Return array minimum keys loaded (faster), 1=Force all keys like date and size to be loaded (slower), 2=Force load of date only, 3=Force load of size only
  49. * @param int $nohook Disable all hooks
  50. * @return array Array of array('name'=>'xxx','fullname'=>'/abc/xxx','date'=>'yyy','size'=>99,'type'=>'dir|file')
  51. */
  52. function dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter="", $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=false)
  53. {
  54. global $db, $hookmanager;
  55. global $object;
  56. dol_syslog("files.lib.php::dol_dir_list path=".$path." types=".$types." recursive=".$recursive." filter=".$filter." excludefilter=".json_encode($excludefilter));
  57. //print 'xxx'."files.lib.php::dol_dir_list path=".$path." types=".$types." recursive=".$recursive." filter=".$filter." excludefilter=".json_encode($excludefilter);
  58. $loaddate=($mode==1||$mode==2)?true:false;
  59. $loadsize=($mode==1||$mode==3)?true:false;
  60. // Clean parameters
  61. $path=preg_replace('/([\\/]+)$/i','',$path);
  62. $newpath=dol_osencode($path);
  63. if (! $nohook)
  64. {
  65. $hookmanager->initHooks(array('fileslib'));
  66. $parameters=array(
  67. 'path' => $newpath,
  68. 'types'=> $types,
  69. 'recursive' => $recursive,
  70. 'filter' => $filter,
  71. 'excludefilter' => $excludefilter,
  72. 'sortcriteria' => $sortcriteria,
  73. 'sortorder' => $sortorder,
  74. 'loaddate' => $loaddate,
  75. 'loadsize' => $loadsize,
  76. 'mode' => $mode
  77. );
  78. $reshook=$hookmanager->executeHooks('getNodesList', $parameters, $object);
  79. }
  80. // $reshook may contain returns stacked by other modules
  81. // $reshook is always empty with an array for can not lose returns stacked with other modules
  82. // $hookmanager->resArray may contain array stacked by other modules
  83. if (! $nohook && ! empty($hookmanager->resArray)) // forced to use $hookmanager->resArray even if $hookmanager->resArray['nodes'] is empty
  84. {
  85. return $hookmanager->resArray['nodes'];
  86. }
  87. else
  88. {
  89. if (! is_dir($newpath)) return array();
  90. if ($dir = opendir($newpath))
  91. {
  92. $filedate='';
  93. $filesize='';
  94. $file_list = array();
  95. while (false !== ($file = readdir($dir)))
  96. {
  97. if (! utf8_check($file)) $file=utf8_encode($file); // To be sure data is stored in utf8 in memory
  98. $qualified=1;
  99. // Define excludefilterarray
  100. $excludefilterarray=array('^\.');
  101. if (is_array($excludefilter))
  102. {
  103. $excludefilterarray=array_merge($excludefilterarray,$excludefilter);
  104. }
  105. else if ($excludefilter) $excludefilterarray[]=$excludefilter;
  106. // Check if file is qualified
  107. foreach($excludefilterarray as $filt)
  108. {
  109. if (preg_match('/'.$filt.'/i',$file)) {
  110. $qualified=0; break;
  111. }
  112. }
  113. if ($qualified)
  114. {
  115. $isdir=is_dir(dol_osencode($path."/".$file));
  116. // Check whether this is a file or directory and whether we're interested in that type
  117. if ($isdir && (($types=="directories") || ($types=="all") || $recursive))
  118. {
  119. // Add entry into file_list array
  120. if (($types=="directories") || ($types=="all"))
  121. {
  122. if ($loaddate || $sortcriteria == 'date') $filedate=dol_filemtime($path."/".$file);
  123. if ($loadsize || $sortcriteria == 'size') $filesize=dol_filesize($path."/".$file);
  124. if (! $filter || preg_match('/'.$filter.'/i',$file)) // We do not search key $filter into $path, only into $file
  125. {
  126. preg_match('/([^\/]+)\/[^\/]+$/',$path.'/'.$file,$reg);
  127. $level1name=(isset($reg[1])?$reg[1]:'');
  128. $file_list[] = array(
  129. "name" => $file,
  130. "path" => $path,
  131. "level1name" => $level1name,
  132. "fullname" => $path.'/'.$file,
  133. "date" => $filedate,
  134. "size" => $filesize,
  135. "type" => 'dir'
  136. );
  137. }
  138. }
  139. // if we're in a directory and we want recursive behavior, call this function again
  140. if ($recursive)
  141. {
  142. $file_list = array_merge($file_list,dol_dir_list($path."/".$file, $types, $recursive, $filter, $excludefilter, $sortcriteria, $sortorder, $mode, $nohook));
  143. }
  144. }
  145. else if (! $isdir && (($types == "files") || ($types == "all")))
  146. {
  147. // Add file into file_list array
  148. if ($loaddate || $sortcriteria == 'date') $filedate=dol_filemtime($path."/".$file);
  149. if ($loadsize || $sortcriteria == 'size') $filesize=dol_filesize($path."/".$file);
  150. if (! $filter || preg_match('/'.$filter.'/i',$file)) // We do not search key $filter into $path, only into $file
  151. {
  152. preg_match('/([^\/]+)\/[^\/]+$/',$path.'/'.$file,$reg);
  153. $level1name=(isset($reg[1])?$reg[1]:'');
  154. $file_list[] = array(
  155. "name" => $file,
  156. "path" => $path,
  157. "level1name" => $level1name,
  158. "fullname" => $path.'/'.$file,
  159. "date" => $filedate,
  160. "size" => $filesize,
  161. "type" => 'file'
  162. );
  163. }
  164. }
  165. }
  166. }
  167. closedir($dir);
  168. // Obtain a list of columns
  169. if (! empty($sortcriteria))
  170. {
  171. $myarray=array();
  172. foreach ($file_list as $key => $row)
  173. {
  174. $myarray[$key] = (isset($row[$sortcriteria])?$row[$sortcriteria]:'');
  175. }
  176. // Sort the data
  177. if ($sortorder) array_multisort($myarray, $sortorder, $file_list);
  178. }
  179. return $file_list;
  180. }
  181. else
  182. {
  183. return array();
  184. }
  185. }
  186. }
  187. /**
  188. * Fast compare of 2 files identified by their properties ->name, ->date and ->size
  189. *
  190. * @param string $a File 1
  191. * @param string $b File 2
  192. * @return int 1, 0, 1
  193. */
  194. function dol_compare_file($a, $b)
  195. {
  196. global $sortorder;
  197. global $sortfield;
  198. $sortorder=strtoupper($sortorder);
  199. if ($sortorder == 'ASC') { $retup=-1; $retdown=1; }
  200. else { $retup=1; $retdown=-1; }
  201. if ($sortfield == 'name')
  202. {
  203. if ($a->name == $b->name) return 0;
  204. return ($a->name < $b->name) ? $retup : $retdown;
  205. }
  206. if ($sortfield == 'date')
  207. {
  208. if ($a->date == $b->date) return 0;
  209. return ($a->date < $b->date) ? $retup : $retdown;
  210. }
  211. if ($sortfield == 'size')
  212. {
  213. if ($a->size == $b->size) return 0;
  214. return ($a->size < $b->size) ? $retup : $retdown;
  215. }
  216. }
  217. /**
  218. * Test if filename is a directory
  219. *
  220. * @param string $folder Name of folder
  221. * @return boolean True if it's a directory, False if not found
  222. */
  223. function dol_is_dir($folder)
  224. {
  225. $newfolder=dol_osencode($folder);
  226. if (is_dir($newfolder)) return true;
  227. else return false;
  228. }
  229. /**
  230. * Return if path is a file
  231. *
  232. * @param string $pathoffile Path of file
  233. * @return boolean True or false
  234. */
  235. function dol_is_file($pathoffile)
  236. {
  237. $newpathoffile=dol_osencode($pathoffile);
  238. return is_file($newpathoffile);
  239. }
  240. /**
  241. * Return if path is an URL
  242. *
  243. * @param string $url Url
  244. * @return boolean True or false
  245. */
  246. function dol_is_url($url)
  247. {
  248. $tmpprot=array('file','http','https','ftp','zlib','data','ssh','ssh2','ogg','expect');
  249. foreach($tmpprot as $prot)
  250. {
  251. if (preg_match('/^'.$prot.':/i',$url)) return true;
  252. }
  253. return false;
  254. }
  255. /**
  256. * Test if a folder is empty
  257. *
  258. * @param string $folder Name of folder
  259. * @return boolean True if dir is empty or non-existing, False if it contains files
  260. */
  261. function dol_dir_is_emtpy($folder)
  262. {
  263. $newfolder=dol_osencode($folder);
  264. if (is_dir($newfolder))
  265. {
  266. $handle = opendir($newfolder);
  267. $folder_content = '';
  268. while ((gettype($name = readdir($handle)) != "boolean"))
  269. {
  270. $name_array[] = $name;
  271. }
  272. foreach($name_array as $temp) $folder_content .= $temp;
  273. closedir($handle);
  274. if ($folder_content == "...") return true;
  275. else return false;
  276. }
  277. else
  278. return true; // Dir does not exists
  279. }
  280. /**
  281. * Count number of lines in a file
  282. *
  283. * @param string $file Filename
  284. * @return int <0 if KO, Number of lines in files if OK
  285. */
  286. function dol_count_nb_of_line($file)
  287. {
  288. $nb=0;
  289. $newfile=dol_osencode($file);
  290. //print 'x'.$file;
  291. $fp=fopen($newfile,'r');
  292. if ($fp)
  293. {
  294. while (!feof($fp))
  295. {
  296. $line=fgets($fp);
  297. // We increase count only if read was success. We need test because feof return true only after fgets so we do n+1 fgets for a file with n lines.
  298. if (! $line === false) $nb++;
  299. }
  300. fclose($fp);
  301. }
  302. else
  303. {
  304. $nb=-1;
  305. }
  306. return $nb;
  307. }
  308. /**
  309. * Return size of a file
  310. *
  311. * @param string $pathoffile Path of file
  312. * @return integer File size
  313. */
  314. function dol_filesize($pathoffile)
  315. {
  316. $newpathoffile=dol_osencode($pathoffile);
  317. return filesize($newpathoffile);
  318. }
  319. /**
  320. * Return time of a file
  321. *
  322. * @param string $pathoffile Path of file
  323. * @return int Time of file
  324. */
  325. function dol_filemtime($pathoffile)
  326. {
  327. $newpathoffile=dol_osencode($pathoffile);
  328. return @filemtime($newpathoffile); // @Is to avoid errors if files does not exists
  329. }
  330. /**
  331. * Copy a file to another file.
  332. *
  333. * @param string $srcfile Source file (can't be a directory)
  334. * @param string $destfile Destination file (can't be a directory)
  335. * @param int $newmask Mask for new file (0 by default means $conf->global->MAIN_UMASK). Example: '0666'
  336. * @param int $overwriteifexists Overwrite file if exists (1 by default)
  337. * @return int <0 if error, 0 if nothing done (dest file already exists and overwriteifexists=0), >0 if OK
  338. * @see dolCopyr
  339. */
  340. function dol_copy($srcfile, $destfile, $newmask=0, $overwriteifexists=1)
  341. {
  342. global $conf;
  343. dol_syslog("files.lib.php::dol_copy srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." overwriteifexists=".$overwriteifexists);
  344. if (empty($srcfile) || empty($destfile)) return -1;
  345. $destexists=dol_is_file($destfile);
  346. if (! $overwriteifexists && $destexists) return 0;
  347. $newpathofsrcfile=dol_osencode($srcfile);
  348. $newpathofdestfile=dol_osencode($destfile);
  349. $newdirdestfile=dirname($newpathofdestfile);
  350. if ($destexists && ! is_writable($newpathofdestfile))
  351. {
  352. dol_syslog("files.lib.php::dol_copy failed Permission denied to overwrite target file", LOG_WARNING);
  353. return -1;
  354. }
  355. if (! is_writable($newdirdestfile))
  356. {
  357. dol_syslog("files.lib.php::dol_copy failed Permission denied to write into target directory ".$newdirdestfile, LOG_WARNING);
  358. return -2;
  359. }
  360. // Copy with overwriting if exists
  361. $result=@copy($newpathofsrcfile, $newpathofdestfile);
  362. //$result=copy($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @
  363. if (! $result)
  364. {
  365. dol_syslog("files.lib.php::dol_copy failed to copy", LOG_WARNING);
  366. return -3;
  367. }
  368. if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
  369. if (empty($newmask)) // This should no happen
  370. {
  371. dol_syslog("Warning: dol_copy called with empty value for newmask and no default value defined", LOG_WARNING);
  372. $newmask='0664';
  373. }
  374. @chmod($newpathofdestfile, octdec($newmask));
  375. return 1;
  376. }
  377. /**
  378. * Copy a dir to another dir.
  379. *
  380. * @param string $srcfile Source file (a directory)
  381. * @param string $destfile Destination file (a directory)
  382. * @param int $newmask Mask for new file (0 by default means $conf->global->MAIN_UMASK). Example: '0666'
  383. * @param int $overwriteifexists Overwrite file if exists (1 by default)
  384. * @return int <0 if error, 0 if nothing done (dest dir already exists and overwriteifexists=0), >0 if OK
  385. * @see dol_copy
  386. */
  387. function dolCopyDir($srcfile, $destfile, $newmask, $overwriteifexists)
  388. {
  389. global $conf;
  390. $result=0;
  391. dol_syslog("files.lib.php::dolCopyDir srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." overwriteifexists=".$overwriteifexists);
  392. if (empty($srcfile) || empty($destfile)) return -1;
  393. $destexists=dol_is_dir($destfile);
  394. if (! $overwriteifexists && $destexists) return 0;
  395. if (! $destexists)
  396. {
  397. // We must set mask just before creating dir, becaause it can be set differently by dol_copy
  398. umask(0);
  399. $dirmaskdec=octdec($newmask);
  400. if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $dirmaskdec=octdec($conf->global->MAIN_UMASK);
  401. $dirmaskdec |= octdec('0200'); // Set w bit required to be able to create content for recursive subdirs files
  402. dol_mkdir($destfile."/".$file, '', decoct($dirmaskdec));
  403. }
  404. $srcfile=dol_osencode($srcfile);
  405. $destfile=dol_osencode($destfile);
  406. // recursive function to copy
  407. // all subdirectories and contents:
  408. if (is_dir($srcfile))
  409. {
  410. $dir_handle=opendir($srcfile);
  411. while ($file=readdir($dir_handle))
  412. {
  413. if ($file!="." && $file!="..")
  414. {
  415. if (is_dir($srcfile."/".$file))
  416. {
  417. if (!is_dir($destfile."/".$file))
  418. {
  419. // We must set mask just before creating dir, becaause it can be set differently by dol_copy
  420. umask(0);
  421. $dirmaskdec=octdec($newmask);
  422. if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $dirmaskdec=octdec($conf->global->MAIN_UMASK);
  423. $dirmaskdec |= octdec('0200'); // Set w bit required to be able to create content for recursive subdirs files
  424. dol_mkdir($destfile."/".$file, '', decoct($dirmaskdec));
  425. }
  426. $result=dolCopyDir($srcfile."/".$file, $destfile."/".$file, $newmask, $overwriteifexists);
  427. }
  428. else
  429. {
  430. $result=dol_copy($srcfile."/".$file, $destfile."/".$file, $newmask, $overwriteifexists);
  431. }
  432. if ($result < 0) break;
  433. }
  434. }
  435. closedir($dir_handle);
  436. }
  437. else
  438. {
  439. $result=dol_copy($srcfile, $destfile, $newmask, $overwriteifexists);
  440. }
  441. return $result;
  442. }
  443. /**
  444. * Move a file into another name.
  445. * This function differs from dol_move_uploaded_file, because it can be called in any context.
  446. *
  447. * @param string $srcfile Source file (can't be a directory. use native php @rename() to move a directory)
  448. * @param string $destfile Destination file (can't be a directory. use native php @rename() to move a directory)
  449. * @param integer $newmask Mask in octal string for new file (0 by default means $conf->global->MAIN_UMASK)
  450. * @param int $overwriteifexists Overwrite file if exists (1 by default)
  451. * @return boolean True if OK, false if KO
  452. */
  453. function dol_move($srcfile, $destfile, $newmask=0, $overwriteifexists=1)
  454. {
  455. global $conf;
  456. $result=false;
  457. dol_syslog("files.lib.php::dol_move srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." overwritifexists=".$overwriteifexists);
  458. $destexists=dol_is_file($destfile);
  459. if ($overwriteifexists || ! $destexists)
  460. {
  461. $newpathofsrcfile=dol_osencode($srcfile);
  462. $newpathofdestfile=dol_osencode($destfile);
  463. $result=@rename($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @
  464. if (! $result)
  465. {
  466. if ($destexists)
  467. {
  468. dol_syslog("files.lib.php::dol_move failed. We try to delete first and move after.", LOG_WARNING);
  469. // We force delete and try again. Rename function sometimes fails to replace dest file with some windows NTFS partitions.
  470. dol_delete_file($destfile);
  471. $result=@rename($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @
  472. }
  473. else dol_syslog("files.lib.php::dol_move failed", LOG_WARNING);
  474. }
  475. if (empty($newmask)) $newmask=empty($conf->global->MAIN_UMASK)?'0755':$conf->global->MAIN_UMASK;
  476. $newmaskdec=octdec($newmask);
  477. // Currently method is restricted to files (dol_delete_files previously used is for files, and mask usage if for files too)
  478. // to allow mask usage for dir, we shoul introduce a new param "isdir" to 1 to complete newmask like this
  479. // if ($isdir) $newmaskdec |= octdec('0111'); // Set x bit required for directories
  480. @chmod($newpathofdestfile, $newmaskdec);
  481. }
  482. return $result;
  483. }
  484. /**
  485. * Unescape a file submitted by upload.
  486. * PHP escape char " (%22) or char ' (%27) into $FILES.
  487. *
  488. * @param string $filename Filename
  489. * @return string Filename sanitized
  490. */
  491. function dol_unescapefile($filename)
  492. {
  493. // Remove path information and dots around the filename, to prevent uploading
  494. // into different directories or replacing hidden system files.
  495. // Also remove control characters and spaces (\x00..\x20) around the filename:
  496. return trim(basename($filename), ".\x00..\x20");
  497. }
  498. /**
  499. * Make control on an uploaded file from an GUI page and move it to final destination.
  500. * If there is errors (virus found, antivir in error, bad filename), file is not moved.
  501. * Note: This function can be used only into a HTML page context. Use dol_move if you are outside.
  502. *
  503. * @param string $src_file Source full path filename ($_FILES['field']['tmp_name'])
  504. * @param string $dest_file Target full path filename ($_FILES['field']['name'])
  505. * @param int $allowoverwrite 1=Overwrite target file if it already exists
  506. * @param int $disablevirusscan 1=Disable virus scan
  507. * @param integer $uploaderrorcode Value of PHP upload error code ($_FILES['field']['error'])
  508. * @param int $nohook Disable all hooks
  509. * @param string $varfiles _FILES var name
  510. * @return int >0 if OK, <0 or string if KO
  511. * @see dol_move
  512. */
  513. function dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disablevirusscan=0, $uploaderrorcode=0, $nohook=0, $varfiles='addedfile')
  514. {
  515. global $conf, $db, $user, $langs;
  516. global $object, $hookmanager;
  517. $reshook=0;
  518. $file_name = $dest_file;
  519. if (empty($nohook))
  520. {
  521. // If an upload error has been reported
  522. if ($uploaderrorcode)
  523. {
  524. switch($uploaderrorcode)
  525. {
  526. case UPLOAD_ERR_INI_SIZE: // 1
  527. return 'ErrorFileSizeTooLarge';
  528. break;
  529. case UPLOAD_ERR_FORM_SIZE: // 2
  530. return 'ErrorFileSizeTooLarge';
  531. break;
  532. case UPLOAD_ERR_PARTIAL: // 3
  533. return 'ErrorPartialFile';
  534. break;
  535. case UPLOAD_ERR_NO_TMP_DIR: //
  536. return 'ErrorNoTmpDir';
  537. break;
  538. case UPLOAD_ERR_CANT_WRITE:
  539. return 'ErrorFailedToWriteInDir';
  540. break;
  541. case UPLOAD_ERR_EXTENSION:
  542. return 'ErrorUploadBlockedByAddon';
  543. break;
  544. default:
  545. break;
  546. }
  547. }
  548. // If we need to make a virus scan
  549. if (empty($disablevirusscan) && file_exists($src_file) && ! empty($conf->global->MAIN_ANTIVIRUS_COMMAND))
  550. {
  551. if (! class_exists('AntiVir')) {
  552. require_once DOL_DOCUMENT_ROOT.'/core/class/antivir.class.php';
  553. }
  554. $antivir=new AntiVir($db);
  555. $result = $antivir->dol_avscan_file($src_file);
  556. if ($result < 0) // If virus or error, we stop here
  557. {
  558. $reterrors=$antivir->errors;
  559. dol_syslog('Files.lib::dol_move_uploaded_file File "'.$src_file.'" (target name "'.$dest_file.'") KO with antivirus: result='.$result.' errors='.join(',',$antivir->errors), LOG_WARNING);
  560. return 'ErrorFileIsInfectedWithAVirus: '.join(',',$reterrors);
  561. }
  562. }
  563. // Security:
  564. // Disallow file with some extensions. We renamed them.
  565. // Car si on a mis le rep documents dans un rep de la racine web (pas bien), cela permet d'executer du code a la demande.
  566. if (preg_match('/\.htm|\.html|\.php|\.pl|\.cgi$/i',$dest_file) && empty($conf->global->MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED))
  567. {
  568. $file_name.= '.noexe';
  569. }
  570. // Security:
  571. // We refuse cache files/dirs, upload using .. and pipes into filenames.
  572. if (preg_match('/^\./',$src_file) || preg_match('/\.\./',$src_file) || preg_match('/[<>|]/',$src_file))
  573. {
  574. dol_syslog("Refused to deliver file ".$src_file, LOG_WARNING);
  575. return -1;
  576. }
  577. // Security:
  578. // On interdit fichiers caches, remontees de repertoire ainsi que les pipe dans les noms de fichiers.
  579. if (preg_match('/^\./',$dest_file) || preg_match('/\.\./',$dest_file) || preg_match('/[<>|]/',$dest_file))
  580. {
  581. dol_syslog("Refused to deliver file ".$dest_file, LOG_WARNING);
  582. return -2;
  583. }
  584. $reshook=$hookmanager->initHooks(array('fileslib'));
  585. $parameters=array('dest_file' => $dest_file, 'src_file' => $src_file, 'file_name' => $file_name, 'varfiles' => $varfiles, 'allowoverwrite' => $allowoverwrite);
  586. $reshook=$hookmanager->executeHooks('moveUploadedFile', $parameters, $object);
  587. }
  588. if ($reshook < 0) // At least one blocking error returned by one hook
  589. {
  590. $errmsg = join(',', $hookmanager->errors);
  591. if (empty($errmsg)) $errmsg = 'ErrorReturnedBySomeHooks'; // Should not occurs. Added if hook is bugged and does not set ->errors when there is error.
  592. return $errmsg;
  593. }
  594. elseif (empty($reshook))
  595. {
  596. // The file functions must be in OS filesystem encoding.
  597. $src_file_osencoded=dol_osencode($src_file);
  598. $file_name_osencoded=dol_osencode($file_name);
  599. // Check if destination dir is writable
  600. // TODO
  601. // Check if destination file already exists
  602. if (! $allowoverwrite)
  603. {
  604. if (file_exists($file_name_osencoded))
  605. {
  606. dol_syslog("Files.lib::dol_move_uploaded_file File ".$file_name." already exists. Return 'ErrorFileAlreadyExists'", LOG_WARNING);
  607. return 'ErrorFileAlreadyExists';
  608. }
  609. }
  610. // Move file
  611. $return=move_uploaded_file($src_file_osencoded, $file_name_osencoded);
  612. if ($return)
  613. {
  614. if (! empty($conf->global->MAIN_UMASK)) @chmod($file_name_osencoded, octdec($conf->global->MAIN_UMASK));
  615. dol_syslog("Files.lib::dol_move_uploaded_file Success to move ".$src_file." to ".$file_name." - Umask=".$conf->global->MAIN_UMASK, LOG_DEBUG);
  616. return 1; // Success
  617. }
  618. else
  619. {
  620. dol_syslog("Files.lib::dol_move_uploaded_file Failed to move ".$src_file." to ".$file_name, LOG_ERR);
  621. return -3; // Unknown error
  622. }
  623. }
  624. return 1; // Success
  625. }
  626. /**
  627. * Remove a file or several files with a mask
  628. *
  629. * @param string $file File to delete or mask of files to delete
  630. * @param int $disableglob Disable usage of glob like * so function is an exact delete function that will return error if no file found
  631. * @param int $nophperrors Disable all PHP output errors
  632. * @param int $nohook Disable all hooks
  633. * @param object $object Current object in use
  634. * @return boolean True if no error (file is deleted or if glob is used and there's nothing to delete), False if error
  635. * @see dol_delete_dir
  636. */
  637. function dol_delete_file($file,$disableglob=0,$nophperrors=0,$nohook=0,$object=null)
  638. {
  639. global $db, $conf, $user, $langs;
  640. global $hookmanager;
  641. $langs->load("other");
  642. $langs->load("errors");
  643. dol_syslog("dol_delete_file file=".$file." disableglob=".$disableglob." nophperrors=".$nophperrors." nohook=".$nohook);
  644. // Security:
  645. // We refuse transversal using .. and pipes into filenames.
  646. if (preg_match('/\.\./',$file) || preg_match('/[<>|]/',$file))
  647. {
  648. dol_syslog("Refused to delete file ".$file, LOG_WARNING);
  649. return False;
  650. }
  651. if (empty($nohook))
  652. {
  653. $hookmanager->initHooks(array('fileslib'));
  654. $parameters=array(
  655. 'GET' => $_GET,
  656. 'file' => $file,
  657. 'disableglob'=> $disableglob,
  658. 'nophperrors' => $nophperrors
  659. );
  660. $reshook=$hookmanager->executeHooks('deleteFile', $parameters, $object);
  661. }
  662. if (empty($nohook) && $reshook != 0) // reshook = 0 to do standard actions, 1 = ok, -1 = ko
  663. {
  664. if ($reshook < 0) return false;
  665. return true;
  666. }
  667. else
  668. {
  669. $error=0;
  670. //print "x".$file." ".$disableglob;exit;
  671. $file_osencoded=dol_osencode($file); // New filename encoded in OS filesystem encoding charset
  672. if (empty($disableglob) && ! empty($file_osencoded))
  673. {
  674. $ok=true;
  675. $globencoded=str_replace('[','\[',$file_osencoded);
  676. $globencoded=str_replace(']','\]',$globencoded);
  677. $listofdir=glob($globencoded);
  678. if (! empty($listofdir) && is_array($listofdir))
  679. {
  680. foreach ($listofdir as $filename)
  681. {
  682. if ($nophperrors) $ok=@unlink($filename);
  683. else $ok=unlink($filename);
  684. if ($ok) dol_syslog("Removed file ".$filename, LOG_DEBUG);
  685. else dol_syslog("Failed to remove file ".$filename, LOG_WARNING);
  686. // TODO Failure to remove can be because file was already removed or because of permission
  687. // If error because of not exists, we must can return true but we should return false if this is a permission problem
  688. }
  689. }
  690. else dol_syslog("No files to delete found", LOG_WARNING);
  691. }
  692. else
  693. {
  694. $ok=false;
  695. if ($nophperrors) $ok=@unlink($file_osencoded);
  696. else $ok=unlink($file_osencoded);
  697. if ($ok) dol_syslog("Removed file ".$file_osencoded, LOG_DEBUG);
  698. else dol_syslog("Failed to remove file ".$file_osencoded, LOG_WARNING);
  699. }
  700. return $ok;
  701. }
  702. }
  703. /**
  704. * Remove a directory (not recursive, so content must be empty).
  705. * If directory is not empty, return false
  706. *
  707. * @param string $dir Directory to delete
  708. * @param int $nophperrors Disable all PHP output errors
  709. * @return boolean True if success, false if error
  710. * @see dol_delete_file
  711. */
  712. function dol_delete_dir($dir,$nophperrors=0)
  713. {
  714. // Security:
  715. // We refuse transversal using .. and pipes into filenames.
  716. if (preg_match('/\.\./',$dir) || preg_match('/[<>|]/',$dir))
  717. {
  718. dol_syslog("Refused to delete dir ".$dir, LOG_WARNING);
  719. return False;
  720. }
  721. $dir_osencoded=dol_osencode($dir);
  722. return ($nophperrors?@rmdir($dir_osencoded):rmdir($dir_osencoded));
  723. }
  724. /**
  725. * Remove a directory $dir and its subdirectories (or only files and subdirectories)
  726. *
  727. * @param string $dir Dir to delete
  728. * @param int $count Counter to count nb of deleted elements
  729. * @param int $nophperrors Disable all PHP output errors
  730. * @param int $onlysub Delete only files and subdir, not main directory
  731. * @return int Number of files and directory removed
  732. */
  733. function dol_delete_dir_recursive($dir,$count=0,$nophperrors=0,$onlysub=0)
  734. {
  735. dol_syslog("functions.lib:dol_delete_dir_recursive ".$dir,LOG_DEBUG);
  736. if (dol_is_dir($dir))
  737. {
  738. $dir_osencoded=dol_osencode($dir);
  739. if ($handle = opendir("$dir_osencoded"))
  740. {
  741. while (false !== ($item = readdir($handle)))
  742. {
  743. if (! utf8_check($item)) $item=utf8_encode($item); // should be useless
  744. if ($item != "." && $item != "..")
  745. {
  746. if (is_dir(dol_osencode("$dir/$item")))
  747. {
  748. $count=dol_delete_dir_recursive("$dir/$item",$count,$nophperrors);
  749. }
  750. else
  751. {
  752. dol_delete_file("$dir/$item",1,$nophperrors);
  753. $count++;
  754. //echo " removing $dir/$item<br>\n";
  755. }
  756. }
  757. }
  758. closedir($handle);
  759. if (empty($onlysub))
  760. {
  761. dol_delete_dir($dir,$nophperrors);
  762. $count++;
  763. //echo "removing $dir<br>\n";
  764. }
  765. }
  766. }
  767. //echo "return=".$count;
  768. return $count;
  769. }
  770. /**
  771. * Delete all preview files linked to object instance
  772. *
  773. * @param object $object Object to clean
  774. * @return int 0 if error, 1 if OK
  775. */
  776. function dol_delete_preview($object)
  777. {
  778. global $langs,$conf;
  779. // Define parent dir of elements
  780. $element = $object->element;
  781. if ($object->element == 'order_supplier') $dir = $conf->fournisseur->dir_output.'/commande';
  782. elseif ($object->element == 'invoice_supplier') $dir = $conf->fournisseur->dir_output.'/facture';
  783. elseif ($object->element == 'project') $dir = $conf->projet->dir_output;
  784. elseif ($object->element == 'shipping') $dir = $conf->expedition->dir_output.'/sending';
  785. elseif ($object->element == 'delivery') $dir = $conf->expedition->dir_output.'/receipt';
  786. elseif ($object->element == 'fichinter') $dir = $conf->ficheinter->dir_output;
  787. else $dir=empty($conf->$element->dir_output)?'':$conf->$element->dir_output;
  788. if (empty($dir)) return 'ErrorObjectNoSupportedByFunction';
  789. $refsan = dol_sanitizeFileName($object->ref);
  790. $dir = $dir . "/" . $refsan ;
  791. $file = $dir . "/" . $refsan . ".pdf.png";
  792. $multiple = $file . ".";
  793. if (file_exists($file) && is_writable($file))
  794. {
  795. if (! dol_delete_file($file,1))
  796. {
  797. $object->error=$langs->trans("ErrorFailedToDeleteFile",$file);
  798. return 0;
  799. }
  800. }
  801. else
  802. {
  803. for ($i = 0; $i < 20; $i++)
  804. {
  805. $preview = $multiple.$i;
  806. if (file_exists($preview) && is_writable($preview))
  807. {
  808. if ( ! dol_delete_file($preview,1) )
  809. {
  810. $object->error=$langs->trans("ErrorFailedToOpenFile",$preview);
  811. return 0;
  812. }
  813. }
  814. }
  815. }
  816. return 1;
  817. }
  818. /**
  819. * Create a meta file with document file into same directory.
  820. * This should allow "grep" search.
  821. * This feature is enabled only if option MAIN_DOC_CREATE_METAFILE is set.
  822. *
  823. * @param CommonObject $object Object
  824. * @return int 0 if we did nothing, >0 success, <0 error
  825. */
  826. function dol_meta_create($object)
  827. {
  828. global $conf;
  829. if (empty($conf->global->MAIN_DOC_CREATE_METAFILE)) return 0; // By default, no metafile.
  830. // Define parent dir of elements
  831. $element=$object->element;
  832. if ($object->element == 'order_supplier') $dir = $conf->fournisseur->dir_output.'/commande';
  833. elseif ($object->element == 'invoice_supplier') $dir = $conf->fournisseur->dir_output.'/facture';
  834. elseif ($object->element == 'project') $dir = $conf->projet->dir_output;
  835. elseif ($object->element == 'shipping') $dir = $conf->expedition->dir_output.'/sending';
  836. elseif ($object->element == 'delivery') $dir = $conf->expedition->dir_output.'/receipt';
  837. elseif ($object->element == 'fichinter') $dir = $conf->ficheinter->dir_output;
  838. else $dir=empty($conf->$element->dir_output)?'':$conf->$element->dir_output;
  839. if ($dir)
  840. {
  841. $object->fetch_thirdparty();
  842. $facref = dol_sanitizeFileName($object->ref);
  843. $dir = $dir . "/" . $facref;
  844. $file = $dir . "/" . $facref . ".meta";
  845. if (! is_dir($dir))
  846. {
  847. dol_mkdir($dir);
  848. }
  849. if (is_dir($dir))
  850. {
  851. $nblignes = count($object->lines);
  852. $client = $object->thirdparty->name . " " . $object->thirdparty->address . " " . $object->thirdparty->zip . " " . $object->thirdparty->town;
  853. $meta = "REFERENCE=\"" . $object->ref . "\"
  854. DATE=\"" . dol_print_date($object->date,'') . "\"
  855. NB_ITEMS=\"" . $nblignes . "\"
  856. CLIENT=\"" . $client . "\"
  857. TOTAL_HT=\"" . $object->total_ht . "\"
  858. TOTAL_TTC=\"" . $object->total_ttc . "\"\n";
  859. for ($i = 0 ; $i < $nblignes ; $i++)
  860. {
  861. //Pour les articles
  862. $meta .= "ITEM_" . $i . "_QUANTITY=\"" . $object->lines[$i]->qty . "\"
  863. ITEM_" . $i . "_TOTAL_HT=\"" . $object->lines[$i]->total_ht . "\"
  864. ITEM_" . $i . "_TVA=\"" .$object->lines[$i]->tva_tx . "\"
  865. ITEM_" . $i . "_DESCRIPTION=\"" . str_replace("\r\n","",nl2br($object->lines[$i]->desc)) . "\"
  866. ";
  867. }
  868. }
  869. $fp = fopen($file,"w");
  870. fputs($fp,$meta);
  871. fclose($fp);
  872. if (! empty($conf->global->MAIN_UMASK))
  873. @chmod($file, octdec($conf->global->MAIN_UMASK));
  874. return 1;
  875. }
  876. return 0;
  877. }
  878. /**
  879. * Scan a directory and init $_SESSION to manage uploaded files with list of all found files.
  880. * Note: Only email module seems to use this. Other feature initialize the $_SESSION doing $formmail->clear_attached_files(); $formmail->add_attached_files()
  881. *
  882. * @param string $pathtoscan Path to scan
  883. * @param string $trackid Track id (used to prefix name of session vars to avoid conflict)
  884. * @return void
  885. */
  886. function dol_init_file_process($pathtoscan='', $trackid='')
  887. {
  888. $listofpaths=array();
  889. $listofnames=array();
  890. $listofmimes=array();
  891. if ($pathtoscan)
  892. {
  893. $listoffiles=dol_dir_list($pathtoscan,'files');
  894. foreach($listoffiles as $key => $val)
  895. {
  896. $listofpaths[]=$val['fullname'];
  897. $listofnames[]=$val['name'];
  898. $listofmimes[]=dol_mimetype($val['name']);
  899. }
  900. }
  901. $keytoavoidconflict = empty($trackid)?'':'-'.$trackid;
  902. $_SESSION["listofpaths".$keytoavoidconflict]=join(';',$listofpaths);
  903. $_SESSION["listofnames".$keytoavoidconflict]=join(';',$listofnames);
  904. $_SESSION["listofmimes".$keytoavoidconflict]=join(';',$listofmimes);
  905. }
  906. /**
  907. * Get and save an upload file (for example after submitting a new file a mail form).
  908. * All information used are in db, conf, langs, user and _FILES.
  909. * Note: This function can be used only into a HTML page context.
  910. *
  911. * @param string $upload_dir Directory where to store uploaded file (note: also find in first part of dest_file)
  912. * @param int $allowoverwrite 1=Allow overwrite existing file
  913. * @param int $donotupdatesession 1=Do no edit _SESSION variable
  914. * @param string $varfiles _FILES var name
  915. * @param string $savingdocmask Mask to use to define output filename. For example 'XXXXX-__YYYYMMDD__-__file__'
  916. * @param string $link Link to add
  917. * @param string $trackid Track id (used to prefix name of session vars to avoid conflict)
  918. * @return void
  919. */
  920. function dol_add_file_process($upload_dir, $allowoverwrite=0, $donotupdatesession=0, $varfiles='addedfile', $savingdocmask='', $link=null, $trackid='')
  921. {
  922. global $db,$user,$conf,$langs;
  923. if (! empty($_FILES[$varfiles])) // For view $_FILES[$varfiles]['error']
  924. {
  925. dol_syslog('dol_add_file_process upload_dir='.$upload_dir.' allowoverwrite='.$allowoverwrite.' donotupdatesession='.$donotupdatesession.' savingdocmask='.$savingdocmask, LOG_DEBUG);
  926. if (dol_mkdir($upload_dir) >= 0)
  927. {
  928. $TFile = $_FILES[$varfiles];
  929. if (!is_array($TFile['name']))
  930. {
  931. foreach ($TFile as $key => &$val)
  932. {
  933. $val = array($val);
  934. }
  935. }
  936. $nbfile = count($TFile['name']);
  937. for ($i = 0; $i < $nbfile; $i++)
  938. {
  939. // Define $destpath (path to file including filename) and $destfile (only filename)
  940. $destpath=$upload_dir . "/" . $TFile['name'][$i];
  941. $destfile=$TFile['name'][$i];
  942. $savingdocmask = dol_sanitizeFileName($savingdocmask);
  943. if ($savingdocmask)
  944. {
  945. $destpath=$upload_dir . "/" . preg_replace('/__file__/',$TFile['name'][$i],$savingdocmask);
  946. $destfile=preg_replace('/__file__/',$TFile['name'][$i],$savingdocmask);
  947. }
  948. // lowercase extension
  949. $info = pathinfo($destpath);
  950. $destpath = $info['dirname'].'/'.$info['filename'].'.'.strtolower($info['extension']);
  951. $info = pathinfo($destfile);
  952. $destfile = $info['filename'].'.'.strtolower($info['extension']);
  953. $resupload = dol_move_uploaded_file($TFile['tmp_name'][$i], $destpath, $allowoverwrite, 0, $TFile['error'][$i], 0, $varfiles);
  954. if (is_numeric($resupload) && $resupload > 0)
  955. {
  956. global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini;
  957. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  958. if (empty($donotupdatesession))
  959. {
  960. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  961. $formmail = new FormMail($db);
  962. $formmail->trackid = $trackid;
  963. $formmail->add_attached_files($destpath, $destfile, $TFile['type'][$i]);
  964. }
  965. if (image_format_supported($destpath) == 1)
  966. {
  967. // Create thumbs
  968. // We can't use $object->addThumbs here because there is no $object known
  969. // Used on logon for example
  970. $imgThumbSmall = vignette($destpath, $maxwidthsmall, $maxheightsmall, '_small', 50, "thumbs");
  971. // Create mini thumbs for image (Ratio is near 16/9)
  972. // Used on menu or for setup page for example
  973. $imgThumbMini = vignette($destpath, $maxwidthmini, $maxheightmini, '_mini', 50, "thumbs");
  974. }
  975. setEventMessages($langs->trans("FileTransferComplete"), null, 'mesgs');
  976. }
  977. else
  978. {
  979. $langs->load("errors");
  980. if ($resupload < 0) // Unknown error
  981. {
  982. setEventMessages($langs->trans("ErrorFileNotUploaded"), null, 'errors');
  983. }
  984. else if (preg_match('/ErrorFileIsInfectedWithAVirus/',$resupload)) // Files infected by a virus
  985. {
  986. setEventMessages($langs->trans("ErrorFileIsInfectedWithAVirus"), null, 'errors');
  987. }
  988. else // Known error
  989. {
  990. setEventMessages($langs->trans($resupload), null, 'errors');
  991. }
  992. }
  993. }
  994. }
  995. } elseif ($link) {
  996. require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php';
  997. $linkObject = new Link($db);
  998. $linkObject->entity = $conf->entity;
  999. $linkObject->url = $link;
  1000. $linkObject->objecttype = GETPOST('objecttype', 'alpha');
  1001. $linkObject->objectid = GETPOST('objectid', 'int');
  1002. $linkObject->label = GETPOST('label', 'alpha');
  1003. $res = $linkObject->create($user);
  1004. $langs->load('link');
  1005. if ($res > 0) {
  1006. setEventMessages($langs->trans("LinkComplete"), null, 'mesgs');
  1007. } else {
  1008. setEventMessages($langs->trans("ErrorFileNotLinked"), null, 'errors');
  1009. }
  1010. }
  1011. else
  1012. {
  1013. $langs->load("errors");
  1014. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("File")), null, 'errors');
  1015. }
  1016. }
  1017. /**
  1018. * Remove an uploaded file (for example after submitting a new file a mail form).
  1019. * All information used are in db, conf, langs, user and _FILES.
  1020. *
  1021. * @param int $filenb File nb to delete
  1022. * @param int $donotupdatesession 1=Do not edit _SESSION variable
  1023. * @param int $donotdeletefile 1=Do not delete physically file
  1024. * @param string $trackid Track id (used to prefix name of session vars to avoid conflict)
  1025. * @return void
  1026. */
  1027. function dol_remove_file_process($filenb,$donotupdatesession=0,$donotdeletefile=1,$trackid='')
  1028. {
  1029. global $db,$user,$conf,$langs,$_FILES;
  1030. $keytodelete=$filenb;
  1031. $keytodelete--;
  1032. $listofpaths=array();
  1033. $listofnames=array();
  1034. $listofmimes=array();
  1035. $keytoavoidconflict = empty($trackid)?'':'-'.$trackid;
  1036. if (! empty($_SESSION["listofpaths".$keytoavoidconflict])) $listofpaths=explode(';',$_SESSION["listofpaths".$keytoavoidconflict]);
  1037. if (! empty($_SESSION["listofnames".$keytoavoidconflict])) $listofnames=explode(';',$_SESSION["listofnames".$keytoavoidconflict]);
  1038. if (! empty($_SESSION["listofmimes".$keytoavoidconflict])) $listofmimes=explode(';',$_SESSION["listofmimes".$keytoavoidconflict]);
  1039. if ($keytodelete >= 0)
  1040. {
  1041. $pathtodelete=$listofpaths[$keytodelete];
  1042. $filetodelete=$listofnames[$keytodelete];
  1043. if (empty($donotdeletefile)) $result = dol_delete_file($pathtodelete,1);
  1044. else $result=0;
  1045. if ($result >= 0)
  1046. {
  1047. if (empty($donotdeletefile))
  1048. {
  1049. $langs->load("other");
  1050. setEventMessages($langs->trans("FileWasRemoved",$filetodelete), null, 'mesgs');
  1051. }
  1052. if (empty($donotupdatesession))
  1053. {
  1054. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  1055. $formmail = new FormMail($db);
  1056. $formmail->trackid = $trackid;
  1057. $formmail->remove_attached_files($keytodelete);
  1058. }
  1059. }
  1060. }
  1061. }
  1062. /**
  1063. * Convert an image file into anoher format.
  1064. * This need Imagick php extension.
  1065. *
  1066. * @param string $fileinput Input file name
  1067. * @param string $ext Format of target file (It is also extension added to file if fileoutput is not provided).
  1068. * @param string $fileoutput Output filename
  1069. * @return int <0 if KO, >0 if OK
  1070. */
  1071. function dol_convert_file($fileinput,$ext='png',$fileoutput='')
  1072. {
  1073. global $langs;
  1074. $image=new Imagick();
  1075. $ret = $image->readImage($fileinput);
  1076. if ($ret)
  1077. {
  1078. $ret = $image->setImageFormat($ext);
  1079. if ($ret)
  1080. {
  1081. if (empty($fileoutput)) $fileoutput=$fileinput.".".$ext;
  1082. $count = $image->getNumberImages();
  1083. $ret = $image->writeImages($fileoutput, true);
  1084. if ($ret) return $count;
  1085. else return -3;
  1086. }
  1087. else
  1088. {
  1089. return -2;
  1090. }
  1091. }
  1092. else
  1093. {
  1094. return -1;
  1095. }
  1096. }
  1097. /**
  1098. * Compress a file
  1099. *
  1100. * @param string $inputfile Source file name
  1101. * @param string $outputfile Target file name
  1102. * @param string $mode 'gz' or 'bz' or 'zip'
  1103. * @return int <0 if KO, >0 if OK
  1104. */
  1105. function dol_compress_file($inputfile, $outputfile, $mode="gz")
  1106. {
  1107. $foundhandler=0;
  1108. try
  1109. {
  1110. $data = implode("", file(dol_osencode($inputfile)));
  1111. if ($mode == 'gz') { $foundhandler=1; $compressdata = gzencode($data, 9); }
  1112. elseif ($mode == 'bz') { $foundhandler=1; $compressdata = bzcompress($data, 9); }
  1113. elseif ($mode == 'zip')
  1114. {
  1115. if (defined('ODTPHP_PATHTOPCLZIP'))
  1116. {
  1117. $foundhandler=1;
  1118. include_once ODTPHP_PATHTOPCLZIP.'/pclzip.lib.php';
  1119. $archive = new PclZip($outputfile);
  1120. $archive->add($inputfile, PCLZIP_OPT_REMOVE_PATH, dirname($inputfile));
  1121. //$archive->add($inputfile);
  1122. return 1;
  1123. }
  1124. }
  1125. if ($foundhandler)
  1126. {
  1127. $fp = fopen($outputfile, "w");
  1128. fwrite($fp, $compressdata);
  1129. fclose($fp);
  1130. return 1;
  1131. }
  1132. else
  1133. {
  1134. dol_syslog("Try to zip with format ".$mode." with no handler for this format",LOG_ERR);
  1135. return -2;
  1136. }
  1137. }
  1138. catch (Exception $e)
  1139. {
  1140. global $langs, $errormsg;
  1141. $langs->load("errors");
  1142. dol_syslog("Failed to open file ".$outputfile,LOG_ERR);
  1143. $errormsg=$langs->trans("ErrorFailedToWriteInDir");
  1144. return -1;
  1145. }
  1146. }
  1147. /**
  1148. * Uncompress a file
  1149. *
  1150. * @param string $inputfile File to uncompress
  1151. * @param string $outputdir Target dir name
  1152. * @return array array('error'=>'Error code') or array() if no error
  1153. */
  1154. function dol_uncompress($inputfile,$outputdir)
  1155. {
  1156. global $conf, $langs;
  1157. if (defined('ODTPHP_PATHTOPCLZIP'))
  1158. {
  1159. dol_syslog("Constant ODTPHP_PATHTOPCLZIP for pclzip library is set to ".constant('ODTPHP_PATHTOPCLZIP').", so we use Pclzip to unzip into ".$outputdir);
  1160. include_once ODTPHP_PATHTOPCLZIP.'/pclzip.lib.php';
  1161. $archive = new PclZip($inputfile);
  1162. $result=$archive->extract(PCLZIP_OPT_PATH, $outputdir);
  1163. //var_dump($result);
  1164. if (! is_array($result) && $result <= 0) return array('error'=>$archive->errorInfo(true));
  1165. else
  1166. {
  1167. $ok=1; $errmsg='';
  1168. // Loop on each file to check result for unzipping file
  1169. foreach($result as $key => $val)
  1170. {
  1171. if ($val['status'] == 'path_creation_fail')
  1172. {
  1173. $langs->load("errors");
  1174. $ok=0;
  1175. $errmsg=$langs->trans("ErrorFailToCreateDir", $val['filename']);
  1176. break;
  1177. }
  1178. }
  1179. if ($ok) return array();
  1180. else return array('error'=>$errmsg);
  1181. }
  1182. }
  1183. if (class_exists('ZipArchive'))
  1184. {
  1185. dol_syslog("Class ZipArchive is set so we unzip using ZipArchive to unzip into ".$outputdir);
  1186. $zip = new ZipArchive;
  1187. $res = $zip->open($inputfile);
  1188. if ($res === TRUE)
  1189. {
  1190. $zip->extractTo($outputdir.'/');
  1191. $zip->close();
  1192. return array();
  1193. }
  1194. else
  1195. {
  1196. return array('error'=>'ErrUnzipFails');
  1197. }
  1198. }
  1199. return array('error'=>'ErrNoZipEngine');
  1200. }
  1201. /**
  1202. * Return file(s) into a directory (by default most recent)
  1203. *
  1204. * @param string $dir Directory to scan
  1205. * @param string $regexfilter Regex filter to restrict list. This regex value must be escaped for '/', since this char is used for preg_match function
  1206. * @param array $excludefilter Array of Regex for exclude filter (example: array('(\.meta|_preview\.png)$','^\.')). This regex value must be escaped for '/', since this char is used for preg_match function
  1207. * @param int $nohook Disable all hooks
  1208. * @return string Full path to most recent file
  1209. */
  1210. function dol_most_recent_file($dir,$regexfilter='',$excludefilter=array('(\.meta|_preview\.png)$','^\.'),$nohook=false)
  1211. {
  1212. $tmparray=dol_dir_list($dir,'files',0,$regexfilter,$excludefilter,'date',SORT_DESC,'',$nohook);
  1213. return $tmparray[0];
  1214. }
  1215. /**
  1216. * Security check when accessing to a document (used by document.php, viewimage.php and webservices)
  1217. *
  1218. * @param string $modulepart Module of document ('module', 'module_user_temp', 'module_user' or 'module_temp')
  1219. * @param string $original_file Relative path with filename
  1220. * @param string $entity Restrict onto entity
  1221. * @param User $fuser User object (forced)
  1222. * @param string $refname Ref of object to check permission for external users (autodetect if not provided)
  1223. * @return mixed Array with access information : accessallowed & sqlprotectagainstexternals & original_file (as full path name)
  1224. */
  1225. function dol_check_secure_access_document($modulepart,$original_file,$entity,$fuser='',$refname='')
  1226. {
  1227. global $user, $conf, $db;
  1228. global $dolibarr_main_data_root;
  1229. if (! is_object($fuser)) $fuser=$user;
  1230. if (empty($modulepart)) return 'ErrorBadParameter';
  1231. if (empty($entity)) $entity=0;
  1232. dol_syslog('modulepart='.$modulepart.' original_file='.$original_file);
  1233. // We define $accessallowed and $sqlprotectagainstexternals
  1234. $accessallowed=0;
  1235. $sqlprotectagainstexternals='';
  1236. $ret=array();
  1237. // Find the subdirectory name as the reference. For exemple original_file='10/myfile.pdf' -> refname='10'
  1238. if (empty($refname)) $refname=basename(dirname($original_file)."/");
  1239. $relative_original_file = $original_file;
  1240. // Wrapping for some images
  1241. if ($modulepart == 'companylogo' && !empty($conf->mycompany->dir_output))
  1242. {
  1243. $accessallowed=1;
  1244. $original_file=$conf->mycompany->dir_output.'/logos/'.$original_file;
  1245. }
  1246. // Wrapping for users photos
  1247. elseif ($modulepart == 'userphoto' && !empty($conf->user->dir_output))
  1248. {
  1249. $accessallowed=1;
  1250. $original_file=$conf->user->dir_output.'/'.$original_file;
  1251. }
  1252. // Wrapping for members photos
  1253. elseif ($modulepart == 'memberphoto' && !empty($conf->adherent->dir_output))
  1254. {
  1255. $accessallowed=1;
  1256. $original_file=$conf->adherent->dir_output.'/'.$original_file;
  1257. }
  1258. // Wrapping pour les apercu factures
  1259. elseif ($modulepart == 'apercufacture' && !empty($conf->facture->dir_output))
  1260. {
  1261. if ($fuser->rights->facture->lire) $accessallowed=1;
  1262. $original_file=$conf->facture->dir_output.'/'.$original_file;
  1263. }
  1264. // Wrapping pour les apercu propal
  1265. elseif ($modulepart == 'apercupropal' && !empty($conf->propal->dir_output))
  1266. {
  1267. if ($fuser->rights->propale->lire) $accessallowed=1;
  1268. $original_file=$conf->propal->dir_output.'/'.$original_file;
  1269. }
  1270. // Wrapping pour les apercu commande
  1271. elseif ($modulepart == 'apercucommande' && !empty($conf->commande->dir_output))
  1272. {
  1273. if ($fuser->rights->commande->lire) $accessallowed=1;
  1274. $original_file=$conf->commande->dir_output.'/'.$original_file;
  1275. }
  1276. // Wrapping pour les apercu intervention
  1277. elseif ($modulepart == 'apercufichinter' && !empty($conf->ficheinter->dir_output))
  1278. {
  1279. if ($fuser->rights->ficheinter->lire) $accessallowed=1;
  1280. $original_file=$conf->ficheinter->dir_output.'/'.$original_file;
  1281. }
  1282. // Wrapping pour les images des stats propales
  1283. elseif ($modulepart == 'propalstats' && !empty($conf->propal->dir_temp))
  1284. {
  1285. if ($fuser->rights->propale->lire) $accessallowed=1;
  1286. $original_file=$conf->propal->dir_temp.'/'.$original_file;
  1287. }
  1288. // Wrapping pour les images des stats commandes
  1289. elseif ($modulepart == 'orderstats' && !empty($conf->commande->dir_temp))
  1290. {
  1291. if ($fuser->rights->commande->lire) $accessallowed=1;
  1292. $original_file=$conf->commande->dir_temp.'/'.$original_file;
  1293. }
  1294. elseif ($modulepart == 'orderstatssupplier' && !empty($conf->fournisseur->dir_output))
  1295. {
  1296. if ($fuser->rights->fournisseur->commande->lire) $accessallowed=1;
  1297. $original_file=$conf->fournisseur->dir_output.'/commande/temp/'.$original_file;
  1298. }
  1299. // Wrapping pour les images des stats factures
  1300. elseif ($modulepart == 'billstats' && !empty($conf->facture->dir_temp))
  1301. {
  1302. if ($fuser->rights->facture->lire) $accessallowed=1;
  1303. $original_file=$conf->facture->dir_temp.'/'.$original_file;
  1304. }
  1305. elseif ($modulepart == 'billstatssupplier' && !empty($conf->fournisseur->dir_output))
  1306. {
  1307. if ($fuser->rights->fournisseur->facture->lire) $accessallowed=1;
  1308. $original_file=$conf->fournisseur->dir_output.'/facture/temp/'.$original_file;
  1309. }
  1310. // Wrapping pour les images des stats expeditions
  1311. elseif ($modulepart == 'expeditionstats' && !empty($conf->expedition->dir_temp))
  1312. {
  1313. if ($fuser->rights->expedition->lire) $accessallowed=1;
  1314. $original_file=$conf->expedition->dir_temp.'/'.$original_file;
  1315. }
  1316. // Wrapping pour les images des stats expeditions
  1317. elseif ($modulepart == 'tripsexpensesstats' && !empty($conf->deplacement->dir_temp))
  1318. {
  1319. if ($fuser->rights->deplacement->lire) $accessallowed=1;
  1320. $original_file=$conf->deplacement->dir_temp.'/'.$original_file;
  1321. }
  1322. // Wrapping pour les images des stats expeditions
  1323. elseif ($modulepart == 'memberstats' && !empty($conf->adherent->dir_temp))
  1324. {
  1325. if ($fuser->rights->adherent->lire) $accessallowed=1;
  1326. $original_file=$conf->adherent->dir_temp.'/'.$original_file;
  1327. }
  1328. // Wrapping pour les images des stats produits
  1329. elseif (preg_match('/^productstats_/i',$modulepart) && !empty($conf->product->dir_temp))
  1330. {
  1331. if ($fuser->rights->produit->lire || $fuser->rights->service->lire) $accessallowed=1;
  1332. $original_file=(!empty($conf->product->multidir_temp[$entity])?$conf->product->multidir_temp[$entity]:$conf->service->multidir_temp[$entity]).'/'.$original_file;
  1333. }
  1334. // Wrapping for products or services
  1335. elseif ($modulepart == 'tax' && !empty($conf->tax->dir_output))
  1336. {
  1337. if ($fuser->rights->tax->charges->lire) $accessallowed=1;
  1338. $original_file=$conf->tax->dir_output.'/'.$original_file;
  1339. }
  1340. // Wrapping for products or services
  1341. elseif ($modulepart == 'actions' && !empty($conf->agenda->dir_output))
  1342. {
  1343. if ($fuser->rights->agenda->myactions->read) $accessallowed=1;
  1344. $original_file=$conf->agenda->dir_output.'/'.$original_file;
  1345. }
  1346. // Wrapping for categories
  1347. elseif ($modulepart == 'category' && !empty($conf->categorie->dir_output))
  1348. {
  1349. if ($fuser->rights->categorie->lire) $accessallowed=1;
  1350. $original_file=$conf->categorie->multidir_output[$entity].'/'.$original_file;
  1351. }
  1352. // Wrapping pour les prelevements
  1353. elseif ($modulepart == 'prelevement' && !empty($conf->prelevement->dir_output))
  1354. {
  1355. if ($fuser->rights->prelevement->bons->lire || preg_match('/^specimen/i',$original_file)) $accessallowed=1;
  1356. $original_file=$conf->prelevement->dir_output.'/'.$original_file;
  1357. }
  1358. // Wrapping pour les graph energie
  1359. elseif ($modulepart == 'graph_stock' && !empty($conf->stock->dir_temp))
  1360. {
  1361. $accessallowed=1;
  1362. $original_file=$conf->stock->dir_temp.'/'.$original_file;
  1363. }
  1364. // Wrapping pour les graph fournisseurs
  1365. elseif ($modulepart == 'graph_fourn' && !empty($conf->fournisseur->dir_temp))
  1366. {
  1367. $accessallowed=1;
  1368. $original_file=$conf->fournisseur->dir_temp.'/'.$original_file;
  1369. }
  1370. // Wrapping pour les graph des produits
  1371. elseif ($modulepart == 'graph_product' && !empty($conf->product->dir_temp))
  1372. {
  1373. $accessallowed=1;
  1374. $original_file=$conf->product->multidir_temp[$entity].'/'.$original_file;
  1375. }
  1376. // Wrapping pour les code barre
  1377. elseif ($modulepart == 'barcode')
  1378. {
  1379. $accessallowed=1;
  1380. // If viewimage is called for barcode, we try to output an image on the fly, with no build of file on disk.
  1381. //$original_file=$conf->barcode->dir_temp.'/'.$original_file;
  1382. $original_file='';
  1383. }
  1384. // Wrapping pour les icones de background des mailings
  1385. elseif ($modulepart == 'iconmailing' && !empty($conf->mailing->dir_temp))
  1386. {
  1387. $accessallowed=1;
  1388. $original_file=$conf->mailing->dir_temp.'/'.$original_file;
  1389. }
  1390. // Wrapping pour le scanner
  1391. elseif ($modulepart == 'scanner_user_temp' && !empty($conf->scanner->dir_temp))
  1392. {
  1393. $accessallowed=1;
  1394. $original_file=$conf->scanner->dir_temp.'/'.$fuser->id.'/'.$original_file;
  1395. }
  1396. // Wrapping pour les images fckeditor
  1397. elseif ($modulepart == 'fckeditor' && !empty($conf->fckeditor->dir_output))
  1398. {
  1399. $accessallowed=1;
  1400. $original_file=$conf->fckeditor->dir_output.'/'.$original_file;
  1401. }
  1402. // Wrapping for users
  1403. else if ($modulepart == 'user' && !empty($conf->user->dir_output))
  1404. {
  1405. $canreaduser=(! empty($fuser->admin) || $fuser->rights->user->user->lire);
  1406. if ($fuser->id == (int) $refname) { $canreaduser=1; } // A user can always read its own card
  1407. if ($canreaduser || preg_match('/^specimen/i',$original_file))
  1408. {
  1409. $accessallowed=1;
  1410. }
  1411. $original_file=$conf->user->dir_output.'/'.$original_file;
  1412. }
  1413. // Wrapping for third parties
  1414. else if (($modulepart == 'company' || $modulepart == 'societe') && !empty($conf->societe->dir_output))
  1415. {
  1416. if ($fuser->rights->societe->lire || preg_match('/^specimen/i',$original_file))
  1417. {
  1418. $accessallowed=1;
  1419. }
  1420. $original_file=$conf->societe->multidir_output[$entity].'/'.$original_file;
  1421. $sqlprotectagainstexternals = "SELECT rowid as fk_soc FROM ".MAIN_DB_PREFIX."societe WHERE rowid='".$db->escape($refname)."' AND entity IN (".getEntity('societe', 1).")";
  1422. }
  1423. // Wrapping for contact
  1424. else if ($modulepart == 'contact' && !empty($conf->societe->dir_output))
  1425. {
  1426. if ($fuser->rights->societe->lire)
  1427. {
  1428. $accessallowed=1;
  1429. }
  1430. $original_file=$conf->societe->multidir_output[$entity].'/contact/'.$original_file;
  1431. }
  1432. // Wrapping for invoices
  1433. else if (($modulepart == 'facture' || $modulepart == 'invoice') && !empty($conf->facture->dir_output))
  1434. {
  1435. if ($fuser->rights->facture->lire || preg_match('/^specimen/i',$original_file))
  1436. {
  1437. $accessallowed=1;
  1438. }
  1439. $original_file=$conf->facture->dir_output.'/'.$original_file;
  1440. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."facture WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  1441. }
  1442. else if ($modulepart == 'massfilesarea_proposals' && !empty($conf->propal->dir_output))
  1443. {
  1444. if ($fuser->rights->propal->lire || preg_match('/^specimen/i',$original_file))
  1445. {
  1446. $accessallowed=1;
  1447. }
  1448. $original_file=$conf->propal->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
  1449. }
  1450. else if ($modulepart == 'massfilesarea_orders')
  1451. {
  1452. if ($fuser->rights->commande->lire || preg_match('/^specimen/i',$original_file))
  1453. {
  1454. $accessallowed=1;
  1455. }
  1456. $original_file=$conf->commande->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
  1457. }
  1458. else if ($modulepart == 'massfilesarea_invoices')
  1459. {
  1460. if ($fuser->rights->facture->lire || preg_match('/^specimen/i',$original_file))
  1461. {
  1462. $accessallowed=1;
  1463. }
  1464. $original_file=$conf->facture->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
  1465. }
  1466. // Wrapping for interventions
  1467. else if (($modulepart == 'fichinter' || $modulepart == 'ficheinter') && !empty($conf->ficheinter->dir_output))
  1468. {
  1469. if ($fuser->rights->ficheinter->lire || preg_match('/^specimen/i',$original_file))
  1470. {
  1471. $accessallowed=1;
  1472. }
  1473. $original_file=$conf->ficheinter->dir_output.'/'.$original_file;
  1474. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."fichinter WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  1475. }
  1476. // Wrapping pour les deplacements et notes de frais
  1477. else if ($modulepart == 'deplacement' && !empty($conf->deplacement->dir_output))
  1478. {
  1479. if ($fuser->rights->deplacement->lire || preg_match('/^specimen/i',$original_file))
  1480. {
  1481. $accessallowed=1;
  1482. }
  1483. $original_file=$conf->deplacement->dir_output.'/'.$original_file;
  1484. //$sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."fichinter WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  1485. }
  1486. // Wrapping pour les propales
  1487. else if ($modulepart == 'propal' && !empty($conf->propal->dir_output))
  1488. {
  1489. if ($fuser->rights->propale->lire || preg_match('/^specimen/i',$original_file))
  1490. {
  1491. $accessallowed=1;
  1492. }
  1493. $original_file=$conf->propal->dir_output.'/'.$original_file;
  1494. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."propal WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  1495. }
  1496. // Wrapping pour les commandes
  1497. else if (($modulepart == 'commande' || $modulepart == 'order') && !empty($conf->commande->dir_output))
  1498. {
  1499. if ($fuser->rights->commande->lire || preg_match('/^specimen/i',$original_file))
  1500. {
  1501. $accessallowed=1;
  1502. }
  1503. $original_file=$conf->commande->dir_output.'/'.$original_file;
  1504. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."commande WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  1505. }
  1506. // Wrapping pour les projets
  1507. else if ($modulepart == 'project' && !empty($conf->projet->dir_output))
  1508. {
  1509. if ($fuser->rights->projet->lire || preg_match('/^specimen/i',$original_file))
  1510. {
  1511. $accessallowed=1;
  1512. }
  1513. $original_file=$conf->projet->dir_output.'/'.$original_file;
  1514. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."projet WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  1515. }
  1516. else if ($modulepart == 'project_task' && !empty($conf->projet->dir_output))
  1517. {
  1518. if ($fuser->rights->projet->lire || preg_match('/^specimen/i',$original_file))
  1519. {
  1520. $accessallowed=1;
  1521. }
  1522. $original_file=$conf->projet->dir_output.'/'.$original_file;
  1523. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."projet WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  1524. }
  1525. // Wrapping pour les commandes fournisseurs
  1526. else if (($modulepart == 'commande_fournisseur' || $modulepart == 'order_supplier') && !empty($conf->fournisseur->commande->dir_output))
  1527. {
  1528. if ($fuser->rights->fournisseur->commande->lire || preg_match('/^specimen/i',$original_file))
  1529. {
  1530. $accessallowed=1;
  1531. }
  1532. $original_file=$conf->fournisseur->commande->dir_output.'/'.$original_file;
  1533. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."commande_fournisseur WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  1534. }
  1535. // Wrapping pour les factures fournisseurs
  1536. else if (($modulepart == 'facture_fournisseur' || $modulepart == 'invoice_supplier') && !empty($conf->fournisseur->facture->dir_output))
  1537. {
  1538. if ($fuser->rights->fournisseur->facture->lire || preg_match('/^specimen/i',$original_file))
  1539. {
  1540. $accessallowed=1;
  1541. }
  1542. $original_file=$conf->fournisseur->facture->dir_output.'/'.$original_file;
  1543. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."facture_fourn WHERE facnumber='".$db->escape($refname)."' AND entity=".$conf->entity;
  1544. }
  1545. // Wrapping pour les rapport de paiements
  1546. else if ($modulepart == 'facture_paiement' && !empty($conf->facture->dir_output))
  1547. {
  1548. if ($fuser->rights->facture->lire || preg_match('/^specimen/i',$original_file))
  1549. {
  1550. $accessallowed=1;
  1551. }
  1552. if ($fuser->societe_id > 0) $original_file=$conf->facture->dir_output.'/payments/private/'.$fuser->id.'/'.$original_file;
  1553. else $original_file=$conf->facture->dir_output.'/payments/'.$original_file;
  1554. }
  1555. // Wrapping for accounting exports
  1556. else if ($modulepart == 'export_compta' && !empty($conf->accounting->dir_output))
  1557. {
  1558. if ($fuser->rights->accounting->bind->write || preg_match('/^specimen/i',$original_file))
  1559. {
  1560. $accessallowed=1;
  1561. }
  1562. $original_file=$conf->accounting->dir_output.'/'.$original_file;
  1563. }
  1564. // Wrapping pour les expedition
  1565. else if ($modulepart == 'expedition' && !empty($conf->expedition->dir_output))
  1566. {
  1567. if ($fuser->rights->expedition->lire || preg_match('/^specimen/i',$original_file))
  1568. {
  1569. $accessallowed=1;
  1570. }
  1571. $original_file=$conf->expedition->dir_output."/sending/".$original_file;
  1572. }
  1573. // Wrapping pour les bons de livraison
  1574. else if ($modulepart == 'livraison' && !empty($conf->expedition->dir_output))
  1575. {
  1576. if ($fuser->rights->expedition->livraison->lire || preg_match('/^specimen/i',$original_file))
  1577. {
  1578. $accessallowed=1;
  1579. }
  1580. $original_file=$conf->expedition->dir_output."/receipt/".$original_file;
  1581. }
  1582. // Wrapping pour les actions
  1583. else if ($modulepart == 'actions' && !empty($conf->agenda->dir_output))
  1584. {
  1585. if ($fuser->rights->agenda->myactions->read || preg_match('/^specimen/i',$original_file))
  1586. {
  1587. $accessallowed=1;
  1588. }
  1589. $original_file=$conf->agenda->dir_output.'/'.$original_file;
  1590. }
  1591. // Wrapping pour les actions
  1592. else if ($modulepart == 'actionsreport' && !empty($conf->agenda->dir_temp))
  1593. {
  1594. if ($fuser->rights->agenda->allactions->read || preg_match('/^specimen/i',$original_file))
  1595. {
  1596. $accessallowed=1;
  1597. }
  1598. $original_file = $conf->agenda->dir_temp."/".$original_file;
  1599. }
  1600. // Wrapping pour les produits et services
  1601. else if ($modulepart == 'product' || $modulepart == 'produit' || $modulepart == 'service' || $modulepart == 'produit|service')
  1602. {
  1603. if (($fuser->rights->produit->lire || $fuser->rights->service->lire) || preg_match('/^specimen/i',$original_file))
  1604. {
  1605. $accessallowed=1;
  1606. }
  1607. if (! empty($conf->product->enabled)) $original_file=$conf->product->multidir_output[$entity].'/'.$original_file;
  1608. elseif (! empty($conf->service->enabled)) $original_file=$conf->service->multidir_output[$entity].'/'.$original_file;
  1609. }
  1610. // Wrapping pour les contrats
  1611. else if ($modulepart == 'contract' && !empty($conf->contrat->dir_output))
  1612. {
  1613. if ($fuser->rights->contrat->lire || preg_match('/^specimen/i',$original_file))
  1614. {
  1615. $accessallowed=1;
  1616. }
  1617. $original_file=$conf->contrat->dir_output.'/'.$original_file;
  1618. }
  1619. // Wrapping pour les dons
  1620. else if ($modulepart == 'donation' && !empty($conf->donation->dir_output))
  1621. {
  1622. if ($fuser->rights->don->lire || preg_match('/^specimen/i',$original_file))
  1623. {
  1624. $accessallowed=1;
  1625. }
  1626. $original_file=$conf->don->dir_output.'/'.$original_file;
  1627. }
  1628. // Wrapping pour les remises de cheques
  1629. else if ($modulepart == 'remisecheque' && !empty($conf->banque->dir_output))
  1630. {
  1631. if ($fuser->rights->banque->lire || preg_match('/^specimen/i',$original_file))
  1632. {
  1633. $accessallowed=1;
  1634. }
  1635. $original_file=$conf->bank->dir_output.'/checkdeposits/'.$original_file; // original_file should contains relative path so include the get_exdir result
  1636. }
  1637. // Wrapping for bank
  1638. else if ($modulepart == 'bank' && !empty($conf->bank->dir_output))
  1639. {
  1640. if ($fuser->rights->banque->lire)
  1641. {
  1642. $accessallowed=1;
  1643. }
  1644. $original_file=$conf->bank->dir_output.'/'.$original_file;
  1645. }
  1646. // Wrapping for export module
  1647. else if ($modulepart == 'export' && !empty($conf->export->dir_temp))
  1648. {
  1649. // Aucun test necessaire car on force le rep de download sur
  1650. // le rep export qui est propre a l'utilisateur
  1651. $accessallowed=1;
  1652. $original_file=$conf->export->dir_temp.'/'.$fuser->id.'/'.$original_file;
  1653. }
  1654. // Wrapping for import module
  1655. else if ($modulepart == 'import' && !empty($conf->import->dir_temp))
  1656. {
  1657. $accessallowed=1;
  1658. $original_file=$conf->import->dir_temp.'/'.$original_file;
  1659. }
  1660. // Wrapping pour l'editeur wysiwyg
  1661. else if ($modulepart == 'editor' && !empty($conf->fckeditor->dir_output))
  1662. {
  1663. $accessallowed=1;
  1664. $original_file=$conf->fckeditor->dir_output.'/'.$original_file;
  1665. }
  1666. // Wrapping for miscellaneous medias files
  1667. elseif ($modulepart == 'medias' && !empty($dolibarr_main_data_root))
  1668. {
  1669. $accessallowed=1;
  1670. $original_file=$dolibarr_main_data_root.'/medias/'.$original_file;
  1671. }
  1672. // Wrapping for backups
  1673. else if ($modulepart == 'systemtools' && !empty($conf->admin->dir_output))
  1674. {
  1675. if ($fuser->admin) $accessallowed=1;
  1676. $original_file=$conf->admin->dir_output.'/'.$original_file;
  1677. }
  1678. // Wrapping for upload file test
  1679. else if ($modulepart == 'admin_temp' && !empty($conf->admin->dir_temp))
  1680. {
  1681. if ($fuser->admin) $accessallowed=1;
  1682. $original_file=$conf->admin->dir_temp.'/'.$original_file;
  1683. }
  1684. // Wrapping pour BitTorrent
  1685. else if ($modulepart == 'bittorrent' && !empty($conf->bittorrent->dir_output))
  1686. {
  1687. $accessallowed=1;
  1688. $dir='files';
  1689. if (dol_mimetype($original_file) == 'application/x-bittorrent') $dir='torrents';
  1690. $original_file=$conf->bittorrent->dir_output.'/'.$dir.'/'.$original_file;
  1691. }
  1692. // Wrapping pour Foundation module
  1693. else if ($modulepart == 'member' && !empty($conf->adherent->dir_output))
  1694. {
  1695. if ($fuser->rights->adherent->lire || preg_match('/^specimen/i',$original_file))
  1696. {
  1697. $accessallowed=1;
  1698. }
  1699. $original_file=$conf->adherent->dir_output.'/'.$original_file;
  1700. }
  1701. // Wrapping for Scanner
  1702. else if ($modulepart == 'scanner_user_temp' && !empty($conf->scanner->dir_temp))
  1703. {
  1704. $accessallowed=1;
  1705. $original_file=$conf->scanner->dir_temp.'/'.$fuser->id.'/'.$original_file;
  1706. }
  1707. // GENERIC Wrapping
  1708. // If modulepart=module_user_temp Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/temp/iduser
  1709. // If modulepart=module_temp Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/temp
  1710. // If modulepart=module_user Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/iduser
  1711. // If modulepart=module Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart
  1712. else
  1713. {
  1714. if (preg_match('/^specimen/i',$original_file)) $accessallowed=1; // If link to a file called specimen. Test must be done before changing $original_file int full path.
  1715. if ($fuser->admin) $accessallowed=1; // If user is admin
  1716. // Define $accessallowed
  1717. if (preg_match('/^([a-z]+)_user_temp$/i',$modulepart,$reg))
  1718. {
  1719. if (empty($conf->{$reg[1]}->dir_temp)) // modulepart not supported
  1720. {
  1721. dol_print_error('','Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
  1722. exit;
  1723. }
  1724. if ($fuser->rights->{$reg[1]}->lire || $fuser->rights->{$reg[1]}->read || ($fuser->rights->{$reg[1]}->download)) $accessallowed=1;
  1725. $original_file=$conf->{$reg[1]}->dir_temp.'/'.$fuser->id.'/'.$original_file;
  1726. }
  1727. else if (preg_match('/^([a-z]+)_temp$/i',$modulepart,$reg))
  1728. {
  1729. if (empty($conf->{$reg[1]}->dir_temp)) // modulepart not supported
  1730. {
  1731. dol_print_error('','Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
  1732. exit;
  1733. }
  1734. if ($fuser->rights->{$reg[1]}->lire || $fuser->rights->{$reg[1]}->read || ($fuser->rights->{$reg[1]}->download)) $accessallowed=1;
  1735. $original_file=$conf->{$reg[1]}->dir_temp.'/'.$original_file;
  1736. }
  1737. else if (preg_match('/^([a-z]+)_user$/i',$modulepart,$reg))
  1738. {
  1739. if (empty($conf->{$reg[1]}->dir_output)) // modulepart not supported
  1740. {
  1741. dol_print_error('','Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
  1742. exit;
  1743. }
  1744. if ($fuser->rights->{$reg[1]}->lire || $fuser->rights->{$reg[1]}->read || ($fuser->rights->{$reg[1]}->download)) $accessallowed=1;
  1745. $original_file=$conf->{$reg[1]}->dir_output.'/'.$fuser->id.'/'.$original_file;
  1746. }
  1747. else
  1748. {
  1749. if (empty($conf->$modulepart->dir_output)) // modulepart not supported
  1750. {
  1751. dol_print_error('','Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
  1752. exit;
  1753. }
  1754. $perm=GETPOST('perm');
  1755. $subperm=GETPOST('subperm');
  1756. if ($perm || $subperm)
  1757. {
  1758. if (($perm && ! $subperm && $fuser->rights->$modulepart->$perm) || ($perm && $subperm && $fuser->rights->$modulepart->$perm->$subperm)) $accessallowed=1;
  1759. $original_file=$conf->$modulepart->dir_output.'/'.$original_file;
  1760. }
  1761. else
  1762. {
  1763. if ($fuser->rights->$modulepart->lire || $fuser->rights->$modulepart->read) $accessallowed=1;
  1764. $original_file=$conf->$modulepart->dir_output.'/'.$original_file;
  1765. }
  1766. }
  1767. // For modules who wants to manage different levels of permissions for documents
  1768. $subPermCategoryConstName = strtoupper($modulepart).'_SUBPERMCATEGORY_FOR_DOCUMENTS';
  1769. if (! empty($conf->global->$subPermCategoryConstName))
  1770. {
  1771. $subPermCategory = $conf->global->$subPermCategoryConstName;
  1772. if (! empty($subPermCategory) && (($fuser->rights->$modulepart->$subPermCategory->lire) || ($fuser->rights->$modulepart->$subPermCategory->read) || ($fuser->rights->$modulepart->$subPermCategory->download)))
  1773. {
  1774. $accessallowed=1;
  1775. }
  1776. }
  1777. // Define $sqlprotectagainstexternals for modules who want to protect access using a SQL query.
  1778. $sqlProtectConstName = strtoupper($modulepart).'_SQLPROTECTAGAINSTEXTERNALS_FOR_DOCUMENTS';
  1779. if (! empty($conf->global->$sqlProtectConstName)) // If module want to define its own $sqlprotectagainstexternals
  1780. {
  1781. // Example: mymodule__SQLPROTECTAGAINSTEXTERNALS_FOR_DOCUMENTS = "SELECT fk_soc FROM ".MAIN_DB_PREFIX.$modulepart." WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  1782. eval('$sqlprotectagainstexternals = "'.$conf->global->$sqlProtectConstName.'";');
  1783. }
  1784. }
  1785. $ret = array(
  1786. 'accessallowed' => $accessallowed,
  1787. 'sqlprotectagainstexternals'=>$sqlprotectagainstexternals,
  1788. 'original_file'=>$original_file
  1789. );
  1790. return $ret;
  1791. }
  1792. /**
  1793. * Store object in file.
  1794. *
  1795. * @param string $directory Directory of cache
  1796. * @param string $filename Name of filecache
  1797. * @param mixed $object Object to store in cachefile
  1798. * @return void
  1799. */
  1800. function dol_filecache($directory, $filename, $object)
  1801. {
  1802. if (! dol_is_dir($directory)) dol_mkdir($directory);
  1803. $cachefile = $directory . $filename;
  1804. file_put_contents($cachefile, serialize($object), LOCK_EX);
  1805. @chmod($cachefile, 0644);
  1806. }
  1807. /**
  1808. * Test if Refresh needed.
  1809. *
  1810. * @param string $directory Directory of cache
  1811. * @param string $filename Name of filecache
  1812. * @param int $cachetime Cachetime delay
  1813. * @return boolean 0 no refresh 1 if refresh needed
  1814. */
  1815. function dol_cache_refresh($directory, $filename, $cachetime)
  1816. {
  1817. $now = dol_now();
  1818. $cachefile = $directory . $filename;
  1819. $refresh = !file_exists($cachefile) || ($now-$cachetime) > dol_filemtime($cachefile);
  1820. return $refresh;
  1821. }
  1822. /**
  1823. * Read object from cachefile.
  1824. *
  1825. * @param string $directory Directory of cache
  1826. * @param string $filename Name of filecache
  1827. * @return mixed Unserialise from file
  1828. */
  1829. function dol_readcachefile($directory, $filename)
  1830. {
  1831. $cachefile = $directory . $filename;
  1832. $object = unserialize(file_get_contents($cachefile));
  1833. return $object;
  1834. }