files.lib.php 103 KB

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