files.lib.php 141 KB

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