files.lib.php 141 KB

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