files.lib.php 82 KB

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