files.lib.php 125 KB

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