files.lib.php 127 KB

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