files.lib.php 85 KB

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