files.lib.php 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406
  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::dolCopyr 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. $srcfile=dol_osencode($srcfile);
  793. $destfile=dol_osencode($destfile);
  794. // recursive function to copy
  795. // all subdirectories and contents:
  796. if (is_dir($srcfile))
  797. {
  798. $dir_handle=opendir($srcfile);
  799. while ($file=readdir($dir_handle))
  800. {
  801. if ($file!="." && $file!="..")
  802. {
  803. if (is_dir($srcfile."/".$file))
  804. {
  805. if (!is_dir($destfile."/".$file))
  806. {
  807. umask(0);
  808. $dirmaskdec=octdec($newmask);
  809. if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $dirmaskdec=octdec($conf->global->MAIN_UMASK);
  810. $dirmaskdec |= octdec('0200'); // Set w bit required to be able to create content for recursive subdirs files
  811. dol_mkdir($destfile."/".$file, '', decoct($dirmaskdec));
  812. }
  813. $result=dolCopyDir($srcfile."/".$file, $destfile."/".$file, $newmask, $overwriteifexists);
  814. }
  815. else
  816. {
  817. $result=dol_copy($srcfile."/".$file, $destfile."/".$file, $newmask, $overwriteifexists);
  818. }
  819. if ($result < 0) break;
  820. }
  821. }
  822. closedir($dir_handle);
  823. }
  824. else
  825. {
  826. $result=dol_copy($srcfile, $destfile, $newmask, $overwriteifexists);
  827. }
  828. return $result;
  829. }
  830. /**
  831. * Move a file into another name.
  832. * This function differs from dol_move_uploaded_file, because it can be called in any context.
  833. *
  834. * @param string $srcfile Source file (can't be a directory. use native php @rename() to move a directory)
  835. * @param string $destfile Destination file (can't be a directory. use native php @rename() to move a directory)
  836. * @param integer $newmask Mask in octal string for new file (0 by default means $conf->global->MAIN_UMASK)
  837. * @param int $overwriteifexists Overwrite file if exists (1 by default)
  838. * @return boolean True if OK, false if KO
  839. */
  840. function dol_move($srcfile, $destfile, $newmask=0, $overwriteifexists=1)
  841. {
  842. global $conf;
  843. $result=false;
  844. dol_syslog("files.lib.php::dol_move srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." overwritifexists=".$overwriteifexists);
  845. $destexists=dol_is_file($destfile);
  846. if ($overwriteifexists || ! $destexists)
  847. {
  848. $newpathofsrcfile=dol_osencode($srcfile);
  849. $newpathofdestfile=dol_osencode($destfile);
  850. $result=@rename($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @
  851. if (! $result)
  852. {
  853. if ($destexists)
  854. {
  855. dol_syslog("files.lib.php::dol_move failed. We try to delete first and move after.", LOG_WARNING);
  856. // We force delete and try again. Rename function sometimes fails to replace dest file with some windows NTFS partitions.
  857. dol_delete_file($destfile);
  858. $result=@rename($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @
  859. }
  860. else dol_syslog("files.lib.php::dol_move failed", LOG_WARNING);
  861. }
  862. if (empty($newmask)) $newmask=empty($conf->global->MAIN_UMASK)?'0755':$conf->global->MAIN_UMASK;
  863. $newmaskdec=octdec($newmask);
  864. // Currently method is restricted to files (dol_delete_files previously used is for files, and mask usage if for files too)
  865. // to allow mask usage for dir, we shoul introduce a new param "isdir" to 1 to complete newmask like this
  866. // if ($isdir) $newmaskdec |= octdec('0111'); // Set x bit required for directories
  867. @chmod($newpathofdestfile, $newmaskdec);
  868. }
  869. return $result;
  870. }
  871. /**
  872. * Unescape a file submitted by upload.
  873. * PHP escape char " (%22) or char ' (%27) into $FILES.
  874. *
  875. * @param string $filename Filename
  876. * @return string Filename sanitized
  877. */
  878. function dol_unescapefile($filename)
  879. {
  880. // Remove path information and dots around the filename, to prevent uploading
  881. // into different directories or replacing hidden system files.
  882. // Also remove control characters and spaces (\x00..\x20) around the filename:
  883. return trim(basename($filename), ".\x00..\x20");
  884. }
  885. /**
  886. * Make control on an uploaded file from an GUI page and move it to final destination.
  887. * If there is errors (virus found, antivir in error, bad filename), file is not moved.
  888. * Note: This function can be used only into a HTML page context. Use dol_move if you are outside.
  889. *
  890. * @param string $src_file Source full path filename ($_FILES['field']['tmp_name'])
  891. * @param string $dest_file Target full path filename ($_FILES['field']['name'])
  892. * @param int $allowoverwrite 1=Overwrite target file if it already exists
  893. * @param int $disablevirusscan 1=Disable virus scan
  894. * @param integer $uploaderrorcode Value of PHP upload error code ($_FILES['field']['error'])
  895. * @param int $nohook Disable all hooks
  896. * @param string $varfiles _FILES var name
  897. * @return int >0 if OK, <0 or string if KO
  898. * @see dol_move
  899. */
  900. function dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disablevirusscan=0, $uploaderrorcode=0, $nohook=0, $varfiles='addedfile')
  901. {
  902. global $conf, $db, $user, $langs;
  903. global $object, $hookmanager;
  904. $reshook=0;
  905. $file_name = $dest_file;
  906. if (empty($nohook))
  907. {
  908. // If an upload error has been reported
  909. if ($uploaderrorcode)
  910. {
  911. switch($uploaderrorcode)
  912. {
  913. case UPLOAD_ERR_INI_SIZE: // 1
  914. return 'ErrorFileSizeTooLarge';
  915. break;
  916. case UPLOAD_ERR_FORM_SIZE: // 2
  917. return 'ErrorFileSizeTooLarge';
  918. break;
  919. case UPLOAD_ERR_PARTIAL: // 3
  920. return 'ErrorPartialFile';
  921. break;
  922. case UPLOAD_ERR_NO_TMP_DIR: //
  923. return 'ErrorNoTmpDir';
  924. break;
  925. case UPLOAD_ERR_CANT_WRITE:
  926. return 'ErrorFailedToWriteInDir';
  927. break;
  928. case UPLOAD_ERR_EXTENSION:
  929. return 'ErrorUploadBlockedByAddon';
  930. break;
  931. default:
  932. break;
  933. }
  934. }
  935. // If we need to make a virus scan
  936. if (empty($disablevirusscan) && file_exists($src_file) && ! empty($conf->global->MAIN_ANTIVIRUS_COMMAND))
  937. {
  938. if (! class_exists('AntiVir')) {
  939. require DOL_DOCUMENT_ROOT.'/core/class/antivir.class.php';
  940. }
  941. $antivir=new AntiVir($db);
  942. $result = $antivir->dol_avscan_file($src_file);
  943. if ($result < 0) // If virus or error, we stop here
  944. {
  945. $reterrors=$antivir->errors;
  946. 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);
  947. return 'ErrorFileIsInfectedWithAVirus: '.join(',',$reterrors);
  948. }
  949. }
  950. // Security:
  951. // Disallow file with some extensions. We renamed them.
  952. // 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.
  953. if (preg_match('/\.htm|\.html|\.php|\.pl|\.cgi$/i',$dest_file))
  954. {
  955. $file_name.= '.noexe';
  956. }
  957. // Security:
  958. // On interdit fichiers caches, remontees de repertoire ainsi que les pipes dans les noms de fichiers.
  959. if (preg_match('/^\./',$src_file) || preg_match('/\.\./',$src_file) || preg_match('/[<>|]/',$src_file))
  960. {
  961. dol_syslog("Refused to deliver file ".$src_file, LOG_WARNING);
  962. return -1;
  963. }
  964. // Security:
  965. // On interdit fichiers caches, remontees de repertoire ainsi que les pipe dans les noms de fichiers.
  966. if (preg_match('/^\./',$dest_file) || preg_match('/\.\./',$dest_file) || preg_match('/[<>|]/',$dest_file))
  967. {
  968. dol_syslog("Refused to deliver file ".$dest_file, LOG_WARNING);
  969. return -2;
  970. }
  971. $reshook=$hookmanager->initHooks(array('fileslib'));
  972. $parameters=array('dest_file' => $dest_file, 'src_file' => $src_file, 'file_name' => $file_name, 'varfiles' => $varfiles, 'allowoverwrite' => $allowoverwrite);
  973. $reshook=$hookmanager->executeHooks('moveUploadedFile', $parameters, $object);
  974. }
  975. if ($reshook < 0) // At least one blocking error returned by one hook
  976. {
  977. $errmsg = join(',', $hookmanager->errors);
  978. if (empty($errmsg)) $errmsg = 'ErrorReturnedBySomeHooks'; // Should not occurs. Added if hook is bugged and does not set ->errors when there is error.
  979. return $errmsg;
  980. }
  981. elseif (empty($reshook))
  982. {
  983. // The file functions must be in OS filesystem encoding.
  984. $src_file_osencoded=dol_osencode($src_file);
  985. $file_name_osencoded=dol_osencode($file_name);
  986. // Check if destination dir is writable
  987. // TODO
  988. // Check if destination file already exists
  989. if (! $allowoverwrite)
  990. {
  991. if (file_exists($file_name_osencoded))
  992. {
  993. dol_syslog("Files.lib::dol_move_uploaded_file File ".$file_name." already exists. Return 'ErrorFileAlreadyExists'", LOG_WARNING);
  994. return 'ErrorFileAlreadyExists';
  995. }
  996. }
  997. // Move file
  998. $return=move_uploaded_file($src_file_osencoded, $file_name_osencoded);
  999. if ($return)
  1000. {
  1001. if (! empty($conf->global->MAIN_UMASK)) @chmod($file_name_osencoded, octdec($conf->global->MAIN_UMASK));
  1002. dol_syslog("Files.lib::dol_move_uploaded_file Success to move ".$src_file." to ".$file_name." - Umask=".$conf->global->MAIN_UMASK, LOG_DEBUG);
  1003. return 1; // Success
  1004. }
  1005. else
  1006. {
  1007. dol_syslog("Files.lib::dol_move_uploaded_file Failed to move ".$src_file." to ".$file_name, LOG_ERR);
  1008. return -3; // Unknown error
  1009. }
  1010. }
  1011. return 1; // Success
  1012. }
  1013. /**
  1014. * Remove a file or several files with a mask
  1015. *
  1016. * @param string $file File to delete or mask of files to delete
  1017. * @param int $disableglob Disable usage of glob like * so function is an exact delete function that will return error if no file found
  1018. * @param int $nophperrors Disable all PHP output errors
  1019. * @param int $nohook Disable all hooks
  1020. * @param object $object Current object in use
  1021. * @return boolean True if no error (file is deleted or if glob is used and there's nothing to delete), False if error
  1022. */
  1023. function dol_delete_file($file,$disableglob=0,$nophperrors=0,$nohook=0,$object=null)
  1024. {
  1025. global $db, $conf, $user, $langs;
  1026. global $hookmanager;
  1027. $langs->load("other");
  1028. $langs->load("errors");
  1029. dol_syslog("dol_delete_file file=".$file." disableglob=".$disableglob." nophperrors=".$nophperrors." nohook=".$nohook);
  1030. if (empty($nohook))
  1031. {
  1032. $hookmanager->initHooks(array('fileslib'));
  1033. $parameters=array(
  1034. 'GET' => $_GET,
  1035. 'file' => $file,
  1036. 'disableglob'=> $disableglob,
  1037. 'nophperrors' => $nophperrors
  1038. );
  1039. $reshook=$hookmanager->executeHooks('deleteFile', $parameters, $object);
  1040. }
  1041. if (empty($nohook) && $reshook != 0) // reshook = 0 to do standard actions, 1 = ok, -1 = ko
  1042. {
  1043. if ($reshook < 0) return false;
  1044. return true;
  1045. }
  1046. else
  1047. {
  1048. $error=0;
  1049. //print "x".$file." ".$disableglob;exit;
  1050. $file_osencoded=dol_osencode($file); // New filename encoded in OS filesystem encoding charset
  1051. if (empty($disableglob) && ! empty($file_osencoded))
  1052. {
  1053. $ok=true;
  1054. $globencoded=str_replace('[','\[',$file_osencoded);
  1055. $globencoded=str_replace(']','\]',$globencoded);
  1056. $listofdir=glob($globencoded);
  1057. if (! empty($listofdir) && is_array($listofdir))
  1058. {
  1059. foreach ($listofdir as $filename)
  1060. {
  1061. if ($nophperrors) $ok=@unlink($filename);
  1062. else $ok=unlink($filename);
  1063. if ($ok) dol_syslog("Removed file ".$filename, LOG_DEBUG);
  1064. else dol_syslog("Failed to remove file ".$filename, LOG_WARNING);
  1065. // TODO Failure to remove can be because file was already removed or because of permission
  1066. // If error because of not exists, we must can return true but we should return false if this is a permission problem
  1067. }
  1068. }
  1069. else dol_syslog("No files to delete found", LOG_WARNING);
  1070. }
  1071. else
  1072. {
  1073. $ok=false;
  1074. if ($nophperrors) $ok=@unlink($file_osencoded);
  1075. else $ok=unlink($file_osencoded);
  1076. if ($ok) dol_syslog("Removed file ".$file_osencoded, LOG_DEBUG);
  1077. else dol_syslog("Failed to remove file ".$file_osencoded, LOG_WARNING);
  1078. }
  1079. return $ok;
  1080. }
  1081. }
  1082. /**
  1083. * Remove a directory (not recursive, so content must be empty).
  1084. * If directory is not empty, return false
  1085. *
  1086. * @param string $dir Directory to delete
  1087. * @param int $nophperrors Disable all PHP output errors
  1088. * @return boolean True if success, false if error
  1089. */
  1090. function dol_delete_dir($dir,$nophperrors=0)
  1091. {
  1092. $dir_osencoded=dol_osencode($dir);
  1093. return ($nophperrors?@rmdir($dir_osencoded):rmdir($dir_osencoded));
  1094. }
  1095. /**
  1096. * Remove a directory $dir and its subdirectories (or only files and subdirectories)
  1097. *
  1098. * @param string $dir Dir to delete
  1099. * @param int $count Counter to count nb of deleted elements
  1100. * @param int $nophperrors Disable all PHP output errors
  1101. * @param int $onlysub Delete only files and subdir, not main directory
  1102. * @return int Number of files and directory removed
  1103. */
  1104. function dol_delete_dir_recursive($dir,$count=0,$nophperrors=0,$onlysub=0)
  1105. {
  1106. dol_syslog("functions.lib:dol_delete_dir_recursive ".$dir,LOG_DEBUG);
  1107. if (dol_is_dir($dir))
  1108. {
  1109. $dir_osencoded=dol_osencode($dir);
  1110. if ($handle = opendir("$dir_osencoded"))
  1111. {
  1112. while (false !== ($item = readdir($handle)))
  1113. {
  1114. if (! utf8_check($item)) $item=utf8_encode($item); // should be useless
  1115. if ($item != "." && $item != "..")
  1116. {
  1117. if (is_dir(dol_osencode("$dir/$item")))
  1118. {
  1119. $count=dol_delete_dir_recursive("$dir/$item",$count,$nophperrors);
  1120. }
  1121. else
  1122. {
  1123. dol_delete_file("$dir/$item",1,$nophperrors);
  1124. $count++;
  1125. //echo " removing $dir/$item<br>\n";
  1126. }
  1127. }
  1128. }
  1129. closedir($handle);
  1130. if (empty($onlysub))
  1131. {
  1132. dol_delete_dir($dir,$nophperrors);
  1133. $count++;
  1134. //echo "removing $dir<br>\n";
  1135. }
  1136. }
  1137. }
  1138. //echo "return=".$count;
  1139. return $count;
  1140. }
  1141. /**
  1142. * Delete all preview files linked to object instance
  1143. *
  1144. * @param object $object Object to clean
  1145. * @return int 0 if error, 1 if OK
  1146. */
  1147. function dol_delete_preview($object)
  1148. {
  1149. global $langs,$conf;
  1150. // Define parent dir of elements
  1151. $element = $object->element;
  1152. if ($object->element == 'order_supplier') $dir = $conf->fournisseur->dir_output.'/commande';
  1153. elseif ($object->element == 'invoice_supplier') $dir = $conf->fournisseur->dir_output.'/facture';
  1154. elseif ($object->element == 'project') $dir = $conf->projet->dir_output;
  1155. elseif ($object->element == 'shipping') $dir = $conf->expedition->dir_output.'/sending';
  1156. elseif ($object->element == 'delivery') $dir = $conf->expedition->dir_output.'/receipt';
  1157. elseif ($object->element == 'fichinter') $dir = $conf->ficheinter->dir_output;
  1158. else $dir=empty($conf->$element->dir_output)?'':$conf->$element->dir_output;
  1159. if (empty($dir)) return 'ErrorObjectNoSupportedByFunction';
  1160. $refsan = dol_sanitizeFileName($object->ref);
  1161. $dir = $dir . "/" . $refsan ;
  1162. $file = $dir . "/" . $refsan . ".pdf.png";
  1163. $multiple = $file . ".";
  1164. if (file_exists($file) && is_writable($file))
  1165. {
  1166. if (! dol_delete_file($file,1))
  1167. {
  1168. $object->error=$langs->trans("ErrorFailedToDeleteFile",$file);
  1169. return 0;
  1170. }
  1171. }
  1172. else
  1173. {
  1174. for ($i = 0; $i < 20; $i++)
  1175. {
  1176. $preview = $multiple.$i;
  1177. if (file_exists($preview) && is_writable($preview))
  1178. {
  1179. if ( ! dol_delete_file($preview,1) )
  1180. {
  1181. $object->error=$langs->trans("ErrorFailedToOpenFile",$preview);
  1182. return 0;
  1183. }
  1184. }
  1185. }
  1186. }
  1187. return 1;
  1188. }
  1189. /**
  1190. * Create a meta file with document file into same directory.
  1191. * This should allow "grep" search.
  1192. * This feature is enabled only if option MAIN_DOC_CREATE_METAFILE is set.
  1193. *
  1194. * @param CommonObject $object Object
  1195. * @return int 0 if we did nothing, >0 success, <0 error
  1196. */
  1197. function dol_meta_create($object)
  1198. {
  1199. global $conf;
  1200. if (empty($conf->global->MAIN_DOC_CREATE_METAFILE)) return 0; // By default, no metafile.
  1201. // Define parent dir of elements
  1202. $element=$object->element;
  1203. if ($object->element == 'order_supplier') $dir = $conf->fournisseur->dir_output.'/commande';
  1204. elseif ($object->element == 'invoice_supplier') $dir = $conf->fournisseur->dir_output.'/facture';
  1205. elseif ($object->element == 'project') $dir = $conf->projet->dir_output;
  1206. elseif ($object->element == 'shipping') $dir = $conf->expedition->dir_output.'/sending';
  1207. elseif ($object->element == 'delivery') $dir = $conf->expedition->dir_output.'/receipt';
  1208. elseif ($object->element == 'fichinter') $dir = $conf->ficheinter->dir_output;
  1209. else $dir=empty($conf->$element->dir_output)?'':$conf->$element->dir_output;
  1210. if ($dir)
  1211. {
  1212. $object->fetch_thirdparty();
  1213. $facref = dol_sanitizeFileName($object->ref);
  1214. $dir = $dir . "/" . $facref;
  1215. $file = $dir . "/" . $facref . ".meta";
  1216. if (! is_dir($dir))
  1217. {
  1218. dol_mkdir($dir);
  1219. }
  1220. if (is_dir($dir))
  1221. {
  1222. $nblignes = count($object->lines);
  1223. $client = $object->thirdparty->name . " " . $object->thirdparty->address . " " . $object->thirdparty->zip . " " . $object->thirdparty->town;
  1224. $meta = "REFERENCE=\"" . $object->ref . "\"
  1225. DATE=\"" . dol_print_date($object->date,'') . "\"
  1226. NB_ITEMS=\"" . $nblignes . "\"
  1227. CLIENT=\"" . $client . "\"
  1228. TOTAL_HT=\"" . $object->total_ht . "\"
  1229. TOTAL_TTC=\"" . $object->total_ttc . "\"\n";
  1230. for ($i = 0 ; $i < $nblignes ; $i++)
  1231. {
  1232. //Pour les articles
  1233. $meta .= "ITEM_" . $i . "_QUANTITY=\"" . $object->lines[$i]->qty . "\"
  1234. ITEM_" . $i . "_TOTAL_HT=\"" . $object->lines[$i]->total_ht . "\"
  1235. ITEM_" . $i . "_TVA=\"" .$object->lines[$i]->tva_tx . "\"
  1236. ITEM_" . $i . "_DESCRIPTION=\"" . str_replace("\r\n","",nl2br($object->lines[$i]->desc)) . "\"
  1237. ";
  1238. }
  1239. }
  1240. $fp = fopen($file,"w");
  1241. fputs($fp,$meta);
  1242. fclose($fp);
  1243. if (! empty($conf->global->MAIN_UMASK))
  1244. @chmod($file, octdec($conf->global->MAIN_UMASK));
  1245. return 1;
  1246. }
  1247. return 0;
  1248. }
  1249. /**
  1250. * Scan a directory and init $_SESSION to manage uploaded files with list of all found files.
  1251. * Note: Only email module seems to use this. Other feature initialize the $_SESSION doing $formmail->clear_attached_files(); $formmail->add_attached_files()
  1252. *
  1253. * @param string $pathtoscan Path to scan
  1254. * @param string $trackid Track id (used to prefix name of session vars to avoid conflict)
  1255. * @return void
  1256. */
  1257. function dol_init_file_process($pathtoscan='', $trackid='')
  1258. {
  1259. $listofpaths=array();
  1260. $listofnames=array();
  1261. $listofmimes=array();
  1262. if ($pathtoscan)
  1263. {
  1264. $listoffiles=dol_dir_list($pathtoscan,'files');
  1265. foreach($listoffiles as $key => $val)
  1266. {
  1267. $listofpaths[]=$val['fullname'];
  1268. $listofnames[]=$val['name'];
  1269. $listofmimes[]=dol_mimetype($val['name']);
  1270. }
  1271. }
  1272. $keytoavoidconflict = empty($trackid)?'':'-'.$trackid;
  1273. $_SESSION["listofpaths".$keytoavoidconflict]=join(';',$listofpaths);
  1274. $_SESSION["listofnames".$keytoavoidconflict]=join(';',$listofnames);
  1275. $_SESSION["listofmimes".$keytoavoidconflict]=join(';',$listofmimes);
  1276. }
  1277. /**
  1278. * Get and save an upload file (for example after submitting a new file a mail form).
  1279. * All information used are in db, conf, langs, user and _FILES.
  1280. * Note: This function can be used only into a HTML page context.
  1281. *
  1282. * @param string $upload_dir Directory where to store uploaded file (note: also find in first part of dest_file)
  1283. * @param int $allowoverwrite 1=Allow overwrite existing file
  1284. * @param int $donotupdatesession 1=Do no edit _SESSION variable
  1285. * @param string $varfiles _FILES var name
  1286. * @param string $savingdocmask Mask to use to define output filename. For example 'XXXXX-__YYYYMMDD__-__file__'
  1287. * @param string $link Link to add
  1288. * @param string $trackid Track id (used to prefix name of session vars to avoid conflict)
  1289. * @return void
  1290. */
  1291. function dol_add_file_process($upload_dir, $allowoverwrite=0, $donotupdatesession=0, $varfiles='addedfile', $savingdocmask='', $link=null, $trackid='')
  1292. {
  1293. global $db,$user,$conf,$langs;
  1294. if (! empty($_FILES[$varfiles])) // For view $_FILES[$varfiles]['error']
  1295. {
  1296. dol_syslog('dol_add_file_process upload_dir='.$upload_dir.' allowoverwrite='.$allowoverwrite.' donotupdatesession='.$donotupdatesession.' savingdocmask='.$savingdocmask, LOG_DEBUG);
  1297. if (dol_mkdir($upload_dir) >= 0)
  1298. {
  1299. $TFile = $_FILES[$varfiles];
  1300. if (!is_array($TFile['name']))
  1301. {
  1302. foreach ($TFile as $key => &$val)
  1303. {
  1304. $val = array($val);
  1305. }
  1306. }
  1307. $nbfile = count($TFile['name']);
  1308. for ($i = 0; $i < $nbfile; $i++)
  1309. {
  1310. // Define $destpath (path to file including filename) and $destfile (only filename)
  1311. $destpath=$upload_dir . "/" . $TFile['name'][$i];
  1312. $destfile=$TFile['name'][$i];
  1313. $savingdocmask = dol_sanitizeFileName($savingdocmask);
  1314. if ($savingdocmask)
  1315. {
  1316. $destpath=$upload_dir . "/" . preg_replace('/__file__/',$TFile['name'][$i],$savingdocmask);
  1317. $destfile=preg_replace('/__file__/',$TFile['name'][$i],$savingdocmask);
  1318. }
  1319. // lowercase extension
  1320. $info = pathinfo($destpath);
  1321. $destpath = $info['dirname'].'/'.$info['filename'].'.'.strtolower($info['extension']);
  1322. $info = pathinfo($destfile);
  1323. $destfile = $info['filename'].'.'.strtolower($info['extension']);
  1324. $resupload = dol_move_uploaded_file($TFile['tmp_name'][$i], $destpath, $allowoverwrite, 0, $TFile['error'][$i], 0, $varfiles);
  1325. if (is_numeric($resupload) && $resupload > 0)
  1326. {
  1327. global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini;
  1328. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  1329. if (empty($donotupdatesession))
  1330. {
  1331. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  1332. $formmail = new FormMail($db);
  1333. $formmail->trackid = $trackid;
  1334. $formmail->add_attached_files($destpath, $destfile, $TFile['type'][$i]);
  1335. }
  1336. if (image_format_supported($destpath) == 1)
  1337. {
  1338. // Create thumbs
  1339. // We can't use $object->addThumbs here because there is no $object known
  1340. // Used on logon for example
  1341. $imgThumbSmall = vignette($destpath, $maxwidthsmall, $maxheightsmall, '_small', 50, "thumbs");
  1342. // Create mini thumbs for image (Ratio is near 16/9)
  1343. // Used on menu or for setup page for example
  1344. $imgThumbMini = vignette($destpath, $maxwidthmini, $maxheightmini, '_mini', 50, "thumbs");
  1345. }
  1346. setEventMessages($langs->trans("FileTransferComplete"), null, 'mesgs');
  1347. }
  1348. else
  1349. {
  1350. $langs->load("errors");
  1351. if ($resupload < 0) // Unknown error
  1352. {
  1353. setEventMessages($langs->trans("ErrorFileNotUploaded"), null, 'errors');
  1354. }
  1355. else if (preg_match('/ErrorFileIsInfectedWithAVirus/',$resupload)) // Files infected by a virus
  1356. {
  1357. setEventMessages($langs->trans("ErrorFileIsInfectedWithAVirus"), null, 'errors');
  1358. }
  1359. else // Known error
  1360. {
  1361. setEventMessages($langs->trans($resupload), null, 'errors');
  1362. }
  1363. }
  1364. }
  1365. }
  1366. } elseif ($link) {
  1367. if (dol_mkdir($upload_dir) >= 0) {
  1368. require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php';
  1369. $linkObject = new Link($db);
  1370. $linkObject->entity = $conf->entity;
  1371. $linkObject->url = $link;
  1372. $linkObject->objecttype = GETPOST('objecttype', 'alpha');
  1373. $linkObject->objectid = GETPOST('objectid', 'int');
  1374. $linkObject->label = GETPOST('label', 'alpha');
  1375. $res = $linkObject->create($user);
  1376. $langs->load('link');
  1377. if ($res > 0) {
  1378. setEventMessages($langs->trans("LinkComplete"), null, 'mesgs');
  1379. } else {
  1380. setEventMessages($langs->trans("ErrorFileNotLinked"), null, 'errors');
  1381. }
  1382. }
  1383. }
  1384. else
  1385. {
  1386. $langs->load("errors");
  1387. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("File")), null, 'errors');
  1388. }
  1389. }
  1390. /**
  1391. * Remove an uploaded file (for example after submitting a new file a mail form).
  1392. * All information used are in db, conf, langs, user and _FILES.
  1393. *
  1394. * @param int $filenb File nb to delete
  1395. * @param int $donotupdatesession 1=Do not edit _SESSION variable
  1396. * @param int $donotdeletefile 1=Do not delete physically file
  1397. * @param string $trackid Track id (used to prefix name of session vars to avoid conflict)
  1398. * @return void
  1399. */
  1400. function dol_remove_file_process($filenb,$donotupdatesession=0,$donotdeletefile=1,$trackid='')
  1401. {
  1402. global $db,$user,$conf,$langs,$_FILES;
  1403. $keytodelete=$filenb;
  1404. $keytodelete--;
  1405. $listofpaths=array();
  1406. $listofnames=array();
  1407. $listofmimes=array();
  1408. $keytoavoidconflict = empty($trackid)?'':'-'.$trackid;
  1409. if (! empty($_SESSION["listofpaths".$keytoavoidconflict])) $listofpaths=explode(';',$_SESSION["listofpaths".$keytoavoidconflict]);
  1410. if (! empty($_SESSION["listofnames".$keytoavoidconflict])) $listofnames=explode(';',$_SESSION["listofnames".$keytoavoidconflict]);
  1411. if (! empty($_SESSION["listofmimes".$keytoavoidconflict])) $listofmimes=explode(';',$_SESSION["listofmimes".$keytoavoidconflict]);
  1412. if ($keytodelete >= 0)
  1413. {
  1414. $pathtodelete=$listofpaths[$keytodelete];
  1415. $filetodelete=$listofnames[$keytodelete];
  1416. if (empty($donotdeletefile)) $result = dol_delete_file($pathtodelete,1);
  1417. else $result=0;
  1418. if ($result >= 0)
  1419. {
  1420. if (empty($donotdeletefile))
  1421. {
  1422. $langs->load("other");
  1423. setEventMessages($langs->trans("FileWasRemoved",$filetodelete), null, 'mesgs');
  1424. }
  1425. if (empty($donotupdatesession))
  1426. {
  1427. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  1428. $formmail = new FormMail($db);
  1429. $formmail->trackid = $trackid;
  1430. $formmail->remove_attached_files($keytodelete);
  1431. }
  1432. }
  1433. }
  1434. }
  1435. /**
  1436. * Convert an image file into anoher format.
  1437. * This need Imagick php extension.
  1438. *
  1439. * @param string $fileinput Input file name
  1440. * @param string $ext Format of target file (It is also extension added to file if fileoutput is not provided).
  1441. * @param string $fileoutput Output filename
  1442. * @return int <0 if KO, >0 if OK
  1443. */
  1444. function dol_convert_file($fileinput,$ext='png',$fileoutput='')
  1445. {
  1446. global $langs;
  1447. $image=new Imagick();
  1448. $ret = $image->readImage($fileinput);
  1449. if ($ret)
  1450. {
  1451. $ret = $image->setImageFormat($ext);
  1452. if ($ret)
  1453. {
  1454. if (empty($fileoutput)) $fileoutput=$fileinput.".".$ext;
  1455. $count = $image->getNumberImages();
  1456. $ret = $image->writeImages($fileoutput, true);
  1457. if ($ret) return $count;
  1458. else return -3;
  1459. }
  1460. else
  1461. {
  1462. return -2;
  1463. }
  1464. }
  1465. else
  1466. {
  1467. return -1;
  1468. }
  1469. }
  1470. /**
  1471. * Compress a file
  1472. *
  1473. * @param string $inputfile Source file name
  1474. * @param string $outputfile Target file name
  1475. * @param string $mode 'gz' or 'bz' or 'zip'
  1476. * @return int <0 if KO, >0 if OK
  1477. */
  1478. function dol_compress_file($inputfile, $outputfile, $mode="gz")
  1479. {
  1480. $foundhandler=0;
  1481. try
  1482. {
  1483. $data = implode("", file(dol_osencode($inputfile)));
  1484. if ($mode == 'gz') { $foundhandler=1; $compressdata = gzencode($data, 9); }
  1485. elseif ($mode == 'bz') { $foundhandler=1; $compressdata = bzcompress($data, 9); }
  1486. elseif ($mode == 'zip')
  1487. {
  1488. if (defined('ODTPHP_PATHTOPCLZIP'))
  1489. {
  1490. $foundhandler=1;
  1491. include_once ODTPHP_PATHTOPCLZIP.'/pclzip.lib.php';
  1492. $archive = new PclZip($outputfile);
  1493. $archive->add($inputfile, PCLZIP_OPT_REMOVE_PATH, dirname($inputfile));
  1494. //$archive->add($inputfile);
  1495. return 1;
  1496. }
  1497. }
  1498. if ($foundhandler)
  1499. {
  1500. $fp = fopen($outputfile, "w");
  1501. fwrite($fp, $compressdata);
  1502. fclose($fp);
  1503. return 1;
  1504. }
  1505. else
  1506. {
  1507. dol_syslog("Try to zip with format ".$mode." with no handler for this format",LOG_ERR);
  1508. return -2;
  1509. }
  1510. }
  1511. catch (Exception $e)
  1512. {
  1513. global $langs, $errormsg;
  1514. $langs->load("errors");
  1515. dol_syslog("Failed to open file ".$outputfile,LOG_ERR);
  1516. $errormsg=$langs->trans("ErrorFailedToWriteInDir");
  1517. return -1;
  1518. }
  1519. }
  1520. /**
  1521. * Uncompress a file
  1522. *
  1523. * @param string $inputfile File to uncompress
  1524. * @param string $outputdir Target dir name
  1525. * @return array array('error'=>'Error code') or array() if no error
  1526. */
  1527. function dol_uncompress($inputfile,$outputdir)
  1528. {
  1529. global $conf, $langs;
  1530. if (defined('ODTPHP_PATHTOPCLZIP'))
  1531. {
  1532. dol_syslog("Constant ODTPHP_PATHTOPCLZIP for pclzip library is set to ".constant('ODTPHP_PATHTOPCLZIP').", so we use Pclzip to unzip into ".$outputdir);
  1533. include_once ODTPHP_PATHTOPCLZIP.'/pclzip.lib.php';
  1534. $archive = new PclZip($inputfile);
  1535. $result=$archive->extract(PCLZIP_OPT_PATH, $outputdir);
  1536. //var_dump($result);
  1537. if (! is_array($result) && $result <= 0) return array('error'=>$archive->errorInfo(true));
  1538. else
  1539. {
  1540. $ok=1; $errmsg='';
  1541. // Loop on each file to check result for unzipping file
  1542. foreach($result as $key => $val)
  1543. {
  1544. if ($val['status'] == 'path_creation_fail')
  1545. {
  1546. $langs->load("errors");
  1547. $ok=0;
  1548. $errmsg=$langs->trans("ErrorFailToCreateDir", $val['filename']);
  1549. break;
  1550. }
  1551. }
  1552. if ($ok) return array();
  1553. else return array('error'=>$errmsg);
  1554. }
  1555. }
  1556. if (class_exists('ZipArchive'))
  1557. {
  1558. dol_syslog("Class ZipArchive is set so we unzip using ZipArchive to unzip into ".$outputdir);
  1559. $zip = new ZipArchive;
  1560. $res = $zip->open($inputfile);
  1561. if ($res === TRUE)
  1562. {
  1563. $zip->extractTo($outputdir.'/');
  1564. $zip->close();
  1565. return array();
  1566. }
  1567. else
  1568. {
  1569. return array('error'=>'ErrUnzipFails');
  1570. }
  1571. }
  1572. return array('error'=>'ErrNoZipEngine');
  1573. }
  1574. /**
  1575. * Return file(s) into a directory (by default most recent)
  1576. *
  1577. * @param string $dir Directory to scan
  1578. * @param string $regexfilter Regex filter to restrict list. This regex value must be escaped for '/', since this char is used for preg_match function
  1579. * @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
  1580. * @param int $nohook Disable all hooks
  1581. * @return string Full path to most recent file
  1582. */
  1583. function dol_most_recent_file($dir,$regexfilter='',$excludefilter=array('(\.meta|_preview\.png)$','^\.'),$nohook=false)
  1584. {
  1585. $tmparray=dol_dir_list($dir,'files',0,$regexfilter,$excludefilter,'date',SORT_DESC,'',$nohook);
  1586. return $tmparray[0];
  1587. }
  1588. /**
  1589. * Security check when accessing to a document (used by document.php, viewimage.php and webservices)
  1590. *
  1591. * @param string $modulepart Module of document ('module', 'module_user_temp', 'module_user' or 'module_temp')
  1592. * @param string $original_file Relative path with filename
  1593. * @param string $entity Restrict onto entity
  1594. * @param User $fuser User object (forced)
  1595. * @param string $refname Ref of object to check permission for external users (autodetect if not provided)
  1596. * @return mixed Array with access information : accessallowed & sqlprotectagainstexternals & original_file (as full path name)
  1597. */
  1598. function dol_check_secure_access_document($modulepart,$original_file,$entity,$fuser='',$refname='')
  1599. {
  1600. global $user, $conf, $db;
  1601. if (! is_object($fuser)) $fuser=$user;
  1602. if (empty($modulepart)) return 'ErrorBadParameter';
  1603. if (empty($entity)) $entity=0;
  1604. dol_syslog('modulepart='.$modulepart.' original_file='.$original_file);
  1605. // We define $accessallowed and $sqlprotectagainstexternals
  1606. $accessallowed=0;
  1607. $sqlprotectagainstexternals='';
  1608. $ret=array();
  1609. // find the subdirectory name as the reference
  1610. if (empty($refname)) $refname=basename(dirname($original_file)."/");
  1611. // Wrapping for some images
  1612. if ($modulepart == 'companylogo')
  1613. {
  1614. $accessallowed=1;
  1615. $original_file=$conf->mycompany->dir_output.'/logos/'.$original_file;
  1616. }
  1617. // Wrapping for users photos
  1618. elseif ($modulepart == 'userphoto')
  1619. {
  1620. $accessallowed=1;
  1621. $original_file=$conf->user->dir_output.'/'.$original_file;
  1622. }
  1623. // Wrapping for members photos
  1624. elseif ($modulepart == 'memberphoto')
  1625. {
  1626. $accessallowed=1;
  1627. $original_file=$conf->adherent->dir_output.'/'.$original_file;
  1628. }
  1629. // Wrapping pour les apercu factures
  1630. elseif ($modulepart == 'apercufacture')
  1631. {
  1632. if ($fuser->rights->facture->lire) $accessallowed=1;
  1633. $original_file=$conf->facture->dir_output.'/'.$original_file;
  1634. }
  1635. // Wrapping pour les apercu propal
  1636. elseif ($modulepart == 'apercupropal')
  1637. {
  1638. if ($fuser->rights->propale->lire) $accessallowed=1;
  1639. $original_file=$conf->propal->dir_output.'/'.$original_file;
  1640. }
  1641. // Wrapping pour les apercu commande
  1642. elseif ($modulepart == 'apercucommande')
  1643. {
  1644. if ($fuser->rights->commande->lire) $accessallowed=1;
  1645. $original_file=$conf->commande->dir_output.'/'.$original_file;
  1646. }
  1647. // Wrapping pour les apercu intervention
  1648. elseif ($modulepart == 'apercufichinter')
  1649. {
  1650. if ($fuser->rights->ficheinter->lire) $accessallowed=1;
  1651. $original_file=$conf->ficheinter->dir_output.'/'.$original_file;
  1652. }
  1653. // Wrapping pour les images des stats propales
  1654. elseif ($modulepart == 'propalstats')
  1655. {
  1656. if ($fuser->rights->propale->lire) $accessallowed=1;
  1657. $original_file=$conf->propal->dir_temp.'/'.$original_file;
  1658. }
  1659. // Wrapping pour les images des stats commandes
  1660. elseif ($modulepart == 'orderstats')
  1661. {
  1662. if ($fuser->rights->commande->lire) $accessallowed=1;
  1663. $original_file=$conf->commande->dir_temp.'/'.$original_file;
  1664. }
  1665. elseif ($modulepart == 'orderstatssupplier')
  1666. {
  1667. if ($fuser->rights->fournisseur->commande->lire) $accessallowed=1;
  1668. $original_file=$conf->fournisseur->dir_output.'/commande/temp/'.$original_file;
  1669. }
  1670. // Wrapping pour les images des stats factures
  1671. elseif ($modulepart == 'billstats')
  1672. {
  1673. if ($fuser->rights->facture->lire) $accessallowed=1;
  1674. $original_file=$conf->facture->dir_temp.'/'.$original_file;
  1675. }
  1676. elseif ($modulepart == 'billstatssupplier')
  1677. {
  1678. if ($fuser->rights->fournisseur->facture->lire) $accessallowed=1;
  1679. $original_file=$conf->fournisseur->dir_output.'/facture/temp/'.$original_file;
  1680. }
  1681. // Wrapping pour les images des stats expeditions
  1682. elseif ($modulepart == 'expeditionstats')
  1683. {
  1684. if ($fuser->rights->expedition->lire) $accessallowed=1;
  1685. $original_file=$conf->expedition->dir_temp.'/'.$original_file;
  1686. }
  1687. // Wrapping pour les images des stats expeditions
  1688. elseif ($modulepart == 'tripsexpensesstats')
  1689. {
  1690. if ($fuser->rights->deplacement->lire) $accessallowed=1;
  1691. $original_file=$conf->deplacement->dir_temp.'/'.$original_file;
  1692. }
  1693. // Wrapping pour les images des stats expeditions
  1694. elseif ($modulepart == 'memberstats')
  1695. {
  1696. if ($fuser->rights->adherent->lire) $accessallowed=1;
  1697. $original_file=$conf->adherent->dir_temp.'/'.$original_file;
  1698. }
  1699. // Wrapping pour les images des stats produits
  1700. elseif (preg_match('/^productstats_/i',$modulepart))
  1701. {
  1702. if ($fuser->rights->produit->lire || $fuser->rights->service->lire) $accessallowed=1;
  1703. $original_file=(!empty($conf->product->multidir_temp[$entity])?$conf->product->multidir_temp[$entity]:$conf->service->multidir_temp[$entity]).'/'.$original_file;
  1704. }
  1705. // Wrapping for products or services
  1706. elseif ($modulepart == 'tax')
  1707. {
  1708. if ($fuser->rights->tax->charges->lire) $accessallowed=1;
  1709. $original_file=$conf->tax->dir_output.'/'.$original_file;
  1710. }
  1711. // Wrapping for products or services
  1712. elseif ($modulepart == 'actions')
  1713. {
  1714. if ($fuser->rights->agenda->myactions->read) $accessallowed=1;
  1715. $original_file=$conf->agenda->dir_output.'/'.$original_file;
  1716. }
  1717. // Wrapping for categories
  1718. elseif ($modulepart == 'category')
  1719. {
  1720. if ($fuser->rights->categorie->lire) $accessallowed=1;
  1721. $original_file=$conf->categorie->multidir_output[$entity].'/'.$original_file;
  1722. }
  1723. // Wrapping pour les prelevements
  1724. elseif ($modulepart == 'prelevement')
  1725. {
  1726. if ($fuser->rights->prelevement->bons->lire || preg_match('/^specimen/i',$original_file))
  1727. {
  1728. $accessallowed=1;
  1729. }
  1730. $original_file=$conf->prelevement->dir_output.'/'.$original_file;
  1731. }
  1732. // Wrapping pour les graph energie
  1733. elseif ($modulepart == 'graph_stock')
  1734. {
  1735. $accessallowed=1;
  1736. $original_file=$conf->stock->dir_temp.'/'.$original_file;
  1737. }
  1738. // Wrapping pour les graph fournisseurs
  1739. elseif ($modulepart == 'graph_fourn')
  1740. {
  1741. $accessallowed=1;
  1742. $original_file=$conf->fournisseur->dir_temp.'/'.$original_file;
  1743. }
  1744. // Wrapping pour les graph des produits
  1745. elseif ($modulepart == 'graph_product')
  1746. {
  1747. $accessallowed=1;
  1748. $original_file=$conf->product->multidir_temp[$entity].'/'.$original_file;
  1749. }
  1750. // Wrapping pour les code barre
  1751. elseif ($modulepart == 'barcode')
  1752. {
  1753. $accessallowed=1;
  1754. // If viewimage is called for barcode, we try to output an image on the fly,
  1755. // with not build of file on disk.
  1756. //$original_file=$conf->barcode->dir_temp.'/'.$original_file;
  1757. $original_file='';
  1758. }
  1759. // Wrapping pour les icones de background des mailings
  1760. elseif ($modulepart == 'iconmailing')
  1761. {
  1762. $accessallowed=1;
  1763. $original_file=$conf->mailing->dir_temp.'/'.$original_file;
  1764. }
  1765. // Wrapping pour les icones de background des mailings
  1766. elseif ($modulepart == 'scanner_user_temp')
  1767. {
  1768. $accessallowed=1;
  1769. $original_file=$conf->scanner->dir_temp.'/'.$fuser->id.'/'.$original_file;
  1770. }
  1771. // Wrapping pour les images fckeditor
  1772. elseif ($modulepart == 'fckeditor')
  1773. {
  1774. $accessallowed=1;
  1775. $original_file=$conf->fckeditor->dir_output.'/'.$original_file;
  1776. }
  1777. // Wrapping for third parties
  1778. else if ($modulepart == 'company' || $modulepart == 'societe')
  1779. {
  1780. if ($fuser->rights->societe->lire || preg_match('/^specimen/i',$original_file))
  1781. {
  1782. $accessallowed=1;
  1783. }
  1784. $original_file=$conf->societe->multidir_output[$entity].'/'.$original_file;
  1785. $sqlprotectagainstexternals = "SELECT rowid as fk_soc FROM ".MAIN_DB_PREFIX."societe WHERE rowid='".$db->escape($refname)."' AND entity IN (".getEntity('societe', 1).")";
  1786. }
  1787. // Wrapping for contact
  1788. else if ($modulepart == 'contact')
  1789. {
  1790. if ($fuser->rights->societe->lire)
  1791. {
  1792. $accessallowed=1;
  1793. }
  1794. $original_file=$conf->societe->multidir_output[$entity].'/contact/'.$original_file;
  1795. }
  1796. // Wrapping for invoices
  1797. else if ($modulepart == 'facture' || $modulepart == 'invoice')
  1798. {
  1799. if ($fuser->rights->facture->lire || preg_match('/^specimen/i',$original_file))
  1800. {
  1801. $accessallowed=1;
  1802. }
  1803. $original_file=$conf->facture->dir_output.'/'.$original_file;
  1804. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."facture WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  1805. }
  1806. else if ($modulepart == 'massfilesarea_facture')
  1807. {
  1808. if ($fuser->rights->facture->lire || preg_match('/^specimen/i',$original_file))
  1809. {
  1810. $accessallowed=1;
  1811. }
  1812. $original_file=$conf->facture->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
  1813. }
  1814. // Wrapping pour les fiches intervention
  1815. else if ($modulepart == 'ficheinter')
  1816. {
  1817. if ($fuser->rights->ficheinter->lire || preg_match('/^specimen/i',$original_file))
  1818. {
  1819. $accessallowed=1;
  1820. }
  1821. $original_file=$conf->ficheinter->dir_output.'/'.$original_file;
  1822. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."fichinter WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  1823. }
  1824. // Wrapping pour les deplacements et notes de frais
  1825. else if ($modulepart == 'deplacement')
  1826. {
  1827. if ($fuser->rights->deplacement->lire || preg_match('/^specimen/i',$original_file))
  1828. {
  1829. $accessallowed=1;
  1830. }
  1831. $original_file=$conf->deplacement->dir_output.'/'.$original_file;
  1832. //$sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."fichinter WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  1833. }
  1834. // Wrapping pour les propales
  1835. else if ($modulepart == 'propal')
  1836. {
  1837. if ($fuser->rights->propale->lire || preg_match('/^specimen/i',$original_file))
  1838. {
  1839. $accessallowed=1;
  1840. }
  1841. $original_file=$conf->propal->dir_output.'/'.$original_file;
  1842. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."propal WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  1843. }
  1844. // Wrapping pour les commandes
  1845. else if ($modulepart == 'commande' || $modulepart == 'order')
  1846. {
  1847. if ($fuser->rights->commande->lire || preg_match('/^specimen/i',$original_file))
  1848. {
  1849. $accessallowed=1;
  1850. }
  1851. $original_file=$conf->commande->dir_output.'/'.$original_file;
  1852. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."commande WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  1853. }
  1854. // Wrapping pour les projets
  1855. else if ($modulepart == 'project')
  1856. {
  1857. if ($fuser->rights->projet->lire || preg_match('/^specimen/i',$original_file))
  1858. {
  1859. $accessallowed=1;
  1860. }
  1861. $original_file=$conf->projet->dir_output.'/'.$original_file;
  1862. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."projet WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  1863. }
  1864. else if ($modulepart == 'project_task')
  1865. {
  1866. if ($fuser->rights->projet->lire || preg_match('/^specimen/i',$original_file))
  1867. {
  1868. $accessallowed=1;
  1869. }
  1870. $original_file=$conf->projet->dir_output.'/'.$original_file;
  1871. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."projet WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  1872. }
  1873. // Wrapping for interventions
  1874. else if ($modulepart == 'fichinter')
  1875. {
  1876. if ($fuser->rights->ficheinter->lire || preg_match('/^specimen/i',$original_file))
  1877. {
  1878. $accessallowed=1;
  1879. }
  1880. $original_file=$conf->ficheinter->dir_output.'/'.$original_file;
  1881. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."fichinter WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  1882. }
  1883. // Wrapping pour les commandes fournisseurs
  1884. else if ($modulepart == 'commande_fournisseur' || $modulepart == 'order_supplier')
  1885. {
  1886. if ($fuser->rights->fournisseur->commande->lire || preg_match('/^specimen/i',$original_file))
  1887. {
  1888. $accessallowed=1;
  1889. }
  1890. $original_file=$conf->fournisseur->commande->dir_output.'/'.$original_file;
  1891. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."commande_fournisseur WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  1892. }
  1893. // Wrapping pour les factures fournisseurs
  1894. else if ($modulepart == 'facture_fournisseur' || $modulepart == 'invoice_supplier')
  1895. {
  1896. if ($fuser->rights->fournisseur->facture->lire || preg_match('/^specimen/i',$original_file))
  1897. {
  1898. $accessallowed=1;
  1899. }
  1900. $original_file=$conf->fournisseur->facture->dir_output.'/'.$original_file;
  1901. $sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."facture_fourn WHERE facnumber='".$db->escape($refname)."' AND entity=".$conf->entity;
  1902. }
  1903. // Wrapping pour les rapport de paiements
  1904. else if ($modulepart == 'facture_paiement')
  1905. {
  1906. if ($fuser->rights->facture->lire || preg_match('/^specimen/i',$original_file))
  1907. {
  1908. $accessallowed=1;
  1909. }
  1910. if ($fuser->societe_id > 0) $original_file=$conf->facture->dir_output.'/payments/private/'.$fuser->id.'/'.$original_file;
  1911. else $original_file=$conf->facture->dir_output.'/payments/'.$original_file;
  1912. }
  1913. // Wrapping for accounting exports
  1914. else if ($modulepart == 'export_compta')
  1915. {
  1916. if ($fuser->rights->accounting->ventilation->dispatch || preg_match('/^specimen/i',$original_file))
  1917. {
  1918. $accessallowed=1;
  1919. }
  1920. $original_file=$conf->accounting->dir_output.'/'.$original_file;
  1921. }
  1922. // Wrapping pour les expedition
  1923. else if ($modulepart == 'expedition')
  1924. {
  1925. if ($fuser->rights->expedition->lire || preg_match('/^specimen/i',$original_file))
  1926. {
  1927. $accessallowed=1;
  1928. }
  1929. $original_file=$conf->expedition->dir_output."/sending/".$original_file;
  1930. }
  1931. // Wrapping pour les bons de livraison
  1932. else if ($modulepart == 'livraison')
  1933. {
  1934. if ($fuser->rights->expedition->livraison->lire || preg_match('/^specimen/i',$original_file))
  1935. {
  1936. $accessallowed=1;
  1937. }
  1938. $original_file=$conf->expedition->dir_output."/receipt/".$original_file;
  1939. }
  1940. // Wrapping pour les actions
  1941. else if ($modulepart == 'actions')
  1942. {
  1943. if ($fuser->rights->agenda->myactions->read || preg_match('/^specimen/i',$original_file))
  1944. {
  1945. $accessallowed=1;
  1946. }
  1947. $original_file=$conf->agenda->dir_output.'/'.$original_file;
  1948. }
  1949. // Wrapping pour les actions
  1950. else if ($modulepart == 'actionsreport')
  1951. {
  1952. if ($fuser->rights->agenda->allactions->read || preg_match('/^specimen/i',$original_file))
  1953. {
  1954. $accessallowed=1;
  1955. }
  1956. $original_file = $conf->agenda->dir_temp."/".$original_file;
  1957. }
  1958. // Wrapping pour les produits et services
  1959. else if ($modulepart == 'product' || $modulepart == 'produit' || $modulepart == 'service')
  1960. {
  1961. if (($fuser->rights->produit->lire || $fuser->rights->service->lire) || preg_match('/^specimen/i',$original_file))
  1962. {
  1963. $accessallowed=1;
  1964. }
  1965. if (! empty($conf->product->enabled)) $original_file=$conf->product->multidir_output[$entity].'/'.$original_file;
  1966. elseif (! empty($conf->service->enabled)) $original_file=$conf->service->multidir_output[$entity].'/'.$original_file;
  1967. }
  1968. // Wrapping pour les contrats
  1969. else if ($modulepart == 'contract')
  1970. {
  1971. if ($fuser->rights->contrat->lire || preg_match('/^specimen/i',$original_file))
  1972. {
  1973. $accessallowed=1;
  1974. }
  1975. $original_file=$conf->contrat->dir_output.'/'.$original_file;
  1976. }
  1977. // Wrapping pour les dons
  1978. else if ($modulepart == 'donation')
  1979. {
  1980. if ($fuser->rights->don->lire || preg_match('/^specimen/i',$original_file))
  1981. {
  1982. $accessallowed=1;
  1983. }
  1984. $original_file=$conf->don->dir_output.'/'.$original_file;
  1985. }
  1986. // Wrapping pour les remises de cheques
  1987. else if ($modulepart == 'remisecheque')
  1988. {
  1989. if ($fuser->rights->banque->lire || preg_match('/^specimen/i',$original_file))
  1990. {
  1991. $accessallowed=1;
  1992. }
  1993. $original_file=$conf->banque->dir_output.'/bordereau/'.$original_file; // original_file should contains relative path so include the get_exdir result
  1994. }
  1995. // Wrapping for bank
  1996. else if ($modulepart == 'bank')
  1997. {
  1998. if ($fuser->rights->banque->lire)
  1999. {
  2000. $accessallowed=1;
  2001. }
  2002. $original_file=$conf->bank->dir_output.'/'.$original_file;
  2003. }
  2004. // Wrapping for export module
  2005. else if ($modulepart == 'export')
  2006. {
  2007. // Aucun test necessaire car on force le rep de download sur
  2008. // le rep export qui est propre a l'utilisateur
  2009. $accessallowed=1;
  2010. $original_file=$conf->export->dir_temp.'/'.$fuser->id.'/'.$original_file;
  2011. }
  2012. // Wrapping for import module
  2013. else if ($modulepart == 'import')
  2014. {
  2015. $accessallowed=1;
  2016. $original_file=$conf->import->dir_temp.'/'.$original_file;
  2017. }
  2018. // Wrapping pour l'editeur wysiwyg
  2019. else if ($modulepart == 'editor')
  2020. {
  2021. $accessallowed=1;
  2022. $original_file=$conf->fckeditor->dir_output.'/'.$original_file;
  2023. }
  2024. // Wrapping for miscellaneous medias files
  2025. elseif ($modulepart == 'medias')
  2026. {
  2027. $accessallowed=1;
  2028. global $dolibarr_main_data_root;
  2029. $original_file=$dolibarr_main_data_root.'/medias/'.$original_file;
  2030. }
  2031. // Wrapping for backups
  2032. else if ($modulepart == 'systemtools')
  2033. {
  2034. if ($fuser->admin)
  2035. {
  2036. $accessallowed=1;
  2037. }
  2038. $original_file=$conf->admin->dir_output.'/'.$original_file;
  2039. }
  2040. // Wrapping for upload file test
  2041. else if ($modulepart == 'admin_temp')
  2042. {
  2043. if ($fuser->admin)
  2044. $accessallowed=1;
  2045. $original_file=$conf->admin->dir_temp.'/'.$original_file;
  2046. }
  2047. // Wrapping pour BitTorrent
  2048. else if ($modulepart == 'bittorrent')
  2049. {
  2050. $accessallowed=1;
  2051. $dir='files';
  2052. if (dol_mimetype($original_file) == 'application/x-bittorrent') $dir='torrents';
  2053. $original_file=$conf->bittorrent->dir_output.'/'.$dir.'/'.$original_file;
  2054. }
  2055. // Wrapping pour Foundation module
  2056. else if ($modulepart == 'member')
  2057. {
  2058. if ($fuser->rights->adherent->lire || preg_match('/^specimen/i',$original_file))
  2059. {
  2060. $accessallowed=1;
  2061. }
  2062. $original_file=$conf->adherent->dir_output.'/'.$original_file;
  2063. }
  2064. // Wrapping for Scanner
  2065. else if ($modulepart == 'scanner_user_temp')
  2066. {
  2067. $accessallowed=1;
  2068. $original_file=$conf->scanner->dir_temp.'/'.$fuser->id.'/'.$original_file;
  2069. }
  2070. // GENERIC Wrapping
  2071. // If modulepart=module_user_temp Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/temp/iduser
  2072. // If modulepart=module_temp Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/temp
  2073. // If modulepart=module_user Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/iduser
  2074. // If modulepart=module Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart
  2075. else
  2076. {
  2077. // Define $accessallowed
  2078. if (preg_match('/^([a-z]+)_user_temp$/i',$modulepart,$reg))
  2079. {
  2080. if ($fuser->rights->{$reg[1]}->lire || $fuser->rights->{$reg[1]}->read || ($fuser->rights->{$reg[1]}->download)) $accessallowed=1;
  2081. $original_file=$conf->{$reg[1]}->dir_temp.'/'.$fuser->id.'/'.$original_file;
  2082. }
  2083. else if (preg_match('/^([a-z]+)_temp$/i',$modulepart,$reg))
  2084. {
  2085. if ($fuser->rights->{$reg[1]}->lire || $fuser->rights->{$reg[1]}->read || ($fuser->rights->{$reg[1]}->download)) $accessallowed=1;
  2086. $original_file=$conf->{$reg[1]}->dir_temp.'/'.$original_file;
  2087. }
  2088. else if (preg_match('/^([a-z]+)_user$/i',$modulepart,$reg))
  2089. {
  2090. if ($fuser->rights->{$reg[1]}->lire || $fuser->rights->{$reg[1]}->read || ($fuser->rights->{$reg[1]}->download)) $accessallowed=1;
  2091. $original_file=$conf->{$reg[1]}->dir_output.'/'.$fuser->id.'/'.$original_file;
  2092. }
  2093. else
  2094. {
  2095. if (empty($conf->$modulepart->dir_output)) // modulepart not supported
  2096. {
  2097. dol_print_error('','Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')');
  2098. exit;
  2099. }
  2100. $perm=GETPOST('perm');
  2101. $subperm=GETPOST('subperm');
  2102. if ($perm || $subperm)
  2103. {
  2104. if (($perm && ! $subperm && $fuser->rights->$modulepart->$perm) || ($perm && $subperm && $fuser->rights->$modulepart->$perm->$subperm)) $accessallowed=1;
  2105. $original_file=$conf->$modulepart->dir_output.'/'.$original_file;
  2106. }
  2107. else
  2108. {
  2109. if ($fuser->rights->$modulepart->lire || $fuser->rights->$modulepart->read) $accessallowed=1;
  2110. $original_file=$conf->$modulepart->dir_output.'/'.$original_file;
  2111. }
  2112. }
  2113. if (preg_match('/^specimen/i',$original_file)) $accessallowed=1; // If link to a specimen
  2114. if ($fuser->admin) $accessallowed=1; // If user is admin
  2115. // For modules who wants to manage different levels of permissions for documents
  2116. $subPermCategoryConstName = strtoupper($modulepart).'_SUBPERMCATEGORY_FOR_DOCUMENTS';
  2117. if (! empty($conf->global->$subPermCategoryConstName))
  2118. {
  2119. $subPermCategory = $conf->global->$subPermCategoryConstName;
  2120. if (! empty($subPermCategory) && (($fuser->rights->$modulepart->$subPermCategory->lire) || ($fuser->rights->$modulepart->$subPermCategory->read) || ($fuser->rights->$modulepart->$subPermCategory->download)))
  2121. {
  2122. $accessallowed=1;
  2123. }
  2124. }
  2125. // Define $sqlprotectagainstexternals for modules who want to protect access using a SQL query.
  2126. $sqlProtectConstName = strtoupper($modulepart).'_SQLPROTECTAGAINSTEXTERNALS_FOR_DOCUMENTS';
  2127. if (! empty($conf->global->$sqlProtectConstName)) // If module want to define its own $sqlprotectagainstexternals
  2128. {
  2129. // Example: mymodule__SQLPROTECTAGAINSTEXTERNALS_FOR_DOCUMENTS = "SELECT fk_soc FROM ".MAIN_DB_PREFIX.$modulepart." WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
  2130. eval('$sqlprotectagainstexternals = "'.$conf->global->$sqlProtectConstName.'";');
  2131. }
  2132. }
  2133. $ret = array(
  2134. 'accessallowed' => $accessallowed,
  2135. 'sqlprotectagainstexternals'=>$sqlprotectagainstexternals,
  2136. 'original_file'=>$original_file
  2137. );
  2138. return $ret;
  2139. }
  2140. /**
  2141. * Store object in file
  2142. *
  2143. * @param string $directory Directory of cache
  2144. * @param string $filename Name of filecache
  2145. * @param mixed $object Object to store in cachefile
  2146. * @return void
  2147. */
  2148. function dol_filecache($directory, $filename, $object)
  2149. {
  2150. if (! dol_is_dir($directory)) dol_mkdir($directory);
  2151. $cachefile = $directory . $filename;
  2152. file_put_contents($cachefile, serialize($object), LOCK_EX);
  2153. @chmod($cachefile, 0644);
  2154. }
  2155. /**
  2156. * Test if Refresh needed
  2157. *
  2158. * @param string $directory Directory of cache
  2159. * @param string $filename Name of filecache
  2160. * @param int $cachetime Cachetime delay
  2161. * @return boolean 0 no refresh 1 if refresh needed
  2162. */
  2163. function dol_cache_refresh($directory, $filename, $cachetime)
  2164. {
  2165. $now = dol_now();
  2166. $cachefile = $directory . $filename;
  2167. $refresh = !file_exists($cachefile) || ($now-$cachetime) > dol_filemtime($cachefile);
  2168. return $refresh;
  2169. }
  2170. /**
  2171. * Read object from cachefile
  2172. *
  2173. * @param string $directory Directory of cache
  2174. * @param string $filename Name of filecache
  2175. * @return mixed Unserialise from file
  2176. */
  2177. function dol_readcachefile($directory, $filename)
  2178. {
  2179. $cachefile = $directory . $filename;
  2180. $object = unserialize(file_get_contents($cachefile));
  2181. return $object;
  2182. }