PageRenderTime 60ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

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

https://github.com/asterix14/dolibarr
PHP | 4480 lines | 2707 code | 400 blank | 1373 comment | 930 complexity | 1cdd3126dd381b0536d2d331e41c8c37 MD5 | raw file
Possible License(s): LGPL-2.0

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-2011 Laurent Destailleur <eldy@users.sourceforge.net>
  5. * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
  6. * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
  7. * Copyright (C) 2004 Christophe Combelles <ccomb@free.fr>
  8. * Copyright (C) 2005-2010 Regis Houssin <regis@dolibarr.fr>
  9. * Copyright (C) 2008 Raphael Bertrand (Resultic) <raphael.bertrand@resultic.fr>
  10. * Copyright (C) 2010-2011 Juanjo Menent <jmenent@2byte.es>
  11. *
  12. * This program is free software; you can redistribute it and/or modify
  13. * it under the terms of the GNU General Public License as published by
  14. * the Free Software Foundation; either version 2 of the License, or
  15. * (at your option) any later version.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU General Public License
  23. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  24. * or see http://www.gnu.org/
  25. */
  26. /**
  27. * \file htdocs/core/lib/functions.lib.php
  28. * \brief A set of functions for Dolibarr
  29. * This file contains all frequently used functions.
  30. */
  31. if (! function_exists('json_encode'))
  32. {
  33. /**
  34. * Implement json_encode for PHP that does not support it
  35. *
  36. * @param mixed $elements PHP Object to json encode
  37. * @return string Json encoded string
  38. */
  39. function json_encode($elements)
  40. {
  41. $num = count($elements);
  42. // determine type
  43. if (is_numeric(key($elements)))
  44. {
  45. // indexed (list)
  46. $output = '[';
  47. for ($i = 0, $last = ($num - 1); isset($elements[$i]); ++$i)
  48. {
  49. if (is_array($elements[$i])) $output.= json_encode($elements[$i]);
  50. else $output .= _val($elements[$i]);
  51. if($i !== $last) $output.= ',';
  52. }
  53. $output.= ']';
  54. }
  55. else
  56. {
  57. // associative (object)
  58. $output = '{';
  59. $last = $num - 1;
  60. $i = 0;
  61. foreach($elements as $key => $value)
  62. {
  63. $output .= '"'.$key.'":';
  64. if (is_array($value)) $output.= json_encode($value);
  65. else $output .= _val($value);
  66. if ($i !== $last) $output.= ',';
  67. ++$i;
  68. }
  69. $output.= '}';
  70. }
  71. // return
  72. return $output;
  73. }
  74. function _val($val)
  75. {
  76. if (is_string($val)) return '"'.rawurlencode($val).'"';
  77. elseif (is_int($val)) return sprintf('%d', $val);
  78. elseif (is_float($val)) return sprintf('%F', $val);
  79. elseif (is_bool($val)) return ($val ? 'true' : 'false');
  80. else return 'null';
  81. }
  82. }
  83. if (! function_exists('json_decode'))
  84. {
  85. /**
  86. * Implement json_decode for PHP that does not support it
  87. *
  88. * @param string $json Json encoded to PHP Object or Array
  89. * @param bool $assoc False return an object, true return an array
  90. * @return mixed Object or Array
  91. */
  92. function json_decode($json, $assoc=false)
  93. {
  94. $comment = false;
  95. $strLength = dol_strlen($json);
  96. for ($i=0; $i<$strLength; $i++)
  97. {
  98. if (! $comment)
  99. {
  100. if (($json[$i] == '{') || ($json[$i] == '[')) $out.= 'array(';
  101. else if (($json[$i] == '}') || ($json[$i] == ']')) $out.= ')';
  102. else if ($json[$i] == ':') $out.= ' => ';
  103. else $out.= $json[$i];
  104. }
  105. else $out.= $json[$i];
  106. if ($json[$i] == '"' && $json[($i-1)]!="\\") $comment = !$comment;
  107. }
  108. // Return an array
  109. eval('$array = '.$out.';');
  110. // Return an object
  111. if (! $assoc)
  112. {
  113. if (! empty($array))
  114. {
  115. $object = false;
  116. foreach ($array as $key => $value)
  117. {
  118. $object->{$key} = $value;
  119. }
  120. return $object;
  121. }
  122. return false;
  123. }
  124. return $array;
  125. }
  126. }
  127. /**
  128. * Return a DoliDB instance (database handler).
  129. *
  130. * @param string $type Type of database (mysql, pgsql...)
  131. * @param string $host Address of database server
  132. * @param string $user Nom de l'utilisateur autorise
  133. * @param string $pass Mot de passe
  134. * @param string $name Nom de la database
  135. * @param int $port Port of database server
  136. * @return DoliDB A DoliDB instance
  137. */
  138. function getDoliDBInstance($type, $host, $user, $pass, $name, $port)
  139. {
  140. require_once(DOL_DOCUMENT_ROOT ."/core/db/".$type.".class.php");
  141. $class='DoliDB'.ucfirst($type);
  142. $dolidb=new $class($type, $host, $user, $pass, $name, $port);
  143. return $dolidb;
  144. }
  145. /**
  146. * Function called at end of web php process
  147. *
  148. * @return void
  149. */
  150. function dol_shutdown()
  151. {
  152. global $conf,$user,$langs,$db;
  153. $disconnectdone=false;
  154. if (is_object($db) && ! empty($db->connected)) $disconnectdone=$db->close();
  155. dol_syslog("--- End access to ".$_SERVER["PHP_SELF"].($disconnectdone?' (Warn: db disconnection forced)':''), ($disconnectdone?LOG_WARNING:LOG_DEBUG));
  156. }
  157. /**
  158. * Return value of a param into GET or POST supervariable
  159. *
  160. * @param string $paramname Name of parameter to found
  161. * @param string $check Type of check (''=no check, 'int'=check it's numeric, 'alpha'=check it's alpha only)
  162. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  163. * @return string Value found or '' if check fails
  164. */
  165. function GETPOST($paramname,$check='',$method=0)
  166. {
  167. if (empty($method)) $out = isset($_GET[$paramname])?$_GET[$paramname]:(isset($_POST[$paramname])?$_POST[$paramname]:'');
  168. elseif ($method==1) $out = isset($_GET[$paramname])?$_GET[$paramname]:'';
  169. elseif ($method==2) $out = isset($_POST[$paramname])?$_POST[$paramname]:'';
  170. elseif ($method==3) $out = isset($_POST[$paramname])?$_POST[$paramname]:(isset($_GET[$paramname])?$_GET[$paramname]:'');
  171. if (!empty($check))
  172. {
  173. // Check if numeric
  174. if ($check == 'int' && ! preg_match('/^[\.,0-9]+$/i',trim($out))) $out='';
  175. // Check if alpha
  176. //if ($check == 'alpha' && ! preg_match('/^[ =:@#\/\\\(\)\-\._a-z0-9]+$/i',trim($out))) $out='';
  177. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  178. if ($check == 'alpha' && preg_match('/"/',trim($out))) $out='';
  179. }
  180. return $out;
  181. }
  182. /**
  183. * Return a prefix to use for this Dolibarr instance for session or cookie names.
  184. * This prefix is unique for instance and avoid conflict between multi-instances,
  185. * even when having two instances with one root dir or two instances in virtual servers
  186. *
  187. * @return string A calculated prefix
  188. */
  189. function dol_getprefix()
  190. {
  191. return dol_hash($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  192. }
  193. /**
  194. * Make an include_once using default root and alternate root if it fails.
  195. * WARNING: In most cases, you should not use this function:
  196. * To link to a core file, use include(DOL_DOCUMENT_ROOT.'/pathtofile')
  197. * To link to a module file from a module file, use include('./mymodulefile');
  198. * To link to a module file from a core file, then this function can be used
  199. *
  200. * @param string $relpath Relative path to file (Ie: mydir/myfile, ../myfile, ...)
  201. * @return int false if include fails.
  202. */
  203. function dol_include_once($relpath)
  204. {
  205. global $conf,$langs,$user,$mysoc; // Other global var must be retreived with $GLOBALS['var']
  206. return @include_once(dol_buildpath($relpath));
  207. }
  208. /**
  209. * Return path of url or filesystem. Return default_root or alternate root if file_exist fails
  210. *
  211. * @param string $path Relative path to file (if mode=0, ie: mydir/myfile, ../myfile, ...) or relative url (if mode=1).
  212. * @param int $type 0=Used for a Filesystem path, 1=Used for an URL path (output relative), 2=Used for an URL path (output full path)
  213. * @return string Full filsystem path (if mode=0), Full url path (if mode=1)
  214. */
  215. function dol_buildpath($path,$type=0)
  216. {
  217. if (empty($type)) // For a filesystem path
  218. {
  219. $res = DOL_DOCUMENT_ROOT.$path; // Standard value
  220. if (defined('DOL_DOCUMENT_ROOT_ALT') && DOL_DOCUMENT_ROOT_ALT) // We check only if alternate feature is used
  221. {
  222. if (! file_exists(DOL_DOCUMENT_ROOT.$path)) $res = DOL_DOCUMENT_ROOT_ALT.$path;
  223. }
  224. }
  225. else // For an url path
  226. {
  227. // We try to get local path of file on filesystem from url
  228. // Note that trying to know if a file on disk exist by forging path on disk from url
  229. // works only for some web server and some setup. This is bugged when
  230. // using proxy, rewriting, virtual path, etc...
  231. if ($type == 1)
  232. {
  233. $res = DOL_URL_ROOT.$path; // Standard value
  234. if (defined('DOL_URL_ROOT_ALT') && DOL_URL_ROOT_ALT) // We check only if alternate feature is used
  235. {
  236. preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i',$path,$regs); // Take part before '?'
  237. if (! empty($regs[1]))
  238. {
  239. if (! file_exists(DOL_DOCUMENT_ROOT.$regs[1])) $res = DOL_URL_ROOT_ALT.$path;
  240. }
  241. }
  242. }
  243. if ($type == 2)
  244. {
  245. $res = DOL_MAIN_URL_ROOT.$path; // Standard value
  246. if (defined('DOL_URL_ROOT_ALT') && DOL_URL_ROOT_ALT) // We check only if alternate feature is used
  247. {
  248. preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i',$path,$regs); // Take part before '?'
  249. if (! empty($regs[1]))
  250. {
  251. if (! file_exists(DOL_DOCUMENT_ROOT.$regs[1])) $res = DOL_MAIN_URL_ROOT_ALT.$path;
  252. }
  253. }
  254. }
  255. }
  256. return $res;
  257. }
  258. /**
  259. * Create a clone of instance of object (new instance with same properties)
  260. * This function works for both PHP4 and PHP5
  261. *
  262. * @param object $object Object to clone
  263. * @return object Object clone
  264. */
  265. function dol_clone($object)
  266. {
  267. dol_syslog("Functions.lib::dol_clone Clone object");
  268. // We create dynamically a clone function, making a =
  269. if (version_compare(phpversion(), '5.0') < 0 && ! function_exists('clone'))
  270. {
  271. eval('function clone($object){return($object);}');
  272. }
  273. $myclone=clone($object);
  274. return $myclone;
  275. }
  276. /**
  277. * Optimize a size for some browsers (phone, smarphone, ...)
  278. *
  279. * @param int $size Size we want
  280. * @param string $type Type of optimizing:
  281. * '' = function used to define a size for truncation
  282. * 'width' = function is used to define a width
  283. * @return int New size after optimizing
  284. */
  285. function dol_size($size,$type='')
  286. {
  287. global $conf;
  288. if (empty($conf->browser->phone)) return $size;
  289. if ($type == 'width' && $size > 250) return 250;
  290. else return 10;
  291. }
  292. /**
  293. * Return date for now. We should always use this function without parameters (that means GMT time)
  294. *
  295. * @param string $mode 'gmt' => we return GMT timestamp,
  296. * 'tzserver' => we add the PHP server timezone
  297. * 'tzref' => we add the company timezone
  298. * 'tzuser' => we add the user timezone
  299. * @return timestamp $date Timestamp
  300. */
  301. function dol_now($mode='gmt')
  302. {
  303. // Note that gmmktime and mktime return same value (GMT) whithout parameters
  304. if ($mode == 'gmt') $ret=gmmktime(); // Time for now at greenwich.
  305. else if ($mode == 'tzserver') // Time for now with PHP server timezone added
  306. {
  307. $tzsecond=-dol_mktime(0,0,0,1,1,1970);
  308. $ret=gmmktime()+$tzsecond;
  309. }
  310. else if ($mode == 'tzref') // Time for now where parent company timezone is added
  311. {
  312. // TODO Should add the company timezone
  313. $ret=gmmktime();
  314. }
  315. else if ($mode == 'tzuser') // Time for now where user timezone is added
  316. {
  317. //print 'eeee'.time().'-'.mktime().'-'.gmmktime();
  318. $tzhour=isset($_SESSION['dol_tz'])?$_SESSION['dol_tz']:0;
  319. $ret=gmmktime()+($tzhour*60*60);
  320. }
  321. return $ret;
  322. }
  323. /**
  324. * Clean a string to use it as a file name
  325. *
  326. * @param string $str String to clean
  327. * @param string $newstr String to replace bad chars with
  328. * @return string String cleaned (a-zA-Z_)
  329. *
  330. * @see dol_string_nospecial, dol_string_unaccent
  331. */
  332. function dol_sanitizeFileName($str,$newstr='_')
  333. {
  334. global $conf;
  335. return dol_string_nospecial(dol_string_unaccent($str),$newstr,$conf->filesystem_forbidden_chars);
  336. }
  337. /**
  338. * Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName
  339. *
  340. * @param string $str String to clean
  341. * @return string Cleaned string
  342. *
  343. * @see dol_sanitizeFilename, dol_string_nospecial
  344. */
  345. function dol_string_unaccent($str)
  346. {
  347. if (utf8_check($str))
  348. {
  349. $string = rawurlencode($str);
  350. $replacements = array(
  351. '%C3%80' => 'A','%C3%81' => 'A',
  352. '%C3%88' => 'E','%C3%89' => 'E',
  353. '%C3%8C' => 'I','%C3%8D' => 'I',
  354. '%C3%92' => 'O','%C3%93' => 'O',
  355. '%C3%99' => 'U','%C3%9A' => 'U',
  356. '%C3%A0' => 'a','%C3%A1' => 'a','%C3%A2' => 'a',
  357. '%C3%A8' => 'e','%C3%A9' => 'e','%C3%AA' => 'e','%C3%AB' => 'e',
  358. '%C3%AC' => 'i','%C3%AD' => 'i','%C3%AE' => 'i',
  359. '%C3%B2' => 'o','%C3%B3' => 'o',
  360. '%C3%B9' => 'u','%C3%BA' => 'u'
  361. );
  362. $string=strtr($string, $replacements);
  363. return rawurldecode($string);
  364. }
  365. else
  366. {
  367. $string = strtr($str,
  368. "\xC0\xC1\xC2\xC3\xC5\xC7
  369. \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
  370. \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
  371. \xE0\xE1\xE2\xE3\xE5\xE7\xE8\xE9\xEA\xEB
  372. \xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
  373. \xF9\xFA\xFB\xFD\xFF",
  374. "AAAAAC
  375. EEEEIIIIDN
  376. OOOOOUUUY
  377. aaaaaceeee
  378. iiiidnooooo
  379. uuuyy");
  380. $string = strtr($string, array("\xC4"=>"Ae", "\xC6"=>"AE", "\xD6"=>"Oe", "\xDC"=>"Ue", "\xDE"=>"TH", "\xDF"=>"ss", "\xE4"=>"ae", "\xE6"=>"ae", "\xF6"=>"oe", "\xFC"=>"ue", "\xFE"=>"th"));
  381. return $string;
  382. }
  383. }
  384. /**
  385. * Clean a string from all punctuation characters to use it as a ref or login
  386. *
  387. * @param string $str String to clean
  388. * @param string $newstr String to replace forbidden chars with
  389. * @param array $badchars List of forbidden characters
  390. * @return string Cleaned string
  391. *
  392. * @see dol_sanitizeFilename, dol_string_unaccent
  393. */
  394. function dol_string_nospecial($str,$newstr='_',$badchars='')
  395. {
  396. $forbidden_chars_to_replace=array(" ","'","/","\\",":","*","?","\"","<",">","|","[","]",",",";","=");
  397. $forbidden_chars_to_remove=array();
  398. if (is_array($badchars)) $forbidden_chars_to_replace=$badchars;
  399. //$forbidden_chars_to_remove=array("(",")");
  400. return str_replace($forbidden_chars_to_replace,$newstr,str_replace($forbidden_chars_to_remove,"",$str));
  401. }
  402. /**
  403. * Returns text escaped for inclusion into javascript code
  404. *
  405. * @param string $stringtoescape String to escape
  406. * @return string Escaped string
  407. */
  408. function dol_escape_js($stringtoescape)
  409. {
  410. // escape quotes and backslashes, newlines, etc.
  411. $substitjs=array("&#039;"=>"\\'",'\\'=>'\\\\',"'"=>"\\'",'"'=>"\\'","\r"=>'\\r',"\n"=>'\\n','</'=>'<\/');
  412. return strtr($stringtoescape, $substitjs);
  413. }
  414. /**
  415. * Returns text escaped for inclusion in HTML alt or title tags
  416. *
  417. * @param string $stringtoescape String to escape
  418. * @param int $keepb Do not clean b tags
  419. * @return string Escaped string
  420. */
  421. function dol_escape_htmltag($stringtoescape,$keepb=0)
  422. {
  423. // escape quotes and backslashes, newlines, etc.
  424. $tmp=dol_html_entity_decode($stringtoescape,ENT_COMPAT,'UTF-8');
  425. if ($keepb) $tmp=strtr($tmp, array('"'=>'',"\r"=>'\\r',"\n"=>'\\n'));
  426. else $tmp=strtr($tmp, array('"'=>'',"\r"=>'\\r',"\n"=>'\\n',"<b>"=>'','</b>'=>''));
  427. return dol_htmlentities($tmp,ENT_COMPAT,'UTF-8');
  428. }
  429. /**
  430. * Write log message into outputs. Possible outputs can be:
  431. * A file if SYSLOG_FILE_ON defined: file name is then defined by SYSLOG_FILE
  432. * Syslog if SYSLOG_SYSLOG_ON defined: facility is then defined by SYSLOG_FACILITY
  433. * Warning, les fonctions syslog sont buggues sous Windows et generent des
  434. * fautes de protection memoire. Pour resoudre, utiliser le loggage fichier,
  435. * au lieu du loggage syslog (configuration du module).
  436. * Note: If SYSLOG_FILE_NO_ERROR defined, we never output error message when writing to log fails.
  437. *
  438. * This function works only if syslog module is enabled.
  439. * This must not use any call to other function calling dol_syslog (avoid infinite loop).
  440. *
  441. * @param string $message Line to log. Ne doit pas etre traduit si level = LOG_ERR
  442. * @param int $level Log level
  443. * On Windows LOG_ERR=4, LOG_WARNING=5, LOG_NOTICE=LOG_INFO=6, LOG_DEBUG=6 si define_syslog_variables ou PHP 5.3+, 7 si dolibarr
  444. * On Linux LOG_ERR=3, LOG_WARNING=4, LOG_INFO=6, LOG_DEBUG=7
  445. * @return void
  446. */
  447. function dol_syslog($message, $level=LOG_INFO)
  448. {
  449. global $conf,$user,$langs,$_REQUEST;
  450. // If adding log inside HTML page is required
  451. if (! empty($_REQUEST['logtohtml']) && ! empty($conf->global->MAIN_LOGTOHTML))
  452. {
  453. $conf->logbuffer[]=dol_print_date(time(),"%Y-%m-%d %H:%M:%S")." ".$message;
  454. }
  455. // If syslog module enabled
  456. if (! empty($conf->syslog->enabled))
  457. {
  458. //print $level.' - '.$conf->global->SYSLOG_LEVEL.' - '.$conf->syslog->enabled." \n";
  459. if ($level > $conf->global->SYSLOG_LEVEL) return;
  460. // Translate error message if this is an error message (rare) and langs is loaded
  461. if ($level == LOG_ERR)
  462. {
  463. if (is_object($langs))
  464. {
  465. $langs->load("errors");
  466. if ($message != $langs->trans($message)) $message = $langs->trans($message);
  467. }
  468. }
  469. // Add page/script name to log message
  470. $script=isset($_SERVER['PHP_SELF'])?basename($_SERVER['PHP_SELF'],'.php').' ':'';
  471. $message=$script.$message;
  472. // Add user to log message
  473. $login='nologin';
  474. if (is_object($user) && $user->id) $login=$user->login;
  475. $message=sprintf("%-8s",$login)." ".$message;
  476. // Check if log is to a file (SYSLOG_FILE_ON defined)
  477. if (defined("SYSLOG_FILE_ON") && constant("SYSLOG_FILE_ON"))
  478. {
  479. $filelog=SYSLOG_FILE;
  480. $filelog=preg_replace('/DOL_DATA_ROOT/i',DOL_DATA_ROOT,$filelog);
  481. //print "filelog=".$filelog."\n";
  482. if (defined("SYSLOG_FILE_NO_ERROR")) $file=@fopen($filelog,"a+");
  483. else $file=fopen($filelog,"a+");
  484. if ($file)
  485. {
  486. $ip='???'; // $ip contains information to identify computer that run the code
  487. if (! empty($_SERVER["REMOTE_ADDR"])) $ip=$_SERVER["REMOTE_ADDR"]; // In most cases.
  488. else if (! empty($_SERVER['SERVER_ADDR'])) $ip=$_SERVER['SERVER_ADDR']; // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
  489. else if (! empty($_SERVER['COMPUTERNAME'])) $ip=$_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME'])?'':'@'.$_SERVER['USERNAME']); // This is when PHP session is ran outside a web server, like from Windows command line (Not always defined, but usefull if OS defined it).
  490. else if (! empty($_SERVER['LOGNAME'])) $ip='???@'.$_SERVER['LOGNAME']; // This is when PHP session is ran outside a web server, like from Linux command line (Not always defined, but usefull if OS defined it).
  491. $liblevelarray=array(LOG_ERR=>'ERROR',LOG_WARNING=>'WARN',LOG_INFO=>'INFO',LOG_DEBUG=>'DEBUG');
  492. $liblevel=$liblevelarray[$level];
  493. if (! $liblevel) $liblevel='UNDEF';
  494. $message=dol_print_date(time(),"%Y-%m-%d %H:%M:%S")." ".sprintf("%-5s",$liblevel)." ".sprintf("%-15s",$ip)." ".$message;
  495. fwrite($file,$message."\n");
  496. fclose($file);
  497. // This is for log file, we do not change permissions
  498. // If enable html log tag enabled and url parameter log defined, we show output log on HTML comments
  499. if (! empty($conf->global->MAIN_ENABLE_LOG_HTML) && ! empty($_GET["log"]))
  500. {
  501. print "\n\n<!-- Log start\n";
  502. print $message."\n";
  503. print "Log end -->\n";
  504. }
  505. }
  506. elseif (! defined("SYSLOG_FILE_NO_ERROR"))
  507. {
  508. // Do not use here a call to functions that make call to dol_syslog so making call to langs. A simple print is enough.
  509. print "Error, failed to open file ".$filelog."\n";
  510. }
  511. }
  512. // Check if log is to syslog (SYSLOG_SYSLOG_ON defined)
  513. if (defined("SYSLOG_SYSLOG_ON") && constant("SYSLOG_SYSLOG_ON"))
  514. {
  515. if (function_exists('openlog')) // This function does not exists on some ISP (Ex: Free in France)
  516. {
  517. $facility = LOG_USER;
  518. if (defined("SYSLOG_FACILITY") && constant("SYSLOG_FACILITY"))
  519. {
  520. // Exemple: SYSLOG_FACILITY vaut LOG_USER qui vaut 8. On a besoin de 8 dans $facility.
  521. $facility = constant("SYSLOG_FACILITY");
  522. }
  523. openlog("dolibarr", LOG_PID | LOG_PERROR, (int) $facility); // (int) is required to avoid error parameter 3 expected to be long
  524. if (! $level) syslog(LOG_ERR, $message);
  525. else syslog($level, $message);
  526. closelog();
  527. }
  528. }
  529. // Check if log is to syslog (SYSLOG_FIREPHP_ON defined)
  530. if (defined("SYSLOG_FIREPHP_ON") && constant("SYSLOG_FIREPHP_ON") && ! empty($_SERVER["SERVER_NAME"])) //! empty($_SERVER["SERVER_NAME"]) to be sure to enable this in Web mode only
  531. {
  532. try
  533. {
  534. // Warning FirePHPCore must be into PHP include path. It is not possible to use into require_once() a constant from
  535. // database or config file because we must be able to log data before database or config file read.
  536. $oldinclude=get_include_path();
  537. set_include_path('/usr/share/php/');
  538. require_once('FirePHPCore/FirePHP.class.php');
  539. set_include_path($oldinclude);
  540. ob_start();
  541. $firephp = FirePHP::getInstance(true);
  542. if ($level == LOG_ERR) $firephp->error($message);
  543. elseif ($level == LOG_WARNING) $firephp->warn($message);
  544. elseif ($level == LOG_INFO) $firephp->log($message);
  545. else $firephp->log($message);
  546. }
  547. catch(Exception $e)
  548. {
  549. }
  550. }
  551. }
  552. }
  553. /**
  554. * Show tab header of a card
  555. *
  556. * @param array $links Array of tabs
  557. * @param int $active Active tab name
  558. * @param string $title Title
  559. * @param int $notab 0=Add tab header, 1=no tab header
  560. * @param string $picto Add a picto on tab title
  561. * @return void
  562. */
  563. function dol_fiche_head($links=array(), $active='0', $title='', $notab=0, $picto='')
  564. {
  565. print dol_get_fiche_head($links, $active, $title, $notab, $picto);
  566. }
  567. /**
  568. * Show tab header of a card
  569. *
  570. * @param array $links Array of tabs
  571. * @param int $active Active tab name
  572. * @param string $title Title
  573. * @param int $notab 0=Add tab header, 1=no tab header
  574. * @param string $picto Add a picto on tab title
  575. * @return void
  576. */
  577. function dol_get_fiche_head($links=array(), $active='0', $title='', $notab=0, $picto='')
  578. {
  579. $out="\n".'<div class="tabs">'."\n";
  580. // Affichage titre
  581. if ($title)
  582. {
  583. $limittitle=30;
  584. $out.='<a class="tabTitle">';
  585. if ($picto) $out.=img_object('',$picto).' ';
  586. $out.=dol_trunc($title,$limittitle);
  587. $out.='</a>';
  588. }
  589. // Define max of key (max may be higher than sizeof because of hole due to module disabling some tabs).
  590. $maxkey=-1;
  591. if (is_array($links))
  592. {
  593. $keys=array_keys($links);
  594. if (count($keys)) $maxkey=max($keys);
  595. }
  596. // Show tabs
  597. for ($i = 0 ; $i <= $maxkey ; $i++)
  598. {
  599. if (isset($links[$i][2]) && $links[$i][2] == 'image')
  600. {
  601. if (!empty($links[$i][0]))
  602. {
  603. $out.='<a class="tabimage" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  604. }
  605. else
  606. {
  607. $out.='<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  608. }
  609. }
  610. else if (! empty($links[$i][1]))
  611. {
  612. //print "x $i $active ".$links[$i][2]." z";
  613. if ((is_numeric($active) && $i == $active)
  614. || (! is_numeric($active) && $active == $links[$i][2]))
  615. {
  616. $out.='<a id="active" class="tab" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  617. }
  618. else
  619. {
  620. $out.='<a id="'.$links[$i][2].'" class="tab" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  621. }
  622. }
  623. }
  624. $out.="</div>\n";
  625. if (! $notab) $out.="\n".'<div class="tabBar">'."\n";
  626. return $out;
  627. }
  628. /**
  629. * Show tab footer of a card
  630. *
  631. * @param int $notab 0=Add tab footer, 1=no tab footer
  632. * @return void
  633. */
  634. function dol_fiche_end($notab=0)
  635. {
  636. print dol_get_fiche_end($notab);
  637. }
  638. /**
  639. * Return tab footer of a card
  640. *
  641. * @param int $notab 0=Add tab footer, 1=no tab footer
  642. * @return void
  643. */
  644. function dol_get_fiche_end($notab=0)
  645. {
  646. if (! $notab) return "\n</div>\n";
  647. else return '';
  648. }
  649. /* For backward compatibility */
  650. function dolibarr_print_date($time,$format='',$to_gmt=false,$outputlangs='',$encodetooutput=false)
  651. {
  652. return dol_print_date($time,$format,$to_gmt,$outputlangs,$encodetooutput);
  653. }
  654. /**
  655. * Return a formated address (part address/zip/town/state) according to country rules
  656. *
  657. * @param outputlangs Output langs object
  658. * @param object A company or contact object
  659. * @return string Formated string
  660. */
  661. function dol_format_address($outputlangs,$object)
  662. {
  663. $ret='';
  664. $countriesusingstate=array('US','IN');
  665. // Address
  666. $ret .= $outputlangs->convToOutputCharset($object->address);
  667. // Zip/Town/State
  668. if (in_array($object->country_code,array('US'))) // US: town, state, zip
  669. {
  670. $ret .= ($ret ? "\n" : '' ).$outputlangs->convToOutputCharset($object->town);
  671. if ($object->state && in_array($object->country_code,$countriesusingstate))
  672. {
  673. $ret.=", ".$outputlangs->convToOutputCharset($object->departement);
  674. }
  675. if ($object->zip) $ret .= ', '.$outputlangs->convToOutputCharset($object->zip);
  676. }
  677. else // Other: zip town, state
  678. {
  679. $ret .= ($ret ? "\n" : '' ).$outputlangs->convToOutputCharset($object->zip);
  680. $ret .= ' '.$outputlangs->convToOutputCharset($object->town);
  681. if ($object->state && in_array($object->country_code,$countriesusingstate))
  682. {
  683. $ret.=", ".$outputlangs->convToOutputCharset($object->state);
  684. }
  685. }
  686. return $ret;
  687. }
  688. /**
  689. * Output date in a string format according to outputlangs (or langs if not defined).
  690. * Return charset is always UTF-8, except if encodetoouput is defined. In this cas charset is output charset
  691. *
  692. * @param timestamp $time GM Timestamps date (or deprecated strings 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS')
  693. * @param string $format Output date format
  694. * "%d %b %Y",
  695. * "%d/%m/%Y %H:%M",
  696. * "%d/%m/%Y %H:%M:%S",
  697. * "day", "daytext", "dayhour", "dayhourldap", "dayhourtext"
  698. * @param string $tzoutput true=output or 'gmt' => string is for Greenwich location
  699. * false or 'tzserver' => output string is for local PHP server TZ usage
  700. * 'tzuser' => output string is for local browser TZ usage
  701. * @param Tranlsate $outputlangs Object lang that contains language for text translation.
  702. * @param boolean $encodetooutput false=no convert into output pagecode
  703. * @return string Formated date or '' if time is null
  704. *
  705. * @see dol_mktime, dol_stringtotime, dol_getdate
  706. */
  707. function dol_print_date($time,$format='',$tzoutput='tzserver',$outputlangs='',$encodetooutput=false)
  708. {
  709. global $conf,$langs;
  710. $to_gmt=false;
  711. $offsettz=$offsetdst=0;
  712. if ($tzoutput)
  713. {
  714. $to_gmt=true; // For backward compatibility
  715. if (is_string($tzoutput))
  716. {
  717. if ($tzoutput == 'tzserver')
  718. {
  719. $to_gmt=false;
  720. $offsettz=$offsetdst=0;
  721. }
  722. if ($tzoutput == 'tzuser')
  723. {
  724. $to_gmt=true;
  725. $offsettz=(empty($_SESSION['dol_tz'])?0:$_SESSION['dol_tz'])*60*60;
  726. $offsetdst=(empty($_SESSION['dol_dst'])?0:$_SESSION['dol_dst'])*60*60;
  727. }
  728. if ($tzoutput == 'tzcompany')
  729. {
  730. $to_gmt=false;
  731. $offsettz=$offsetdst=0; // TODO Define this and use it later
  732. }
  733. }
  734. }
  735. if (! is_object($outputlangs)) $outputlangs=$langs;
  736. // Si format non defini, on prend $conf->format_date_text_short sinon %Y-%m-%d %H:%M:%S
  737. if (! $format) $format=(isset($conf->format_date_text_short) ? $conf->format_date_text_short : '%Y-%m-%d %H:%M:%S');
  738. // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
  739. if ($format == 'day') $format=($outputlangs->trans("FormatDateShort")!="FormatDateShort"?$outputlangs->trans("FormatDateShort"):$conf->format_date_short);
  740. if ($format == 'hour') $format=($outputlangs->trans("FormatHourShort")!="FormatHourShort"?$outputlangs->trans("FormatHourShort"):$conf->format_hour_short);
  741. if ($format == 'hourduration') $format=($outputlangs->trans("FormatHourShortDuration")!="FormatHourShortDuration"?$outputlangs->trans("FormatHourShortDuration"):$conf->format_hour_short_duration);
  742. if ($format == 'daytext') $format=($outputlangs->trans("FormatDateText")!="FormatDateText"?$outputlangs->trans("FormatDateText"):$conf->format_date_text);
  743. if ($format == 'daytextshort') $format=($outputlangs->trans("FormatDateTextShort")!="FormatDateTextShort"?$outputlangs->trans("FormatDateTextShort"):$conf->format_date_text_short);
  744. if ($format == 'dayhour') $format=($outputlangs->trans("FormatDateHourShort")!="FormatDateHourShort"?$outputlangs->trans("FormatDateHourShort"):$conf->format_date_hour_short);
  745. if ($format == 'dayhourtext') $format=($outputlangs->trans("FormatDateHourText")!="FormatDateHourText"?$outputlangs->trans("FormatDateHourText"):$conf->format_date_hour_text);
  746. if ($format == 'dayhourtextshort') $format=($outputlangs->trans("FormatDateHourTextShort")!="FormatDateHourTextShort"?$outputlangs->trans("FormatDateHourTextShort"):$conf->format_date_hour_text_short);
  747. // Format not sensitive to language
  748. if ($format == 'dayhourlog') $format='%Y%m%d%H%M%S';
  749. if ($format == 'dayhourldap') $format='%Y%m%d%H%M%SZ';
  750. if ($format == 'dayhourxcard') $format='%Y%m%dT%H%M%SZ';
  751. if ($format == 'dayxcard') $format='%Y%m%d';
  752. if ($format == 'dayrfc') $format='%Y-%m-%d'; // DATE_RFC3339
  753. if ($format == 'dayhourrfc') $format='%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339
  754. // If date undefined or "", we return ""
  755. if (dol_strlen($time) == 0) return ''; // $time=0 allowed (it means 01/01/1970 00:00:00)
  756. //print 'x'.$time;
  757. if (preg_match('/%b/i',$format)) // There is some text to translate
  758. {
  759. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  760. $format=str_replace('%b','__b__',$format);
  761. $format=str_replace('%B','__B__',$format);
  762. }
  763. if (preg_match('/%a/i',$format)) // There is some text to translate
  764. {
  765. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  766. $format=str_replace('%a','__a__',$format);
  767. $format=str_replace('%A','__A__',$format);
  768. }
  769. // Analyze date (deprecated) Ex: 1970-01-01, 1970-01-01 01:00:00, 19700101010000
  770. if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+) ?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i',$time,$reg)
  771. || preg_match('/^([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])$/i',$time,$reg))
  772. {
  773. // This part of code should not be used.
  774. dol_syslog("Functions.lib::dol_print_date function call with deprecated value of time in page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  775. // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS' or 'YYYYMMDDHHMMSS'
  776. $syear = $reg[1];
  777. $smonth = $reg[2];
  778. $sday = $reg[3];
  779. $shour = $reg[4];
  780. $smin = $reg[5];
  781. $ssec = $reg[6];
  782. $time=dol_mktime($shour,$smin,$ssec,$smonth,$sday,$syear,true);
  783. $ret=adodb_strftime($format,$time+$offsettz+$offsetdst,$to_gmt);
  784. }
  785. else
  786. {
  787. // Date is a timestamps
  788. if ($time < 100000000000) // Protection against bad date values
  789. {
  790. $ret=adodb_strftime($format,$time+$offsettz+$offsetdst,$to_gmt);
  791. }
  792. else $ret='Bad value '.$time.' for date';
  793. }
  794. if (preg_match('/__b__/i',$format))
  795. {
  796. // Here ret is string in PHP setup language (strftime was used). Now we convert to $outputlangs.
  797. $month=adodb_strftime('%m',$time+$offsettz+$offsetdst);
  798. if ($encodetooutput)
  799. {
  800. $monthtext=$outputlangs->transnoentities('Month'.$month);
  801. $monthtextshort=$outputlangs->transnoentities('MonthShort'.$month);
  802. }
  803. else
  804. {
  805. $monthtext=$outputlangs->transnoentitiesnoconv('Month'.$month);
  806. $monthtextshort=$outputlangs->transnoentitiesnoconv('MonthShort'.$month);
  807. }
  808. //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
  809. $ret=str_replace('__b__',$monthtextshort,$ret);
  810. $ret=str_replace('__B__',$monthtext,$ret);
  811. //print 'x'.$outputlangs->charset_output.'-'.$ret.'x';
  812. //return $ret;
  813. }
  814. if (preg_match('/__a__/i',$format))
  815. {
  816. $w=adodb_strftime('%w',$time+$offsettz+$offsetdst);
  817. $dayweek=$outputlangs->transnoentitiesnoconv('Day'.$w);
  818. $ret=str_replace('__A__',$dayweek,$ret);
  819. $ret=str_replace('__a__',dol_substr($dayweek,0,3),$ret);
  820. }
  821. return $ret;
  822. }
  823. /**
  824. * Convert a string date into a GM Timestamps date
  825. *
  826. * @param string $string Date in a string
  827. * YYYYMMDD
  828. * YYYYMMDDHHMMSS
  829. * YYYY-MM-DDTHH:MM:SSZ (RFC3339)
  830. * DD/MM/YY or DD/MM/YYYY (this format should not be used anymore)
  831. * DD/MM/YY HH:MM:SS or DD/MM/YYYY HH:MM:SS (this format should not be used anymore)
  832. * @param int $gm 1=Input date is GM date, 0=Input date is local date
  833. * 19700101020000 -> 7200 with gm=1
  834. * @return date Date
  835. *
  836. * @see dol_print_date, dol_mktime, dol_getdate
  837. */
  838. function dol_stringtotime($string, $gm=1)
  839. {
  840. if (preg_match('/^([0-9]+)\/([0-9]+)\/([0-9]+)\s?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i',$string,$reg))
  841. {
  842. // This part of code should not be used.
  843. dol_syslog("Functions.lib::dol_stringtotime call to function with deprecated parameter", LOG_WARNING);
  844. // Date est au format 'DD/MM/YY' ou 'DD/MM/YY HH:MM:SS'
  845. // Date est au format 'DD/MM/YYYY' ou 'DD/MM/YYYY HH:MM:SS'
  846. $sday = $reg[1];
  847. $smonth = $reg[2];
  848. $syear = $reg[3];
  849. $shour = $reg[4];
  850. $smin = $reg[5];
  851. $ssec = $reg[6];
  852. if ($syear < 50) $syear+=1900;
  853. if ($syear >= 50 && $syear < 100) $syear+=2000;
  854. $string=sprintf("%04d%02d%02d%02d%02d%02d",$syear,$smonth,$sday,$shour,$smin,$ssec);
  855. }
  856. // Convert date RFC3339
  857. else if (preg_match('/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})Z$/i',$string,$reg))
  858. {
  859. $syear = $reg[1];
  860. $smonth = $reg[2];
  861. $sday = $reg[3];
  862. $shour = $reg[4];
  863. $smin = $reg[5];
  864. $ssec = $reg[6];
  865. $string=sprintf("%04d%02d%02d%02d%02d%02d",$syear,$smonth,$sday,$shour,$smin,$ssec);
  866. }
  867. $string=preg_replace('/([^0-9])/i','',$string);
  868. $tmp=$string.'000000';
  869. $date=dol_mktime(substr($tmp,8,2),substr($tmp,10,2),substr($tmp,12,2),substr($tmp,4,2),substr($tmp,6,2),substr($tmp,0,4),$gm);
  870. return $date;
  871. }
  872. /**
  873. * Return an array with date info
  874. * PHP getdate is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
  875. *
  876. * @param timestamp $timestamp Timestamp
  877. * @param boolean $fast Fast mode
  878. * @return array Array of informations
  879. * If no fast mode:
  880. * 'seconds' => $secs,
  881. * 'minutes' => $min,
  882. * 'hours' => $hour,
  883. * 'mday' => $day,
  884. * 'wday' => $dow,
  885. * 'mon' => $month,
  886. * 'year' => $year,
  887. * 'yday' => floor($secsInYear/$_day_power),
  888. * 'weekday' => gmdate('l',$_day_power*(3+$dow)),
  889. * 'month' => gmdate('F',mktime(0,0,0,$month,2,1971)),
  890. * If fast mode:
  891. * 'seconds' => $secs,
  892. * 'minutes' => $min,
  893. * 'hours' => $hour,
  894. * 'mday' => $day,
  895. * 'mon' => $month,
  896. * 'year' => $year,
  897. * 'yday' => floor($secsInYear/$_day_power),
  898. * 'leap' => $leaf,
  899. * 'ndays' => $ndays
  900. */
  901. function dol_getdate($timestamp,$fast=false)
  902. {
  903. $usealternatemethod=false;
  904. if ($timestamp <= 0) $usealternatemethod=true; // <= 1970
  905. if ($timestamp >= 2145913200) $usealternatemethod=true; // >= 2038
  906. if ($usealternatemethod)
  907. {
  908. $arrayinfo=adodb_getdate($timestamp,$fast);
  909. }
  910. else
  911. {
  912. $arrayinfo=getdate($timestamp);
  913. }
  914. return $arrayinfo;
  915. }
  916. /* For backward compatibility */
  917. function dolibarr_mktime($hour,$minute,$second,$month,$day,$year,$gm=false,$check=1)
  918. {
  919. return dol_mktime($hour,$minute,$second,$month,$day,$year,$gm,$check);
  920. }
  921. /**
  922. * Return a timestamp date built from detailed informations (by default a local PHP server timestamp)
  923. * Replace function mktime not available under Windows if year < 1970
  924. * PHP mktime is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
  925. *
  926. * @param hour Hour (can be -1 for undefined)
  927. * @param minute Minute (can be -1 for undefined)
  928. * @param second Second (can be -1 for undefined)
  929. * @param month Month (1 to 12)
  930. * @param day Day (1 to 31)
  931. * @param year Year
  932. * @param gm 1=Input informations are GMT values, otherwise local to server TZ
  933. * @param check 0=No check on parameters (Can use day 32, etc...)
  934. * @param isdst Dayling saving time
  935. * @return timestamp Date as a timestamp, '' if error
  936. * @see dol_print_date, dol_stringtotime
  937. */
  938. function dol_mktime($hour,$minute,$second,$month,$day,$year,$gm=false,$check=1,$isdst=true)
  939. {
  940. //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
  941. // Clean parameters
  942. if ($hour == -1) $hour=0;
  943. if ($minute == -1) $minute=0;
  944. if ($second == -1) $second=0;
  945. // Check parameters
  946. if ($check)
  947. {
  948. if (! $month || ! $day) return '';
  949. if ($day > 31) return '';
  950. if ($month > 12) return '';
  951. if ($hour < 0 || $hour > 24) return '';
  952. if ($minute< 0 || $minute > 60) return '';
  953. if ($second< 0 || $second > 60) return '';
  954. }
  955. $usealternatemethod=false;
  956. if ($year <= 1970) $usealternatemethod=true; // <= 1970
  957. if ($year >= 2038) $usealternatemethod=true; // >= 2038
  958. if ($usealternatemethod || $gm) // Si time gm, seule adodb peut convertir
  959. {
  960. /*
  961. // On peut utiliser strtotime pour obtenir la traduction.
  962. // strtotime is ok for range: Friday 13 December 1901 20:45:54 GMT to Tuesday 19 January 2038 03:14:07 GMT.
  963. $montharray=array(1=>'january',2=>'february',3=>'march',4=>'april',5=>'may',6=>'june',
  964. 7=>'july',8=>'august',9=>'september',10=>'october',11=>'november',12=>'december');
  965. $string=$day." ".$montharray[0+$month]." ".$year." ".$hour.":".$minute.":".$second." GMT";
  966. $date=strtotime($string);
  967. print "- ".$string." ".$date." -";
  968. */
  969. $date=adodb_mktime($hour,$minute,$second,$month,$day,$year,$isdst,$gm);
  970. }
  971. else
  972. {
  973. $date=mktime($hour,$minute,$second,$month,$day,$year);
  974. }
  975. return $date;
  976. }
  977. /* For backward compatibility */
  978. function dolibarr_date($fmt, $timestamp, $gm=false)
  979. {
  980. return dol_date($fmt, $timestamp, $gm);
  981. }
  982. /**
  983. * Returns formated date
  984. *
  985. * @param string $fmt Format (Exemple: 'Y-m-d H:i:s')
  986. * @param timestamp $timestamp Date. Example: If timestamp=0 and gm=1, return 01/01/1970 00:00:00
  987. * @param boolean $gm 1 if timestamp was built with gmmktime, 0 if timestamp was build with mktime
  988. * @return string Formated date
  989. *
  990. * @deprecated Replaced by dol_print_date
  991. */
  992. function dol_date($fmt, $timestamp, $gm=false)
  993. {
  994. $usealternatemethod=false;
  995. if ($timestamp <= 0) $usealternatemethod=true;
  996. if ($timestamp >= 2145913200) $usealternatemethod=true;
  997. if ($usealternatemethod || $gm) // Si time gm, seule adodb peut convertir
  998. {
  999. $string=adodb_date($fmt,$timestamp,$gm);
  1000. }
  1001. else
  1002. {
  1003. $string=date($fmt,$timestamp);
  1004. }
  1005. return $string;
  1006. }
  1007. /**
  1008. * Return string with formated size
  1009. *
  1010. * @param int $size Size to print
  1011. * @param int $shortvalue Tell if we want long value to use another unit (Ex: 1.5Kb instead of 1500b)
  1012. * @param int $shortunit Use short value of size unit
  1013. * @return string Link
  1014. */
  1015. function dol_print_size($size,$shortvalue=0,$shortunit=0)
  1016. {
  1017. global $langs;
  1018. $level=1024;
  1019. // Set value text
  1020. if (empty($shortvalue) || $size < ($level*10))
  1021. {
  1022. $ret=$size;
  1023. $textunitshort=$langs->trans("b");
  1024. $textunitlong=$langs->trans("Bytes");
  1025. }
  1026. else
  1027. {
  1028. $ret=round($size/$level,0);
  1029. $textunitshort=$langs->trans("Kb");
  1030. $textunitlong=$langs->trans("KiloBytes");
  1031. }
  1032. // Use long or short text unit
  1033. if (empty($shortunit)) { $ret.=' '.$textunitlong; }
  1034. else { $ret.=' '.$textunitshort; }
  1035. return $ret;
  1036. }
  1037. /**
  1038. * Show Url link
  1039. *
  1040. * @param string $url Url to show
  1041. * @param string $target Target for link
  1042. * @param int $max Max number of characters to show
  1043. * @return string HTML Link
  1044. */
  1045. function dol_print_url($url,$target='_blank',$max=32)
  1046. {
  1047. if (empty($url)) return '';
  1048. $link='<a href="';
  1049. if (! preg_match('/^http/i',$url)) $link.='http://';
  1050. $link.=$url;
  1051. if ($target) $link.='" target="'.$target.'">';
  1052. if (! preg_match('/^http/i',$url)) $link.='http://';
  1053. $link.=dol_trunc($url,$max);
  1054. $link.='</a>';
  1055. return $link;
  1056. }
  1057. /**
  1058. * Show EMail link
  1059. *
  1060. * @param string $email EMail to show (only email, without 'Name of recipient' before)
  1061. * @param int $cid Id of contact if known
  1062. * @param int $socid Id of third party if known
  1063. * @param int $addlink 0=no link to create action
  1064. * @param int $max Max number of characters to show
  1065. * @param int $showinvalid Show warning if syntax email is wrong
  1066. * @return string HTML Link
  1067. */
  1068. function dol_print_email($email,$cid=0,$socid=0,$addlink=0,$max=64,$showinvalid=1)
  1069. {
  1070. global $conf,$user,$langs;
  1071. $newemail=$email;
  1072. if (empty($email)) return '&nbsp;';
  1073. if (! empty($addlink))
  1074. {
  1075. $newemail='<a href="';
  1076. if (! preg_match('/^mailto:/i',$email)) $newemail.='mailto:';
  1077. $newemail.=$email;
  1078. $newemail.='">';
  1079. $newemail.=dol_trunc($email,$max);
  1080. $newemail.='</a>';
  1081. if ($showinvalid && ! isValidEmail($email))
  1082. {
  1083. $langs->load("errors");
  1084. $newemail.=img_warning($langs->trans("ErrorBadEMail",$email));
  1085. }
  1086. if (($cid || $socid) && $conf->agenda->enabled && $user->rights->agenda->myactions->create)
  1087. {
  1088. $type='AC_EMAIL'; $link='';
  1089. if (! empty($conf->global->AGENDA_ADDACTIONFOREMAIL)) $link='<a href="'.DOL_URL_ROOT.'/comm/action/fiche.php?action=create&amp;backtopage=1&amp;actioncode='.$type.'&amp;contactid='.$cid.'&amp;socid='.$socid.'">'.img_object($langs->trans("AddAction"),"calendar").'</a>';
  1090. $newemail='<table class="nobordernopadding"><tr><td>'.$newemail.' </td><td>&nbsp;'.$link.'</td></tr></table>';
  1091. }
  1092. }
  1093. else
  1094. {
  1095. if ($showinvalid && ! isValidEmail($email))
  1096. {
  1097. $langs->load("errors");
  1098. $newemail.=img_warning($langs->trans("ErrorBadEMail",$email));
  1099. }
  1100. }
  1101. return $newemail;
  1102. }
  1103. /* For backward compatibility */
  1104. function dolibarr_print_phone($phone,$country="FR",$cid=0,$socid=0,$addlink=0,$separ="&nbsp;")
  1105. {
  1106. return dol_print_phone($phone,$country,$cid,$socid,$addlink,$separ);
  1107. }
  1108. /**
  1109. * Format phone numbers according to country
  1110. *
  1111. * @param string $phone Phone number to format
  1112. * @param string $country Country code to use for formatting
  1113. * @param int $cid Id of contact if known
  1114. * @param int $socid Id of third party if known
  1115. * @param int $addlink 0=no link to create action
  1116. * @param string $separ separation between numbers for a better visibility example : xx.xx.xx.xx.xx
  1117. * @return string Formated phone number
  1118. */
  1119. function dol_print_phone($phone,$country="FR",$cid=0,$socid=0,$addlink=0,$separ="&nbsp;")
  1120. {
  1121. global $conf,$user,$langs;
  1122. // Clean phone parameter
  1123. $phone = preg_replace("/[\s.-]/","",trim($phone));
  1124. if (empty($phone)) { return ''; }
  1125. $newphone=$phone;
  1126. if (strtoupper($country) == "FR")
  1127. {
  1128. // France
  1129. if (dol_strlen($phone) == 10) {
  1130. $newphone=substr($newphone,0,2).$separ.substr($newphone,2,2).$separ.substr($newphone,4,2).$separ.substr($newphone,6,2).$separ.substr($newphone,8,2);
  1131. }
  1132. elseif (dol_strlen($newphone) == 7)
  1133. {
  1134. $newphone=substr($newphone,0,3).$separ.substr($newphone,3,2).$separ.substr($newphone,5,2);
  1135. }
  1136. elseif (dol_strlen($newphone) == 9)
  1137. {
  1138. $newphone=substr($newphone,0,2).$separ.substr($newphone,2,3).$separ.substr($newphone,5,2).$separ.substr($newphone,7,2);
  1139. }
  1140. elseif (dol_strlen($newphone) == 11)
  1141. {
  1142. $newphone=substr($newphone,0,3).$separ.substr($newphone,3,2).$separ.substr($newphone,5,2).$separ.substr($newphone,7,2).$separ.substr($newphone,9,2);
  1143. }
  1144. elseif (dol_strlen($newphone) == 12)
  1145. {
  1146. $newphone=substr($newphone,0,4).$separ.substr($newphone,4,2).$separ.substr($newphone,6,2).$separ.substr($newphone,8,2).$separ.substr($newphone,10,2);
  1147. }
  1148. }
  1149. if (! empty($addlink))
  1150. {
  1151. if ($conf->clicktodial->enabled)
  1152. {
  1153. if (empty($user->clicktodial_loaded)) $user->fetch_clicktodial();
  1154. if (empty($conf->global->CLICKTODIAL_URL)) $urlmask='ErrorClickToDialModuleNotConfigured';
  1155. else $urlmask=$conf->global->CLICKTODIAL_URL;
  1156. // This line is for backward compatibility
  1157. $url = sprintf($urlmask, urlencode($phone), urlencode($user->clicktodial_poste), urlencode($user->clicktodial_login), urlencode($user->clicktodial_password));
  1158. // Thoose lines are for substitution
  1159. $substitarray=array('__PHONEFROM__'=>urlencode($user->clicktodial_poste),
  1160. '__PHONETO__'=>urlencode($phone),
  1161. '__LOGIN__'=>urlencode($user->clicktodial_login),
  1162. '__PASS__'=>urlencode($user->clicktodial_password));
  1163. $url = make_substitutions($url, $substitarray);
  1164. $newphonesav=$newphone;
  1165. $newphone ='<a href="'.$url.'"';
  1166. if (! empty($conf->global->CLICKTODIAL_FORCENEWTARGET)) $newphone.=' target="_blank"';
  1167. $newphone.='>'.$newphonesav.'</a>';
  1168. }
  1169. //if (($cid || $socid) && $conf->agenda->enabled && $user->rights->agenda->myactions->create)
  1170. if ($conf->agenda->enabled && $user->rights->agenda->myactions->create)
  1171. {
  1172. $type='AC_TEL'; $link='';
  1173. if ($addlink == 'AC_FAX') $type='AC_FAX';
  1174. if (! empty($conf->global->AGENDA_ADDACTIONFORPHONE)) $link='<a href="'.DOL_URL_ROOT.'/comm/action/fiche.php?action=create&amp;backtopage=1&amp;actioncode='.$type.($cid?'&amp;contactid='.$cid:'').($socid?'&amp;socid='.$socid:'').'">'.img_object($langs->trans("AddAction"),"calendar").'</a>';
  1175. $newphone='<table class="nobordernopadding"><tr><td>'.$newphone.' </td><td>&nbsp;'.$link.'</td></tr></table>';
  1176. }
  1177. }
  1178. return $newphone;
  1179. }
  1180. /**
  1181. * Return an IP formated to be shown on screen
  1182. *
  1183. * @param string $ip IP
  1184. * @param int $mode 1=return only country/flag,2=return only IP
  1185. * @return string Formated IP, with country if GeoIP module is enabled
  1186. */
  1187. function dol_print_ip($ip,$mode=0)
  1188. {
  1189. global $conf,$langs;
  1190. $ret='';
  1191. if (empty($mode)) $ret.=$ip;
  1192. if (! empty($conf->geoipmaxmind->enabled) && $mode != 2)
  1193. {
  1194. $datafile=$conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
  1195. //$ip='24.24.24.24';
  1196. //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat'; Note that this must be downloaded datafile (not same than datafile provided with ubuntu packages)
  1197. include_once(DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php');
  1198. $geoip=new DolGeoIP('country',$datafile);
  1199. //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
  1200. //print "geoip_country_id_by_addr=".geoip_country_id_by_addr($geoip->gi,$ip)."\n";
  1201. $countrycode=$geoip->getCountryCodeFromIP($ip);
  1202. if ($countrycode) // If success, countrycode is us, fr, …

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