files.lib.php 88 KB

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