files.lib.php 113 KB

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