files.lib.php 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438
  1. <?php
  2. /* Copyright (C) 2008-2012 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2012-2015 Regis Houssin <regis.houssin@capnetworks.com>
  4. * Copyright (C) 2012 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. *
  8. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. * or see http://www.gnu.org/
  21. */
  22. /**
  23. * \file htdocs/core/lib/files.lib.php
  24. * \brief Library for file managing functions
  25. */
  26. /**
  27. * Make a basename working with all page code (default PHP basenamed fails with cyrillic).
  28. * We supose dir separator for input is '/'.
  29. *
  30. * @param string $pathfile String to find basename.
  31. * @return string Basename of input
  32. */
  33. function dol_basename($pathfile)
  34. {
  35. return preg_replace('/^.*\/([^\/]+)$/','$1',rtrim($pathfile,'/'));
  36. }
  37. /**
  38. * Scan a directory and return a list of files/directories.
  39. * Content for string is UTF8 and dir separator is "/".
  40. *
  41. * @param string $path Starting path from which to search
  42. * @param string $types Can be "directories", "files", or "all"
  43. * @param int $recursive Determines whether subdirectories are searched
  44. * @param string $filter Regex filter to restrict list. This regex value must be escaped for '/', since this char is used for preg_match function
  45. * @param array $excludefilter Array of Regex for exclude filter (example: array('(\.meta|_preview\.png)$','^\.'))
  46. * @param string $sortcriteria Sort criteria ("","fullname","name","date","size")
  47. * @param string $sortorder Sort order (SORT_ASC, SORT_DESC)
  48. * @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
  49. * @param int $nohook Disable all hooks
  50. * @return array Array of array('name'=>'xxx','fullname'=>'/abc/xxx','date'=>'yyy','size'=>99,'type'=>'dir|file')
  51. */
  52. function dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter="", $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=false)
  53. {
  54. global $db, $hookmanager;
  55. global $object;
  56. dol_syslog("files.lib.php::dol_dir_list path=".$path." types=".$types." recursive=".$recursive." filter=".$filter." excludefilter=".json_encode($excludefilter));
  57. //print 'xxx'."files.lib.php::dol_dir_list path=".$path." types=".$types." recursive=".$recursive." filter=".$filter." excludefilter=".json_encode($excludefilter);
  58. $loaddate=($mode==1||$mode==2)?true:false;
  59. $loadsize=($mode==1||$mode==3)?true:false;
  60. // Clean parameters
  61. $path=preg_replace('/([\\/]+)$/i','',$path);
  62. $newpath=dol_osencode($path);
  63. if (! $nohook)
  64. {
  65. $hookmanager->initHooks(array('fileslib'));
  66. $parameters=array(
  67. 'path' => $newpath,
  68. 'types'=> $types,
  69. 'recursive' => $recursive,
  70. 'filter' => $filter,
  71. 'excludefilter' => $excludefilter,
  72. 'sortcriteria' => $sortcriteria,
  73. 'sortorder' => $sortorder,
  74. 'loaddate' => $loaddate,
  75. 'loadsize' => $loadsize,
  76. 'mode' => $mode
  77. );
  78. $reshook=$hookmanager->executeHooks('getNodesList', $parameters, $object);
  79. }
  80. // $reshook may contain returns stacked by other modules
  81. // $reshook is always empty with an array for can not lose returns stacked with other modules
  82. // $hookmanager->resArray may contain array stacked by other modules
  83. if (! $nohook && ! empty($hookmanager->resArray)) // forced to use $hookmanager->resArray even if $hookmanager->resArray['nodes'] is empty
  84. {
  85. return $hookmanager->resArray['nodes'];
  86. }
  87. else
  88. {
  89. if (! is_dir($newpath)) return array();
  90. if ($dir = opendir($newpath))
  91. {
  92. $filedate='';
  93. $filesize='';
  94. $file_list = array();
  95. while (false !== ($file = readdir($dir)))
  96. {
  97. if (! utf8_check($file)) $file=utf8_encode($file); // To be sure data is stored in utf8 in memory
  98. $qualified=1;
  99. // Define excludefilterarray
  100. $excludefilterarray=array('^\.');
  101. if (is_array($excludefilter))
  102. {
  103. $excludefilterarray=array_merge($excludefilterarray,$excludefilter);
  104. }
  105. else if ($excludefilter) $excludefilterarray[]=$excludefilter;
  106. // Check if file is qualified
  107. foreach($excludefilterarray as $filt)
  108. {
  109. if (preg_match('/'.$filt.'/i',$file)) {
  110. $qualified=0; break;
  111. }
  112. }
  113. if ($qualified)
  114. {
  115. $isdir=is_dir(dol_osencode($path."/".$file));
  116. // Check whether this is a file or directory and whether we're interested in that type
  117. if ($isdir && (($types=="directories") || ($types=="all") || $recursive))
  118. {
  119. // Add entry into file_list array
  120. if (($types=="directories") || ($types=="all"))
  121. {
  122. if ($loaddate || $sortcriteria == 'date') $filedate=dol_filemtime($path."/".$file);
  123. if ($loadsize || $sortcriteria == 'size') $filesize=dol_filesize($path."/".$file);
  124. if (! $filter || preg_match('/'.$filter.'/i',$file)) // We do not search key $filter into $path, only into $file
  125. {
  126. preg_match('/([^\/]+)\/[^\/]+$/',$path.'/'.$file,$reg);
  127. $level1name=(isset($reg[1])?$reg[1]:'');
  128. $file_list[] = array(
  129. "name" => $file,
  130. "path" => $path,
  131. "level1name" => $level1name,
  132. "fullname" => $path.'/'.$file,
  133. "date" => $filedate,
  134. "size" => $filesize,
  135. "type" => 'dir'
  136. );
  137. }
  138. }
  139. // if we're in a directory and we want recursive behavior, call this function again
  140. if ($recursive)
  141. {
  142. $file_list = array_merge($file_list,dol_dir_list($path."/".$file, $types, $recursive, $filter, $excludefilter, $sortcriteria, $sortorder, $mode, $nohook));
  143. }
  144. }
  145. else if (! $isdir && (($types == "files") || ($types == "all")))
  146. {
  147. // Add file into file_list array
  148. if ($loaddate || $sortcriteria == 'date') $filedate=dol_filemtime($path."/".$file);
  149. if ($loadsize || $sortcriteria == 'size') $filesize=dol_filesize($path."/".$file);
  150. if (! $filter || preg_match('/'.$filter.'/i',$file)) // We do not search key $filter into $path, only into $file
  151. {
  152. preg_match('/([^\/]+)\/[^\/]+$/',$path.'/'.$file,$reg);
  153. $level1name=(isset($reg[1])?$reg[1]:'');
  154. $file_list[] = array(
  155. "name" => $file,
  156. "path" => $path,
  157. "level1name" => $level1name,
  158. "fullname" => $path.'/'.$file,
  159. "date" => $filedate,
  160. "size" => $filesize,
  161. "type" => 'file'
  162. );
  163. }
  164. }
  165. }
  166. }
  167. closedir($dir);
  168. // Obtain a list of columns
  169. if (! empty($sortcriteria))
  170. {
  171. $myarray=array();
  172. foreach ($file_list as $key => $row)
  173. {
  174. $myarray[$key] = (isset($row[$sortcriteria])?$row[$sortcriteria]:'');
  175. }
  176. // Sort the data
  177. if ($sortorder) array_multisort($myarray, $sortorder, $file_list);
  178. }
  179. return $file_list;
  180. }
  181. else
  182. {
  183. return array();
  184. }
  185. }
  186. }
  187. /**
  188. * Scan a directory and return a array of files/directories from a selection.
  189. * Content for string is UTF8 and dir separator is "/".
  190. *
  191. * @param int $fk_soc select socid - for your selection in array
  192. * @param string $module_get Starting path from which to search
  193. * @param string $sortorder SORT_ASC or SORT_DESC
  194. * @param array $excludefiles Array of Regex for exclude filter (example: array('(\.meta|_preview\.png)$','^\.'))
  195. * @return array Array of array( filefolder=> array( filelabel=> array( file=> array('name'=>'xxx','date'=>'yyy','size'=>99,'type'=>'dir|file'))))
  196. */
  197. function get_soc_file_array($fk_soc, $module_get = false, $sortorder = false, $excludefiles = false)
  198. {
  199. global $user, $conf, $db;
  200. $sortfield = "date";
  201. if(!$sortorder){
  202. $sorting = SORT_DESC;
  203. }else{
  204. $sorting = $sortorder;
  205. }
  206. $ar_modules_get = array();
  207. if (is_array($module_get)) $ar_modules_get = $module_get;
  208. elseif (strlen($module_get) > 0) $ar_modules_get[$module_get] = $module_get;
  209. else
  210. {
  211. $ar_modules_get['company'] = 'company';
  212. $ar_modules_get['dolimail'] = 'dolimail';
  213. $ar_modules_get['actions'] = 'actions';
  214. $ar_modules_get['invoice'] = 'invoice';
  215. $ar_modules_get['order'] = 'order';
  216. $ar_modules_get['propal'] = 'propal';
  217. $ar_modules_get['contract'] = 'contract';
  218. $ar_modules_get['project'] = 'project';
  219. $ar_modules_get['invoice_supplier'] = 'invoice_supplier';
  220. $ar_modules_get['order_supplier'] = 'order_supplier';
  221. }
  222. // rights
  223. if (count($ar_modules_get) > 0)
  224. foreach($ar_modules_get as $curmodule)
  225. {
  226. switch($curmodule)
  227. {
  228. case 'company':
  229. if (! empty($conf->societe->enabled)) // Recht Alle oder nur die Vertriebspartneradressen
  230. $ar_modules_secure['company']['outputdir'] = $conf->societe->dir_output;
  231. break;
  232. case 'dolimail':
  233. if (! empty($conf->dolimail->enabled) && ($user->rights->dolimail->read || $user->admin))
  234. $ar_modules_secure[$curmodule]['outputdir']=$conf->dolimail->dir_output.'/attachments';
  235. break;
  236. case 'actions':
  237. if (! empty($conf->agenda->enabled) || ($user->rights->agenda->allactions->read || $user->admin))
  238. $ar_modules_secure[$curmodule]['outputdir']=$conf->agenda->dir_output;
  239. break;
  240. case 'invoice':
  241. if (! empty($conf->facture->enabled) && ($user->rights->facture->lire || $user->admin))
  242. $ar_modules_secure[$curmodule]['outputdir']=$conf->facture->dir_output;
  243. break;
  244. case 'order':
  245. if (!empty($conf->commande->enabled) && ($user->rights->commande->lire || $user->admin))
  246. $ar_modules_secure[$curmodule]['outputdir']=$conf->commande->dir_output;
  247. break;
  248. case 'propal':
  249. if (!empty($conf->propal->enabled) && ($user->rights->propale->lire || $user->admin))
  250. $ar_modules_secure[$curmodule]['outputdir']=$conf->propal->dir_output;
  251. break;
  252. case 'project':
  253. if (! empty($conf->projet->enabled) && ($user->rights->projet->lire || $user->admin))
  254. $ar_modules_secure[$curmodule]['outputdir']=$conf->projet->dir_output;
  255. break;
  256. case 'invoice_supplier':
  257. if (! empty($conf->fournisseur->enabled) && ($user->rights->fournisseur->facture->lire || $user->admin))
  258. $ar_modules_secure[$curmodule]['outputdir']=$conf->fournisseur->dir_output.'/facture';
  259. break;
  260. case 'order_supplier':
  261. if (! empty($conf->fournisseur->enabled) && ($user->rights->fournisseur->commande->lire || $user->admin))
  262. $ar_modules_secure[$curmodule]['outputdir']=$conf->fournisseur->dir_output.'/commande';
  263. break;
  264. }
  265. }
  266. /* TODO make a outputdir*/
  267. //unset($ar_modules_secure['dolimail']);
  268. unset($ar_modules_secure['project']); // project (list with project) is "ref"
  269. unset($ar_modules_secure['actions']);
  270. unset($ar_modules_secure['contract']);
  271. /* TODO make a outputdir*/
  272. unset($curmodule);
  273. if($fk_soc > 0)
  274. $ar_modules_get = $ar_modules_secure;
  275. $xy=0;
  276. if (count($ar_modules_get)>0)
  277. foreach($ar_modules_get as $curmodule => $myarray)
  278. {
  279. if($fk_soc > 0 && $curmodule != "company")
  280. {
  281. // SQL to find documents (ref number)
  282. if($curmodule == "invoice") $sql = "SELECT facnumber as refstr FROM ".MAIN_DB_PREFIX."facture";
  283. elseif($curmodule == "order") $sql = "SELECT ref as refstr FROM ".MAIN_DB_PREFIX."commande";
  284. elseif($curmodule == "invoice_supplier") $sql = "SELECT rowid as refstr FROM ".MAIN_DB_PREFIX."facture_fourn";
  285. elseif($curmodule == "order_supplier") $sql = "SELECT ref as refstr FROM ".MAIN_DB_PREFIX."commande_fournisseur";
  286. elseif($curmodule == "propal") $sql = "SELECT ref as refstr FROM ".MAIN_DB_PREFIX."propal";
  287. elseif($curmodule == "contract") $sql = "SELECT ref as refstr FROM ".MAIN_DB_PREFIX."contrat";
  288. elseif($curmodule == "dolimail") $sql = "SELECT uid as refstr, subject FROM ".MAIN_DB_PREFIX."mails";
  289. $sql.= ' WHERE entity IN ('.getEntity('societe', 1).')';
  290. $sql.= " AND fk_soc = '".$fk_soc."'";
  291. $res = $db->query($sql);
  292. if ($res && $db->num_rows($res) > 0)
  293. {
  294. while($obj = $db->fetch_object($res))
  295. {
  296. $ar_modules_secure[$curmodule]['socref'][] = $obj->refstr;
  297. if($curmodule == "dolimail") $ar_modules_secure['dolimail']['subject'][$obj->refstr] = $obj->subject;
  298. }
  299. }
  300. else
  301. {
  302. unset($ar_modules_secure[$curmodule]);
  303. continue;
  304. $errors[]="SQL Error: ".$sql;
  305. $error++;
  306. }
  307. }else{
  308. if($curmodule == "dolimail") $sql = "SELECT uid as refstr, subject FROM ".MAIN_DB_PREFIX."mails";
  309. $res = $db->query($sql);
  310. if ($res && $db->num_rows($res) > 0)
  311. {
  312. while($obj = $db->fetch_object($res))
  313. {
  314. if($curmodule == "dolimail") $ar_modules_secure['dolimail']['subject'][$obj->refstr] = $obj->subject;
  315. }
  316. }
  317. }
  318. // Data in Array
  319. // Get Array from ar_module
  320. $output[$curmodule]=dol_dir_list($myarray['outputdir'],"files",1,'', $excludefiles, $sortfield, $sorting,1);
  321. if($fk_soc > 0)
  322. {
  323. if($curmodule == "company")
  324. {
  325. foreach($output["company"] as $label => $filedata)
  326. {
  327. if($filedata['level1name'] != $fk_soc)
  328. {
  329. unset($output['company'][$label]);
  330. }
  331. }
  332. }
  333. elseif($curmodule == "invoice")
  334. {
  335. if (! is_array($ar_modules_secure[$curmodule]['socref'])) { unset($output[$curmodule]); continue; } // wenn no file exsit
  336. foreach($output["invoice"] as $label => $filedata)
  337. {
  338. if (! in_array($filedata['level1name'], $ar_modules_secure[$curmodule]['socref']))
  339. {
  340. unset($output[$curmodule][$label]); // throw all ref number who are not in ($fac_supp_N_arr) array
  341. }
  342. }
  343. }
  344. elseif($curmodule == "invoice_supplier")
  345. {
  346. if (! is_array($ar_modules_secure[$curmodule]['socref'])) { unset($output[$curmodule]); } // throw all ref number who are not in ($fac_invoice_arr) array
  347. foreach($output["invoice_supplier"] as $label => $filedata)
  348. {
  349. if (! in_array($filedata['level1name'], $ar_modules_secure[$curmodule]['socref'])) {
  350. unset($output[$curmodule][$label]); // throw all ref number who are not in ($fac_supp_N_arr) array
  351. }
  352. }
  353. }
  354. elseif($curmodule == "order")
  355. {
  356. if (! is_array($ar_modules_secure[$curmodule]['socref'])) { unset($output[$curmodule]); continue; } // throw all ref number who are not in ($fac_invoice_arr) array
  357. foreach($output["order"] as $label => $filedata)
  358. {
  359. if (! in_array($filedata['level1name'], $ar_modules_secure[$curmodule]['socref'])) {
  360. unset($output[$curmodule][$label]); // throw all ref number who are not in ($ref_order_arr) array
  361. }
  362. }
  363. }
  364. elseif($curmodule == "order_supplier")
  365. {
  366. if (! is_array($ar_modules_secure[$curmodule]['socref'])) { unset($output[$curmodule]); continue; } // throw all ref number who are not in ($fac_invoice_arr) array
  367. foreach($output["order_supplier"] as $label => $filedata)
  368. {
  369. if (! in_array($filedata['level1name'], $ar_modules_secure[$curmodule]['socref'])) {
  370. unset($output[$curmodule][$label]); // throw all ref number who are not in ($ref_order_supp_arr) array
  371. }
  372. }
  373. }
  374. elseif($curmodule == "propal")
  375. {
  376. if (! is_array($ar_modules_secure[$curmodule]['socref'])) { unset($output[$curmodule]); continue; } // throw all ref number who are not in ($fac_invoice_arr) array
  377. foreach($output["propal"] as $label => $filedata)
  378. {
  379. if (! in_array($filedata['level1name'], $ar_modules_secure[$curmodule]['socref'])) {
  380. unset($output[$curmodule][$label]); // throw all ref number who are not in ($ref_propal_arr) array
  381. }
  382. }
  383. }
  384. elseif($curmodule == "contract")
  385. {
  386. if (! is_array($ar_modules_secure[$curmodule]['socref'])) { unset($output[$curmodule]); continue; } // throw all ref number who are not in ($fac_invoice_arr) array
  387. foreach($output["contract"] as $label => $filedata)
  388. {
  389. if (! in_array($filedata['level1name'], $ar_modules_secure[$curmodule]['socref'])) {
  390. unset($output[$curmodule][$label]); // throw all ref number who are not in ($ref_contract_arr) array
  391. }
  392. }
  393. }
  394. elseif($curmodule == "dolimail")
  395. {
  396. if (! is_array($ar_modules_secure[$curmodule]['socref'])) { unset($output[$curmodule]); continue; } // throw all ref number who are not in ($fac_invoice_arr) array
  397. foreach($output["dolimail"] as $label => $filedata)
  398. {
  399. if($filedata['name'] == "winmail.dat" || $filedata['name'] == "smime.p7s") unset($output[$curmodule][$label]);
  400. else
  401. if (! in_array($filedata['level1name'], $ar_modules_secure[$curmodule]['socref'])) {
  402. unset($output[$curmodule][$label]); // throw all ref number who are not in ($ref_propal_arr) array
  403. }
  404. }
  405. }
  406. // Error if ther isn't any File
  407. if(count($output[$curmodule]) == 0)
  408. {
  409. $error++;
  410. $errors[]="Error [404]: No File found for User: ".$fk_soc." in module: ".$curmodule;
  411. unset($output[$curmodule]);
  412. }
  413. }
  414. // Extra for Mail attachments
  415. if($curmodule == "dolimail" && count($output["dolimail"])>0)
  416. {
  417. foreach($output["dolimail"] as $label => $filedata)
  418. {
  419. $output[$curmodule][$label]['subject'] = $ar_modules_secure['dolimail']['subject'][$filedata['level1name']];
  420. }
  421. }
  422. // Extra for Mail attachments
  423. if($curmodule == "invoice" && count($output["invoice"])>0)
  424. {
  425. foreach($output["invoice"] as $label => $filedata)
  426. {
  427. $output[$curmodule][$label]['subject'] = $filedata['level1name'];
  428. }
  429. }
  430. // Extra for Mail attachments
  431. if($curmodule == "invoice_supplier" && count($output["invoice_supplier"])>0)
  432. {
  433. foreach($output["invoice_supplier"] as $label => $filedata)
  434. {
  435. $output[$curmodule][$label]['subject'] = $filedata['level1name'];
  436. }
  437. }
  438. // Extra for Mail attachments
  439. if($curmodule == "contract" && count($output["contract"])>0)
  440. {
  441. foreach($output["contract"] as $label => $filedata)
  442. {
  443. $output[$curmodule][$label]['subject'] = $filedata['level1name'];
  444. }
  445. }
  446. $xy++;
  447. }
  448. if(count($output) > 0)
  449. {
  450. return $output;
  451. }
  452. else
  453. {
  454. return -1;
  455. }
  456. }
  457. /**
  458. * Calculate Bytes to kb, mb and translate it to current language
  459. *
  460. * @param int $byt Bytes
  461. * @return string calculated string
  462. */
  463. function calculate_byte($byt)
  464. {
  465. global $langs;
  466. if ($byt < 1024) {
  467. $unit = '&nbsp;'.$langs->trans("b");
  468. $mailsize=$byt;
  469. } else if ($byt / 1024 > 1024) {
  470. $mailsize = $byt / 1024 / 1024;
  471. $unit = '&nbsp;'.$langs->trans("Mb");
  472. } else {
  473. $mailsize = $byt / 1024;
  474. $unit = '&nbsp;'.$langs->trans("Kb");
  475. }
  476. $val = number_format($mailsize, 2).$unit;
  477. return $val;
  478. }
  479. /**
  480. * Fast compare of 2 files identified by their properties ->name, ->date and ->size
  481. *
  482. * @param string $a File 1
  483. * @param string $b File 2
  484. * @return int 1, 0, 1
  485. */
  486. function dol_compare_file($a, $b)
  487. {
  488. global $sortorder;
  489. global $sortfield;
  490. $sortorder=strtoupper($sortorder);
  491. if ($sortorder == 'ASC') { $retup=-1; $retdown=1; }
  492. else { $retup=1; $retdown=-1; }
  493. if ($sortfield == 'name')
  494. {
  495. if ($a->name == $b->name) return 0;
  496. return ($a->name < $b->name) ? $retup : $retdown;
  497. }
  498. if ($sortfield == 'date')
  499. {
  500. if ($a->date == $b->date) return 0;
  501. return ($a->date < $b->date) ? $retup : $retdown;
  502. }
  503. if ($sortfield == 'size')
  504. {
  505. if ($a->size == $b->size) return 0;
  506. return ($a->size < $b->size) ? $retup : $retdown;
  507. }
  508. }
  509. /**
  510. * Return mime type of a file
  511. *
  512. * @param string $file Filename we looking for MIME type
  513. * @param string $default Default mime type if extension not found in known list
  514. * @param int $mode 0=Return full mime, 1=otherwise short mime string, 2=image for mime type, 3=source language
  515. * @return string Return a mime type family (text/xxx, application/xxx, image/xxx, audio, video, archive)
  516. * @see image_format_supported (images.lib.php)
  517. */
  518. function dol_mimetype($file,$default='application/octet-stream',$mode=0)
  519. {
  520. $mime=$default;
  521. $imgmime='other.png';
  522. $srclang='';
  523. $tmpfile=preg_replace('/\.noexe$/','',$file);
  524. // Text files
  525. if (preg_match('/\.txt$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; }
  526. if (preg_match('/\.rtx$/i',$tmpfile)) { $mime='text/richtext'; $imgmime='text.png'; }
  527. if (preg_match('/\.csv$/i',$tmpfile)) { $mime='text/csv'; $imgmime='text.png'; }
  528. if (preg_match('/\.tsv$/i',$tmpfile)) { $mime='text/tab-separated-values'; $imgmime='text.png'; }
  529. if (preg_match('/\.(cf|conf|log)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; }
  530. if (preg_match('/\.ini$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='ini'; }
  531. if (preg_match('/\.css$/i',$tmpfile)) { $mime='text/css'; $imgmime='css.png'; $srclang='css'; }
  532. // Certificate files
  533. if (preg_match('/\.(crt|cer|key|pub)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; }
  534. // HTML/XML
  535. if (preg_match('/\.(html|htm|shtml)$/i',$tmpfile)) { $mime='text/html'; $imgmime='html.png'; $srclang='html'; }
  536. if (preg_match('/\.(xml|xhtml)$/i',$tmpfile)) { $mime='text/xml'; $imgmime='other.png'; $srclang='xml'; }
  537. // Languages
  538. if (preg_match('/\.bas$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='bas'; }
  539. if (preg_match('/\.(c)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='c'; }
  540. if (preg_match('/\.(cpp)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='cpp'; }
  541. if (preg_match('/\.(h)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='h'; }
  542. if (preg_match('/\.(java|jsp)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='java'; }
  543. if (preg_match('/\.php([0-9]{1})?$/i',$tmpfile)) { $mime='text/plain'; $imgmime='php.png'; $srclang='php'; }
  544. if (preg_match('/\.phtml$/i',$tmpfile)) { $mime='text/plain'; $imgmime='php.png'; $srclang='php'; }
  545. if (preg_match('/\.(pl|pm)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='pl.png'; $srclang='perl'; }
  546. if (preg_match('/\.sql$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='sql'; }
  547. if (preg_match('/\.js$/i',$tmpfile)) { $mime='text/x-javascript'; $imgmime='jscript.png'; $srclang='js'; }
  548. // Open office
  549. if (preg_match('/\.odp$/i',$tmpfile)) { $mime='application/vnd.oasis.opendocument.presentation'; $imgmime='ooffice.png'; }
  550. if (preg_match('/\.ods$/i',$tmpfile)) { $mime='application/vnd.oasis.opendocument.spreadsheet'; $imgmime='ooffice.png'; }
  551. if (preg_match('/\.odt$/i',$tmpfile)) { $mime='application/vnd.oasis.opendocument.text'; $imgmime='ooffice.png'; }
  552. // MS Office
  553. if (preg_match('/\.mdb$/i',$tmpfile)) { $mime='application/msaccess'; $imgmime='mdb.png'; }
  554. if (preg_match('/\.doc(x|m)?$/i',$tmpfile)) { $mime='application/msword'; $imgmime='doc.png'; }
  555. if (preg_match('/\.dot(x|m)?$/i',$tmpfile)) { $mime='application/msword'; $imgmime='doc.png'; }
  556. if (preg_match('/\.xlt(x)?$/i',$tmpfile)) { $mime='application/vnd.ms-excel'; $imgmime='xls.png'; }
  557. if (preg_match('/\.xla(m)?$/i',$tmpfile)) { $mime='application/vnd.ms-excel'; $imgmime='xls.png'; }
  558. if (preg_match('/\.xls$/i',$tmpfile)) { $mime='application/vnd.ms-excel'; $imgmime='xls.png'; }
  559. if (preg_match('/\.xls(b|m|x)$/i',$tmpfile)) { $mime='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; $imgmime='xls.png'; }
  560. if (preg_match('/\.pps(m|x)?$/i',$tmpfile)) { $mime='application/vnd.ms-powerpoint'; $imgmime='ppt.png'; }
  561. if (preg_match('/\.ppt(m|x)?$/i',$tmpfile)) { $mime='application/x-mspowerpoint'; $imgmime='ppt.png'; }
  562. // Other
  563. if (preg_match('/\.pdf$/i',$tmpfile)) { $mime='application/pdf'; $imgmime='pdf.png'; }
  564. // Scripts
  565. if (preg_match('/\.bat$/i',$tmpfile)) { $mime='text/x-bat'; $imgmime='script.png'; $srclang='dos'; }
  566. if (preg_match('/\.sh$/i',$tmpfile)) { $mime='text/x-sh'; $imgmime='script.png'; $srclang='bash'; }
  567. if (preg_match('/\.ksh$/i',$tmpfile)) { $mime='text/x-ksh'; $imgmime='script.png'; $srclang='bash'; }
  568. if (preg_match('/\.bash$/i',$tmpfile)) { $mime='text/x-bash'; $imgmime='script.png'; $srclang='bash'; }
  569. // Images
  570. if (preg_match('/\.ico$/i',$tmpfile)) { $mime='image/x-icon'; $imgmime='image.png'; }
  571. if (preg_match('/\.(jpg|jpeg)$/i',$tmpfile)) { $mime='image/jpeg'; $imgmime='image.png'; }
  572. if (preg_match('/\.png$/i',$tmpfile)) { $mime='image/png'; $imgmime='image.png'; }
  573. if (preg_match('/\.gif$/i',$tmpfile)) { $mime='image/gif'; $imgmime='image.png'; }
  574. if (preg_match('/\.bmp$/i',$tmpfile)) { $mime='image/bmp'; $imgmime='image.png'; }
  575. if (preg_match('/\.(tif|tiff)$/i',$tmpfile)) { $mime='image/tiff'; $imgmime='image.png'; }
  576. // Calendar
  577. if (preg_match('/\.vcs$/i',$tmpfile)) { $mime='text/calendar'; $imgmime='other.png'; }
  578. if (preg_match('/\.ics$/i',$tmpfile)) { $mime='text/calendar'; $imgmime='other.png'; }
  579. // Other
  580. if (preg_match('/\.torrent$/i',$tmpfile)) { $mime='application/x-bittorrent'; $imgmime='other.png'; }
  581. // Audio
  582. if (preg_match('/\.(mp3|ogg|au|wav|wma|mid)$/i',$tmpfile)) { $mime='audio'; $imgmime='audio.png'; }
  583. // Video
  584. if (preg_match('/\.ogv$/i',$tmpfile)) { $mime='video/ogg'; $imgmime='video.png'; }
  585. if (preg_match('/\.webm$/i',$tmpfile)) { $mime='video/webm'; $imgmime='video.png'; }
  586. if (preg_match('/\.avi$/i',$tmpfile)) { $mime='video/x-msvideo'; $imgmime='video.png'; }
  587. if (preg_match('/\.divx$/i',$tmpfile)) { $mime='video/divx'; $imgmime='video.png'; }
  588. if (preg_match('/\.xvid$/i',$tmpfile)) { $mime='video/xvid'; $imgmime='video.png'; }
  589. if (preg_match('/\.(wmv|mpg|mpeg)$/i',$tmpfile)) { $mime='video'; $imgmime='video.png'; }
  590. // Archive
  591. if (preg_match('/\.(zip|rar|gz|tgz|z|cab|bz2|7z|tar|lzh)$/i',$tmpfile)) { $mime='archive'; $imgmime='archive.png'; } // application/xxx where zzz is zip, ...
  592. // Exe
  593. if (preg_match('/\.(exe|com)$/i',$tmpfile)) { $mime='application/octet-stream'; $imgmime='other.png'; }
  594. // Lib
  595. if (preg_match('/\.(dll|lib|o|so|a)$/i',$tmpfile)) { $mime='library'; $imgmime='library.png'; }
  596. // Err
  597. if (preg_match('/\.err$/i',$tmpfile)) { $mime='error'; $imgmime='error.png'; }
  598. // Return string
  599. if ($mode == 1)
  600. {
  601. $tmp=explode('/',$mime);
  602. return (! empty($tmp[1])?$tmp[1]:$tmp[0]);
  603. }
  604. if ($mode == 2)
  605. {
  606. return $imgmime;
  607. }
  608. if ($mode == 3)
  609. {
  610. return $srclang;
  611. }
  612. return $mime;
  613. }
  614. /**
  615. * Test if filename is a directory
  616. *
  617. * @param string $folder Name of folder
  618. * @return boolean True if it's a directory, False if not found
  619. */
  620. function dol_is_dir($folder)
  621. {
  622. $newfolder=dol_osencode($folder);
  623. if (is_dir($newfolder)) return true;
  624. else return false;
  625. }
  626. /**
  627. * Return if path is a file
  628. *
  629. * @param string $pathoffile Path of file
  630. * @return boolean True or false
  631. */
  632. function dol_is_file($pathoffile)
  633. {
  634. $newpathoffile=dol_osencode($pathoffile);
  635. return is_file($newpathoffile);
  636. }
  637. /**
  638. * Return if path is an URL
  639. *
  640. * @param string $url Url
  641. * @return boolean True or false
  642. */
  643. function dol_is_url($url)
  644. {
  645. $tmpprot=array('file','http','https','ftp','zlib','data','ssh','ssh2','ogg','expect');
  646. foreach($tmpprot as $prot)
  647. {
  648. if (preg_match('/^'.$prot.':/i',$url)) return true;
  649. }
  650. return false;
  651. }
  652. /**
  653. * Test if a folder is empty
  654. *
  655. * @param string $folder Name of folder
  656. * @return boolean True if dir is empty or non-existing, False if it contains files
  657. */
  658. function dol_dir_is_emtpy($folder)
  659. {
  660. $newfolder=dol_osencode($folder);
  661. if (is_dir($newfolder))
  662. {
  663. $handle = opendir($newfolder);
  664. $folder_content = '';
  665. while ((gettype($name = readdir($handle)) != "boolean"))
  666. {
  667. $name_array[] = $name;
  668. }
  669. foreach($name_array as $temp) $folder_content .= $temp;
  670. closedir($handle);
  671. if ($folder_content == "...") return true;
  672. else return false;
  673. }
  674. else
  675. return true; // Dir does not exists
  676. }
  677. /**
  678. * Count number of lines in a file
  679. *
  680. * @param string $file Filename
  681. * @return int <0 if KO, Number of lines in files if OK
  682. */
  683. function dol_count_nb_of_line($file)
  684. {
  685. $nb=0;
  686. $newfile=dol_osencode($file);
  687. //print 'x'.$file;
  688. $fp=fopen($newfile,'r');
  689. if ($fp)
  690. {
  691. while (!feof($fp))
  692. {
  693. $line=fgets($fp);
  694. // 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.
  695. if (! $line === false) $nb++;
  696. }
  697. fclose($fp);
  698. }
  699. else
  700. {
  701. $nb=-1;
  702. }
  703. return $nb;
  704. }
  705. /**
  706. * Return size of a file
  707. *
  708. * @param string $pathoffile Path of file
  709. * @return integer File size
  710. */
  711. function dol_filesize($pathoffile)
  712. {
  713. $newpathoffile=dol_osencode($pathoffile);
  714. return filesize($newpathoffile);
  715. }
  716. /**
  717. * Return time of a file
  718. *
  719. * @param string $pathoffile Path of file
  720. * @return int Time of file
  721. */
  722. function dol_filemtime($pathoffile)
  723. {
  724. $newpathoffile=dol_osencode($pathoffile);
  725. return @filemtime($newpathoffile); // @Is to avoid errors if files does not exists
  726. }
  727. /**
  728. * Copy a file to another file.
  729. *
  730. * @param string $srcfile Source file (can't be a directory)
  731. * @param string $destfile Destination file (can't be a directory)
  732. * @param int $newmask Mask for new file (0 by default means $conf->global->MAIN_UMASK). Example: '0666'
  733. * @param int $overwriteifexists Overwrite file if exists (1 by default)
  734. * @return int <0 if error, 0 if nothing done (dest file already exists and overwriteifexists=0), >0 if OK
  735. * @see dolCopyr
  736. */
  737. function dol_copy($srcfile, $destfile, $newmask=0, $overwriteifexists=1)
  738. {
  739. global $conf;
  740. dol_syslog("files.lib.php::dol_copy srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." overwriteifexists=".$overwriteifexists);
  741. if (empty($srcfile) || empty($destfile)) return -1;
  742. $destexists=dol_is_file($destfile);
  743. if (! $overwriteifexists && $destexists) return 0;
  744. $newpathofsrcfile=dol_osencode($srcfile);
  745. $newpathofdestfile=dol_osencode($destfile);
  746. $newdirdestfile=dirname($newpathofdestfile);
  747. if ($destexists && ! is_writable($newpathofdestfile))
  748. {
  749. dol_syslog("files.lib.php::dol_copy failed Permission denied to overwrite target file", LOG_WARNING);
  750. return -1;
  751. }
  752. if (! is_writable($newdirdestfile))
  753. {
  754. dol_syslog("files.lib.php::dol_copy failed Permission denied to write into target directory ".$newdirdestfile, LOG_WARNING);
  755. return -2;
  756. }
  757. // Copy with overwriting if exists
  758. $result=@copy($newpathofsrcfile, $newpathofdestfile);
  759. //$result=copy($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @
  760. if (! $result)
  761. {
  762. dol_syslog("files.lib.php::dol_copy failed to copy", LOG_WARNING);
  763. return -3;
  764. }
  765. if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
  766. if (empty($newmask)) // This should no happen
  767. {
  768. dol_syslog("Warning: dol_copy called with empty value for newmask and no default value defined", LOG_WARNING);
  769. $newmask='0664';
  770. }
  771. @chmod($newpathofdestfile, octdec($newmask));
  772. return 1;
  773. }
  774. /**
  775. * Copy a dir to another dir.
  776. *
  777. * @param string $srcfile Source file (a directory)
  778. * @param string $destfile Destination file (a directory)
  779. * @param int $newmask Mask for new file (0 by default means $conf->global->MAIN_UMASK). Example: '0666'
  780. * @param int $overwriteifexists Overwrite file if exists (1 by default)
  781. * @return int <0 if error, 0 if nothing done (dest dir already exists and overwriteifexists=0), >0 if OK
  782. * @see dol_copy
  783. */
  784. function dolCopyDir($srcfile, $destfile, $newmask, $overwriteifexists)
  785. {
  786. global $conf;
  787. $result=0;
  788. dol_syslog("files.lib.php::dolCopyDir srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." overwriteifexists=".$overwriteifexists);
  789. if (empty($srcfile) || empty($destfile)) return -1;
  790. $destexists=dol_is_dir($destfile);
  791. if (! $overwriteifexists && $destexists) return 0;
  792. if (! $destexists)
  793. {
  794. // We must set mask just before creating dir, becaause it can be set differently by dol_copy
  795. umask(0);
  796. $dirmaskdec=octdec($newmask);
  797. if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $dirmaskdec=octdec($conf->global->MAIN_UMASK);
  798. $dirmaskdec |= octdec('0200'); // Set w bit required to be able to create content for recursive subdirs files
  799. dol_mkdir($destfile."/".$file, '', decoct($dirmaskdec));
  800. }
  801. $srcfile=dol_osencode($srcfile);
  802. $destfile=dol_osencode($destfile);
  803. // recursive function to copy
  804. // all subdirectories and contents:
  805. if (is_dir($srcfile))
  806. {
  807. $dir_handle=opendir($srcfile);
  808. while ($file=readdir($dir_handle))
  809. {
  810. if ($file!="." && $file!="..")
  811. {
  812. if (is_dir($srcfile."/".$file))
  813. {
  814. if (!is_dir($destfile."/".$file))
  815. {
  816. // We must set mask just before creating dir, becaause it can be set differently by dol_copy
  817. umask(0);
  818. $dirmaskdec=octdec($newmask);
  819. if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $dirmaskdec=octdec($conf->global->MAIN_UMASK);
  820. $dirmaskdec |= octdec('0200'); // Set w bit required to be able to create content for recursive subdirs files
  821. dol_mkdir($destfile."/".$file, '', decoct($dirmaskdec));
  822. }
  823. $result=dolCopyDir($srcfile."/".$file, $destfile."/".$file, $newmask, $overwriteifexists);
  824. }
  825. else
  826. {
  827. $result=dol_copy($srcfile."/".$file, $destfile."/".$file, $newmask, $overwriteifexists);
  828. }
  829. if ($result < 0) break;
  830. }
  831. }
  832. closedir($dir_handle);
  833. }
  834. else
  835. {
  836. $result=dol_copy($srcfile, $destfile, $newmask, $overwriteifexists);
  837. }
  838. return $result;
  839. }
  840. /**
  841. * Move a file into another name.
  842. * This function differs from dol_move_uploaded_file, because it can be called in any context.
  843. *
  844. * @param string $srcfile Source file (can't be a directory. use native php @rename() to move a directory)
  845. * @param string $destfile Destination file (can't be a directory. use native php @rename() to move a directory)
  846. * @param integer $newmask Mask in octal string for new file (0 by default means $conf->global->MAIN_UMASK)
  847. * @param int $overwriteifexists Overwrite file if exists (1 by default)
  848. * @return boolean True if OK, false if KO
  849. */
  850. function dol_move($srcfile, $destfile, $newmask=0, $overwriteifexists=1)
  851. {
  852. global $conf;
  853. $result=false;
  854. dol_syslog("files.lib.php::dol_move srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." overwritifexists=".$overwriteifexists);
  855. $destexists=dol_is_file($destfile);
  856. if ($overwriteifexists || ! $destexists)
  857. {
  858. $newpathofsrcfile=dol_osencode($srcfile);
  859. $newpathofdestfile=dol_osencode($destfile);
  860. $result=@rename($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @
  861. if (! $result)
  862. {
  863. if ($destexists)
  864. {
  865. dol_syslog("files.lib.php::dol_move failed. We try to delete first and move after.", LOG_WARNING);
  866. // We force delete and try again. Rename function sometimes fails to replace dest file with some windows NTFS partitions.
  867. dol_delete_file($destfile);
  868. $result=@rename($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @
  869. }
  870. else dol_syslog("files.lib.php::dol_move failed", LOG_WARNING);
  871. }
  872. if (empty($newmask)) $newmask=empty($conf->global->MAIN_UMASK)?'0755':$conf->global->MAIN_UMASK;
  873. $newmaskdec=octdec($newmask);
  874. // Currently method is restricted to files (dol_delete_files previously used is for files, and mask usage if for files too)
  875. // to allow mask usage for dir, we shoul introduce a new param "isdir" to 1 to complete newmask like this
  876. // if ($isdir) $newmaskdec |= octdec('0111'); // Set x bit required for directories
  877. @chmod($newpathofdestfile, $newmaskdec);
  878. }
  879. return $result;
  880. }
  881. /**
  882. * Unescape a file submitted by upload.
  883. * PHP escape char " (%22) or char ' (%27) into $FILES.
  884. *
  885. * @param string $filename Filename
  886. * @return string Filename sanitized
  887. */
  888. function dol_unescapefile($filename)
  889. {
  890. // Remove path information and dots around the filename, to prevent uploading
  891. // into different directories or replacing hidden system files.
  892. // Also remove control characters and spaces (\x00..\x20) around the filename:
  893. return trim(basename($filename), ".\x00..\x20");
  894. }
  895. /**
  896. * Make control on an uploaded file from an GUI page and move it to final destination.
  897. * If there is errors (virus found, antivir in error, bad filename), file is not moved.
  898. * Note: This function can be used only into a HTML page context. Use dol_move if you are outside.
  899. *
  900. * @param string $src_file Source full path filename ($_FILES['field']['tmp_name'])
  901. * @param string $dest_file Target full path filename ($_FILES['field']['name'])
  902. * @param int $allowoverwrite 1=Overwrite target file if it already exists
  903. * @param int $disablevirusscan 1=Disable virus scan
  904. * @param integer $uploaderrorcode Value of PHP upload error code ($_FILES['field']['error'])
  905. * @param int $nohook Disable all hooks
  906. * @param string $varfiles _FILES var name
  907. * @return int >0 if OK, <0 or string if KO
  908. * @see dol_move
  909. */
  910. function dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disablevirusscan=0, $uploaderrorcode=0, $nohook=0, $varfiles='addedfile')
  911. {
  912. global $conf, $db, $user, $langs;
  913. global $object, $hookmanager;
  914. $reshook=0;
  915. $file_name = $dest_file;
  916. if (empty($nohook))
  917. {
  918. // If an upload error has been reported
  919. if ($uploaderrorcode)
  920. {
  921. switch($uploaderrorcode)
  922. {
  923. case UPLOAD_ERR_INI_SIZE: // 1
  924. return 'ErrorFileSizeTooLarge';
  925. break;
  926. case UPLOAD_ERR_FORM_SIZE: // 2
  927. return 'ErrorFileSizeTooLarge';
  928. break;
  929. case UPLOAD_ERR_PARTIAL: // 3
  930. return 'ErrorPartialFile';
  931. break;
  932. case UPLOAD_ERR_NO_TMP_DIR: //
  933. return 'ErrorNoTmpDir';
  934. break;
  935. case UPLOAD_ERR_CANT_WRITE:
  936. return 'ErrorFailedToWriteInDir';
  937. break;
  938. case UPLOAD_ERR_EXTENSION:
  939. return 'ErrorUploadBlockedByAddon';
  940. break;
  941. default:
  942. break;
  943. }
  944. }
  945. // If we need to make a virus scan
  946. if (empty($disablevirusscan) && file_exists($src_file) && ! empty($conf->global->MAIN_ANTIVIRUS_COMMAND))
  947. {
  948. if (! class_exists('AntiVir')) {
  949. require DOL_DOCUMENT_ROOT.'/core/class/antivir.class.php';
  950. }
  951. $antivir=new AntiVir($db);
  952. $result = $antivir->dol_avscan_file($src_file);
  953. if ($result < 0) // If virus or error, we stop here
  954. {
  955. $reterrors=$antivir->errors;
  956. dol_syslog('Files.lib::dol_move_uploaded_file File "'.$src_file.'" (target name "'.$dest_file.'") KO with antivirus: result='.$result.' errors='.join(',',$antivir->errors), LOG_WARNING);
  957. return 'ErrorFileIsInfectedWithAVirus: '.join(',',$reterrors);
  958. }
  959. }
  960. // Security:
  961. // Disallow file with some extensions. We renamed them.
  962. // Car si on a mis le rep documents dans un rep de la racine web (pas bien), cela permet d'executer du code a la demande.
  963. if (preg_match('/\.htm|\.html|\.php|\.pl|\.cgi$/i',$dest_file) && empty($conf->global->MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED))
  964. {
  965. $file_name.= '.noexe';
  966. }
  967. // Security:
  968. // We refuse cache files/dirs, upload using .. and pipes into filenames.
  969. if (preg_match('/^\./',$src_file) || preg_match('/\.\./',$src_file) || preg_match('/[<>|]/',$src_file))
  970. {
  971. dol_syslog("Refused to deliver file ".$src_file, LOG_WARNING);
  972. return -1;
  973. }
  974. // Security:
  975. // On interdit fichiers caches, remontees de repertoire ainsi que les pipe dans les noms de fichiers.
  976. if (preg_match('/^\./',$dest_file) || preg_match('/\.\./',$dest_file) || preg_match('/[<>|]/',$dest_file))
  977. {
  978. dol_syslog("Refused to deliver file ".$dest_file, LOG_WARNING);
  979. return -2;
  980. }
  981. $reshook=$hookmanager->initHooks(array('fileslib'));
  982. $parameters=array('dest_file' => $dest_file, 'src_file' => $src_file, 'file_name' => $file_name, 'varfiles' => $varfiles, 'allowoverwrite' => $allowoverwrite);
  983. $reshook=$hookmanager->executeHooks('moveUploadedFile', $parameters, $object);
  984. }
  985. if ($reshook < 0) // At least one blocking error returned by one hook
  986. {
  987. $errmsg = join(',', $hookmanager->errors);
  988. if (empty($errmsg)) $errmsg = 'ErrorReturnedBySomeHooks'; // Should not occurs. Added if hook is bugged and does not set ->errors when there is error.
  989. return $errmsg;
  990. }
  991. elseif (empty($reshook))
  992. {
  993. // The file functions must be in OS filesystem encoding.
  994. $src_file_osencoded=dol_osencode($src_file);
  995. $file_name_osencoded=dol_osencode($file_name);
  996. // Check if destination dir is writable
  997. // TODO
  998. // Check if destination file already exists
  999. if (! $allowoverwrite)
  1000. {
  1001. if (file_exists($file_name_osencoded))
  1002. {
  1003. dol_syslog("Files.lib::dol_move_uploaded_file File ".$file_name." already exists. Return 'ErrorFileAlreadyExists'", LOG_WARNING);
  1004. return 'ErrorFileAlreadyExists';
  1005. }
  1006. }
  1007. // Move file
  1008. $return=move_uploaded_file($src_file_osencoded, $file_name_osencoded);
  1009. if ($return)
  1010. {
  1011. if (! empty($conf->global->MAIN_UMASK)) @chmod($file_name_osencoded, octdec($conf->global->MAIN_UMASK));
  1012. dol_syslog("Files.lib::dol_move_uploaded_file Success to move ".$src_file." to ".$file_name." - Umask=".$conf->global->MAIN_UMASK, LOG_DEBUG);
  1013. return 1; // Success
  1014. }
  1015. else
  1016. {
  1017. dol_syslog("Files.lib::dol_move_uploaded_file Failed to move ".$src_file." to ".$file_name, LOG_ERR);
  1018. return -3; // Unknown error
  1019. }
  1020. }
  1021. return 1; // Success
  1022. }
  1023. /**
  1024. * Remove a file or several files with a mask
  1025. *
  1026. * @param string $file File to delete or mask of files to delete
  1027. * @param int $disableglob Disable usage of glob like * so function is an exact delete function that will return error if no file found
  1028. * @param int $nophperrors Disable all PHP output errors
  1029. * @param int $nohook Disable all hooks
  1030. * @param object $object Current object in use
  1031. * @return boolean True if no error (file is deleted or if glob is used and there's nothing to delete), False if error
  1032. * @see dol_delete_dir
  1033. */
  1034. function dol_delete_file($file,$disableglob=0,$nophperrors=0,$nohook=0,$object=null)
  1035. {
  1036. global $db, $conf, $user, $langs;
  1037. global $hookmanager;
  1038. $langs->load("other");
  1039. $langs->load("errors");
  1040. dol_syslog("dol_delete_file file=".$file." disableglob=".$disableglob." nophperrors=".$nophperrors." nohook=".$nohook);
  1041. // Security:
  1042. // We refuse transversal using .. and pipes into filenames.
  1043. if (preg_match('/\.\./',$file) || preg_match('/[<>|]/',$file))
  1044. {
  1045. dol_syslog("Refused to delete file ".$file, LOG_WARNING);
  1046. return False;
  1047. }
  1048. if (empty($nohook))
  1049. {
  1050. $hookmanager->initHooks(array('fileslib'));
  1051. $parameters=array(
  1052. 'GET' => $_GET,
  1053. 'file' => $file,
  1054. 'disableglob'=> $disableglob,
  1055. 'nophperrors' => $nophperrors
  1056. );
  1057. $reshook=$hookmanager->executeHooks('deleteFile', $parameters, $object);
  1058. }
  1059. if (empty($nohook) && $reshook != 0) // reshook = 0 to do standard actions, 1 = ok, -1 = ko
  1060. {
  1061. if ($reshook < 0) return false;
  1062. return true;
  1063. }
  1064. else
  1065. {
  1066. $error=0;
  1067. //print "x".$file." ".$disableglob;exit;
  1068. $file_osencoded=dol_osencode($file); // New filename encoded in OS filesystem encoding charset
  1069. if (empty($disableglob) && ! empty($file_osencoded))
  1070. {
  1071. $ok=true;
  1072. $globencoded=str_replace('[','\[',$file_osencoded);
  1073. $globencoded=str_replace(']','\]',$globencoded);
  1074. $listofdir=glob($globencoded);
  1075. if (! empty($listofdir) && is_array($listofdir))
  1076. {
  1077. foreach ($listofdir as $filename)
  1078. {
  1079. if ($nophperrors) $ok=@unlink($filename);
  1080. else $ok=unlink($filename);
  1081. if ($ok) dol_syslog("Removed file ".$filename, LOG_DEBUG);
  1082. else dol_syslog("Failed to remove file ".$filename, LOG_WARNING);
  1083. // TODO Failure to remove can be because file was already removed or because of permission
  1084. // If error because of not exists, we must can return true but we should return false if this is a permission problem
  1085. }
  1086. }
  1087. else dol_syslog("No files to delete found", LOG_WARNING);
  1088. }
  1089. else
  1090. {
  1091. $ok=false;
  1092. if ($nophperrors) $ok=@unlink($file_osencoded);
  1093. else $ok=unlink($file_osencoded);
  1094. if ($ok) dol_syslog("Removed file ".$file_osencoded, LOG_DEBUG);
  1095. else dol_syslog("Failed to remove file ".$file_osencoded, LOG_WARNING);
  1096. }
  1097. return $ok;
  1098. }
  1099. }
  1100. /**
  1101. * Remove a directory (not recursive, so content must be empty).
  1102. * If directory is not empty, return false
  1103. *
  1104. * @param string $dir Directory to delete
  1105. * @param int $nophperrors Disable all PHP output errors
  1106. * @return boolean True if success, false if error
  1107. * @see dol_delete_file
  1108. */
  1109. function dol_delete_dir($dir,$nophperrors=0)
  1110. {
  1111. // Security:
  1112. // We refuse transversal using .. and pipes into filenames.
  1113. if (preg_match('/\.\./',$dir) || preg_match('/[<>|]/',$dir))
  1114. {
  1115. dol_syslog("Refused to delete dir ".$dir, LOG_WARNING);
  1116. return False;
  1117. }
  1118. $dir_osencoded=dol_osencode($dir);
  1119. return ($nophperrors?@rmdir($dir_osencoded):rmdir($dir_osencoded));
  1120. }
  1121. /**
  1122. * Remove a directory $dir and its subdirectories (or only files and subdirectories)
  1123. *
  1124. * @param string $dir Dir to delete
  1125. * @param int $count Counter to count nb of deleted elements
  1126. * @param int $nophperrors Disable all PHP output errors
  1127. * @param int $onlysub Delete only files and subdir, not main directory
  1128. * @return int Number of files and directory removed
  1129. */
  1130. function dol_delete_dir_recursive($dir,$count=0,$nophperrors=0,$onlysub=0)
  1131. {
  1132. dol_syslog("functions.lib:dol_delete_dir_recursive ".$dir,LOG_DEBUG);
  1133. if (dol_is_dir($dir))
  1134. {
  1135. $dir_osencoded=dol_osencode($dir);
  1136. if ($handle = opendir("$dir_osencoded"))
  1137. {
  1138. while (false !== ($item = readdir($handle)))
  1139. {
  1140. if (! utf8_check($item)) $item=utf8_encode($item); // should be useless
  1141. if ($item != "." && $item != "..")
  1142. {
  1143. if (is_dir(dol_osencode("$dir/$item")))
  1144. {
  1145. $count=dol_delete_dir_recursive("$dir/$item",$count,$nophperrors);
  1146. }
  1147. else
  1148. {
  1149. dol_delete_file("$dir/$item",1,$nophperrors);
  1150. $count++;
  1151. //echo " removing $dir/$item<br>\n";
  1152. }
  1153. }
  1154. }
  1155. closedir($handle);
  1156. if (empty($onlysub))
  1157. {
  1158. dol_delete_dir($dir,$nophperrors);
  1159. $count++;
  1160. //echo "removing $dir<br>\n";
  1161. }
  1162. }
  1163. }
  1164. //echo "return=".$count;
  1165. return $count;
  1166. }
  1167. /**
  1168. * Delete all preview files linked to object instance
  1169. *
  1170. * @param object $object Object to clean
  1171. * @return int 0 if error, 1 if OK
  1172. */
  1173. function dol_delete_preview($object)
  1174. {
  1175. global $langs,$conf;
  1176. // Define parent dir of elements
  1177. $element = $object->element;
  1178. if ($object->element == 'order_supplier') $dir = $conf->fournisseur->dir_output.'/commande';
  1179. elseif ($object->element == 'invoice_supplier') $dir = $conf->fournisseur->dir_output.'/facture';
  1180. elseif ($object->element == 'project') $dir = $conf->projet->dir_output;
  1181. elseif ($object->element == 'shipping') $dir = $conf->expedition->dir_output.'/sending';
  1182. elseif ($object->element == 'delivery') $dir = $conf->expedition->dir_output.'/receipt';
  1183. elseif ($object->element == 'fichinter') $dir = $conf->ficheinter->dir_output;
  1184. else $dir=empty($conf->$element->dir_output)?'':$conf->$element->dir_output;
  1185. if (empty($dir)) return 'ErrorObjectNoSupportedByFunction';
  1186. $refsan = dol_sanitizeFileName($object->ref);
  1187. $dir = $dir . "/" . $refsan ;
  1188. $file = $dir . "/" . $refsan . ".pdf.png";
  1189. $multiple = $file . ".";
  1190. if (file_exists($file) && is_writable($file))
  1191. {
  1192. if (! dol_delete_file($file,1))
  1193. {
  1194. $object->error=$langs->trans("ErrorFailedToDeleteFile",$file);
  1195. return 0;
  1196. }
  1197. }
  1198. else
  1199. {
  1200. for ($i = 0; $i < 20; $i++)
  1201. {
  1202. $preview = $multiple.$i;
  1203. if (file_exists($preview) && is_writable($preview))
  1204. {
  1205. if ( ! dol_delete_file($preview,1) )
  1206. {
  1207. $object->error=$langs->trans("ErrorFailedToOpenFile",$preview);
  1208. return 0;
  1209. }
  1210. }
  1211. }
  1212. }
  1213. return 1;
  1214. }
  1215. /**
  1216. * Create a meta file with document file into same directory.
  1217. * This should allow "grep" search.
  1218. * This feature is enabled only if option MAIN_DOC_CREATE_METAFILE is set.
  1219. *
  1220. * @param CommonObject $object Object
  1221. * @return int 0 if we did nothing, >0 success, <0 error
  1222. */
  1223. function dol_meta_create($object)
  1224. {
  1225. global $conf;
  1226. if (empty($conf->global->MAIN_DOC_CREATE_METAFILE)) return 0; // By default, no metafile.
  1227. // Define parent dir of elements
  1228. $element=$object->element;
  1229. if ($object->element == 'order_supplier') $dir = $conf->fournisseur->dir_output.'/commande';
  1230. elseif ($object->element == 'invoice_supplier') $dir = $conf->fournisseur->dir_output.'/facture';
  1231. elseif ($object->element == 'project') $dir = $conf->projet->dir_output;
  1232. elseif ($object->element == 'shipping') $dir = $conf->expedition->dir_output.'/sending';
  1233. elseif ($object->element == 'delivery') $dir = $conf->expedition->dir_output.'/receipt';
  1234. elseif ($object->element == 'fichinter') $dir = $conf->ficheinter->dir_output;
  1235. else $dir=empty($conf->$element->dir_output)?'':$conf->$element->dir_output;
  1236. if ($dir)
  1237. {
  1238. $object->fetch_thirdparty();
  1239. $facref = dol_sanitizeFileName($object->ref);
  1240. $dir = $dir . "/" . $facref;
  1241. $file = $dir . "/" . $facref . ".meta";
  1242. if (! is_dir($dir))
  1243. {
  1244. dol_mkdir($dir);
  1245. }
  1246. if (is_dir($dir))
  1247. {
  1248. $nblignes = count($object->lines);
  1249. $client = $object->thirdparty->name . " " . $object->thirdparty->address . " " . $object->thirdparty->zip . " " . $object->thirdparty->town;
  1250. $meta = "REFERENCE=\"" . $object->ref . "\"
  1251. DATE=\"" . dol_print_date($object->date,'') . "\"
  1252. NB_ITEMS=\"" . $nblignes . "\"
  1253. CLIENT=\"" . $client . "\"
  1254. TOTAL_HT=\"" . $object->total_ht . "\"
  1255. TOTAL_TTC=\"" . $object->total_ttc . "\"\n";
  1256. for ($i = 0 ; $i < $nblignes ; $i++)
  1257. {
  1258. //Pour les articles
  1259. $meta .= "ITEM_" . $i . "_QUANTITY=\"" . $object->lines[$i]->qty . "\"
  1260. ITEM_" . $i . "_TOTAL_HT=\"" . $object->lines[$i]->total_ht . "\"
  1261. ITEM_" . $i . "_TVA=\"" .$object->lines[$i]->tva_tx . "\"
  1262. ITEM_" . $i . "_DESCRIPTION=\"" . str_replace("\r\n","",nl2br($object->lines[$i]->desc)) . "\"
  1263. ";
  1264. }
  1265. }
  1266. $fp = fopen($file,"w");
  1267. fputs($fp,$meta);
  1268. fclose($fp);
  1269. if (! empty($conf->global->MAIN_UMASK))
  1270. @chmod($file, octdec($conf->global->MAIN_UMASK));
  1271. return 1;
  1272. }
  1273. return 0;
  1274. }
  1275. /**
  1276. * Scan a directory and init $_SESSION to manage uploaded files with list of all found files.
  1277. * Note: Only email module seems to use this. Other feature initialize the $_SESSION doing $formmail->clear_attached_files(); $formmail->add_attached_files()
  1278. *
  1279. * @param string $pathtoscan Path to scan
  1280. * @param string $trackid Track id (used to prefix name of session vars to avoid conflict)
  1281. * @return void
  1282. */
  1283. function dol_init_file_process($pathtoscan='', $trackid='')
  1284. {
  1285. $listofpaths=array();
  1286. $listofnames=array();
  1287. $listofmimes=array();
  1288. if ($pathtoscan)
  1289. {
  1290. $listoffiles=dol_dir_list($pathtoscan,'files');
  1291. foreach($listoffiles as $key => $val)
  1292. {
  1293. $listofpaths[]=$val['fullname'];
  1294. $listofnames[]=$val['name'];
  1295. $listofmimes[]=dol_mimetype($val['name']);
  1296. }
  1297. }
  1298. $keytoavoidconflict = empty($trackid)?'':'-'.$trackid;
  1299. $_SESSION["listofpaths".$keytoavoidconflict]=join(';',$listofpaths);
  1300. $_SESSION["listofnames".$keytoavoidconflict]=join(';',$listofnames);
  1301. $_SESSION["listofmimes".$keytoavoidconflict]=join(';',$listofmimes);
  1302. }
  1303. /**
  1304. * Get and save an upload file (for example after submitting a new file a mail form).
  1305. * All information used are in db, conf, langs, user and _FILES.
  1306. * Note: This function can be used only into a HTML page context.
  1307. *
  1308. * @param string $upload_dir Directory where to store uploaded file (note: also find in first part of dest_file)
  1309. * @param int $allowoverwrite 1=Allow overwrite existing file
  1310. * @param int $donotupdatesession 1=Do no edit _SESSION variable
  1311. * @param string $varfiles _FILES var name
  1312. * @param string $savingdocmask Mask to use to define output filename. For example 'XXXXX-__YYYYMMDD__-__file__'
  1313. * @param string $link Link to add
  1314. * @param string $trackid Track id (used to prefix name of session vars to avoid conflict)
  1315. * @return void
  1316. */
  1317. function dol_add_file_process($upload_dir, $allowoverwrite=0, $donotupdatesession=0, $varfiles='addedfile', $savingdocmask='', $link=null, $trackid='')
  1318. {
  1319. global $db,$user,$conf,$langs;
  1320. if (! empty($_FILES[$varfiles])) // For view $_FILES[$varfiles]['error']
  1321. {
  1322. dol_syslog('dol_add_file_process upload_dir='.$upload_dir.' allowoverwrite='.$allowoverwrite.' donotupdatesession='.$donotupdatesession.' savingdocmask='.$savingdocmask, LOG_DEBUG);
  1323. if (dol_mkdir($upload_dir) >= 0)
  1324. {
  1325. $TFile = $_FILES[$varfiles];
  1326. if (!is_array($TFile['name']))
  1327. {
  1328. foreach ($TFile as $key => &$val)
  1329. {
  1330. $val = array($val);
  1331. }
  1332. }
  1333. $nbfile = count($TFile['name']);
  1334. for ($i = 0; $i < $nbfile; $i++)
  1335. {
  1336. // Define $destpath (path to file including filename) and $destfile (only filename)
  1337. $destpath=$upload_dir . "/" . $TFile['name'][$i];
  1338. $destfile=$TFile['name'][$i];
  1339. $savingdocmask = dol_sanitizeFileName($savingdocmask);
  1340. if ($savingdocmask)
  1341. {
  1342. $destpath=$upload_dir . "/" . preg_replace('/__file__/',$TFile['name'][$i],$savingdocmask);
  1343. $destfile=preg_replace('/__file__/',$TFile['name'][$i],$savingdocmask);
  1344. }
  1345. // lowercase extension
  1346. $info = pathinfo($destpath);
  1347. $destpath = $info['dirname'].'/'.$info['filename'].'.'.strtolower($info['extension']);
  1348. $info = pathinfo($destfile);
  1349. $destfile = $info['filename'].'.'.strtolower($info['extension']);
  1350. $resupload = dol_move_uploaded_file($TFile['tmp_name'][$i], $destpath, $allowoverwrite, 0, $TFile['error'][$i], 0, $varfiles);
  1351. if (is_numeric($resupload) && $resupload > 0)
  1352. {
  1353. global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini;
  1354. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  1355. if (empty($donotupdatesession))
  1356. {
  1357. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  1358. $formmail = new FormMail($db);
  1359. $formmail->trackid = $trackid;
  1360. $formmail->add_attached_files($destpath, $destfile, $TFile['type'][$i]);
  1361. }
  1362. if (image_format_supported($destpath) == 1)
  1363. {
  1364. // Create thumbs
  1365. // We can't use $object->addThumbs here because there is no $object known
  1366. // Used on logon for example
  1367. $imgThumbSmall = vignette($destpath, $maxwidthsmall, $maxheightsmall, '_small', 50, "thumbs");
  1368. // Create mini thumbs for image (Ratio is near 16/9)
  1369. // Used on menu or for setup page for example
  1370. $imgThumbMini = vignette($destpath, $maxwidthmini, $maxheightmini, '_mini', 50, "thumbs");
  1371. }
  1372. setEventMessages($langs->trans("FileTransferComplete"), null, 'mesgs');
  1373. }
  1374. else
  1375. {
  1376. $langs->load("errors");
  1377. if ($resupload < 0) // Unknown error
  1378. {
  1379. setEventMessages($langs->trans("ErrorFileNotUploaded"), null, 'errors');
  1380. }
  1381. else if (preg_match('/ErrorFileIsInfectedWithAVirus/',$resupload)) // Files infected by a virus
  1382. {
  1383. setEventMessages($langs->trans("ErrorFileIsInfectedWithAVirus"), null, 'errors');
  1384. }
  1385. else // Known error
  1386. {
  1387. setEventMessages($langs->trans($resupload), null, 'errors');
  1388. }
  1389. }
  1390. }
  1391. }
  1392. } elseif ($link) {
  1393. if (dol_mkdir($upload_dir) >= 0) {
  1394. require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php';
  1395. $linkObject = new Link($db);
  1396. $linkObject->entity = $conf->entity;
  1397. $linkObject->url = $link;
  1398. $linkObject->objecttype = GETPOST('objecttype', 'alpha');
  1399. $linkObject->objectid = GETPOST('objectid', 'int');
  1400. $linkObject->label = GETPOST('label', 'alpha');
  1401. $res = $linkObject->create($user);
  1402. $langs->load('link');
  1403. if ($res > 0) {
  1404. setEventMessages($langs->trans("LinkComplete"), null, 'mesgs');
  1405. } else {
  1406. setEventMessages($langs->trans("ErrorFileNotLinked"), null, 'errors');
  1407. }
  1408. }
  1409. }
  1410. else
  1411. {
  1412. $langs->load("errors");
  1413. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("File")), null, 'errors');
  1414. }
  1415. }
  1416. /**
  1417. * Remove an uploaded file (for example after submitting a new file a mail form).
  1418. * All information used are in db, conf, langs, user and _FILES.
  1419. *
  1420. * @param int $filenb File nb to delete
  1421. * @param int $donotupdatesession 1=Do not edit _SESSION variable
  1422. * @param int $donotdeletefile 1=Do not delete physically file
  1423. * @param string $trackid Track id (used to prefix name of session vars to avoid conflict)
  1424. * @return void
  1425. */
  1426. function dol_remove_file_process($filenb,$donotupdatesession=0,$donotdeletefile=1,$trackid='')
  1427. {
  1428. global $db,$user,$conf,$langs,$_FILES;
  1429. $keytodelete=$filenb;
  1430. $keytodelete--;
  1431. $listofpaths=array();
  1432. $listofnames=array();
  1433. $listofmimes=array();
  1434. $keytoavoidconflict = empty($trackid)?'':'-'.$trackid;
  1435. if (! empty($_SESSION["listofpaths".$keytoavoidconflict])) $listofpaths=explode(';',$_SESSION["listofpaths".$keytoavoidconflict]);
  1436. if (! empty($_SESSION["listofnames".$keytoavoidconflict])) $listofnames=explode(';',$_SESSION["listofnames".$keytoavoidconflict]);
  1437. if (! empty($_SESSION["listofmimes".$keytoavoidconflict])) $listofmimes=explode(';',$_SESSION["listofmimes".$keytoavoidconflict]);
  1438. if ($keytodelete >= 0)
  1439. {
  1440. $pathtodelete=$listofpaths[$keytodelete];
  1441. $filetodelete=$listofnames[$keytodelete];
  1442. if (empty($donotdeletefile)) $result = dol_delete_file($pathtodelete,1);
  1443. else $result=0;
  1444. if ($result >= 0)
  1445. {
  1446. if (empty($donotdeletefile))
  1447. {
  1448. $langs->load("other");
  1449. setEventMessages($langs->trans("FileWasRemoved",$filetodelete), null, 'mesgs');
  1450. }
  1451. if (empty($donotupdatesession))
  1452. {
  1453. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  1454. $formmail = new FormMail($db);
  1455. $formmail->trackid = $trackid;
  1456. $formmail->remove_attached_files($keytodelete);
  1457. }
  1458. }
  1459. }
  1460. }
  1461. /**
  1462. * Convert an image file into anoher format.
  1463. * This need Imagick php extension.
  1464. *
  1465. * @param string $fileinput Input file name
  1466. * @param string $ext Format of target file (It is also extension added to file if fileoutput is not provided).
  1467. * @param string $fileoutput Output filename
  1468. * @return int <0 if KO, >0 if OK
  1469. */
  1470. function dol_convert_file($fileinput,$ext='png',$fileoutput='')
  1471. {
  1472. global $langs;
  1473. $image=new Imagick();
  1474. $ret = $image->readImage($fileinput);
  1475. if ($ret)
  1476. {
  1477. $ret = $image->setImageFormat($ext);
  1478. if ($ret)
  1479. {
  1480. if (empty($fileoutput)) $fileoutput=$fileinput.".".$ext;
  1481. $count = $image->getNumberImages();
  1482. $ret = $image->writeImages($fileoutput, true);
  1483. if ($ret) return $count;
  1484. else return -3;
  1485. }
  1486. else
  1487. {
  1488. return -2;
  1489. }
  1490. }
  1491. else
  1492. {
  1493. return -1;
  1494. }
  1495. }
  1496. /**
  1497. * Compress a file
  1498. *
  1499. * @param string $inputfile Source file name
  1500. * @param string $outputfile Target file name
  1501. * @param string $mode 'gz' or 'bz' or 'zip'
  1502. * @return int <0 if KO, >0 if OK
  1503. */
  1504. function dol_compress_file($inputfile, $outputfile, $mode="gz")
  1505. {
  1506. $foundhandler=0;
  1507. try
  1508. {
  1509. $data = implode("", file(dol_osencode($inputfile)));
  1510. if ($mode == 'gz') { $foundhandler=1; $compressdata = gzencode($data, 9); }
  1511. elseif ($mode == 'bz') { $foundhandler=1; $compressdata = bzcompress($data, 9); }
  1512. elseif ($mode == 'zip')
  1513. {
  1514. if (defined('ODTPHP_PATHTOPCLZIP'))
  1515. {
  1516. $foundhandler=1;
  1517. include_once ODTPHP_PATHTOPCLZIP.'/pclzip.lib.php';
  1518. $archive = new PclZip($outputfile);
  1519. $archive->add($inputfile, PCLZIP_OPT_REMOVE_PATH, dirname($inputfile));
  1520. //$archive->add($inputfile);
  1521. return 1;
  1522. }
  1523. }
  1524. if ($foundhandler)
  1525. {
  1526. $fp = fopen($outputfile, "w");
  1527. fwrite($fp, $compressdata);
  1528. fclose($fp);
  1529. return 1;
  1530. }
  1531. else
  1532. {
  1533. dol_syslog("Try to zip with format ".$mode." with no handler for this format",LOG_ERR);
  1534. return -2;
  1535. }
  1536. }
  1537. catch (Exception $e)
  1538. {
  1539. global $langs, $errormsg;
  1540. $langs->load("errors");
  1541. dol_syslog("Failed to open file ".$outputfile,LOG_ERR);
  1542. $errormsg=$langs->trans("ErrorFailedToWriteInDir");
  1543. return -1;
  1544. }
  1545. }
  1546. /**
  1547. * Uncompress a file
  1548. *
  1549. * @param string $inputfile File to uncompress
  1550. * @param string $outputdir Target dir name
  1551. * @return array array('error'=>'Error code') or array() if no error
  1552. */
  1553. function dol_uncompress($inputfile,$outputdir)
  1554. {
  1555. global $conf, $langs;
  1556. if (defined('ODTPHP_PATHTOPCLZIP'))
  1557. {
  1558. dol_syslog("Constant ODTPHP_PATHTOPCLZIP for pclzip library is set to ".constant('ODTPHP_PATHTOPCLZIP').", so we use Pclzip to unzip into ".$outputdir);
  1559. include_once ODTPHP_PATHTOPCLZIP.'/pclzip.lib.php';
  1560. $archive = new PclZip($inputfile);
  1561. $result=$archive->extract(PCLZIP_OPT_PATH, $outputdir);
  1562. //var_dump($result);
  1563. if (! is_array($result) && $result <= 0) return array('error'=>$archive->errorInfo(true));
  1564. else
  1565. {
  1566. $ok=1; $errmsg='';
  1567. // Loop on each file to check result for unzipping file
  1568. foreach($result as $key => $val)
  1569. {
  1570. if ($val['status'] == 'path_creation_fail')
  1571. {
  1572. $langs->load("errors");
  1573. $ok=0;
  1574. $errmsg=$langs->trans("ErrorFailToCreateDir", $val['filename']);
  1575. break;
  1576. }
  1577. }
  1578. if ($ok) return array();
  1579. else return array('error'=>$errmsg);
  1580. }
  1581. }
  1582. if (class_exists('ZipArchive'))
  1583. {
  1584. dol_syslog("Class ZipArchive is set so we unzip using ZipArchive to unzip into ".$outputdir);
  1585. $zip = new ZipArchive;
  1586. $res = $zip->open($inputfile);
  1587. if ($res === TRUE)
  1588. {
  1589. $zip->extractTo($outputdir.'/');
  1590. $zip->close();
  1591. return array();
  1592. }
  1593. else
  1594. {
  1595. return array('error'=>'ErrUnzipFails');
  1596. }
  1597. }
  1598. return array('error'=>'ErrNoZipEngine');
  1599. }
  1600. /**
  1601. * Return file(s) into a directory (by default most recent)
  1602. *
  1603. * @param string $dir Directory to scan
  1604. * @param string $regexfilter Regex filter to restrict list. This regex value must be escaped for '/', since this char is used for preg_match function
  1605. * @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
  1606. * @param int $nohook Disable all hooks
  1607. * @return string Full path to most recent file
  1608. */
  1609. function dol_most_recent_file($dir,$regexfilter='',$excludefilter=array('(\.meta|_preview\.png)$','^\.'),$nohook=false)
  1610. {
  1611. $tmparray=dol_dir_list($dir,'files',0,$regexfilter,$excludefilter,'date',SORT_DESC,'',$nohook);
  1612. return $tmparray[0];
  1613. }
  1614. /**
  1615. * Security check when accessing to a document (used by document.php, viewimage.php and webservices)
  1616. *
  1617. * @param string $modulepart Module of document ('module', 'module_user_temp', 'module_user' or 'module_temp')
  1618. * @param string $original_file Relative path with filename
  1619. * @param string $entity Restrict onto entity
  1620. * @param User $fuser User object (forced)
  1621. * @param string $refname Ref of object to check permission for external users (autodetect if not provided)
  1622. * @return mixed Array with access information : accessallowed & sqlprotectagainstexternals & original_file (as full path name)
  1623. */
  1624. function dol_check_secure_access_document($modulepart,$original_file,$entity,$fuser='',$refname='')
  1625. {
  1626. global $user, $conf, $db;
  1627. global $dolibarr_main_data_root;
  1628. if (! is_object($fuser)) $fuser=$user;
  1629. if (empty($modulepart)) return 'ErrorBadParameter';
  1630. if (empty($entity)) $entity=0;
  1631. dol_syslog('modulepart='.$modulepart.' original_file='.$original_file);
  1632. // We define $accessallowed and $sqlprotectagainstexternals
  1633. $accessallowed=0;
  1634. $sqlprotectagainstexternals='';
  1635. $ret=array();
  1636. // find the subdirectory name as the reference
  1637. if (empty($refname)) $refname=basename(dirname($original_file)."/");
  1638. $relative_original_file = $original_file;
  1639. // Wrapping for some images
  1640. if ($modulepart == 'companylogo' && !empty($conf->mycompany->dir_output))
  1641. {
  1642. $accessallowed=1;
  1643. $original_file=$conf->mycompany->dir_output.'/logos/'.$original_file;
  1644. }
  1645. // Wrapping for users photos
  1646. elseif ($modulepart == 'userphoto' && !empty($conf->user->dir_output))
  1647. {
  1648. $accessallowed=1;
  1649. $original_file=$conf->user->dir_output.'/'.$original_file;
  1650. }
  1651. // Wrapping for members photos
  1652. elseif ($modulepart == 'memberphoto' && !empty($conf->adherent->dir_output))
  1653. {
  1654. $accessallowed=1;
  1655. $original_file=$conf->adherent->dir_output.'/'.$original_file;
  1656. }
  1657. // Wrapping pour les apercu factures
  1658. elseif ($modulepart == 'apercufacture' && !empty($conf->facture->dir_output))
  1659. {
  1660. if ($fuser->rights->facture->lire) $accessallowed=1;
  1661. $original_file=$conf->facture->dir_output.'/'.$original_file;
  1662. }
  1663. // Wrapping pour les apercu propal
  1664. elseif ($modulepart == 'apercupropal' && !empty($conf->propal->dir_output))
  1665. {
  1666. if ($fuser->rights->propale->lire) $accessallowed=1;
  1667. $original_file=$conf->propal->dir_output.'/'.$original_file;
  1668. }
  1669. // Wrapping pour les apercu commande
  1670. elseif ($modulepart == 'apercucommande' && !empty($conf->commande->dir_output))
  1671. {
  1672. if ($fuser->rights->commande->lire) $accessallowed=1;
  1673. $original_file=$conf->commande->dir_output.'/'.$original_file;
  1674. }
  1675. // Wrapping pour les apercu intervention
  1676. elseif ($modulepart == 'apercufichinter' && !empty($conf->ficheinter->dir_output))
  1677. {
  1678. if ($fuser->rights->ficheinter->lire) $accessallowed=1;
  1679. $original_file=$conf->ficheinter->dir_output.'/'.$original_file;
  1680. }
  1681. // Wrapping pour les images des stats propales
  1682. elseif ($modulepart == 'propalstats' && !empty($conf->propal->dir_temp))
  1683. {
  1684. if ($fuser->rights->propale->lire) $accessallowed=1;
  1685. $original_file=$conf->propal->dir_temp.'/'.$original_file;
  1686. }
  1687. // Wrapping pour les images des stats commandes
  1688. elseif ($modulepart == 'orderstats' && !empty($conf->commande->dir_temp))
  1689. {
  1690. if ($fuser->rights->commande->lire) $accessallowed=1;
  1691. $original_file=$conf->commande->dir_temp.'/'.$original_file;
  1692. }
  1693. elseif ($modulepart == 'orderstatssupplier' && !empty($conf->fournisseur->dir_output))
  1694. {
  1695. if ($fuser->rights->fournisseur->commande->lire) $accessallowed=1;
  1696. $original_file=$conf->fournisseur->dir_output.'/commande/temp/'.$original_file;
  1697. }
  1698. // Wrapping pour les images des stats factures
  1699. elseif ($modulepart == 'billstats' && !empty($conf->facture->dir_temp))
  1700. {
  1701. if ($fuser->rights->facture->lire) $accessallowed=1;
  1702. $original_file=$conf->facture->dir_temp.'/'.$original_file;
  1703. }
  1704. elseif ($modulepart == 'billstatssupplier' && !empty($conf->fournisseur->dir_output))
  1705. {
  1706. if ($fuser->rights->fournisseur->facture->lire) $accessallowed=1;
  1707. $original_file=$conf->fournisseur->dir_output.'/facture/temp/'.$original_file;
  1708. }
  1709. // Wrapping pour les images des stats expeditions
  1710. elseif ($modulepart == 'expeditionstats' && !empty($conf->expedition->dir_temp))
  1711. {
  1712. if ($fuser->rights->expedition->lire) $accessallowed=1;
  1713. $original_file=$conf->expedition->dir_temp.'/'.$original_file;
  1714. }
  1715. // Wrapping pour les images des stats expeditions
  1716. elseif ($modulepart == 'tripsexpensesstats' && !empty($conf->deplacement->dir_temp))
  1717. {
  1718. if ($fuser->rights->deplacement->lire) $accessallowed=1;
  1719. $original_file=$conf->deplacement->dir_temp.'/'.$original_file;
  1720. }
  1721. // Wrapping pour les images des stats expeditions
  1722. elseif ($modulepart == 'memberstats' && !empty($conf->adherent->dir_temp))
  1723. {
  1724. if ($fuser->rights->adherent->lire) $accessallowed=1;
  1725. $original_file=$conf->adherent->dir_temp.'/'.$original_file;
  1726. }
  1727. // Wrapping pour les images des stats produits
  1728. elseif (preg_match('/^productstats_/i',$modulepart) && !empty($conf->product->dir_temp))
  1729. {
  1730. if ($fuser->rights->produit->lire || $fuser->rights->service->lire) $accessallowed=1;
  1731. $original_file=(!empty($conf->product->multidir_temp[$entity])?$conf->product->multidir_temp[$entity]:$conf->service->multidir_temp[$entity]).'/'.$original_file;
  1732. }
  1733. // Wrapping for products or services
  1734. elseif ($modulepart == 'tax' && !empty($conf->tax->dir_output))
  1735. {
  1736. if ($fuser->rights->tax->charges->lire) $accessallowed=1;
  1737. $original_file=$conf->tax->dir_output.'/'.$original_file;
  1738. }
  1739. // Wrapping for products or services
  1740. elseif ($modulepart == 'actions' && !empty($conf->agenda->dir_output))
  1741. {
  1742. if ($fuser->rights->agenda->myactions->read) $accessallowed=1;
  1743. $original_file=$conf->agenda->dir_output.'/'.$original_file;
  1744. }
  1745. // Wrapping for categories
  1746. elseif ($modulepart == 'category' && !empty($conf->categorie->dir_output))
  1747. {
  1748. if ($fuser->rights->categorie->lire) $accessallowed=1;
  1749. $original_file=$conf->categorie->multidir_output[$entity].'/'.$original_file;
  1750. }
  1751. // Wrapping pour les prelevements
  1752. elseif ($modulepart == 'prelevement' && !empty($conf->prelevement->dir_output))
  1753. {
  1754. if ($fuser->rights->prelevement->bons->lire || preg_match('/^specimen/i',$original_file))
  1755. {
  1756. $accessallowed=1;
  1757. }
  1758. $original_file=$conf->prelevement->dir_output.'/'.$original_file;
  1759. }
  1760. // Wrapping pour les graph energie
  1761. elseif ($modulepart == 'graph_stock' && !empty($conf->stock->dir_temp))
  1762. {
  1763. $accessallowed=1;
  1764. $original_file=$conf->stock->dir_temp.'/'.$original_file;
  1765. }
  1766. // Wrapping pour les graph fournisseurs
  1767. elseif ($modulepart == 'graph_fourn' && !empty($conf->fournisseur->dir_temp))
  1768. {
  1769. $accessallowed=1;
  1770. $original_file=$conf->fournisseur->dir_temp.'/'.$original_file;
  1771. }
  1772. // Wrapping pour les graph des produits
  1773. elseif ($modulepart == 'graph_product' && !empty($conf->product->dir_temp))
  1774. {
  1775. $accessallowed=1;
  1776. $original_file=$conf->product->multidir_temp[$entity].'/'.$original_file;
  1777. }
  1778. // Wrapping pour les code barre
  1779. elseif ($modulepart == 'barcode')
  1780. {
  1781. $accessallowed=1;
  1782. // If viewimage is called for barcode, we try to output an image on the fly, with no build of file on disk.
  1783. //$original_file=$conf->barcode->dir_temp.'/'.$original_file;
  1784. $original_file='';
  1785. }
  1786. // Wrapping pour les icones de background des mailings
  1787. elseif ($modulepart == 'iconmailing' && !empty($conf->mailing->dir_temp))
  1788. {
  1789. $accessallowed=1;
  1790. $original_file=$conf->mailing->dir_temp.'/'.$original_file;
  1791. }
  1792. // Wrapping pour le scanner
  1793. elseif ($modulepart == 'scanner_user_temp' && !empty($conf->scanner->dir_temp))
  1794. {
  1795. $accessallowed=1;
  1796. $original_file=$conf->scanner->dir_temp.'/'.$fuser->id.'/'.$original_file;
  1797. }
  1798. // Wrapping pour les images fckeditor
  1799. elseif ($modulepart == 'fckeditor' && !empty($conf->fckeditor->dir_output))
  1800. {
  1801. $accessallowed=1;
  1802. $original_file=$conf->fckeditor->dir_output.'/'.$original_file;
  1803. }
  1804. // Wrapping for third parties
  1805. else if (($modulepart == 'company' || $modulepart == 'societe') && !empty($conf->societe->dir_output))
  1806. {
  1807. if ($fuser->rights->societe->lire || preg_match('/^specimen/i',$original_file))
  1808. {
  1809. $accessallowed=1;
  1810. }
  1811. $original_file=$conf->societe->multidir_output[$entity].'/'.$original_file;
  1812. $sqlprotectagainstexternals = "SELECT rowid as fk_soc FROM ".MAIN_DB_PREFIX."societe WHERE rowid='".$db->escape($refname)."' AND entity IN (".getEntity('societe', 1).")";
  1813. }
  1814. // Wrapping for contact
  1815. else if ($modulepart == 'contact' && !empty($conf->societe->dir_output))
  1816. {
  1817. if ($fuser->rights->societe->lire)
  1818. {
  1819. $accessallowed=1;
  1820. }
  1821. $original_file=$conf->societe->multidir_output[$entity].'/contact/'.$original_file;
  1822. }
  1823. // Wrapping for invoices
  1824. else if (($modulepart == 'facture' || $modulepart == 'invoice') && !empty($conf->facture->dir_output))
  1825. {
  1826. if ($fuser->rights->facture->lire || preg_match('/^specimen/i',$original_file))
  1827. {
  1828. $accessallowed=1;
  1829. }
  1830. $original_file=$conf->facture->dir_output.'/'.$original_file;
  1831. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."facture WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  1832. }
  1833. else if ($modulepart == 'massfilesarea_facture' && !empty($conf->facture->dir_output))
  1834. {
  1835. if ($fuser->rights->facture->lire || preg_match('/^specimen/i',$original_file))
  1836. {
  1837. $accessallowed=1;
  1838. }
  1839. $original_file=$conf->facture->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
  1840. }
  1841. // Wrapping for interventions
  1842. else if (($modulepart == 'fichinter' || $modulepart == 'ficheinter') && !empty($conf->ficheinter->dir_output))
  1843. {
  1844. if ($fuser->rights->ficheinter->lire || preg_match('/^specimen/i',$original_file))
  1845. {
  1846. $accessallowed=1;
  1847. }
  1848. $original_file=$conf->ficheinter->dir_output.'/'.$original_file;
  1849. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."fichinter WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  1850. }
  1851. // Wrapping pour les deplacements et notes de frais
  1852. else if ($modulepart == 'deplacement' && !empty($conf->deplacement->dir_output))
  1853. {
  1854. if ($fuser->rights->deplacement->lire || preg_match('/^specimen/i',$original_file))
  1855. {
  1856. $accessallowed=1;
  1857. }
  1858. $original_file=$conf->deplacement->dir_output.'/'.$original_file;
  1859. //$sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."fichinter WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  1860. }
  1861. // Wrapping pour les propales
  1862. else if ($modulepart == 'propal' && !empty($conf->propal->dir_output))
  1863. {
  1864. if ($fuser->rights->propale->lire || preg_match('/^specimen/i',$original_file))
  1865. {
  1866. $accessallowed=1;
  1867. }
  1868. $original_file=$conf->propal->dir_output.'/'.$original_file;
  1869. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."propal WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  1870. }
  1871. // Wrapping pour les commandes
  1872. else if (($modulepart == 'commande' || $modulepart == 'order') && !empty($conf->commande->dir_output))
  1873. {
  1874. if ($fuser->rights->commande->lire || preg_match('/^specimen/i',$original_file))
  1875. {
  1876. $accessallowed=1;
  1877. }
  1878. $original_file=$conf->commande->dir_output.'/'.$original_file;
  1879. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."commande WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  1880. }
  1881. // Wrapping pour les projets
  1882. else if ($modulepart == 'project' && !empty($conf->projet->dir_output))
  1883. {
  1884. if ($fuser->rights->projet->lire || preg_match('/^specimen/i',$original_file))
  1885. {
  1886. $accessallowed=1;
  1887. }
  1888. $original_file=$conf->projet->dir_output.'/'.$original_file;
  1889. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."projet WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  1890. }
  1891. else if ($modulepart == 'project_task' && !empty($conf->projet->dir_output))
  1892. {
  1893. if ($fuser->rights->projet->lire || preg_match('/^specimen/i',$original_file))
  1894. {
  1895. $accessallowed=1;
  1896. }
  1897. $original_file=$conf->projet->dir_output.'/'.$original_file;
  1898. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."projet WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  1899. }
  1900. // Wrapping pour les commandes fournisseurs
  1901. else if (($modulepart == 'commande_fournisseur' || $modulepart == 'order_supplier') && !empty($conf->fournisseur->commande->dir_output))
  1902. {
  1903. if ($fuser->rights->fournisseur->commande->lire || preg_match('/^specimen/i',$original_file))
  1904. {
  1905. $accessallowed=1;
  1906. }
  1907. $original_file=$conf->fournisseur->commande->dir_output.'/'.$original_file;
  1908. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."commande_fournisseur WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  1909. }
  1910. // Wrapping pour les factures fournisseurs
  1911. else if (($modulepart == 'facture_fournisseur' || $modulepart == 'invoice_supplier') && !empty($conf->fournisseur->facture->dir_output))
  1912. {
  1913. if ($fuser->rights->fournisseur->facture->lire || preg_match('/^specimen/i',$original_file))
  1914. {
  1915. $accessallowed=1;
  1916. }
  1917. $original_file=$conf->fournisseur->facture->dir_output.'/'.$original_file;
  1918. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."facture_fourn WHERE facnumber='".$db->escape($refname)."' AND entity=".$conf->entity;
  1919. }
  1920. // Wrapping pour les rapport de paiements
  1921. else if ($modulepart == 'facture_paiement' && !empty($conf->facture->dir_output))
  1922. {
  1923. if ($fuser->rights->facture->lire || preg_match('/^specimen/i',$original_file))
  1924. {
  1925. $accessallowed=1;
  1926. }
  1927. if ($fuser->societe_id > 0) $original_file=$conf->facture->dir_output.'/payments/private/'.$fuser->id.'/'.$original_file;
  1928. else $original_file=$conf->facture->dir_output.'/payments/'.$original_file;
  1929. }
  1930. // Wrapping for accounting exports
  1931. else if ($modulepart == 'export_compta' && !empty($conf->accounting->dir_output))
  1932. {
  1933. if ($fuser->rights->accounting->ventilation->dispatch || preg_match('/^specimen/i',$original_file))
  1934. {
  1935. $accessallowed=1;
  1936. }
  1937. $original_file=$conf->accounting->dir_output.'/'.$original_file;
  1938. }
  1939. // Wrapping pour les expedition
  1940. else if ($modulepart == 'expedition' && !empty($conf->expedition->dir_output))
  1941. {
  1942. if ($fuser->rights->expedition->lire || preg_match('/^specimen/i',$original_file))
  1943. {
  1944. $accessallowed=1;
  1945. }
  1946. $original_file=$conf->expedition->dir_output."/sending/".$original_file;
  1947. }
  1948. // Wrapping pour les bons de livraison
  1949. else if ($modulepart == 'livraison' && !empty($conf->expedition->dir_output))
  1950. {
  1951. if ($fuser->rights->expedition->livraison->lire || preg_match('/^specimen/i',$original_file))
  1952. {
  1953. $accessallowed=1;
  1954. }
  1955. $original_file=$conf->expedition->dir_output."/receipt/".$original_file;
  1956. }
  1957. // Wrapping pour les actions
  1958. else if ($modulepart == 'actions' && !empty($conf->agenda->dir_output))
  1959. {
  1960. if ($fuser->rights->agenda->myactions->read || preg_match('/^specimen/i',$original_file))
  1961. {
  1962. $accessallowed=1;
  1963. }
  1964. $original_file=$conf->agenda->dir_output.'/'.$original_file;
  1965. }
  1966. // Wrapping pour les actions
  1967. else if ($modulepart == 'actionsreport' && !empty($conf->agenda->dir_temp))
  1968. {
  1969. if ($fuser->rights->agenda->allactions->read || preg_match('/^specimen/i',$original_file))
  1970. {
  1971. $accessallowed=1;
  1972. }
  1973. $original_file = $conf->agenda->dir_temp."/".$original_file;
  1974. }
  1975. // Wrapping pour les produits et services
  1976. else if ($modulepart == 'product' || $modulepart == 'produit' || $modulepart == 'service')
  1977. {
  1978. if (($fuser->rights->produit->lire || $fuser->rights->service->lire) || preg_match('/^specimen/i',$original_file))
  1979. {
  1980. $accessallowed=1;
  1981. }
  1982. if (! empty($conf->product->enabled)) $original_file=$conf->product->multidir_output[$entity].'/'.$original_file;
  1983. elseif (! empty($conf->service->enabled)) $original_file=$conf->service->multidir_output[$entity].'/'.$original_file;
  1984. }
  1985. // Wrapping pour les contrats
  1986. else if ($modulepart == 'contract' && !empty($conf->contrat->dir_output))
  1987. {
  1988. if ($fuser->rights->contrat->lire || preg_match('/^specimen/i',$original_file))
  1989. {
  1990. $accessallowed=1;
  1991. }
  1992. $original_file=$conf->contrat->dir_output.'/'.$original_file;
  1993. }
  1994. // Wrapping pour les dons
  1995. else if ($modulepart == 'donation' && !empty($conf->donation->dir_output))
  1996. {
  1997. if ($fuser->rights->don->lire || preg_match('/^specimen/i',$original_file))
  1998. {
  1999. $accessallowed=1;
  2000. }
  2001. $original_file=$conf->don->dir_output.'/'.$original_file;
  2002. }
  2003. // Wrapping pour les remises de cheques
  2004. else if ($modulepart == 'remisecheque' && !empty($conf->banque->dir_output))
  2005. {
  2006. if ($fuser->rights->banque->lire || preg_match('/^specimen/i',$original_file))
  2007. {
  2008. $accessallowed=1;
  2009. }
  2010. $original_file=$conf->banque->dir_output.'/bordereau/'.$original_file; // original_file should contains relative path so include the get_exdir result
  2011. }
  2012. // Wrapping for bank
  2013. else if ($modulepart == 'bank' && !empty($conf->bank->dir_output))
  2014. {
  2015. if ($fuser->rights->banque->lire)
  2016. {
  2017. $accessallowed=1;
  2018. }
  2019. $original_file=$conf->bank->dir_output.'/'.$original_file;
  2020. }
  2021. // Wrapping for export module
  2022. else if ($modulepart == 'export' && !empty($conf->export->dir_temp))
  2023. {
  2024. // Aucun test necessaire car on force le rep de download sur
  2025. // le rep export qui est propre a l'utilisateur
  2026. $accessallowed=1;
  2027. $original_file=$conf->export->dir_temp.'/'.$fuser->id.'/'.$original_file;
  2028. }
  2029. // Wrapping for import module
  2030. else if ($modulepart == 'import' && !empty($conf->import->dir_temp))
  2031. {
  2032. $accessallowed=1;
  2033. $original_file=$conf->import->dir_temp.'/'.$original_file;
  2034. }
  2035. // Wrapping pour l'editeur wysiwyg
  2036. else if ($modulepart == 'editor' && !empty($conf->fckeditor->dir_output))
  2037. {
  2038. $accessallowed=1;
  2039. $original_file=$conf->fckeditor->dir_output.'/'.$original_file;
  2040. }
  2041. // Wrapping for miscellaneous medias files
  2042. elseif ($modulepart == 'medias' && !empty($dolibarr_main_data_root))
  2043. {
  2044. $accessallowed=1;
  2045. $original_file=$dolibarr_main_data_root.'/medias/'.$original_file;
  2046. }
  2047. // Wrapping for backups
  2048. else if ($modulepart == 'systemtools' && !empty($conf->admin->dir_output))
  2049. {
  2050. if ($fuser->admin) $accessallowed=1;
  2051. $original_file=$conf->admin->dir_output.'/'.$original_file;
  2052. }
  2053. // Wrapping for upload file test
  2054. else if ($modulepart == 'admin_temp' && !empty($conf->admin->dir_temp))
  2055. {
  2056. if ($fuser->admin) $accessallowed=1;
  2057. $original_file=$conf->admin->dir_temp.'/'.$original_file;
  2058. }
  2059. // Wrapping pour BitTorrent
  2060. else if ($modulepart == 'bittorrent' && !empty($conf->bittorrent->dir_output))
  2061. {
  2062. $accessallowed=1;
  2063. $dir='files';
  2064. if (dol_mimetype($original_file) == 'application/x-bittorrent') $dir='torrents';
  2065. $original_file=$conf->bittorrent->dir_output.'/'.$dir.'/'.$original_file;
  2066. }
  2067. // Wrapping pour Foundation module
  2068. else if ($modulepart == 'member' && !empty($conf->adherent->dir_output))
  2069. {
  2070. if ($fuser->rights->adherent->lire || preg_match('/^specimen/i',$original_file))
  2071. {
  2072. $accessallowed=1;
  2073. }
  2074. $original_file=$conf->adherent->dir_output.'/'.$original_file;
  2075. }
  2076. // Wrapping for Scanner
  2077. else if ($modulepart == 'scanner_user_temp' && !empty($conf->scanner->dir_temp))
  2078. {
  2079. $accessallowed=1;
  2080. $original_file=$conf->scanner->dir_temp.'/'.$fuser->id.'/'.$original_file;
  2081. }
  2082. // GENERIC Wrapping
  2083. // If modulepart=module_user_temp Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/temp/iduser
  2084. // If modulepart=module_temp Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/temp
  2085. // If modulepart=module_user Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/iduser
  2086. // If modulepart=module Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart
  2087. else
  2088. {
  2089. if (preg_match('/^specimen/i',$original_file)) $accessallowed=1; // If link to a file called specimen. Test must be done before changing $original_file int full path.
  2090. if ($fuser->admin) $accessallowed=1; // If user is admin
  2091. // Define $accessallowed
  2092. if (preg_match('/^([a-z]+)_user_temp$/i',$modulepart,$reg))
  2093. {
  2094. if (empty($conf->{$reg[1]}->dir_temp)) // modulepart not supported
  2095. {
  2096. dol_print_error('','Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
  2097. exit;
  2098. }
  2099. if ($fuser->rights->{$reg[1]}->lire || $fuser->rights->{$reg[1]}->read || ($fuser->rights->{$reg[1]}->download)) $accessallowed=1;
  2100. $original_file=$conf->{$reg[1]}->dir_temp.'/'.$fuser->id.'/'.$original_file;
  2101. }
  2102. else if (preg_match('/^([a-z]+)_temp$/i',$modulepart,$reg))
  2103. {
  2104. if (empty($conf->{$reg[1]}->dir_temp)) // modulepart not supported
  2105. {
  2106. dol_print_error('','Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
  2107. exit;
  2108. }
  2109. if ($fuser->rights->{$reg[1]}->lire || $fuser->rights->{$reg[1]}->read || ($fuser->rights->{$reg[1]}->download)) $accessallowed=1;
  2110. $original_file=$conf->{$reg[1]}->dir_temp.'/'.$original_file;
  2111. }
  2112. else if (preg_match('/^([a-z]+)_user$/i',$modulepart,$reg))
  2113. {
  2114. if (empty($conf->{$reg[1]}->dir_output)) // modulepart not supported
  2115. {
  2116. dol_print_error('','Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
  2117. exit;
  2118. }
  2119. if ($fuser->rights->{$reg[1]}->lire || $fuser->rights->{$reg[1]}->read || ($fuser->rights->{$reg[1]}->download)) $accessallowed=1;
  2120. $original_file=$conf->{$reg[1]}->dir_output.'/'.$fuser->id.'/'.$original_file;
  2121. }
  2122. else
  2123. {
  2124. if (empty($conf->$modulepart->dir_output)) // modulepart not supported
  2125. {
  2126. dol_print_error('','Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
  2127. exit;
  2128. }
  2129. $perm=GETPOST('perm');
  2130. $subperm=GETPOST('subperm');
  2131. if ($perm || $subperm)
  2132. {
  2133. if (($perm && ! $subperm && $fuser->rights->$modulepart->$perm) || ($perm && $subperm && $fuser->rights->$modulepart->$perm->$subperm)) $accessallowed=1;
  2134. $original_file=$conf->$modulepart->dir_output.'/'.$original_file;
  2135. }
  2136. else
  2137. {
  2138. if ($fuser->rights->$modulepart->lire || $fuser->rights->$modulepart->read) $accessallowed=1;
  2139. $original_file=$conf->$modulepart->dir_output.'/'.$original_file;
  2140. }
  2141. }
  2142. // For modules who wants to manage different levels of permissions for documents
  2143. $subPermCategoryConstName = strtoupper($modulepart).'_SUBPERMCATEGORY_FOR_DOCUMENTS';
  2144. if (! empty($conf->global->$subPermCategoryConstName))
  2145. {
  2146. $subPermCategory = $conf->global->$subPermCategoryConstName;
  2147. if (! empty($subPermCategory) && (($fuser->rights->$modulepart->$subPermCategory->lire) || ($fuser->rights->$modulepart->$subPermCategory->read) || ($fuser->rights->$modulepart->$subPermCategory->download)))
  2148. {
  2149. $accessallowed=1;
  2150. }
  2151. }
  2152. // Define $sqlprotectagainstexternals for modules who want to protect access using a SQL query.
  2153. $sqlProtectConstName = strtoupper($modulepart).'_SQLPROTECTAGAINSTEXTERNALS_FOR_DOCUMENTS';
  2154. if (! empty($conf->global->$sqlProtectConstName)) // If module want to define its own $sqlprotectagainstexternals
  2155. {
  2156. // Example: mymodule__SQLPROTECTAGAINSTEXTERNALS_FOR_DOCUMENTS = "SELECT fk_soc FROM ".MAIN_DB_PREFIX.$modulepart." WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  2157. eval('$sqlprotectagainstexternals = "'.$conf->global->$sqlProtectConstName.'";');
  2158. }
  2159. }
  2160. $ret = array(
  2161. 'accessallowed' => $accessallowed,
  2162. 'sqlprotectagainstexternals'=>$sqlprotectagainstexternals,
  2163. 'original_file'=>$original_file
  2164. );
  2165. return $ret;
  2166. }
  2167. /**
  2168. * Store object in file
  2169. *
  2170. * @param string $directory Directory of cache
  2171. * @param string $filename Name of filecache
  2172. * @param mixed $object Object to store in cachefile
  2173. * @return void
  2174. */
  2175. function dol_filecache($directory, $filename, $object)
  2176. {
  2177. if (! dol_is_dir($directory)) dol_mkdir($directory);
  2178. $cachefile = $directory . $filename;
  2179. file_put_contents($cachefile, serialize($object), LOCK_EX);
  2180. @chmod($cachefile, 0644);
  2181. }
  2182. /**
  2183. * Test if Refresh needed
  2184. *
  2185. * @param string $directory Directory of cache
  2186. * @param string $filename Name of filecache
  2187. * @param int $cachetime Cachetime delay
  2188. * @return boolean 0 no refresh 1 if refresh needed
  2189. */
  2190. function dol_cache_refresh($directory, $filename, $cachetime)
  2191. {
  2192. $now = dol_now();
  2193. $cachefile = $directory . $filename;
  2194. $refresh = !file_exists($cachefile) || ($now-$cachetime) > dol_filemtime($cachefile);
  2195. return $refresh;
  2196. }
  2197. /**
  2198. * Read object from cachefile
  2199. *
  2200. * @param string $directory Directory of cache
  2201. * @param string $filename Name of filecache
  2202. * @return mixed Unserialise from file
  2203. */
  2204. function dol_readcachefile($directory, $filename)
  2205. {
  2206. $cachefile = $directory . $filename;
  2207. $object = unserialize(file_get_contents($cachefile));
  2208. return $object;
  2209. }