files.lib.php 132 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318
  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. dolChmod($newpathoftmpdestfile, $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. dolChmod($newpathofdestfile, $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. dolChmod($newpathofdestfile, $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. global $dolibarr_main_restrict_os_commands;
  801. if (!empty($dolibarr_main_restrict_os_commands)) {
  802. $arrayofallowedcommand = explode(',', $dolibarr_main_restrict_os_commands);
  803. $arrayofallowedcommand = array_map('trim', $arrayofallowedcommand);
  804. if (in_array(basename($destfile), $arrayofallowedcommand)) {
  805. //$langs->load("errors"); // key must be loaded because we can't rely on loading during output, we need var substitution to be done now.
  806. //setEventMessages($langs->trans("ErrorFilenameReserved", basename($destfile)), null, 'errors');
  807. dol_syslog("files.lib.php::dol_move canceled because target filename ".basename($destfile)." is using a reserved command name. we ignore the move request.", LOG_WARNING);
  808. return false;
  809. }
  810. }
  811. $result = @rename($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @
  812. if (!$result) {
  813. if ($destexists) {
  814. dol_syslog("files.lib.php::dol_move Failed. We try to delete target first and move after.", LOG_WARNING);
  815. // We force delete and try again. Rename function sometimes fails to replace dest file with some windows NTFS partitions.
  816. dol_delete_file($destfile);
  817. $result = @rename($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @
  818. } else {
  819. dol_syslog("files.lib.php::dol_move Failed.", LOG_WARNING);
  820. }
  821. }
  822. // Move ok
  823. if ($result && $indexdatabase) {
  824. // Rename entry into ecm database
  825. $rel_filetorenamebefore = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $srcfile);
  826. $rel_filetorenameafter = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $destfile);
  827. if (!preg_match('/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filetorenameafter)) { // If not a tmp file
  828. $rel_filetorenamebefore = preg_replace('/^[\\/]/', '', $rel_filetorenamebefore);
  829. $rel_filetorenameafter = preg_replace('/^[\\/]/', '', $rel_filetorenameafter);
  830. //var_dump($rel_filetorenamebefore.' - '.$rel_filetorenameafter);exit;
  831. dol_syslog("Try to rename also entries in database for full relative path before = ".$rel_filetorenamebefore." after = ".$rel_filetorenameafter, LOG_DEBUG);
  832. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  833. $ecmfiletarget = new EcmFiles($db);
  834. $resultecmtarget = $ecmfiletarget->fetch(0, '', $rel_filetorenameafter);
  835. if ($resultecmtarget > 0) { // An entry for target name already exists for target, we delete it, a new one will be created.
  836. $ecmfiletarget->delete($user);
  837. }
  838. $ecmfile = new EcmFiles($db);
  839. $resultecm = $ecmfile->fetch(0, '', $rel_filetorenamebefore);
  840. if ($resultecm > 0) { // If an entry was found for src file, we use it to move entry
  841. $filename = basename($rel_filetorenameafter);
  842. $rel_dir = dirname($rel_filetorenameafter);
  843. $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
  844. $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
  845. $ecmfile->filepath = $rel_dir;
  846. $ecmfile->filename = $filename;
  847. $resultecm = $ecmfile->update($user);
  848. } elseif ($resultecm == 0) { // If no entry were found for src files, create/update target file
  849. $filename = basename($rel_filetorenameafter);
  850. $rel_dir = dirname($rel_filetorenameafter);
  851. $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
  852. $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
  853. $ecmfile->filepath = $rel_dir;
  854. $ecmfile->filename = $filename;
  855. $ecmfile->label = md5_file(dol_osencode($destfile)); // $destfile is a full path to file
  856. $ecmfile->fullpath_orig = $srcfile;
  857. $ecmfile->gen_or_uploaded = 'unknown';
  858. $ecmfile->description = ''; // indexed content
  859. $ecmfile->keywords = ''; // keyword content
  860. $resultecm = $ecmfile->create($user);
  861. if ($resultecm < 0) {
  862. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  863. }
  864. } elseif ($resultecm < 0) {
  865. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  866. }
  867. if ($resultecm > 0) {
  868. $result = true;
  869. } else {
  870. $result = false;
  871. }
  872. }
  873. }
  874. if (empty($newmask)) {
  875. $newmask = empty($conf->global->MAIN_UMASK) ? '0755' : $conf->global->MAIN_UMASK;
  876. }
  877. // Currently method is restricted to files (dol_delete_files previously used is for files, and mask usage if for files too)
  878. // to allow mask usage for dir, we shoul introduce a new param "isdir" to 1 to complete newmask like this
  879. // if ($isdir) $newmaskdec |= octdec('0111'); // Set x bit required for directories
  880. dolChmod($newpathofdestfile, $newmask);
  881. }
  882. return $result;
  883. }
  884. /**
  885. * Move a directory into another name.
  886. *
  887. * @param string $srcdir Source directory
  888. * @param string $destdir Destination directory
  889. * @param int $overwriteifexists Overwrite directory if exists (1 by default)
  890. * @param int $indexdatabase Index new name of files into database.
  891. * @param int $renamedircontent Also rename contents inside srcdir after the move to match new destination name.
  892. *
  893. * @return boolean True if OK, false if KO
  894. */
  895. function dol_move_dir($srcdir, $destdir, $overwriteifexists = 1, $indexdatabase = 1, $renamedircontent = 1)
  896. {
  897. global $user, $db, $conf;
  898. $result = false;
  899. dol_syslog("files.lib.php::dol_move_dir srcdir=".$srcdir." destdir=".$destdir." overwritifexists=".$overwriteifexists." indexdatabase=".$indexdatabase." renamedircontent=".$renamedircontent);
  900. $srcexists = dol_is_dir($srcdir);
  901. $srcbasename = basename($srcdir);
  902. $destexists = dol_is_dir($destdir);
  903. if (!$srcexists) {
  904. dol_syslog("files.lib.php::dol_move_dir srcdir does not exists. we ignore the move request.");
  905. return false;
  906. }
  907. if ($overwriteifexists || !$destexists) {
  908. $newpathofsrcdir = dol_osencode($srcdir);
  909. $newpathofdestdir = dol_osencode($destdir);
  910. $result = @rename($newpathofsrcdir, $newpathofdestdir);
  911. if ($result && $renamedircontent) {
  912. if (file_exists($newpathofdestdir)) {
  913. $destbasename = basename($newpathofdestdir);
  914. $files = dol_dir_list($newpathofdestdir);
  915. if (!empty($files) && is_array($files)) {
  916. foreach ($files as $key => $file) {
  917. if (!file_exists($file["fullname"])) continue;
  918. $filepath = $file["path"];
  919. $oldname = $file["name"];
  920. $newname = str_replace($srcbasename, $destbasename, $oldname);
  921. if (!empty($newname) && $newname !== $oldname) {
  922. if ($file["type"] == "dir") {
  923. $res = dol_move_dir($filepath.'/'.$oldname, $filepath.'/'.$newname, $overwriteifexists, $indexdatabase, $renamedircontent);
  924. } else {
  925. $res = dol_move($filepath.'/'.$oldname, $filepath.'/'.$newname, 0, $overwriteifexists, 0, $indexdatabase);
  926. }
  927. if (!$res) {
  928. return $result;
  929. }
  930. }
  931. }
  932. $result = true;
  933. }
  934. }
  935. }
  936. }
  937. return $result;
  938. }
  939. /**
  940. * Unescape a file submitted by upload.
  941. * PHP escape char " (%22) or char ' (%27) into $FILES.
  942. *
  943. * @param string $filename Filename
  944. * @return string Filename sanitized
  945. */
  946. function dol_unescapefile($filename)
  947. {
  948. // Remove path information and dots around the filename, to prevent uploading
  949. // into different directories or replacing hidden system files.
  950. // Also remove control characters and spaces (\x00..\x20) around the filename:
  951. return trim(basename($filename), ".\x00..\x20");
  952. }
  953. /**
  954. * Check virus into a file
  955. *
  956. * @param string $src_file Source file to check
  957. * @return array Array of errors or empty array if not virus found
  958. */
  959. function dolCheckVirus($src_file)
  960. {
  961. global $conf, $db;
  962. if (!empty($conf->global->MAIN_ANTIVIRUS_COMMAND)) {
  963. if (!class_exists('AntiVir')) {
  964. require_once DOL_DOCUMENT_ROOT.'/core/class/antivir.class.php';
  965. }
  966. $antivir = new AntiVir($db);
  967. $result = $antivir->dol_avscan_file($src_file);
  968. if ($result < 0) { // If virus or error, we stop here
  969. $reterrors = $antivir->errors;
  970. return $reterrors;
  971. }
  972. }
  973. return array();
  974. }
  975. /**
  976. * Make control on an uploaded file from an GUI page and move it to final destination.
  977. * If there is errors (virus found, antivir in error, bad filename), file is not moved.
  978. * Note:
  979. * - This function can be used only into a HTML page context. Use dol_move if you are outside.
  980. * - Test on antivirus is always done (if antivirus set).
  981. * - Database of files is NOT updated (this is done by dol_add_file_process() that calls this function).
  982. * - Extension .noexe may be added if file is executable and MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED is not set.
  983. *
  984. * @param string $src_file Source full path filename ($_FILES['field']['tmp_name'])
  985. * @param string $dest_file Target full path filename ($_FILES['field']['name'])
  986. * @param int $allowoverwrite 1=Overwrite target file if it already exists
  987. * @param int $disablevirusscan 1=Disable virus scan
  988. * @param integer $uploaderrorcode Value of PHP upload error code ($_FILES['field']['error'])
  989. * @param int $nohook Disable all hooks
  990. * @param string $varfiles _FILES var name
  991. * @param string $upload_dir For information. Already included into $dest_file.
  992. * @return int|string 1 if OK, 2 if OK and .noexe appended, <0 or string if KO
  993. * @see dol_move()
  994. */
  995. function dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disablevirusscan = 0, $uploaderrorcode = 0, $nohook = 0, $varfiles = 'addedfile', $upload_dir = '')
  996. {
  997. global $conf, $db, $user, $langs;
  998. global $object, $hookmanager;
  999. $reshook = 0;
  1000. $file_name = $dest_file;
  1001. $successcode = 1;
  1002. if (empty($nohook)) {
  1003. $reshook = $hookmanager->initHooks(array('fileslib'));
  1004. $parameters = array('dest_file' => $dest_file, 'src_file' => $src_file, 'file_name' => $file_name, 'varfiles' => $varfiles, 'allowoverwrite' => $allowoverwrite);
  1005. $reshook = $hookmanager->executeHooks('moveUploadedFile', $parameters, $object);
  1006. }
  1007. if (empty($reshook)) {
  1008. // If an upload error has been reported
  1009. if ($uploaderrorcode) {
  1010. switch ($uploaderrorcode) {
  1011. case UPLOAD_ERR_INI_SIZE: // 1
  1012. return 'ErrorFileSizeTooLarge';
  1013. case UPLOAD_ERR_FORM_SIZE: // 2
  1014. return 'ErrorFileSizeTooLarge';
  1015. case UPLOAD_ERR_PARTIAL: // 3
  1016. return 'ErrorPartialFile';
  1017. case UPLOAD_ERR_NO_TMP_DIR: //
  1018. return 'ErrorNoTmpDir';
  1019. case UPLOAD_ERR_CANT_WRITE:
  1020. return 'ErrorFailedToWriteInDir';
  1021. case UPLOAD_ERR_EXTENSION:
  1022. return 'ErrorUploadBlockedByAddon';
  1023. default:
  1024. break;
  1025. }
  1026. }
  1027. // If we need to make a virus scan
  1028. if (empty($disablevirusscan) && file_exists($src_file)) {
  1029. $checkvirusarray = dolCheckVirus($src_file);
  1030. if (count($checkvirusarray)) {
  1031. dol_syslog('Files.lib::dol_move_uploaded_file File "'.$src_file.'" (target name "'.$dest_file.'") KO with antivirus: errors='.join(',', $checkvirusarray), LOG_WARNING);
  1032. return 'ErrorFileIsInfectedWithAVirus: '.join(',', $checkvirusarray);
  1033. }
  1034. }
  1035. // Security:
  1036. // Disallow file with some extensions. We rename them.
  1037. // Because if we put the documents directory into a directory inside web root (very bad), this allows to execute on demand arbitrary code.
  1038. if (isAFileWithExecutableContent($dest_file) && empty($conf->global->MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED)) {
  1039. // $upload_dir ends with a slash, so be must be sure the medias dir to compare to ends with slash too.
  1040. $publicmediasdirwithslash = $conf->medias->multidir_output[$conf->entity];
  1041. if (!preg_match('/\/$/', $publicmediasdirwithslash)) {
  1042. $publicmediasdirwithslash .= '/';
  1043. }
  1044. if (strpos($upload_dir, $publicmediasdirwithslash) !== 0) { // We never add .noexe on files into media directory
  1045. $file_name .= '.noexe';
  1046. $successcode = 2;
  1047. }
  1048. }
  1049. // Security:
  1050. // We refuse cache files/dirs, upload using .. and pipes into filenames.
  1051. if (preg_match('/^\./', basename($src_file)) || preg_match('/\.\./', $src_file) || preg_match('/[<>|]/', $src_file)) {
  1052. dol_syslog("Refused to deliver file ".$src_file, LOG_WARNING);
  1053. return -1;
  1054. }
  1055. // Security:
  1056. // We refuse cache files/dirs, upload using .. and pipes into filenames.
  1057. if (preg_match('/^\./', basename($dest_file)) || preg_match('/\.\./', $dest_file) || preg_match('/[<>|]/', $dest_file)) {
  1058. dol_syslog("Refused to deliver file ".$dest_file, LOG_WARNING);
  1059. return -2;
  1060. }
  1061. }
  1062. if ($reshook < 0) { // At least one blocking error returned by one hook
  1063. $errmsg = join(',', $hookmanager->errors);
  1064. if (empty($errmsg)) {
  1065. $errmsg = 'ErrorReturnedBySomeHooks'; // Should not occurs. Added if hook is bugged and does not set ->errors when there is error.
  1066. }
  1067. return $errmsg;
  1068. } elseif (empty($reshook)) {
  1069. // The file functions must be in OS filesystem encoding.
  1070. $src_file_osencoded = dol_osencode($src_file);
  1071. $file_name_osencoded = dol_osencode($file_name);
  1072. // Check if destination dir is writable
  1073. if (!is_writable(dirname($file_name_osencoded))) {
  1074. dol_syslog("Files.lib::dol_move_uploaded_file Dir ".dirname($file_name_osencoded)." is not writable. Return 'ErrorDirNotWritable'", LOG_WARNING);
  1075. return 'ErrorDirNotWritable';
  1076. }
  1077. // Check if destination file already exists
  1078. if (!$allowoverwrite) {
  1079. if (file_exists($file_name_osencoded)) {
  1080. dol_syslog("Files.lib::dol_move_uploaded_file File ".$file_name." already exists. Return 'ErrorFileAlreadyExists'", LOG_WARNING);
  1081. return 'ErrorFileAlreadyExists';
  1082. }
  1083. } else { // We are allowed to erase
  1084. if (is_dir($file_name_osencoded)) { // If there is a directory with name of file to create
  1085. dol_syslog("Files.lib::dol_move_uploaded_file A directory with name ".$file_name." already exists. Return 'ErrorDirWithFileNameAlreadyExists'", LOG_WARNING);
  1086. return 'ErrorDirWithFileNameAlreadyExists';
  1087. }
  1088. }
  1089. // Move file
  1090. $return = move_uploaded_file($src_file_osencoded, $file_name_osencoded);
  1091. if ($return) {
  1092. dolChmod($file_name_osencoded);
  1093. dol_syslog("Files.lib::dol_move_uploaded_file Success to move ".$src_file." to ".$file_name." - Umask=".$conf->global->MAIN_UMASK, LOG_DEBUG);
  1094. return $successcode; // Success
  1095. } else {
  1096. dol_syslog("Files.lib::dol_move_uploaded_file Failed to move ".$src_file." to ".$file_name, LOG_ERR);
  1097. return -3; // Unknown error
  1098. }
  1099. }
  1100. return $successcode; // Success
  1101. }
  1102. /**
  1103. * Remove a file or several files with a mask.
  1104. * This delete file physically but also database indexes.
  1105. *
  1106. * @param string $file File to delete or mask of files to delete
  1107. * @param int $disableglob Disable usage of glob like * so function is an exact delete function that will return error if no file found
  1108. * @param int $nophperrors Disable all PHP output errors
  1109. * @param int $nohook Disable all hooks
  1110. * @param object $object Current object in use
  1111. * @param boolean $allowdotdot Allow to delete file path with .. inside. Never use this, it is reserved for migration purpose.
  1112. * @param int $indexdatabase Try to remove also index entries.
  1113. * @param int $nolog Disable log file
  1114. * @return boolean True if no error (file is deleted or if glob is used and there's nothing to delete), False if error
  1115. * @see dol_delete_dir()
  1116. */
  1117. function dol_delete_file($file, $disableglob = 0, $nophperrors = 0, $nohook = 0, $object = null, $allowdotdot = false, $indexdatabase = 1, $nolog = 0)
  1118. {
  1119. global $db, $conf, $user, $langs;
  1120. global $hookmanager;
  1121. // Load translation files required by the page
  1122. $langs->loadLangs(array('other', 'errors'));
  1123. if (empty($nolog)) {
  1124. dol_syslog("dol_delete_file file=".$file." disableglob=".$disableglob." nophperrors=".$nophperrors." nohook=".$nohook);
  1125. }
  1126. // Security:
  1127. // We refuse transversal using .. and pipes into filenames.
  1128. if ((!$allowdotdot && preg_match('/\.\./', $file)) || preg_match('/[<>|]/', $file)) {
  1129. dol_syslog("Refused to delete file ".$file, LOG_WARNING);
  1130. return false;
  1131. }
  1132. $reshook = 0;
  1133. if (empty($nohook)) {
  1134. $hookmanager->initHooks(array('fileslib'));
  1135. $parameters = array(
  1136. 'file' => $file,
  1137. 'disableglob'=> $disableglob,
  1138. 'nophperrors' => $nophperrors
  1139. );
  1140. $reshook = $hookmanager->executeHooks('deleteFile', $parameters, $object);
  1141. }
  1142. if (empty($nohook) && $reshook != 0) { // reshook = 0 to do standard actions, 1 = ok and replace, -1 = ko
  1143. dol_syslog("reshook=".$reshook);
  1144. if ($reshook < 0) {
  1145. return false;
  1146. }
  1147. return true;
  1148. } else {
  1149. $file_osencoded = dol_osencode($file); // New filename encoded in OS filesystem encoding charset
  1150. if (empty($disableglob) && !empty($file_osencoded)) {
  1151. $ok = true;
  1152. $globencoded = str_replace('[', '\[', $file_osencoded);
  1153. $globencoded = str_replace(']', '\]', $globencoded);
  1154. $listofdir = glob($globencoded);
  1155. if (!empty($listofdir) && is_array($listofdir)) {
  1156. foreach ($listofdir as $filename) {
  1157. if ($nophperrors) {
  1158. $ok = @unlink($filename);
  1159. } else {
  1160. $ok = unlink($filename);
  1161. }
  1162. // If it fails and it is because of the missing write permission on parent dir
  1163. if (!$ok && file_exists(dirname($filename)) && !(fileperms(dirname($filename)) & 0200)) {
  1164. 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);
  1165. dolChmod(dirname($filename), decoct(fileperms(dirname($filename)) | 0200));
  1166. // Now we retry deletion
  1167. if ($nophperrors) {
  1168. $ok = @unlink($filename);
  1169. } else {
  1170. $ok = unlink($filename);
  1171. }
  1172. }
  1173. if ($ok) {
  1174. if (empty($nolog)) {
  1175. dol_syslog("Removed file ".$filename, LOG_DEBUG);
  1176. }
  1177. // Delete entry into ecm database
  1178. $rel_filetodelete = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $filename);
  1179. if (!preg_match('/(\/temp\/|\/thumbs\/|\.meta$)/', $rel_filetodelete)) { // If not a tmp file
  1180. if (is_object($db) && $indexdatabase) { // $db may not be defined when lib is in a context with define('NOREQUIREDB',1)
  1181. $rel_filetodelete = preg_replace('/^[\\/]/', '', $rel_filetodelete);
  1182. $rel_filetodelete = preg_replace('/\.noexe$/', '', $rel_filetodelete);
  1183. dol_syslog("Try to remove also entries in database for full relative path = ".$rel_filetodelete, LOG_DEBUG);
  1184. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  1185. $ecmfile = new EcmFiles($db);
  1186. $result = $ecmfile->fetch(0, '', $rel_filetodelete);
  1187. if ($result >= 0 && $ecmfile->id > 0) {
  1188. $result = $ecmfile->delete($user);
  1189. }
  1190. if ($result < 0) {
  1191. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  1192. }
  1193. }
  1194. }
  1195. } else {
  1196. dol_syslog("Failed to remove file ".$filename, LOG_WARNING);
  1197. // TODO Failure to remove can be because file was already removed or because of permission
  1198. // If error because it does not exists, we should return true, and we should return false if this is a permission problem
  1199. }
  1200. }
  1201. } else {
  1202. dol_syslog("No files to delete found", LOG_DEBUG);
  1203. }
  1204. } else {
  1205. $ok = false;
  1206. if ($nophperrors) {
  1207. $ok = @unlink($file_osencoded);
  1208. } else {
  1209. $ok = unlink($file_osencoded);
  1210. }
  1211. if ($ok) {
  1212. if (empty($nolog)) {
  1213. dol_syslog("Removed file ".$file_osencoded, LOG_DEBUG);
  1214. }
  1215. } else {
  1216. dol_syslog("Failed to remove file ".$file_osencoded, LOG_WARNING);
  1217. }
  1218. }
  1219. return $ok;
  1220. }
  1221. }
  1222. /**
  1223. * Remove a directory (not recursive, so content must be empty).
  1224. * If directory is not empty, return false
  1225. *
  1226. * @param string $dir Directory to delete
  1227. * @param int $nophperrors Disable all PHP output errors
  1228. * @return boolean True if success, false if error
  1229. * @see dol_delete_file() dolCopyDir()
  1230. */
  1231. function dol_delete_dir($dir, $nophperrors = 0)
  1232. {
  1233. // Security:
  1234. // We refuse transversal using .. and pipes into filenames.
  1235. if (preg_match('/\.\./', $dir) || preg_match('/[<>|]/', $dir)) {
  1236. dol_syslog("Refused to delete dir ".$dir.' (contains invalid char sequence)', LOG_WARNING);
  1237. return false;
  1238. }
  1239. $dir_osencoded = dol_osencode($dir);
  1240. return ($nophperrors ? @rmdir($dir_osencoded) : rmdir($dir_osencoded));
  1241. }
  1242. /**
  1243. * Remove a directory $dir and its subdirectories (or only files and subdirectories)
  1244. *
  1245. * @param string $dir Dir to delete
  1246. * @param int $count Counter to count nb of elements found to delete
  1247. * @param int $nophperrors Disable all PHP output errors
  1248. * @param int $onlysub Delete only files and subdir, not main directory
  1249. * @param int $countdeleted Counter to count nb of elements found really deleted
  1250. * @param int $indexdatabase Try to remove also index entries.
  1251. * @param int $nolog Disable log files (too verbose when making recursive directories)
  1252. * @return int Number of files and directory we try to remove. NB really removed is returned into var by reference $countdeleted.
  1253. */
  1254. function dol_delete_dir_recursive($dir, $count = 0, $nophperrors = 0, $onlysub = 0, &$countdeleted = 0, $indexdatabase = 1, $nolog = 0)
  1255. {
  1256. if (empty($nolog)) {
  1257. dol_syslog("functions.lib:dol_delete_dir_recursive ".$dir, LOG_DEBUG);
  1258. }
  1259. if (dol_is_dir($dir)) {
  1260. $dir_osencoded = dol_osencode($dir);
  1261. if ($handle = opendir("$dir_osencoded")) {
  1262. while (false !== ($item = readdir($handle))) {
  1263. if (!utf8_check($item)) {
  1264. $item = utf8_encode($item); // should be useless
  1265. }
  1266. if ($item != "." && $item != "..") {
  1267. if (is_dir(dol_osencode("$dir/$item")) && !is_link(dol_osencode("$dir/$item"))) {
  1268. $count = dol_delete_dir_recursive("$dir/$item", $count, $nophperrors, 0, $countdeleted, $indexdatabase, $nolog);
  1269. } else {
  1270. $result = dol_delete_file("$dir/$item", 1, $nophperrors, 0, null, false, $indexdatabase, $nolog);
  1271. $count++;
  1272. if ($result) {
  1273. $countdeleted++;
  1274. }
  1275. //else print 'Error on '.$item."\n";
  1276. }
  1277. }
  1278. }
  1279. closedir($handle);
  1280. // Delete also the main directory
  1281. if (empty($onlysub)) {
  1282. $result = dol_delete_dir($dir, $nophperrors);
  1283. $count++;
  1284. if ($result) {
  1285. $countdeleted++;
  1286. }
  1287. //else print 'Error on '.$dir."\n";
  1288. }
  1289. }
  1290. }
  1291. return $count;
  1292. }
  1293. /**
  1294. * Delete all preview files linked to object instance.
  1295. * Note that preview image of PDF files is generated when required, by dol_banner_tab() for example.
  1296. *
  1297. * @param object $object Object to clean
  1298. * @return int 0 if error, 1 if OK
  1299. * @see dol_convert_file()
  1300. */
  1301. function dol_delete_preview($object)
  1302. {
  1303. global $langs, $conf;
  1304. // Define parent dir of elements
  1305. $element = $object->element;
  1306. if ($object->element == 'order_supplier') {
  1307. $dir = $conf->fournisseur->commande->dir_output;
  1308. } elseif ($object->element == 'invoice_supplier') {
  1309. $dir = $conf->fournisseur->facture->dir_output;
  1310. } elseif ($object->element == 'project') {
  1311. $dir = $conf->project->dir_output;
  1312. } elseif ($object->element == 'shipping') {
  1313. $dir = $conf->expedition->dir_output.'/sending';
  1314. } elseif ($object->element == 'delivery') {
  1315. $dir = $conf->expedition->dir_output.'/receipt';
  1316. } elseif ($object->element == 'fichinter') {
  1317. $dir = $conf->ficheinter->dir_output;
  1318. } else {
  1319. $dir = empty($conf->$element->dir_output) ? '' : $conf->$element->dir_output;
  1320. }
  1321. if (empty($dir)) {
  1322. return 'ErrorObjectNoSupportedByFunction';
  1323. }
  1324. $refsan = dol_sanitizeFileName($object->ref);
  1325. $dir = $dir."/".$refsan;
  1326. $filepreviewnew = $dir."/".$refsan.".pdf_preview.png";
  1327. $filepreviewnewbis = $dir."/".$refsan.".pdf_preview-0.png";
  1328. $filepreviewold = $dir."/".$refsan.".pdf.png";
  1329. // For new preview files
  1330. if (file_exists($filepreviewnew) && is_writable($filepreviewnew)) {
  1331. if (!dol_delete_file($filepreviewnew, 1)) {
  1332. $object->error = $langs->trans("ErrorFailedToDeleteFile", $filepreviewnew);
  1333. return 0;
  1334. }
  1335. }
  1336. if (file_exists($filepreviewnewbis) && is_writable($filepreviewnewbis)) {
  1337. if (!dol_delete_file($filepreviewnewbis, 1)) {
  1338. $object->error = $langs->trans("ErrorFailedToDeleteFile", $filepreviewnewbis);
  1339. return 0;
  1340. }
  1341. }
  1342. // For old preview files
  1343. if (file_exists($filepreviewold) && is_writable($filepreviewold)) {
  1344. if (!dol_delete_file($filepreviewold, 1)) {
  1345. $object->error = $langs->trans("ErrorFailedToDeleteFile", $filepreviewold);
  1346. return 0;
  1347. }
  1348. } else {
  1349. $multiple = $filepreviewold.".";
  1350. for ($i = 0; $i < 20; $i++) {
  1351. $preview = $multiple.$i;
  1352. if (file_exists($preview) && is_writable($preview)) {
  1353. if (!dol_delete_file($preview, 1)) {
  1354. $object->error = $langs->trans("ErrorFailedToOpenFile", $preview);
  1355. return 0;
  1356. }
  1357. }
  1358. }
  1359. }
  1360. return 1;
  1361. }
  1362. /**
  1363. * Create a meta file with document file into same directory.
  1364. * This make "grep" search possible.
  1365. * This feature to generate the meta file is enabled only if option MAIN_DOC_CREATE_METAFILE is set.
  1366. *
  1367. * @param CommonObject $object Object
  1368. * @return int 0 if do nothing, >0 if we update meta file too, <0 if KO
  1369. */
  1370. function dol_meta_create($object)
  1371. {
  1372. global $conf;
  1373. // Create meta file
  1374. if (empty($conf->global->MAIN_DOC_CREATE_METAFILE)) {
  1375. return 0; // By default, no metafile.
  1376. }
  1377. // Define parent dir of elements
  1378. $element = $object->element;
  1379. if ($object->element == 'order_supplier') {
  1380. $dir = $conf->fournisseur->dir_output.'/commande';
  1381. } elseif ($object->element == 'invoice_supplier') {
  1382. $dir = $conf->fournisseur->dir_output.'/facture';
  1383. } elseif ($object->element == 'project') {
  1384. $dir = $conf->project->dir_output;
  1385. } elseif ($object->element == 'shipping') {
  1386. $dir = $conf->expedition->dir_output.'/sending';
  1387. } elseif ($object->element == 'delivery') {
  1388. $dir = $conf->expedition->dir_output.'/receipt';
  1389. } elseif ($object->element == 'fichinter') {
  1390. $dir = $conf->ficheinter->dir_output;
  1391. } else {
  1392. $dir = empty($conf->$element->dir_output) ? '' : $conf->$element->dir_output;
  1393. }
  1394. if ($dir) {
  1395. $object->fetch_thirdparty();
  1396. $objectref = dol_sanitizeFileName($object->ref);
  1397. $dir = $dir."/".$objectref;
  1398. $file = $dir."/".$objectref.".meta";
  1399. if (!is_dir($dir)) {
  1400. dol_mkdir($dir);
  1401. }
  1402. if (is_dir($dir)) {
  1403. if (is_countable($object->lines) && count($object->lines) > 0) {
  1404. $nblines = count($object->lines);
  1405. }
  1406. $client = $object->thirdparty->name." ".$object->thirdparty->address." ".$object->thirdparty->zip." ".$object->thirdparty->town;
  1407. $meta = "REFERENCE=\"".$object->ref."\"
  1408. DATE=\"" . dol_print_date($object->date, '')."\"
  1409. NB_ITEMS=\"" . $nblines."\"
  1410. CLIENT=\"" . $client."\"
  1411. AMOUNT_EXCL_TAX=\"" . $object->total_ht."\"
  1412. AMOUNT=\"" . $object->total_ttc."\"\n";
  1413. for ($i = 0; $i < $nblines; $i++) {
  1414. //Pour les articles
  1415. $meta .= "ITEM_".$i."_QUANTITY=\"".$object->lines[$i]->qty."\"
  1416. ITEM_" . $i."_AMOUNT_WO_TAX=\"".$object->lines[$i]->total_ht."\"
  1417. ITEM_" . $i."_VAT=\"".$object->lines[$i]->tva_tx."\"
  1418. ITEM_" . $i."_DESCRIPTION=\"".str_replace("\r\n", "", nl2br($object->lines[$i]->desc))."\"
  1419. ";
  1420. }
  1421. }
  1422. $fp = fopen($file, "w");
  1423. fputs($fp, $meta);
  1424. fclose($fp);
  1425. dolChmod($file);
  1426. return 1;
  1427. } else {
  1428. dol_syslog('FailedToDetectDirInDolMetaCreateFor'.$object->element, LOG_WARNING);
  1429. }
  1430. return 0;
  1431. }
  1432. /**
  1433. * Scan a directory and init $_SESSION to manage uploaded files with list of all found files.
  1434. * Note: Only email module seems to use this. Other feature initialize the $_SESSION doing $formmail->clear_attached_files(); $formmail->add_attached_files()
  1435. *
  1436. * @param string $pathtoscan Path to scan
  1437. * @param string $trackid Track id (used to prefix name of session vars to avoid conflict)
  1438. * @return void
  1439. */
  1440. function dol_init_file_process($pathtoscan = '', $trackid = '')
  1441. {
  1442. $listofpaths = array();
  1443. $listofnames = array();
  1444. $listofmimes = array();
  1445. if ($pathtoscan) {
  1446. $listoffiles = dol_dir_list($pathtoscan, 'files');
  1447. foreach ($listoffiles as $key => $val) {
  1448. $listofpaths[] = $val['fullname'];
  1449. $listofnames[] = $val['name'];
  1450. $listofmimes[] = dol_mimetype($val['name']);
  1451. }
  1452. }
  1453. $keytoavoidconflict = empty($trackid) ? '' : '-'.$trackid;
  1454. $_SESSION["listofpaths".$keytoavoidconflict] = join(';', $listofpaths);
  1455. $_SESSION["listofnames".$keytoavoidconflict] = join(';', $listofnames);
  1456. $_SESSION["listofmimes".$keytoavoidconflict] = join(';', $listofmimes);
  1457. }
  1458. /**
  1459. * 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.
  1460. * All information used are in db, conf, langs, user and _FILES.
  1461. * Note: This function can be used only into a HTML page context.
  1462. *
  1463. * @param string $upload_dir Directory where to store uploaded file (note: used to forge $destpath = $upload_dir + filename)
  1464. * @param int $allowoverwrite 1=Allow overwrite existing file
  1465. * @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.
  1466. * @param string $varfiles _FILES var name
  1467. * @param string $savingdocmask Mask to use to define output filename. For example 'XXXXX-__YYYYMMDD__-__file__'
  1468. * @param string $link Link to add (to add a link instead of a file)
  1469. * @param string $trackid Track id (used to prefix name of session vars to avoid conflict)
  1470. * @param int $generatethumbs 1=Generate also thumbs for uploaded image files
  1471. * @param Object $object Object used to set 'src_object_*' fields
  1472. * @return int <=0 if KO, >0 if OK
  1473. * @see dol_remove_file_process()
  1474. */
  1475. function dol_add_file_process($upload_dir, $allowoverwrite = 0, $donotupdatesession = 0, $varfiles = 'addedfile', $savingdocmask = '', $link = null, $trackid = '', $generatethumbs = 1, $object = null)
  1476. {
  1477. global $db, $user, $conf, $langs;
  1478. $res = 0;
  1479. if (!empty($_FILES[$varfiles])) { // For view $_FILES[$varfiles]['error']
  1480. dol_syslog('dol_add_file_process upload_dir='.$upload_dir.' allowoverwrite='.$allowoverwrite.' donotupdatesession='.$donotupdatesession.' savingdocmask='.$savingdocmask, LOG_DEBUG);
  1481. $maxfilesinform = getDolGlobalInt("MAIN_SECURITY_MAX_ATTACHMENT_ON_FORMS", 10);
  1482. if (is_array($_FILES[$varfiles]["name"]) && count($_FILES[$varfiles]["name"]) > $maxfilesinform) {
  1483. $langs->load("errors"); // key must be loaded because we can't rely on loading during output, we need var substitution to be done now.
  1484. setEventMessages($langs->trans("ErrorTooMuchFileInForm", $maxfilesinform), null, "errors");
  1485. return -1;
  1486. }
  1487. $result = dol_mkdir($upload_dir);
  1488. // var_dump($result);exit;
  1489. if ($result >= 0) {
  1490. $TFile = $_FILES[$varfiles];
  1491. if (!is_array($TFile['name'])) {
  1492. foreach ($TFile as $key => &$val) {
  1493. $val = array($val);
  1494. }
  1495. }
  1496. $nbfile = count($TFile['name']);
  1497. $nbok = 0;
  1498. for ($i = 0; $i < $nbfile; $i++) {
  1499. if (empty($TFile['name'][$i])) {
  1500. continue; // For example, when submitting a form with no file name
  1501. }
  1502. // Define $destfull (path to file including filename) and $destfile (only filename)
  1503. $destfull = $upload_dir."/".$TFile['name'][$i];
  1504. $destfile = $TFile['name'][$i];
  1505. $destfilewithoutext = preg_replace('/\.[^\.]+$/', '', $destfile);
  1506. if ($savingdocmask && strpos($savingdocmask, $destfilewithoutext) !== 0) {
  1507. $destfull = $upload_dir."/".preg_replace('/__file__/', $TFile['name'][$i], $savingdocmask);
  1508. $destfile = preg_replace('/__file__/', $TFile['name'][$i], $savingdocmask);
  1509. }
  1510. $filenameto = basename($destfile);
  1511. if (preg_match('/^\./', $filenameto)) {
  1512. $langs->load("errors"); // key must be loaded because we can't rely on loading during output, we need var substitution to be done now.
  1513. setEventMessages($langs->trans("ErrorFilenameCantStartWithDot", $filenameto), null, 'errors');
  1514. break;
  1515. }
  1516. // dol_sanitizeFileName the file name and lowercase extension
  1517. $info = pathinfo($destfull);
  1518. $destfull = $info['dirname'].'/'.dol_sanitizeFileName($info['filename'].($info['extension'] != '' ? ('.'.strtolower($info['extension'])) : ''));
  1519. $info = pathinfo($destfile);
  1520. $destfile = dol_sanitizeFileName($info['filename'].($info['extension'] != '' ? ('.'.strtolower($info['extension'])) : ''));
  1521. // We apply dol_string_nohtmltag also to clean file names (this remove duplicate spaces) because
  1522. // this function is also applied when we rename and when we make try to download file (by the GETPOST(filename, 'alphanohtml') call).
  1523. $destfile = dol_string_nohtmltag($destfile);
  1524. $destfull = dol_string_nohtmltag($destfull);
  1525. // Check that filename is not the one of a reserved allowed CLI command
  1526. global $dolibarr_main_restrict_os_commands;
  1527. if (!empty($dolibarr_main_restrict_os_commands)) {
  1528. $arrayofallowedcommand = explode(',', $dolibarr_main_restrict_os_commands);
  1529. $arrayofallowedcommand = array_map('trim', $arrayofallowedcommand);
  1530. if (in_array($destfile, $arrayofallowedcommand)) {
  1531. $langs->load("errors"); // key must be loaded because we can't rely on loading during output, we need var substitution to be done now.
  1532. setEventMessages($langs->trans("ErrorFilenameReserved", $destfile), null, 'errors');
  1533. return -1;
  1534. }
  1535. }
  1536. // Move file from temp directory to final directory. A .noexe may also be appended on file name.
  1537. $resupload = dol_move_uploaded_file($TFile['tmp_name'][$i], $destfull, $allowoverwrite, 0, $TFile['error'][$i], 0, $varfiles, $upload_dir);
  1538. if (is_numeric($resupload) && $resupload > 0) { // $resupload can be 'ErrorFileAlreadyExists'
  1539. global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini;
  1540. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  1541. // Generate thumbs.
  1542. if ($generatethumbs) {
  1543. if (image_format_supported($destfull) == 1) {
  1544. // Create thumbs
  1545. // We can't use $object->addThumbs here because there is no $object known
  1546. // Used on logon for example
  1547. $imgThumbSmall = vignette($destfull, $maxwidthsmall, $maxheightsmall, '_small', 50, "thumbs");
  1548. // Create mini thumbs for image (Ratio is near 16/9)
  1549. // Used on menu or for setup page for example
  1550. $imgThumbMini = vignette($destfull, $maxwidthmini, $maxheightmini, '_mini', 50, "thumbs");
  1551. }
  1552. }
  1553. // Update session
  1554. if (empty($donotupdatesession)) {
  1555. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  1556. $formmail = new FormMail($db);
  1557. $formmail->trackid = $trackid;
  1558. $formmail->add_attached_files($destfull, $destfile, $TFile['type'][$i]);
  1559. }
  1560. // Update index table of files (llx_ecm_files)
  1561. if ($donotupdatesession == 1) {
  1562. $sharefile = 0;
  1563. if ($TFile['type'][$i] == 'application/pdf' && strpos($_SERVER["REQUEST_URI"], 'product') !== false && !empty($conf->global->PRODUCT_ALLOW_EXTERNAL_DOWNLOAD)) $sharefile = 1;
  1564. $result = addFileIntoDatabaseIndex($upload_dir, basename($destfile).($resupload == 2 ? '.noexe' : ''), $TFile['name'][$i], 'uploaded', $sharefile, $object);
  1565. if ($result < 0) {
  1566. if ($allowoverwrite) {
  1567. // Do not show error message. We can have an error due to DB_ERROR_RECORD_ALREADY_EXISTS
  1568. } else {
  1569. setEventMessages('WarningFailedToAddFileIntoDatabaseIndex', null, 'warnings');
  1570. }
  1571. }
  1572. }
  1573. $nbok++;
  1574. } else {
  1575. $langs->load("errors");
  1576. if ($resupload < 0) { // Unknown error
  1577. setEventMessages($langs->trans("ErrorFileNotUploaded"), null, 'errors');
  1578. } elseif (preg_match('/ErrorFileIsInfectedWithAVirus/', $resupload)) { // Files infected by a virus
  1579. setEventMessages($langs->trans("ErrorFileIsInfectedWithAVirus"), null, 'errors');
  1580. } else // Known error
  1581. {
  1582. setEventMessages($langs->trans($resupload), null, 'errors');
  1583. }
  1584. }
  1585. }
  1586. if ($nbok > 0) {
  1587. $res = 1;
  1588. setEventMessages($langs->trans("FileTransferComplete"), null, 'mesgs');
  1589. }
  1590. } else {
  1591. setEventMessages($langs->trans("ErrorFailedToCreateDir", $upload_dir), null, 'errors');
  1592. }
  1593. } elseif ($link) {
  1594. require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
  1595. $linkObject = new Link($db);
  1596. $linkObject->entity = $conf->entity;
  1597. $linkObject->url = $link;
  1598. $linkObject->objecttype = GETPOST('objecttype', 'alpha');
  1599. $linkObject->objectid = GETPOST('objectid', 'int');
  1600. $linkObject->label = GETPOST('label', 'alpha');
  1601. $res = $linkObject->create($user);
  1602. $langs->load('link');
  1603. if ($res > 0) {
  1604. setEventMessages($langs->trans("LinkComplete"), null, 'mesgs');
  1605. } else {
  1606. setEventMessages($langs->trans("ErrorFileNotLinked"), null, 'errors');
  1607. }
  1608. } else {
  1609. $langs->load("errors");
  1610. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("File")), null, 'errors');
  1611. }
  1612. return $res;
  1613. }
  1614. /**
  1615. * Remove an uploaded file (for example after submitting a new file a mail form).
  1616. * All information used are in db, conf, langs, user and _FILES.
  1617. *
  1618. * @param int $filenb File nb to delete
  1619. * @param int $donotupdatesession -1 or 1 = Do not update _SESSION variable
  1620. * @param int $donotdeletefile 1=Do not delete physically file
  1621. * @param string $trackid Track id (used to prefix name of session vars to avoid conflict)
  1622. * @return void
  1623. * @see dol_add_file_process()
  1624. */
  1625. function dol_remove_file_process($filenb, $donotupdatesession = 0, $donotdeletefile = 1, $trackid = '')
  1626. {
  1627. global $db, $user, $conf, $langs, $_FILES;
  1628. $keytodelete = $filenb;
  1629. $keytodelete--;
  1630. $listofpaths = array();
  1631. $listofnames = array();
  1632. $listofmimes = array();
  1633. $keytoavoidconflict = empty($trackid) ? '' : '-'.$trackid;
  1634. if (!empty($_SESSION["listofpaths".$keytoavoidconflict])) {
  1635. $listofpaths = explode(';', $_SESSION["listofpaths".$keytoavoidconflict]);
  1636. }
  1637. if (!empty($_SESSION["listofnames".$keytoavoidconflict])) {
  1638. $listofnames = explode(';', $_SESSION["listofnames".$keytoavoidconflict]);
  1639. }
  1640. if (!empty($_SESSION["listofmimes".$keytoavoidconflict])) {
  1641. $listofmimes = explode(';', $_SESSION["listofmimes".$keytoavoidconflict]);
  1642. }
  1643. if ($keytodelete >= 0) {
  1644. $pathtodelete = $listofpaths[$keytodelete];
  1645. $filetodelete = $listofnames[$keytodelete];
  1646. if (empty($donotdeletefile)) {
  1647. $result = dol_delete_file($pathtodelete, 1); // The delete of ecm database is inside the function dol_delete_file
  1648. } else {
  1649. $result = 0;
  1650. }
  1651. if ($result >= 0) {
  1652. if (empty($donotdeletefile)) {
  1653. $langs->load("other");
  1654. setEventMessages($langs->trans("FileWasRemoved", $filetodelete), null, 'mesgs');
  1655. }
  1656. if (empty($donotupdatesession)) {
  1657. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  1658. $formmail = new FormMail($db);
  1659. $formmail->trackid = $trackid;
  1660. $formmail->remove_attached_files($keytodelete);
  1661. }
  1662. }
  1663. }
  1664. }
  1665. /**
  1666. * Add a file into database index.
  1667. * Called by dol_add_file_process when uploading a file and on other cases.
  1668. * See also commonGenerateDocument that also add/update database index when a file is generated.
  1669. *
  1670. * @param string $dir Directory name (full real path without ending /)
  1671. * @param string $file File name (May end with '.noexe')
  1672. * @param string $fullpathorig Full path of origin for file (can be '')
  1673. * @param string $mode How file was created ('uploaded', 'generated', ...)
  1674. * @param int $setsharekey Set also the share key
  1675. * @param Object $object Object used to set 'src_object_*' fields
  1676. * @return int <0 if KO, 0 if nothing done, >0 if OK
  1677. */
  1678. function addFileIntoDatabaseIndex($dir, $file, $fullpathorig = '', $mode = 'uploaded', $setsharekey = 0, $object = null)
  1679. {
  1680. global $db, $user, $conf;
  1681. $result = 0;
  1682. $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
  1683. if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
  1684. $filename = basename(preg_replace('/\.noexe$/', '', $file));
  1685. $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
  1686. $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
  1687. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  1688. $ecmfile = new EcmFiles($db);
  1689. $ecmfile->filepath = $rel_dir;
  1690. $ecmfile->filename = $filename;
  1691. $ecmfile->label = md5_file(dol_osencode($dir.'/'.$file)); // MD5 of file content
  1692. $ecmfile->fullpath_orig = $fullpathorig;
  1693. $ecmfile->gen_or_uploaded = $mode;
  1694. $ecmfile->description = ''; // indexed content
  1695. $ecmfile->keywords = ''; // keyword content
  1696. if (is_object($object) && $object->id > 0) {
  1697. $ecmfile->src_object_id = $object->id;
  1698. if (isset($object->table_element)) {
  1699. $ecmfile->src_object_type = $object->table_element;
  1700. } else {
  1701. dol_syslog('Error: object ' . get_class($object) . ' has no table_element attribute.');
  1702. return -1;
  1703. }
  1704. if (isset($object->src_object_description)) $ecmfile->description = $object->src_object_description;
  1705. if (isset($object->src_object_keywords)) $ecmfile->keywords = $object->src_object_keywords;
  1706. }
  1707. if (!empty($conf->global->MAIN_FORCE_SHARING_ON_ANY_UPLOADED_FILE)) {
  1708. $setsharekey = 1;
  1709. }
  1710. if ($setsharekey) {
  1711. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  1712. $ecmfile->share = getRandomPassword(true);
  1713. }
  1714. $result = $ecmfile->create($user);
  1715. if ($result < 0) {
  1716. dol_syslog($ecmfile->error);
  1717. }
  1718. }
  1719. return $result;
  1720. }
  1721. /**
  1722. * Delete files into database index using search criterias.
  1723. *
  1724. * @param string $dir Directory name (full real path without ending /)
  1725. * @param string $file File name
  1726. * @param string $mode How file was created ('uploaded', 'generated', ...)
  1727. * @return int <0 if KO, 0 if nothing done, >0 if OK
  1728. */
  1729. function deleteFilesIntoDatabaseIndex($dir, $file, $mode = 'uploaded')
  1730. {
  1731. global $conf, $db, $user;
  1732. $error = 0;
  1733. if (empty($dir)) {
  1734. dol_syslog("deleteFilesIntoDatabaseIndex: dir parameter can't be empty", LOG_ERR);
  1735. return -1;
  1736. }
  1737. $db->begin();
  1738. $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
  1739. $filename = basename($file);
  1740. $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
  1741. $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
  1742. if (!$error) {
  1743. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'ecm_files';
  1744. $sql .= ' WHERE entity = '.$conf->entity;
  1745. $sql .= " AND filepath = '".$db->escape($rel_dir)."'";
  1746. if ($file) {
  1747. $sql .= " AND filename = '".$db->escape($file)."'";
  1748. }
  1749. if ($mode) {
  1750. $sql .= " AND gen_or_uploaded = '".$db->escape($mode)."'";
  1751. }
  1752. $resql = $db->query($sql);
  1753. if (!$resql) {
  1754. $error++;
  1755. dol_syslog(__METHOD__.' '.$db->lasterror(), LOG_ERR);
  1756. }
  1757. }
  1758. // Commit or rollback
  1759. if ($error) {
  1760. $db->rollback();
  1761. return -1 * $error;
  1762. } else {
  1763. $db->commit();
  1764. return 1;
  1765. }
  1766. }
  1767. /**
  1768. * Convert an image file or a PDF into another image format.
  1769. * This need Imagick php extension. You can use dol_imageResizeOrCrop() for a function that need GD.
  1770. *
  1771. * @param string $fileinput Input file name
  1772. * @param string $ext Format of target file (It is also extension added to file if fileoutput is not provided).
  1773. * @param string $fileoutput Output filename
  1774. * @param string $page Page number if we convert a PDF into png
  1775. * @return int <0 if KO, 0=Nothing done, >0 if OK
  1776. * @see dol_imageResizeOrCrop()
  1777. */
  1778. function dol_convert_file($fileinput, $ext = 'png', $fileoutput = '', $page = '')
  1779. {
  1780. if (class_exists('Imagick')) {
  1781. $image = new Imagick();
  1782. try {
  1783. $filetoconvert = $fileinput.(($page != '') ? '['.$page.']' : '');
  1784. //var_dump($filetoconvert);
  1785. $ret = $image->readImage($filetoconvert);
  1786. } catch (Exception $e) {
  1787. $ext = pathinfo($fileinput, PATHINFO_EXTENSION);
  1788. 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);
  1789. return 0;
  1790. }
  1791. if ($ret) {
  1792. $ret = $image->setImageFormat($ext);
  1793. if ($ret) {
  1794. if (empty($fileoutput)) {
  1795. $fileoutput = $fileinput.".".$ext;
  1796. }
  1797. $count = $image->getNumberImages();
  1798. if (!dol_is_file($fileoutput) || is_writeable($fileoutput)) {
  1799. try {
  1800. $ret = $image->writeImages($fileoutput, true);
  1801. } catch (Exception $e) {
  1802. dol_syslog($e->getMessage(), LOG_WARNING);
  1803. }
  1804. } else {
  1805. dol_syslog("Warning: Failed to write cache preview file '.$fileoutput.'. Check permission on file/dir", LOG_ERR);
  1806. }
  1807. if ($ret) {
  1808. return $count;
  1809. } else {
  1810. return -3;
  1811. }
  1812. } else {
  1813. return -2;
  1814. }
  1815. } else {
  1816. return -1;
  1817. }
  1818. } else {
  1819. return 0;
  1820. }
  1821. }
  1822. /**
  1823. * Compress a file.
  1824. * An error string may be returned into parameters.
  1825. *
  1826. * @param string $inputfile Source file name
  1827. * @param string $outputfile Target file name
  1828. * @param string $mode 'gz' or 'bz' or 'zip'
  1829. * @param string $errorstring Error string
  1830. * @return int <0 if KO, >0 if OK
  1831. * @see dol_uncompress(), dol_compress_dir()
  1832. */
  1833. function dol_compress_file($inputfile, $outputfile, $mode = "gz", &$errorstring = null)
  1834. {
  1835. global $conf;
  1836. $foundhandler = 0;
  1837. try {
  1838. dol_syslog("dol_compress_file mode=".$mode." inputfile=".$inputfile." outputfile=".$outputfile);
  1839. $data = implode("", file(dol_osencode($inputfile)));
  1840. if ($mode == 'gz' && function_exists('gzencode')) {
  1841. $foundhandler = 1;
  1842. $compressdata = gzencode($data, 9);
  1843. } elseif ($mode == 'bz' && function_exists('bzcompress')) {
  1844. $foundhandler = 1;
  1845. $compressdata = bzcompress($data, 9);
  1846. } elseif ($mode == 'zstd' && function_exists('zstd_compress')) {
  1847. $foundhandler = 1;
  1848. $compressdata = zstd_compress($data, 9);
  1849. } elseif ($mode == 'zip') {
  1850. if (class_exists('ZipArchive') && !empty($conf->global->MAIN_USE_ZIPARCHIVE_FOR_ZIP_COMPRESS)) {
  1851. $foundhandler = 1;
  1852. $rootPath = realpath($inputfile);
  1853. dol_syslog("Class ZipArchive is set so we zip using ZipArchive to zip into ".$outputfile.' rootPath='.$rootPath);
  1854. $zip = new ZipArchive;
  1855. if ($zip->open($outputfile, ZipArchive::CREATE) !== true) {
  1856. $errorstring = "dol_compress_file failure - Failed to open file ".$outputfile."\n";
  1857. dol_syslog($errorstring, LOG_ERR);
  1858. global $errormsg;
  1859. $errormsg = $errorstring;
  1860. return -6;
  1861. }
  1862. // Create recursive directory iterator
  1863. /** @var SplFileInfo[] $files */
  1864. $files = new RecursiveIteratorIterator(
  1865. new RecursiveDirectoryIterator($rootPath),
  1866. RecursiveIteratorIterator::LEAVES_ONLY
  1867. );
  1868. foreach ($files as $name => $file) {
  1869. // Skip directories (they would be added automatically)
  1870. if (!$file->isDir()) {
  1871. // Get real and relative path for current file
  1872. $filePath = $file->getPath(); // the full path with filename using the $inputdir root.
  1873. $fileName = $file->getFilename();
  1874. $fileFullRealPath = $file->getRealPath(); // the full path with name and transformed to use real path directory.
  1875. //$relativePath = substr($fileFullRealPath, strlen($rootPath) + 1);
  1876. $relativePath = substr(($filePath ? $filePath.'/' : '').$fileName, strlen($rootPath) + 1);
  1877. // Add current file to archive
  1878. $zip->addFile($fileFullRealPath, $relativePath);
  1879. }
  1880. }
  1881. // Zip archive will be created only after closing object
  1882. $zip->close();
  1883. dol_syslog("dol_compress_file success - ".count($zip->numFiles)." files");
  1884. return 1;
  1885. }
  1886. if (defined('ODTPHP_PATHTOPCLZIP')) {
  1887. $foundhandler = 1;
  1888. include_once ODTPHP_PATHTOPCLZIP.'/pclzip.lib.php';
  1889. $archive = new PclZip($outputfile);
  1890. $result = $archive->add($inputfile, PCLZIP_OPT_REMOVE_PATH, dirname($inputfile));
  1891. if ($result === 0) {
  1892. global $errormsg;
  1893. $errormsg = $archive->errorInfo(true);
  1894. if ($archive->errorCode() == PCLZIP_ERR_WRITE_OPEN_FAIL) {
  1895. $errorstring = "PCLZIP_ERR_WRITE_OPEN_FAIL";
  1896. dol_syslog("dol_compress_file error - archive->errorCode() = PCLZIP_ERR_WRITE_OPEN_FAIL", LOG_ERR);
  1897. return -4;
  1898. }
  1899. $errorstring = "dol_compress_file error archive->errorCode = ".$archive->errorCode()." errormsg=".$errormsg;
  1900. dol_syslog("dol_compress_file failure - ".$errormsg, LOG_ERR);
  1901. return -3;
  1902. } else {
  1903. dol_syslog("dol_compress_file success - ".count($result)." files");
  1904. return 1;
  1905. }
  1906. }
  1907. }
  1908. if ($foundhandler) {
  1909. $fp = fopen($outputfile, "w");
  1910. fwrite($fp, $compressdata);
  1911. fclose($fp);
  1912. return 1;
  1913. } else {
  1914. $errorstring = "Try to zip with format ".$mode." with no handler for this format";
  1915. dol_syslog($errorstring, LOG_ERR);
  1916. global $errormsg;
  1917. $errormsg = $errorstring;
  1918. return -2;
  1919. }
  1920. } catch (Exception $e) {
  1921. global $langs, $errormsg;
  1922. $langs->load("errors");
  1923. $errormsg = $langs->trans("ErrorFailedToWriteInDir");
  1924. $errorstring = "Failed to open file ".$outputfile;
  1925. dol_syslog($errorstring, LOG_ERR);
  1926. return -1;
  1927. }
  1928. }
  1929. /**
  1930. * Uncompress a file
  1931. *
  1932. * @param string $inputfile File to uncompress
  1933. * @param string $outputdir Target dir name
  1934. * @return array array('error'=>'Error code') or array() if no error
  1935. * @see dol_compress_file(), dol_compress_dir()
  1936. */
  1937. function dol_uncompress($inputfile, $outputdir)
  1938. {
  1939. global $conf, $langs, $db;
  1940. $fileinfo = pathinfo($inputfile);
  1941. $fileinfo["extension"] = strtolower($fileinfo["extension"]);
  1942. if ($fileinfo["extension"] == "zip") {
  1943. if (defined('ODTPHP_PATHTOPCLZIP') && empty($conf->global->MAIN_USE_ZIPARCHIVE_FOR_ZIP_UNCOMPRESS)) {
  1944. dol_syslog("Constant ODTPHP_PATHTOPCLZIP for pclzip library is set to ".ODTPHP_PATHTOPCLZIP.", so we use Pclzip to unzip into ".$outputdir);
  1945. include_once ODTPHP_PATHTOPCLZIP.'/pclzip.lib.php';
  1946. $archive = new PclZip($inputfile);
  1947. // We create output dir manually, so it uses the correct permission (When created by the archive->extract, dir is rwx for everybody).
  1948. dol_mkdir(dol_sanitizePathName($outputdir));
  1949. // Extract into outputdir, but only files that match the regex '/^((?!\.\.).)*$/' that means "does not include .."
  1950. $result = $archive->extract(PCLZIP_OPT_PATH, $outputdir, PCLZIP_OPT_BY_PREG, '/^((?!\.\.).)*$/');
  1951. if (!is_array($result) && $result <= 0) {
  1952. return array('error'=>$archive->errorInfo(true));
  1953. } else {
  1954. $ok = 1;
  1955. $errmsg = '';
  1956. // Loop on each file to check result for unzipping file
  1957. foreach ($result as $key => $val) {
  1958. if ($val['status'] == 'path_creation_fail') {
  1959. $langs->load("errors");
  1960. $ok = 0;
  1961. $errmsg = $langs->trans("ErrorFailToCreateDir", $val['filename']);
  1962. break;
  1963. }
  1964. }
  1965. if ($ok) {
  1966. return array();
  1967. } else {
  1968. return array('error'=>$errmsg);
  1969. }
  1970. }
  1971. }
  1972. if (class_exists('ZipArchive')) { // Must install php-zip to have it
  1973. dol_syslog("Class ZipArchive is set so we unzip using ZipArchive to unzip into ".$outputdir);
  1974. $zip = new ZipArchive;
  1975. $res = $zip->open($inputfile);
  1976. if ($res === true) {
  1977. //$zip->extractTo($outputdir.'/');
  1978. // 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
  1979. // python3 path_traversal_archiver.py <Created_file_name> test.zip -l 10 -p tmp/
  1980. // with -l is the range of dot to go back in path.
  1981. // and path_traversal_archiver.py found at https://github.com/Alamot/code-snippets/blob/master/path_traversal/path_traversal_archiver.py
  1982. for ($i = 0; $i < $zip->numFiles; $i++) {
  1983. if (preg_match('/\.\./', $zip->getNameIndex($i))) {
  1984. dol_syslog("Warning: Try to unzip a file with a transversal path ".$zip->getNameIndex($i), LOG_WARNING);
  1985. continue; // Discard the file
  1986. }
  1987. $zip->extractTo($outputdir.'/', array($zip->getNameIndex($i)));
  1988. }
  1989. $zip->close();
  1990. return array();
  1991. } else {
  1992. return array('error'=>'ErrUnzipFails');
  1993. }
  1994. }
  1995. return array('error'=>'ErrNoZipEngine');
  1996. } elseif (in_array($fileinfo["extension"], array('gz', 'bz2', 'zst'))) {
  1997. include_once DOL_DOCUMENT_ROOT."/core/class/utils.class.php";
  1998. $utils = new Utils($db);
  1999. dol_mkdir(dol_sanitizePathName($outputdir));
  2000. $outputfilename = escapeshellcmd(dol_sanitizePathName($outputdir).'/'.dol_sanitizeFileName($fileinfo["filename"]));
  2001. dol_delete_file($outputfilename.'.tmp');
  2002. dol_delete_file($outputfilename.'.err');
  2003. $extension = strtolower(pathinfo($fileinfo["filename"], PATHINFO_EXTENSION));
  2004. if ($extension == "tar") {
  2005. $cmd = 'tar -C '.escapeshellcmd(dol_sanitizePathName($outputdir)).' -xvf '.escapeshellcmd(dol_sanitizePathName($fileinfo["dirname"]).'/'.dol_sanitizeFileName($fileinfo["basename"]));
  2006. $resarray = $utils->executeCLI($cmd, $outputfilename.'.tmp', 0, $outputfilename.'.err', 0);
  2007. if ($resarray["result"] != 0) {
  2008. $resarray["error"] .= file_get_contents($outputfilename.'.err');
  2009. }
  2010. } else {
  2011. $program = "";
  2012. if ($fileinfo["extension"] == "gz") {
  2013. $program = 'gzip';
  2014. } elseif ($fileinfo["extension"] == "bz2") {
  2015. $program = 'bzip2';
  2016. } elseif ($fileinfo["extension"] == "zst") {
  2017. $program = 'zstd';
  2018. } else {
  2019. return array('error'=>'ErrorBadFileExtension');
  2020. }
  2021. $cmd = $program.' -dc '.escapeshellcmd(dol_sanitizePathName($fileinfo["dirname"]).'/'.dol_sanitizeFileName($fileinfo["basename"]));
  2022. $cmd .= ' > '.$outputfilename;
  2023. $resarray = $utils->executeCLI($cmd, $outputfilename.'.tmp', 0, null, 1, $outputfilename.'.err');
  2024. if ($resarray["result"] != 0) {
  2025. $errfilecontent = @file_get_contents($outputfilename.'.err');
  2026. if ($errfilecontent) {
  2027. $resarray["error"] .= " - ".$errfilecontent;
  2028. }
  2029. }
  2030. }
  2031. return $resarray["result"] != 0 ? array('error' => $resarray["error"]) : array();
  2032. }
  2033. return array('error'=>'ErrorBadFileExtension');
  2034. }
  2035. /**
  2036. * Compress a directory and subdirectories into a package file.
  2037. *
  2038. * @param string $inputdir Source dir name
  2039. * @param string $outputfile Target file name (output directory must exists and be writable)
  2040. * @param string $mode 'zip'
  2041. * @param string $excludefiles A regex pattern. For example: '/\.log$|\/temp\//'
  2042. * @param string $rootdirinzip Add a root dir level in zip file
  2043. * @param string $newmask Mask for new file (0 by default means $conf->global->MAIN_UMASK). Example: '0666'
  2044. * @return int <0 if KO, >0 if OK
  2045. * @see dol_uncompress(), dol_compress_file()
  2046. */
  2047. function dol_compress_dir($inputdir, $outputfile, $mode = "zip", $excludefiles = '', $rootdirinzip = '', $newmask = 0)
  2048. {
  2049. global $conf;
  2050. $foundhandler = 0;
  2051. dol_syslog("Try to zip dir ".$inputdir." into ".$outputfile." mode=".$mode);
  2052. if (!dol_is_dir(dirname($outputfile)) || !is_writable(dirname($outputfile))) {
  2053. global $langs, $errormsg;
  2054. $langs->load("errors");
  2055. $errormsg = $langs->trans("ErrorFailedToWriteInDir", $outputfile);
  2056. return -3;
  2057. }
  2058. try {
  2059. if ($mode == 'gz') {
  2060. $foundhandler = 0;
  2061. } elseif ($mode == 'bz') {
  2062. $foundhandler = 0;
  2063. } elseif ($mode == 'zip') {
  2064. /*if (defined('ODTPHP_PATHTOPCLZIP'))
  2065. {
  2066. $foundhandler=0; // TODO implement this
  2067. include_once ODTPHP_PATHTOPCLZIP.'/pclzip.lib.php';
  2068. $archive = new PclZip($outputfile);
  2069. $archive->add($inputfile, PCLZIP_OPT_REMOVE_PATH, dirname($inputfile));
  2070. //$archive->add($inputfile);
  2071. return 1;
  2072. }
  2073. else*/
  2074. //if (class_exists('ZipArchive') && !empty($conf->global->MAIN_USE_ZIPARCHIVE_FOR_ZIP_COMPRESS))
  2075. if (class_exists('ZipArchive')) {
  2076. $foundhandler = 1;
  2077. // Initialize archive object
  2078. $zip = new ZipArchive();
  2079. $result = $zip->open($outputfile, ZipArchive::CREATE | ZipArchive::OVERWRITE);
  2080. if (!$result) {
  2081. global $langs, $errormsg;
  2082. $langs->load("errors");
  2083. $errormsg = $langs->trans("ErrorFailedToWriteInFile", $outputfile);
  2084. return -4;
  2085. }
  2086. // Create recursive directory iterator
  2087. // This does not return symbolic links
  2088. /** @var SplFileInfo[] $files */
  2089. $files = new RecursiveIteratorIterator(
  2090. new RecursiveDirectoryIterator($inputdir),
  2091. RecursiveIteratorIterator::LEAVES_ONLY
  2092. );
  2093. //var_dump($inputdir);
  2094. foreach ($files as $name => $file) {
  2095. // Skip directories (they would be added automatically)
  2096. if (!$file->isDir()) {
  2097. // Get real and relative path for current file
  2098. $filePath = $file->getPath(); // the full path with filename using the $inputdir root.
  2099. $fileName = $file->getFilename();
  2100. $fileFullRealPath = $file->getRealPath(); // the full path with name and transformed to use real path directory.
  2101. //$relativePath = ($rootdirinzip ? $rootdirinzip.'/' : '').substr($fileFullRealPath, strlen($inputdir) + 1);
  2102. $relativePath = ($rootdirinzip ? $rootdirinzip.'/' : '').substr(($filePath ? $filePath.'/' : '').$fileName, strlen($inputdir) + 1);
  2103. //var_dump($filePath);var_dump($fileFullRealPath);var_dump($relativePath);
  2104. if (empty($excludefiles) || !preg_match($excludefiles, $fileFullRealPath)) {
  2105. // Add current file to archive
  2106. $zip->addFile($fileFullRealPath, $relativePath);
  2107. }
  2108. }
  2109. }
  2110. // Zip archive will be created only after closing object
  2111. $zip->close();
  2112. if (empty($newmask) && !empty($conf->global->MAIN_UMASK)) {
  2113. $newmask = $conf->global->MAIN_UMASK;
  2114. }
  2115. if (empty($newmask)) { // This should no happen
  2116. dol_syslog("Warning: dol_copy called with empty value for newmask and no default value defined", LOG_WARNING);
  2117. $newmask = '0664';
  2118. }
  2119. dolChmod($outputfile, $newmask);
  2120. return 1;
  2121. }
  2122. }
  2123. if (!$foundhandler) {
  2124. dol_syslog("Try to zip with format ".$mode." with no handler for this format", LOG_ERR);
  2125. return -2;
  2126. } else {
  2127. return 0;
  2128. }
  2129. } catch (Exception $e) {
  2130. global $langs, $errormsg;
  2131. $langs->load("errors");
  2132. dol_syslog("Failed to open file ".$outputfile, LOG_ERR);
  2133. dol_syslog($e->getMessage(), LOG_ERR);
  2134. $errormsg = $langs->trans("ErrorFailedToBuildArchive", $outputfile).' - '.$e->getMessage();
  2135. return -1;
  2136. }
  2137. }
  2138. /**
  2139. * Return file(s) into a directory (by default most recent)
  2140. *
  2141. * @param string $dir Directory to scan
  2142. * @param string $regexfilter Regex filter to restrict list. This regex value must be escaped for '/', since this char is used for preg_match function
  2143. * @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
  2144. * @param int $nohook Disable all hooks
  2145. * @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
  2146. * @return array Array with properties (full path, date, ...) of to most recent file
  2147. */
  2148. function dol_most_recent_file($dir, $regexfilter = '', $excludefilter = array('(\.meta|_preview.*\.png)$', '^\.'), $nohook = false, $mode = '')
  2149. {
  2150. $tmparray = dol_dir_list($dir, 'files', 0, $regexfilter, $excludefilter, 'date', SORT_DESC, $mode, $nohook);
  2151. return isset($tmparray[0])?$tmparray[0]:null;
  2152. }
  2153. /**
  2154. * Security check when accessing to a document (used by document.php, viewimage.php and webservices to get documents).
  2155. * TODO Replace code that set $accessallowed by a call to restrictedArea()
  2156. *
  2157. * @param string $modulepart Module of document ('module', 'module_user_temp', 'module_user' or 'module_temp'). Exemple: 'medias', 'invoice', 'logs', 'tax-vat', ...
  2158. * @param string $original_file Relative path with filename, relative to modulepart.
  2159. * @param string $entity Restrict onto entity (0=no restriction)
  2160. * @param User $fuser User object (forced)
  2161. * @param string $refname Ref of object to check permission for external users (autodetect if not provided) or for hierarchy
  2162. * @param string $mode Check permission for 'read' or 'write'
  2163. * @return mixed Array with access information : 'accessallowed' & 'sqlprotectagainstexternals' & 'original_file' (as a full path name)
  2164. * @see restrictedArea()
  2165. */
  2166. function dol_check_secure_access_document($modulepart, $original_file, $entity, $fuser = '', $refname = '', $mode = 'read')
  2167. {
  2168. global $conf, $db, $user, $hookmanager;
  2169. global $dolibarr_main_data_root, $dolibarr_main_document_root_alt;
  2170. global $object;
  2171. if (!is_object($fuser)) {
  2172. $fuser = $user;
  2173. }
  2174. if (empty($modulepart)) {
  2175. return 'ErrorBadParameter';
  2176. }
  2177. if (empty($entity)) {
  2178. if (!isModEnabled('multicompany')) {
  2179. $entity = 1;
  2180. } else {
  2181. $entity = 0;
  2182. }
  2183. }
  2184. // Fix modulepart for backward compatibility
  2185. if ($modulepart == 'users') {
  2186. $modulepart = 'user';
  2187. }
  2188. if ($modulepart == 'tva') {
  2189. $modulepart = 'tax-vat';
  2190. }
  2191. //print 'dol_check_secure_access_document modulepart='.$modulepart.' original_file='.$original_file.' entity='.$entity;
  2192. dol_syslog('dol_check_secure_access_document modulepart='.$modulepart.' original_file='.$original_file.' entity='.$entity);
  2193. // We define $accessallowed and $sqlprotectagainstexternals
  2194. $accessallowed = 0;
  2195. $sqlprotectagainstexternals = '';
  2196. $ret = array();
  2197. // Find the subdirectory name as the reference. For example original_file='10/myfile.pdf' -> refname='10'
  2198. if (empty($refname)) {
  2199. $refname = basename(dirname($original_file)."/");
  2200. if ($refname == 'thumbs') {
  2201. // If we get the thumbs directory, we must go one step higher. For example original_file='10/thumbs/myfile_small.jpg' -> refname='10'
  2202. $refname = basename(dirname(dirname($original_file))."/");
  2203. }
  2204. }
  2205. // Define possible keys to use for permission check
  2206. $lire = 'lire';
  2207. $read = 'read';
  2208. $download = 'download';
  2209. if ($mode == 'write') {
  2210. $lire = 'creer';
  2211. $read = 'write';
  2212. $download = 'upload';
  2213. }
  2214. // Wrapping for miscellaneous medias files
  2215. if ($modulepart == 'medias' && !empty($dolibarr_main_data_root)) {
  2216. if (empty($entity) || empty($conf->medias->multidir_output[$entity])) {
  2217. return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
  2218. }
  2219. $accessallowed = 1;
  2220. $original_file = $conf->medias->multidir_output[$entity].'/'.$original_file;
  2221. } elseif ($modulepart == 'logs' && !empty($dolibarr_main_data_root)) {
  2222. // Wrapping for *.log files, like when used with url http://.../document.php?modulepart=logs&file=dolibarr.log
  2223. $accessallowed = ($user->admin && basename($original_file) == $original_file && preg_match('/^dolibarr.*\.log$/', basename($original_file)));
  2224. $original_file = $dolibarr_main_data_root.'/'.$original_file;
  2225. } elseif ($modulepart == 'doctemplates' && !empty($dolibarr_main_data_root)) {
  2226. // Wrapping for doctemplates
  2227. $accessallowed = $user->admin;
  2228. $original_file = $dolibarr_main_data_root.'/doctemplates/'.$original_file;
  2229. } elseif ($modulepart == 'doctemplateswebsite' && !empty($dolibarr_main_data_root)) {
  2230. // Wrapping for doctemplates of websites
  2231. $accessallowed = ($fuser->rights->website->write && preg_match('/\.jpg$/i', basename($original_file)));
  2232. $original_file = $dolibarr_main_data_root.'/doctemplates/websites/'.$original_file;
  2233. } elseif ($modulepart == 'packages' && !empty($dolibarr_main_data_root)) {
  2234. // Wrapping for *.zip package files, like when used with url http://.../document.php?modulepart=packages&file=module_myfile.zip
  2235. // Dir for custom dirs
  2236. $tmp = explode(',', $dolibarr_main_document_root_alt);
  2237. $dirins = $tmp[0];
  2238. $accessallowed = ($user->admin && preg_match('/^module_.*\.zip$/', basename($original_file)));
  2239. $original_file = $dirins.'/'.$original_file;
  2240. } elseif ($modulepart == 'mycompany' && !empty($conf->mycompany->dir_output)) {
  2241. // Wrapping for some images
  2242. $accessallowed = 1;
  2243. $original_file = $conf->mycompany->dir_output.'/'.$original_file;
  2244. } elseif ($modulepart == 'userphoto' && !empty($conf->user->dir_output)) {
  2245. // Wrapping for users photos (user photos are allowed to any connected users)
  2246. $accessallowed = 0;
  2247. if (preg_match('/^\d+\/photos\//', $original_file)) {
  2248. $accessallowed = 1;
  2249. }
  2250. $original_file = $conf->user->dir_output.'/'.$original_file;
  2251. } elseif ($modulepart == 'userphotopublic' && !empty($conf->user->dir_output)) {
  2252. // Wrapping for users photos that were set to public by their owner (public user photos can be read with the public link and securekey)
  2253. $accessok = false;
  2254. $reg = array();
  2255. if (preg_match('/^(\d+)\/photos\//', $original_file, $reg)) {
  2256. if ($reg[0]) {
  2257. $tmpobject = new User($db);
  2258. $tmpobject->fetch($reg[0], '', '', 1);
  2259. if (getDolUserInt('USER_ENABLE_PUBLIC', 0, $tmpobject)) {
  2260. $securekey = GETPOST('securekey', 'alpha', 1);
  2261. // Security check
  2262. global $dolibarr_main_instance_unique_id;
  2263. $encodedsecurekey = dol_hash($dolibarr_main_instance_unique_id.'uservirtualcard'.$tmpobject->id.'-'.$tmpobject->login, 'md5');
  2264. if ($encodedsecurekey == $securekey) {
  2265. $accessok = true;
  2266. }
  2267. }
  2268. }
  2269. }
  2270. if ($accessok) {
  2271. $accessallowed = 1;
  2272. }
  2273. $original_file = $conf->user->dir_output.'/'.$original_file;
  2274. } elseif (($modulepart == 'companylogo') && !empty($conf->mycompany->dir_output)) {
  2275. // Wrapping for company logos (company logos are allowed to anyboby, they are public)
  2276. $accessallowed = 1;
  2277. $original_file = $conf->mycompany->dir_output.'/logos/'.$original_file;
  2278. } elseif ($modulepart == 'memberphoto' && !empty($conf->adherent->dir_output)) {
  2279. // Wrapping for members photos
  2280. $accessallowed = 0;
  2281. if (preg_match('/^\d+\/photos\//', $original_file)) {
  2282. $accessallowed = 1;
  2283. }
  2284. $original_file = $conf->adherent->dir_output.'/'.$original_file;
  2285. } elseif ($modulepart == 'apercufacture' && !empty($conf->facture->multidir_output[$entity])) {
  2286. // Wrapping for invoices (user need permission to read invoices)
  2287. if ($fuser->hasRight('facture', $lire)) {
  2288. $accessallowed = 1;
  2289. }
  2290. $original_file = $conf->facture->multidir_output[$entity].'/'.$original_file;
  2291. } elseif ($modulepart == 'apercupropal' && !empty($conf->propal->multidir_output[$entity])) {
  2292. // Wrapping pour les apercu propal
  2293. if ($fuser->hasRight('propal', $lire)) {
  2294. $accessallowed = 1;
  2295. }
  2296. $original_file = $conf->propal->multidir_output[$entity].'/'.$original_file;
  2297. } elseif ($modulepart == 'apercucommande' && !empty($conf->commande->multidir_output[$entity])) {
  2298. // Wrapping pour les apercu commande
  2299. if ($fuser->hasRight('commande', $lire)) {
  2300. $accessallowed = 1;
  2301. }
  2302. $original_file = $conf->commande->multidir_output[$entity].'/'.$original_file;
  2303. } elseif (($modulepart == 'apercufichinter' || $modulepart == 'apercuficheinter') && !empty($conf->ficheinter->dir_output)) {
  2304. // Wrapping pour les apercu intervention
  2305. if ($fuser->hasRight('ficheinter', $lire)) {
  2306. $accessallowed = 1;
  2307. }
  2308. $original_file = $conf->ficheinter->dir_output.'/'.$original_file;
  2309. } elseif (($modulepart == 'apercucontract') && !empty($conf->contrat->multidir_output[$entity])) {
  2310. // Wrapping pour les apercu contrat
  2311. if ($fuser->hasRight('contrat', $lire)) {
  2312. $accessallowed = 1;
  2313. }
  2314. $original_file = $conf->contrat->multidir_output[$entity].'/'.$original_file;
  2315. } elseif (($modulepart == 'apercusupplier_proposal' || $modulepart == 'apercusupplier_proposal') && !empty($conf->supplier_proposal->dir_output)) {
  2316. // Wrapping pour les apercu supplier proposal
  2317. if ($fuser->hasRight('supplier_proposal', $lire)) {
  2318. $accessallowed = 1;
  2319. }
  2320. $original_file = $conf->supplier_proposal->dir_output.'/'.$original_file;
  2321. } elseif (($modulepart == 'apercusupplier_order' || $modulepart == 'apercusupplier_order') && !empty($conf->fournisseur->commande->dir_output)) {
  2322. // Wrapping pour les apercu supplier order
  2323. if ($fuser->hasRight('fournisseur', 'commande', $lire)) {
  2324. $accessallowed = 1;
  2325. }
  2326. $original_file = $conf->fournisseur->commande->dir_output.'/'.$original_file;
  2327. } elseif (($modulepart == 'apercusupplier_invoice' || $modulepart == 'apercusupplier_invoice') && !empty($conf->fournisseur->facture->dir_output)) {
  2328. // Wrapping pour les apercu supplier invoice
  2329. if ($fuser->hasRight('fournisseur', $lire)) {
  2330. $accessallowed = 1;
  2331. }
  2332. $original_file = $conf->fournisseur->facture->dir_output.'/'.$original_file;
  2333. } elseif (($modulepart == 'holiday') && !empty($conf->holiday->dir_output)) {
  2334. if ($fuser->hasRight('holiday', $read) || !empty($fuser->rights->holiday->readall) || preg_match('/^specimen/i', $original_file)) {
  2335. $accessallowed = 1;
  2336. // If we known $id of holiday, call checkUserAccessToObject to check permission on properties and hierarchy of leave request
  2337. if ($refname && empty($fuser->rights->holiday->readall) && !preg_match('/^specimen/i', $original_file)) {
  2338. include_once DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php';
  2339. $tmpholiday = new Holiday($db);
  2340. $tmpholiday->fetch('', $refname);
  2341. $accessallowed = checkUserAccessToObject($user, array('holiday'), $tmpholiday, 'holiday', '', '', 'rowid', '');
  2342. }
  2343. }
  2344. $original_file = $conf->holiday->dir_output.'/'.$original_file;
  2345. } elseif (($modulepart == 'expensereport') && !empty($conf->expensereport->dir_output)) {
  2346. if ($fuser->hasRight('expensereport', $lire) || !empty($fuser->rights->expensereport->readall) || preg_match('/^specimen/i', $original_file)) {
  2347. $accessallowed = 1;
  2348. // If we known $id of expensereport, call checkUserAccessToObject to check permission on properties and hierarchy of expense report
  2349. if ($refname && empty($fuser->rights->expensereport->readall) && !preg_match('/^specimen/i', $original_file)) {
  2350. include_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
  2351. $tmpexpensereport = new ExpenseReport($db);
  2352. $tmpexpensereport->fetch('', $refname);
  2353. $accessallowed = checkUserAccessToObject($user, array('expensereport'), $tmpexpensereport, 'expensereport', '', '', 'rowid', '');
  2354. }
  2355. }
  2356. $original_file = $conf->expensereport->dir_output.'/'.$original_file;
  2357. } elseif (($modulepart == 'apercuexpensereport') && !empty($conf->expensereport->dir_output)) {
  2358. // Wrapping pour les apercu expense report
  2359. if ($fuser->hasRight('expensereport', $lire)) {
  2360. $accessallowed = 1;
  2361. }
  2362. $original_file = $conf->expensereport->dir_output.'/'.$original_file;
  2363. } elseif ($modulepart == 'propalstats' && !empty($conf->propal->multidir_temp[$entity])) {
  2364. // Wrapping pour les images des stats propales
  2365. if ($fuser->hasRight('propal', $lire)) {
  2366. $accessallowed = 1;
  2367. }
  2368. $original_file = $conf->propal->multidir_temp[$entity].'/'.$original_file;
  2369. } elseif ($modulepart == 'orderstats' && !empty($conf->commande->dir_temp)) {
  2370. // Wrapping pour les images des stats commandes
  2371. if ($fuser->hasRight('commande', $lire)) {
  2372. $accessallowed = 1;
  2373. }
  2374. $original_file = $conf->commande->dir_temp.'/'.$original_file;
  2375. } elseif ($modulepart == 'orderstatssupplier' && !empty($conf->fournisseur->dir_output)) {
  2376. if ($fuser->hasRight('fournisseur', 'commande', $lire)) {
  2377. $accessallowed = 1;
  2378. }
  2379. $original_file = $conf->fournisseur->commande->dir_temp.'/'.$original_file;
  2380. } elseif ($modulepart == 'billstats' && !empty($conf->facture->dir_temp)) {
  2381. // Wrapping pour les images des stats factures
  2382. if ($fuser->hasRight('facture', $lire)) {
  2383. $accessallowed = 1;
  2384. }
  2385. $original_file = $conf->facture->dir_temp.'/'.$original_file;
  2386. } elseif ($modulepart == 'billstatssupplier' && !empty($conf->fournisseur->dir_output)) {
  2387. if ($fuser->hasRight('fournisseur', 'facture', $lire)) {
  2388. $accessallowed = 1;
  2389. }
  2390. $original_file = $conf->fournisseur->facture->dir_temp.'/'.$original_file;
  2391. } elseif ($modulepart == 'expeditionstats' && !empty($conf->expedition->dir_temp)) {
  2392. // Wrapping pour les images des stats expeditions
  2393. if ($fuser->hasRight('expedition', $lire)) {
  2394. $accessallowed = 1;
  2395. }
  2396. $original_file = $conf->expedition->dir_temp.'/'.$original_file;
  2397. } elseif ($modulepart == 'tripsexpensesstats' && !empty($conf->deplacement->dir_temp)) {
  2398. // Wrapping pour les images des stats expeditions
  2399. if ($fuser->hasRight('deplacement', $lire)) {
  2400. $accessallowed = 1;
  2401. }
  2402. $original_file = $conf->deplacement->dir_temp.'/'.$original_file;
  2403. } elseif ($modulepart == 'memberstats' && !empty($conf->adherent->dir_temp)) {
  2404. // Wrapping pour les images des stats expeditions
  2405. if ($fuser->hasRight('adherent', $lire)) {
  2406. $accessallowed = 1;
  2407. }
  2408. $original_file = $conf->adherent->dir_temp.'/'.$original_file;
  2409. } elseif (preg_match('/^productstats_/i', $modulepart) && !empty($conf->product->dir_temp)) {
  2410. // Wrapping pour les images des stats produits
  2411. if ($fuser->hasRight('produit', $lire) || $fuser->hasRight('service', $lire)) {
  2412. $accessallowed = 1;
  2413. }
  2414. $original_file = (!empty($conf->product->multidir_temp[$entity]) ? $conf->product->multidir_temp[$entity] : $conf->service->multidir_temp[$entity]).'/'.$original_file;
  2415. } elseif (in_array($modulepart, array('tax', 'tax-vat', 'tva')) && !empty($conf->tax->dir_output)) {
  2416. // Wrapping for taxes
  2417. if ($fuser->hasRight('tax', 'charges', $lire)) {
  2418. $accessallowed = 1;
  2419. }
  2420. $modulepartsuffix = str_replace('tax-', '', $modulepart);
  2421. $original_file = $conf->tax->dir_output.'/'.($modulepartsuffix != 'tax' ? $modulepartsuffix.'/' : '').$original_file;
  2422. } elseif ($modulepart == 'actions' && !empty($conf->agenda->dir_output)) {
  2423. // Wrapping for events
  2424. if ($fuser->hasRight('agenda', 'myactions', $read)) {
  2425. $accessallowed = 1;
  2426. // If we known $id of project, call checkUserAccessToObject to check permission on the given agenda event on properties and assigned users
  2427. if ($refname && !preg_match('/^specimen/i', $original_file)) {
  2428. include_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
  2429. $tmpobject = new ActionComm($db);
  2430. $tmpobject->fetch((int) $refname);
  2431. $accessallowed = checkUserAccessToObject($user, array('agenda'), $tmpobject->id, 'actioncomm&societe', 'myactions|allactions', 'fk_soc', 'id', '');
  2432. if ($user->socid && $tmpobject->socid) {
  2433. $accessallowed = checkUserAccessToObject($user, array('societe'), $tmpobject->socid);
  2434. }
  2435. }
  2436. }
  2437. $original_file = $conf->agenda->dir_output.'/'.$original_file;
  2438. } elseif ($modulepart == 'category' && !empty($conf->categorie->multidir_output[$entity])) {
  2439. // Wrapping for categories (categories are allowed if user has permission to read categories or to work on TakePos)
  2440. if (empty($entity) || empty($conf->categorie->multidir_output[$entity])) {
  2441. return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
  2442. }
  2443. if ($fuser->hasRight("categorie", $lire) || $fuser->hasRight("takepos", "run")) {
  2444. $accessallowed = 1;
  2445. }
  2446. $original_file = $conf->categorie->multidir_output[$entity].'/'.$original_file;
  2447. } elseif ($modulepart == 'prelevement' && !empty($conf->prelevement->dir_output)) {
  2448. // Wrapping pour les prelevements
  2449. if ($fuser->rights->prelevement->bons->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2450. $accessallowed = 1;
  2451. }
  2452. $original_file = $conf->prelevement->dir_output.'/'.$original_file;
  2453. } elseif ($modulepart == 'graph_stock' && !empty($conf->stock->dir_temp)) {
  2454. // Wrapping pour les graph energie
  2455. $accessallowed = 1;
  2456. $original_file = $conf->stock->dir_temp.'/'.$original_file;
  2457. } elseif ($modulepart == 'graph_fourn' && !empty($conf->fournisseur->dir_temp)) {
  2458. // Wrapping pour les graph fournisseurs
  2459. $accessallowed = 1;
  2460. $original_file = $conf->fournisseur->dir_temp.'/'.$original_file;
  2461. } elseif ($modulepart == 'graph_product' && !empty($conf->product->dir_temp)) {
  2462. // Wrapping pour les graph des produits
  2463. $accessallowed = 1;
  2464. $original_file = $conf->product->multidir_temp[$entity].'/'.$original_file;
  2465. } elseif ($modulepart == 'barcode') {
  2466. // Wrapping pour les code barre
  2467. $accessallowed = 1;
  2468. // If viewimage is called for barcode, we try to output an image on the fly, with no build of file on disk.
  2469. //$original_file=$conf->barcode->dir_temp.'/'.$original_file;
  2470. $original_file = '';
  2471. } elseif ($modulepart == 'iconmailing' && !empty($conf->mailing->dir_temp)) {
  2472. // Wrapping pour les icones de background des mailings
  2473. $accessallowed = 1;
  2474. $original_file = $conf->mailing->dir_temp.'/'.$original_file;
  2475. } elseif ($modulepart == 'scanner_user_temp' && !empty($conf->scanner->dir_temp)) {
  2476. // Wrapping pour le scanner
  2477. $accessallowed = 1;
  2478. $original_file = $conf->scanner->dir_temp.'/'.$fuser->id.'/'.$original_file;
  2479. } elseif ($modulepart == 'fckeditor' && !empty($conf->fckeditor->dir_output)) {
  2480. // Wrapping pour les images fckeditor
  2481. $accessallowed = 1;
  2482. $original_file = $conf->fckeditor->dir_output.'/'.$original_file;
  2483. } elseif ($modulepart == 'user' && !empty($conf->user->dir_output)) {
  2484. // Wrapping for users
  2485. $canreaduser = (!empty($fuser->admin) || $fuser->rights->user->user->{$lire});
  2486. if ($fuser->id == (int) $refname) {
  2487. $canreaduser = 1;
  2488. } // A user can always read its own card
  2489. if ($canreaduser || preg_match('/^specimen/i', $original_file)) {
  2490. $accessallowed = 1;
  2491. }
  2492. $original_file = $conf->user->dir_output.'/'.$original_file;
  2493. } elseif (($modulepart == 'company' || $modulepart == 'societe' || $modulepart == 'thirdparty') && !empty($conf->societe->multidir_output[$entity])) {
  2494. // Wrapping for third parties
  2495. if (empty($entity) || empty($conf->societe->multidir_output[$entity])) {
  2496. return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
  2497. }
  2498. if ($fuser->rights->societe->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2499. $accessallowed = 1;
  2500. }
  2501. $original_file = $conf->societe->multidir_output[$entity].'/'.$original_file;
  2502. $sqlprotectagainstexternals = "SELECT rowid as fk_soc FROM ".MAIN_DB_PREFIX."societe WHERE rowid='".$db->escape($refname)."' AND entity IN (".getEntity('societe').")";
  2503. } elseif ($modulepart == 'contact' && !empty($conf->societe->multidir_output[$entity])) {
  2504. // Wrapping for contact
  2505. if (empty($entity) || empty($conf->societe->multidir_output[$entity])) {
  2506. return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
  2507. }
  2508. if ($fuser->hasRight('societe', $lire)) {
  2509. $accessallowed = 1;
  2510. }
  2511. $original_file = $conf->societe->multidir_output[$entity].'/contact/'.$original_file;
  2512. } elseif (($modulepart == 'facture' || $modulepart == 'invoice') && !empty($conf->facture->multidir_output[$entity])) {
  2513. // Wrapping for invoices
  2514. if ($fuser->hasRight('facture', $lire) || preg_match('/^specimen/i', $original_file)) {
  2515. $accessallowed = 1;
  2516. }
  2517. $original_file = $conf->facture->multidir_output[$entity].'/'.$original_file;
  2518. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."facture WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('invoice').")";
  2519. } elseif ($modulepart == 'massfilesarea_proposals' && !empty($conf->propal->multidir_output[$entity])) {
  2520. // Wrapping for mass actions
  2521. if ($fuser->hasRight('propal', $lire) || preg_match('/^specimen/i', $original_file)) {
  2522. $accessallowed = 1;
  2523. }
  2524. $original_file = $conf->propal->multidir_output[$entity].'/temp/massgeneration/'.$user->id.'/'.$original_file;
  2525. } elseif ($modulepart == 'massfilesarea_orders') {
  2526. if ($fuser->hasRight('commande', $lire) || preg_match('/^specimen/i', $original_file)) {
  2527. $accessallowed = 1;
  2528. }
  2529. $original_file = $conf->commande->multidir_output[$entity].'/temp/massgeneration/'.$user->id.'/'.$original_file;
  2530. } elseif ($modulepart == 'massfilesarea_sendings') {
  2531. if ($fuser->hasRight('expedition', $lire) || preg_match('/^specimen/i', $original_file)) {
  2532. $accessallowed = 1;
  2533. }
  2534. $original_file = $conf->expedition->dir_output.'/sending/temp/massgeneration/'.$user->id.'/'.$original_file;
  2535. } elseif ($modulepart == 'massfilesarea_invoices') {
  2536. if ($fuser->hasRight('facture', $lire) || preg_match('/^specimen/i', $original_file)) {
  2537. $accessallowed = 1;
  2538. }
  2539. $original_file = $conf->facture->multidir_output[$entity].'/temp/massgeneration/'.$user->id.'/'.$original_file;
  2540. } elseif ($modulepart == 'massfilesarea_expensereport') {
  2541. if ($fuser->hasRight('facture', $lire) || preg_match('/^specimen/i', $original_file)) {
  2542. $accessallowed = 1;
  2543. }
  2544. $original_file = $conf->expensereport->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
  2545. } elseif ($modulepart == 'massfilesarea_interventions') {
  2546. if ($fuser->hasRight('ficheinter', $lire) || preg_match('/^specimen/i', $original_file)) {
  2547. $accessallowed = 1;
  2548. }
  2549. $original_file = $conf->ficheinter->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
  2550. } elseif ($modulepart == 'massfilesarea_supplier_proposal' && !empty($conf->supplier_proposal->dir_output)) {
  2551. if ($fuser->hasRight('supplier_proposal', $lire) || preg_match('/^specimen/i', $original_file)) {
  2552. $accessallowed = 1;
  2553. }
  2554. $original_file = $conf->supplier_proposal->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
  2555. } elseif ($modulepart == 'massfilesarea_supplier_order') {
  2556. if ($fuser->hasRight('fournisseur', 'commande', $lire) || preg_match('/^specimen/i', $original_file)) {
  2557. $accessallowed = 1;
  2558. }
  2559. $original_file = $conf->fournisseur->commande->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
  2560. } elseif ($modulepart == 'massfilesarea_supplier_invoice') {
  2561. if ($fuser->hasRight('fournisseur', 'facture', $lire) || preg_match('/^specimen/i', $original_file)) {
  2562. $accessallowed = 1;
  2563. }
  2564. $original_file = $conf->fournisseur->facture->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
  2565. } elseif ($modulepart == 'massfilesarea_contract' && !empty($conf->contrat->dir_output)) {
  2566. if ($fuser->hasRight('contrat', $lire) || preg_match('/^specimen/i', $original_file)) {
  2567. $accessallowed = 1;
  2568. }
  2569. $original_file = $conf->contrat->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
  2570. } elseif (($modulepart == 'fichinter' || $modulepart == 'ficheinter') && !empty($conf->ficheinter->dir_output)) {
  2571. // Wrapping for interventions
  2572. if ($fuser->hasRight('ficheinter', $lire) || preg_match('/^specimen/i', $original_file)) {
  2573. $accessallowed = 1;
  2574. }
  2575. $original_file = $conf->ficheinter->dir_output.'/'.$original_file;
  2576. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."fichinter WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  2577. } elseif ($modulepart == 'deplacement' && !empty($conf->deplacement->dir_output)) {
  2578. // Wrapping pour les deplacements et notes de frais
  2579. if ($fuser->hasRight('deplacement', $lire) || preg_match('/^specimen/i', $original_file)) {
  2580. $accessallowed = 1;
  2581. }
  2582. $original_file = $conf->deplacement->dir_output.'/'.$original_file;
  2583. //$sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."fichinter WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  2584. } elseif (($modulepart == 'propal' || $modulepart == 'propale') && isset($conf->propal->multidir_output[$entity])) {
  2585. // Wrapping pour les propales
  2586. if ($fuser->hasRight('propal', $lire) || preg_match('/^specimen/i', $original_file)) {
  2587. $accessallowed = 1;
  2588. }
  2589. $original_file = $conf->propal->multidir_output[$entity].'/'.$original_file;
  2590. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."propal WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('propal').")";
  2591. } elseif (($modulepart == 'commande' || $modulepart == 'order') && !empty($conf->commande->multidir_output[$entity])) {
  2592. // Wrapping pour les commandes
  2593. if ($fuser->rights->commande->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2594. $accessallowed = 1;
  2595. }
  2596. $original_file = $conf->commande->multidir_output[$entity].'/'.$original_file;
  2597. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."commande WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('order').")";
  2598. } elseif ($modulepart == 'project' && !empty($conf->project->dir_output)) {
  2599. // Wrapping pour les projets
  2600. if ($fuser->hasRight('projet', $lire) || preg_match('/^specimen/i', $original_file)) {
  2601. $accessallowed = 1;
  2602. // If we known $id of project, call checkUserAccessToObject to check permission on properties and contact of project
  2603. if ($refname && !preg_match('/^specimen/i', $original_file)) {
  2604. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  2605. $tmpproject = new Project($db);
  2606. $tmpproject->fetch('', $refname);
  2607. $accessallowed = checkUserAccessToObject($user, array('projet'), $tmpproject->id, 'projet&project', '', '', 'rowid', '');
  2608. }
  2609. }
  2610. $original_file = $conf->project->dir_output.'/'.$original_file;
  2611. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."projet WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('project').")";
  2612. } elseif ($modulepart == 'project_task' && !empty($conf->project->dir_output)) {
  2613. if ($fuser->hasRight('projet', $lire) || preg_match('/^specimen/i', $original_file)) {
  2614. $accessallowed = 1;
  2615. // If we known $id of project, call checkUserAccessToObject to check permission on properties and contact of project
  2616. if ($refname && !preg_match('/^specimen/i', $original_file)) {
  2617. include_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
  2618. $tmptask = new Task($db);
  2619. $tmptask->fetch('', $refname);
  2620. $accessallowed = checkUserAccessToObject($user, array('projet_task'), $tmptask->id, 'projet_task&project', '', '', 'rowid', '');
  2621. }
  2622. }
  2623. $original_file = $conf->project->dir_output.'/'.$original_file;
  2624. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."projet WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('project').")";
  2625. } elseif (($modulepart == 'commande_fournisseur' || $modulepart == 'order_supplier') && !empty($conf->fournisseur->commande->dir_output)) {
  2626. // Wrapping pour les commandes fournisseurs
  2627. if ($fuser->rights->fournisseur->commande->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2628. $accessallowed = 1;
  2629. }
  2630. $original_file = $conf->fournisseur->commande->dir_output.'/'.$original_file;
  2631. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."commande_fournisseur WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  2632. } elseif (($modulepart == 'facture_fournisseur' || $modulepart == 'invoice_supplier') && !empty($conf->fournisseur->facture->dir_output)) {
  2633. // Wrapping pour les factures fournisseurs
  2634. if ($fuser->rights->fournisseur->facture->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2635. $accessallowed = 1;
  2636. }
  2637. $original_file = $conf->fournisseur->facture->dir_output.'/'.$original_file;
  2638. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."facture_fourn WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  2639. } elseif ($modulepart == 'supplier_payment') {
  2640. // Wrapping pour les rapport de paiements
  2641. if ($fuser->rights->fournisseur->facture->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2642. $accessallowed = 1;
  2643. }
  2644. $original_file = $conf->fournisseur->payment->dir_output.'/'.$original_file;
  2645. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."paiementfournisseur WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  2646. } elseif ($modulepart == 'facture_paiement' && !empty($conf->facture->dir_output)) {
  2647. // Wrapping pour les rapport de paiements
  2648. if ($fuser->hasRight('facture', $lire) || preg_match('/^specimen/i', $original_file)) {
  2649. $accessallowed = 1;
  2650. }
  2651. if ($fuser->socid > 0) {
  2652. $original_file = $conf->facture->dir_output.'/payments/private/'.$fuser->id.'/'.$original_file;
  2653. } else {
  2654. $original_file = $conf->facture->dir_output.'/payments/'.$original_file;
  2655. }
  2656. } elseif ($modulepart == 'export_compta' && !empty($conf->accounting->dir_output)) {
  2657. // Wrapping for accounting exports
  2658. if ($fuser->rights->accounting->bind->write || preg_match('/^specimen/i', $original_file)) {
  2659. $accessallowed = 1;
  2660. }
  2661. $original_file = $conf->accounting->dir_output.'/'.$original_file;
  2662. } elseif (($modulepart == 'expedition' || $modulepart == 'shipment') && !empty($conf->expedition->dir_output)) {
  2663. // Wrapping pour les expedition
  2664. if ($fuser->hasRight('expedition', $lire) || preg_match('/^specimen/i', $original_file)) {
  2665. $accessallowed = 1;
  2666. }
  2667. $original_file = $conf->expedition->dir_output."/".(strpos('sending/', $original_file) === 0 ? '' : 'sending/').$original_file;
  2668. //$original_file = $conf->expedition->dir_output."/".$original_file;
  2669. } elseif (($modulepart == 'livraison' || $modulepart == 'delivery') && !empty($conf->expedition->dir_output)) {
  2670. // Delivery Note Wrapping
  2671. if ($fuser->hasRight('expedition', 'delivery', $lire) || preg_match('/^specimen/i', $original_file)) {
  2672. $accessallowed = 1;
  2673. }
  2674. $original_file = $conf->expedition->dir_output."/".(strpos('receipt/', $original_file) === 0 ? '' : 'receipt/').$original_file;
  2675. } elseif ($modulepart == 'actions' && !empty($conf->agenda->dir_output)) {
  2676. // Wrapping pour les actions
  2677. if ($fuser->hasRight('agenda', 'myactions', $read) || preg_match('/^specimen/i', $original_file)) {
  2678. $accessallowed = 1;
  2679. }
  2680. $original_file = $conf->agenda->dir_output.'/'.$original_file;
  2681. } elseif ($modulepart == 'actionsreport' && !empty($conf->agenda->dir_temp)) {
  2682. // Wrapping pour les actions
  2683. if ($fuser->hasRight('agenda', 'allactions', $read) || preg_match('/^specimen/i', $original_file)) {
  2684. $accessallowed = 1;
  2685. }
  2686. $original_file = $conf->agenda->dir_temp."/".$original_file;
  2687. } elseif ($modulepart == 'product' || $modulepart == 'produit' || $modulepart == 'service' || $modulepart == 'produit|service') {
  2688. // Wrapping pour les produits et services
  2689. if (empty($entity) || (empty($conf->product->multidir_output[$entity]) && empty($conf->service->multidir_output[$entity]))) {
  2690. return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
  2691. }
  2692. if (($fuser->hasRight('produit', $lire) || $fuser->hasRight('service', $lire)) || preg_match('/^specimen/i', $original_file)) {
  2693. $accessallowed = 1;
  2694. }
  2695. if (isModEnabled("product")) {
  2696. $original_file = $conf->product->multidir_output[$entity].'/'.$original_file;
  2697. } elseif (isModEnabled("service")) {
  2698. $original_file = $conf->service->multidir_output[$entity].'/'.$original_file;
  2699. }
  2700. } elseif ($modulepart == 'product_batch' || $modulepart == 'produitlot') {
  2701. // Wrapping pour les lots produits
  2702. if (empty($entity) || (empty($conf->productbatch->multidir_output[$entity]))) {
  2703. return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
  2704. }
  2705. if (($fuser->hasRight('produit', $lire)) || preg_match('/^specimen/i', $original_file)) {
  2706. $accessallowed = 1;
  2707. }
  2708. if (isModEnabled('productbatch')) {
  2709. $original_file = $conf->productbatch->multidir_output[$entity].'/'.$original_file;
  2710. }
  2711. } elseif ($modulepart == 'movement' || $modulepart == 'mouvement') {
  2712. // Wrapping for stock movements
  2713. if (empty($entity) || empty($conf->stock->multidir_output[$entity])) {
  2714. return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
  2715. }
  2716. if (($fuser->hasRight('stock', $lire) || $fuser->hasRight('stock', 'movement', $lire) || $fuser->hasRight('stock', 'mouvement', $lire)) || preg_match('/^specimen/i', $original_file)) {
  2717. $accessallowed = 1;
  2718. }
  2719. if (isModEnabled('stock')) {
  2720. $original_file = $conf->stock->multidir_output[$entity].'/movement/'.$original_file;
  2721. }
  2722. } elseif ($modulepart == 'contract' && !empty($conf->contrat->multidir_output[$entity])) {
  2723. // Wrapping pour les contrats
  2724. if ($fuser->rights->contrat->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2725. $accessallowed = 1;
  2726. }
  2727. $original_file = $conf->contrat->multidir_output[$entity].'/'.$original_file;
  2728. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."contrat WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('contract').")";
  2729. } elseif ($modulepart == 'donation' && !empty($conf->don->dir_output)) {
  2730. // Wrapping pour les dons
  2731. if ($fuser->hasRight('don', $lire) || preg_match('/^specimen/i', $original_file)) {
  2732. $accessallowed = 1;
  2733. }
  2734. $original_file = $conf->don->dir_output.'/'.$original_file;
  2735. } elseif ($modulepart == 'dolresource' && !empty($conf->resource->dir_output)) {
  2736. // Wrapping pour les dons
  2737. if ($fuser->hasRight('resource', $read) || preg_match('/^specimen/i', $original_file)) {
  2738. $accessallowed = 1;
  2739. }
  2740. $original_file = $conf->resource->dir_output.'/'.$original_file;
  2741. } elseif (($modulepart == 'remisecheque' || $modulepart == 'chequereceipt') && !empty($conf->bank->dir_output)) {
  2742. // Wrapping pour les remises de cheques
  2743. if ($fuser->hasRight('banque', $lire) || preg_match('/^specimen/i', $original_file)) {
  2744. $accessallowed = 1;
  2745. }
  2746. $original_file = $conf->bank->dir_output.'/checkdeposits/'.$original_file; // original_file should contains relative path so include the get_exdir result
  2747. } elseif (($modulepart == 'banque' || $modulepart == 'bank') && !empty($conf->bank->dir_output)) {
  2748. // Wrapping for bank
  2749. if ($fuser->hasRight('banque', $lire)) {
  2750. $accessallowed = 1;
  2751. }
  2752. $original_file = $conf->bank->dir_output.'/'.$original_file;
  2753. } elseif ($modulepart == 'export' && !empty($conf->export->dir_temp)) {
  2754. // Wrapping for export module
  2755. // Note that a test may not be required because we force the dir of download on the directory of the user that export
  2756. $accessallowed = $user->rights->export->lire;
  2757. $original_file = $conf->export->dir_temp.'/'.$fuser->id.'/'.$original_file;
  2758. } elseif ($modulepart == 'import' && !empty($conf->import->dir_temp)) {
  2759. // Wrapping for import module
  2760. $accessallowed = $user->rights->import->run;
  2761. $original_file = $conf->import->dir_temp.'/'.$original_file;
  2762. } elseif ($modulepart == 'recruitment' && !empty($conf->recruitment->dir_output)) {
  2763. // Wrapping for recruitment module
  2764. $accessallowed = $user->rights->recruitment->recruitmentjobposition->read;
  2765. $original_file = $conf->recruitment->dir_output.'/'.$original_file;
  2766. } elseif ($modulepart == 'editor' && !empty($conf->fckeditor->dir_output)) {
  2767. // Wrapping for wysiwyg editor
  2768. $accessallowed = 1;
  2769. $original_file = $conf->fckeditor->dir_output.'/'.$original_file;
  2770. } elseif ($modulepart == 'systemtools' && !empty($conf->admin->dir_output)) {
  2771. // Wrapping for backups
  2772. if ($fuser->admin) {
  2773. $accessallowed = 1;
  2774. }
  2775. $original_file = $conf->admin->dir_output.'/'.$original_file;
  2776. } elseif ($modulepart == 'admin_temp' && !empty($conf->admin->dir_temp)) {
  2777. // Wrapping for upload file test
  2778. if ($fuser->admin) {
  2779. $accessallowed = 1;
  2780. }
  2781. $original_file = $conf->admin->dir_temp.'/'.$original_file;
  2782. } elseif ($modulepart == 'bittorrent' && !empty($conf->bittorrent->dir_output)) {
  2783. // Wrapping pour BitTorrent
  2784. $accessallowed = 1;
  2785. $dir = 'files';
  2786. if (dol_mimetype($original_file) == 'application/x-bittorrent') {
  2787. $dir = 'torrents';
  2788. }
  2789. $original_file = $conf->bittorrent->dir_output.'/'.$dir.'/'.$original_file;
  2790. } elseif ($modulepart == 'member' && !empty($conf->adherent->dir_output)) {
  2791. // Wrapping pour Foundation module
  2792. if ($fuser->hasRight('adherent', $lire) || preg_match('/^specimen/i', $original_file)) {
  2793. $accessallowed = 1;
  2794. }
  2795. $original_file = $conf->adherent->dir_output.'/'.$original_file;
  2796. } elseif ($modulepart == 'scanner_user_temp' && !empty($conf->scanner->dir_temp)) {
  2797. // Wrapping for Scanner
  2798. $accessallowed = 1;
  2799. $original_file = $conf->scanner->dir_temp.'/'.$fuser->id.'/'.$original_file;
  2800. // If modulepart=module_user_temp Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/temp/iduser
  2801. // If modulepart=module_temp Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/temp
  2802. // If modulepart=module_user Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/iduser
  2803. // If modulepart=module Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart
  2804. // If modulepart=module-abc Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart
  2805. } else {
  2806. // GENERIC Wrapping
  2807. //var_dump($modulepart);
  2808. //var_dump($original_file);
  2809. if (preg_match('/^specimen/i', $original_file)) {
  2810. $accessallowed = 1; // If link to a file called specimen. Test must be done before changing $original_file int full path.
  2811. }
  2812. if ($fuser->admin) {
  2813. $accessallowed = 1; // If user is admin
  2814. }
  2815. $tmpmodulepart = explode('-', $modulepart);
  2816. if (!empty($tmpmodulepart[1])) {
  2817. $modulepart = $tmpmodulepart[0];
  2818. $original_file = $tmpmodulepart[1].'/'.$original_file;
  2819. }
  2820. // Define $accessallowed
  2821. $reg = array();
  2822. if (preg_match('/^([a-z]+)_user_temp$/i', $modulepart, $reg)) {
  2823. if (empty($conf->{$reg[1]}->dir_temp)) { // modulepart not supported
  2824. dol_print_error('', 'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
  2825. exit;
  2826. }
  2827. if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) {
  2828. $accessallowed = 1;
  2829. }
  2830. $original_file = $conf->{$reg[1]}->dir_temp.'/'.$fuser->id.'/'.$original_file;
  2831. } elseif (preg_match('/^([a-z]+)_temp$/i', $modulepart, $reg)) {
  2832. if (empty($conf->{$reg[1]}->dir_temp)) { // modulepart not supported
  2833. dol_print_error('', 'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
  2834. exit;
  2835. }
  2836. if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) {
  2837. $accessallowed = 1;
  2838. }
  2839. $original_file = $conf->{$reg[1]}->dir_temp.'/'.$original_file;
  2840. } elseif (preg_match('/^([a-z]+)_user$/i', $modulepart, $reg)) {
  2841. if (empty($conf->{$reg[1]}->dir_output)) { // modulepart not supported
  2842. dol_print_error('', 'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
  2843. exit;
  2844. }
  2845. if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) {
  2846. $accessallowed = 1;
  2847. }
  2848. $original_file = $conf->{$reg[1]}->dir_output.'/'.$fuser->id.'/'.$original_file;
  2849. } elseif (preg_match('/^massfilesarea_([a-z]+)$/i', $modulepart, $reg)) {
  2850. if (empty($conf->{$reg[1]}->dir_output)) { // modulepart not supported
  2851. dol_print_error('', 'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
  2852. exit;
  2853. }
  2854. if ($fuser->rights->{$reg[1]}->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2855. $accessallowed = 1;
  2856. }
  2857. $original_file = $conf->{$reg[1]}->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
  2858. } else {
  2859. if (empty($conf->$modulepart->dir_output)) { // modulepart not supported
  2860. 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.');
  2861. exit;
  2862. }
  2863. // Check fuser->rights->modulepart->myobject->read and fuser->rights->modulepart->read
  2864. $partsofdirinoriginalfile = explode('/', $original_file);
  2865. if (!empty($partsofdirinoriginalfile[1])) { // If original_file is xxx/filename (xxx is a part we will use)
  2866. $partofdirinoriginalfile = $partsofdirinoriginalfile[0];
  2867. if ($partofdirinoriginalfile && !empty($fuser->rights->$modulepart->$partofdirinoriginalfile) && ($fuser->rights->$modulepart->$partofdirinoriginalfile->{$lire} || $fuser->rights->$modulepart->$partofdirinoriginalfile->{$read})) {
  2868. $accessallowed = 1;
  2869. }
  2870. }
  2871. if (!empty($fuser->rights->$modulepart->{$lire}) || !empty($fuser->rights->$modulepart->{$read})) {
  2872. $accessallowed = 1;
  2873. }
  2874. if (is_array($conf->$modulepart->multidir_output) && !empty($conf->$modulepart->multidir_output[$entity])) {
  2875. $original_file = $conf->$modulepart->multidir_output[$entity].'/'.$original_file;
  2876. } else {
  2877. $original_file = $conf->$modulepart->dir_output.'/'.$original_file;
  2878. }
  2879. }
  2880. $parameters = array(
  2881. 'modulepart' => $modulepart,
  2882. 'original_file' => $original_file,
  2883. 'entity' => $entity,
  2884. 'fuser' => $fuser,
  2885. 'refname' => '',
  2886. 'mode' => $mode
  2887. );
  2888. $reshook = $hookmanager->executeHooks('checkSecureAccess', $parameters, $object);
  2889. if ($reshook > 0) {
  2890. if (!empty($hookmanager->resArray['original_file'])) {
  2891. $original_file = $hookmanager->resArray['original_file'];
  2892. }
  2893. if (!empty($hookmanager->resArray['accessallowed'])) {
  2894. $accessallowed = $hookmanager->resArray['accessallowed'];
  2895. }
  2896. if (!empty($hookmanager->resArray['sqlprotectagainstexternals'])) {
  2897. $sqlprotectagainstexternals = $hookmanager->resArray['sqlprotectagainstexternals'];
  2898. }
  2899. }
  2900. }
  2901. $ret = array(
  2902. 'accessallowed' => ($accessallowed ? 1 : 0),
  2903. 'sqlprotectagainstexternals' => $sqlprotectagainstexternals,
  2904. 'original_file' => $original_file
  2905. );
  2906. return $ret;
  2907. }
  2908. /**
  2909. * Store object in file.
  2910. *
  2911. * @param string $directory Directory of cache
  2912. * @param string $filename Name of filecache
  2913. * @param mixed $object Object to store in cachefile
  2914. * @return void
  2915. */
  2916. function dol_filecache($directory, $filename, $object)
  2917. {
  2918. if (!dol_is_dir($directory)) {
  2919. dol_mkdir($directory);
  2920. }
  2921. $cachefile = $directory.$filename;
  2922. file_put_contents($cachefile, serialize($object), LOCK_EX);
  2923. dolChmod($cachefile, '0644');
  2924. }
  2925. /**
  2926. * Test if Refresh needed.
  2927. *
  2928. * @param string $directory Directory of cache
  2929. * @param string $filename Name of filecache
  2930. * @param int $cachetime Cachetime delay
  2931. * @return boolean 0 no refresh 1 if refresh needed
  2932. */
  2933. function dol_cache_refresh($directory, $filename, $cachetime)
  2934. {
  2935. $now = dol_now();
  2936. $cachefile = $directory.$filename;
  2937. $refresh = !file_exists($cachefile) || ($now - $cachetime) > dol_filemtime($cachefile);
  2938. return $refresh;
  2939. }
  2940. /**
  2941. * Read object from cachefile.
  2942. *
  2943. * @param string $directory Directory of cache
  2944. * @param string $filename Name of filecache
  2945. * @return mixed Unserialise from file
  2946. */
  2947. function dol_readcachefile($directory, $filename)
  2948. {
  2949. $cachefile = $directory.$filename;
  2950. $object = unserialize(file_get_contents($cachefile));
  2951. return $object;
  2952. }
  2953. /**
  2954. * Function to get list of updated or modified files.
  2955. * $file_list is used as global variable
  2956. *
  2957. * @param array $file_list Array for response
  2958. * @param SimpleXMLElement $dir SimpleXMLElement of files to test
  2959. * @param string $path Path of files relative to $pathref. We start with ''. Used by recursive calls.
  2960. * @param string $pathref Path ref (DOL_DOCUMENT_ROOT)
  2961. * @param array $checksumconcat Array of checksum
  2962. * @return array Array of filenames
  2963. */
  2964. function getFilesUpdated(&$file_list, SimpleXMLElement $dir, $path = '', $pathref = '', &$checksumconcat = array())
  2965. {
  2966. global $conffile;
  2967. $exclude = 'install';
  2968. foreach ($dir->md5file as $file) { // $file is a simpleXMLElement
  2969. $filename = $path.$file['name'];
  2970. $file_list['insignature'][] = $filename;
  2971. $expectedsize = (empty($file['size']) ? '' : $file['size']);
  2972. $expectedmd5 = (string) $file;
  2973. //if (preg_match('#'.$exclude.'#', $filename)) continue;
  2974. if (!file_exists($pathref.'/'.$filename)) {
  2975. $file_list['missing'][] = array('filename'=>$filename, 'expectedmd5'=>$expectedmd5, 'expectedsize'=>$expectedsize);
  2976. } else {
  2977. $md5_local = md5_file($pathref.'/'.$filename);
  2978. 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
  2979. $checksumconcat[] = $expectedmd5;
  2980. } else {
  2981. if ($md5_local != $expectedmd5) {
  2982. $file_list['updated'][] = array('filename'=>$filename, 'expectedmd5'=>$expectedmd5, 'expectedsize'=>$expectedsize, 'md5'=>(string) $md5_local);
  2983. }
  2984. $checksumconcat[] = $md5_local;
  2985. }
  2986. }
  2987. }
  2988. foreach ($dir->dir as $subdir) { // $subdir['name'] is '' or '/accountancy/admin' for example
  2989. getFilesUpdated($file_list, $subdir, $path.$subdir['name'].'/', $pathref, $checksumconcat);
  2990. }
  2991. return $file_list;
  2992. }