PageRenderTime 64ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/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

Large files files are truncated, but you can click here to view the full file

  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

Large files files are truncated, but you can click here to view the full file