files.lib.php 85 KB

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