files.lib.php 119 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039
  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. * @return boolean True if no error (file is deleted or if glob is used and there's nothing to delete), False if error
  1031. * @see dol_delete_dir()
  1032. */
  1033. function dol_delete_file($file, $disableglob = 0, $nophperrors = 0, $nohook = 0, $object = null, $allowdotdot = false, $indexdatabase = 1)
  1034. {
  1035. global $db, $conf, $user, $langs;
  1036. global $hookmanager;
  1037. // Load translation files required by the page
  1038. $langs->loadLangs(array('other', 'errors'));
  1039. dol_syslog("dol_delete_file file=".$file." disableglob=".$disableglob." nophperrors=".$nophperrors." nohook=".$nohook);
  1040. // Security:
  1041. // We refuse transversal using .. and pipes into filenames.
  1042. if ((!$allowdotdot && preg_match('/\.\./', $file)) || preg_match('/[<>|]/', $file)) {
  1043. dol_syslog("Refused to delete file ".$file, LOG_WARNING);
  1044. return false;
  1045. }
  1046. $reshook = 0;
  1047. if (empty($nohook)) {
  1048. $hookmanager->initHooks(array('fileslib'));
  1049. $parameters = array(
  1050. 'GET' => $_GET,
  1051. 'file' => $file,
  1052. 'disableglob'=> $disableglob,
  1053. 'nophperrors' => $nophperrors
  1054. );
  1055. $reshook = $hookmanager->executeHooks('deleteFile', $parameters, $object);
  1056. }
  1057. if (empty($nohook) && $reshook != 0) { // reshook = 0 to do standard actions, 1 = ok and replace, -1 = ko
  1058. dol_syslog("reshook=".$reshook);
  1059. if ($reshook < 0) {
  1060. return false;
  1061. }
  1062. return true;
  1063. } else {
  1064. $file_osencoded = dol_osencode($file); // New filename encoded in OS filesystem encoding charset
  1065. if (empty($disableglob) && !empty($file_osencoded)) {
  1066. $ok = true;
  1067. $globencoded = str_replace('[', '\[', $file_osencoded);
  1068. $globencoded = str_replace(']', '\]', $globencoded);
  1069. $listofdir = glob($globencoded);
  1070. if (!empty($listofdir) && is_array($listofdir)) {
  1071. foreach ($listofdir as $filename) {
  1072. if ($nophperrors) {
  1073. $ok = @unlink($filename);
  1074. } else {
  1075. $ok = unlink($filename);
  1076. }
  1077. // If it fails and it is because of the missing write permission on parent dir
  1078. if (!$ok && file_exists(dirname($filename)) && !(fileperms(dirname($filename)) & 0200)) {
  1079. 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);
  1080. @chmod(dirname($filename), fileperms(dirname($filename)) | 0200);
  1081. // Now we retry deletion
  1082. if ($nophperrors) {
  1083. $ok = @unlink($filename);
  1084. } else {
  1085. $ok = unlink($filename);
  1086. }
  1087. }
  1088. if ($ok) {
  1089. dol_syslog("Removed file ".$filename, LOG_DEBUG);
  1090. // Delete entry into ecm database
  1091. $rel_filetodelete = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $filename);
  1092. if (!preg_match('/(\/temp\/|\/thumbs\/|\.meta$)/', $rel_filetodelete)) { // If not a tmp file
  1093. if (is_object($db) && $indexdatabase) { // $db may not be defined when lib is in a context with define('NOREQUIREDB',1)
  1094. $rel_filetodelete = preg_replace('/^[\\/]/', '', $rel_filetodelete);
  1095. $rel_filetodelete = preg_replace('/\.noexe$/', '', $rel_filetodelete);
  1096. dol_syslog("Try to remove also entries in database for full relative path = ".$rel_filetodelete, LOG_DEBUG);
  1097. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  1098. $ecmfile = new EcmFiles($db);
  1099. $result = $ecmfile->fetch(0, '', $rel_filetodelete);
  1100. if ($result >= 0 && $ecmfile->id > 0) {
  1101. $result = $ecmfile->delete($user);
  1102. }
  1103. if ($result < 0) {
  1104. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  1105. }
  1106. }
  1107. }
  1108. } else {
  1109. dol_syslog("Failed to remove file ".$filename, LOG_WARNING);
  1110. // TODO Failure to remove can be because file was already removed or because of permission
  1111. // If error because it does not exists, we should return true, and we should return false if this is a permission problem
  1112. }
  1113. }
  1114. } else {
  1115. dol_syslog("No files to delete found", LOG_DEBUG);
  1116. }
  1117. } else {
  1118. $ok = false;
  1119. if ($nophperrors) {
  1120. $ok = @unlink($file_osencoded);
  1121. } else {
  1122. $ok = unlink($file_osencoded);
  1123. }
  1124. if ($ok) {
  1125. dol_syslog("Removed file ".$file_osencoded, LOG_DEBUG);
  1126. } else {
  1127. dol_syslog("Failed to remove file ".$file_osencoded, LOG_WARNING);
  1128. }
  1129. }
  1130. return $ok;
  1131. }
  1132. }
  1133. /**
  1134. * Remove a directory (not recursive, so content must be empty).
  1135. * If directory is not empty, return false
  1136. *
  1137. * @param string $dir Directory to delete
  1138. * @param int $nophperrors Disable all PHP output errors
  1139. * @return boolean True if success, false if error
  1140. * @see dol_delete_file() dolCopyDir()
  1141. */
  1142. function dol_delete_dir($dir, $nophperrors = 0)
  1143. {
  1144. // Security:
  1145. // We refuse transversal using .. and pipes into filenames.
  1146. if (preg_match('/\.\./', $dir) || preg_match('/[<>|]/', $dir)) {
  1147. dol_syslog("Refused to delete dir ".$dir, LOG_WARNING);
  1148. return false;
  1149. }
  1150. $dir_osencoded = dol_osencode($dir);
  1151. return ($nophperrors ? @rmdir($dir_osencoded) : rmdir($dir_osencoded));
  1152. }
  1153. /**
  1154. * Remove a directory $dir and its subdirectories (or only files and subdirectories)
  1155. *
  1156. * @param string $dir Dir to delete
  1157. * @param int $count Counter to count nb of elements found to delete
  1158. * @param int $nophperrors Disable all PHP output errors
  1159. * @param int $onlysub Delete only files and subdir, not main directory
  1160. * @param int $countdeleted Counter to count nb of elements found really deleted
  1161. * @return int Number of files and directory we try to remove. NB really removed is returned into var by reference $countdeleted.
  1162. */
  1163. function dol_delete_dir_recursive($dir, $count = 0, $nophperrors = 0, $onlysub = 0, &$countdeleted = 0)
  1164. {
  1165. dol_syslog("functions.lib:dol_delete_dir_recursive ".$dir, LOG_DEBUG);
  1166. if (dol_is_dir($dir)) {
  1167. $dir_osencoded = dol_osencode($dir);
  1168. if ($handle = opendir("$dir_osencoded")) {
  1169. while (false !== ($item = readdir($handle))) {
  1170. if (!utf8_check($item)) {
  1171. $item = utf8_encode($item); // should be useless
  1172. }
  1173. if ($item != "." && $item != "..") {
  1174. if (is_dir(dol_osencode("$dir/$item")) && !is_link(dol_osencode("$dir/$item"))) {
  1175. $count = dol_delete_dir_recursive("$dir/$item", $count, $nophperrors, 0, $countdeleted);
  1176. } else {
  1177. $result = dol_delete_file("$dir/$item", 1, $nophperrors);
  1178. $count++;
  1179. if ($result) {
  1180. $countdeleted++;
  1181. }
  1182. //else print 'Error on '.$item."\n";
  1183. }
  1184. }
  1185. }
  1186. closedir($handle);
  1187. if (empty($onlysub)) {
  1188. $result = dol_delete_dir($dir, $nophperrors);
  1189. $count++;
  1190. if ($result) {
  1191. $countdeleted++;
  1192. }
  1193. //else print 'Error on '.$dir."\n";
  1194. }
  1195. }
  1196. }
  1197. return $count;
  1198. }
  1199. /**
  1200. * Delete all preview files linked to object instance.
  1201. * Note that preview image of PDF files is generated when required, by dol_banner_tab() for example.
  1202. *
  1203. * @param object $object Object to clean
  1204. * @return int 0 if error, 1 if OK
  1205. * @see dol_convert_file()
  1206. */
  1207. function dol_delete_preview($object)
  1208. {
  1209. global $langs, $conf;
  1210. // Define parent dir of elements
  1211. $element = $object->element;
  1212. if ($object->element == 'order_supplier') {
  1213. $dir = $conf->fournisseur->commande->dir_output;
  1214. } elseif ($object->element == 'invoice_supplier') {
  1215. $dir = $conf->fournisseur->facture->dir_output;
  1216. } elseif ($object->element == 'project') {
  1217. $dir = $conf->projet->dir_output;
  1218. } elseif ($object->element == 'shipping') {
  1219. $dir = $conf->expedition->dir_output.'/sending';
  1220. } elseif ($object->element == 'delivery') {
  1221. $dir = $conf->expedition->dir_output.'/receipt';
  1222. } elseif ($object->element == 'fichinter') {
  1223. $dir = $conf->ficheinter->dir_output;
  1224. } else {
  1225. $dir = empty($conf->$element->dir_output) ? '' : $conf->$element->dir_output;
  1226. }
  1227. if (empty($dir)) {
  1228. return 'ErrorObjectNoSupportedByFunction';
  1229. }
  1230. $refsan = dol_sanitizeFileName($object->ref);
  1231. $dir = $dir."/".$refsan;
  1232. $filepreviewnew = $dir."/".$refsan.".pdf_preview.png";
  1233. $filepreviewnewbis = $dir."/".$refsan.".pdf_preview-0.png";
  1234. $filepreviewold = $dir."/".$refsan.".pdf.png";
  1235. // For new preview files
  1236. if (file_exists($filepreviewnew) && is_writable($filepreviewnew)) {
  1237. if (!dol_delete_file($filepreviewnew, 1)) {
  1238. $object->error = $langs->trans("ErrorFailedToDeleteFile", $filepreviewnew);
  1239. return 0;
  1240. }
  1241. }
  1242. if (file_exists($filepreviewnewbis) && is_writable($filepreviewnewbis)) {
  1243. if (!dol_delete_file($filepreviewnewbis, 1)) {
  1244. $object->error = $langs->trans("ErrorFailedToDeleteFile", $filepreviewnewbis);
  1245. return 0;
  1246. }
  1247. }
  1248. // For old preview files
  1249. if (file_exists($filepreviewold) && is_writable($filepreviewold)) {
  1250. if (!dol_delete_file($filepreviewold, 1)) {
  1251. $object->error = $langs->trans("ErrorFailedToDeleteFile", $filepreviewold);
  1252. return 0;
  1253. }
  1254. } else {
  1255. $multiple = $filepreviewold.".";
  1256. for ($i = 0; $i < 20; $i++) {
  1257. $preview = $multiple.$i;
  1258. if (file_exists($preview) && is_writable($preview)) {
  1259. if (!dol_delete_file($preview, 1)) {
  1260. $object->error = $langs->trans("ErrorFailedToOpenFile", $preview);
  1261. return 0;
  1262. }
  1263. }
  1264. }
  1265. }
  1266. return 1;
  1267. }
  1268. /**
  1269. * Create a meta file with document file into same directory.
  1270. * This make "grep" search possible.
  1271. * This feature to generate the meta file is enabled only if option MAIN_DOC_CREATE_METAFILE is set.
  1272. *
  1273. * @param CommonObject $object Object
  1274. * @return int 0 if do nothing, >0 if we update meta file too, <0 if KO
  1275. */
  1276. function dol_meta_create($object)
  1277. {
  1278. global $conf;
  1279. // Create meta file
  1280. if (empty($conf->global->MAIN_DOC_CREATE_METAFILE)) {
  1281. return 0; // By default, no metafile.
  1282. }
  1283. // Define parent dir of elements
  1284. $element = $object->element;
  1285. if ($object->element == 'order_supplier') {
  1286. $dir = $conf->fournisseur->dir_output.'/commande';
  1287. } elseif ($object->element == 'invoice_supplier') {
  1288. $dir = $conf->fournisseur->dir_output.'/facture';
  1289. } elseif ($object->element == 'project') {
  1290. $dir = $conf->projet->dir_output;
  1291. } elseif ($object->element == 'shipping') {
  1292. $dir = $conf->expedition->dir_output.'/sending';
  1293. } elseif ($object->element == 'delivery') {
  1294. $dir = $conf->expedition->dir_output.'/receipt';
  1295. } elseif ($object->element == 'fichinter') {
  1296. $dir = $conf->ficheinter->dir_output;
  1297. } else {
  1298. $dir = empty($conf->$element->dir_output) ? '' : $conf->$element->dir_output;
  1299. }
  1300. if ($dir) {
  1301. $object->fetch_thirdparty();
  1302. $objectref = dol_sanitizeFileName($object->ref);
  1303. $dir = $dir."/".$objectref;
  1304. $file = $dir."/".$objectref.".meta";
  1305. if (!is_dir($dir)) {
  1306. dol_mkdir($dir);
  1307. }
  1308. if (is_dir($dir)) {
  1309. $nblines = count($object->lines);
  1310. $client = $object->thirdparty->name." ".$object->thirdparty->address." ".$object->thirdparty->zip." ".$object->thirdparty->town;
  1311. $meta = "REFERENCE=\"".$object->ref."\"
  1312. DATE=\"" . dol_print_date($object->date, '')."\"
  1313. NB_ITEMS=\"" . $nblines."\"
  1314. CLIENT=\"" . $client."\"
  1315. AMOUNT_EXCL_TAX=\"" . $object->total_ht."\"
  1316. AMOUNT=\"" . $object->total_ttc."\"\n";
  1317. for ($i = 0; $i < $nblines; $i++) {
  1318. //Pour les articles
  1319. $meta .= "ITEM_".$i."_QUANTITY=\"".$object->lines[$i]->qty."\"
  1320. ITEM_" . $i."_AMOUNT_WO_TAX=\"".$object->lines[$i]->total_ht."\"
  1321. ITEM_" . $i."_VAT=\"".$object->lines[$i]->tva_tx."\"
  1322. ITEM_" . $i."_DESCRIPTION=\"".str_replace("\r\n", "", nl2br($object->lines[$i]->desc))."\"
  1323. ";
  1324. }
  1325. }
  1326. $fp = fopen($file, "w");
  1327. fputs($fp, $meta);
  1328. fclose($fp);
  1329. if (!empty($conf->global->MAIN_UMASK)) {
  1330. @chmod($file, octdec($conf->global->MAIN_UMASK));
  1331. }
  1332. return 1;
  1333. } else {
  1334. dol_syslog('FailedToDetectDirInDolMetaCreateFor'.$object->element, LOG_WARNING);
  1335. }
  1336. return 0;
  1337. }
  1338. /**
  1339. * Scan a directory and init $_SESSION to manage uploaded files with list of all found files.
  1340. * Note: Only email module seems to use this. Other feature initialize the $_SESSION doing $formmail->clear_attached_files(); $formmail->add_attached_files()
  1341. *
  1342. * @param string $pathtoscan Path to scan
  1343. * @param string $trackid Track id (used to prefix name of session vars to avoid conflict)
  1344. * @return void
  1345. */
  1346. function dol_init_file_process($pathtoscan = '', $trackid = '')
  1347. {
  1348. $listofpaths = array();
  1349. $listofnames = array();
  1350. $listofmimes = array();
  1351. if ($pathtoscan) {
  1352. $listoffiles = dol_dir_list($pathtoscan, 'files');
  1353. foreach ($listoffiles as $key => $val) {
  1354. $listofpaths[] = $val['fullname'];
  1355. $listofnames[] = $val['name'];
  1356. $listofmimes[] = dol_mimetype($val['name']);
  1357. }
  1358. }
  1359. $keytoavoidconflict = empty($trackid) ? '' : '-'.$trackid;
  1360. $_SESSION["listofpaths".$keytoavoidconflict] = join(';', $listofpaths);
  1361. $_SESSION["listofnames".$keytoavoidconflict] = join(';', $listofnames);
  1362. $_SESSION["listofmimes".$keytoavoidconflict] = join(';', $listofmimes);
  1363. }
  1364. /**
  1365. * 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.
  1366. * All information used are in db, conf, langs, user and _FILES.
  1367. * Note: This function can be used only into a HTML page context.
  1368. *
  1369. * @param string $upload_dir Directory where to store uploaded file (note: used to forge $destpath = $upload_dir + filename)
  1370. * @param int $allowoverwrite 1=Allow overwrite existing file
  1371. * @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.
  1372. * @param string $varfiles _FILES var name
  1373. * @param string $savingdocmask Mask to use to define output filename. For example 'XXXXX-__YYYYMMDD__-__file__'
  1374. * @param string $link Link to add (to add a link instead of a file)
  1375. * @param string $trackid Track id (used to prefix name of session vars to avoid conflict)
  1376. * @param int $generatethumbs 1=Generate also thumbs for uploaded image files
  1377. * @param Object $object Object used to set 'src_object_*' fields
  1378. * @return int <=0 if KO, >0 if OK
  1379. * @see dol_remove_file_process()
  1380. */
  1381. function dol_add_file_process($upload_dir, $allowoverwrite = 0, $donotupdatesession = 0, $varfiles = 'addedfile', $savingdocmask = '', $link = null, $trackid = '', $generatethumbs = 1, $object = null)
  1382. {
  1383. global $db, $user, $conf, $langs;
  1384. $res = 0;
  1385. if (!empty($_FILES[$varfiles])) { // For view $_FILES[$varfiles]['error']
  1386. dol_syslog('dol_add_file_process upload_dir='.$upload_dir.' allowoverwrite='.$allowoverwrite.' donotupdatesession='.$donotupdatesession.' savingdocmask='.$savingdocmask, LOG_DEBUG);
  1387. $result = dol_mkdir($upload_dir);
  1388. // var_dump($result);exit;
  1389. if ($result >= 0) {
  1390. $TFile = $_FILES[$varfiles];
  1391. if (!is_array($TFile['name'])) {
  1392. foreach ($TFile as $key => &$val) {
  1393. $val = array($val);
  1394. }
  1395. }
  1396. $nbfile = count($TFile['name']);
  1397. $nbok = 0;
  1398. for ($i = 0; $i < $nbfile; $i++) {
  1399. if (empty($TFile['name'][$i])) {
  1400. continue; // For example, when submitting a form with no file name
  1401. }
  1402. // Define $destfull (path to file including filename) and $destfile (only filename)
  1403. $destfull = $upload_dir."/".$TFile['name'][$i];
  1404. $destfile = $TFile['name'][$i];
  1405. $destfilewithoutext = preg_replace('/\.[^\.]+$/', '', $destfile);
  1406. if ($savingdocmask && strpos($savingdocmask, $destfilewithoutext) !== 0) {
  1407. $destfull = $upload_dir."/".preg_replace('/__file__/', $TFile['name'][$i], $savingdocmask);
  1408. $destfile = preg_replace('/__file__/', $TFile['name'][$i], $savingdocmask);
  1409. }
  1410. $filenameto = basename($destfile);
  1411. if (preg_match('/^\./', $filenameto)) {
  1412. $langs->load("errors"); // key must be loaded because we can't rely on loading during output, we need var substitution to be done now.
  1413. setEventMessages($langs->trans("ErrorFilenameCantStartWithDot", $filenameto), null, 'errors');
  1414. break;
  1415. }
  1416. // dol_sanitizeFileName the file name and lowercase extension
  1417. $info = pathinfo($destfull);
  1418. $destfull = $info['dirname'].'/'.dol_sanitizeFileName($info['filename'].($info['extension'] != '' ? ('.'.strtolower($info['extension'])) : ''));
  1419. $info = pathinfo($destfile);
  1420. $destfile = dol_sanitizeFileName($info['filename'].($info['extension'] != '' ? ('.'.strtolower($info['extension'])) : ''));
  1421. // We apply dol_string_nohtmltag also to clean file names (this remove duplicate spaces) because
  1422. // this function is also applied when we rename and when we make try to download file (by the GETPOST(filename, 'alphanohtml') call).
  1423. $destfile = dol_string_nohtmltag($destfile);
  1424. $destfull = dol_string_nohtmltag($destfull);
  1425. // Move file from temp directory to final directory. A .noexe may also be appended on file name.
  1426. $resupload = dol_move_uploaded_file($TFile['tmp_name'][$i], $destfull, $allowoverwrite, 0, $TFile['error'][$i], 0, $varfiles, $upload_dir);
  1427. if (is_numeric($resupload) && $resupload > 0) { // $resupload can be 'ErrorFileAlreadyExists'
  1428. global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini;
  1429. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  1430. // Generate thumbs.
  1431. if ($generatethumbs) {
  1432. if (image_format_supported($destfull) == 1) {
  1433. // Create thumbs
  1434. // We can't use $object->addThumbs here because there is no $object known
  1435. // Used on logon for example
  1436. $imgThumbSmall = vignette($destfull, $maxwidthsmall, $maxheightsmall, '_small', 50, "thumbs");
  1437. // Create mini thumbs for image (Ratio is near 16/9)
  1438. // Used on menu or for setup page for example
  1439. $imgThumbMini = vignette($destfull, $maxwidthmini, $maxheightmini, '_mini', 50, "thumbs");
  1440. }
  1441. }
  1442. // Update session
  1443. if (empty($donotupdatesession)) {
  1444. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  1445. $formmail = new FormMail($db);
  1446. $formmail->trackid = $trackid;
  1447. $formmail->add_attached_files($destfull, $destfile, $TFile['type'][$i]);
  1448. }
  1449. // Update index table of files (llx_ecm_files)
  1450. if ($donotupdatesession == 1) {
  1451. $result = addFileIntoDatabaseIndex($upload_dir, basename($destfile).($resupload == 2 ? '.noexe' : ''), $TFile['name'][$i], 'uploaded', 0, $object);
  1452. if ($result < 0) {
  1453. if ($allowoverwrite) {
  1454. // Do not show error message. We can have an error due to DB_ERROR_RECORD_ALREADY_EXISTS
  1455. } else {
  1456. setEventMessages('WarningFailedToAddFileIntoDatabaseIndex', '', 'warnings');
  1457. }
  1458. }
  1459. }
  1460. $nbok++;
  1461. } else {
  1462. $langs->load("errors");
  1463. if ($resupload < 0) { // Unknown error
  1464. setEventMessages($langs->trans("ErrorFileNotUploaded"), null, 'errors');
  1465. } elseif (preg_match('/ErrorFileIsInfectedWithAVirus/', $resupload)) { // Files infected by a virus
  1466. setEventMessages($langs->trans("ErrorFileIsInfectedWithAVirus"), null, 'errors');
  1467. } else // Known error
  1468. {
  1469. setEventMessages($langs->trans($resupload), null, 'errors');
  1470. }
  1471. }
  1472. }
  1473. if ($nbok > 0) {
  1474. $res = 1;
  1475. setEventMessages($langs->trans("FileTransferComplete"), null, 'mesgs');
  1476. }
  1477. } else {
  1478. setEventMessages($langs->trans("ErrorFailedToCreateDir", $upload_dir), null, 'errors');
  1479. }
  1480. } elseif ($link) {
  1481. require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
  1482. $linkObject = new Link($db);
  1483. $linkObject->entity = $conf->entity;
  1484. $linkObject->url = $link;
  1485. $linkObject->objecttype = GETPOST('objecttype', 'alpha');
  1486. $linkObject->objectid = GETPOST('objectid', 'int');
  1487. $linkObject->label = GETPOST('label', 'alpha');
  1488. $res = $linkObject->create($user);
  1489. $langs->load('link');
  1490. if ($res > 0) {
  1491. setEventMessages($langs->trans("LinkComplete"), null, 'mesgs');
  1492. } else {
  1493. setEventMessages($langs->trans("ErrorFileNotLinked"), null, 'errors');
  1494. }
  1495. } else {
  1496. $langs->load("errors");
  1497. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("File")), null, 'errors');
  1498. }
  1499. return $res;
  1500. }
  1501. /**
  1502. * Remove an uploaded file (for example after submitting a new file a mail form).
  1503. * All information used are in db, conf, langs, user and _FILES.
  1504. *
  1505. * @param int $filenb File nb to delete
  1506. * @param int $donotupdatesession -1 or 1 = Do not update _SESSION variable
  1507. * @param int $donotdeletefile 1=Do not delete physically file
  1508. * @param string $trackid Track id (used to prefix name of session vars to avoid conflict)
  1509. * @return void
  1510. * @see dol_add_file_process()
  1511. */
  1512. function dol_remove_file_process($filenb, $donotupdatesession = 0, $donotdeletefile = 1, $trackid = '')
  1513. {
  1514. global $db, $user, $conf, $langs, $_FILES;
  1515. $keytodelete = $filenb;
  1516. $keytodelete--;
  1517. $listofpaths = array();
  1518. $listofnames = array();
  1519. $listofmimes = array();
  1520. $keytoavoidconflict = empty($trackid) ? '' : '-'.$trackid;
  1521. if (!empty($_SESSION["listofpaths".$keytoavoidconflict])) {
  1522. $listofpaths = explode(';', $_SESSION["listofpaths".$keytoavoidconflict]);
  1523. }
  1524. if (!empty($_SESSION["listofnames".$keytoavoidconflict])) {
  1525. $listofnames = explode(';', $_SESSION["listofnames".$keytoavoidconflict]);
  1526. }
  1527. if (!empty($_SESSION["listofmimes".$keytoavoidconflict])) {
  1528. $listofmimes = explode(';', $_SESSION["listofmimes".$keytoavoidconflict]);
  1529. }
  1530. if ($keytodelete >= 0) {
  1531. $pathtodelete = $listofpaths[$keytodelete];
  1532. $filetodelete = $listofnames[$keytodelete];
  1533. if (empty($donotdeletefile)) {
  1534. $result = dol_delete_file($pathtodelete, 1); // The delete of ecm database is inside the function dol_delete_file
  1535. } else {
  1536. $result = 0;
  1537. }
  1538. if ($result >= 0) {
  1539. if (empty($donotdeletefile)) {
  1540. $langs->load("other");
  1541. setEventMessages($langs->trans("FileWasRemoved", $filetodelete), null, 'mesgs');
  1542. }
  1543. if (empty($donotupdatesession)) {
  1544. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  1545. $formmail = new FormMail($db);
  1546. $formmail->trackid = $trackid;
  1547. $formmail->remove_attached_files($keytodelete);
  1548. }
  1549. }
  1550. }
  1551. }
  1552. /**
  1553. * Add a file into database index.
  1554. * Called by dol_add_file_process when uploading a file and on other cases.
  1555. * See also commonGenerateDocument that also add/update database index when a file is generated.
  1556. *
  1557. * @param string $dir Directory name (full real path without ending /)
  1558. * @param string $file File name (May end with '.noexe')
  1559. * @param string $fullpathorig Full path of origin for file (can be '')
  1560. * @param string $mode How file was created ('uploaded', 'generated', ...)
  1561. * @param int $setsharekey Set also the share key
  1562. * @param Object $object Object used to set 'src_object_*' fields
  1563. * @return int <0 if KO, 0 if nothing done, >0 if OK
  1564. */
  1565. function addFileIntoDatabaseIndex($dir, $file, $fullpathorig = '', $mode = 'uploaded', $setsharekey = 0, $object = null)
  1566. {
  1567. global $db, $user, $conf;
  1568. $result = 0;
  1569. $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
  1570. if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
  1571. $filename = basename(preg_replace('/\.noexe$/', '', $file));
  1572. $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
  1573. $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
  1574. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  1575. $ecmfile = new EcmFiles($db);
  1576. $ecmfile->filepath = $rel_dir;
  1577. $ecmfile->filename = $filename;
  1578. $ecmfile->label = md5_file(dol_osencode($dir.'/'.$file)); // MD5 of file content
  1579. $ecmfile->fullpath_orig = $fullpathorig;
  1580. $ecmfile->gen_or_uploaded = $mode;
  1581. $ecmfile->description = ''; // indexed content
  1582. $ecmfile->keywords = ''; // keyword content
  1583. if (is_object($object) && $object->id > 0) {
  1584. $ecmfile->src_object_id = $object->id;
  1585. if (isset($object->table_element)) {
  1586. $ecmfile->src_object_type = $object->table_element;
  1587. } else {
  1588. dol_syslog('Error: object ' . get_class($object) . ' has no table_element attribute.');
  1589. return -1;
  1590. }
  1591. if (isset($object->src_object_description)) $ecmfile->description = $object->src_object_description;
  1592. if (isset($object->src_object_keywords)) $ecmfile->keywords = $object->src_object_keywords;
  1593. }
  1594. if (!empty($conf->global->MAIN_FORCE_SHARING_ON_ANY_UPLOADED_FILE)) {
  1595. $setsharekey = 1;
  1596. }
  1597. if ($setsharekey) {
  1598. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  1599. $ecmfile->share = getRandomPassword(true);
  1600. }
  1601. $result = $ecmfile->create($user);
  1602. if ($result < 0) {
  1603. dol_syslog($ecmfile->error);
  1604. }
  1605. }
  1606. return $result;
  1607. }
  1608. /**
  1609. * Delete files into database index using search criterias.
  1610. *
  1611. * @param string $dir Directory name (full real path without ending /)
  1612. * @param string $file File name
  1613. * @param string $mode How file was created ('uploaded', 'generated', ...)
  1614. * @return int <0 if KO, 0 if nothing done, >0 if OK
  1615. */
  1616. function deleteFilesIntoDatabaseIndex($dir, $file, $mode = 'uploaded')
  1617. {
  1618. global $conf, $db, $user;
  1619. $error = 0;
  1620. if (empty($dir)) {
  1621. dol_syslog("deleteFilesIntoDatabaseIndex: dir parameter can't be empty", LOG_ERR);
  1622. return -1;
  1623. }
  1624. $db->begin();
  1625. $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
  1626. $filename = basename($file);
  1627. $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
  1628. $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
  1629. if (!$error) {
  1630. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'ecm_files';
  1631. $sql .= ' WHERE entity = '.$conf->entity;
  1632. $sql .= " AND filepath = '".$db->escape($rel_dir)."'";
  1633. if ($file) {
  1634. $sql .= " AND filename = '".$db->escape($file)."'";
  1635. }
  1636. if ($mode) {
  1637. $sql .= " AND gen_or_uploaded = '".$db->escape($mode)."'";
  1638. }
  1639. $resql = $db->query($sql);
  1640. if (!$resql) {
  1641. $error++;
  1642. dol_syslog(__METHOD__.' '.$db->lasterror(), LOG_ERR);
  1643. }
  1644. }
  1645. // Commit or rollback
  1646. if ($error) {
  1647. $db->rollback();
  1648. return -1 * $error;
  1649. } else {
  1650. $db->commit();
  1651. return 1;
  1652. }
  1653. }
  1654. /**
  1655. * Convert an image file or a PDF into another image format.
  1656. * This need Imagick php extension. You can use dol_imageResizeOrCrop() for a function that need GD.
  1657. *
  1658. * @param string $fileinput Input file name
  1659. * @param string $ext Format of target file (It is also extension added to file if fileoutput is not provided).
  1660. * @param string $fileoutput Output filename
  1661. * @param string $page Page number if we convert a PDF into png
  1662. * @return int <0 if KO, 0=Nothing done, >0 if OK
  1663. * @see dol_imageResizeOrCrop()
  1664. */
  1665. function dol_convert_file($fileinput, $ext = 'png', $fileoutput = '', $page = '')
  1666. {
  1667. global $langs;
  1668. if (class_exists('Imagick')) {
  1669. $image = new Imagick();
  1670. try {
  1671. $filetoconvert = $fileinput.(($page != '') ? '['.$page.']' : '');
  1672. //var_dump($filetoconvert);
  1673. $ret = $image->readImage($filetoconvert);
  1674. } catch (Exception $e) {
  1675. $ext = pathinfo($fileinput, PATHINFO_EXTENSION);
  1676. 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);
  1677. return 0;
  1678. }
  1679. if ($ret) {
  1680. $ret = $image->setImageFormat($ext);
  1681. if ($ret) {
  1682. if (empty($fileoutput)) {
  1683. $fileoutput = $fileinput.".".$ext;
  1684. }
  1685. $count = $image->getNumberImages();
  1686. if (!dol_is_file($fileoutput) || is_writeable($fileoutput)) {
  1687. try {
  1688. $ret = $image->writeImages($fileoutput, true);
  1689. } catch (Exception $e) {
  1690. dol_syslog($e->getMessage(), LOG_WARNING);
  1691. }
  1692. } else {
  1693. dol_syslog("Warning: Failed to write cache preview file '.$fileoutput.'. Check permission on file/dir", LOG_ERR);
  1694. }
  1695. if ($ret) {
  1696. return $count;
  1697. } else {
  1698. return -3;
  1699. }
  1700. } else {
  1701. return -2;
  1702. }
  1703. } else {
  1704. return -1;
  1705. }
  1706. } else {
  1707. return 0;
  1708. }
  1709. }
  1710. /**
  1711. * Compress a file.
  1712. * An error string may be returned into parameters.
  1713. *
  1714. * @param string $inputfile Source file name
  1715. * @param string $outputfile Target file name
  1716. * @param string $mode 'gz' or 'bz' or 'zip'
  1717. * @param string $errorstring Error string
  1718. * @return int <0 if KO, >0 if OK
  1719. */
  1720. function dol_compress_file($inputfile, $outputfile, $mode = "gz", &$errorstring = null)
  1721. {
  1722. global $conf;
  1723. $foundhandler = 0;
  1724. try {
  1725. dol_syslog("dol_compress_file mode=".$mode." inputfile=".$inputfile." outputfile=".$outputfile);
  1726. $data = implode("", file(dol_osencode($inputfile)));
  1727. if ($mode == 'gz') {
  1728. $foundhandler = 1;
  1729. $compressdata = gzencode($data, 9);
  1730. } elseif ($mode == 'bz') {
  1731. $foundhandler = 1;
  1732. $compressdata = bzcompress($data, 9);
  1733. } elseif ($mode == 'zip') {
  1734. if (class_exists('ZipArchive') && !empty($conf->global->MAIN_USE_ZIPARCHIVE_FOR_ZIP_COMPRESS)) {
  1735. $foundhandler = 1;
  1736. $rootPath = realpath($inputfile);
  1737. dol_syslog("Class ZipArchive is set so we zip using ZipArchive to zip into ".$outputfile.' rootPath='.$rootPath);
  1738. $zip = new ZipArchive;
  1739. if ($zip->open($outputfile, ZipArchive::CREATE) !== true) {
  1740. $errorstring = "dol_compress_file failure - Failed to open file ".$outputfile."\n";
  1741. dol_syslog($errorstring, LOG_ERR);
  1742. global $errormsg;
  1743. $errormsg = $errorstring;
  1744. return -6;
  1745. }
  1746. // Create recursive directory iterator
  1747. /** @var SplFileInfo[] $files */
  1748. $files = new RecursiveIteratorIterator(
  1749. new RecursiveDirectoryIterator($rootPath),
  1750. RecursiveIteratorIterator::LEAVES_ONLY
  1751. );
  1752. foreach ($files as $name => $file) {
  1753. // Skip directories (they would be added automatically)
  1754. if (!$file->isDir()) {
  1755. // Get real and relative path for current file
  1756. $filePath = $file->getRealPath();
  1757. $relativePath = substr($filePath, strlen($rootPath) + 1);
  1758. // Add current file to archive
  1759. $zip->addFile($filePath, $relativePath);
  1760. }
  1761. }
  1762. // Zip archive will be created only after closing object
  1763. $zip->close();
  1764. dol_syslog("dol_compress_file success - ".count($zip->numFiles)." files");
  1765. return 1;
  1766. }
  1767. if (defined('ODTPHP_PATHTOPCLZIP')) {
  1768. $foundhandler = 1;
  1769. include_once ODTPHP_PATHTOPCLZIP.'/pclzip.lib.php';
  1770. $archive = new PclZip($outputfile);
  1771. $result = $archive->add($inputfile, PCLZIP_OPT_REMOVE_PATH, dirname($inputfile));
  1772. if ($result === 0) {
  1773. global $errormsg;
  1774. $errormsg = $archive->errorInfo(true);
  1775. if ($archive->errorCode() == PCLZIP_ERR_WRITE_OPEN_FAIL) {
  1776. $errorstring = "PCLZIP_ERR_WRITE_OPEN_FAIL";
  1777. dol_syslog("dol_compress_file error - archive->errorCode() = PCLZIP_ERR_WRITE_OPEN_FAIL", LOG_ERR);
  1778. return -4;
  1779. }
  1780. $errorstring = "dol_compress_file error archive->errorCode = ".$archive->errorCode()." errormsg=".$errormsg;
  1781. dol_syslog("dol_compress_file failure - ".$errormsg, LOG_ERR);
  1782. return -3;
  1783. } else {
  1784. dol_syslog("dol_compress_file success - ".count($result)." files");
  1785. return 1;
  1786. }
  1787. }
  1788. }
  1789. if ($foundhandler) {
  1790. $fp = fopen($outputfile, "w");
  1791. fwrite($fp, $compressdata);
  1792. fclose($fp);
  1793. return 1;
  1794. } else {
  1795. $errorstring = "Try to zip with format ".$mode." with no handler for this format";
  1796. dol_syslog($errorstring, LOG_ERR);
  1797. global $errormsg;
  1798. $errormsg = $errorstring;
  1799. return -2;
  1800. }
  1801. } catch (Exception $e) {
  1802. global $langs, $errormsg;
  1803. $langs->load("errors");
  1804. $errormsg = $langs->trans("ErrorFailedToWriteInDir");
  1805. $errorstring = "Failed to open file ".$outputfile;
  1806. dol_syslog($errorstring, LOG_ERR);
  1807. return -1;
  1808. }
  1809. }
  1810. /**
  1811. * Uncompress a file
  1812. *
  1813. * @param string $inputfile File to uncompress
  1814. * @param string $outputdir Target dir name
  1815. * @return array array('error'=>'Error code') or array() if no error
  1816. */
  1817. function dol_uncompress($inputfile, $outputdir)
  1818. {
  1819. global $conf, $langs;
  1820. if (defined('ODTPHP_PATHTOPCLZIP') && empty($conf->global->MAIN_USE_ZIPARCHIVE_FOR_ZIP_UNCOMPRESS)) {
  1821. dol_syslog("Constant ODTPHP_PATHTOPCLZIP for pclzip library is set to ".ODTPHP_PATHTOPCLZIP.", so we use Pclzip to unzip into ".$outputdir);
  1822. include_once ODTPHP_PATHTOPCLZIP.'/pclzip.lib.php';
  1823. $archive = new PclZip($inputfile);
  1824. // Extract into outputdir, but only files that match the regex '/^((?!\.\.).)*$/' that means "does not include .."
  1825. $result = $archive->extract(PCLZIP_OPT_PATH, $outputdir, PCLZIP_OPT_BY_PREG, '/^((?!\.\.).)*$/');
  1826. if (!is_array($result) && $result <= 0) {
  1827. return array('error'=>$archive->errorInfo(true));
  1828. } else {
  1829. $ok = 1;
  1830. $errmsg = '';
  1831. // Loop on each file to check result for unzipping file
  1832. foreach ($result as $key => $val) {
  1833. if ($val['status'] == 'path_creation_fail') {
  1834. $langs->load("errors");
  1835. $ok = 0;
  1836. $errmsg = $langs->trans("ErrorFailToCreateDir", $val['filename']);
  1837. break;
  1838. }
  1839. }
  1840. if ($ok) {
  1841. return array();
  1842. } else {
  1843. return array('error'=>$errmsg);
  1844. }
  1845. }
  1846. }
  1847. if (class_exists('ZipArchive')) { // Must install php-zip to have it
  1848. dol_syslog("Class ZipArchive is set so we unzip using ZipArchive to unzip into ".$outputdir);
  1849. $zip = new ZipArchive;
  1850. $res = $zip->open($inputfile);
  1851. if ($res === true) {
  1852. //$zip->extractTo($outputdir.'/');
  1853. // 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
  1854. // python3 path_traversal_archiver.py <Created_file_name> test.zip -l 10 -p tmp/
  1855. // with -l is the range of dot to go back in path.
  1856. // and path_traversal_archiver.py found at https://github.com/Alamot/code-snippets/blob/master/path_traversal/path_traversal_archiver.py
  1857. for ($i = 0; $i < $zip->numFiles; $i++) {
  1858. if (preg_match('/\.\./', $zip->getNameIndex($i))) {
  1859. dol_syslog("Warning: Try to unzip a file with a transversal path ".$zip->getNameIndex($i), LOG_WARNING);
  1860. continue; // Discard the file
  1861. }
  1862. $zip->extractTo($outputdir.'/', array($zip->getNameIndex($i)));
  1863. }
  1864. $zip->close();
  1865. return array();
  1866. } else {
  1867. return array('error'=>'ErrUnzipFails');
  1868. }
  1869. }
  1870. return array('error'=>'ErrNoZipEngine');
  1871. }
  1872. /**
  1873. * Compress a directory and subdirectories into a package file.
  1874. *
  1875. * @param string $inputdir Source dir name
  1876. * @param string $outputfile Target file name (output directory must exists and be writable)
  1877. * @param string $mode 'zip'
  1878. * @param string $excludefiles A regex pattern. For example: '/\.log$|\/temp\//'
  1879. * @param string $rootdirinzip Add a root dir level in zip file
  1880. * @return int <0 if KO, >0 if OK
  1881. */
  1882. function dol_compress_dir($inputdir, $outputfile, $mode = "zip", $excludefiles = '', $rootdirinzip = '')
  1883. {
  1884. $foundhandler = 0;
  1885. dol_syslog("Try to zip dir ".$inputdir." into ".$outputfile." mode=".$mode);
  1886. if (!dol_is_dir(dirname($outputfile)) || !is_writable(dirname($outputfile))) {
  1887. global $langs, $errormsg;
  1888. $langs->load("errors");
  1889. $errormsg = $langs->trans("ErrorFailedToWriteInDir", $outputfile);
  1890. return -3;
  1891. }
  1892. try {
  1893. if ($mode == 'gz') {
  1894. $foundhandler = 0;
  1895. } elseif ($mode == 'bz') {
  1896. $foundhandler = 0;
  1897. } elseif ($mode == 'zip') {
  1898. /*if (defined('ODTPHP_PATHTOPCLZIP'))
  1899. {
  1900. $foundhandler=0; // TODO implement this
  1901. include_once ODTPHP_PATHTOPCLZIP.'/pclzip.lib.php';
  1902. $archive = new PclZip($outputfile);
  1903. $archive->add($inputfile, PCLZIP_OPT_REMOVE_PATH, dirname($inputfile));
  1904. //$archive->add($inputfile);
  1905. return 1;
  1906. }
  1907. else*/
  1908. //if (class_exists('ZipArchive') && ! empty($conf->global->MAIN_USE_ZIPARCHIVE_FOR_ZIP_COMPRESS))
  1909. if (class_exists('ZipArchive')) {
  1910. $foundhandler = 1;
  1911. // Initialize archive object
  1912. $zip = new ZipArchive();
  1913. $result = $zip->open($outputfile, ZipArchive::CREATE | ZipArchive::OVERWRITE);
  1914. if (!$result) {
  1915. global $langs, $errormsg;
  1916. $langs->load("errors");
  1917. $errormsg = $langs->trans("ErrorFailedToWriteInFile", $outputfile);
  1918. return -4;
  1919. }
  1920. // Create recursive directory iterator
  1921. /** @var SplFileInfo[] $files */
  1922. $files = new RecursiveIteratorIterator(
  1923. new RecursiveDirectoryIterator($inputdir),
  1924. RecursiveIteratorIterator::LEAVES_ONLY
  1925. );
  1926. foreach ($files as $name => $file) {
  1927. // Skip directories (they would be added automatically)
  1928. if (!$file->isDir()) {
  1929. // Get real and relative path for current file
  1930. $filePath = $file->getRealPath();
  1931. $relativePath = ($rootdirinzip ? $rootdirinzip.'/' : '').substr($filePath, strlen($inputdir) + 1);
  1932. if (empty($excludefiles) || !preg_match($excludefiles, $filePath)) {
  1933. // Add current file to archive
  1934. $zip->addFile($filePath, $relativePath);
  1935. }
  1936. }
  1937. }
  1938. // Zip archive will be created only after closing object
  1939. $zip->close();
  1940. return 1;
  1941. }
  1942. }
  1943. if (!$foundhandler) {
  1944. dol_syslog("Try to zip with format ".$mode." with no handler for this format", LOG_ERR);
  1945. return -2;
  1946. } else {
  1947. return 0;
  1948. }
  1949. } catch (Exception $e) {
  1950. global $langs, $errormsg;
  1951. $langs->load("errors");
  1952. dol_syslog("Failed to open file ".$outputfile, LOG_ERR);
  1953. dol_syslog($e->getMessage(), LOG_ERR);
  1954. $errormsg = $langs->trans("ErrorFailedToWriteInDir", $outputfile);
  1955. return -1;
  1956. }
  1957. }
  1958. /**
  1959. * Return file(s) into a directory (by default most recent)
  1960. *
  1961. * @param string $dir Directory to scan
  1962. * @param string $regexfilter Regex filter to restrict list. This regex value must be escaped for '/', since this char is used for preg_match function
  1963. * @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
  1964. * @param int $nohook Disable all hooks
  1965. * @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
  1966. * @return string Full path to most recent file
  1967. */
  1968. function dol_most_recent_file($dir, $regexfilter = '', $excludefilter = array('(\.meta|_preview.*\.png)$', '^\.'), $nohook = false, $mode = '')
  1969. {
  1970. $tmparray = dol_dir_list($dir, 'files', 0, $regexfilter, $excludefilter, 'date', SORT_DESC, $mode, $nohook);
  1971. return $tmparray[0];
  1972. }
  1973. /**
  1974. * Security check when accessing to a document (used by document.php, viewimage.php and webservices to get documents).
  1975. * TODO Replace code that set $accesallowed by a call to restrictedArea()
  1976. *
  1977. * @param string $modulepart Module of document ('module', 'module_user_temp', 'module_user' or 'module_temp'). Exemple: 'medias', 'invoice', 'logs', 'tax-vat', ...
  1978. * @param string $original_file Relative path with filename, relative to modulepart.
  1979. * @param string $entity Restrict onto entity (0=no restriction)
  1980. * @param User $fuser User object (forced)
  1981. * @param string $refname Ref of object to check permission for external users (autodetect if not provided)
  1982. * @param string $mode Check permission for 'read' or 'write'
  1983. * @return mixed Array with access information : 'accessallowed' & 'sqlprotectagainstexternals' & 'original_file' (as a full path name)
  1984. * @see restrictedArea()
  1985. */
  1986. function dol_check_secure_access_document($modulepart, $original_file, $entity, $fuser = '', $refname = '', $mode = 'read')
  1987. {
  1988. global $conf, $db, $user;
  1989. global $dolibarr_main_data_root, $dolibarr_main_document_root_alt;
  1990. if (!is_object($fuser)) {
  1991. $fuser = $user;
  1992. }
  1993. if (empty($modulepart)) {
  1994. return 'ErrorBadParameter';
  1995. }
  1996. if (empty($entity)) {
  1997. if (empty($conf->multicompany->enabled)) {
  1998. $entity = 1;
  1999. } else {
  2000. $entity = 0;
  2001. }
  2002. }
  2003. // Fix modulepart for backward compatibility
  2004. if ($modulepart == 'users') {
  2005. $modulepart = 'user';
  2006. }
  2007. if ($modulepart == 'tva') {
  2008. $modulepart = 'tax-vat';
  2009. }
  2010. //print 'dol_check_secure_access_document modulepart='.$modulepart.' original_file='.$original_file.' entity='.$entity;
  2011. dol_syslog('dol_check_secure_access_document modulepart='.$modulepart.' original_file='.$original_file.' entity='.$entity);
  2012. // We define $accessallowed and $sqlprotectagainstexternals
  2013. $accessallowed = 0;
  2014. $sqlprotectagainstexternals = '';
  2015. $ret = array();
  2016. // Find the subdirectory name as the reference. For exemple original_file='10/myfile.pdf' -> refname='10'
  2017. if (empty($refname)) {
  2018. $refname = basename(dirname($original_file)."/");
  2019. }
  2020. // Define possible keys to use for permission check
  2021. $lire = 'lire';
  2022. $read = 'read';
  2023. $download = 'download';
  2024. if ($mode == 'write') {
  2025. $lire = 'creer';
  2026. $read = 'write';
  2027. $download = 'upload';
  2028. }
  2029. // Wrapping for miscellaneous medias files
  2030. if ($modulepart == 'medias' && !empty($dolibarr_main_data_root)) {
  2031. if (empty($entity) || empty($conf->medias->multidir_output[$entity])) {
  2032. return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
  2033. }
  2034. $accessallowed = 1;
  2035. $original_file = $conf->medias->multidir_output[$entity].'/'.$original_file;
  2036. } elseif ($modulepart == 'logs' && !empty($dolibarr_main_data_root)) {
  2037. // Wrapping for *.log files, like when used with url http://.../document.php?modulepart=logs&file=dolibarr.log
  2038. $accessallowed = ($user->admin && basename($original_file) == $original_file && preg_match('/^dolibarr.*\.log$/', basename($original_file)));
  2039. $original_file = $dolibarr_main_data_root.'/'.$original_file;
  2040. } elseif ($modulepart == 'doctemplates' && !empty($dolibarr_main_data_root)) {
  2041. // Wrapping for *.log files, like when used with url http://.../document.php?modulepart=logs&file=dolibarr.log
  2042. $accessallowed = $user->admin;
  2043. $original_file = $dolibarr_main_data_root.'/doctemplates/'.$original_file;
  2044. } elseif ($modulepart == 'doctemplateswebsite' && !empty($dolibarr_main_data_root)) {
  2045. // Wrapping for *.zip files, like when used with url http://.../document.php?modulepart=packages&file=module_myfile.zip
  2046. $accessallowed = ($fuser->rights->website->write && preg_match('/\.jpg$/i', basename($original_file)));
  2047. $original_file = $dolibarr_main_data_root.'/doctemplates/websites/'.$original_file;
  2048. } elseif ($modulepart == 'packages' && !empty($dolibarr_main_data_root)) {
  2049. // Wrapping for *.zip files, like when used with url http://.../document.php?modulepart=packages&file=module_myfile.zip
  2050. // Dir for custom dirs
  2051. $tmp = explode(',', $dolibarr_main_document_root_alt);
  2052. $dirins = $tmp[0];
  2053. $accessallowed = ($user->admin && preg_match('/^module_.*\.zip$/', basename($original_file)));
  2054. $original_file = $dirins.'/'.$original_file;
  2055. } elseif ($modulepart == 'mycompany' && !empty($conf->mycompany->dir_output)) {
  2056. // Wrapping for some images
  2057. $accessallowed = 1;
  2058. $original_file = $conf->mycompany->dir_output.'/'.$original_file;
  2059. } elseif ($modulepart == 'userphoto' && !empty($conf->user->dir_output)) {
  2060. // Wrapping for users photos
  2061. $accessallowed = 1;
  2062. $original_file = $conf->user->dir_output.'/'.$original_file;
  2063. } elseif ($modulepart == 'memberphoto' && !empty($conf->adherent->dir_output)) {
  2064. // Wrapping for members photos
  2065. $accessallowed = 1;
  2066. $original_file = $conf->adherent->dir_output.'/'.$original_file;
  2067. } elseif ($modulepart == 'apercufacture' && !empty($conf->facture->multidir_output[$entity])) {
  2068. // Wrapping pour les apercu factures
  2069. if ($fuser->rights->facture->{$lire}) {
  2070. $accessallowed = 1;
  2071. }
  2072. $original_file = $conf->facture->multidir_output[$entity].'/'.$original_file;
  2073. } elseif ($modulepart == 'apercupropal' && !empty($conf->propal->multidir_output[$entity])) {
  2074. // Wrapping pour les apercu propal
  2075. if ($fuser->rights->propale->{$lire}) {
  2076. $accessallowed = 1;
  2077. }
  2078. $original_file = $conf->propal->multidir_output[$entity].'/'.$original_file;
  2079. } elseif ($modulepart == 'apercucommande' && !empty($conf->commande->multidir_output[$entity])) {
  2080. // Wrapping pour les apercu commande
  2081. if ($fuser->rights->commande->{$lire}) {
  2082. $accessallowed = 1;
  2083. }
  2084. $original_file = $conf->commande->multidir_output[$entity].'/'.$original_file;
  2085. } elseif (($modulepart == 'apercufichinter' || $modulepart == 'apercuficheinter') && !empty($conf->ficheinter->dir_output)) {
  2086. // Wrapping pour les apercu intervention
  2087. if ($fuser->rights->ficheinter->{$lire}) {
  2088. $accessallowed = 1;
  2089. }
  2090. $original_file = $conf->ficheinter->dir_output.'/'.$original_file;
  2091. } elseif (($modulepart == 'apercucontract') && !empty($conf->contrat->multidir_output[$entity])) {
  2092. // Wrapping pour les apercu contrat
  2093. if ($fuser->rights->contrat->{$lire}) {
  2094. $accessallowed = 1;
  2095. }
  2096. $original_file = $conf->contrat->multidir_output[$entity].'/'.$original_file;
  2097. } elseif (($modulepart == 'apercusupplier_proposal' || $modulepart == 'apercusupplier_proposal') && !empty($conf->supplier_proposal->dir_output)) {
  2098. // Wrapping pour les apercu supplier proposal
  2099. if ($fuser->rights->supplier_proposal->{$lire}) {
  2100. $accessallowed = 1;
  2101. }
  2102. $original_file = $conf->supplier_proposal->dir_output.'/'.$original_file;
  2103. } elseif (($modulepart == 'apercusupplier_order' || $modulepart == 'apercusupplier_order') && !empty($conf->fournisseur->commande->dir_output)) {
  2104. // Wrapping pour les apercu supplier order
  2105. if ($fuser->rights->fournisseur->commande->{$lire}) {
  2106. $accessallowed = 1;
  2107. }
  2108. $original_file = $conf->fournisseur->commande->dir_output.'/'.$original_file;
  2109. } elseif (($modulepart == 'apercusupplier_invoice' || $modulepart == 'apercusupplier_invoice') && !empty($conf->fournisseur->facture->dir_output)) {
  2110. // Wrapping pour les apercu supplier invoice
  2111. if ($fuser->rights->fournisseur->facture->{$lire}) {
  2112. $accessallowed = 1;
  2113. }
  2114. $original_file = $conf->fournisseur->facture->dir_output.'/'.$original_file;
  2115. } elseif (($modulepart == 'apercuexpensereport') && !empty($conf->expensereport->dir_output)) {
  2116. // Wrapping pour les apercu supplier invoice
  2117. if ($fuser->rights->expensereport->{$lire}) {
  2118. $accessallowed = 1;
  2119. }
  2120. $original_file = $conf->expensereport->dir_output.'/'.$original_file;
  2121. } elseif ($modulepart == 'propalstats' && !empty($conf->propal->multidir_temp[$entity])) {
  2122. // Wrapping pour les images des stats propales
  2123. if ($fuser->rights->propale->{$lire}) {
  2124. $accessallowed = 1;
  2125. }
  2126. $original_file = $conf->propal->multidir_temp[$entity].'/'.$original_file;
  2127. } elseif ($modulepart == 'orderstats' && !empty($conf->commande->dir_temp)) {
  2128. // Wrapping pour les images des stats commandes
  2129. if ($fuser->rights->commande->{$lire}) {
  2130. $accessallowed = 1;
  2131. }
  2132. $original_file = $conf->commande->dir_temp.'/'.$original_file;
  2133. } elseif ($modulepart == 'orderstatssupplier' && !empty($conf->fournisseur->dir_output)) {
  2134. if ($fuser->rights->fournisseur->commande->{$lire}) {
  2135. $accessallowed = 1;
  2136. }
  2137. $original_file = $conf->fournisseur->commande->dir_temp.'/'.$original_file;
  2138. } elseif ($modulepart == 'billstats' && !empty($conf->facture->dir_temp)) {
  2139. // Wrapping pour les images des stats factures
  2140. if ($fuser->rights->facture->{$lire}) {
  2141. $accessallowed = 1;
  2142. }
  2143. $original_file = $conf->facture->dir_temp.'/'.$original_file;
  2144. } elseif ($modulepart == 'billstatssupplier' && !empty($conf->fournisseur->dir_output)) {
  2145. if ($fuser->rights->fournisseur->facture->{$lire}) {
  2146. $accessallowed = 1;
  2147. }
  2148. $original_file = $conf->fournisseur->facture->dir_temp.'/'.$original_file;
  2149. } elseif ($modulepart == 'expeditionstats' && !empty($conf->expedition->dir_temp)) {
  2150. // Wrapping pour les images des stats expeditions
  2151. if ($fuser->rights->expedition->{$lire}) {
  2152. $accessallowed = 1;
  2153. }
  2154. $original_file = $conf->expedition->dir_temp.'/'.$original_file;
  2155. } elseif ($modulepart == 'tripsexpensesstats' && !empty($conf->deplacement->dir_temp)) {
  2156. // Wrapping pour les images des stats expeditions
  2157. if ($fuser->rights->deplacement->{$lire}) {
  2158. $accessallowed = 1;
  2159. }
  2160. $original_file = $conf->deplacement->dir_temp.'/'.$original_file;
  2161. } elseif ($modulepart == 'memberstats' && !empty($conf->adherent->dir_temp)) {
  2162. // Wrapping pour les images des stats expeditions
  2163. if ($fuser->rights->adherent->{$lire}) {
  2164. $accessallowed = 1;
  2165. }
  2166. $original_file = $conf->adherent->dir_temp.'/'.$original_file;
  2167. } elseif (preg_match('/^productstats_/i', $modulepart) && !empty($conf->product->dir_temp)) {
  2168. // Wrapping pour les images des stats produits
  2169. if ($fuser->rights->produit->{$lire} || $fuser->rights->service->{$lire}) {
  2170. $accessallowed = 1;
  2171. }
  2172. $original_file = (!empty($conf->product->multidir_temp[$entity]) ? $conf->product->multidir_temp[$entity] : $conf->service->multidir_temp[$entity]).'/'.$original_file;
  2173. } elseif (in_array($modulepart, array('tax', 'tax-vat', 'tva')) && !empty($conf->tax->dir_output)) {
  2174. // Wrapping for taxes
  2175. if ($fuser->rights->tax->charges->{$lire}) {
  2176. $accessallowed = 1;
  2177. }
  2178. $modulepartsuffix = str_replace('tax-', '', $modulepart);
  2179. $original_file = $conf->tax->dir_output.'/'.($modulepartsuffix != 'tax' ? $modulepartsuffix.'/' : '').$original_file;
  2180. } elseif ($modulepart == 'actions' && !empty($conf->agenda->dir_output)) {
  2181. // Wrapping for events
  2182. if ($fuser->rights->agenda->myactions->{$read}) {
  2183. $accessallowed = 1;
  2184. // If we known $id of project, call checkUserAccessToObject to check permission on the given agenda event on properties and assigned users
  2185. if ($refname && !preg_match('/^specimen/i', $original_file)) {
  2186. include_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
  2187. $tmpobject = new ActionComm($db);
  2188. $tmpobject->fetch((int) $refname);
  2189. $accessallowed = checkUserAccessToObject($user, array('agenda'), $tmpobject->id, 'actioncomm&societe', 'myactions|allactions', 'fk_soc', 'id', '');
  2190. if ($user->socid && $tmpobject->socid) {
  2191. $accessallowed = checkUserAccessToObject($user, array('societe'), $tmpobject->socid);
  2192. }
  2193. }
  2194. }
  2195. $original_file = $conf->agenda->dir_output.'/'.$original_file;
  2196. } elseif ($modulepart == 'category' && !empty($conf->categorie->multidir_output[$entity])) {
  2197. // Wrapping for categories
  2198. if (empty($entity) || empty($conf->categorie->multidir_output[$entity])) {
  2199. return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
  2200. }
  2201. if ($fuser->rights->categorie->{$lire}) {
  2202. $accessallowed = 1;
  2203. }
  2204. $original_file = $conf->categorie->multidir_output[$entity].'/'.$original_file;
  2205. } elseif ($modulepart == 'prelevement' && !empty($conf->prelevement->dir_output)) {
  2206. // Wrapping pour les prelevements
  2207. if ($fuser->rights->prelevement->bons->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2208. $accessallowed = 1;
  2209. }
  2210. $original_file = $conf->prelevement->dir_output.'/'.$original_file;
  2211. } elseif ($modulepart == 'graph_stock' && !empty($conf->stock->dir_temp)) {
  2212. // Wrapping pour les graph energie
  2213. $accessallowed = 1;
  2214. $original_file = $conf->stock->dir_temp.'/'.$original_file;
  2215. } elseif ($modulepart == 'graph_fourn' && !empty($conf->fournisseur->dir_temp)) {
  2216. // Wrapping pour les graph fournisseurs
  2217. $accessallowed = 1;
  2218. $original_file = $conf->fournisseur->dir_temp.'/'.$original_file;
  2219. } elseif ($modulepart == 'graph_product' && !empty($conf->product->dir_temp)) {
  2220. // Wrapping pour les graph des produits
  2221. $accessallowed = 1;
  2222. $original_file = $conf->product->multidir_temp[$entity].'/'.$original_file;
  2223. } elseif ($modulepart == 'barcode') {
  2224. // Wrapping pour les code barre
  2225. $accessallowed = 1;
  2226. // If viewimage is called for barcode, we try to output an image on the fly, with no build of file on disk.
  2227. //$original_file=$conf->barcode->dir_temp.'/'.$original_file;
  2228. $original_file = '';
  2229. } elseif ($modulepart == 'iconmailing' && !empty($conf->mailing->dir_temp)) {
  2230. // Wrapping pour les icones de background des mailings
  2231. $accessallowed = 1;
  2232. $original_file = $conf->mailing->dir_temp.'/'.$original_file;
  2233. } elseif ($modulepart == 'scanner_user_temp' && !empty($conf->scanner->dir_temp)) {
  2234. // Wrapping pour le scanner
  2235. $accessallowed = 1;
  2236. $original_file = $conf->scanner->dir_temp.'/'.$fuser->id.'/'.$original_file;
  2237. } elseif ($modulepart == 'fckeditor' && !empty($conf->fckeditor->dir_output)) {
  2238. // Wrapping pour les images fckeditor
  2239. $accessallowed = 1;
  2240. $original_file = $conf->fckeditor->dir_output.'/'.$original_file;
  2241. } elseif ($modulepart == 'user' && !empty($conf->user->dir_output)) {
  2242. // Wrapping for users
  2243. $canreaduser = (!empty($fuser->admin) || $fuser->rights->user->user->{$lire});
  2244. if ($fuser->id == (int) $refname) {
  2245. $canreaduser = 1;
  2246. } // A user can always read its own card
  2247. if ($canreaduser || preg_match('/^specimen/i', $original_file)) {
  2248. $accessallowed = 1;
  2249. }
  2250. $original_file = $conf->user->dir_output.'/'.$original_file;
  2251. } elseif (($modulepart == 'company' || $modulepart == 'societe' || $modulepart == 'thirdparty') && !empty($conf->societe->multidir_output[$entity])) {
  2252. // Wrapping for third parties
  2253. if (empty($entity) || empty($conf->societe->multidir_output[$entity])) {
  2254. return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
  2255. }
  2256. if ($fuser->rights->societe->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2257. $accessallowed = 1;
  2258. }
  2259. $original_file = $conf->societe->multidir_output[$entity].'/'.$original_file;
  2260. $sqlprotectagainstexternals = "SELECT rowid as fk_soc FROM ".MAIN_DB_PREFIX."societe WHERE rowid='".$db->escape($refname)."' AND entity IN (".getEntity('societe').")";
  2261. } elseif ($modulepart == 'contact' && !empty($conf->societe->multidir_output[$entity])) {
  2262. // Wrapping for contact
  2263. if (empty($entity) || empty($conf->societe->multidir_output[$entity])) {
  2264. return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
  2265. }
  2266. if ($fuser->rights->societe->{$lire}) {
  2267. $accessallowed = 1;
  2268. }
  2269. $original_file = $conf->societe->multidir_output[$entity].'/contact/'.$original_file;
  2270. } elseif (($modulepart == 'facture' || $modulepart == 'invoice') && !empty($conf->facture->multidir_output[$entity])) {
  2271. // Wrapping for invoices
  2272. if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2273. $accessallowed = 1;
  2274. }
  2275. $original_file = $conf->facture->multidir_output[$entity].'/'.$original_file;
  2276. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."facture WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('invoice').")";
  2277. } elseif ($modulepart == 'massfilesarea_proposals' && !empty($conf->propal->multidir_output[$entity])) {
  2278. // Wrapping for mass actions
  2279. if ($fuser->rights->propal->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2280. $accessallowed = 1;
  2281. }
  2282. $original_file = $conf->propal->multidir_output[$entity].'/temp/massgeneration/'.$user->id.'/'.$original_file;
  2283. } elseif ($modulepart == 'massfilesarea_orders') {
  2284. if ($fuser->rights->commande->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2285. $accessallowed = 1;
  2286. }
  2287. $original_file = $conf->commande->multidir_output[$entity].'/temp/massgeneration/'.$user->id.'/'.$original_file;
  2288. } elseif ($modulepart == 'massfilesarea_sendings') {
  2289. if ($fuser->rights->expedition->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2290. $accessallowed = 1;
  2291. }
  2292. $original_file = $conf->expedition->dir_output.'/sending/temp/massgeneration/'.$user->id.'/'.$original_file;
  2293. } elseif ($modulepart == 'massfilesarea_invoices') {
  2294. if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2295. $accessallowed = 1;
  2296. }
  2297. $original_file = $conf->facture->multidir_output[$entity].'/temp/massgeneration/'.$user->id.'/'.$original_file;
  2298. } elseif ($modulepart == 'massfilesarea_expensereport') {
  2299. if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2300. $accessallowed = 1;
  2301. }
  2302. $original_file = $conf->expensereport->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
  2303. } elseif ($modulepart == 'massfilesarea_interventions') {
  2304. if ($fuser->rights->ficheinter->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2305. $accessallowed = 1;
  2306. }
  2307. $original_file = $conf->ficheinter->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
  2308. } elseif ($modulepart == 'massfilesarea_supplier_proposal' && !empty($conf->supplier_proposal->dir_output)) {
  2309. if ($fuser->rights->supplier_proposal->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2310. $accessallowed = 1;
  2311. }
  2312. $original_file = $conf->supplier_proposal->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
  2313. } elseif ($modulepart == 'massfilesarea_supplier_order') {
  2314. if ($fuser->rights->fournisseur->commande->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2315. $accessallowed = 1;
  2316. }
  2317. $original_file = $conf->fournisseur->commande->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
  2318. } elseif ($modulepart == 'massfilesarea_supplier_invoice') {
  2319. if ($fuser->rights->fournisseur->facture->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2320. $accessallowed = 1;
  2321. }
  2322. $original_file = $conf->fournisseur->facture->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
  2323. } elseif ($modulepart == 'massfilesarea_contract' && !empty($conf->contrat->dir_output)) {
  2324. if ($fuser->rights->contrat->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2325. $accessallowed = 1;
  2326. }
  2327. $original_file = $conf->contrat->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
  2328. } elseif (($modulepart == 'fichinter' || $modulepart == 'ficheinter') && !empty($conf->ficheinter->dir_output)) {
  2329. // Wrapping for interventions
  2330. if ($fuser->rights->ficheinter->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2331. $accessallowed = 1;
  2332. }
  2333. $original_file = $conf->ficheinter->dir_output.'/'.$original_file;
  2334. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."fichinter WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  2335. } elseif ($modulepart == 'deplacement' && !empty($conf->deplacement->dir_output)) {
  2336. // Wrapping pour les deplacements et notes de frais
  2337. if ($fuser->rights->deplacement->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2338. $accessallowed = 1;
  2339. }
  2340. $original_file = $conf->deplacement->dir_output.'/'.$original_file;
  2341. //$sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."fichinter WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  2342. } elseif (($modulepart == 'propal' || $modulepart == 'propale') && !empty($conf->propal->multidir_output[$entity])) {
  2343. // Wrapping pour les propales
  2344. if ($fuser->rights->propale->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2345. $accessallowed = 1;
  2346. }
  2347. $original_file = $conf->propal->multidir_output[$entity].'/'.$original_file;
  2348. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."propal WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('propal').")";
  2349. } elseif (($modulepart == 'commande' || $modulepart == 'order') && !empty($conf->commande->multidir_output[$entity])) {
  2350. // Wrapping pour les commandes
  2351. if ($fuser->rights->commande->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2352. $accessallowed = 1;
  2353. }
  2354. $original_file = $conf->commande->multidir_output[$entity].'/'.$original_file;
  2355. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."commande WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('order').")";
  2356. } elseif ($modulepart == 'project' && !empty($conf->projet->dir_output)) {
  2357. // Wrapping pour les projets
  2358. if ($fuser->rights->projet->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2359. $accessallowed = 1;
  2360. // If we known $id of project, call checkUserAccessToObject to check permission on properties and contact of project
  2361. if ($refname && !preg_match('/^specimen/i', $original_file)) {
  2362. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  2363. $tmpproject = new Project($db);
  2364. $tmpproject->fetch('', $refname);
  2365. $accessallowed = checkUserAccessToObject($user, array('projet'), $tmpproject->id, 'projet&project', '', '', 'rowid', '');
  2366. }
  2367. }
  2368. $original_file = $conf->projet->dir_output.'/'.$original_file;
  2369. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."projet WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('project').")";
  2370. } elseif ($modulepart == 'project_task' && !empty($conf->projet->dir_output)) {
  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/task.class.php';
  2376. $tmptask = new Task($db);
  2377. $tmptask->fetch('', $refname);
  2378. $accessallowed = checkUserAccessToObject($user, array('projet_task'), $tmptask->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 == 'commande_fournisseur' || $modulepart == 'order_supplier') && !empty($conf->fournisseur->commande->dir_output)) {
  2384. // Wrapping pour les commandes fournisseurs
  2385. if ($fuser->rights->fournisseur->commande->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2386. $accessallowed = 1;
  2387. }
  2388. $original_file = $conf->fournisseur->commande->dir_output.'/'.$original_file;
  2389. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."commande_fournisseur WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  2390. } elseif (($modulepart == 'facture_fournisseur' || $modulepart == 'invoice_supplier') && !empty($conf->fournisseur->facture->dir_output)) {
  2391. // Wrapping pour les factures fournisseurs
  2392. if ($fuser->rights->fournisseur->facture->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2393. $accessallowed = 1;
  2394. }
  2395. $original_file = $conf->fournisseur->facture->dir_output.'/'.$original_file;
  2396. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."facture_fourn WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  2397. } elseif ($modulepart == 'supplier_payment') {
  2398. // Wrapping pour les rapport de paiements
  2399. if ($fuser->rights->fournisseur->facture->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2400. $accessallowed = 1;
  2401. }
  2402. $original_file = $conf->fournisseur->payment->dir_output.'/'.$original_file;
  2403. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."paiementfournisseur WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  2404. } elseif ($modulepart == 'facture_paiement' && !empty($conf->facture->dir_output)) {
  2405. // Wrapping pour les rapport de paiements
  2406. if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2407. $accessallowed = 1;
  2408. }
  2409. if ($fuser->societe_id > 0) {
  2410. $original_file = $conf->facture->dir_output.'/payments/private/'.$fuser->id.'/'.$original_file;
  2411. } else {
  2412. $original_file = $conf->facture->dir_output.'/payments/'.$original_file;
  2413. }
  2414. } elseif ($modulepart == 'export_compta' && !empty($conf->accounting->dir_output)) {
  2415. // Wrapping for accounting exports
  2416. if ($fuser->rights->accounting->bind->write || preg_match('/^specimen/i', $original_file)) {
  2417. $accessallowed = 1;
  2418. }
  2419. $original_file = $conf->accounting->dir_output.'/'.$original_file;
  2420. } elseif (($modulepart == 'expedition' || $modulepart == 'shipment') && !empty($conf->expedition->dir_output)) {
  2421. // Wrapping pour les expedition
  2422. if ($fuser->rights->expedition->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2423. $accessallowed = 1;
  2424. }
  2425. $original_file = $conf->expedition->dir_output."/sending/".$original_file;
  2426. } elseif (($modulepart == 'livraison' || $modulepart == 'delivery') && !empty($conf->expedition->dir_output)) {
  2427. // Delivery Note Wrapping
  2428. if ($fuser->rights->expedition->delivery->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2429. $accessallowed = 1;
  2430. }
  2431. $original_file = $conf->expedition->dir_output."/receipt/".$original_file;
  2432. } elseif ($modulepart == 'actions' && !empty($conf->agenda->dir_output)) {
  2433. // Wrapping pour les actions
  2434. if ($fuser->rights->agenda->myactions->{$read} || preg_match('/^specimen/i', $original_file)) {
  2435. $accessallowed = 1;
  2436. }
  2437. $original_file = $conf->agenda->dir_output.'/'.$original_file;
  2438. } elseif ($modulepart == 'actionsreport' && !empty($conf->agenda->dir_temp)) {
  2439. // Wrapping pour les actions
  2440. if ($fuser->rights->agenda->allactions->{$read} || preg_match('/^specimen/i', $original_file)) {
  2441. $accessallowed = 1;
  2442. }
  2443. $original_file = $conf->agenda->dir_temp."/".$original_file;
  2444. } elseif ($modulepart == 'product' || $modulepart == 'produit' || $modulepart == 'service' || $modulepart == 'produit|service') {
  2445. // Wrapping pour les produits et services
  2446. if (empty($entity) || (empty($conf->product->multidir_output[$entity]) && empty($conf->service->multidir_output[$entity]))) {
  2447. return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
  2448. }
  2449. if (($fuser->rights->produit->{$lire} || $fuser->rights->service->{$lire}) || preg_match('/^specimen/i', $original_file)) {
  2450. $accessallowed = 1;
  2451. }
  2452. if (!empty($conf->product->enabled)) {
  2453. $original_file = $conf->product->multidir_output[$entity].'/'.$original_file;
  2454. } elseif (!empty($conf->service->enabled)) {
  2455. $original_file = $conf->service->multidir_output[$entity].'/'.$original_file;
  2456. }
  2457. } elseif ($modulepart == 'product_batch' || $modulepart == 'produitlot') {
  2458. // Wrapping pour les lots produits
  2459. if (empty($entity) || (empty($conf->productbatch->multidir_output[$entity]))) {
  2460. return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
  2461. }
  2462. if (($fuser->rights->produit->{$lire} ) || preg_match('/^specimen/i', $original_file)) {
  2463. $accessallowed = 1;
  2464. }
  2465. if (!empty($conf->productbatch->enabled)) {
  2466. $original_file = $conf->productbatch->multidir_output[$entity].'/'.$original_file;
  2467. }
  2468. } elseif ($modulepart == 'movement' || $modulepart == 'mouvement') {
  2469. // Wrapping for stock movements
  2470. if (empty($entity) || empty($conf->stock->multidir_output[$entity])) {
  2471. return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
  2472. }
  2473. if (($fuser->rights->stock->{$lire} || $fuser->rights->stock->movement->{$lire} || $fuser->rights->stock->mouvement->{$lire}) || preg_match('/^specimen/i', $original_file)) {
  2474. $accessallowed = 1;
  2475. }
  2476. if (!empty($conf->stock->enabled)) {
  2477. $original_file = $conf->stock->multidir_output[$entity].'/movement/'.$original_file;
  2478. }
  2479. } elseif ($modulepart == 'contract' && !empty($conf->contrat->multidir_output[$entity])) {
  2480. // Wrapping pour les contrats
  2481. if ($fuser->rights->contrat->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2482. $accessallowed = 1;
  2483. }
  2484. $original_file = $conf->contrat->multidir_output[$entity].'/'.$original_file;
  2485. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."contrat WHERE ref='".$db->escape($refname)."' AND entity IN (".getEntity('contract').")";
  2486. } elseif ($modulepart == 'donation' && !empty($conf->don->dir_output)) {
  2487. // Wrapping pour les dons
  2488. if ($fuser->rights->don->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2489. $accessallowed = 1;
  2490. }
  2491. $original_file = $conf->don->dir_output.'/'.$original_file;
  2492. } elseif ($modulepart == 'dolresource' && !empty($conf->resource->dir_output)) {
  2493. // Wrapping pour les dons
  2494. if ($fuser->rights->resource->{$read} || preg_match('/^specimen/i', $original_file)) {
  2495. $accessallowed = 1;
  2496. }
  2497. $original_file = $conf->resource->dir_output.'/'.$original_file;
  2498. } elseif ($modulepart == 'remisecheque' && !empty($conf->bank->dir_output)) {
  2499. // Wrapping pour les remises de cheques
  2500. if ($fuser->rights->banque->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2501. $accessallowed = 1;
  2502. }
  2503. $original_file = $conf->bank->dir_output.'/checkdeposits/'.$original_file; // original_file should contains relative path so include the get_exdir result
  2504. } elseif (($modulepart == 'banque' || $modulepart == 'bank') && !empty($conf->bank->dir_output)) {
  2505. // Wrapping for bank
  2506. if ($fuser->rights->banque->{$lire}) {
  2507. $accessallowed = 1;
  2508. }
  2509. $original_file = $conf->bank->dir_output.'/'.$original_file;
  2510. } elseif ($modulepart == 'export' && !empty($conf->export->dir_temp)) {
  2511. // Wrapping for export module
  2512. // Note that a test may not be required because we force the dir of download on the directory of the user that export
  2513. $accessallowed = $user->rights->export->lire;
  2514. $original_file = $conf->export->dir_temp.'/'.$fuser->id.'/'.$original_file;
  2515. } elseif ($modulepart == 'import' && !empty($conf->import->dir_temp)) {
  2516. // Wrapping for import module
  2517. $accessallowed = $user->rights->import->run;
  2518. $original_file = $conf->import->dir_temp.'/'.$original_file;
  2519. } elseif ($modulepart == 'editor' && !empty($conf->fckeditor->dir_output)) {
  2520. // Wrapping for wysiwyg editor
  2521. $accessallowed = 1;
  2522. $original_file = $conf->fckeditor->dir_output.'/'.$original_file;
  2523. } elseif ($modulepart == 'systemtools' && !empty($conf->admin->dir_output)) {
  2524. // Wrapping for backups
  2525. if ($fuser->admin) {
  2526. $accessallowed = 1;
  2527. }
  2528. $original_file = $conf->admin->dir_output.'/'.$original_file;
  2529. } elseif ($modulepart == 'admin_temp' && !empty($conf->admin->dir_temp)) {
  2530. // Wrapping for upload file test
  2531. if ($fuser->admin) {
  2532. $accessallowed = 1;
  2533. }
  2534. $original_file = $conf->admin->dir_temp.'/'.$original_file;
  2535. } elseif ($modulepart == 'bittorrent' && !empty($conf->bittorrent->dir_output)) {
  2536. // Wrapping pour BitTorrent
  2537. $accessallowed = 1;
  2538. $dir = 'files';
  2539. if (dol_mimetype($original_file) == 'application/x-bittorrent') {
  2540. $dir = 'torrents';
  2541. }
  2542. $original_file = $conf->bittorrent->dir_output.'/'.$dir.'/'.$original_file;
  2543. } elseif ($modulepart == 'member' && !empty($conf->adherent->dir_output)) {
  2544. // Wrapping pour Foundation module
  2545. if ($fuser->rights->adherent->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2546. $accessallowed = 1;
  2547. }
  2548. $original_file = $conf->adherent->dir_output.'/'.$original_file;
  2549. } elseif ($modulepart == 'scanner_user_temp' && !empty($conf->scanner->dir_temp)) {
  2550. // Wrapping for Scanner
  2551. $accessallowed = 1;
  2552. $original_file = $conf->scanner->dir_temp.'/'.$fuser->id.'/'.$original_file;
  2553. // If modulepart=module_user_temp Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/temp/iduser
  2554. // If modulepart=module_temp Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/temp
  2555. // If modulepart=module_user Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/iduser
  2556. // If modulepart=module Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart
  2557. // If modulepart=module-abc Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart
  2558. } else {
  2559. // GENERIC Wrapping
  2560. //var_dump($modulepart);
  2561. //var_dump($original_file);
  2562. if (preg_match('/^specimen/i', $original_file)) {
  2563. $accessallowed = 1; // If link to a file called specimen. Test must be done before changing $original_file int full path.
  2564. }
  2565. if ($fuser->admin) {
  2566. $accessallowed = 1; // If user is admin
  2567. }
  2568. $tmpmodulepart = explode('-', $modulepart);
  2569. if (!empty($tmpmodulepart[1])) {
  2570. $modulepart = $tmpmodulepart[0];
  2571. $original_file = $tmpmodulepart[1].'/'.$original_file;
  2572. }
  2573. // Define $accessallowed
  2574. $reg = array();
  2575. if (preg_match('/^([a-z]+)_user_temp$/i', $modulepart, $reg)) {
  2576. if (empty($conf->{$reg[1]}->dir_temp)) { // modulepart not supported
  2577. dol_print_error('', 'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
  2578. exit;
  2579. }
  2580. if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) {
  2581. $accessallowed = 1;
  2582. }
  2583. $original_file = $conf->{$reg[1]}->dir_temp.'/'.$fuser->id.'/'.$original_file;
  2584. } elseif (preg_match('/^([a-z]+)_temp$/i', $modulepart, $reg)) {
  2585. if (empty($conf->{$reg[1]}->dir_temp)) { // modulepart not supported
  2586. dol_print_error('', 'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
  2587. exit;
  2588. }
  2589. if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) {
  2590. $accessallowed = 1;
  2591. }
  2592. $original_file = $conf->{$reg[1]}->dir_temp.'/'.$original_file;
  2593. } elseif (preg_match('/^([a-z]+)_user$/i', $modulepart, $reg)) {
  2594. if (empty($conf->{$reg[1]}->dir_output)) { // modulepart not supported
  2595. dol_print_error('', 'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
  2596. exit;
  2597. }
  2598. if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) {
  2599. $accessallowed = 1;
  2600. }
  2601. $original_file = $conf->{$reg[1]}->dir_output.'/'.$fuser->id.'/'.$original_file;
  2602. } elseif (preg_match('/^massfilesarea_([a-z]+)$/i', $modulepart, $reg)) {
  2603. if (empty($conf->{$reg[1]}->dir_output)) { // modulepart not supported
  2604. dol_print_error('', 'Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
  2605. exit;
  2606. }
  2607. if ($fuser->rights->{$reg[1]}->{$lire} || preg_match('/^specimen/i', $original_file)) {
  2608. $accessallowed = 1;
  2609. }
  2610. $original_file = $conf->{$reg[1]}->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
  2611. } else {
  2612. if (empty($conf->$modulepart->dir_output)) { // modulepart not supported
  2613. 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.');
  2614. exit;
  2615. }
  2616. // Check fuser->rights->modulepart->myobject->read and fuser->rights->modulepart->read
  2617. $partsofdirinoriginalfile = explode('/', $original_file);
  2618. if (!empty($partsofdirinoriginalfile[1])) { // If original_file is xxx/filename (xxx is a part we will use)
  2619. $partofdirinoriginalfile = $partsofdirinoriginalfile[0];
  2620. if ($partofdirinoriginalfile && !empty($fuser->rights->$modulepart->$partofdirinoriginalfile) && ($fuser->rights->$modulepart->$partofdirinoriginalfile->{$lire} || $fuser->rights->$modulepart->$partofdirinoriginalfile->{$read})) {
  2621. $accessallowed = 1;
  2622. }
  2623. }
  2624. if (!empty($fuser->rights->$modulepart->{$lire}) || !empty($fuser->rights->$modulepart->{$read})) {
  2625. $accessallowed = 1;
  2626. }
  2627. if (is_array($conf->$modulepart->multidir_output) && !empty($conf->$modulepart->multidir_output[$entity])) {
  2628. $original_file = $conf->$modulepart->multidir_output[$entity].'/'.$original_file;
  2629. } else {
  2630. $original_file = $conf->$modulepart->dir_output.'/'.$original_file;
  2631. }
  2632. }
  2633. // For modules who wants to manage different levels of permissions for documents
  2634. $subPermCategoryConstName = strtoupper($modulepart).'_SUBPERMCATEGORY_FOR_DOCUMENTS';
  2635. if (!empty($conf->global->$subPermCategoryConstName)) {
  2636. $subPermCategory = $conf->global->$subPermCategoryConstName;
  2637. if (!empty($subPermCategory) && (($fuser->rights->$modulepart->$subPermCategory->{$lire}) || ($fuser->rights->$modulepart->$subPermCategory->{$read}) || ($fuser->rights->$modulepart->$subPermCategory->{$download}))) {
  2638. $accessallowed = 1;
  2639. }
  2640. }
  2641. // Define $sqlprotectagainstexternals for modules who want to protect access using a SQL query.
  2642. $sqlProtectConstName = strtoupper($modulepart).'_SQLPROTECTAGAINSTEXTERNALS_FOR_DOCUMENTS';
  2643. if (!empty($conf->global->$sqlProtectConstName)) { // If module want to define its own $sqlprotectagainstexternals
  2644. // Example: mymodule__SQLPROTECTAGAINSTEXTERNALS_FOR_DOCUMENTS = "SELECT fk_soc FROM ".MAIN_DB_PREFIX.$modulepart." WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  2645. eval('$sqlprotectagainstexternals = "'.$conf->global->$sqlProtectConstName.'";');
  2646. }
  2647. }
  2648. $ret = array(
  2649. 'accessallowed' => $accessallowed,
  2650. 'sqlprotectagainstexternals'=>$sqlprotectagainstexternals,
  2651. 'original_file'=>$original_file
  2652. );
  2653. return $ret;
  2654. }
  2655. /**
  2656. * Store object in file.
  2657. *
  2658. * @param string $directory Directory of cache
  2659. * @param string $filename Name of filecache
  2660. * @param mixed $object Object to store in cachefile
  2661. * @return void
  2662. */
  2663. function dol_filecache($directory, $filename, $object)
  2664. {
  2665. if (!dol_is_dir($directory)) {
  2666. dol_mkdir($directory);
  2667. }
  2668. $cachefile = $directory.$filename;
  2669. file_put_contents($cachefile, serialize($object), LOCK_EX);
  2670. @chmod($cachefile, 0644);
  2671. }
  2672. /**
  2673. * Test if Refresh needed.
  2674. *
  2675. * @param string $directory Directory of cache
  2676. * @param string $filename Name of filecache
  2677. * @param int $cachetime Cachetime delay
  2678. * @return boolean 0 no refresh 1 if refresh needed
  2679. */
  2680. function dol_cache_refresh($directory, $filename, $cachetime)
  2681. {
  2682. $now = dol_now();
  2683. $cachefile = $directory.$filename;
  2684. $refresh = !file_exists($cachefile) || ($now - $cachetime) > dol_filemtime($cachefile);
  2685. return $refresh;
  2686. }
  2687. /**
  2688. * Read object from cachefile.
  2689. *
  2690. * @param string $directory Directory of cache
  2691. * @param string $filename Name of filecache
  2692. * @return mixed Unserialise from file
  2693. */
  2694. function dol_readcachefile($directory, $filename)
  2695. {
  2696. $cachefile = $directory.$filename;
  2697. $object = unserialize(file_get_contents($cachefile));
  2698. return $object;
  2699. }
  2700. /**
  2701. * Function to get list of updated or modified files.
  2702. * $file_list is used as global variable
  2703. *
  2704. * @param array $file_list Array for response
  2705. * @param SimpleXMLElement $dir SimpleXMLElement of files to test
  2706. * @param string $path Path of files relative to $pathref. We start with ''. Used by recursive calls.
  2707. * @param string $pathref Path ref (DOL_DOCUMENT_ROOT)
  2708. * @param array $checksumconcat Array of checksum
  2709. * @return array Array of filenames
  2710. */
  2711. function getFilesUpdated(&$file_list, SimpleXMLElement $dir, $path = '', $pathref = '', &$checksumconcat = array())
  2712. {
  2713. global $conffile;
  2714. $exclude = 'install';
  2715. foreach ($dir->md5file as $file) { // $file is a simpleXMLElement
  2716. $filename = $path.$file['name'];
  2717. $file_list['insignature'][] = $filename;
  2718. $expectedsize = (empty($file['size']) ? '' : $file['size']);
  2719. $expectedmd5 = (string) $file;
  2720. //if (preg_match('#'.$exclude.'#', $filename)) continue;
  2721. if (!file_exists($pathref.'/'.$filename)) {
  2722. $file_list['missing'][] = array('filename'=>$filename, 'expectedmd5'=>$expectedmd5, 'expectedsize'=>$expectedsize);
  2723. } else {
  2724. $md5_local = md5_file($pathref.'/'.$filename);
  2725. 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
  2726. $checksumconcat[] = $expectedmd5;
  2727. } else {
  2728. if ($md5_local != $expectedmd5) {
  2729. $file_list['updated'][] = array('filename'=>$filename, 'expectedmd5'=>$expectedmd5, 'expectedsize'=>$expectedsize, 'md5'=>(string) $md5_local);
  2730. }
  2731. $checksumconcat[] = $md5_local;
  2732. }
  2733. }
  2734. }
  2735. foreach ($dir->dir as $subdir) { // $subdir['name'] is '' or '/accountancy/admin' for example
  2736. getFilesUpdated($file_list, $subdir, $path.$subdir['name'].'/', $pathref, $checksumconcat);
  2737. }
  2738. return $file_list;
  2739. }