files.lib.php 80 KB

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