files.lib.php 119 KB

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