PageRenderTime 78ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

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

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