files.lib.php 119 KB

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