files.lib.php 130 KB

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