files.lib.php 88 KB

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