files.lib.php 139 KB

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