PageRenderTime 62ms CodeModel.GetById 10ms RepoModel.GetById 1ms app.codeStats 0ms

/htdocs/core/lib/functions.lib.php

https://github.com/asterix14/dolibarr
PHP | 4480 lines | 2707 code | 400 blank | 1373 comment | 930 complexity | 1cdd3126dd381b0536d2d331e41c8c37 MD5 | raw file
Possible License(s): LGPL-2.0
  1. <?php
  2. /* Copyright (C) 2000-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2003 Jean-Louis Bergamo <jlb@j1b.org>
  4. * Copyright (C) 2004-2011 Laurent Destailleur <eldy@users.sourceforge.net>
  5. * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
  6. * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
  7. * Copyright (C) 2004 Christophe Combelles <ccomb@free.fr>
  8. * Copyright (C) 2005-2010 Regis Houssin <regis@dolibarr.fr>
  9. * Copyright (C) 2008 Raphael Bertrand (Resultic) <raphael.bertrand@resultic.fr>
  10. * Copyright (C) 2010-2011 Juanjo Menent <jmenent@2byte.es>
  11. *
  12. * This program is free software; you can redistribute it and/or modify
  13. * it under the terms of the GNU General Public License as published by
  14. * the Free Software Foundation; either version 2 of the License, or
  15. * (at your option) any later version.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU General Public License
  23. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  24. * or see http://www.gnu.org/
  25. */
  26. /**
  27. * \file htdocs/core/lib/functions.lib.php
  28. * \brief A set of functions for Dolibarr
  29. * This file contains all frequently used functions.
  30. */
  31. if (! function_exists('json_encode'))
  32. {
  33. /**
  34. * Implement json_encode for PHP that does not support it
  35. *
  36. * @param mixed $elements PHP Object to json encode
  37. * @return string Json encoded string
  38. */
  39. function json_encode($elements)
  40. {
  41. $num = count($elements);
  42. // determine type
  43. if (is_numeric(key($elements)))
  44. {
  45. // indexed (list)
  46. $output = '[';
  47. for ($i = 0, $last = ($num - 1); isset($elements[$i]); ++$i)
  48. {
  49. if (is_array($elements[$i])) $output.= json_encode($elements[$i]);
  50. else $output .= _val($elements[$i]);
  51. if($i !== $last) $output.= ',';
  52. }
  53. $output.= ']';
  54. }
  55. else
  56. {
  57. // associative (object)
  58. $output = '{';
  59. $last = $num - 1;
  60. $i = 0;
  61. foreach($elements as $key => $value)
  62. {
  63. $output .= '"'.$key.'":';
  64. if (is_array($value)) $output.= json_encode($value);
  65. else $output .= _val($value);
  66. if ($i !== $last) $output.= ',';
  67. ++$i;
  68. }
  69. $output.= '}';
  70. }
  71. // return
  72. return $output;
  73. }
  74. function _val($val)
  75. {
  76. if (is_string($val)) return '"'.rawurlencode($val).'"';
  77. elseif (is_int($val)) return sprintf('%d', $val);
  78. elseif (is_float($val)) return sprintf('%F', $val);
  79. elseif (is_bool($val)) return ($val ? 'true' : 'false');
  80. else return 'null';
  81. }
  82. }
  83. if (! function_exists('json_decode'))
  84. {
  85. /**
  86. * Implement json_decode for PHP that does not support it
  87. *
  88. * @param string $json Json encoded to PHP Object or Array
  89. * @param bool $assoc False return an object, true return an array
  90. * @return mixed Object or Array
  91. */
  92. function json_decode($json, $assoc=false)
  93. {
  94. $comment = false;
  95. $strLength = dol_strlen($json);
  96. for ($i=0; $i<$strLength; $i++)
  97. {
  98. if (! $comment)
  99. {
  100. if (($json[$i] == '{') || ($json[$i] == '[')) $out.= 'array(';
  101. else if (($json[$i] == '}') || ($json[$i] == ']')) $out.= ')';
  102. else if ($json[$i] == ':') $out.= ' => ';
  103. else $out.= $json[$i];
  104. }
  105. else $out.= $json[$i];
  106. if ($json[$i] == '"' && $json[($i-1)]!="\\") $comment = !$comment;
  107. }
  108. // Return an array
  109. eval('$array = '.$out.';');
  110. // Return an object
  111. if (! $assoc)
  112. {
  113. if (! empty($array))
  114. {
  115. $object = false;
  116. foreach ($array as $key => $value)
  117. {
  118. $object->{$key} = $value;
  119. }
  120. return $object;
  121. }
  122. return false;
  123. }
  124. return $array;
  125. }
  126. }
  127. /**
  128. * Return a DoliDB instance (database handler).
  129. *
  130. * @param string $type Type of database (mysql, pgsql...)
  131. * @param string $host Address of database server
  132. * @param string $user Nom de l'utilisateur autorise
  133. * @param string $pass Mot de passe
  134. * @param string $name Nom de la database
  135. * @param int $port Port of database server
  136. * @return DoliDB A DoliDB instance
  137. */
  138. function getDoliDBInstance($type, $host, $user, $pass, $name, $port)
  139. {
  140. require_once(DOL_DOCUMENT_ROOT ."/core/db/".$type.".class.php");
  141. $class='DoliDB'.ucfirst($type);
  142. $dolidb=new $class($type, $host, $user, $pass, $name, $port);
  143. return $dolidb;
  144. }
  145. /**
  146. * Function called at end of web php process
  147. *
  148. * @return void
  149. */
  150. function dol_shutdown()
  151. {
  152. global $conf,$user,$langs,$db;
  153. $disconnectdone=false;
  154. if (is_object($db) && ! empty($db->connected)) $disconnectdone=$db->close();
  155. dol_syslog("--- End access to ".$_SERVER["PHP_SELF"].($disconnectdone?' (Warn: db disconnection forced)':''), ($disconnectdone?LOG_WARNING:LOG_DEBUG));
  156. }
  157. /**
  158. * Return value of a param into GET or POST supervariable
  159. *
  160. * @param string $paramname Name of parameter to found
  161. * @param string $check Type of check (''=no check, 'int'=check it's numeric, 'alpha'=check it's alpha only)
  162. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  163. * @return string Value found or '' if check fails
  164. */
  165. function GETPOST($paramname,$check='',$method=0)
  166. {
  167. if (empty($method)) $out = isset($_GET[$paramname])?$_GET[$paramname]:(isset($_POST[$paramname])?$_POST[$paramname]:'');
  168. elseif ($method==1) $out = isset($_GET[$paramname])?$_GET[$paramname]:'';
  169. elseif ($method==2) $out = isset($_POST[$paramname])?$_POST[$paramname]:'';
  170. elseif ($method==3) $out = isset($_POST[$paramname])?$_POST[$paramname]:(isset($_GET[$paramname])?$_GET[$paramname]:'');
  171. if (!empty($check))
  172. {
  173. // Check if numeric
  174. if ($check == 'int' && ! preg_match('/^[\.,0-9]+$/i',trim($out))) $out='';
  175. // Check if alpha
  176. //if ($check == 'alpha' && ! preg_match('/^[ =:@#\/\\\(\)\-\._a-z0-9]+$/i',trim($out))) $out='';
  177. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  178. if ($check == 'alpha' && preg_match('/"/',trim($out))) $out='';
  179. }
  180. return $out;
  181. }
  182. /**
  183. * Return a prefix to use for this Dolibarr instance for session or cookie names.
  184. * This prefix is unique for instance and avoid conflict between multi-instances,
  185. * even when having two instances with one root dir or two instances in virtual servers
  186. *
  187. * @return string A calculated prefix
  188. */
  189. function dol_getprefix()
  190. {
  191. return dol_hash($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  192. }
  193. /**
  194. * Make an include_once using default root and alternate root if it fails.
  195. * WARNING: In most cases, you should not use this function:
  196. * To link to a core file, use include(DOL_DOCUMENT_ROOT.'/pathtofile')
  197. * To link to a module file from a module file, use include('./mymodulefile');
  198. * To link to a module file from a core file, then this function can be used
  199. *
  200. * @param string $relpath Relative path to file (Ie: mydir/myfile, ../myfile, ...)
  201. * @return int false if include fails.
  202. */
  203. function dol_include_once($relpath)
  204. {
  205. global $conf,$langs,$user,$mysoc; // Other global var must be retreived with $GLOBALS['var']
  206. return @include_once(dol_buildpath($relpath));
  207. }
  208. /**
  209. * Return path of url or filesystem. Return default_root or alternate root if file_exist fails
  210. *
  211. * @param string $path Relative path to file (if mode=0, ie: mydir/myfile, ../myfile, ...) or relative url (if mode=1).
  212. * @param int $type 0=Used for a Filesystem path, 1=Used for an URL path (output relative), 2=Used for an URL path (output full path)
  213. * @return string Full filsystem path (if mode=0), Full url path (if mode=1)
  214. */
  215. function dol_buildpath($path,$type=0)
  216. {
  217. if (empty($type)) // For a filesystem path
  218. {
  219. $res = DOL_DOCUMENT_ROOT.$path; // Standard value
  220. if (defined('DOL_DOCUMENT_ROOT_ALT') && DOL_DOCUMENT_ROOT_ALT) // We check only if alternate feature is used
  221. {
  222. if (! file_exists(DOL_DOCUMENT_ROOT.$path)) $res = DOL_DOCUMENT_ROOT_ALT.$path;
  223. }
  224. }
  225. else // For an url path
  226. {
  227. // We try to get local path of file on filesystem from url
  228. // Note that trying to know if a file on disk exist by forging path on disk from url
  229. // works only for some web server and some setup. This is bugged when
  230. // using proxy, rewriting, virtual path, etc...
  231. if ($type == 1)
  232. {
  233. $res = DOL_URL_ROOT.$path; // Standard value
  234. if (defined('DOL_URL_ROOT_ALT') && DOL_URL_ROOT_ALT) // We check only if alternate feature is used
  235. {
  236. preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i',$path,$regs); // Take part before '?'
  237. if (! empty($regs[1]))
  238. {
  239. if (! file_exists(DOL_DOCUMENT_ROOT.$regs[1])) $res = DOL_URL_ROOT_ALT.$path;
  240. }
  241. }
  242. }
  243. if ($type == 2)
  244. {
  245. $res = DOL_MAIN_URL_ROOT.$path; // Standard value
  246. if (defined('DOL_URL_ROOT_ALT') && DOL_URL_ROOT_ALT) // We check only if alternate feature is used
  247. {
  248. preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i',$path,$regs); // Take part before '?'
  249. if (! empty($regs[1]))
  250. {
  251. if (! file_exists(DOL_DOCUMENT_ROOT.$regs[1])) $res = DOL_MAIN_URL_ROOT_ALT.$path;
  252. }
  253. }
  254. }
  255. }
  256. return $res;
  257. }
  258. /**
  259. * Create a clone of instance of object (new instance with same properties)
  260. * This function works for both PHP4 and PHP5
  261. *
  262. * @param object $object Object to clone
  263. * @return object Object clone
  264. */
  265. function dol_clone($object)
  266. {
  267. dol_syslog("Functions.lib::dol_clone Clone object");
  268. // We create dynamically a clone function, making a =
  269. if (version_compare(phpversion(), '5.0') < 0 && ! function_exists('clone'))
  270. {
  271. eval('function clone($object){return($object);}');
  272. }
  273. $myclone=clone($object);
  274. return $myclone;
  275. }
  276. /**
  277. * Optimize a size for some browsers (phone, smarphone, ...)
  278. *
  279. * @param int $size Size we want
  280. * @param string $type Type of optimizing:
  281. * '' = function used to define a size for truncation
  282. * 'width' = function is used to define a width
  283. * @return int New size after optimizing
  284. */
  285. function dol_size($size,$type='')
  286. {
  287. global $conf;
  288. if (empty($conf->browser->phone)) return $size;
  289. if ($type == 'width' && $size > 250) return 250;
  290. else return 10;
  291. }
  292. /**
  293. * Return date for now. We should always use this function without parameters (that means GMT time)
  294. *
  295. * @param string $mode 'gmt' => we return GMT timestamp,
  296. * 'tzserver' => we add the PHP server timezone
  297. * 'tzref' => we add the company timezone
  298. * 'tzuser' => we add the user timezone
  299. * @return timestamp $date Timestamp
  300. */
  301. function dol_now($mode='gmt')
  302. {
  303. // Note that gmmktime and mktime return same value (GMT) whithout parameters
  304. if ($mode == 'gmt') $ret=gmmktime(); // Time for now at greenwich.
  305. else if ($mode == 'tzserver') // Time for now with PHP server timezone added
  306. {
  307. $tzsecond=-dol_mktime(0,0,0,1,1,1970);
  308. $ret=gmmktime()+$tzsecond;
  309. }
  310. else if ($mode == 'tzref') // Time for now where parent company timezone is added
  311. {
  312. // TODO Should add the company timezone
  313. $ret=gmmktime();
  314. }
  315. else if ($mode == 'tzuser') // Time for now where user timezone is added
  316. {
  317. //print 'eeee'.time().'-'.mktime().'-'.gmmktime();
  318. $tzhour=isset($_SESSION['dol_tz'])?$_SESSION['dol_tz']:0;
  319. $ret=gmmktime()+($tzhour*60*60);
  320. }
  321. return $ret;
  322. }
  323. /**
  324. * Clean a string to use it as a file name
  325. *
  326. * @param string $str String to clean
  327. * @param string $newstr String to replace bad chars with
  328. * @return string String cleaned (a-zA-Z_)
  329. *
  330. * @see dol_string_nospecial, dol_string_unaccent
  331. */
  332. function dol_sanitizeFileName($str,$newstr='_')
  333. {
  334. global $conf;
  335. return dol_string_nospecial(dol_string_unaccent($str),$newstr,$conf->filesystem_forbidden_chars);
  336. }
  337. /**
  338. * Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName
  339. *
  340. * @param string $str String to clean
  341. * @return string Cleaned string
  342. *
  343. * @see dol_sanitizeFilename, dol_string_nospecial
  344. */
  345. function dol_string_unaccent($str)
  346. {
  347. if (utf8_check($str))
  348. {
  349. $string = rawurlencode($str);
  350. $replacements = array(
  351. '%C3%80' => 'A','%C3%81' => 'A',
  352. '%C3%88' => 'E','%C3%89' => 'E',
  353. '%C3%8C' => 'I','%C3%8D' => 'I',
  354. '%C3%92' => 'O','%C3%93' => 'O',
  355. '%C3%99' => 'U','%C3%9A' => 'U',
  356. '%C3%A0' => 'a','%C3%A1' => 'a','%C3%A2' => 'a',
  357. '%C3%A8' => 'e','%C3%A9' => 'e','%C3%AA' => 'e','%C3%AB' => 'e',
  358. '%C3%AC' => 'i','%C3%AD' => 'i','%C3%AE' => 'i',
  359. '%C3%B2' => 'o','%C3%B3' => 'o',
  360. '%C3%B9' => 'u','%C3%BA' => 'u'
  361. );
  362. $string=strtr($string, $replacements);
  363. return rawurldecode($string);
  364. }
  365. else
  366. {
  367. $string = strtr($str,
  368. "\xC0\xC1\xC2\xC3\xC5\xC7
  369. \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
  370. \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
  371. \xE0\xE1\xE2\xE3\xE5\xE7\xE8\xE9\xEA\xEB
  372. \xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
  373. \xF9\xFA\xFB\xFD\xFF",
  374. "AAAAAC
  375. EEEEIIIIDN
  376. OOOOOUUUY
  377. aaaaaceeee
  378. iiiidnooooo
  379. uuuyy");
  380. $string = strtr($string, array("\xC4"=>"Ae", "\xC6"=>"AE", "\xD6"=>"Oe", "\xDC"=>"Ue", "\xDE"=>"TH", "\xDF"=>"ss", "\xE4"=>"ae", "\xE6"=>"ae", "\xF6"=>"oe", "\xFC"=>"ue", "\xFE"=>"th"));
  381. return $string;
  382. }
  383. }
  384. /**
  385. * Clean a string from all punctuation characters to use it as a ref or login
  386. *
  387. * @param string $str String to clean
  388. * @param string $newstr String to replace forbidden chars with
  389. * @param array $badchars List of forbidden characters
  390. * @return string Cleaned string
  391. *
  392. * @see dol_sanitizeFilename, dol_string_unaccent
  393. */
  394. function dol_string_nospecial($str,$newstr='_',$badchars='')
  395. {
  396. $forbidden_chars_to_replace=array(" ","'","/","\\",":","*","?","\"","<",">","|","[","]",",",";","=");
  397. $forbidden_chars_to_remove=array();
  398. if (is_array($badchars)) $forbidden_chars_to_replace=$badchars;
  399. //$forbidden_chars_to_remove=array("(",")");
  400. return str_replace($forbidden_chars_to_replace,$newstr,str_replace($forbidden_chars_to_remove,"",$str));
  401. }
  402. /**
  403. * Returns text escaped for inclusion into javascript code
  404. *
  405. * @param string $stringtoescape String to escape
  406. * @return string Escaped string
  407. */
  408. function dol_escape_js($stringtoescape)
  409. {
  410. // escape quotes and backslashes, newlines, etc.
  411. $substitjs=array("&#039;"=>"\\'",'\\'=>'\\\\',"'"=>"\\'",'"'=>"\\'","\r"=>'\\r',"\n"=>'\\n','</'=>'<\/');
  412. return strtr($stringtoescape, $substitjs);
  413. }
  414. /**
  415. * Returns text escaped for inclusion in HTML alt or title tags
  416. *
  417. * @param string $stringtoescape String to escape
  418. * @param int $keepb Do not clean b tags
  419. * @return string Escaped string
  420. */
  421. function dol_escape_htmltag($stringtoescape,$keepb=0)
  422. {
  423. // escape quotes and backslashes, newlines, etc.
  424. $tmp=dol_html_entity_decode($stringtoescape,ENT_COMPAT,'UTF-8');
  425. if ($keepb) $tmp=strtr($tmp, array('"'=>'',"\r"=>'\\r',"\n"=>'\\n'));
  426. else $tmp=strtr($tmp, array('"'=>'',"\r"=>'\\r',"\n"=>'\\n',"<b>"=>'','</b>'=>''));
  427. return dol_htmlentities($tmp,ENT_COMPAT,'UTF-8');
  428. }
  429. /**
  430. * Write log message into outputs. Possible outputs can be:
  431. * A file if SYSLOG_FILE_ON defined: file name is then defined by SYSLOG_FILE
  432. * Syslog if SYSLOG_SYSLOG_ON defined: facility is then defined by SYSLOG_FACILITY
  433. * Warning, les fonctions syslog sont buggues sous Windows et generent des
  434. * fautes de protection memoire. Pour resoudre, utiliser le loggage fichier,
  435. * au lieu du loggage syslog (configuration du module).
  436. * Note: If SYSLOG_FILE_NO_ERROR defined, we never output error message when writing to log fails.
  437. *
  438. * This function works only if syslog module is enabled.
  439. * This must not use any call to other function calling dol_syslog (avoid infinite loop).
  440. *
  441. * @param string $message Line to log. Ne doit pas etre traduit si level = LOG_ERR
  442. * @param int $level Log level
  443. * On Windows LOG_ERR=4, LOG_WARNING=5, LOG_NOTICE=LOG_INFO=6, LOG_DEBUG=6 si define_syslog_variables ou PHP 5.3+, 7 si dolibarr
  444. * On Linux LOG_ERR=3, LOG_WARNING=4, LOG_INFO=6, LOG_DEBUG=7
  445. * @return void
  446. */
  447. function dol_syslog($message, $level=LOG_INFO)
  448. {
  449. global $conf,$user,$langs,$_REQUEST;
  450. // If adding log inside HTML page is required
  451. if (! empty($_REQUEST['logtohtml']) && ! empty($conf->global->MAIN_LOGTOHTML))
  452. {
  453. $conf->logbuffer[]=dol_print_date(time(),"%Y-%m-%d %H:%M:%S")." ".$message;
  454. }
  455. // If syslog module enabled
  456. if (! empty($conf->syslog->enabled))
  457. {
  458. //print $level.' - '.$conf->global->SYSLOG_LEVEL.' - '.$conf->syslog->enabled." \n";
  459. if ($level > $conf->global->SYSLOG_LEVEL) return;
  460. // Translate error message if this is an error message (rare) and langs is loaded
  461. if ($level == LOG_ERR)
  462. {
  463. if (is_object($langs))
  464. {
  465. $langs->load("errors");
  466. if ($message != $langs->trans($message)) $message = $langs->trans($message);
  467. }
  468. }
  469. // Add page/script name to log message
  470. $script=isset($_SERVER['PHP_SELF'])?basename($_SERVER['PHP_SELF'],'.php').' ':'';
  471. $message=$script.$message;
  472. // Add user to log message
  473. $login='nologin';
  474. if (is_object($user) && $user->id) $login=$user->login;
  475. $message=sprintf("%-8s",$login)." ".$message;
  476. // Check if log is to a file (SYSLOG_FILE_ON defined)
  477. if (defined("SYSLOG_FILE_ON") && constant("SYSLOG_FILE_ON"))
  478. {
  479. $filelog=SYSLOG_FILE;
  480. $filelog=preg_replace('/DOL_DATA_ROOT/i',DOL_DATA_ROOT,$filelog);
  481. //print "filelog=".$filelog."\n";
  482. if (defined("SYSLOG_FILE_NO_ERROR")) $file=@fopen($filelog,"a+");
  483. else $file=fopen($filelog,"a+");
  484. if ($file)
  485. {
  486. $ip='???'; // $ip contains information to identify computer that run the code
  487. if (! empty($_SERVER["REMOTE_ADDR"])) $ip=$_SERVER["REMOTE_ADDR"]; // In most cases.
  488. else if (! empty($_SERVER['SERVER_ADDR'])) $ip=$_SERVER['SERVER_ADDR']; // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
  489. else if (! empty($_SERVER['COMPUTERNAME'])) $ip=$_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME'])?'':'@'.$_SERVER['USERNAME']); // This is when PHP session is ran outside a web server, like from Windows command line (Not always defined, but usefull if OS defined it).
  490. else if (! empty($_SERVER['LOGNAME'])) $ip='???@'.$_SERVER['LOGNAME']; // This is when PHP session is ran outside a web server, like from Linux command line (Not always defined, but usefull if OS defined it).
  491. $liblevelarray=array(LOG_ERR=>'ERROR',LOG_WARNING=>'WARN',LOG_INFO=>'INFO',LOG_DEBUG=>'DEBUG');
  492. $liblevel=$liblevelarray[$level];
  493. if (! $liblevel) $liblevel='UNDEF';
  494. $message=dol_print_date(time(),"%Y-%m-%d %H:%M:%S")." ".sprintf("%-5s",$liblevel)." ".sprintf("%-15s",$ip)." ".$message;
  495. fwrite($file,$message."\n");
  496. fclose($file);
  497. // This is for log file, we do not change permissions
  498. // If enable html log tag enabled and url parameter log defined, we show output log on HTML comments
  499. if (! empty($conf->global->MAIN_ENABLE_LOG_HTML) && ! empty($_GET["log"]))
  500. {
  501. print "\n\n<!-- Log start\n";
  502. print $message."\n";
  503. print "Log end -->\n";
  504. }
  505. }
  506. elseif (! defined("SYSLOG_FILE_NO_ERROR"))
  507. {
  508. // Do not use here a call to functions that make call to dol_syslog so making call to langs. A simple print is enough.
  509. print "Error, failed to open file ".$filelog."\n";
  510. }
  511. }
  512. // Check if log is to syslog (SYSLOG_SYSLOG_ON defined)
  513. if (defined("SYSLOG_SYSLOG_ON") && constant("SYSLOG_SYSLOG_ON"))
  514. {
  515. if (function_exists('openlog')) // This function does not exists on some ISP (Ex: Free in France)
  516. {
  517. $facility = LOG_USER;
  518. if (defined("SYSLOG_FACILITY") && constant("SYSLOG_FACILITY"))
  519. {
  520. // Exemple: SYSLOG_FACILITY vaut LOG_USER qui vaut 8. On a besoin de 8 dans $facility.
  521. $facility = constant("SYSLOG_FACILITY");
  522. }
  523. openlog("dolibarr", LOG_PID | LOG_PERROR, (int) $facility); // (int) is required to avoid error parameter 3 expected to be long
  524. if (! $level) syslog(LOG_ERR, $message);
  525. else syslog($level, $message);
  526. closelog();
  527. }
  528. }
  529. // Check if log is to syslog (SYSLOG_FIREPHP_ON defined)
  530. if (defined("SYSLOG_FIREPHP_ON") && constant("SYSLOG_FIREPHP_ON") && ! empty($_SERVER["SERVER_NAME"])) //! empty($_SERVER["SERVER_NAME"]) to be sure to enable this in Web mode only
  531. {
  532. try
  533. {
  534. // Warning FirePHPCore must be into PHP include path. It is not possible to use into require_once() a constant from
  535. // database or config file because we must be able to log data before database or config file read.
  536. $oldinclude=get_include_path();
  537. set_include_path('/usr/share/php/');
  538. require_once('FirePHPCore/FirePHP.class.php');
  539. set_include_path($oldinclude);
  540. ob_start();
  541. $firephp = FirePHP::getInstance(true);
  542. if ($level == LOG_ERR) $firephp->error($message);
  543. elseif ($level == LOG_WARNING) $firephp->warn($message);
  544. elseif ($level == LOG_INFO) $firephp->log($message);
  545. else $firephp->log($message);
  546. }
  547. catch(Exception $e)
  548. {
  549. }
  550. }
  551. }
  552. }
  553. /**
  554. * Show tab header of a card
  555. *
  556. * @param array $links Array of tabs
  557. * @param int $active Active tab name
  558. * @param string $title Title
  559. * @param int $notab 0=Add tab header, 1=no tab header
  560. * @param string $picto Add a picto on tab title
  561. * @return void
  562. */
  563. function dol_fiche_head($links=array(), $active='0', $title='', $notab=0, $picto='')
  564. {
  565. print dol_get_fiche_head($links, $active, $title, $notab, $picto);
  566. }
  567. /**
  568. * Show tab header of a card
  569. *
  570. * @param array $links Array of tabs
  571. * @param int $active Active tab name
  572. * @param string $title Title
  573. * @param int $notab 0=Add tab header, 1=no tab header
  574. * @param string $picto Add a picto on tab title
  575. * @return void
  576. */
  577. function dol_get_fiche_head($links=array(), $active='0', $title='', $notab=0, $picto='')
  578. {
  579. $out="\n".'<div class="tabs">'."\n";
  580. // Affichage titre
  581. if ($title)
  582. {
  583. $limittitle=30;
  584. $out.='<a class="tabTitle">';
  585. if ($picto) $out.=img_object('',$picto).' ';
  586. $out.=dol_trunc($title,$limittitle);
  587. $out.='</a>';
  588. }
  589. // Define max of key (max may be higher than sizeof because of hole due to module disabling some tabs).
  590. $maxkey=-1;
  591. if (is_array($links))
  592. {
  593. $keys=array_keys($links);
  594. if (count($keys)) $maxkey=max($keys);
  595. }
  596. // Show tabs
  597. for ($i = 0 ; $i <= $maxkey ; $i++)
  598. {
  599. if (isset($links[$i][2]) && $links[$i][2] == 'image')
  600. {
  601. if (!empty($links[$i][0]))
  602. {
  603. $out.='<a class="tabimage" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  604. }
  605. else
  606. {
  607. $out.='<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  608. }
  609. }
  610. else if (! empty($links[$i][1]))
  611. {
  612. //print "x $i $active ".$links[$i][2]." z";
  613. if ((is_numeric($active) && $i == $active)
  614. || (! is_numeric($active) && $active == $links[$i][2]))
  615. {
  616. $out.='<a id="active" class="tab" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  617. }
  618. else
  619. {
  620. $out.='<a id="'.$links[$i][2].'" class="tab" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  621. }
  622. }
  623. }
  624. $out.="</div>\n";
  625. if (! $notab) $out.="\n".'<div class="tabBar">'."\n";
  626. return $out;
  627. }
  628. /**
  629. * Show tab footer of a card
  630. *
  631. * @param int $notab 0=Add tab footer, 1=no tab footer
  632. * @return void
  633. */
  634. function dol_fiche_end($notab=0)
  635. {
  636. print dol_get_fiche_end($notab);
  637. }
  638. /**
  639. * Return tab footer of a card
  640. *
  641. * @param int $notab 0=Add tab footer, 1=no tab footer
  642. * @return void
  643. */
  644. function dol_get_fiche_end($notab=0)
  645. {
  646. if (! $notab) return "\n</div>\n";
  647. else return '';
  648. }
  649. /* For backward compatibility */
  650. function dolibarr_print_date($time,$format='',$to_gmt=false,$outputlangs='',$encodetooutput=false)
  651. {
  652. return dol_print_date($time,$format,$to_gmt,$outputlangs,$encodetooutput);
  653. }
  654. /**
  655. * Return a formated address (part address/zip/town/state) according to country rules
  656. *
  657. * @param outputlangs Output langs object
  658. * @param object A company or contact object
  659. * @return string Formated string
  660. */
  661. function dol_format_address($outputlangs,$object)
  662. {
  663. $ret='';
  664. $countriesusingstate=array('US','IN');
  665. // Address
  666. $ret .= $outputlangs->convToOutputCharset($object->address);
  667. // Zip/Town/State
  668. if (in_array($object->country_code,array('US'))) // US: town, state, zip
  669. {
  670. $ret .= ($ret ? "\n" : '' ).$outputlangs->convToOutputCharset($object->town);
  671. if ($object->state && in_array($object->country_code,$countriesusingstate))
  672. {
  673. $ret.=", ".$outputlangs->convToOutputCharset($object->departement);
  674. }
  675. if ($object->zip) $ret .= ', '.$outputlangs->convToOutputCharset($object->zip);
  676. }
  677. else // Other: zip town, state
  678. {
  679. $ret .= ($ret ? "\n" : '' ).$outputlangs->convToOutputCharset($object->zip);
  680. $ret .= ' '.$outputlangs->convToOutputCharset($object->town);
  681. if ($object->state && in_array($object->country_code,$countriesusingstate))
  682. {
  683. $ret.=", ".$outputlangs->convToOutputCharset($object->state);
  684. }
  685. }
  686. return $ret;
  687. }
  688. /**
  689. * Output date in a string format according to outputlangs (or langs if not defined).
  690. * Return charset is always UTF-8, except if encodetoouput is defined. In this cas charset is output charset
  691. *
  692. * @param timestamp $time GM Timestamps date (or deprecated strings 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS')
  693. * @param string $format Output date format
  694. * "%d %b %Y",
  695. * "%d/%m/%Y %H:%M",
  696. * "%d/%m/%Y %H:%M:%S",
  697. * "day", "daytext", "dayhour", "dayhourldap", "dayhourtext"
  698. * @param string $tzoutput true=output or 'gmt' => string is for Greenwich location
  699. * false or 'tzserver' => output string is for local PHP server TZ usage
  700. * 'tzuser' => output string is for local browser TZ usage
  701. * @param Tranlsate $outputlangs Object lang that contains language for text translation.
  702. * @param boolean $encodetooutput false=no convert into output pagecode
  703. * @return string Formated date or '' if time is null
  704. *
  705. * @see dol_mktime, dol_stringtotime, dol_getdate
  706. */
  707. function dol_print_date($time,$format='',$tzoutput='tzserver',$outputlangs='',$encodetooutput=false)
  708. {
  709. global $conf,$langs;
  710. $to_gmt=false;
  711. $offsettz=$offsetdst=0;
  712. if ($tzoutput)
  713. {
  714. $to_gmt=true; // For backward compatibility
  715. if (is_string($tzoutput))
  716. {
  717. if ($tzoutput == 'tzserver')
  718. {
  719. $to_gmt=false;
  720. $offsettz=$offsetdst=0;
  721. }
  722. if ($tzoutput == 'tzuser')
  723. {
  724. $to_gmt=true;
  725. $offsettz=(empty($_SESSION['dol_tz'])?0:$_SESSION['dol_tz'])*60*60;
  726. $offsetdst=(empty($_SESSION['dol_dst'])?0:$_SESSION['dol_dst'])*60*60;
  727. }
  728. if ($tzoutput == 'tzcompany')
  729. {
  730. $to_gmt=false;
  731. $offsettz=$offsetdst=0; // TODO Define this and use it later
  732. }
  733. }
  734. }
  735. if (! is_object($outputlangs)) $outputlangs=$langs;
  736. // Si format non defini, on prend $conf->format_date_text_short sinon %Y-%m-%d %H:%M:%S
  737. if (! $format) $format=(isset($conf->format_date_text_short) ? $conf->format_date_text_short : '%Y-%m-%d %H:%M:%S');
  738. // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
  739. if ($format == 'day') $format=($outputlangs->trans("FormatDateShort")!="FormatDateShort"?$outputlangs->trans("FormatDateShort"):$conf->format_date_short);
  740. if ($format == 'hour') $format=($outputlangs->trans("FormatHourShort")!="FormatHourShort"?$outputlangs->trans("FormatHourShort"):$conf->format_hour_short);
  741. if ($format == 'hourduration') $format=($outputlangs->trans("FormatHourShortDuration")!="FormatHourShortDuration"?$outputlangs->trans("FormatHourShortDuration"):$conf->format_hour_short_duration);
  742. if ($format == 'daytext') $format=($outputlangs->trans("FormatDateText")!="FormatDateText"?$outputlangs->trans("FormatDateText"):$conf->format_date_text);
  743. if ($format == 'daytextshort') $format=($outputlangs->trans("FormatDateTextShort")!="FormatDateTextShort"?$outputlangs->trans("FormatDateTextShort"):$conf->format_date_text_short);
  744. if ($format == 'dayhour') $format=($outputlangs->trans("FormatDateHourShort")!="FormatDateHourShort"?$outputlangs->trans("FormatDateHourShort"):$conf->format_date_hour_short);
  745. if ($format == 'dayhourtext') $format=($outputlangs->trans("FormatDateHourText")!="FormatDateHourText"?$outputlangs->trans("FormatDateHourText"):$conf->format_date_hour_text);
  746. if ($format == 'dayhourtextshort') $format=($outputlangs->trans("FormatDateHourTextShort")!="FormatDateHourTextShort"?$outputlangs->trans("FormatDateHourTextShort"):$conf->format_date_hour_text_short);
  747. // Format not sensitive to language
  748. if ($format == 'dayhourlog') $format='%Y%m%d%H%M%S';
  749. if ($format == 'dayhourldap') $format='%Y%m%d%H%M%SZ';
  750. if ($format == 'dayhourxcard') $format='%Y%m%dT%H%M%SZ';
  751. if ($format == 'dayxcard') $format='%Y%m%d';
  752. if ($format == 'dayrfc') $format='%Y-%m-%d'; // DATE_RFC3339
  753. if ($format == 'dayhourrfc') $format='%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339
  754. // If date undefined or "", we return ""
  755. if (dol_strlen($time) == 0) return ''; // $time=0 allowed (it means 01/01/1970 00:00:00)
  756. //print 'x'.$time;
  757. if (preg_match('/%b/i',$format)) // There is some text to translate
  758. {
  759. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  760. $format=str_replace('%b','__b__',$format);
  761. $format=str_replace('%B','__B__',$format);
  762. }
  763. if (preg_match('/%a/i',$format)) // There is some text to translate
  764. {
  765. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  766. $format=str_replace('%a','__a__',$format);
  767. $format=str_replace('%A','__A__',$format);
  768. }
  769. // Analyze date (deprecated) Ex: 1970-01-01, 1970-01-01 01:00:00, 19700101010000
  770. if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+) ?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i',$time,$reg)
  771. || preg_match('/^([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])$/i',$time,$reg))
  772. {
  773. // This part of code should not be used.
  774. dol_syslog("Functions.lib::dol_print_date function call with deprecated value of time in page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  775. // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS' or 'YYYYMMDDHHMMSS'
  776. $syear = $reg[1];
  777. $smonth = $reg[2];
  778. $sday = $reg[3];
  779. $shour = $reg[4];
  780. $smin = $reg[5];
  781. $ssec = $reg[6];
  782. $time=dol_mktime($shour,$smin,$ssec,$smonth,$sday,$syear,true);
  783. $ret=adodb_strftime($format,$time+$offsettz+$offsetdst,$to_gmt);
  784. }
  785. else
  786. {
  787. // Date is a timestamps
  788. if ($time < 100000000000) // Protection against bad date values
  789. {
  790. $ret=adodb_strftime($format,$time+$offsettz+$offsetdst,$to_gmt);
  791. }
  792. else $ret='Bad value '.$time.' for date';
  793. }
  794. if (preg_match('/__b__/i',$format))
  795. {
  796. // Here ret is string in PHP setup language (strftime was used). Now we convert to $outputlangs.
  797. $month=adodb_strftime('%m',$time+$offsettz+$offsetdst);
  798. if ($encodetooutput)
  799. {
  800. $monthtext=$outputlangs->transnoentities('Month'.$month);
  801. $monthtextshort=$outputlangs->transnoentities('MonthShort'.$month);
  802. }
  803. else
  804. {
  805. $monthtext=$outputlangs->transnoentitiesnoconv('Month'.$month);
  806. $monthtextshort=$outputlangs->transnoentitiesnoconv('MonthShort'.$month);
  807. }
  808. //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
  809. $ret=str_replace('__b__',$monthtextshort,$ret);
  810. $ret=str_replace('__B__',$monthtext,$ret);
  811. //print 'x'.$outputlangs->charset_output.'-'.$ret.'x';
  812. //return $ret;
  813. }
  814. if (preg_match('/__a__/i',$format))
  815. {
  816. $w=adodb_strftime('%w',$time+$offsettz+$offsetdst);
  817. $dayweek=$outputlangs->transnoentitiesnoconv('Day'.$w);
  818. $ret=str_replace('__A__',$dayweek,$ret);
  819. $ret=str_replace('__a__',dol_substr($dayweek,0,3),$ret);
  820. }
  821. return $ret;
  822. }
  823. /**
  824. * Convert a string date into a GM Timestamps date
  825. *
  826. * @param string $string Date in a string
  827. * YYYYMMDD
  828. * YYYYMMDDHHMMSS
  829. * YYYY-MM-DDTHH:MM:SSZ (RFC3339)
  830. * DD/MM/YY or DD/MM/YYYY (this format should not be used anymore)
  831. * DD/MM/YY HH:MM:SS or DD/MM/YYYY HH:MM:SS (this format should not be used anymore)
  832. * @param int $gm 1=Input date is GM date, 0=Input date is local date
  833. * 19700101020000 -> 7200 with gm=1
  834. * @return date Date
  835. *
  836. * @see dol_print_date, dol_mktime, dol_getdate
  837. */
  838. function dol_stringtotime($string, $gm=1)
  839. {
  840. if (preg_match('/^([0-9]+)\/([0-9]+)\/([0-9]+)\s?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i',$string,$reg))
  841. {
  842. // This part of code should not be used.
  843. dol_syslog("Functions.lib::dol_stringtotime call to function with deprecated parameter", LOG_WARNING);
  844. // Date est au format 'DD/MM/YY' ou 'DD/MM/YY HH:MM:SS'
  845. // Date est au format 'DD/MM/YYYY' ou 'DD/MM/YYYY HH:MM:SS'
  846. $sday = $reg[1];
  847. $smonth = $reg[2];
  848. $syear = $reg[3];
  849. $shour = $reg[4];
  850. $smin = $reg[5];
  851. $ssec = $reg[6];
  852. if ($syear < 50) $syear+=1900;
  853. if ($syear >= 50 && $syear < 100) $syear+=2000;
  854. $string=sprintf("%04d%02d%02d%02d%02d%02d",$syear,$smonth,$sday,$shour,$smin,$ssec);
  855. }
  856. // Convert date RFC3339
  857. else if (preg_match('/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})Z$/i',$string,$reg))
  858. {
  859. $syear = $reg[1];
  860. $smonth = $reg[2];
  861. $sday = $reg[3];
  862. $shour = $reg[4];
  863. $smin = $reg[5];
  864. $ssec = $reg[6];
  865. $string=sprintf("%04d%02d%02d%02d%02d%02d",$syear,$smonth,$sday,$shour,$smin,$ssec);
  866. }
  867. $string=preg_replace('/([^0-9])/i','',$string);
  868. $tmp=$string.'000000';
  869. $date=dol_mktime(substr($tmp,8,2),substr($tmp,10,2),substr($tmp,12,2),substr($tmp,4,2),substr($tmp,6,2),substr($tmp,0,4),$gm);
  870. return $date;
  871. }
  872. /**
  873. * Return an array with date info
  874. * PHP getdate is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
  875. *
  876. * @param timestamp $timestamp Timestamp
  877. * @param boolean $fast Fast mode
  878. * @return array Array of informations
  879. * If no fast mode:
  880. * 'seconds' => $secs,
  881. * 'minutes' => $min,
  882. * 'hours' => $hour,
  883. * 'mday' => $day,
  884. * 'wday' => $dow,
  885. * 'mon' => $month,
  886. * 'year' => $year,
  887. * 'yday' => floor($secsInYear/$_day_power),
  888. * 'weekday' => gmdate('l',$_day_power*(3+$dow)),
  889. * 'month' => gmdate('F',mktime(0,0,0,$month,2,1971)),
  890. * If fast mode:
  891. * 'seconds' => $secs,
  892. * 'minutes' => $min,
  893. * 'hours' => $hour,
  894. * 'mday' => $day,
  895. * 'mon' => $month,
  896. * 'year' => $year,
  897. * 'yday' => floor($secsInYear/$_day_power),
  898. * 'leap' => $leaf,
  899. * 'ndays' => $ndays
  900. */
  901. function dol_getdate($timestamp,$fast=false)
  902. {
  903. $usealternatemethod=false;
  904. if ($timestamp <= 0) $usealternatemethod=true; // <= 1970
  905. if ($timestamp >= 2145913200) $usealternatemethod=true; // >= 2038
  906. if ($usealternatemethod)
  907. {
  908. $arrayinfo=adodb_getdate($timestamp,$fast);
  909. }
  910. else
  911. {
  912. $arrayinfo=getdate($timestamp);
  913. }
  914. return $arrayinfo;
  915. }
  916. /* For backward compatibility */
  917. function dolibarr_mktime($hour,$minute,$second,$month,$day,$year,$gm=false,$check=1)
  918. {
  919. return dol_mktime($hour,$minute,$second,$month,$day,$year,$gm,$check);
  920. }
  921. /**
  922. * Return a timestamp date built from detailed informations (by default a local PHP server timestamp)
  923. * Replace function mktime not available under Windows if year < 1970
  924. * PHP mktime is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
  925. *
  926. * @param hour Hour (can be -1 for undefined)
  927. * @param minute Minute (can be -1 for undefined)
  928. * @param second Second (can be -1 for undefined)
  929. * @param month Month (1 to 12)
  930. * @param day Day (1 to 31)
  931. * @param year Year
  932. * @param gm 1=Input informations are GMT values, otherwise local to server TZ
  933. * @param check 0=No check on parameters (Can use day 32, etc...)
  934. * @param isdst Dayling saving time
  935. * @return timestamp Date as a timestamp, '' if error
  936. * @see dol_print_date, dol_stringtotime
  937. */
  938. function dol_mktime($hour,$minute,$second,$month,$day,$year,$gm=false,$check=1,$isdst=true)
  939. {
  940. //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
  941. // Clean parameters
  942. if ($hour == -1) $hour=0;
  943. if ($minute == -1) $minute=0;
  944. if ($second == -1) $second=0;
  945. // Check parameters
  946. if ($check)
  947. {
  948. if (! $month || ! $day) return '';
  949. if ($day > 31) return '';
  950. if ($month > 12) return '';
  951. if ($hour < 0 || $hour > 24) return '';
  952. if ($minute< 0 || $minute > 60) return '';
  953. if ($second< 0 || $second > 60) return '';
  954. }
  955. $usealternatemethod=false;
  956. if ($year <= 1970) $usealternatemethod=true; // <= 1970
  957. if ($year >= 2038) $usealternatemethod=true; // >= 2038
  958. if ($usealternatemethod || $gm) // Si time gm, seule adodb peut convertir
  959. {
  960. /*
  961. // On peut utiliser strtotime pour obtenir la traduction.
  962. // strtotime is ok for range: Friday 13 December 1901 20:45:54 GMT to Tuesday 19 January 2038 03:14:07 GMT.
  963. $montharray=array(1=>'january',2=>'february',3=>'march',4=>'april',5=>'may',6=>'june',
  964. 7=>'july',8=>'august',9=>'september',10=>'october',11=>'november',12=>'december');
  965. $string=$day." ".$montharray[0+$month]." ".$year." ".$hour.":".$minute.":".$second." GMT";
  966. $date=strtotime($string);
  967. print "- ".$string." ".$date." -";
  968. */
  969. $date=adodb_mktime($hour,$minute,$second,$month,$day,$year,$isdst,$gm);
  970. }
  971. else
  972. {
  973. $date=mktime($hour,$minute,$second,$month,$day,$year);
  974. }
  975. return $date;
  976. }
  977. /* For backward compatibility */
  978. function dolibarr_date($fmt, $timestamp, $gm=false)
  979. {
  980. return dol_date($fmt, $timestamp, $gm);
  981. }
  982. /**
  983. * Returns formated date
  984. *
  985. * @param string $fmt Format (Exemple: 'Y-m-d H:i:s')
  986. * @param timestamp $timestamp Date. Example: If timestamp=0 and gm=1, return 01/01/1970 00:00:00
  987. * @param boolean $gm 1 if timestamp was built with gmmktime, 0 if timestamp was build with mktime
  988. * @return string Formated date
  989. *
  990. * @deprecated Replaced by dol_print_date
  991. */
  992. function dol_date($fmt, $timestamp, $gm=false)
  993. {
  994. $usealternatemethod=false;
  995. if ($timestamp <= 0) $usealternatemethod=true;
  996. if ($timestamp >= 2145913200) $usealternatemethod=true;
  997. if ($usealternatemethod || $gm) // Si time gm, seule adodb peut convertir
  998. {
  999. $string=adodb_date($fmt,$timestamp,$gm);
  1000. }
  1001. else
  1002. {
  1003. $string=date($fmt,$timestamp);
  1004. }
  1005. return $string;
  1006. }
  1007. /**
  1008. * Return string with formated size
  1009. *
  1010. * @param int $size Size to print
  1011. * @param int $shortvalue Tell if we want long value to use another unit (Ex: 1.5Kb instead of 1500b)
  1012. * @param int $shortunit Use short value of size unit
  1013. * @return string Link
  1014. */
  1015. function dol_print_size($size,$shortvalue=0,$shortunit=0)
  1016. {
  1017. global $langs;
  1018. $level=1024;
  1019. // Set value text
  1020. if (empty($shortvalue) || $size < ($level*10))
  1021. {
  1022. $ret=$size;
  1023. $textunitshort=$langs->trans("b");
  1024. $textunitlong=$langs->trans("Bytes");
  1025. }
  1026. else
  1027. {
  1028. $ret=round($size/$level,0);
  1029. $textunitshort=$langs->trans("Kb");
  1030. $textunitlong=$langs->trans("KiloBytes");
  1031. }
  1032. // Use long or short text unit
  1033. if (empty($shortunit)) { $ret.=' '.$textunitlong; }
  1034. else { $ret.=' '.$textunitshort; }
  1035. return $ret;
  1036. }
  1037. /**
  1038. * Show Url link
  1039. *
  1040. * @param string $url Url to show
  1041. * @param string $target Target for link
  1042. * @param int $max Max number of characters to show
  1043. * @return string HTML Link
  1044. */
  1045. function dol_print_url($url,$target='_blank',$max=32)
  1046. {
  1047. if (empty($url)) return '';
  1048. $link='<a href="';
  1049. if (! preg_match('/^http/i',$url)) $link.='http://';
  1050. $link.=$url;
  1051. if ($target) $link.='" target="'.$target.'">';
  1052. if (! preg_match('/^http/i',$url)) $link.='http://';
  1053. $link.=dol_trunc($url,$max);
  1054. $link.='</a>';
  1055. return $link;
  1056. }
  1057. /**
  1058. * Show EMail link
  1059. *
  1060. * @param string $email EMail to show (only email, without 'Name of recipient' before)
  1061. * @param int $cid Id of contact if known
  1062. * @param int $socid Id of third party if known
  1063. * @param int $addlink 0=no link to create action
  1064. * @param int $max Max number of characters to show
  1065. * @param int $showinvalid Show warning if syntax email is wrong
  1066. * @return string HTML Link
  1067. */
  1068. function dol_print_email($email,$cid=0,$socid=0,$addlink=0,$max=64,$showinvalid=1)
  1069. {
  1070. global $conf,$user,$langs;
  1071. $newemail=$email;
  1072. if (empty($email)) return '&nbsp;';
  1073. if (! empty($addlink))
  1074. {
  1075. $newemail='<a href="';
  1076. if (! preg_match('/^mailto:/i',$email)) $newemail.='mailto:';
  1077. $newemail.=$email;
  1078. $newemail.='">';
  1079. $newemail.=dol_trunc($email,$max);
  1080. $newemail.='</a>';
  1081. if ($showinvalid && ! isValidEmail($email))
  1082. {
  1083. $langs->load("errors");
  1084. $newemail.=img_warning($langs->trans("ErrorBadEMail",$email));
  1085. }
  1086. if (($cid || $socid) && $conf->agenda->enabled && $user->rights->agenda->myactions->create)
  1087. {
  1088. $type='AC_EMAIL'; $link='';
  1089. if (! empty($conf->global->AGENDA_ADDACTIONFOREMAIL)) $link='<a href="'.DOL_URL_ROOT.'/comm/action/fiche.php?action=create&amp;backtopage=1&amp;actioncode='.$type.'&amp;contactid='.$cid.'&amp;socid='.$socid.'">'.img_object($langs->trans("AddAction"),"calendar").'</a>';
  1090. $newemail='<table class="nobordernopadding"><tr><td>'.$newemail.' </td><td>&nbsp;'.$link.'</td></tr></table>';
  1091. }
  1092. }
  1093. else
  1094. {
  1095. if ($showinvalid && ! isValidEmail($email))
  1096. {
  1097. $langs->load("errors");
  1098. $newemail.=img_warning($langs->trans("ErrorBadEMail",$email));
  1099. }
  1100. }
  1101. return $newemail;
  1102. }
  1103. /* For backward compatibility */
  1104. function dolibarr_print_phone($phone,$country="FR",$cid=0,$socid=0,$addlink=0,$separ="&nbsp;")
  1105. {
  1106. return dol_print_phone($phone,$country,$cid,$socid,$addlink,$separ);
  1107. }
  1108. /**
  1109. * Format phone numbers according to country
  1110. *
  1111. * @param string $phone Phone number to format
  1112. * @param string $country Country code to use for formatting
  1113. * @param int $cid Id of contact if known
  1114. * @param int $socid Id of third party if known
  1115. * @param int $addlink 0=no link to create action
  1116. * @param string $separ separation between numbers for a better visibility example : xx.xx.xx.xx.xx
  1117. * @return string Formated phone number
  1118. */
  1119. function dol_print_phone($phone,$country="FR",$cid=0,$socid=0,$addlink=0,$separ="&nbsp;")
  1120. {
  1121. global $conf,$user,$langs;
  1122. // Clean phone parameter
  1123. $phone = preg_replace("/[\s.-]/","",trim($phone));
  1124. if (empty($phone)) { return ''; }
  1125. $newphone=$phone;
  1126. if (strtoupper($country) == "FR")
  1127. {
  1128. // France
  1129. if (dol_strlen($phone) == 10) {
  1130. $newphone=substr($newphone,0,2).$separ.substr($newphone,2,2).$separ.substr($newphone,4,2).$separ.substr($newphone,6,2).$separ.substr($newphone,8,2);
  1131. }
  1132. elseif (dol_strlen($newphone) == 7)
  1133. {
  1134. $newphone=substr($newphone,0,3).$separ.substr($newphone,3,2).$separ.substr($newphone,5,2);
  1135. }
  1136. elseif (dol_strlen($newphone) == 9)
  1137. {
  1138. $newphone=substr($newphone,0,2).$separ.substr($newphone,2,3).$separ.substr($newphone,5,2).$separ.substr($newphone,7,2);
  1139. }
  1140. elseif (dol_strlen($newphone) == 11)
  1141. {
  1142. $newphone=substr($newphone,0,3).$separ.substr($newphone,3,2).$separ.substr($newphone,5,2).$separ.substr($newphone,7,2).$separ.substr($newphone,9,2);
  1143. }
  1144. elseif (dol_strlen($newphone) == 12)
  1145. {
  1146. $newphone=substr($newphone,0,4).$separ.substr($newphone,4,2).$separ.substr($newphone,6,2).$separ.substr($newphone,8,2).$separ.substr($newphone,10,2);
  1147. }
  1148. }
  1149. if (! empty($addlink))
  1150. {
  1151. if ($conf->clicktodial->enabled)
  1152. {
  1153. if (empty($user->clicktodial_loaded)) $user->fetch_clicktodial();
  1154. if (empty($conf->global->CLICKTODIAL_URL)) $urlmask='ErrorClickToDialModuleNotConfigured';
  1155. else $urlmask=$conf->global->CLICKTODIAL_URL;
  1156. // This line is for backward compatibility
  1157. $url = sprintf($urlmask, urlencode($phone), urlencode($user->clicktodial_poste), urlencode($user->clicktodial_login), urlencode($user->clicktodial_password));
  1158. // Thoose lines are for substitution
  1159. $substitarray=array('__PHONEFROM__'=>urlencode($user->clicktodial_poste),
  1160. '__PHONETO__'=>urlencode($phone),
  1161. '__LOGIN__'=>urlencode($user->clicktodial_login),
  1162. '__PASS__'=>urlencode($user->clicktodial_password));
  1163. $url = make_substitutions($url, $substitarray);
  1164. $newphonesav=$newphone;
  1165. $newphone ='<a href="'.$url.'"';
  1166. if (! empty($conf->global->CLICKTODIAL_FORCENEWTARGET)) $newphone.=' target="_blank"';
  1167. $newphone.='>'.$newphonesav.'</a>';
  1168. }
  1169. //if (($cid || $socid) && $conf->agenda->enabled && $user->rights->agenda->myactions->create)
  1170. if ($conf->agenda->enabled && $user->rights->agenda->myactions->create)
  1171. {
  1172. $type='AC_TEL'; $link='';
  1173. if ($addlink == 'AC_FAX') $type='AC_FAX';
  1174. if (! empty($conf->global->AGENDA_ADDACTIONFORPHONE)) $link='<a href="'.DOL_URL_ROOT.'/comm/action/fiche.php?action=create&amp;backtopage=1&amp;actioncode='.$type.($cid?'&amp;contactid='.$cid:'').($socid?'&amp;socid='.$socid:'').'">'.img_object($langs->trans("AddAction"),"calendar").'</a>';
  1175. $newphone='<table class="nobordernopadding"><tr><td>'.$newphone.' </td><td>&nbsp;'.$link.'</td></tr></table>';
  1176. }
  1177. }
  1178. return $newphone;
  1179. }
  1180. /**
  1181. * Return an IP formated to be shown on screen
  1182. *
  1183. * @param string $ip IP
  1184. * @param int $mode 1=return only country/flag,2=return only IP
  1185. * @return string Formated IP, with country if GeoIP module is enabled
  1186. */
  1187. function dol_print_ip($ip,$mode=0)
  1188. {
  1189. global $conf,$langs;
  1190. $ret='';
  1191. if (empty($mode)) $ret.=$ip;
  1192. if (! empty($conf->geoipmaxmind->enabled) && $mode != 2)
  1193. {
  1194. $datafile=$conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
  1195. //$ip='24.24.24.24';
  1196. //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat'; Note that this must be downloaded datafile (not same than datafile provided with ubuntu packages)
  1197. include_once(DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php');
  1198. $geoip=new DolGeoIP('country',$datafile);
  1199. //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
  1200. //print "geoip_country_id_by_addr=".geoip_country_id_by_addr($geoip->gi,$ip)."\n";
  1201. $countrycode=$geoip->getCountryCodeFromIP($ip);
  1202. if ($countrycode) // If success, countrycode is us, fr, ...
  1203. {
  1204. if (file_exists(DOL_DOCUMENT_ROOT.'/theme/common/flags/'.$countrycode.'.png'))
  1205. {
  1206. $ret.=' '.img_picto($countrycode.' '.$langs->trans("AccordingToGeoIPDatabase"),DOL_URL_ROOT.'/theme/common/flags/'.$countrycode.'.png','',1);
  1207. }
  1208. else $ret.=' ('.$countrycode.')';
  1209. }
  1210. }
  1211. return $ret;
  1212. }
  1213. /**
  1214. * Return country code for current user.
  1215. * If software is used inside a local network, detection may fails (we need a public ip)
  1216. *
  1217. * @return string Country code (fr, es, it, us, ...)
  1218. */
  1219. function dol_user_country()
  1220. {
  1221. global $conf,$langs,$user;
  1222. //$ret=$user->xxx;
  1223. $ret='';
  1224. if (! empty($conf->geoipmaxmind->enabled))
  1225. {
  1226. $ip=$_SERVER["REMOTE_ADDR"];
  1227. $datafile=$conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
  1228. //$ip='24.24.24.24';
  1229. //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';
  1230. include_once(DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php');
  1231. $geoip=new DolGeoIP('country',$datafile);
  1232. $countrycode=$geoip->getCountryCodeFromIP($ip);
  1233. $ret=$countrycode;
  1234. }
  1235. return $ret;
  1236. }
  1237. /**
  1238. * Format address string
  1239. *
  1240. * @param string $address Address
  1241. * @param int $htmlid Html ID
  1242. * @param int $mode thirdparty|contact|member|other
  1243. * @param int $id Id of object
  1244. * @return void
  1245. */
  1246. function dol_print_address($address, $htmlid='gmap', $mode, $id)
  1247. {
  1248. global $conf,$user,$langs;
  1249. if ($address)
  1250. {
  1251. print nl2br($address);
  1252. $showmap=0;
  1253. if ($mode=='thirdparty' && $conf->google->enabled && $conf->global->GOOGLE_ENABLE_GMAPS) $showmap=1;
  1254. if ($mode=='contact' && $conf->google->enabled && $conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS) $showmap=1;
  1255. if ($mode=='member' && $conf->google->enabled && $conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS) $showmap=1;
  1256. if ($showmap)
  1257. {
  1258. $url=dol_buildpath('/google/gmaps.php?mode='.$mode.'&id='.$id,1);
  1259. /* print ' <img id="'.$htmlid.'" src="'.DOL_URL_ROOT.'/theme/common/gmap.png">';
  1260. print '<script type="text/javascript">
  1261. $(\'#gmap\').css(\'cursor\',\'pointer\');
  1262. $(\'#gmap\').click(function() {
  1263. $( \'<div>\').dialog({
  1264. modal: true,
  1265. open: function ()
  1266. {
  1267. $(this).load(\''.$url.'\');
  1268. },
  1269. height: 400,
  1270. width: 600,
  1271. title: \'GMap\'
  1272. });
  1273. });
  1274. </script>
  1275. '; */
  1276. print ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'" border="0" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  1277. }
  1278. }
  1279. }
  1280. /**
  1281. * Return true if email syntax is ok
  1282. *
  1283. * @param string $address email (Ex: "toto@titi.com", "John Do <johndo@titi.com>")
  1284. * @return boolean true if email syntax is OK, false if KO or empty string
  1285. */
  1286. function isValidEmail($address)
  1287. {
  1288. if (preg_match("/.*<(.+)>/i", $address, $regs)) {
  1289. $address = $regs[1];
  1290. }
  1291. // 2 letters domains extensions are for countries
  1292. // 3 letters domains extensions: biz|com|edu|gov|int|mil|net|org|pro|...
  1293. if (preg_match("/^[^@\s\t]+@([a-zA-Z0-9\-]+\.)+([a-zA-Z0-9\-]{2,3}|asso|aero|coop|info|name)\$/i",$address))
  1294. {
  1295. return true;
  1296. }
  1297. else
  1298. {
  1299. return false;
  1300. }
  1301. }
  1302. /**
  1303. * Return true if phone number syntax is ok
  1304. *
  1305. * @param string $address phone (Ex: "0601010101")
  1306. * @return boolean true if phone syntax is OK, false if KO or empty string
  1307. */
  1308. function isValidPhone($address)
  1309. {
  1310. return true;
  1311. }
  1312. /**
  1313. * Make a strlen call. Works even if mbstring module not enabled
  1314. *
  1315. * @param string $string String to calculate length
  1316. * @param string $stringencoding Encoding of string
  1317. * @return int Length of string
  1318. */
  1319. function dol_strlen($string,$stringencoding='UTF-8')
  1320. {
  1321. if (function_exists('mb_strlen')) return mb_strlen($string,$stringencoding);
  1322. else return strlen($string);
  1323. }
  1324. /**
  1325. * Make a substring. Works even in mbstring module is not enabled.
  1326. *
  1327. * @param string $string String to scan
  1328. * @param string $start Start position
  1329. * @param int $length Length
  1330. * @param string $stringencoding Page code used for input string encoding
  1331. * @return string substring
  1332. */
  1333. function dol_substr($string,$start,$length,$stringencoding='')
  1334. {
  1335. global $langs;
  1336. if (empty($stringencoding)) $stringencoding=$langs->charset_output;
  1337. $ret='';
  1338. if (function_exists('mb_substr'))
  1339. {
  1340. $ret=mb_substr($string,$start,$length,$stringencoding);
  1341. }
  1342. else
  1343. {
  1344. $ret=substr($string,$start,$length);
  1345. }
  1346. return $ret;
  1347. }
  1348. /* For backward compatibility */
  1349. function dolibarr_trunc($string,$size=40,$trunc='right',$stringencoding='')
  1350. {
  1351. return dol_trunc($string,$size,$trunc,$stringencoding);
  1352. }
  1353. /**
  1354. * Show a javascript graph
  1355. *
  1356. * @param string $htmlid Html id name
  1357. * @param int $width Width in pixel
  1358. * @param int $height Height in pixel
  1359. * @param array $data Data array
  1360. * @param int $showlegend 1 to show legend, 0 otherwise
  1361. * @param string $type Type of graph ('pie', 'barline')
  1362. * @param int $showpercent Show percent (with type='pie' only)
  1363. * @param string $url Param to add an url to click values
  1364. * @return void
  1365. */
  1366. function dol_print_graph($htmlid,$width,$height,$data,$showlegend=0,$type='pie',$showpercent=0,$url='')
  1367. {
  1368. global $conf,$langs;
  1369. global $theme_datacolor; // To have var kept when function is called several times
  1370. if (empty($conf->use_javascript_ajax)) return;
  1371. $jsgraphlib='flot';
  1372. $datacolor=array();
  1373. // Load colors of theme into $datacolor array
  1374. $color_file = DOL_DOCUMENT_ROOT."/theme/".$conf->theme."/graph-color.php";
  1375. if (is_readable($color_file))
  1376. {
  1377. include_once($color_file);
  1378. if (isset($theme_datacolor))
  1379. {
  1380. $datacolor=array();
  1381. foreach($theme_datacolor as $val)
  1382. {
  1383. $datacolor[]="#".sprintf("%02x",$val[0]).sprintf("%02x",$val[1]).sprintf("%02x",$val[2]);
  1384. }
  1385. }
  1386. }
  1387. print '<div id="'.$htmlid.'" style="width:'.$width.'px;height:'.$height.'px;"></div>';
  1388. // We use Flot js lib
  1389. if ($jsgraphlib == 'flot')
  1390. {
  1391. if ($type == 'pie')
  1392. {
  1393. // data is array('series'=>array(serie1,serie2,...),
  1394. // 'seriestype'=>array('bar','line',...),
  1395. // 'seriescolor'=>array(0=>'#999999',1=>'#999999',...)
  1396. // 'xlabel'=>array(0=>labelx1,1=>labelx2,...));
  1397. // serieX is array('label'=>'label', data=>val)
  1398. print '
  1399. <script type="text/javascript">
  1400. $(function () {
  1401. var data = '.json_encode($data['series']).';
  1402. function plotWithOptions() {
  1403. $.plot($("#'.$htmlid.'"), data,
  1404. {
  1405. series: {
  1406. pie: {
  1407. show: true,
  1408. radius: 3/4,
  1409. label: {
  1410. show: true,
  1411. radius: 3/4,
  1412. formatter: function(label, series) {
  1413. var percent=Math.round(series.percent);
  1414. var number=series.data[0][1];
  1415. return \'';
  1416. print '<div style="font-size:8pt;text-align:center;padding:2px;color:white;">';
  1417. if ($url) print '<a style="color: #FFFFFF;" border="0" href="'.$url.'=">';
  1418. print '\'+'.($showlegend?'number':'label+\'<br/>\'+number');
  1419. if (! empty($showpercent)) print '+\'<br/>\'+percent+\'%\'';
  1420. print '+\'';
  1421. if ($url) print '</a>';
  1422. print '</div>\';
  1423. },
  1424. background: {
  1425. opacity: 0.5,
  1426. color: \'#000000\'
  1427. }
  1428. }
  1429. }
  1430. },
  1431. zoom: {
  1432. interactive: true
  1433. },
  1434. pan: {
  1435. interactive: true
  1436. },';
  1437. if (count($datacolor))
  1438. {
  1439. print 'colors: '.(! empty($data['seriescolor']) ? json_encode($data['seriescolor']) : json_encode($datacolor)).',';
  1440. }
  1441. print 'legend: {show: '.($showlegend?'true':'false').', position: \'ne\' }
  1442. });
  1443. }
  1444. plotWithOptions();
  1445. });
  1446. </script>';
  1447. }
  1448. else if ($type == 'barline')
  1449. {
  1450. // data is array('series'=>array(serie1,serie2,...),
  1451. // 'seriestype'=>array('bar','line',...),
  1452. // 'seriescolor'=>array(0=>'#999999',1=>'#999999',...)
  1453. // 'xlabel'=>array(0=>labelx1,1=>labelx2,...));
  1454. // serieX is array('label'=>'label', data=>array(0=>y1,1=>y2,...)) with same nb of value than into xlabel
  1455. print '
  1456. <script type="text/javascript">
  1457. $(function () {
  1458. var data = [';
  1459. $i=0; $outputserie=0;
  1460. foreach($data['series'] as $serie)
  1461. {
  1462. if ($data['seriestype'][$i]=='line') { $i++; continue; };
  1463. if ($outputserie > 0) print ',';
  1464. print '{ bars: { stack: 0, show: true, barWidth: 0.9, align: \'center\' }, label: \''.dol_escape_js($serie['label']).'\', data: '.json_encode($serie['data']).'}'."\n";
  1465. $outputserie++; $i++;
  1466. }
  1467. if ($outputserie) print ', ';
  1468. //print '];
  1469. //var datalines = [';
  1470. $i=0; $outputserie=0;
  1471. foreach($data['series'] as $serie)
  1472. {
  1473. if (empty($data['seriestype'][$i]) || $data['seriestype'][$i]=='bar') { $i++; continue; };
  1474. if ($outputserie > 0) print ',';
  1475. print '{ lines: { show: true }, label: \''.dol_escape_js($serie['label']).'\', data: '.json_encode($serie['data']).'}'."\n";
  1476. $outputserie++; $i++;
  1477. }
  1478. print '];
  1479. var dataticks = '.json_encode($data['xlabel']).'
  1480. function plotWithOptions() {
  1481. $.plot(jQuery("#'.$htmlid.'"), data,
  1482. {
  1483. series: {
  1484. stack: 0
  1485. },
  1486. zoom: {
  1487. interactive: true
  1488. },
  1489. pan: {
  1490. interactive: true
  1491. },';
  1492. if (count($datacolor))
  1493. {
  1494. print 'colors: '.json_encode($datacolor).',';
  1495. }
  1496. print 'legend: {show: '.($showlegend?'true':'false').'},
  1497. xaxis: {ticks: dataticks}
  1498. });
  1499. }
  1500. plotWithOptions();
  1501. });
  1502. </script>';
  1503. }
  1504. else print 'BadValueForPArameterType';
  1505. }
  1506. }
  1507. /**
  1508. * Truncate a string to a particular length adding '...' if string larger than length.
  1509. * If length = max length+1, we do no truncate to avoid having just 1 char replaced with '...'.
  1510. * MAIN_DISABLE_TRUNC=1 can disable all truncings
  1511. *
  1512. * @param string String to truncate
  1513. * @param size Max string size. 0 for no limit.
  1514. * @param trunc Where to trunc: right, left, middle, wrap
  1515. * @param stringencoding Tell what is source string encoding
  1516. * @return string Truncated string
  1517. */
  1518. function dol_trunc($string,$size=40,$trunc='right',$stringencoding='UTF-8')
  1519. {
  1520. global $conf;
  1521. if ($size==0) return $string;
  1522. if (empty($conf->global->MAIN_DISABLE_TRUNC))
  1523. {
  1524. // We go always here
  1525. if ($trunc == 'right')
  1526. {
  1527. $newstring=dol_textishtml($string)?dol_string_nohtmltag($string,1):$string;
  1528. if (dol_strlen($newstring,$stringencoding) > ($size+1))
  1529. return dol_substr($newstring,0,$size,$stringencoding).'...';
  1530. else
  1531. return $string;
  1532. }
  1533. if ($trunc == 'middle')
  1534. {
  1535. $newstring=dol_textishtml($string)?dol_string_nohtmltag($string,1):$string;
  1536. if (dol_strlen($newstring,$stringencoding) > 2 && dol_strlen($newstring,$stringencoding) > ($size+1))
  1537. {
  1538. $size1=round($size/2);
  1539. $size2=round($size/2);
  1540. return dol_substr($newstring,0,$size1,$stringencoding).'...'.dol_substr($newstring,dol_strlen($newstring,$stringencoding) - $size2,$size2,$stringencoding);
  1541. }
  1542. else
  1543. return $string;
  1544. }
  1545. if ($trunc == 'left')
  1546. {
  1547. $newstring=dol_textishtml($string)?dol_string_nohtmltag($string,1):$string;
  1548. if (dol_strlen($newstring,$stringencoding) > ($size+1))
  1549. return '...'.dol_substr($newstring,dol_strlen($newstring,$stringencoding) - $size,$size,$stringencoding);
  1550. else
  1551. return $string;
  1552. }
  1553. if ($trunc == 'wrap')
  1554. {
  1555. $newstring=dol_textishtml($string)?dol_string_nohtmltag($string,1):$string;
  1556. if (dol_strlen($newstring,$stringencoding) > ($size+1))
  1557. return dol_substr($newstring,0,$size,$stringencoding)."\n".dol_trunc(dol_substr($newstring,$size,dol_strlen($newstring,$stringencoding)-$size,$stringencoding),$size,$trunc);
  1558. else
  1559. return $string;
  1560. }
  1561. }
  1562. else
  1563. {
  1564. return $string;
  1565. }
  1566. }
  1567. /**
  1568. * Show a picto called object_picto (generic function)
  1569. *
  1570. * @param string $alt Text of alt on image
  1571. * @param string $picto Name of image to show object_picto (example: user, group, action, bill, contract, propal, product, ...)
  1572. * For external modules use imagename@mymodule to search into directory "img" of module.
  1573. * @param string $options Add more attribute on img tag
  1574. * @param int $pictoisfullpath If 1, image path is a full path
  1575. * @return string Return img tag
  1576. * @see #img_picto, #img_picto_common
  1577. */
  1578. function img_object($alt, $picto, $options='', $pictoisfullpath=0)
  1579. {
  1580. global $conf;
  1581. // Clean parameters
  1582. if (! preg_match('/(\.png|\.gif)$/i',$picto) && ! preg_match('/^([^@]+)@([^@]+)$/i',$picto)) $picto.='.png';
  1583. // Define fullpathpicto to use into src
  1584. if (! empty($pictoisfullpath)) $fullpathpicto=$picto;
  1585. else
  1586. {
  1587. // By default, we search into theme directory
  1588. $url = DOL_URL_ROOT;
  1589. $path = 'theme/'.$conf->theme;
  1590. if (! empty($conf->global->MAIN_FORCETHEMEDIR)) $path=preg_replace('/^\//','',$conf->global->MAIN_FORCETHEMEDIR).'/'.$path;
  1591. // If we ask an image into module/img (not into a theme path)
  1592. if (preg_match('/^([^@]+)@([^@]+)$/i',$picto,$regs)) { $picto = $regs[1]; $path=$regs[2]; } // If image into a module/img path
  1593. if (! preg_match('/(\.png|\.gif)$/i',$picto)) $picto.='.png';
  1594. // If img file not into standard path, we use alternate path
  1595. if (defined('DOL_URL_ROOT_ALT') && DOL_URL_ROOT_ALT && ! file_exists(DOL_DOCUMENT_ROOT.'/'.$path.'/img/object_'.$picto)) $url = DOL_URL_ROOT_ALT;
  1596. $fullpathpicto=$url.'/'.$path.'/img/object_'.$picto;
  1597. }
  1598. return '<img src="'.$fullpathpicto.'" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'"'.($options?' '.$options:'').'>';
  1599. }
  1600. /**
  1601. * Show picto whatever it's its name (generic function)
  1602. *
  1603. * @param string $alt Text on alt and title of image
  1604. * @param string $picto Name of image file to show ('filenew', ...)
  1605. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  1606. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  1607. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  1608. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  1609. * @param string $options Add more attribute on img tag (For example 'style="float: right"')
  1610. * @param int $pictoisfullpath If 1, image path is a full path
  1611. * @return string Return img tag
  1612. * @see #img_object, #img_picto_common
  1613. */
  1614. function img_picto($alt, $picto, $options='', $pictoisfullpath=0)
  1615. {
  1616. global $conf;
  1617. // Clean parameters
  1618. if (! preg_match('/(\.png|\.gif)$/i',$picto) && ! preg_match('/^([^@]+)@([^@]+)$/i',$picto)) $picto.='.png';
  1619. // Define fullpathpicto to use into src
  1620. if (! empty($pictoisfullpath)) $fullpathpicto=$picto;
  1621. else
  1622. {
  1623. // By default, we search into theme directory
  1624. $url = DOL_URL_ROOT;
  1625. $path = 'theme/'.$conf->theme;
  1626. if (! empty($conf->global->MAIN_FORCETHEMEDIR)) $path=preg_replace('/^\//','',$conf->global->MAIN_FORCETHEMEDIR).'/'.$path;
  1627. // If we ask an image into module/img (not into a theme path)
  1628. if (preg_match('/^([^@]+)@([^@]+)$/i',$picto,$regs)) { $picto = $regs[1]; $path=$regs[2]; } // If image into a module/img path
  1629. if (! preg_match('/(\.png|\.gif)$/i',$picto)) $picto.='.png';
  1630. // If img file not into standard path, we use alternate path
  1631. if (defined('DOL_URL_ROOT_ALT') && DOL_URL_ROOT_ALT && ! file_exists(DOL_DOCUMENT_ROOT.'/'.$path.'/img/'.$picto)) $url = DOL_URL_ROOT_ALT;
  1632. $fullpathpicto=$url.'/'.$path.'/img/'.$picto;
  1633. }
  1634. return '<img src="'.$fullpathpicto.'" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'"'.($options?' '.$options:'').'>';
  1635. }
  1636. /**
  1637. * Show picto (generic function)
  1638. *
  1639. * @param string $alt Text on alt and title of image
  1640. * @param string $picto Name of image file to show (If no extension provided, we use '.png'). Image must be stored into htdocs/theme/common directory.
  1641. * @param string $options Add more attribute on img tag
  1642. * @param int $pictoisfullpath If 1, image path is a full path
  1643. * @return string Return img tag
  1644. * @see #img_object, #img_picto
  1645. */
  1646. function img_picto_common($alt, $picto, $options='', $pictoisfullpath=0)
  1647. {
  1648. global $conf;
  1649. if (! preg_match('/(\.png|\.gif)$/i',$picto)) $picto.='.png';
  1650. if ($pictoisfullpath) return '<img src="'.$picto.'" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'"'.($options?' '.$options:'').'>';
  1651. if (! empty($conf->global->MAIN_MODULE_CAN_OVERWRITE_COMMONICONS) && file_exists(DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/'.$picto)) return '<img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/'.$picto.'" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'"'.($options?' '.$options:'').'>';
  1652. return '<img src="'.DOL_URL_ROOT.'/theme/common/'.$picto.'" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'"'.($options?' '.$options:'').'>';
  1653. }
  1654. /**
  1655. * Show logo action
  1656. *
  1657. * @param alt Text for image alt and title
  1658. * @param numaction Action to show
  1659. * @return string Return an img tag
  1660. */
  1661. function img_action($alt = "default", $numaction)
  1662. {
  1663. global $conf,$langs;
  1664. if ($alt=="default") {
  1665. if ($numaction == -1) $alt=$langs->trans("ChangeDoNotContact");
  1666. if ($numaction == 0) $alt=$langs->trans("ChangeNeverContacted");
  1667. if ($numaction == 1) $alt=$langs->trans("ChangeToContact");
  1668. if ($numaction == 2) $alt=$langs->trans("ChangeContactInProcess");
  1669. if ($numaction == 3) $alt=$langs->trans("ChangeContactDone");
  1670. }
  1671. return '<img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/stcomm'.$numaction.'.png" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'">';
  1672. }
  1673. /**
  1674. * Show pdf logo
  1675. *
  1676. * @param alt Texte sur le alt de l'image
  1677. * @param $size Taille de l'icone : 3 = 16x16px , 2 = 14x14px
  1678. * @return string Retourne tag img
  1679. */
  1680. function img_pdf($alt = "default",$size=3)
  1681. {
  1682. global $conf,$langs;
  1683. if ($alt=="default") $alt=$langs->trans("Show");
  1684. return '<img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/pdf'.$size.'.png" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'">';
  1685. }
  1686. /**
  1687. * Show logo +
  1688. *
  1689. * @param alt Texte sur le alt de l'image
  1690. * @return string Retourne tag img
  1691. */
  1692. function img_edit_add($alt = "default")
  1693. {
  1694. global $conf,$langs;
  1695. if ($alt=="default") $alt=$langs->trans("Add");
  1696. return img_picto($alt,'edit_add.png');
  1697. }
  1698. /**
  1699. * Show logo -
  1700. *
  1701. * @param alt Texte sur le alt de l'image
  1702. * @return string Retourne tag img
  1703. */
  1704. function img_edit_remove($alt = "default")
  1705. {
  1706. global $conf,$langs;
  1707. if ($alt=="default") $alt=$langs->trans("Remove");
  1708. return img_picto($alt,'edit_remove.png');
  1709. }
  1710. /**
  1711. * Show logo editer/modifier fiche
  1712. *
  1713. * @param alt Texte sur le alt de l'image
  1714. * @param float Si il faut y mettre le style "float: right"
  1715. * @param other Add more attributes on img
  1716. * @return string Retourne tag img
  1717. */
  1718. function img_edit($alt = "default", $float=0, $other='')
  1719. {
  1720. global $conf,$langs;
  1721. if ($alt=="default") $alt=$langs->trans("Modify");
  1722. $img='<img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/edit.png" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'"';
  1723. if ($float) $img.=' style="float: right"';
  1724. if ($other) $img.=' '.$other;
  1725. $img.='>';
  1726. return $img;
  1727. }
  1728. /**
  1729. * Show logo view card
  1730. *
  1731. * @param alt Texte sur le alt de l'image
  1732. * @param float Si il faut y mettre le style "float: right"
  1733. * @param other Add more attributes on img
  1734. * @return string Retourne tag img
  1735. */
  1736. function img_view($alt = "default", $float=0, $other='')
  1737. {
  1738. global $conf,$langs;
  1739. if ($alt=="default") $alt=$langs->trans("View");
  1740. $img='<img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/view.png" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'"';
  1741. if ($float) $img.=' style="float: right"';
  1742. if ($other) $img.=' '.$other;
  1743. $img.='>';
  1744. return $img;
  1745. }
  1746. /**
  1747. * Show delete logo
  1748. *
  1749. * @param alt Texte sur le alt de l'image
  1750. * @param other Add more attributes on img
  1751. * @return string Retourne tag img
  1752. */
  1753. function img_delete($alt = "default", $other='')
  1754. {
  1755. global $conf,$langs;
  1756. if ($alt=="default") $alt=$langs->trans("Delete");
  1757. return img_picto($alt,'delete.png',$other);
  1758. }
  1759. /**
  1760. * Show help logo with cursor "?"
  1761. *
  1762. * @param usehelpcursor
  1763. * @param usealttitle Texte to use as alt title
  1764. * @return string Retourne tag img
  1765. */
  1766. function img_help($usehelpcursor=1,$usealttitle=1)
  1767. {
  1768. global $conf,$langs;
  1769. $s ='<img ';
  1770. if ($usehelpcursor) $s.='style="cursor: help;" ';
  1771. $s.='src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/info.png" border="0"';
  1772. if ($usealttitle)
  1773. {
  1774. if (is_string($usealttitle)) $s.=' alt="'.dol_escape_htmltag($usealttitle).'" title="'.dol_escape_htmltag($usealttitle).'"';
  1775. else $s.=' alt="'.$langs->trans("Info").'" title="'.$langs->trans("Info").'"';
  1776. }
  1777. else $s.=' alt=""';
  1778. $s.='>';
  1779. return $s;
  1780. }
  1781. /**
  1782. * Affiche logo info
  1783. *
  1784. * @param alt Texte sur le alt de l'image
  1785. * @return string Retourne tag img
  1786. */
  1787. function img_info($alt = "default")
  1788. {
  1789. global $conf,$langs;
  1790. if ($alt=="default") $alt=$langs->trans("Informations");
  1791. return img_picto($alt,'info.png');
  1792. }
  1793. /**
  1794. * Affiche logo warning
  1795. *
  1796. * @param alt Texte sur le alt de l'image
  1797. * @param float Si il faut afficher le style "float: right"
  1798. * @return string Retourne tag img
  1799. */
  1800. function img_warning($alt = "default",$float=0)
  1801. {
  1802. global $conf,$langs;
  1803. if ($alt=="default") $alt=$langs->trans("Warning");
  1804. return img_picto($alt,'warning.png',$float?'style="float: right"':'');
  1805. }
  1806. /**
  1807. * Affiche logo error
  1808. *
  1809. * @param alt Texte sur le alt de l'image
  1810. * @return string Retourne tag img
  1811. */
  1812. function img_error($alt = "default")
  1813. {
  1814. global $conf,$langs;
  1815. if ($alt=="default") $alt=$langs->trans("Error");
  1816. return img_picto($alt,'error.png');
  1817. }
  1818. /**
  1819. * Affiche logo telephone
  1820. *
  1821. * @param alt Texte sur le alt de l'image
  1822. * @param option Choose of logo
  1823. * @return string Retourne tag img
  1824. */
  1825. function img_phone($alt = "default",$option=0)
  1826. {
  1827. global $conf,$langs;
  1828. if ($alt=="default") $alt=$langs->trans("Call");
  1829. $img='call_out';
  1830. if ($option == 1) $img='call';
  1831. $img='object_commercial';
  1832. return '<img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/'.$img.'.png" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'">';
  1833. }
  1834. /**
  1835. * Affiche logo suivant
  1836. *
  1837. * @param alt Texte sur le alt de l'image
  1838. * @return string Retourne tag img
  1839. */
  1840. function img_next($alt = "default")
  1841. {
  1842. global $conf,$langs;
  1843. if ($alt=="default") {
  1844. $alt=$langs->trans("Next");
  1845. }
  1846. return '<img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/next.png" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'">';
  1847. }
  1848. /**
  1849. * Affiche logo precedent
  1850. *
  1851. * @param alt Texte sur le alt de l'image
  1852. * @return string Retourne tag img
  1853. */
  1854. function img_previous($alt = "default")
  1855. {
  1856. global $conf,$langs;
  1857. if ($alt=="default") $alt=$langs->trans("Previous");
  1858. return '<img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/previous.png" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'">';
  1859. }
  1860. /**
  1861. * Show logo down arrow
  1862. *
  1863. * @param alt Texte sur le alt de l'image
  1864. * @param selected Affiche version "selected" du logo
  1865. * @return string Retourne tag img
  1866. */
  1867. function img_down($alt = "default", $selected=0)
  1868. {
  1869. global $conf,$langs;
  1870. if ($alt=="default") $alt=$langs->trans("Down");
  1871. if ($selected) return '<img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/1downarrow_selected.png" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'" class="imgdown">';
  1872. else return '<img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/1downarrow.png" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'" class="imgdown">';
  1873. }
  1874. /**
  1875. * Show logo top arrow
  1876. *
  1877. * @param alt Texte sur le alt de l'image
  1878. * @param selected Affiche version "selected" du logo
  1879. * @return string Retourne tag img
  1880. */
  1881. function img_up($alt = "default", $selected=0)
  1882. {
  1883. global $conf,$langs;
  1884. if ($alt=="default") $alt=$langs->trans("Up");
  1885. if ($selected) return '<img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/1uparrow_selected.png" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'" class="imgup">';
  1886. else return '<img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/1uparrow.png" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'" class="imgup">';
  1887. }
  1888. /**
  1889. * Affiche logo gauche
  1890. *
  1891. * @param alt Texte sur le alt de l'image
  1892. * @param selected Affiche version "selected" du logo
  1893. * @return string Retourne tag img
  1894. */
  1895. function img_left($alt = "default", $selected=0)
  1896. {
  1897. global $conf,$langs;
  1898. if ($alt=="default") $alt=$langs->trans("Left");
  1899. if ($selected) return '<img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/1leftarrow_selected.png" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'">';
  1900. else return '<img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/1leftarrow.png" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'">';
  1901. }
  1902. /**
  1903. * Affiche logo droite
  1904. *
  1905. * @param alt Texte sur le alt de l'image
  1906. * @param selected Affiche version "selected" du logo
  1907. * @return string Retourne tag img
  1908. */
  1909. function img_right($alt = "default", $selected=0)
  1910. {
  1911. global $conf,$langs;
  1912. if ($alt=="default") $alt=$langs->trans("Right");
  1913. if ($selected) return '<img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/1rightarrow_selected.png" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'">';
  1914. else return '<img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/1rightarrow.png" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'">';
  1915. }
  1916. /**
  1917. * Affiche le logo tick si allow
  1918. *
  1919. * @param allow Authorise ou non
  1920. * @param alt Alt text for img
  1921. * @return string Retourne tag img
  1922. */
  1923. function img_allow($allow,$alt='default')
  1924. {
  1925. global $conf,$langs;
  1926. if ($alt=="default") $alt=$langs->trans("Active");
  1927. if ($allow == 1)
  1928. {
  1929. return '<img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/tick.png" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'">';
  1930. }
  1931. else
  1932. {
  1933. return "-";
  1934. }
  1935. }
  1936. /**
  1937. * Show MIME img of a file
  1938. * @param file Filename
  1939. * @param alt Alternate text to show on img mous hover
  1940. * @return string Return img tag
  1941. */
  1942. function img_mime($file,$alt='')
  1943. {
  1944. require_once(DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php');
  1945. $mimetype=dol_mimetype($file,'',1);
  1946. $mimeimg=dol_mimetype($file,'',2);
  1947. if (empty($alt)) $alt='Mime type: '.$mimetype;
  1948. return '<img src="'.DOL_URL_ROOT.'/theme/common/mime/'.$mimeimg.'" border="0" alt="'.$alt.'" title="'.$alt.'">';
  1949. }
  1950. /**
  1951. * Show information for admin users
  1952. * @param text Text info
  1953. * @param infoonimgalt Info is shown only on alt of star picto, otherwise it is show on output after the star picto
  1954. * @return string String with info text
  1955. */
  1956. function info_admin($text,$infoonimgalt=0)
  1957. {
  1958. global $conf,$langs;
  1959. $s='';
  1960. if ($infoonimgalt)
  1961. {
  1962. $s.=img_picto($text,'star');
  1963. }
  1964. else
  1965. {
  1966. $s.='<div class="info">';
  1967. $s.=img_picto($langs->trans("InfoAdmin"),'star');
  1968. $s.=' ';
  1969. $s.=$text;
  1970. $s.='</div>';
  1971. }
  1972. return $s;
  1973. }
  1974. /**
  1975. * Check permissions of a user to show a page and an object. Check read permission.
  1976. * If GETPOST('action') defined, we also check write and delete permission.
  1977. *
  1978. * @param user User to check
  1979. * @param features Features to check (in most cases, it's module name)
  1980. * @param objectid Object ID if we want to check permission on a particular record (optionnal)
  1981. * @param dbtablename Table name where object is stored. Not used if objectid is null (optionnal)
  1982. * @param feature2 Feature to check, second level of permission (optionnal)
  1983. * @param dbt_keyfield Field name for socid foreign key if not fk_soc (optionnal)
  1984. * @param dbt_select Field name for select if not rowid (optionnal)
  1985. * @param objcanvas Object canvas
  1986. * @return int Always 1, die process if not allowed
  1987. */
  1988. function restrictedArea($user, $features='societe', $objectid=0, $dbtablename='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $objcanvas=null)
  1989. {
  1990. global $db, $conf;
  1991. //dol_syslog("functions.lib:restrictedArea $feature, $objectid, $dbtablename,$feature2,$dbt_socfield,$dbt_select");
  1992. //print "user_id=".$user->id.", features=".$features.", feature2=".$feature2.", objectid=".$objectid;
  1993. //print ", dbtablename=".$dbtablename.", dbt_socfield=".$dbt_keyfield.", dbt_select=".$dbt_select;
  1994. //print ", perm: ".$features."->".$feature2."=".$user->rights->$features->$feature2->lire."<br>";
  1995. // If we use canvas, we try to use function that overlod restrictarea if provided with canvas
  1996. if (is_object($objcanvas))
  1997. {
  1998. if (method_exists($objcanvas->control,'restrictedArea')) return $objcanvas->control->restrictedArea($user,$features,$objectid,$dbtablename,$feature2,$dbt_keyfield,$dbt_select);
  1999. }
  2000. if ($dbt_select != 'rowid') $objectid = "'".$objectid."'";
  2001. // More features to check
  2002. $features = explode("&",$features);
  2003. //var_dump($features);
  2004. // Check read permission from module
  2005. // TODO Replace "feature" param into caller by first level of permission
  2006. $readok=1;
  2007. foreach ($features as $feature)
  2008. {
  2009. if ($feature == 'societe')
  2010. {
  2011. if (! $user->rights->societe->lire && ! $user->rights->fournisseur->lire) $readok=0;
  2012. }
  2013. else if ($feature == 'contact')
  2014. {
  2015. if (! $user->rights->societe->contact->lire) $readok=0;
  2016. }
  2017. else if ($feature == 'produit|service')
  2018. {
  2019. if (! $user->rights->produit->lire && ! $user->rights->service->lire) $readok=0;
  2020. }
  2021. else if ($feature == 'prelevement')
  2022. {
  2023. if (! $user->rights->prelevement->bons->lire) $readok=0;
  2024. }
  2025. else if ($feature == 'commande_fournisseur')
  2026. {
  2027. if (! $user->rights->fournisseur->commande->lire) $readok=0;
  2028. }
  2029. else if ($feature == 'cheque')
  2030. {
  2031. if (! $user->rights->banque->cheque) $readok=0;
  2032. }
  2033. else if ($feature == 'projet')
  2034. {
  2035. if (! $user->rights->projet->lire && ! $user->rights->projet->all->lire) $readok=0;
  2036. }
  2037. else if (! empty($feature2)) // This should be used for future changes
  2038. {
  2039. if (empty($user->rights->$feature->$feature2->lire)
  2040. && empty($user->rights->$feature->$feature2->read)) $readok=0;
  2041. }
  2042. else if (! empty($feature) && ($feature!='user' && $feature!='usergroup')) // This is for old permissions
  2043. {
  2044. if (empty($user->rights->$feature->lire)
  2045. && empty($user->rights->$feature->read)
  2046. && empty($user->rights->$feature->run)) $readok=0;
  2047. }
  2048. }
  2049. if (! $readok)
  2050. {
  2051. //print "Read access is down";
  2052. accessforbidden();
  2053. }
  2054. //print "Read access is ok";
  2055. // Check write permission from module
  2056. $createok=1;
  2057. if (GETPOST("action") && GETPOST("action") == 'create')
  2058. {
  2059. foreach ($features as $feature)
  2060. {
  2061. if ($feature == 'contact')
  2062. {
  2063. if (! $user->rights->societe->contact->creer) $createok=0;
  2064. }
  2065. else if ($feature == 'produit|service')
  2066. {
  2067. if (! $user->rights->produit->creer && ! $user->rights->service->creer) $createok=0;
  2068. }
  2069. else if ($feature == 'prelevement')
  2070. {
  2071. if (! $user->rights->prelevement->bons->creer) $createok=0;
  2072. }
  2073. else if ($feature == 'commande_fournisseur')
  2074. {
  2075. if (! $user->rights->fournisseur->commande->creer) $createok=0;
  2076. }
  2077. else if ($feature == 'banque')
  2078. {
  2079. if (! $user->rights->banque->modifier) $createok=0;
  2080. }
  2081. else if ($feature == 'cheque')
  2082. {
  2083. if (! $user->rights->banque->cheque) $createok=0;
  2084. }
  2085. else if (! empty($feature2)) // This should be used for future changes
  2086. {
  2087. if (empty($user->rights->$feature->$feature2->creer)
  2088. && empty($user->rights->$feature->$feature2->write)) $createok=0;
  2089. }
  2090. else if (! empty($feature)) // This is for old permissions
  2091. {
  2092. //print '<br>feature='.$feature.' creer='.$user->rights->$feature->creer.' write='.$user->rights->$feature->write;
  2093. if (empty($user->rights->$feature->creer)
  2094. && empty($user->rights->$feature->write)) $createok=0;
  2095. }
  2096. }
  2097. if (! $createok) accessforbidden();
  2098. //print "Write access is ok";
  2099. }
  2100. // Check create user permission
  2101. $createuserok=1;
  2102. if ( GETPOST("action") && (GETPOST("action") == 'confirm_create_user' && GETPOST("confirm") == 'yes') )
  2103. {
  2104. if (! $user->rights->user->user->creer) $createuserok=0;
  2105. if (! $createuserok) accessforbidden();
  2106. //print "Create user access is ok";
  2107. }
  2108. // Check delete permission from module
  2109. $deleteok=1;
  2110. if ( GETPOST("action") && ( (GETPOST("action") == 'confirm_delete' && GETPOST("confirm") && GETPOST("confirm") == 'yes') || GETPOST("action") == 'delete') )
  2111. {
  2112. foreach ($features as $feature)
  2113. {
  2114. if ($feature == 'contact')
  2115. {
  2116. if (! $user->rights->societe->contact->supprimer) $deleteok=0;
  2117. }
  2118. else if ($feature == 'produit|service')
  2119. {
  2120. if (! $user->rights->produit->supprimer && ! $user->rights->service->supprimer) $deleteok=0;
  2121. }
  2122. else if ($feature == 'commande_fournisseur')
  2123. {
  2124. if (! $user->rights->fournisseur->commande->supprimer) $deleteok=0;
  2125. }
  2126. else if ($feature == 'banque')
  2127. {
  2128. if (! $user->rights->banque->modifier) $deleteok=0;
  2129. }
  2130. else if ($feature == 'cheque')
  2131. {
  2132. if (! $user->rights->banque->cheque) $deleteok=0;
  2133. }
  2134. else if ($feature == 'ecm')
  2135. {
  2136. if (! $user->rights->ecm->upload) $deleteok=0;
  2137. }
  2138. else if ($feature == 'ftp')
  2139. {
  2140. if (! $user->rights->ftp->write) $deleteok=0;
  2141. }
  2142. else if (! empty($feature2)) // This should be used for future changes
  2143. {
  2144. if (empty($user->rights->$feature->$feature2->supprimer)
  2145. && empty($user->rights->$feature->$feature2->delete)) $deleteok=0;
  2146. }
  2147. else if (! empty($feature)) // This is for old permissions
  2148. {
  2149. //print '<br>feature='.$feature.' creer='.$user->rights->$feature->supprimer.' write='.$user->rights->$feature->delete;
  2150. if (empty($user->rights->$feature->supprimer)
  2151. && empty($user->rights->$feature->delete)) $deleteok=0;
  2152. }
  2153. }
  2154. //print "Delete access is ko";
  2155. if (! $deleteok) accessforbidden();
  2156. //print "Delete access is ok";
  2157. }
  2158. // If we have a particular object to check permissions on, we check this object
  2159. // is linked to a company allowed to $user.
  2160. if (! empty($objectid) && $objectid > 0)
  2161. {
  2162. foreach ($features as $feature)
  2163. {
  2164. $sql='';
  2165. $check = array('banque','user','usergroup','produit','service','produit|service','categorie'); // Test on entity only (Objects with no link to company)
  2166. $checksoc = array('societe'); // Test for societe object
  2167. $checkother = array('contact'); // Test on entity and link to societe. Allowed if link is empty (Ex: contacts...).
  2168. $checkproject = array('projet'); // Test for project object
  2169. $nocheck = array('barcode','stock','fournisseur'); // No test
  2170. $checkdefault = 'all other not already defined'; // Test on entity and link to third party. Not allowed if link is empty (Ex: invoice, orders...).
  2171. // If dbtable not defined, we use same name for table than module name
  2172. if (empty($dbtablename)) $dbtablename = $feature;
  2173. // Check permission for object with entity
  2174. if (in_array($feature,$check))
  2175. {
  2176. $sql = "SELECT dbt.".$dbt_select;
  2177. $sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  2178. $sql.= " WHERE dbt.".$dbt_select." = ".$objectid;
  2179. if (($feature == 'user' || $feature == 'usergroup') && ! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
  2180. {
  2181. $sql.= " AND dbt.entity IS NOT NULL";
  2182. }
  2183. else
  2184. {
  2185. $sql.= " AND dbt.entity IN (0,".(! empty($conf->entities[$dbtablename]) ? $conf->entities[$dbtablename] : $conf->entity).")";
  2186. }
  2187. }
  2188. else if (in_array($feature,$checksoc))
  2189. {
  2190. // If external user: Check permission for external users
  2191. if ($user->societe_id > 0)
  2192. {
  2193. if ($user->societe_id <> $objectid) accessforbidden();
  2194. }
  2195. // If internal user: Check permission for internal users that are restricted on their objects
  2196. else if (! $user->rights->societe->client->voir)
  2197. {
  2198. $sql = "SELECT sc.fk_soc";
  2199. $sql.= " FROM (".MAIN_DB_PREFIX."societe_commerciaux as sc";
  2200. $sql.= ", ".MAIN_DB_PREFIX."societe as s)";
  2201. $sql.= " WHERE sc.fk_soc = ".$objectid;
  2202. $sql.= " AND sc.fk_user = ".$user->id;
  2203. $sql.= " AND sc.fk_soc = s.rowid";
  2204. $sql.= " AND s.entity IN (0,".(! empty($conf->entities[$dbtablename]) ? $conf->entities[$dbtablename] : $conf->entity).")";
  2205. }
  2206. // If multicompany and internal users with all permissions, check user is in correct entity
  2207. else if (! empty($conf->multicompany->enabled))
  2208. {
  2209. $sql = "SELECT s.rowid";
  2210. $sql.= " FROM ".MAIN_DB_PREFIX."societe as s";
  2211. $sql.= " WHERE s.rowid = ".$objectid;
  2212. $sql.= " AND s.entity IN (0,".(! empty($conf->entities[$dbtablename]) ? $conf->entities[$dbtablename] : $conf->entity).")";
  2213. }
  2214. }
  2215. else if (in_array($feature,$checkother))
  2216. {
  2217. // If external user: Check permission for external users
  2218. if ($user->societe_id > 0)
  2219. {
  2220. $sql = "SELECT dbt.rowid";
  2221. $sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  2222. $sql.= " WHERE dbt.rowid = ".$objectid;
  2223. $sql.= " AND dbt.fk_soc = ".$user->societe_id;
  2224. }
  2225. // If internal user: Check permission for internal users that are restricted on their objects
  2226. else if (! $user->rights->societe->client->voir)
  2227. {
  2228. $sql = "SELECT dbt.rowid";
  2229. $sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  2230. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON dbt.fk_soc = sc.fk_soc AND sc.fk_user = '".$user->id."'";
  2231. $sql.= " WHERE dbt.rowid = ".$objectid;
  2232. $sql.= " AND (dbt.fk_soc IS NULL OR sc.fk_soc IS NOT NULL)"; // Contact not linked to a company or to a company of user
  2233. $sql.= " AND dbt.entity IN (0,".(! empty($conf->entities[$dbtablename]) ? $conf->entities[$dbtablename] : $conf->entity).")";
  2234. }
  2235. // If multicompany and internal users with all permissions, check user is in correct entity
  2236. else if (! empty($conf->multicompany->enabled))
  2237. {
  2238. $sql = "SELECT dbt.rowid";
  2239. $sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  2240. $sql.= " WHERE dbt.rowid = ".$objectid;
  2241. $sql.= " AND dbt.entity IN (0,".(! empty($conf->entities[$dbtablename]) ? $conf->entities[$dbtablename] : $conf->entity).")";
  2242. }
  2243. }
  2244. else if (in_array($feature,$checkproject))
  2245. {
  2246. if (! $user->rights->projet->all->lire)
  2247. {
  2248. include_once(DOL_DOCUMENT_ROOT."/projet/class/project.class.php");
  2249. $projectstatic=new Project($db);
  2250. $tmps=$projectstatic->getProjectsAuthorizedForUser($user,0,1,$user->societe_id);
  2251. $tmparray=explode(',',$tmps);
  2252. if (! in_array($objectid,$tmparray)) accessforbidden();
  2253. }
  2254. }
  2255. else if (! in_array($feature,$nocheck)) // By default we check with link to third party
  2256. {
  2257. // If external user: Check permission for external users
  2258. if ($user->societe_id > 0)
  2259. {
  2260. $sql = "SELECT dbt.".$dbt_keyfield;
  2261. $sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  2262. $sql.= " WHERE dbt.rowid = ".$objectid;
  2263. $sql.= " AND dbt.".$dbt_keyfield." = ".$user->societe_id;
  2264. }
  2265. // If internal user: Check permission for internal users that are restricted on their objects
  2266. else if (! $user->rights->societe->client->voir)
  2267. {
  2268. $sql = "SELECT sc.fk_soc";
  2269. $sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  2270. $sql.= ", ".MAIN_DB_PREFIX."societe as s";
  2271. $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  2272. $sql.= " WHERE dbt.".$dbt_select." = ".$objectid;
  2273. $sql.= " AND sc.fk_soc = dbt.".$dbt_keyfield;
  2274. $sql.= " AND dbt.".$dbt_keyfield." = s.rowid";
  2275. $sql.= " AND s.entity IN (0,".(! empty($conf->entities[$dbtablename]) ? $conf->entities[$dbtablename] : $conf->entity).")";
  2276. $sql.= " AND sc.fk_user = ".$user->id;
  2277. }
  2278. // If multicompany and internal users with all permissions, check user is in correct entity
  2279. else if (! empty($conf->multicompany->enabled))
  2280. {
  2281. $sql = "SELECT dbt.".$dbt_select;
  2282. $sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  2283. $sql.= " WHERE dbt.".$dbt_select." = ".$objectid;
  2284. $sql.= " AND dbt.entity IN (0,".(! empty($conf->entities[$dbtablename]) ? $conf->entities[$dbtablename] : $conf->entity).")";
  2285. }
  2286. }
  2287. //print $sql."<br>";
  2288. if ($sql)
  2289. {
  2290. $resql=$db->query($sql);
  2291. if ($resql)
  2292. {
  2293. if ($db->num_rows($resql) == 0) accessforbidden();
  2294. }
  2295. else
  2296. {
  2297. dol_syslog("functions.lib:restrictedArea sql=".$sql, LOG_ERR);
  2298. accessforbidden();
  2299. }
  2300. }
  2301. }
  2302. }
  2303. return 1;
  2304. }
  2305. /**
  2306. * Show a message to say access is forbidden and stop program
  2307. * Calling this function terminate execution of PHP.
  2308. * @param message Force error message
  2309. * @param printheader Show header before
  2310. * @param printfooter Show footer after
  2311. * @param showonlymessage Show only message parameter. Otherwise add more information.
  2312. */
  2313. function accessforbidden($message='',$printheader=1,$printfooter=1,$showonlymessage=0)
  2314. {
  2315. global $conf, $db, $user, $langs;
  2316. if (! is_object($langs))
  2317. {
  2318. include_once(DOL_DOCUMENT_ROOT.'/core/class/translate.class.php');
  2319. $langs=new Translate('',$conf);
  2320. }
  2321. $langs->load("errors");
  2322. if ($printheader)
  2323. {
  2324. if (function_exists("llxHeader")) llxHeader('');
  2325. else if (function_exists("llxHeaderVierge")) llxHeaderVierge('');
  2326. }
  2327. print '<div class="error">';
  2328. if (! $message) print $langs->trans("ErrorForbidden");
  2329. else print $message;
  2330. print '</div>';
  2331. print '<br>';
  2332. if (empty($showonlymessage))
  2333. {
  2334. if ($user->login)
  2335. {
  2336. print $langs->trans("CurrentLogin").': <font class="error">'.$user->login.'</font><br>';
  2337. print $langs->trans("ErrorForbidden2",$langs->trans("Home"),$langs->trans("Users"));
  2338. }
  2339. else
  2340. {
  2341. print $langs->trans("ErrorForbidden3");
  2342. }
  2343. }
  2344. if ($printfooter && function_exists("llxFooter")) llxFooter();
  2345. exit(0);
  2346. }
  2347. /* For backward compatibility */
  2348. function dolibarr_print_error($db='',$error='')
  2349. {
  2350. return dol_print_error($db, $error);
  2351. }
  2352. /**
  2353. * Affiche message erreur system avec toutes les informations pour faciliter le diagnostic et la remontee des bugs.
  2354. * On doit appeler cette fonction quand une erreur technique bloquante est rencontree.
  2355. * Toutefois, il faut essayer de ne l'appeler qu'au sein de pages php, les classes devant
  2356. * renvoyer leur erreur par l'intermediaire de leur propriete "error".
  2357. * @param db Database handler
  2358. * @param error String or array of errors strings to show
  2359. * @see dol_htmloutput_errors
  2360. */
  2361. function dol_print_error($db='',$error='')
  2362. {
  2363. global $conf,$langs,$argv;
  2364. global $dolibarr_main_prod;
  2365. $out = '';
  2366. $syslog = '';
  2367. // Si erreur intervenue avant chargement langue
  2368. if (! $langs)
  2369. {
  2370. require_once(DOL_DOCUMENT_ROOT ."/core/class/translate.class.php");
  2371. $langs = new Translate("", $conf);
  2372. $langs->load("main");
  2373. }
  2374. $langs->load("main");
  2375. $langs->load("errors");
  2376. if ($_SERVER['DOCUMENT_ROOT']) // Mode web
  2377. {
  2378. $out.=$langs->trans("DolibarrHasDetectedError").".<br>\n";
  2379. if (! empty($conf->global->MAIN_FEATURES_LEVEL))
  2380. $out.="You use an experimental level of features, so please do NOT report any bugs, anywhere, until going back to MAIN_FEATURES_LEVEL = 0.<br>\n";
  2381. $out.=$langs->trans("InformationToHelpDiagnose").":<br>\n";
  2382. $out.="<b>".$langs->trans("Date").":</b> ".dol_print_date(time(),'dayhourlog')."<br>\n";;
  2383. $out.="<b>".$langs->trans("Dolibarr").":</b> ".DOL_VERSION."<br>\n";;
  2384. if (isset($conf->global->MAIN_FEATURES_LEVEL)) $out.="<b>".$langs->trans("LevelOfFeature").":</b> ".$conf->global->MAIN_FEATURES_LEVEL."<br>\n";;
  2385. if (function_exists("phpversion"))
  2386. {
  2387. $out.="<b>".$langs->trans("PHP").":</b> ".phpversion()."<br>\n";
  2388. //phpinfo(); // This is to show location of php.ini file
  2389. }
  2390. $out.="<b>".$langs->trans("Server").":</b> ".$_SERVER["SERVER_SOFTWARE"]."<br>\n";;
  2391. $out.="<br>\n";
  2392. $out.="<b>".$langs->trans("RequestedUrl").":</b> ".$_SERVER["REQUEST_URI"]."<br>\n";;
  2393. $out.="<b>".$langs->trans("Referer").":</b> ".(isset($_SERVER["HTTP_REFERER"])?$_SERVER["HTTP_REFERER"]:'')."<br>\n";;
  2394. $out.="<b>".$langs->trans("MenuManager").":</b> ".$conf->top_menu."<br>\n";
  2395. $out.="<br>\n";
  2396. $syslog.="url=".$_SERVER["REQUEST_URI"];
  2397. $syslog.=", query_string=".$_SERVER["QUERY_STRING"];
  2398. }
  2399. else // Mode CLI
  2400. {
  2401. $out.='> '.$langs->transnoentities("ErrorInternalErrorDetected").":\n".$argv[0]."\n";
  2402. $syslog.="pid=".getmypid();
  2403. }
  2404. if (is_object($db))
  2405. {
  2406. if ($_SERVER['DOCUMENT_ROOT']) // Mode web
  2407. {
  2408. $out.="<b>".$langs->trans("DatabaseTypeManager").":</b> ".$db->type."<br>\n";
  2409. $out.="<b>".$langs->trans("RequestLastAccessInError").":</b> ".($db->lastqueryerror()?$db->lastqueryerror():$langs->trans("ErrorNoRequestInError"))."<br>\n";
  2410. $out.="<b>".$langs->trans("ReturnCodeLastAccessInError").":</b> ".($db->lasterrno()?$db->lasterrno():$langs->trans("ErrorNoRequestInError"))."<br>\n";
  2411. $out.="<b>".$langs->trans("InformationLastAccessInError").":</b> ".($db->lasterror()?$db->lasterror():$langs->trans("ErrorNoRequestInError"))."<br>\n";
  2412. $out.="<br>\n";
  2413. }
  2414. else // Mode CLI
  2415. {
  2416. $out.='> '.$langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n";
  2417. $out.='> '.$langs->transnoentities("RequestLastAccessInError").":\n".($db->lastqueryerror()?$db->lastqueryerror():$langs->trans("ErrorNoRequestInError"))."\n";
  2418. $out.='> '.$langs->transnoentities("ReturnCodeLastAccessInError").":\n".($db->lasterrno()?$db->lasterrno():$langs->trans("ErrorNoRequestInError"))."\n";
  2419. $out.='> '.$langs->transnoentities("InformationLastAccessInError").":\n".($db->lasterror()?$db->lasterror():$langs->trans("ErrorNoRequestInError"))."\n";
  2420. }
  2421. $syslog.=", sql=".$db->lastquery();
  2422. $syslog.=", db_error=".$db->lasterror();
  2423. }
  2424. if ($error)
  2425. {
  2426. $langs->load("errors");
  2427. if (is_array($error)) $errors=$error;
  2428. else $errors=array($error);
  2429. foreach($errors as $msg)
  2430. {
  2431. $msg=$langs->trans($msg);
  2432. if ($_SERVER['DOCUMENT_ROOT']) // Mode web
  2433. {
  2434. $out.="<b>".$langs->trans("Message").":</b> ".$msg."<br>\n" ;
  2435. }
  2436. else // Mode CLI
  2437. {
  2438. $out.='> '.$langs->transnoentities("Message").":\n".$msg."\n" ;
  2439. }
  2440. $syslog.=", msg=".$msg;
  2441. }
  2442. }
  2443. if (empty($dolibarr_main_prod) && $_SERVER['DOCUMENT_ROOT'] && function_exists('xdebug_call_file'))
  2444. {
  2445. xdebug_print_function_stack();
  2446. $out.='<b>XDebug informations:</b>'."<br>\n";
  2447. $out.='File: '.xdebug_call_file()."<br>\n";
  2448. $out.='Line: '.xdebug_call_line()."<br>\n";
  2449. $out.='Function: '.xdebug_call_function()."<br>\n";
  2450. $out.="<br>\n";
  2451. }
  2452. if (empty($dolibarr_main_prod)) print $out;
  2453. else define("MAIN_CORE_ERROR", 1);
  2454. //else print 'Sorry, an error occured but the parameter $dolibarr_main_prod is defined in conf file so no message is reported to your browser. Please read the log file for error message.';
  2455. dol_syslog("Error ".$syslog, LOG_ERR);
  2456. }
  2457. /**
  2458. * Show email to contact if technical error
  2459. */
  2460. function dol_print_error_email()
  2461. {
  2462. global $langs,$conf;
  2463. $langs->load("errors");
  2464. print '<br><div class="error">'.$langs->trans("ErrorContactEMail",$conf->global->MAIN_INFO_SOCIETE_MAIL,'ERRORNEWPAYMENT'.dol_print_date(mktime(),'%Y%m%d')).'</div>';
  2465. }
  2466. /**
  2467. * Show title line of an array
  2468. *
  2469. * @param name Label of field
  2470. * @param file Url used when we click on sort picto
  2471. * @param field Field to use for new sorting
  2472. * @param begin ("" by defaut)
  2473. * @param moreparam Add more parameters on sort url links ("" by default)
  2474. * @param td Options of attribute td ("" by defaut)
  2475. * @param sortfield Current field used to sort
  2476. * @param sortorder Current sort order
  2477. */
  2478. function print_liste_field_titre($name, $file="", $field="", $begin="", $moreparam="", $td="", $sortfield="", $sortorder="")
  2479. {
  2480. print getTitleFieldOfList($name, 0, $file, $field, $begin, $moreparam, $td, $sortfield, $sortorder);
  2481. }
  2482. /**
  2483. * Get title line of an array
  2484. *
  2485. * @param name Label of field
  2486. * @param thead For thead format
  2487. * @param file Url used when we click on sort picto
  2488. * @param field Field to use for new sorting
  2489. * @param begin ("" by defaut)
  2490. * @param moreparam Add more parameters on sort url links ("" by default)
  2491. * @param moreattrib Add more attributes on th ("" by defaut)
  2492. * @param sortfield Current field used to sort
  2493. * @param sortorder Current sort order
  2494. */
  2495. function getTitleFieldOfList($name, $thead=0, $file="", $field="", $begin="", $moreparam="", $moreattrib="", $sortfield="", $sortorder="")
  2496. {
  2497. global $conf;
  2498. //print "$name, $file, $field, $begin, $options, $moreattrib, $sortfield, $sortorder<br>\n";
  2499. $out='';
  2500. // If field is used as sort criteria we use a specific class
  2501. // Example if (sortfield,field)=("nom","xxx.nom") or (sortfield,field)=("nom","nom")
  2502. if ($field && ($sortfield == $field || $sortfield == preg_replace("/^[^\.]+\./","",$field)))
  2503. {
  2504. $out.= '<th class="liste_titre_sel" '. $moreattrib.'>';
  2505. }
  2506. else
  2507. {
  2508. $out.= '<th class="liste_titre" '. $moreattrib.'>';
  2509. }
  2510. $out.=$name;
  2511. if (empty($thead) && $field) // If this is a sort field
  2512. {
  2513. $options=preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i','',$moreparam);
  2514. $options=preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i','',$options);
  2515. $options=preg_replace('/&+/i','&',$options);
  2516. if (! preg_match('/^&/',$options)) $options='&'.$options;
  2517. //print "&nbsp;";
  2518. $out.= '<img width="2" src="'.DOL_URL_ROOT.'/theme/common/transparent.png" alt="">';
  2519. if (! $sortorder)
  2520. {
  2521. $out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  2522. $out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  2523. }
  2524. else
  2525. {
  2526. if ($field != $sortfield)
  2527. {
  2528. $out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  2529. $out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  2530. }
  2531. else {
  2532. $sortorder=strtoupper($sortorder);
  2533. if ($sortorder == 'DESC' ) {
  2534. $out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  2535. $out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",1).'</a>';
  2536. }
  2537. if ($sortorder == 'ASC' ) {
  2538. $out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",1).'</a>';
  2539. $out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  2540. }
  2541. }
  2542. }
  2543. }
  2544. $out.='</th>';
  2545. return $out;
  2546. }
  2547. /**
  2548. * Show a title (deprecated. use print_fiche_titre instrad)
  2549. * @param titre Title to show
  2550. */
  2551. function print_titre($titre)
  2552. {
  2553. print '<div class="titre">'.$titre.'</div>';
  2554. }
  2555. /**
  2556. * Show a title with picto
  2557. * @param titre Title to show
  2558. * @param mesg Added message to show on right
  2559. * @param picto Icon to use before title (should be a 32x32 transparent png file)
  2560. * @param pictoisfullpath 1=Icon name is a full absolute url of image
  2561. * @param id To force an id on html objects
  2562. */
  2563. function print_fiche_titre($titre, $mesg='', $picto='title.png', $pictoisfullpath=0, $id='')
  2564. {
  2565. print load_fiche_titre($titre, $mesg, $picto, $pictoisfullpath, $id);
  2566. }
  2567. /**
  2568. * Load a title with picto
  2569. *
  2570. * @param titre Title to show
  2571. * @param mesg Added message to show on right
  2572. * @param picto Icon to use before title (should be a 32x32 transparent png file)
  2573. * @param pictoisfullpath 1=Icon name is a full absolute url of image
  2574. * @param id To force an id on html objects
  2575. */
  2576. function load_fiche_titre($titre, $mesg='', $picto='title.png', $pictoisfullpath=0, $id='')
  2577. {
  2578. global $conf;
  2579. $return='';
  2580. if ($picto == 'setup') $picto='title.png';
  2581. if (!empty($conf->browser->ie) && $picto=='title.png') $picto='title.gif';
  2582. $return.= "\n";
  2583. $return.= '<table '.($id?'id="'.$id.'" ':'').'summary="" width="100%" border="0" class="notopnoleftnoright" style="margin-bottom: 2px;"><tr>';
  2584. if ($picto) $return.= '<td class="nobordernopadding hideonsmartphone" width="40" align="left" valign="middle">'.img_picto('',$picto, 'id="pictotitle"', $pictoisfullpath).'</td>';
  2585. $return.= '<td class="nobordernopadding" valign="middle">';
  2586. $return.= '<div class="titre">'.$titre.'</div>';
  2587. $return.= '</td>';
  2588. if (dol_strlen($mesg))
  2589. {
  2590. $return.= '<td class="nobordernopadding" align="right" valign="middle"><b>'.$mesg.'</b></td>';
  2591. }
  2592. $return.= '</tr></table>'."\n";
  2593. return $return;
  2594. }
  2595. /**
  2596. * Print a title with navigation controls for pagination
  2597. *
  2598. * @param titre Title to show (required)
  2599. * @param page Numero of page (required)
  2600. * @param file Url of page (required)
  2601. * @param options parametres complementaires lien ('' par defaut)
  2602. * @param sortfield champ de tri ('' par defaut)
  2603. * @param sortorder ordre de tri ('' par defaut)
  2604. * @param center chaine du centre ('' par defaut)
  2605. * @param num number of records found by select with limit+1
  2606. * @param totalnboflines Total number of records/lines for all pages (if known)
  2607. * @param picto Icon to use before title (should be a 32x32 transparent png file)
  2608. * @param pictoisfullpath 1=Icon name is a full absolute url of image
  2609. * @return void
  2610. */
  2611. function print_barre_liste($titre, $page, $file, $options='', $sortfield='', $sortorder='', $center='', $num=-1, $totalnboflines=0, $picto='title.png', $pictoisfullpath=0)
  2612. {
  2613. global $conf,$langs;
  2614. if ($picto == 'setup') $picto='title.png';
  2615. if (!empty($conf->browser->ie) && $picto=='title.png') $picto='title.gif';
  2616. if ($num > $conf->liste_limit or $num == -1)
  2617. {
  2618. $nextpage = 1;
  2619. }
  2620. else
  2621. {
  2622. $nextpage = 0;
  2623. }
  2624. print "\n";
  2625. print "<!-- Begin title '".$titre."' -->\n";
  2626. print '<table width="100%" border="0" class="notopnoleftnoright" style="margin-bottom: 2px;"><tr>';
  2627. $pagelist = '';
  2628. // Left
  2629. if ($page > 0 || $num > $conf->liste_limit)
  2630. {
  2631. if ($totalnboflines)
  2632. {
  2633. if ($picto && $titre) print '<td class="nobordernopadding" width="40" align="left" valign="middle">'.img_picto('',$picto, '', $pictoisfullpath).'</td>';
  2634. print '<td class="nobordernopadding">';
  2635. print '<div class="titre">'.$titre.'</div>';
  2636. print '</td>';
  2637. $maxnbofpage=10;
  2638. $nbpages=ceil($totalnboflines/$conf->liste_limit);
  2639. $cpt=($page-$maxnbofpage);
  2640. if ($cpt < 0) { $cpt=0; }
  2641. $pagelist.=$langs->trans('Page');
  2642. if ($cpt>=1)
  2643. {
  2644. $pagelist.=' <a href="'.$file.'?page=0'.$options.'&amp;sortfield='.$sortfield.'&amp;sortorder='.$sortorder.'">1</a>';
  2645. if ($cpt >= 2) $pagelist.=' ...';
  2646. }
  2647. do
  2648. {
  2649. if($cpt==$page)
  2650. {
  2651. $pagelist.= ' <u>'.($page+1).'</u>';
  2652. }
  2653. else
  2654. {
  2655. $pagelist.= ' <a href="'.$file.'?page='.$cpt.$options.'&amp;sortfield='.$sortfield.'&amp;sortorder='.$sortorder.'">'.($cpt+1).'</a>';
  2656. }
  2657. $cpt++;
  2658. }
  2659. while ($cpt < $nbpages && $cpt<=$page+$maxnbofpage);
  2660. if ($cpt<$nbpages)
  2661. {
  2662. if ($cpt<$nbpages-1) $pagelist.= ' ...';
  2663. $pagelist.= ' <a href="'.$file.'?page='.($nbpages-1).$options.'&amp;sortfield='.$sortfield.'&amp;sortorder='.$sortorder.'">'.$nbpages.'</a>';
  2664. }
  2665. }
  2666. else
  2667. {
  2668. if (empty($conf->browser->phone) && $picto && $titre) print '<td class="nobordernopadding" width="40" align="left" valign="middle">'.img_picto('',$picto, '', $pictoisfullpath).'</td>';
  2669. print '<td class="nobordernopadding">';
  2670. print '<div class="titre">'.$titre.'</div>';
  2671. $pagelist.= $langs->trans('Page').' '.($page+1);
  2672. print '</td>';
  2673. }
  2674. }
  2675. else
  2676. {
  2677. if (empty($conf->browser->phone) && $picto && $titre) print '<td class="nobordernopadding" width="40" align="left" valign="middle">'.img_picto('',$picto, '', $pictoisfullpath).'</td>';
  2678. print '<td class="nobordernopadding"><div class="titre">'.$titre.'</div></td>';
  2679. }
  2680. // Center
  2681. if ($center)
  2682. {
  2683. print '<td class="nobordernopadding" align="left" valign="middle">'.$center.'</td>';
  2684. }
  2685. // Right
  2686. print '<td class="nobordernopadding" align="right" valign="middle">';
  2687. if ($sortfield) $options .= "&amp;sortfield=".$sortfield;
  2688. if ($sortorder) $options .= "&amp;sortorder=".$sortorder;
  2689. // Affichage des fleches de navigation
  2690. print_fleche_navigation($page,$file,$options,$nextpage,$pagelist);
  2691. print '</td>';
  2692. print '</tr></table>'."\n";
  2693. print "<!-- End title -->\n\n";
  2694. }
  2695. /**
  2696. * Fonction servant a afficher les fleches de navigation dans les pages de listes
  2697. *
  2698. * @param int $page Numero of page
  2699. * @param string $file Lien
  2700. * @param string $options Autres parametres d'url a propager dans les liens ("" par defaut)
  2701. * @param int $nextpage Faut-il une page suivante
  2702. * @param string $betweenarrows HTML Content to show between arrows
  2703. * @return void
  2704. */
  2705. function print_fleche_navigation($page,$file,$options='',$nextpage,$betweenarrows='')
  2706. {
  2707. global $conf, $langs;
  2708. if ($page > 0)
  2709. {
  2710. print '<a href="'.$file.'?page='.($page-1).$options.'">'.img_previous($langs->trans("Previous")).'</a>';
  2711. }
  2712. if ($betweenarrows) print ($page > 0?' ':'').$betweenarrows.($nextpage>0?' ':'');
  2713. if ($nextpage > 0)
  2714. {
  2715. print '<a href="'.$file.'?page='.($page+1).$options.'">'.img_next($langs->trans("Next")).'</a>';
  2716. }
  2717. }
  2718. /**
  2719. * Return a string with VAT rate label formated for view output
  2720. * Used into pdf and HTML pages
  2721. *
  2722. * @param float $rate Rate value to format (19.6 19,6 19.6% 19,6%,...)
  2723. * @param boolean $addpercent Add a percent % sign in output
  2724. * @param int $info_bits Miscellanous information on vat (0=Default, 1=French NPR vat)
  2725. * @param int $usestarfornpr 1=Use '*' for NPR vat rate intead of MAIN_LABEL_MENTION_NPR
  2726. * @return string String with formated amounts (19,6 or 19,6% or 8.5% NPR or 8.5% *)
  2727. */
  2728. function vatrate($rate,$addpercent=false,$info_bits=0,$usestarfornpr=0)
  2729. {
  2730. // Test for compatibility
  2731. if (preg_match('/%/',$rate))
  2732. {
  2733. $rate=str_replace('%','',$rate);
  2734. $addpercent=true;
  2735. }
  2736. if (preg_match('/\*/',$rate) || preg_match('/'.constant('MAIN_LABEL_MENTION_NPR').'/i',$rate))
  2737. {
  2738. $rate=str_replace('*','',$rate);
  2739. $info_bits |= 1;
  2740. }
  2741. $ret=price($rate,0,'',0,0).($addpercent?'%':'');
  2742. if ($info_bits & 1) $ret.=' '.($usestarfornpr?'*':constant('MAIN_LABEL_MENTION_NPR'));
  2743. return $ret;
  2744. }
  2745. /**
  2746. * Fonction qui formate un montant pour visualisation
  2747. * Fonction utilisee dans les pdf et les pages html
  2748. *
  2749. * @param float $amount Montant a formater
  2750. * @param string $form Type de formatage, html ou pas (par defaut)
  2751. * @param Translate $outlangs Objet langs pour formatage text
  2752. * @param int $trunc 1=Tronque affichage si trop de decimales,0=Force le non troncage
  2753. * @param int $rounding Minimum number of decimal. If not defined we use min($conf->global->MAIN_MAX_DECIMALS_UNIT,$conf->global->MAIN_MAX_DECIMALS_TOTAL)
  2754. * @param int $forcerounding Force the number of decimal
  2755. * @return string Chaine avec montant formate
  2756. *
  2757. * @see price2num Revert function of price
  2758. */
  2759. function price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1)
  2760. {
  2761. global $langs,$conf;
  2762. // Clean parameters
  2763. if (empty($amount)) $amount=0; // To have a numeric value if amount not defined or = ''
  2764. if ($rounding < 0) $rounding=min($conf->global->MAIN_MAX_DECIMALS_UNIT,$conf->global->MAIN_MAX_DECIMALS_TOT);
  2765. $nbdecimal=$rounding;
  2766. // Output separators by default (french)
  2767. $dec=','; $thousand=' ';
  2768. // If $outlangs not forced, we use use language
  2769. if (! is_object($outlangs)) $outlangs=$langs;
  2770. if ($outlangs->trans("SeparatorDecimal") != "SeparatorDecimal") $dec=$outlangs->trans("SeparatorDecimal");
  2771. if ($outlangs->trans("SeparatorThousand")!= "SeparatorThousand") $thousand=$outlangs->trans("SeparatorThousand");
  2772. if ($thousand == 'None') $thousand='';
  2773. //print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  2774. //print "amount=".$amount."-";
  2775. $amount = str_replace(',','.',$amount); // should be useless
  2776. //print $amount."-";
  2777. $datas = explode('.',$amount);
  2778. $decpart = isset($datas[1])?$datas[1]:'';
  2779. $decpart = preg_replace('/0+$/i','',$decpart); // Supprime les 0 de fin de partie decimale
  2780. //print "decpart=".$decpart."<br>";
  2781. $end='';
  2782. // We increase nbdecimal if there is more decimal than asked (to not loose information)
  2783. if (dol_strlen($decpart) > $nbdecimal) $nbdecimal=dol_strlen($decpart);
  2784. // Si on depasse max
  2785. if ($trunc && $nbdecimal > $conf->global->MAIN_MAX_DECIMALS_SHOWN)
  2786. {
  2787. $nbdecimal=$conf->global->MAIN_MAX_DECIMALS_SHOWN;
  2788. if (preg_match('/\.\.\./i',$conf->global->MAIN_MAX_DECIMALS_SHOWN))
  2789. {
  2790. // Si un affichage est tronque, on montre des ...
  2791. $end='...';
  2792. }
  2793. }
  2794. // If force rounding
  2795. if ($forcerounding >= 0) $nbdecimal = $forcerounding;
  2796. // Format number
  2797. if ($form)
  2798. {
  2799. $output=preg_replace('/\s/','&nbsp;',number_format($amount, $nbdecimal, $dec, $thousand));
  2800. }
  2801. else
  2802. {
  2803. $output=number_format($amount, $nbdecimal, $dec, $thousand);
  2804. }
  2805. $output.=$end;
  2806. return $output;
  2807. }
  2808. /**
  2809. * Function that return a number with universal decimal format (decimal separator is '.') from
  2810. * an amount typed by a user.
  2811. * Function to use on each input amount before any numeric test or database insert
  2812. *
  2813. * @param float $amount Amount to convert/clean
  2814. * @param string $rounding ''=No rounding
  2815. * 'MU'=Round to Max unit price (MAIN_MAX_DECIMALS_UNIT)
  2816. * 'MT'=Round to Max for totals with Tax (MAIN_MAX_DECIMALS_TOT)
  2817. * 'MS'=Round to Max Shown (MAIN_MAX_DECIMALS_SHOWN)
  2818. * @param int $alreadysqlnb Put 1 if you know that content is already universal format number
  2819. * @return string Amount with universal numeric format (Example: '99.99999')
  2820. *
  2821. * @see price Opposite function of price2num
  2822. */
  2823. function price2num($amount,$rounding='',$alreadysqlnb=0)
  2824. {
  2825. global $langs,$conf;
  2826. // Round PHP function does not allow number like '1,234.56' nor '1.234,56' nor '1 234,56'
  2827. // Numbers must be '1234.56'
  2828. // Decimal delimiter for PHP and database SQL requests must be '.'
  2829. $dec=','; $thousand=' ';
  2830. if ($langs->trans("SeparatorDecimal") != "SeparatorDecimal") $dec=$langs->trans("SeparatorDecimal");
  2831. if ($langs->trans("SeparatorThousand")!= "SeparatorThousand") $thousand=$langs->trans("SeparatorThousand");
  2832. if ($thousand == 'None') $thousand='';
  2833. //print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  2834. // Convert value to universal number format (no thousand separator, '.' as decimal separator)
  2835. if ($alreadysqlnb != 1) // If not a PHP number or unknown, we change format
  2836. {
  2837. //print 'PP'.$amount.' - '.$dec.' - '.$thousand.'<br>';
  2838. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  2839. // to format defined by LC_NUMERIC after a calculation and we want source format to be like defined by Dolibarr setup.
  2840. if (is_numeric($amount))
  2841. {
  2842. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  2843. $temps=sprintf("%0.10F",$amount-intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  2844. $temps=preg_replace('/([\.1-9])0+$/','\\1',$temps); // temps=0. or 0.00002 or 9999.1
  2845. $nbofdec=max(0,dol_strlen($temps)-2); // -2 to remove "0."
  2846. $amount=number_format($amount,$nbofdec,$dec,$thousand);
  2847. }
  2848. //print "QQ".$amount.'<br>';
  2849. // Now make replace (the main goal of function)
  2850. if ($thousand != ',' && $thousand != '.') $amount=str_replace(',','.',$amount); // To accept 2 notations for french users
  2851. $amount=str_replace(' ','',$amount); // To avoid spaces
  2852. $amount=str_replace($thousand,'',$amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  2853. $amount=str_replace($dec,'.',$amount);
  2854. }
  2855. // Now, make a rounding if required
  2856. if ($rounding)
  2857. {
  2858. $nbofdectoround='';
  2859. if ($rounding == 'MU') $nbofdectoround=$conf->global->MAIN_MAX_DECIMALS_UNIT;
  2860. elseif ($rounding == 'MT') $nbofdectoround=$conf->global->MAIN_MAX_DECIMALS_TOT;
  2861. elseif ($rounding == 'MS') $nbofdectoround=$conf->global->MAIN_MAX_DECIMALS_SHOWN;
  2862. elseif ($rounding == '2') $nbofdectoround=2; // For admin info page
  2863. //print "RR".$amount.' - '.$nbofdectoround.'<br>';
  2864. if (dol_strlen($nbofdectoround)) $amount = round($amount,$nbofdectoround); // $nbofdectoround can be 0.
  2865. else return 'ErrorBadParameterProvidedToFunction';
  2866. //print 'SS'.$amount.' - '.$nbofdec.' - '.$dec.' - '.$thousand.' - '.$nbofdectoround.'<br>';
  2867. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  2868. // to format defined by LC_NUMERIC after a calculation and we want source format to be defined by Dolibarr setup.
  2869. if (is_numeric($amount))
  2870. {
  2871. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  2872. $temps=sprintf("%0.10F",$amount-intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  2873. $temps=preg_replace('/([\.1-9])0+$/','\\1',$temps); // temps=0. or 0.00002 or 9999.1
  2874. $nbofdec=max(0,dol_strlen($temps)-2); // -2 to remove "0."
  2875. $amount=number_format($amount,min($nbofdec,$nbofdectoround),$dec,$thousand); // Convert amount to format with dolibarr dec and thousand
  2876. }
  2877. //print "TT".$amount.'<br>';
  2878. // Always make replace because each math function (like round) replace
  2879. // with local values and we want a number that has a SQL string format x.y
  2880. if ($thousand != ',' && $thousand != '.') $amount=str_replace(',','.',$amount); // To accept 2 notations for french users
  2881. $amount=str_replace(' ','',$amount); // To avoid spaces
  2882. $amount=str_replace($thousand,'',$amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  2883. $amount=str_replace($dec,'.',$amount);
  2884. }
  2885. return $amount;
  2886. }
  2887. /**
  2888. * Return localtaxe rate for a particular tva
  2889. *
  2890. * @param float $tva Vat taxe
  2891. * @param int $local Local taxe to search and return
  2892. * @param Societe $societe_acheteuse Object of buying third party
  2893. * @return int 0 if not found, localtax if found
  2894. */
  2895. function get_localtax($tva, $local, $societe_acheteuse="")
  2896. {
  2897. global $db, $conf, $mysoc;
  2898. $code_pays=$mysoc->pays_code;
  2899. if (is_object($societe_acheteuse))
  2900. {
  2901. if ($code_pays!=$societe_acheteuse->pays_code) return 0;
  2902. if ($local==1 && !$societe_acheteuse->localtax1_assuj) return 0;
  2903. elseif ($local==2 && !$societe_acheteuse->localtax2_assuj) return 0;
  2904. }
  2905. // Search local taxes
  2906. $sql = "SELECT t.localtax1, t.localtax2";
  2907. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_pays as p";
  2908. $sql .= " WHERE t.fk_pays = p.rowid AND p.code = '".$code_pays."'";
  2909. $sql .= " AND t.taux = ".$tva." AND t.active = 1";
  2910. $sql .= " ORDER BY t.localtax1 ASC, t.localtax2 ASC";
  2911. $resql=$db->query($sql);
  2912. if ($resql)
  2913. {
  2914. $obj = $db->fetch_object($resql);
  2915. if ($local==1) return $obj->localtax1;
  2916. elseif ($local==2) return $obj->localtax2;
  2917. }
  2918. return 0;
  2919. }
  2920. /**
  2921. * Return vat rate of a product in a particular selling country or default country
  2922. * vat if product is unknown
  2923. *
  2924. * @param int $idprod Id of product or 0 if not a predefined product
  2925. * @param string $countrycode Country code (FR, US, IT, ...)
  2926. * @return int <0 if KO, Vat rate if OK
  2927. * TODO May be this should be better as a method of product class
  2928. */
  2929. function get_product_vat_for_country($idprod, $countrycode)
  2930. {
  2931. global $db,$mysoc;
  2932. $ret=0;
  2933. $found=0;
  2934. if ($idprod > 0)
  2935. {
  2936. // Load product
  2937. $product=new Product($db);
  2938. $result=$product->fetch($idprod);
  2939. if ($mysoc->pays_code == $countrycode) // If selling country is ours
  2940. {
  2941. $ret=$product->tva_tx; // Default vat of product we defined
  2942. $found=1;
  2943. }
  2944. else
  2945. {
  2946. // TODO Read default product vat according to countrycode and product
  2947. }
  2948. }
  2949. if (! $found)
  2950. {
  2951. // If vat of product for the country not found or not defined, we return higher vat of country.
  2952. $sql.="SELECT taux as vat_rate";
  2953. $sql.=" FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_pays as p";
  2954. $sql.=" WHERE t.active=1 AND t.fk_pays = p.rowid AND p.code='".$countrycode."'";
  2955. $sql.=" ORDER BY t.taux DESC, t.recuperableonly ASC";
  2956. $sql.=$db->plimit(1);
  2957. $resql=$db->query($sql);
  2958. if ($resql)
  2959. {
  2960. $obj=$db->fetch_object($resql);
  2961. if ($obj)
  2962. {
  2963. $ret=$obj->vat_rate;
  2964. }
  2965. }
  2966. else dol_print_error($db);
  2967. }
  2968. dol_syslog("get_product_vat_for_country: ret=".$ret);
  2969. return $ret;
  2970. }
  2971. /**
  2972. * Return localtax rate of a product in a particular selling country
  2973. *
  2974. * @param idprod Id of product
  2975. * @package local 1 for localtax1, 2 for localtax 2
  2976. * @param countrycode Country code (FR, US, IT, ...)
  2977. * @return int <0 if KO, Vat rate if OK
  2978. * TODO May be this should be better as a method of product class
  2979. */
  2980. function get_product_localtax_for_country($idprod, $local, $countrycode)
  2981. {
  2982. global $db;
  2983. $product=new Product($db);
  2984. $product->fetch($idprod);
  2985. if ($local==1) return $product->localtax1_tx;
  2986. elseif ($local==2) return $product->localtax2_tx;
  2987. return -1;
  2988. }
  2989. /**
  2990. * Function that return vat rate of a product line (according to seller, buyer and product vat rate)
  2991. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  2992. * Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  2993. * Si (vendeur et acheteur dans Communaute europeenne) et (bien vendu = moyen de transports neuf comme auto, bateau, avion) alors TVA par defaut=0 (La TVA doit etre paye par acheteur au centre d'impots de son pays et non au vendeur). Fin de regle.
  2994. * Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = particulier ou entreprise sans num TVA intra) alors TVA par defaut=TVA du produit vendu. Fin de regle
  2995. * Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise avec num TVA) intra alors TVA par defaut=0. Fin de regle
  2996. * Sinon TVA proposee par defaut=0. Fin de regle.
  2997. *
  2998. * @param Societe $societe_vendeuse Objet societe vendeuse
  2999. * @param Societe $societe_acheteuse Objet societe acheteuse
  3000. * @param int $idprod Id product
  3001. * @return float Taux de tva a appliquer, -1 si ne peut etre determine
  3002. */
  3003. function get_default_tva($societe_vendeuse, $societe_acheteuse, $idprod=0)
  3004. {
  3005. global $conf;
  3006. if (!is_object($societe_vendeuse)) return -1;
  3007. if (!is_object($societe_acheteuse)) return -1;
  3008. dol_syslog("get_default_tva: seller use vat=".$societe_vendeuse->tva_assuj.", seller country=".$societe_vendeuse->pays_code.", seller in cee=".$societe_vendeuse->isInEEC().", buyer country=".$societe_acheteuse->pays_code.", buyer in cee=".$societe_acheteuse->isInEEC().", idprod=".$idprod.", SERVICE_ARE_ECOMMERCE_200238EC=".$conf->global->SERVICES_ARE_ECOMMERCE_200238EC);
  3009. // Si vendeur non assujeti a TVA (tva_assuj vaut 0/1 ou franchise/reel)
  3010. if (is_numeric($societe_vendeuse->tva_assuj) && ! $societe_vendeuse->tva_assuj)
  3011. {
  3012. //print 'VATRULE 1';
  3013. return 0;
  3014. }
  3015. if (! is_numeric($societe_vendeuse->tva_assuj) && $societe_vendeuse->tva_assuj=='franchise')
  3016. {
  3017. //print 'VATRULE 2';
  3018. return 0;
  3019. }
  3020. //if (is_object($societe_acheteuse) && ($societe_vendeuse->pays_id == $societe_acheteuse->pays_id) && ($societe_acheteuse->tva_assuj == 1 || $societe_acheteuse->tva_assuj == 'reel'))
  3021. // Le test ci-dessus ne devrait pas etre necessaire. Me signaler l'exemple du cas juridique concerne si le test suivant n'est pas suffisant.
  3022. // Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  3023. if ($societe_vendeuse->pays_code == $societe_acheteuse->pays_code) // Warning ->pays_code not always defined
  3024. {
  3025. //print 'VATRULE 3';
  3026. return get_product_vat_for_country($idprod,$societe_vendeuse->pays_code);
  3027. }
  3028. // Si (vendeur et acheteur dans Communaute europeenne) et (bien vendu = moyen de transports neuf comme auto, bateau, avion) alors TVA par defaut=0 (La TVA doit etre paye par l'acheteur au centre d'impots de son pays et non au vendeur). Fin de regle.
  3029. // Non gere
  3030. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise) alors TVA par defaut=0. Fin de regle
  3031. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  3032. if (($societe_vendeuse->isInEEC() && $societe_acheteuse->isInEEC()))
  3033. {
  3034. $isacompany=$societe_acheteuse->isACompany();
  3035. if ($isacompany)
  3036. {
  3037. //print 'VATRULE 4';
  3038. return 0;
  3039. }
  3040. else
  3041. {
  3042. //print 'VATRULE 5';
  3043. return get_product_vat_for_country($idprod,$societe_vendeuse->pays_code);
  3044. }
  3045. }
  3046. // If services are eServices according to EU Council Directive 2002/38/EC (ec.europa.eu/taxation_customs/taxation/v.../article_1610_en.htm)
  3047. // we use the buyer VAT.
  3048. if (! empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC))
  3049. {
  3050. //print "eee".$societe_acheteuse->isACompany();exit;
  3051. if (! $societe_vendeuse->isInEEC() && $societe_acheteuse->isInEEC() && ! $societe_acheteuse->isACompany())
  3052. {
  3053. //print 'VATRULE 6';
  3054. return get_product_vat_for_country($idprod,$societe_acheteuse->pays_code);
  3055. }
  3056. }
  3057. // Sinon la TVA proposee par defaut=0. Fin de regle.
  3058. // Rem: Cela signifie qu'au moins un des 2 est hors Communaute europeenne et que le pays differe
  3059. //print 'VATRULE 7';
  3060. return 0;
  3061. }
  3062. /**
  3063. * Fonction qui renvoie si tva doit etre tva percue recuperable
  3064. *
  3065. * @param Societe $societe_vendeuse Objet societe vendeuse
  3066. * @param Societe $societe_acheteuse Objet societe acheteuse
  3067. * @param int $idprod Id product
  3068. * @return float 0 or 1
  3069. */
  3070. function get_default_npr($societe_vendeuse, $societe_acheteuse, $idprod)
  3071. {
  3072. return 0;
  3073. }
  3074. /**
  3075. * Function that return localtax of a product line (according to seller, buyer and product vat rate)
  3076. *
  3077. * @param Societe $societe_vendeuse Objet societe vendeuse
  3078. * @param Societe $societe_acheteuse Objet societe acheteuse
  3079. * @param int $local Localtax to process (1 or 2)
  3080. * @param int $idprod Id product
  3081. * @return float Taux de localtax appliquer, -1 si ne peut etre determine
  3082. */
  3083. function get_default_localtax($societe_vendeuse, $societe_acheteuse, $local, $idprod=0)
  3084. {
  3085. if (!is_object($societe_vendeuse)) return -1;
  3086. if (!is_object($societe_acheteuse)) return -1;
  3087. if ($societe_vendeuse->pays_id=='ES' || $societe_vendeuse->pays_code=='ES')
  3088. {
  3089. if ($local==1) //RE
  3090. {
  3091. // Si achatteur non assujeti a RE, localtax1 par default=0
  3092. if (is_numeric($societe_acheteuse->localtax1_assuj) && ! $societe_acheteuse->localtax1_assuj) return 0;
  3093. if (! is_numeric($societe_acheteuse->localtax1_assuj) && $societe_acheteuse->localtax1_assuj=='localtax1off') return 0;
  3094. }
  3095. elseif ($local==2) //IRPF
  3096. {
  3097. // Si vendeur non assujeti a IRPF, localtax2 par default=0
  3098. if (is_numeric($societe_vendeuse->localtax2_assuj) && ! $societe_vendeuse->localtax2_assuj) return 0;
  3099. if (! is_numeric($societe_vendeuse->localtax2_assuj) && $societe_vendeuse->localtax2_assuj=='localtax2off') return 0;
  3100. } else return -1;
  3101. if ($idprod) return get_product_localtax_for_country($idprod, $local, $societe_vendeuse->pays_code);
  3102. else return -1;
  3103. }
  3104. return 0;
  3105. }
  3106. /**
  3107. * Return yes or no in current language
  3108. *
  3109. * @param yesno Value to test (1, 'yes', 'true' or 0, 'no', 'false')
  3110. * @param case 1=Yes/No, 0=yes/no
  3111. * @param color 0=texte only, 1=Text is formated with a color font style ('ok' or 'error'), 2=Text is formated with 'ok' color.
  3112. */
  3113. function yn($yesno, $case=1, $color=0)
  3114. {
  3115. global $langs;
  3116. $result='unknown';
  3117. if ($yesno == 1 || strtolower($yesno) == 'yes' || strtolower($yesno) == 'true') // A mettre avant test sur no a cause du == 0
  3118. {
  3119. $result=($case?$langs->trans("Yes"):$langs->trans("yes"));
  3120. $classname='ok';
  3121. }
  3122. elseif ($yesno == 0 || strtolower($yesno) == 'no' || strtolower($yesno) == 'false')
  3123. {
  3124. $result=($case?$langs->trans("No"):$langs->trans("no"));
  3125. if ($color == 2) $classname='ok';
  3126. else $classname='error';
  3127. }
  3128. if ($color) return '<font class="'.$classname.'">'.$result.'</font>';
  3129. return $result;
  3130. }
  3131. /**
  3132. * Return a path to have a directory according to an id
  3133. * Examples: '001' with level 3->"0/0/1/", '015' with level 3->"0/1/5/"
  3134. * Examples: 'ABC-1' with level 3 ->"0/0/1/", '015' with level 1->"5/"
  3135. *
  3136. * @param $num Id to develop
  3137. * @param $level Level of development (1, 2 or 3 level)
  3138. * @param $alpha Use alpha ref
  3139. * @param withoutslash 0=With slash at end, 1=without slash at end
  3140. */
  3141. function get_exdir($num,$level=3,$alpha=0,$withoutslash=0)
  3142. {
  3143. $path = '';
  3144. if (empty($alpha)) $num = preg_replace('/([^0-9])/i','',$num);
  3145. else $num = preg_replace('/^.*\-/i','',$num);
  3146. $num = substr("000".$num, -$level);
  3147. if ($level == 1) $path = substr($num,0,1);
  3148. if ($level == 2) $path = substr($num,1,1).'/'.substr($num,0,1);
  3149. if ($level == 3) $path = substr($num,2,1).'/'.substr($num,1,1).'/'.substr($num,0,1);
  3150. if (empty($withoutslash)) $path.='/';
  3151. return $path;
  3152. }
  3153. // For backward compatibility
  3154. function create_exdir($dir)
  3155. {
  3156. dol_mkdir($dir);
  3157. }
  3158. /**
  3159. * Creation of a directory (this can create recursive subdir)
  3160. *
  3161. * @param string $dir Directory to create (Separator must be '/'. Example: '/mydir/mysubdir')
  3162. * @return int < 0 if KO, 0 = already exists, > 0 if OK
  3163. */
  3164. function dol_mkdir($dir)
  3165. {
  3166. global $conf;
  3167. dol_syslog("functions.lib::create_exdir: dir=".$dir,LOG_INFO);
  3168. $dir_osencoded=dol_osencode($dir);
  3169. if (@is_dir($dir_osencoded)) return 0;
  3170. $nberr=0;
  3171. $nbcreated=0;
  3172. $ccdir = '';
  3173. $cdir = explode("/",$dir);
  3174. $num=count($cdir);
  3175. for ($i = 0; $i < $num; $i++)
  3176. {
  3177. if ($i > 0) $ccdir .= '/'.$cdir[$i];
  3178. else $ccdir = $cdir[$i];
  3179. if (preg_match("/^.:$/",$ccdir,$regs)) continue; // Si chemin Windows incomplet, on poursuit par rep suivant
  3180. // Attention, le is_dir() peut echouer bien que le rep existe.
  3181. // (ex selon config de open_basedir)
  3182. if ($ccdir)
  3183. {
  3184. $ccdir_osencoded=dol_osencode($ccdir);
  3185. if (! @is_dir($ccdir_osencoded))
  3186. {
  3187. dol_syslog("functions.lib::create_exdir: Directory '".$ccdir."' does not exists or is outside open_basedir PHP setting.",LOG_DEBUG);
  3188. umask(0);
  3189. $dirmaskdec=octdec('0755');
  3190. if (! empty($conf->global->MAIN_UMASK)) $dirmaskdec=octdec($conf->global->MAIN_UMASK);
  3191. $dirmaskdec |= octdec('0111'); // Set x bit required for directories
  3192. if (! @mkdir($ccdir_osencoded, $dirmaskdec))
  3193. {
  3194. // Si le is_dir a renvoye une fausse info, alors on passe ici.
  3195. dol_syslog("functions.lib::create_exdir: Fails to create directory '".$ccdir."' or directory already exists.",LOG_WARNING);
  3196. $nberr++;
  3197. }
  3198. else
  3199. {
  3200. dol_syslog("functions.lib::create_exdir: Directory '".$ccdir."' created",LOG_DEBUG);
  3201. $nberr=0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignore
  3202. $nbcreated++;
  3203. }
  3204. }
  3205. else
  3206. {
  3207. $nberr=0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignores
  3208. }
  3209. }
  3210. }
  3211. return ($nberr ? -$nberr : $nbcreated);
  3212. }
  3213. /**
  3214. * Return picto saying a field is required
  3215. *
  3216. * @return string Chaine avec picto obligatoire
  3217. */
  3218. function picto_required()
  3219. {
  3220. return '<span class="fieldrequired">*</span>';
  3221. }
  3222. /**
  3223. * Clean a string from all HTML tags and entities
  3224. *
  3225. * @param StringHtml String to clean
  3226. * @param removelinefeed Replace also all lines feeds by a space
  3227. * @return string String cleaned
  3228. */
  3229. function dol_string_nohtmltag($StringHtml,$removelinefeed=1)
  3230. {
  3231. $pattern = "/<[^>]+>/";
  3232. $temp = dol_entity_decode($StringHtml);
  3233. $temp = preg_replace($pattern,"",$temp);
  3234. // Supprime aussi les retours
  3235. if ($removelinefeed) $temp=str_replace("\n"," ",$temp);
  3236. // et les espaces doubles
  3237. while(strpos($temp," "))
  3238. {
  3239. $temp = str_replace(" "," ",$temp);
  3240. }
  3241. $CleanString = trim($temp);
  3242. return $CleanString;
  3243. }
  3244. /**
  3245. * Replace CRLF in string with a HTML BR tag
  3246. *
  3247. * @param stringtoencode String to encode
  3248. * @param nl2brmode 0=Adding br before \n, 1=Replacing \n by br
  3249. * @param forxml false=Use <br>, true=Use <br />
  3250. * @return string String encoded
  3251. */
  3252. function dol_nl2br($stringtoencode,$nl2brmode=0,$forxml=false)
  3253. {
  3254. if (! $nl2brmode)
  3255. {
  3256. // We use @ to avoid warning on PHP4 that does not support entity encoding from UTF8;
  3257. if (version_compare(PHP_VERSION, '5.3.0') < 0) return @nl2br($stringtoencode);
  3258. else return @nl2br($stringtoencode,$forxml);
  3259. }
  3260. else
  3261. {
  3262. $ret=preg_replace('/(\r\n|\r|\n)/i',($forxml?'<br />':'<br>'),$stringtoencode);
  3263. return $ret;
  3264. }
  3265. }
  3266. /**
  3267. * This function is called to encode a string into a HTML string but differs from htmlentities because
  3268. * all entities but &,<,> are converted. This permits to encode special chars to entities with no double
  3269. * encoding for already encoded HTML strings.
  3270. * This function also remove last CR/BR.
  3271. * For PDF usage, you can show text by 2 ways:
  3272. * - writeHTMLCell -> param must be encoded into HTML.
  3273. * - MultiCell -> param must not be encoded into HTML.
  3274. * Because writeHTMLCell convert also \n into <br>, if function
  3275. * is used to build PDF, nl2brmode must be 1
  3276. *
  3277. * @param stringtoencode String to encode
  3278. * @param nl2brmode 0=Adding br before \n, 1=Replacing \n by br (for use with FPDF writeHTMLCell function for example)
  3279. * @param pagecodefrom Pagecode stringtoencode is encoded
  3280. */
  3281. function dol_htmlentitiesbr($stringtoencode,$nl2brmode=0,$pagecodefrom='UTF-8')
  3282. {
  3283. if (dol_textishtml($stringtoencode))
  3284. {
  3285. $newstring=$stringtoencode;
  3286. $newstring=preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i','<br>',$newstring); // Replace "<br type="_moz" />" by "<br>". It's same and avoid pb with FPDF.
  3287. $newstring=preg_replace('/<br>$/i','',$newstring); // Remove last <br>
  3288. $newstring=strtr($newstring,array('&'=>'__and__','<'=>'__lt__','>'=>'__gt__','"'=>'__dquot__'));
  3289. $newstring=dol_htmlentities($newstring,ENT_COMPAT,$pagecodefrom); // Make entity encoding
  3290. $newstring=strtr($newstring,array('__and__'=>'&','__lt__'=>'<','__gt__'=>'>','__dquot__'=>'"'));
  3291. //$newstring=strtr($newstring,array('__li__'=>"<li>\n")); // Restore <li>\n
  3292. }
  3293. else {
  3294. $newstring=dol_nl2br(dol_htmlentities($stringtoencode,ENT_COMPAT,$pagecodefrom),$nl2brmode);
  3295. }
  3296. // Other substitutions that htmlentities does not do
  3297. $newstring=str_replace(chr(128),'&euro;',$newstring); // 128 = 0x80. Not in html entity table.
  3298. return $newstring;
  3299. }
  3300. /**
  3301. * This function is called to decode a HTML string (it decodes entities and br tags)
  3302. *
  3303. * @param stringtodecode String to decode
  3304. * @param pagecodeto Page code for result
  3305. */
  3306. function dol_htmlentitiesbr_decode($stringtodecode,$pagecodeto='UTF-8')
  3307. {
  3308. $ret=dol_html_entity_decode($stringtodecode,ENT_COMPAT,$pagecodeto);
  3309. $ret=preg_replace('/'."\r\n".'<br(\s[\sa-zA-Z_="]*)?\/?>/i',"<br>",$ret);
  3310. $ret=preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\r\n".'/i',"\r\n",$ret);
  3311. $ret=preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\n".'/i',"\n",$ret);
  3312. $ret=preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i',"\n",$ret);
  3313. return $ret;
  3314. }
  3315. /**
  3316. * This function remove all ending \n and br at end
  3317. *
  3318. * @param stringtodecode String to decode
  3319. */
  3320. function dol_htmlcleanlastbr($stringtodecode)
  3321. {
  3322. $ret=preg_replace('/(<br>|<br(\s[\sa-zA-Z_="]*)?\/?>|'."\n".'|'."\r".')+$/i',"",$stringtodecode);
  3323. return $ret;
  3324. }
  3325. /**
  3326. * This function is called to decode a string with HTML entities (it decodes entities tags)
  3327. *
  3328. * @param stringhtml stringhtml
  3329. * @param pagecodeto Encoding of input string
  3330. * @return string decodestring
  3331. */
  3332. function dol_entity_decode($stringhtml,$pagecodeto='UTF-8')
  3333. {
  3334. $ret=dol_html_entity_decode($stringhtml,ENT_COMPAT,$pagecodeto);
  3335. return $ret;
  3336. }
  3337. /**
  3338. * Replace html_entity_decode functions to manage errors
  3339. *
  3340. * @param a
  3341. * @param b
  3342. * @param c
  3343. * @return string String decoded
  3344. */
  3345. function dol_html_entity_decode($a,$b,$c)
  3346. {
  3347. // We use @ to avoid warning on PHP4 that does not support entity decoding to UTF8;
  3348. $ret=@html_entity_decode($a,$b,$c);
  3349. return $ret;
  3350. }
  3351. /**
  3352. * Replace htmlentities functions to manage errors
  3353. *
  3354. * @param a
  3355. * @param b
  3356. * @param c
  3357. * @return string String encoded
  3358. */
  3359. function dol_htmlentities($a,$b,$c)
  3360. {
  3361. // We use @ to avoid warning on PHP4 that does not support entity decoding to UTF8;
  3362. $ret=@htmlentities($a,$b,$c);
  3363. return $ret;
  3364. }
  3365. /**
  3366. * Check if a string is a correct iso string
  3367. * If not, it will we considered not HTML encoded even if it is by FPDF.
  3368. * Example, if string contains euro symbol that has ascii code 128
  3369. *
  3370. * @param s String to check
  3371. * @return int 0 if bad iso, 1 if good iso
  3372. */
  3373. function dol_string_is_good_iso($s)
  3374. {
  3375. $len=dol_strlen($s);
  3376. $ok=1;
  3377. for($scursor=0;$scursor<$len;$scursor++)
  3378. {
  3379. $ordchar=ord($s{$scursor});
  3380. //print $scursor.'-'.$ordchar.'<br>';
  3381. if ($ordchar < 32 && $ordchar != 13 && $ordchar != 10) { $ok=0; break; }
  3382. if ($ordchar > 126 && $ordchar < 160) { $ok=0; break; }
  3383. }
  3384. return $ok;
  3385. }
  3386. /**
  3387. * Return nb of lines of a clear text
  3388. *
  3389. * @param s String to check
  3390. * @param maxchar Not yet used
  3391. * @return int Number of lines
  3392. */
  3393. function dol_nboflines($s,$maxchar=0)
  3394. {
  3395. if ($s == '') return 0;
  3396. $arraystring=explode("\n",$s);
  3397. $nb=count($arraystring);
  3398. return $nb;
  3399. }
  3400. /**
  3401. * Return nb of lines of a formated text with \n and <br>
  3402. *
  3403. * @param text Text
  3404. * @param maxlinesize Largeur de ligne en caracteres (ou 0 si pas de limite - defaut)
  3405. * @param charset Give the charset used to encode the $text variable in memory.
  3406. * @return int Number of lines
  3407. */
  3408. function dol_nboflines_bis($text,$maxlinesize=0,$charset='UTF-8')
  3409. {
  3410. //print $text;
  3411. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  3412. $text = strtr($text, $repTable);
  3413. if ($charset == 'UTF-8') { $pattern = '/(<[^>]+>)/Uu'; } // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  3414. else $pattern = '/(<[^>]+>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  3415. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  3416. $nblines = floor((count($a)+1)/2);
  3417. // count possible auto line breaks
  3418. if($maxlinesize)
  3419. {
  3420. foreach ($a as $line)
  3421. {
  3422. if (dol_strlen($line)>$maxlinesize)
  3423. {
  3424. //$line_dec = html_entity_decode(strip_tags($line));
  3425. $line_dec = html_entity_decode($line);
  3426. if(dol_strlen($line_dec)>$maxlinesize)
  3427. {
  3428. $line_dec=wordwrap($line_dec,$maxlinesize,'\n',true);
  3429. $nblines+=substr_count($line_dec,'\n');
  3430. }
  3431. }
  3432. }
  3433. }
  3434. return $nblines;
  3435. }
  3436. /**
  3437. * Same function than microtime in PHP 5 but compatible with PHP4
  3438. *
  3439. * @return float Time (millisecondes) with microsecondes in decimal part
  3440. */
  3441. function dol_microtime_float()
  3442. {
  3443. list($usec, $sec) = explode(" ", microtime());
  3444. return ((float) $usec + (float) $sec);
  3445. }
  3446. /**
  3447. * Return if a text is a html content
  3448. *
  3449. * @param string $msg Content to check
  3450. * @param int $option 0=Full detection, 1=Fast check
  3451. * @return boolean true/false
  3452. */
  3453. function dol_textishtml($msg,$option=0)
  3454. {
  3455. if ($option == 1)
  3456. {
  3457. if (preg_match('/<html/i',$msg)) return true;
  3458. elseif (preg_match('/<body/i',$msg)) return true;
  3459. elseif (preg_match('/<br/i',$msg)) return true;
  3460. return false;
  3461. }
  3462. else
  3463. {
  3464. if (preg_match('/<html/i',$msg)) return true;
  3465. elseif (preg_match('/<body/i',$msg)) return true;
  3466. elseif (preg_match('/<br/i',$msg)) return true;
  3467. elseif (preg_match('/<span/i',$msg)) return true;
  3468. elseif (preg_match('/<div/i',$msg)) return true;
  3469. elseif (preg_match('/<li/i',$msg)) return true;
  3470. elseif (preg_match('/<table/i',$msg)) return true;
  3471. elseif (preg_match('/<font/i',$msg)) return true;
  3472. elseif (preg_match('/<strong/i',$msg)) return true;
  3473. elseif (preg_match('/<img/i',$msg)) return true;
  3474. elseif (preg_match('/<i>/i',$msg)) return true;
  3475. elseif (preg_match('/<b>/i',$msg)) return true;
  3476. elseif (preg_match('/&[A-Z0-9]{1,6};/i',$msg)) return true;
  3477. return false;
  3478. }
  3479. }
  3480. /**
  3481. * Make substition into a string
  3482. * There is two type of substitions:
  3483. * - From $substitutionarray (oldval=>newval)
  3484. * - From special constants (__XXX__=>f(objet->xxx)) by substitutions modules
  3485. *
  3486. * @param string $chaine Source string in which we must do substitution
  3487. * @param array $substitutionarray Array with key->val to substitute
  3488. * @return string Output string after subsitutions
  3489. */
  3490. function make_substitutions($chaine,$substitutionarray)
  3491. {
  3492. if (! is_array($substitutionarray)) return 'ErrorBadParameterSubstitutionArrayWhenCalling_make_substitutions';
  3493. // Make substitition
  3494. foreach ($substitutionarray as $key => $value)
  3495. {
  3496. $chaine=str_replace("$key","$value",$chaine); // We must keep the " to work when value is 123.5 for example
  3497. }
  3498. return $chaine;
  3499. }
  3500. /**
  3501. * Complete the $substitutionarray with more entries
  3502. *
  3503. * @param array $substitutionarray Array substitution old value => new value value
  3504. * @param Translate $outputlangs If we want substitution from special constants, we provide a language
  3505. * @param Object $object If we want substitution from special constants, we provide data in a source object
  3506. * @return void
  3507. */
  3508. function complete_substitutions_array(&$substitutionarray,$outputlangs,$object='')
  3509. {
  3510. global $conf,$user;
  3511. require_once(DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php');
  3512. // Check if there is external substitution to do asked by plugins
  3513. // We look files into the core/modules/substitutions directory
  3514. // By default, there is no such external plugins.
  3515. foreach ($conf->file->dol_document_root as $dirroot)
  3516. {
  3517. $substitfiles=dol_dir_list($dirroot.'/core/modules/substitutions','files',0,'functions_');
  3518. foreach($substitfiles as $substitfile)
  3519. {
  3520. if (preg_match('/functions_(.*)\.lib\.php/i',$substitfile['name'],$reg))
  3521. {
  3522. $module=$reg[1];
  3523. if (! empty($conf->$module->enabled)) // If module enabled
  3524. {
  3525. dol_syslog("Library functions_".$module.".lib.php found into ".$dirroot);
  3526. require_once($dirroot."/core/modules/substitutions/functions_".$module.".lib.php");
  3527. $function_name=$module."_completesubstitutionarray";
  3528. $function_name($substitutionarray,$outputlangs,$object);
  3529. }
  3530. }
  3531. }
  3532. }
  3533. }
  3534. /**
  3535. * Format output for start and end date
  3536. *
  3537. * @param timestamp $date_start Start date
  3538. * @param timestamp $date_end End date
  3539. * @param string $format Output format
  3540. * @param Translate $outputlangs Output language
  3541. * @return void
  3542. */
  3543. function print_date_range($date_start,$date_end,$format = '',$outputlangs='')
  3544. {
  3545. print get_date_range($date_start,$date_end,$format,$outputlangs);
  3546. }
  3547. /**
  3548. * Format output for start and end date
  3549. *
  3550. * @param timestamp $date_start Start date
  3551. * @param timestamp $date_end End date
  3552. * @param string $format Output format
  3553. * @param Translate $outputlangs Output language
  3554. * @return string String
  3555. */
  3556. function get_date_range($date_start,$date_end,$format = '',$outputlangs='')
  3557. {
  3558. global $langs;
  3559. $out='';
  3560. if (! is_object($outputlangs)) $outputlangs=$langs;
  3561. if ($date_start && $date_end)
  3562. {
  3563. $out.= ' ('.$outputlangs->trans('DateFromTo',dol_print_date($date_start, $format, false, $outputlangs),dol_print_date($date_end, $format, false, $outputlangs)).')';
  3564. }
  3565. if ($date_start && ! $date_end)
  3566. {
  3567. $out.= ' ('.$outputlangs->trans('DateFrom',dol_print_date($date_start, $format, false, $outputlangs)).')';
  3568. }
  3569. if (! $date_start && $date_end)
  3570. {
  3571. $out.= ' ('.$outputlangs->trans('DateUntil',dol_print_date($date_end, $format, false, $outputlangs)).')';
  3572. }
  3573. return $out;
  3574. }
  3575. /**
  3576. * Get formated messages to output (Used to show messages on html output).
  3577. *
  3578. * @param string $mesgstring Message string
  3579. * @param array $mesgarray Messages array
  3580. * @param string $style Style of message output ('ok' or 'error')
  3581. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  3582. * @return string Return html output
  3583. *
  3584. * @see dol_print_error
  3585. * @see dol_htmloutput_errors
  3586. */
  3587. function get_htmloutput_mesg($mesgstring='',$mesgarray='', $style='ok', $keepembedded=0)
  3588. {
  3589. global $conf, $langs;
  3590. $ret='';
  3591. $out='';
  3592. $divstart=$divend='';
  3593. // Use session mesg
  3594. if (isset($_SESSION['mesg']))
  3595. {
  3596. $mesgstring=$_SESSION['mesg'];
  3597. unset($_SESSION['mesg']);
  3598. }
  3599. if (isset($_SESSION['mesgarray']))
  3600. {
  3601. $mesgarray=$_SESSION['mesgarray'];
  3602. unset($_SESSION['mesgarray']);
  3603. }
  3604. // If inline message with no format, we add it.
  3605. if ((! empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) || $keepembedded) && ! preg_match('/<div class=".*">/i',$out))
  3606. {
  3607. $divstart='<div class="'.$style.'">';
  3608. $divend='</div>';
  3609. }
  3610. if ((is_array($mesgarray) && count($mesgarray)) || $mesgstring)
  3611. {
  3612. $langs->load("errors");
  3613. $out.=$divstart;
  3614. if (is_array($mesgarray) && count($mesgarray))
  3615. {
  3616. foreach($mesgarray as $message)
  3617. {
  3618. $ret++;
  3619. $out.= $langs->trans($message);
  3620. if ($ret < count($mesgarray)) $out.= "<br>\n";
  3621. }
  3622. }
  3623. if ($mesgstring)
  3624. {
  3625. $langs->load("errors");
  3626. $ret++;
  3627. $out.= $langs->trans($mesgstring);
  3628. }
  3629. $out.=$divend;
  3630. }
  3631. if ($out)
  3632. {
  3633. if (empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && empty($keepembedded))
  3634. {
  3635. $return = '<script type="text/javascript">
  3636. jQuery(document).ready(function() {
  3637. jQuery.jnotify("'.dol_escape_js($out).'",
  3638. "'.($style=="ok" ? 3000 : $style).'",
  3639. '.($style=="ok" ? "false" : "true").',
  3640. { remove: function (){} } );
  3641. });
  3642. </script>';
  3643. }
  3644. else
  3645. {
  3646. $return = $out;
  3647. }
  3648. }
  3649. return $return;
  3650. }
  3651. /**
  3652. * Get formated error messages to output (Used to show messages on html output).
  3653. *
  3654. * @param string $mesgstring Error message
  3655. * @param array $mesgarray Error messages array
  3656. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  3657. * @return string Return html output
  3658. *
  3659. * @see dol_print_error
  3660. * @see dol_htmloutput_mesg
  3661. */
  3662. function get_htmloutput_errors($mesgstring='', $mesgarray='', $keepembedded=0)
  3663. {
  3664. return get_htmloutput_mesg($mesgstring, $mesgarray,'error',$keepembedded);
  3665. }
  3666. /**
  3667. * Print formated messages to output (Used to show messages on html output).
  3668. *
  3669. * @param string $mesgstring Message
  3670. * @param array $mesgarray Messages array
  3671. * @param string $style Which style to use ('ok', 'error')
  3672. * @param int $keepembedded Set to 1 if message must be kept embedded into its html place (this disable jnotify)
  3673. * @return void
  3674. *
  3675. * @see dol_print_error
  3676. * @see dol_htmloutput_errors
  3677. */
  3678. function dol_htmloutput_mesg($mesgstring='',$mesgarray='', $style='ok', $keepembedded=0)
  3679. {
  3680. if (empty($mesgstring) && (! is_array($mesgarray) || count($mesgarray) == 0)) return;
  3681. $iserror=0;
  3682. if (is_array($mesgarray))
  3683. {
  3684. foreach($mesgarray as $val)
  3685. {
  3686. if ($val && preg_match('/class="error"/i',$val)) { $iserror++; break; }
  3687. }
  3688. }
  3689. else if ($mesgstring && preg_match('/class="error"/i',$mesgstring)) $iserror++;
  3690. if ($style=='error') $iserror++;
  3691. if ($iserror)
  3692. {
  3693. // Remove div from texts
  3694. $mesgstring=preg_replace('/<\/div><div class="error">/','<br>',$mesgstring);
  3695. $mesgstring=preg_replace('/<div class="error">/','',$mesgstring);
  3696. $mesgstring=preg_replace('/<\/div>/','',$mesgstring);
  3697. // Remove div from texts array
  3698. if (is_array($mesgarray))
  3699. {
  3700. $newmesgarray=array();
  3701. foreach($mesgarray as $val)
  3702. {
  3703. $tmpmesgstring=preg_replace('/<\/div><div class="error">/','<br>',$val);
  3704. $tmpmesgstring=preg_replace('/<div class="error">/','',$tmpmesgstring);
  3705. $tmpmesgstring=preg_replace('/<\/div>/','',$tmpmesgstring);
  3706. $newmesgarray[]=$tmpmesgstring;
  3707. }
  3708. $mesgarray=$newmesgarray;
  3709. }
  3710. print get_htmloutput_mesg($mesgstring,$mesgarray,'error',$keepembedded);
  3711. }
  3712. else print get_htmloutput_mesg($mesgstring,$mesgarray,'ok',$keepembedded);
  3713. }
  3714. /**
  3715. * Print formated error messages to output (Used to show messages on html output).
  3716. *
  3717. * @param string $mesgstring Error message
  3718. * @param array $mesgarray Error messages array
  3719. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  3720. * @return void
  3721. *
  3722. * @see dol_print_error
  3723. * @see dol_htmloutput_mesg
  3724. */
  3725. function dol_htmloutput_errors($mesgstring='', $mesgarray='', $keepembedded=0)
  3726. {
  3727. dol_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  3728. }
  3729. /**
  3730. * Advanced sort array by second index function, which produces ascending (default)
  3731. * or descending output and uses optionally natural case insensitive sorting (which
  3732. * can be optionally case sensitive as well).
  3733. *
  3734. * @param array $array Array to sort
  3735. * @param string $index Key in array to use for sorting criteria
  3736. * @param int $order Sort order
  3737. * @param int $natsort 1=use "natural" sort (natsort), 0=use "standard sort (asort)
  3738. * @param int $case_sensitive 1=sort is case sensitive, 0=not case sensitive
  3739. * @return array Sorted array
  3740. */
  3741. function dol_sort_array(&$array, $index, $order='asc', $natsort=0, $case_sensitive=0)
  3742. {
  3743. // Clean parameters
  3744. $order=strtolower($order);
  3745. $sizearray=count($array);
  3746. if (is_array($array) && $sizearray>0)
  3747. {
  3748. foreach(array_keys($array) as $key) $temp[$key]=$array[$key][$index];
  3749. if (!$natsort) ($order=='asc') ? asort($temp) : arsort($temp);
  3750. else
  3751. {
  3752. ($case_sensitive) ? natsort($temp) : natcasesort($temp);
  3753. if($order!='asc') $temp=array_reverse($temp,TRUE);
  3754. }
  3755. foreach(array_keys($temp) as $key) (is_numeric($key))? $sorted[]=$array[$key] : $sorted[$key]=$array[$key];
  3756. return $sorted;
  3757. }
  3758. return $array;
  3759. }
  3760. /**
  3761. * Check if a string is in UTF8
  3762. *
  3763. * @param string $str String to check
  3764. * @return boolean True if string is UTF8 or ISO compatible with UTF8, False if not (ISO with special char or Binary)
  3765. */
  3766. function utf8_check($str)
  3767. {
  3768. // We must use here a binary strlen function (so not dol_strlen)
  3769. $strLength = dol_strlen($str);
  3770. for ($i=0; $i<$strLength; $i++)
  3771. {
  3772. if (ord($str[$i]) < 0x80) continue; // 0bbbbbbb
  3773. elseif ((ord($str[$i]) & 0xE0) == 0xC0) $n=1; // 110bbbbb
  3774. elseif ((ord($str[$i]) & 0xF0) == 0xE0) $n=2; // 1110bbbb
  3775. elseif ((ord($str[$i]) & 0xF8) == 0xF0) $n=3; // 11110bbb
  3776. elseif ((ord($str[$i]) & 0xFC) == 0xF8) $n=4; // 111110bb
  3777. elseif ((ord($str[$i]) & 0xFE) == 0xFC) $n=5; // 1111110b
  3778. else return false; // Does not match any model
  3779. for ($j=0; $j<$n; $j++) { // n bytes matching 10bbbbbb follow ?
  3780. if ((++$i == strlen($str)) || ((ord($str[$i]) & 0xC0) != 0x80))
  3781. return false;
  3782. }
  3783. }
  3784. return true;
  3785. }
  3786. /**
  3787. * Return an UTF-8 string encoded into OS filesystem encoding. This function is used to define
  3788. * value to pass to filesystem PHP functions.
  3789. *
  3790. * @param string $str String to encode (UTF-8)
  3791. * @return string Encoded string (UTF-8, ISO-8859-1)
  3792. */
  3793. function dol_osencode($str)
  3794. {
  3795. global $conf;
  3796. $tmp=ini_get("unicode.filesystem_encoding"); // Disponible avec PHP 6.0
  3797. if (empty($tmp) && ! empty($_SERVER["WINDIR"])) $tmp='iso-8859-1'; // By default for windows
  3798. if (empty($tmp)) $tmp='utf-8'; // By default for other
  3799. if (! empty($conf->global->MAIN_FILESYSTEM_ENCODING)) $tmp=$conf->global->MAIN_FILESYSTEM_ENCODING;
  3800. if ($tmp == 'iso-8859-1') return utf8_decode($str);
  3801. return $str;
  3802. }
  3803. /**
  3804. * Return an id or code from a code or id. Store Code-Id in a cache.
  3805. *
  3806. * @param DoliDB $db Database handler
  3807. * @param string $key Code to get Id
  3808. * @param string $tablename Table name without prefix
  3809. * @param string $fieldkey Field for code
  3810. * @param string $fieldid Field for id
  3811. * @return int Id of code
  3812. */
  3813. function dol_getIdFromCode($db,$key,$tablename,$fieldkey='code',$fieldid='id')
  3814. {
  3815. global $cache_codes;
  3816. // If key empty
  3817. if ($key == '') return '';
  3818. // Check in cache
  3819. if (isset($cache_codes[$tablename][$key])) // Can be defined to 0 or ''
  3820. {
  3821. return $cache_codes[$tablename][$key]; // Found in cache
  3822. }
  3823. $sql = "SELECT ".$fieldid." as id";
  3824. $sql.= " FROM ".MAIN_DB_PREFIX.$tablename;
  3825. $sql.= " WHERE ".$fieldkey." = '".$key."'";
  3826. dol_syslog('dol_getIdFromCode sql='.$sql,LOG_DEBUG);
  3827. $resql = $db->query($sql);
  3828. if ($resql)
  3829. {
  3830. $obj = $db->fetch_object($resql);
  3831. if ($obj) $cache_codes[$tablename][$key]=$obj->id;
  3832. else $cache_codes[$tablename][$key]='';
  3833. $db->free($resql);
  3834. return $cache_codes[$tablename][$key];
  3835. }
  3836. else
  3837. {
  3838. dol_syslog("dol_getIdFromCode error=".$db->lasterror(),LOG_ERR);
  3839. return -1;
  3840. }
  3841. }
  3842. /**
  3843. * Verify if condition in string is ok or not
  3844. *
  3845. * @param string $strRights String with condition to check
  3846. * @return boolean true or false
  3847. */
  3848. function verifCond($strRights)
  3849. {
  3850. global $user,$conf,$langs;
  3851. global $leftmenu;
  3852. global $rights; // To export to dol_eval function
  3853. //print $strRights."<br>\n";
  3854. $rights = true;
  3855. if ($strRights != '')
  3856. {
  3857. //$tab_rights = explode('&&', $strRights);
  3858. //$i = 0;
  3859. //while (($i < count($tab_rights)) && ($rights == true)) {
  3860. $str = 'if(!(' . $strRights . ')) { $rights = false; }';
  3861. dol_eval($str);
  3862. // $i++;
  3863. //}
  3864. }
  3865. return $rights;
  3866. }
  3867. /**
  3868. * Replace eval function to add more security.
  3869. * This function is called by verifCond()
  3870. *
  3871. * @param string $s
  3872. * @return void
  3873. */
  3874. function dol_eval($s)
  3875. {
  3876. // Only global variables can be changed by eval function and returned to caller
  3877. global $langs, $user, $conf;
  3878. global $leftmenu;
  3879. global $rights;
  3880. //print $s."<br>\n";
  3881. eval($s);
  3882. }
  3883. /**
  3884. * Return if var element is ok
  3885. *
  3886. * @param string $element Variable to check
  3887. * @return boolean Return true of variable is not empty
  3888. */
  3889. function dol_validElement($element)
  3890. {
  3891. return (trim($element) != '');
  3892. }
  3893. /**
  3894. * Return img flag of country for a language code or country code
  3895. *
  3896. * @param string $codelang Language code (en_IN, fr_CA...) or Country code (IN, FR)
  3897. * @return string HTML img string with flag.
  3898. */
  3899. function picto_from_langcode($codelang)
  3900. {
  3901. $ret='';
  3902. if (! empty($codelang))
  3903. {
  3904. if ($codelang == 'auto') $ret=img_picto('',DOL_URL_ROOT.'/theme/common/flags/int.png','',1);
  3905. else {
  3906. //print $codelang;
  3907. $langtocountryflag=array('ar_AR'=>'','ca_ES'=>'catalonia','da_DA'=>'dk','fr_CA'=>'mq','sv_SV'=>'se');
  3908. $tmpcode='';
  3909. if (isset($langtocountryflag[$codelang])) $tmpcode=$langtocountryflag[$codelang];
  3910. else
  3911. {
  3912. $tmparray=explode('_',$codelang);
  3913. $tmpcode=empty($tmparray[1])?$tmparray[0]:$tmparray[1];
  3914. }
  3915. if ($tmpcode) $ret.=img_picto($codelang,DOL_URL_ROOT.'/theme/common/flags/'.strtolower($tmpcode).'.png','',1);
  3916. }
  3917. }
  3918. return $ret;
  3919. }
  3920. /**
  3921. * Complete or removed entries into a head array (used to build tabs) with value added by external modules
  3922. *
  3923. * @param Conf $conf Object conf
  3924. * @param Translate $langs Object langs
  3925. * @param Object $object Object object
  3926. * @param array $head Object head
  3927. * @param int $h New position to fill
  3928. * @param string $type Value for object where objectvalue can be
  3929. * 'thirdparty' to add a tab in third party view
  3930. * 'intervention' to add a tab in intervention view
  3931. * 'supplier_order' to add a tab in supplier order view
  3932. * 'supplier_invoice' to add a tab in supplier invoice view
  3933. * 'invoice' to add a tab in customer invoice view
  3934. * 'order' to add a tab in customer order view
  3935. * 'product' to add a tab in product view
  3936. * 'propal' to add a tab in propal view
  3937. * 'user' to add a tab in user view
  3938. * 'group' to add a tab in group view
  3939. * 'member' to add a tab in fundation member view
  3940. * 'categories_x' to add a tab in category view ('x': type of category (0=product, 1=supplier, 2=customer, 3=member)
  3941. * @param string $mode 'add' to complete head, 'remove' to remove entries
  3942. * @return void
  3943. */
  3944. function complete_head_from_modules($conf,$langs,$object,&$head,&$h,$type,$mode='add')
  3945. {
  3946. if (is_array($conf->tabs_modules[$type]))
  3947. {
  3948. foreach ($conf->tabs_modules[$type] as $value)
  3949. {
  3950. $values=explode(':',$value);
  3951. if ($mode == 'add')
  3952. {
  3953. if (count($values) == 6) // new declaration with permissions
  3954. {
  3955. if ($values[0] != $type) continue;
  3956. //print 'ee'.$values[4];
  3957. if (verifCond($values[4]))
  3958. {
  3959. if ($values[3]) $langs->load($values[3]);
  3960. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i',$object->id,$values[5]),1);
  3961. $head[$h][1] = $langs->trans($values[2]);
  3962. $head[$h][2] = str_replace('+','',$values[1]);
  3963. $h++;
  3964. }
  3965. }
  3966. else if (count($values) == 5) // new declaration
  3967. {
  3968. if ($values[0] != $type) continue;
  3969. if ($values[3]) $langs->load($values[3]);
  3970. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i',$object->id,$values[4]),1);
  3971. $head[$h][1] = $langs->trans($values[2]);
  3972. $head[$h][2] = str_replace('+','',$values[1]);
  3973. $h++;
  3974. }
  3975. else if (count($values) == 4) // old declaration, for backward compatibility
  3976. {
  3977. if ($values[0] != $type) continue;
  3978. if ($values[2]) $langs->load($values[2]);
  3979. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i',$object->id,$values[3]),1);
  3980. $head[$h][1] = $langs->trans($values[1]);
  3981. $head[$h][2] = 'tab'.$values[1];
  3982. $h++;
  3983. }
  3984. }
  3985. else if ($mode == 'remove')
  3986. {
  3987. if ($values[0] != $type) continue;
  3988. $tabname=str_replace('-','',$values[1]);
  3989. foreach($head as $key => $val)
  3990. {
  3991. if ($head[$key][2]==$tabname)
  3992. {
  3993. //print 'on vire '.$tabname.' key='.$key;
  3994. unset($head[$key]);
  3995. break;
  3996. }
  3997. }
  3998. }
  3999. }
  4000. }
  4001. }
  4002. /**
  4003. * Print common footer :
  4004. * conf->global->MAIN_HTML_FOOTER
  4005. * conf->global->MAIN_GOOGLE_AN_ID
  4006. * DOL_TUNING
  4007. * conf->logbuffer
  4008. *
  4009. * @param string $zone 'private' (for private pages) or 'public' (for public pages)
  4010. * @return void
  4011. */
  4012. function printCommonFooter($zone='private')
  4013. {
  4014. global $conf;
  4015. if ($zone == 'private') print "\n".'<!-- Common footer for private page -->'."\n";
  4016. else print "\n".'<!-- Common footer for public page -->'."\n";
  4017. if (! empty($conf->global->MAIN_HTML_FOOTER)) print $conf->global->MAIN_HTML_FOOTER."\n";
  4018. // Google Analytics (need Google module)
  4019. if (! empty($conf->global->MAIN_GOOGLE_AN_ID))
  4020. {
  4021. print "\n";
  4022. print '<script type="text/javascript">'."\n";
  4023. print ' var _gaq = _gaq || [];'."\n";
  4024. print ' _gaq.push([\'_setAccount\', \''.$conf->global->MAIN_GOOGLE_AN_ID.'\']);'."\n";
  4025. print ' _gaq.push([\'_trackPageview\']);'."\n";
  4026. print ''."\n";
  4027. print ' (function() {'."\n";
  4028. print ' var ga = document.createElement(\'script\'); ga.type = \'text/javascript\'; ga.async = true;'."\n";
  4029. print ' ga.src = (\'https:\' == document.location.protocol ? \'https://ssl\' : \'http://www\') + \'.google-analytics.com/ga.js\';'."\n";
  4030. print ' var s = document.getElementsByTagName(\'script\')[0]; s.parentNode.insertBefore(ga, s);'."\n";
  4031. print ' })();'."\n";
  4032. print '</script>'."\n";
  4033. }
  4034. // End of tuning
  4035. if (! empty($_SERVER['DOL_TUNING']))
  4036. {
  4037. $micro_end_time=dol_microtime_float(true);
  4038. print "\n".'<script type="text/javascript">console.log("';
  4039. if (! empty($conf->global->MEMCACHED_SERVER)) print 'MEMCACHED_SERVER='.$conf->global->MEMCACHED_SERVER.' - ';
  4040. print 'MAIN_OPTIMIZE_SPEED='.(isset($conf->global->MAIN_OPTIMIZE_SPEED)?$conf->global->MAIN_OPTIMIZE_SPEED:'off');
  4041. print ' - Build time: '.ceil(1000*($micro_end_time-$micro_start_time)).' ms';
  4042. if (function_exists("memory_get_usage"))
  4043. {
  4044. print ' - Mem: '.memory_get_usage();
  4045. }
  4046. if (function_exists("xdebug_memory_usage"))
  4047. {
  4048. print ' - XDebug time: '.ceil(1000*xdebug_time_index()).' ms';
  4049. print ' - XDebug mem: '.xdebug_memory_usage();
  4050. print ' - XDebug mem peak: '.xdebug_peak_memory_usage();
  4051. }
  4052. if (function_exists("zend_loader_file_encoded"))
  4053. {
  4054. print ' - Zend encoded file: '.(zend_loader_file_encoded()?'yes':'no');
  4055. }
  4056. print '")</script>'."\n";
  4057. // Add Xdebug coverage of code
  4058. if (defined('XDEBUGCOVERAGE')) {
  4059. var_dump(xdebug_get_code_coverage());
  4060. }
  4061. }
  4062. // If there is some logs in buffer to show
  4063. if (count($conf->logbuffer))
  4064. {
  4065. print "\n";
  4066. print "<!-- Start of log output\n";
  4067. //print '<div class="hidden">'."\n";
  4068. foreach($conf->logbuffer as $logline)
  4069. {
  4070. print $logline."<br>\n";
  4071. }
  4072. //print '</div>'."\n";
  4073. print "End of log output -->\n";
  4074. }
  4075. }
  4076. ?>