files.lib.php 127 KB

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