PageRenderTime 83ms CodeModel.GetById 22ms app.highlight 43ms RepoModel.GetById 1ms 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

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/**
  28 *	\file			htdocs/core/lib/functions.lib.php
  29 *	\brief			A set of functions for Dolibarr
  30 *					This file contains all frequently used functions.
  31 */
  32
  33
  34if (! function_exists('json_encode'))
  35{
  36	include_once DOL_DOCUMENT_ROOT .'/core/lib/json.lib.php';
  37}
  38
  39/**
  40 * Function to return value of a static property when class
  41 * name is dynamically defined (not hard coded).
  42 * This is because $myclass::$myvar works from PHP 5.3.0+ only
  43 *
  44 * @param	string 	$class		Class name
  45 * @param 	string 	$member		Name of property
  46 * @return 	string				Return value of static property.
  47 */
  48function getStaticMember($class, $member)
  49{
  50	if (is_object($class)) $class = get_class($class);
  51	$classObj = new ReflectionClass($class);
  52	$result = null;
  53
  54	$found=0;
  55	foreach($classObj->getStaticProperties() as $prop => $value)
  56	{
  57		if ($prop == $member)
  58		{
  59			$result = $value;
  60			$found++;
  61			break;
  62		}
  63	}
  64
  65	if (! $found) dol_print_error('','Try to get a static member "'.$member.'" in class "'.$class.'" that does not exists or is not static.');
  66	return $result;
  67}
  68
  69
  70/**
  71 * Return a DoliDB instance (database handler).
  72 *
  73 * @param   string	$type		Type of database (mysql, pgsql...)
  74 * @param	string	$host		Address of database server
  75 * @param	string	$user		Nom de l'utilisateur autorise
  76 * @param	string	$pass		Mot de passe
  77 * @param	string	$name		Nom de la database
  78 * @param	int		$port		Port of database server
  79 * @return	DoliDB				A DoliDB instance
  80 */
  81function getDoliDBInstance($type, $host, $user, $pass, $name, $port)
  82{
  83	require_once DOL_DOCUMENT_ROOT ."/core/db/".$type.'.class.php';
  84
  85	$class='DoliDB'.ucfirst($type);
  86	$dolidb=new $class($type, $host, $user, $pass, $name, $port);
  87	return $dolidb;
  88}
  89
  90/**
  91 * 	Get entity to use
  92 *
  93 * 	@param	string	$element	Current element
  94 * 	@param	int		$shared		1=Return shared entities
  95 * 	@return	mixed				Entity id(s) to use
  96 */
  97function getEntity($element=false, $shared=false)
  98{
  99	global $conf, $mc;
 100
 101	if (is_object($mc))
 102	{
 103		return $mc->getEntity($element, $shared);
 104	}
 105	else
 106	{
 107		$out='';
 108
 109		$addzero = array('user', 'usergroup');
 110		if (in_array($element, $addzero)) $out.= '0,';
 111
 112		$out.= $conf->entity;
 113
 114		return $out;
 115	}
 116}
 117
 118/**
 119 * Return information about user browser
 120 *
 121 * @return	array		Array of information ('browsername'=>,'browseros'=>,'phone'=>,'browserfirefox'=>)
 122 */
 123function getBrowserInfo()
 124{
 125	$name='unknown'; $version=''; $os='unknown'; $phone='';
 126
 127	// If phone/smartphone, we set phone os name.
 128	if (preg_match('/android/i',$_SERVER["HTTP_USER_AGENT"]))			{ $os=$phone='android'; }
 129	elseif (preg_match('/blackberry/i',$_SERVER["HTTP_USER_AGENT"]))	{ $os=$phone='blackberry'; }
 130	elseif (preg_match('/iphone/i',$_SERVER["HTTP_USER_AGENT"]))		{ $os='ios'; $phone='iphone'; }
 131	elseif (preg_match('/ipod/i',$_SERVER["HTTP_USER_AGENT"]))			{ $os='ios'; $phone='iphone'; }
 132	elseif (preg_match('/palm/i',$_SERVER["HTTP_USER_AGENT"]))			{ $os=$phone='palm'; }
 133	elseif (preg_match('/symbian/i',$_SERVER["HTTP_USER_AGENT"]))		{ $os='symbian'; $phone='unknown'; }
 134	elseif (preg_match('/webos/i',$_SERVER["HTTP_USER_AGENT"]))			{ $os='webos'; $phone='unknown'; }
 135	elseif (preg_match('/maemo/i',$_SERVER["HTTP_USER_AGENT"]))			{ $os='maemo'; $phone='unknown'; }
 136	// MS products at end
 137	elseif (preg_match('/iemobile/i',$_SERVER["HTTP_USER_AGENT"]))		{ $os='windows'; $phone='unkown'; }
 138	elseif (preg_match('/windows ce/i',$_SERVER["HTTP_USER_AGENT"]))	{ $os='windows'; $phone='unkown'; }
 139	// Name
 140	if (preg_match('/firefox(\/|\s)([\d\.]*)/i',    $_SERVER["HTTP_USER_AGENT"], $reg))  { $name='firefox';   $version=$reg[2]; }
 141	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
 142	elseif (preg_match('/chrome/i',                 $_SERVER["HTTP_USER_AGENT"], $reg))  { $name='chrome'; }
 143	elseif (preg_match('/iceweasel/i',$_SERVER["HTTP_USER_AGENT"]))                      { $name='iceweasel'; $version=$reg[2]; }
 144	elseif (preg_match('/epiphany/i',$_SERVER["HTTP_USER_AGENT"]))                       { $name='epiphany';  $version=$reg[2]; }
 145	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.
 146	elseif (preg_match('/opera(\/|\s)([\d\.]*)/i',  $_SERVER["HTTP_USER_AGENT"], $reg))  { $name='opera';     $version=$reg[2]; }
 147	elseif (preg_match('/msie(\/|\s)([\d\.]*)/i',   $_SERVER["HTTP_USER_AGENT"], $reg))  { $name='ie';        $version=$reg[2]; }    // MS products at end
 148	// Other
 149	$firefox=0;
 150	if (in_array($name,array('firefox','iceweasel'))) $firefox=1;
 151
 152	return array('browsername'=>$name, 'browserversion'=>$version, 'browseros'=>$os, 'phone'=>$phone, 'browserfirefox'=>$firefox);
 153}
 154
 155/**
 156 *  Function called at end of web php process
 157 *
 158 *  @return	void
 159 */
 160function dol_shutdown()
 161{
 162	global $conf,$user,$langs,$db;
 163	$disconnectdone=false; $depth=0;
 164	if (is_object($db) && ! empty($db->connected)) { $depth=$db->transaction_opened; $disconnectdone=$db->close(); }
 165	dol_syslog("--- End access to ".$_SERVER["PHP_SELF"].(($disconnectdone && $depth)?' (Warn: db disconnection forced, transaction depth was '.$depth.')':''), (($disconnectdone && $depth)?LOG_WARNING:LOG_DEBUG));
 166}
 167
 168
 169/**
 170 *  Return value of a param into GET or POST supervariable
 171 *
 172 *  @param	string	$paramname   Name of parameter to found
 173 *  @param	string	$check	     Type of check (''=no check,  'int'=check it's numeric, 'alpha'=check it's alpha only, 'array'=check it's array)
 174 *  @param	int		$method	     Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
 175 *  @return string      		 Value found or '' if check fails
 176 */
 177function GETPOST($paramname,$check='',$method=0)
 178{
 179	if (empty($method)) $out = isset($_GET[$paramname])?$_GET[$paramname]:(isset($_POST[$paramname])?$_POST[$paramname]:'');
 180	elseif ($method==1) $out = isset($_GET[$paramname])?$_GET[$paramname]:'';
 181	elseif ($method==2) $out = isset($_POST[$paramname])?$_POST[$paramname]:'';
 182	elseif ($method==3) $out = isset($_POST[$paramname])?$_POST[$paramname]:(isset($_GET[$paramname])?$_GET[$paramname]:'');
 183	else return 'BadParameter';
 184
 185	if (! empty($check))
 186	{
 187		// Check if numeric
 188		if ($check == 'int' && ! preg_match('/^[-\.,0-9]+$/i',$out))
 189		{
 190			$out=trim($out);
 191			$out='';
 192		}
 193		// Check if alpha
 194		elseif ($check == 'alpha')
 195		{
 196			$out=trim($out);
 197			// '"' is dangerous because param in url can close the href= or src= and add javascript functions.
 198			// '../' is dangerous because it allows dir transversals
 199			if (preg_match('/"/',$out)) $out='';
 200			else if (preg_match('/\.\.\//',$out)) $out='';
 201		}
 202		elseif ($check == 'array')
 203		{
 204			if (! is_array($out) || empty($out)) $out=array();
 205		}
 206	}
 207
 208	return $out;
 209}
 210
 211
 212/**
 213 *  Return a prefix to use for this Dolibarr instance for session or cookie names.
 214 *  This prefix is unique for instance and avoid conflict between multi-instances,
 215 *  even when having two instances with one root dir or two instances in virtual servers
 216 *
 217 *  @return	string      		A calculated prefix
 218 */
 219function dol_getprefix()
 220{
 221	return dol_hash($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
 222}
 223
 224/**
 225 *	Make an include_once using default root and alternate root if it fails.
 226 *	WARNING: In most cases, you should not use this function:
 227 *  To link to a core file, use include(DOL_DOCUMENT_ROOT.'/pathtofile')
 228 *  To link to a module file from a module file, use include './mymodulefile';
 229 *  To link to a module file from a core file, then this function can be used
 230 *
 231 * 	@param	string	$relpath	Relative path to file (Ie: mydir/myfile, ../myfile, ...)
 232 * 	@param	string	$classname	Class name
 233 *  @return int					false if include fails.
 234 */
 235function dol_include_once($relpath, $classname='')
 236{
 237	global $conf,$langs,$user,$mysoc;   // Other global var must be retreived with $GLOBALS['var']
 238
 239	if (! empty($classname) && ! class_exists($classname)) {
 240		return @include dol_buildpath($relpath);			// Remove @ to find error into php log file if you have problems
 241	} else {
 242		return @include_once dol_buildpath($relpath);		// Remove @ to find error into php log file if you have problems
 243	}
 244}
 245
 246
 247/**
 248 *	Return path of url or filesystem. Return default_root or alternate root if file_exist fails
 249 *
 250 * 	@param	string	$path		Relative path to file (if mode=0, ie: mydir/myfile, ../myfile, ...) or relative url (if mode=1).
 251 *  @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)
 252 *  @return string				Full filsystem path (if mode=0), Full url path (if mode=1)
 253 */
 254function dol_buildpath($path, $type=0)
 255{
 256	if (empty($type))	// For a filesystem path
 257	{
 258		$res = DOL_DOCUMENT_ROOT.$path;	// Standard value
 259		if (defined('DOL_DOCUMENT_ROOT_ALT') && DOL_DOCUMENT_ROOT_ALT)	// We check only if alternate feature is used
 260		{
 261			if (! file_exists(DOL_DOCUMENT_ROOT.$path)) $res = DOL_DOCUMENT_ROOT_ALT.$path;
 262		}
 263	}
 264	else				// For an url path
 265	{
 266		// We try to get local path of file on filesystem from url
 267		// Note that trying to know if a file on disk exist by forging path on disk from url
 268		// works only for some web server and some setup. This is bugged when
 269		// using proxy, rewriting, virtual path, etc...
 270		if ($type == 1)
 271		{
 272			$res = DOL_URL_ROOT.$path;		// Standard value
 273			if (defined('DOL_URL_ROOT_ALT') && DOL_URL_ROOT_ALT)			// We check only if alternate feature is used
 274			{
 275				preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i',$path,$regs);    // Take part before '?'
 276				if (! empty($regs[1]))
 277				{
 278					if (! file_exists(DOL_DOCUMENT_ROOT.$regs[1])) $res = DOL_URL_ROOT_ALT.$path;
 279				}
 280			}
 281		}
 282		else if ($type == 2)
 283		{
 284			$res = DOL_MAIN_URL_ROOT.$path;      // Standard value
 285			if (defined('DOL_URL_ROOT_ALT') && DOL_URL_ROOT_ALT)            // We check only if alternate feature is used
 286			{
 287				preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i',$path,$regs);    // Take part before '?'
 288				if (! empty($regs[1]))
 289				{
 290					if (! file_exists(DOL_DOCUMENT_ROOT.$regs[1])) $res = DOL_MAIN_URL_ROOT_ALT.$path;
 291				}
 292			}
 293		}
 294	}
 295
 296	return $res;
 297}
 298
 299/**
 300 *	Create a clone of instance of object (new instance with same properties)
 301 * 	This function works for both PHP4 and PHP5
 302 *
 303 * 	@param	object	$object		Object to clone
 304 *	@return object				Object clone
 305 */
 306function dol_clone($object)
 307{
 308	dol_syslog("Functions.lib::dol_clone Clone object");
 309
 310	// We create dynamically a clone function, making a =
 311	if (version_compare(phpversion(), '5.0') < 0 && ! function_exists('clone'))
 312	{
 313		eval('function clone($object){return($object);}');
 314	}
 315	$myclone=clone($object);
 316	return $myclone;
 317}
 318
 319/**
 320 *	Optimize a size for some browsers (phone, smarphone, ...)
 321 *
 322 * 	@param	int		$size		Size we want
 323 * 	@param	string	$type		Type of optimizing:
 324 * 								'' = function used to define a size for truncation
 325 * 								'width' = function is used to define a width
 326 *	@return int					New size after optimizing
 327 */
 328function dol_size($size,$type='')
 329{
 330	global $conf;
 331	if (empty($conf->dol_optimize_smallscreen)) return $size;
 332	if ($type == 'width' && $size > 250) return 250;
 333	else return 10;
 334}
 335
 336
 337/**
 338 *	Clean a string to use it as a file name
 339 *
 340 *	@param	string	$str            String to clean
 341 * 	@param	string	$newstr			String to replace bad chars with
 342 *  @param	string	$unaccent		1=Remove also accent (default), 0 do not remove them
 343 *	@return string          		String cleaned (a-zA-Z_)
 344 *
 345 * 	@see        	dol_string_nospecial, dol_string_unaccent
 346 */
 347function dol_sanitizeFileName($str,$newstr='_',$unaccent=1)
 348{
 349	$filesystem_forbidden_chars = array('<','>',':','/','\\','?','*','|','"');
 350	return dol_string_nospecial($unaccent?dol_string_unaccent($str):$str, $newstr, $filesystem_forbidden_chars);
 351}
 352
 353/**
 354 *	Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName
 355 *
 356 *	@param	string	$str			String to clean
 357 *	@return string   	       		Cleaned string
 358 *
 359 * 	@see    		dol_sanitizeFilename, dol_string_nospecial
 360 */
 361function dol_string_unaccent($str)
 362{
 363	if (utf8_check($str))
 364	{
 365		$string = rawurlencode($str);
 366		$replacements = array(
 367		'%C3%80' => 'A','%C3%81' => 'A',
 368		'%C3%88' => 'E','%C3%89' => 'E',
 369		'%C3%8C' => 'I','%C3%8D' => 'I',
 370		'%C3%92' => 'O','%C3%93' => 'O',
 371		'%C3%99' => 'U','%C3%9A' => 'U',
 372		'%C3%A0' => 'a','%C3%A1' => 'a','%C3%A2' => 'a',
 373		'%C3%A8' => 'e','%C3%A9' => 'e','%C3%AA' => 'e','%C3%AB' => 'e',
 374		'%C3%AC' => 'i','%C3%AD' => 'i','%C3%AE' => 'i',
 375		'%C3%B2' => 'o','%C3%B3' => 'o',
 376		'%C3%B9' => 'u','%C3%BA' => 'u'
 377		);
 378		$string=strtr($string, $replacements);
 379		return rawurldecode($string);
 380	}
 381	else
 382	{
 383		$string = strtr(
 384			$str,
 385			"\xC0\xC1\xC2\xC3\xC5\xC7
 386			\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
 387			\xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
 388			\xE0\xE1\xE2\xE3\xE5\xE7\xE8\xE9\xEA\xEB
 389			\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
 390			\xF9\xFA\xFB\xFD\xFF",
 391			"AAAAAC
 392			EEEEIIIIDN
 393			OOOOOUUUY
 394			aaaaaceeee
 395			iiiidnooooo
 396			uuuyy"
 397		);
 398		$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"));
 399		return $string;
 400	}
 401}
 402
 403/**
 404 *	Clean a string from all punctuation characters to use it as a ref or login
 405 *
 406 *	@param	string	$str            String to clean
 407 * 	@param	string	$newstr			String to replace forbidden chars with
 408 *  @param  array	$badchars       List of forbidden characters
 409 * 	@return string          		Cleaned string
 410 *
 411 * 	@see    		dol_sanitizeFilename, dol_string_unaccent
 412 */
 413function dol_string_nospecial($str,$newstr='_',$badchars='')
 414{
 415	$forbidden_chars_to_replace=array(" ","'","/","\\",":","*","?","\"","<",">","|","[","]",",",";","=");
 416	$forbidden_chars_to_remove=array();
 417	if (is_array($badchars)) $forbidden_chars_to_replace=$badchars;
 418	//$forbidden_chars_to_remove=array("(",")");
 419
 420	return str_replace($forbidden_chars_to_replace,$newstr,str_replace($forbidden_chars_to_remove,"",$str));
 421}
 422
 423/**
 424 *  Returns text escaped for inclusion into javascript code
 425 *
 426 *  @param       string		$stringtoescape		String to escape
 427 *  @return      string     		 			Escaped string
 428 */
 429function dol_escape_js($stringtoescape)
 430{
 431	// escape quotes and backslashes, newlines, etc.
 432	$substitjs=array("&#039;"=>"\\'",'\\'=>'\\\\',"'"=>"\\'",'"'=>"\\'","\r"=>'\\r',"\n"=>'\\n','</'=>'<\/');
 433	return strtr($stringtoescape, $substitjs);
 434}
 435
 436
 437/**
 438 *  Returns text escaped for inclusion in HTML alt or title tags
 439 *
 440 *  @param      string		$stringtoescape		String to escape
 441 *  @param		int			$keepb				Do not clean b tags
 442 *  @return     string     				 		Escaped string
 443 */
 444function dol_escape_htmltag($stringtoescape,$keepb=0)
 445{
 446	// escape quotes and backslashes, newlines, etc.
 447	$tmp=dol_html_entity_decode($stringtoescape,ENT_COMPAT,'UTF-8');
 448	if ($keepb) $tmp=strtr($tmp, array("\r"=>'\\r',"\n"=>'\\n'));
 449	else $tmp=strtr($tmp, array("\r"=>'\\r',"\n"=>'\\n',"<b>"=>'','</b>'=>''));
 450	return dol_htmlentities($tmp,ENT_COMPAT,'UTF-8');
 451}
 452
 453
 454/**
 455 * Convert a string to lower. Never use strtolower because it does not works with UTF8 strings.
 456 *
 457 * @param 	string		$utf8_string		String to encode
 458 * @return 	string							String converted
 459 */
 460function dol_strtolower($utf8_string)
 461{
 462	return mb_strtolower($utf8_string, "UTF-8");
 463}
 464
 465/**
 466 * Convert a string to upper. Never use strtolower because it does not works with UTF8 strings.
 467 *
 468 * @param 	string		$utf8_string		String to encode
 469 * @return 	string							String converted
 470 */
 471function dol_strtoupper($utf8_string)
 472{
 473	return mb_strtoupper($utf8_string, "UTF-8");
 474}
 475
 476
 477/**
 478 *	Write log message into outputs. Possible outputs can be:
 479 *	SYSLOG_HANDLERS = ["mod_syslog_file"]  		file name is then defined by SYSLOG_FILE
 480 *	SYSLOG_HANDLERS = ["mod_syslog_syslog"]  	facility is then defined by SYSLOG_FACILITY
 481 *  Warning, syslog functions are bugged on Windows, generating memory protection faults. To solve
 482 *  this, use logging to files instead of syslog (see setup of module).
 483 *  Note: If SYSLOG_FILE_NO_ERROR defined, we never output any error message when writing to log fails.
 484 *  Note: You can get log message into html sources by adding parameter &logtohtml=1 (constant MAIN_LOGTOHTML must be set)
 485 *  This function works only if syslog module is enabled.
 486 * 	This must not use any call to other function calling dol_syslog (avoid infinite loop).
 487 *
 488 * 	@param  string		$message			Line to log. Ne doit pas etre traduit si level = LOG_ERR
 489 *  @param  int			$level				Log level
 490 *                                  		0=Show nothing
 491 *											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
 492 *											On Linux   LOG_ERR=3, LOG_WARNING=4, LOG_INFO=6, LOG_DEBUG=7
 493 *  @param	int			$ident				1=Increase ident of 1, -1=Decrease ident of 1
 494 *  @param	string		$suffixinfilename	When output is a file, append this suffix into default log filename.
 495 *  @return	void
 496 */
 497function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename='')
 498{
 499	global $conf, $user;
 500
 501	// If syslog module enabled
 502	if (empty($conf->syslog->enabled)) return false;
 503
 504	if (! empty($level))
 505	{
 506		// Test log level
 507		$logLevels = array(	LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG);
 508		if (!in_array($level, $logLevels))
 509		{
 510			throw new Exception('Incorrect log level');
 511		}
 512		if ($level > $conf->global->SYSLOG_LEVEL) return false;
 513
 514		// If adding log inside HTML page is required
 515		if (! empty($_REQUEST['logtohtml']) && ! empty($conf->global->MAIN_LOGTOHTML))
 516		{
 517			$conf->logbuffer[] = dol_print_date(time(),"%Y-%m-%d %H:%M:%S")." ".$message;
 518		}
 519
 520		// If enable html log tag enabled and url parameter log defined, we show output log on HTML comments
 521		if (! empty($conf->global->MAIN_ENABLE_LOG_HTML) && ! empty($_GET["log"]))
 522		{
 523			print "\n\n<!-- Log start\n";
 524			print $message."\n";
 525			print "Log end -->\n";
 526		}
 527
 528		$data = array(
 529			'message' => $message,
 530			'script' => (isset($_SERVER['PHP_SELF'])? basename($_SERVER['PHP_SELF'],'.php') : false),
 531			'level' => $level,
 532			'user' => ((is_object($user) && $user->id) ? $user->login : false),
 533			'ip' => false
 534		);
 535
 536		if (! empty($_SERVER["REMOTE_ADDR"])) $data['ip'] = $_SERVER['REMOTE_ADDR'];
 537		// This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
 538		else if (! empty($_SERVER['SERVER_ADDR'])) $data['ip'] = $_SERVER['SERVER_ADDR'];
 539		// 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).
 540		else if (! empty($_SERVER['COMPUTERNAME'])) $data['ip'] = $_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME'])?'':'@'.$_SERVER['USERNAME']);
 541		// 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).
 542		else if (! empty($_SERVER['LOGNAME'])) $data['ip'] = '???@'.$_SERVER['LOGNAME'];
 543
 544		// Loop on each log handler and send output
 545		foreach ($conf->loghandlers as $loghandlerinstance)
 546		{
 547			$loghandlerinstance->export($data,$suffixinfilename);
 548		}
 549		unset($data);
 550	}
 551
 552	if (! empty($ident))
 553	{
 554		foreach ($conf->loghandlers as $loghandlerinstance)
 555		{
 556			$loghandlerinstance->setIdent($ident);
 557		}
 558	}
 559}
 560
 561
 562/**
 563 *	Show tab header of a card
 564 *
 565 *	@param	array	$links				Array of tabs
 566 *	@param	string	$active     		Active tab name (document', 'info', 'ldap', ....)
 567 *	@param  string	$title      		Title
 568 *	@param  int		$notab				0=Add tab header, 1=no tab header
 569 * 	@param	string	$picto				Add a picto on tab title
 570 *	@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.
 571 * 	@return	void
 572 */
 573function dol_fiche_head($links=array(), $active='0', $title='', $notab=0, $picto='', $pictoisfullpath=0)
 574{
 575	print dol_get_fiche_head($links, $active, $title, $notab, $picto, $pictoisfullpath);
 576}
 577
 578/**
 579 *  Show tab header of a card
 580 *
 581 *	@param	array	$links				Array of tabs
 582 *	@param	int		$active     		Active tab name
 583 *	@param  string	$title      		Title
 584 *	@param  int		$notab				0=Add tab header, 1=no tab header
 585 * 	@param	string	$picto				Add a picto on tab title
 586 *	@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.
 587 * 	@return	void
 588 */
 589function dol_get_fiche_head($links=array(), $active='0', $title='', $notab=0, $picto='', $pictoisfullpath=0)
 590{
 591	global $conf;
 592
 593	$out="\n".'<div class="tabs">'."\n";
 594
 595	// Show title
 596	$showtitle=1;
 597	if (! empty($conf->dol_optimize_smallscreen)) $showtitle=0;
 598	if (! empty($title) && $showtitle)
 599	{
 600		$limittitle=30;
 601		$out.='<a class="tabTitle">';
 602		if ($picto) $out.=img_picto('',($pictoisfullpath?'':'object_').$picto,'',$pictoisfullpath).' ';
 603		$out.=dol_trunc($title,$limittitle);
 604		$out.='</a>';
 605	}
 606
 607	// Define max of key (max may be higher than sizeof because of hole due to module disabling some tabs).
 608	$maxkey=-1;
 609	if (is_array($links) && ! empty($links))
 610	{
 611		$keys=array_keys($links);
 612		if (count($keys)) $maxkey=max($keys);
 613	}
 614
 615	// Show tabs
 616	for ($i = 0 ; $i <= $maxkey ; $i++)
 617	{
 618		if (isset($links[$i][2]) && $links[$i][2] == 'image')
 619		{
 620			if (!empty($links[$i][0]))
 621			{
 622				$out.='<a class="tabimage" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
 623			}
 624			else
 625			{
 626				$out.='<span class="tabspan">'.$links[$i][1].'</span>'."\n";
 627			}
 628		}
 629		else if (! empty($links[$i][1]))
 630		{
 631			//print "x $i $active ".$links[$i][2]." z";
 632			if ((is_numeric($active) && $i == $active)
 633			|| (! is_numeric($active) && $active == $links[$i][2]))
 634			{
 635				$out.='<a id="active" class="tab" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
 636			}
 637			else
 638			{
 639				$out.='<a'.(! empty($links[$i][2])?' id="'.$links[$i][2].'"':'').' class="tab" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
 640			}
 641		}
 642	}
 643
 644	$out.="</div>\n";
 645
 646	if (! $notab) $out.="\n".'<div class="tabBar">'."\n";
 647
 648	return $out;
 649}
 650
 651/**
 652 *  Show tab footer of a card
 653 *
 654 *  @param	int		$notab       0=Add tab footer, 1=no tab footer
 655 *  @return	void
 656 */
 657function dol_fiche_end($notab=0)
 658{
 659	print dol_get_fiche_end($notab);
 660}
 661
 662/**
 663 *	Return tab footer of a card
 664 *
 665 *	@param  int		$notab		0=Add tab footer, 1=no tab footer
 666 *  @return	void
 667 */
 668function dol_get_fiche_end($notab=0)
 669{
 670	if (! $notab) return "\n</div>\n";
 671	else return '';
 672}
 673
 674/**
 675 * Return string to add class property on html element with pair/impair.
 676 *
 677 * @param	string	$var			0 or 1
 678 * @param	string	$moreclass		More class to add
 679 * @return	string					String to add class onto HTML element
 680 */
 681function dol_bc($var,$moreclass='')
 682{
 683	global $bc;
 684	$ret=' '.$bc[$var];
 685	if ($moreclass) $ret=preg_replace('/class=\"/','class="'.$moreclass.' ',$ret);
 686	return $ret;
 687}
 688
 689/**
 690 *      Return a formated address (part address/zip/town/state) according to country rules
 691 *
 692 *      @param  Object		$object         A company or contact object
 693 * 	    @param	int			$withcountry	1=Add country into address string
 694 *      @param	string		$sep			Separator to use to build string
 695 *      @return string          			Formated string
 696 */
 697function dol_format_address($object,$withcountry=0,$sep="\n")
 698{
 699	$ret='';
 700	$countriesusingstate=array('AU','US','IN','GB','ES');
 701
 702	// Address
 703	$ret .= $object->address;
 704	// Zip/Town/State
 705	if (in_array($object->country_code,array('US','AU')))   	// US: title firstname name \n address lines \n town, state, zip \n country
 706	{
 707		$ret .= ($ret ? $sep : '' ).$object->town;
 708		if ($object->state && in_array($object->country_code,$countriesusingstate))
 709		{
 710			$ret.=", ".$object->state;
 711		}
 712		if ($object->zip) $ret .= ', '.$object->zip;
 713	}
 714	else if (in_array($object->country_code,array('GB'))) // UK: title firstname name \n address lines \n town state \n zip \n country
 715	{
 716		$ret .= ($ret ? $sep : '' ).$object->town;
 717		if ($object->state && in_array($object->country_code,$countriesusingstate))
 718		{
 719			$ret.=", ".$object->state;
 720		}
 721		if ($object->zip) $ret .= ($ret ? $sep : '' ).$object->zip;
 722	}
 723	else if (in_array($object->country_code,array('ES'))) // ES: title firstname name \n address lines \n zip town \n state \n country
 724	{
 725		$ret .= ($ret ? $sep : '' ).$object->zip;
 726		$ret .= ' '.$object->town;
 727		if ($object->state && in_array($object->country_code,$countriesusingstate))
 728		{
 729			$ret.="\n".$object->state;
 730		}
 731	}
 732
 733	else                                        		// Other: title firstname name \n address lines \n zip town \n country
 734	{
 735		$ret .= ($ret ? $sep : '' ).$object->zip;
 736		$ret .= ' '.$object->town;
 737		if ($object->state && in_array($object->country_code,$countriesusingstate))
 738		{
 739			$ret.=", ".$object->state;
 740		}
 741	}
 742
 743	if ($withcountry) $ret.=($object->country?$sep.$object->country:'');
 744
 745	return $ret;
 746}
 747
 748
 749
 750/**
 751 *	Format a string.
 752 *
 753 *	@param	string	$fmt		Format of strftime function (http://php.net/manual/fr/function.strftime.php)
 754 *  @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)
 755 *  @param	int		$is_gmt		See comment of timestamp parameter
 756 *	@return	string				A formatted string
 757 */
 758function dol_strftime($fmt, $ts=false, $is_gmt=false)
 759{
 760	if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
 761		return ($is_gmt)? @gmstrftime($fmt,$ts): @strftime($fmt,$ts);
 762	}
 763	else return 'Error date into a not supported range';
 764}
 765
 766/**
 767 *	Output date in a string format according to outputlangs (or langs if not defined).
 768 * 	Return charset is always UTF-8, except if encodetoouput is defined. In this case charset is output charset
 769 *
 770 *	@param	timestamp	$time        	GM Timestamps date
 771 *	@param	string		$format      	Output date format
 772 *										"%d %b %Y",
 773 *										"%d/%m/%Y %H:%M",
 774 *										"%d/%m/%Y %H:%M:%S",
 775 *										"day", "daytext", "dayhour", "dayhourldap", "dayhourtext", "dayrfc", "dayhourrfc"
 776 * 	@param	string		$tzoutput		true or 'gmt' => string is for Greenwich location
 777 * 										false or 'tzserver' => output string is for local PHP server TZ usage
 778 * 										'tzuser' => output string is for local browser TZ usage
 779 *	@param	Tranlsate	$outputlangs	Object lang that contains language for text translation.
 780 *  @param  boolean		$encodetooutput false=no convert into output pagecode
 781 * 	@return string      				Formated date or '' if time is null
 782 *
 783 *  @see        dol_mktime, dol_stringtotime, dol_getdate
 784 */
 785function dol_print_date($time,$format='',$tzoutput='tzserver',$outputlangs='',$encodetooutput=false)
 786{
 787	global $conf,$langs;
 788
 789	// Clean parameters
 790	$to_gmt=false;
 791	$offsettz=$offsetdst=0;
 792	if ($tzoutput)
 793	{
 794		$to_gmt=true;	// For backward compatibility
 795		if (is_string($tzoutput))
 796		{
 797			if ($tzoutput == 'tzserver')
 798			{
 799				$to_gmt=false;
 800				$offsettz=$offsetdst=0;
 801			}
 802			elseif ($tzoutput == 'tzuser')
 803			{
 804				$to_gmt=true;
 805				$offsettz=(empty($_SESSION['dol_tz'])?0:$_SESSION['dol_tz'])*60*60;
 806				$offsetdst=(empty($_SESSION['dol_dst'])?0:$_SESSION['dol_dst'])*60*60;
 807			}
 808			elseif ($tzoutput == 'tzcompany')
 809			{
 810				$to_gmt=false;
 811				$offsettz=$offsetdst=0;	// TODO Define this and use it later
 812			}
 813		}
 814	}
 815	if (! is_object($outputlangs)) $outputlangs=$langs;
 816	if (! $format) $format='daytextshort';
 817	$reduceformat=(! empty($conf->dol_optimize_smallscreen) && in_array($format,array('day','hour')))?1:0;
 818	
 819	// Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
 820	if ($format == 'day')				$format=($outputlangs->trans("FormatDateShort")!="FormatDateShort"?$outputlangs->trans("FormatDateShort"):$conf->format_date_short);
 821	else if ($format == 'hour')			$format=($outputlangs->trans("FormatHourShort")!="FormatHourShort"?$outputlangs->trans("FormatHourShort"):$conf->format_hour_short);
 822	else if ($format == 'hourduration')	$format=($outputlangs->trans("FormatHourShortDuration")!="FormatHourShortDuration"?$outputlangs->trans("FormatHourShortDuration"):$conf->format_hour_short_duration);
 823	else if ($format == 'daytext')			 $format=($outputlangs->trans("FormatDateText")!="FormatDateText"?$outputlangs->trans("FormatDateText"):$conf->format_date_text);
 824	else if ($format == 'daytextshort')	$format=($outputlangs->trans("FormatDateTextShort")!="FormatDateTextShort"?$outputlangs->trans("FormatDateTextShort"):$conf->format_date_text_short);
 825	else if ($format == 'dayhour')			 $format=($outputlangs->trans("FormatDateHourShort")!="FormatDateHourShort"?$outputlangs->trans("FormatDateHourShort"):$conf->format_date_hour_short);
 826	else if ($format == 'dayhoursec')		 $format=($outputlangs->trans("FormatDateHourSecShort")!="FormatDateHourSecShort"?$outputlangs->trans("FormatDateHourSecShort"):$conf->format_date_hour_sec_short);
 827	else if ($format == 'dayhourtext')		 $format=($outputlangs->trans("FormatDateHourText")!="FormatDateHourText"?$outputlangs->trans("FormatDateHourText"):$conf->format_date_hour_text);
 828	else if ($format == 'dayhourtextshort') $format=($outputlangs->trans("FormatDateHourTextShort")!="FormatDateHourTextShort"?$outputlangs->trans("FormatDateHourTextShort"):$conf->format_date_hour_text_short);
 829	// Format not sensitive to language
 830	else if ($format == 'dayhourlog')		 $format='%Y%m%d%H%M%S';
 831	else if ($format == 'dayhourldap')		 $format='%Y%m%d%H%M%SZ';
 832	else if ($format == 'dayhourxcard')	$format='%Y%m%dT%H%M%SZ';
 833	else if ($format == 'dayxcard')	 	$format='%Y%m%d';
 834	else if ($format == 'dayrfc')			 $format='%Y-%m-%d';             // DATE_RFC3339
 835	else if ($format == 'dayhourrfc')		 $format='%Y-%m-%dT%H:%M:%SZ';   // DATETIME RFC3339
 836	else if ($format == 'standard')		$format='%Y-%m-%d %H:%M:%S';
 837
 838	if ($reduceformat)
 839	{
 840		$format=str_replace('%Y','%y',$format);
 841		$format=str_replace('yyyy','yy',$format);
 842	}
 843	
 844	// If date undefined or "", we return ""
 845	if (dol_strlen($time) == 0) return '';		// $time=0 allowed (it means 01/01/1970 00:00:00)
 846
 847	// Clean format
 848	if (preg_match('/%b/i',$format))		// There is some text to translate
 849	{
 850		// We inhibate translation to text made by strftime functions. We will use trans instead later.
 851		$format=str_replace('%b','__b__',$format);
 852		$format=str_replace('%B','__B__',$format);
 853	}
 854	if (preg_match('/%a/i',$format))		// There is some text to translate
 855	{
 856		// We inhibate translation to text made by strftime functions. We will use trans instead later.
 857		$format=str_replace('%a','__a__',$format);
 858		$format=str_replace('%A','__A__',$format);
 859	}
 860
 861	// Analyze date (deprecated)   Ex: 1970-01-01, 1970-01-01 01:00:00, 19700101010000
 862	if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+) ?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i',$time,$reg)
 863	|| 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))
 864	{
 865		// This part of code should not be used.
 866		dol_syslog("Functions.lib::dol_print_date function call with deprecated value of time in page ".$_SERVER["PHP_SELF"], LOG_WARNING);
 867		// Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS' or 'YYYYMMDDHHMMSS'
 868		$syear	= (! empty($reg[1]) ? $reg[1] : '');
 869		$smonth	= (! empty($reg[2]) ? $reg[2] : '');
 870		$sday	= (! empty($reg[3]) ? $reg[3] : '');
 871		$shour	= (! empty($reg[4]) ? $reg[4] : '');
 872		$smin	= (! empty($reg[5]) ? $reg[5] : '');
 873		$ssec	= (! empty($reg[6]) ? $reg[6] : '');
 874
 875		$time=dol_mktime($shour,$smin,$ssec,$smonth,$sday,$syear,true);
 876		$ret=adodb_strftime($format,$time+$offsettz+$offsetdst,$to_gmt);
 877	}
 878	else
 879	{
 880		// Date is a timestamps
 881		if ($time < 100000000000)	// Protection against bad date values
 882		{
 883			$ret=adodb_strftime($format,$time+$offsettz+$offsetdst,$to_gmt);
 884		}
 885		else $ret='Bad value '.$time.' for date';
 886	}
 887
 888	if (preg_match('/__b__/i',$format))
 889	{
 890		// Here ret is string in PHP setup language (strftime was used). Now we convert to $outputlangs.
 891		$month=adodb_strftime('%m',$time+$offsettz+$offsetdst);
 892		if ($encodetooutput)
 893		{
 894			$monthtext=$outputlangs->transnoentities('Month'.$month);
 895			$monthtextshort=$outputlangs->transnoentities('MonthShort'.$month);
 896		}
 897		else
 898		{
 899			$monthtext=$outputlangs->transnoentitiesnoconv('Month'.$month);
 900			$monthtextshort=$outputlangs->transnoentitiesnoconv('MonthShort'.$month);
 901		}
 902		//print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
 903		$ret=str_replace('__b__',$monthtextshort,$ret);
 904		$ret=str_replace('__B__',$monthtext,$ret);
 905		//print 'x'.$outputlangs->charset_output.'-'.$ret.'x';
 906		//return $ret;
 907	}
 908	if (preg_match('/__a__/i',$format))
 909	{
 910		$w=adodb_strftime('%w',$time+$offsettz+$offsetdst);
 911		$dayweek=$outputlangs->transnoentitiesnoconv('Day'.$w);
 912		$ret=str_replace('__A__',$dayweek,$ret);
 913		$ret=str_replace('__a__',dol_substr($dayweek,0,3),$ret);
 914	}
 915
 916	return $ret;
 917}
 918
 919
 920/**
 921 *	Return an array with locale date info.
 922 *  PHP getdate is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
 923 *  WARNING: This function always use PHP server timezone to return locale informations.
 924 *  Usage must be avoid.
 925 *
 926 *	@param	timestamp	$timestamp      Timestamp
 927 *	@param	boolean		$fast           Fast mode
 928 *	@return	array						Array of informations
 929 *										If no fast mode:
 930 *										'seconds' => $secs,
 931 *										'minutes' => $min,
 932 *										'hours' => $hour,
 933 *										'mday' => $day,
 934 *										'wday' => $dow,
 935 *										'mon' => $month,
 936 *										'year' => $year,
 937 *										'yday' => floor($secsInYear/$_day_power),
 938 *										'weekday' => gmdate('l',$_day_power*(3+$dow)),
 939 *										'month' => gmdate('F',mktime(0,0,0,$month,2,1971)),
 940 *										If fast mode:
 941 *										'seconds' => $secs,
 942 *										'minutes' => $min,
 943 *										'hours' => $hour,
 944 *										'mday' => $day,
 945 *										'mon' => $month,
 946 *										'year' => $year,
 947 *										'yday' => floor($secsInYear/$_day_power),
 948 *										'leap' => $leaf,
 949 *										'ndays' => $ndays
 950 * 	@see 								dol_print_date, dol_stringtotime, dol_mktime
 951 */
 952function dol_getdate($timestamp,$fast=false)
 953{
 954	$usealternatemethod=false;
 955	if ($timestamp <= 0) $usealternatemethod=true;				// <= 1970
 956	if ($timestamp >= 2145913200) $usealternatemethod=true;		// >= 2038
 957
 958	if ($usealternatemethod)
 959	{
 960		$arrayinfo=adodb_getdate($timestamp,$fast);
 961	}
 962	else
 963	{
 964		$arrayinfo=getdate($timestamp);
 965	}
 966
 967	return $arrayinfo;
 968}
 969
 970/**
 971 *	Return a timestamp date built from detailed informations (by default a local PHP server timestamp)
 972 * 	Replace function mktime not available under Windows if year < 1970
 973 *	PHP mktime is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
 974 *
 975 * 	@param	int			$hour			Hour	(can be -1 for undefined)
 976 *	@param	int			$minute			Minute	(can be -1 for undefined)
 977 *	@param	int			$second			Second	(can be -1 for undefined)
 978 *	@param	int			$month			Month (1 to 12)
 979 *	@param	int			$day			Day (1 to 31)
 980 *	@param	int			$year			Year
 981 *	@param	int			$gm				1=Input informations are GMT values, otherwise local to server TZ
 982 *	@param	int			$check			0=No check on parameters (Can use day 32, etc...)
 983 *	@return	timestamp					Date as a timestamp, '' if error
 984 * 	@see 								dol_print_date, dol_stringtotime, dol_getdate
 985 */
 986function dol_mktime($hour,$minute,$second,$month,$day,$year,$gm=false,$check=1)
 987{
 988	global $conf;
 989	//print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
 990
 991	// Clean parameters
 992	if ($hour   == -1 || empty($hour)) $hour=0;
 993	if ($minute == -1 || empty($minute)) $minute=0;
 994	if ($second == -1 || empty($second)) $second=0;
 995
 996	// Check parameters
 997	if ($check)
 998	{
 999		if (! $month || ! $day)  return '';
1000		if ($day   > 31) return '';
1001		if ($month > 12) return '';
1002		if ($hour  < 0 || $hour   > 24) return '';
1003		if ($minute< 0 || $minute > 60) return '';
1004		if ($second< 0 || $second > 60) return '';
1005	}
1006
1007	if (method_exists('DateTime','getTimestamp') && empty($conf->global->MAIN_OLD_DATE))
1008	{
1009		if (empty($gm)) $localtz = new DateTimeZone(date_default_timezone_get());
1010		else $localtz = new DateTimeZone('UTC');
1011		$dt = new DateTime(null,$localtz);
1012		$dt->setDate($year,$month,$day);
1013		$dt->setTime((int) $hour, (int) $minute, (int) $second);
1014		$date=$dt->getTimestamp();
1015	}
1016	else
1017	{
1018		$usealternatemethod=false;
1019		if ($year <= 1970) $usealternatemethod=true;		// <= 1970
1020		if ($year >= 2038) $usealternatemethod=true;		// >= 2038
1021
1022		if ($usealternatemethod || $gm)	// Si time gm, seule adodb peut convertir
1023		{
1024			$date=adodb_mktime($hour,$minute,$second,$month,$day,$year,0,$gm);
1025		}
1026		else
1027		{
1028			$date=mktime($hour,$minute,$second,$month,$day,$year);
1029		}
1030	}
1031	return $date;
1032}
1033
1034
1035/**
1036 *	Return date for now. We should always use this function without parameters (that means GMT time)
1037 *
1038 * 	@param	string		$mode	'gmt' => we return GMT timestamp,
1039 * 								'tzserver' => we add the PHP server timezone
1040 *  							'tzref' => we add the company timezone
1041 * 								'tzuser' => we add the user timezone
1042 *	@return timestamp   $date	Timestamp
1043 */
1044function dol_now($mode='gmt')
1045{
1046	// Note that gmmktime and mktime return same value (GMT) whithout parameters
1047	//if ($mode == 'gmt') $ret=gmmktime(); // Strict Standards: gmmktime(): You should be using the time() function instead
1048	if ($mode == 'gmt') $ret=time();	// Time for now at greenwich.
1049	else if ($mode == 'tzserver')		// Time for now with PHP server timezone added
1050	{
1051		require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
1052		$tzsecond=getServerTimeZoneInt('now');    // Contains tz+dayling saving time
1053		$ret=dol_now('gmt')+($tzsecond*3600);
1054	}
1055	/*else if ($mode == 'tzref')				// Time for now with parent company timezone is added
1056	{
1057		require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
1058		$tzsecond=getParentCompanyTimeZoneInt();    // Contains tz+dayling saving time
1059		$ret=dol_now('gmt')+($tzsecond*3600);
1060	}*/
1061	else if ($mode == 'tzuser')				// Time for now with user timezone is added
1062	{
1063		//print 'eeee'.time().'-'.mktime().'-'.gmmktime();
1064		$offsettz=(empty($_SESSION['dol_tz'])?0:$_SESSION['dol_tz'])*60*60;
1065		$offsetdst=(empty($_SESSION['dol_dst'])?0:$_SESSION['dol_dst'])*60*60;
1066		$ret=dol_now('gmt')+($offsettz+$offsetdst);
1067	}
1068	return $ret;
1069}
1070
1071
1072/**
1073 * Return string with formated size
1074 *
1075 * @param	int		$size		Size to print
1076 * @param	int		$shortvalue	Tell if we want long value to use another unit (Ex: 1.5Kb instead of 1500b)
1077 * @param	int		$shortunit	Use short value of size unit
1078 * @return	string				Link
1079 */
1080function dol_print_size($size,$shortvalue=0,$shortunit=0)
1081{
1082	global $conf,$langs;
1083	$level=1024;
1084	
1085	if (! empty($conf->dol_optimize_smallscreen)) $shortunit=1;
1086	
1087	// Set value text
1088	if (empty($shortvalue) || $size < ($level*10))
1089	{
1090		$ret=$size;
1091		$textunitshort=$langs->trans("b");
1092		$textunitlong=$langs->trans("Bytes");
1093	}
1094	else
1095	{
1096		$ret=round($size/$level,0);
1097		$textunitshort=$langs->trans("Kb");
1098		$textunitlong=$langs->trans("KiloBytes");
1099	}
1100	// Use long or short text unit
1101	if (empty($shortunit)) { $ret.=' '.$textunitlong; }
1102	else { $ret.=' '.$textunitshort; }
1103
1104	return $ret;
1105}
1106
1107/**
1108 * Show Url link
1109 *
1110 * @param	string		$url		Url to show
1111 * @param	string		$target		Target for link
1112 * @param	int			$max		Max number of characters to show
1113 * @return	string					HTML Link
1114 */
1115function dol_print_url($url,$target='_blank',$max=32)
1116{
1117	if (empty($url)) return '';
1118
1119	$link='<a href="';
1120	if (! preg_match('/^http/i',$url)) $link.='http://';
1121	$link.=$url;
1122	if ($target) $link.='" target="'.$target.'">';
1123	if (! preg_match('/^http/i',$url)) $link.='http://';
1124	$link.=dol_trunc($url,$max);
1125	$link.='</a>';
1126	return $link;
1127}
1128
1129/**
1130 * Show EMail link
1131 *
1132 * @param	string		$email			EMail to show (only email, without 'Name of recipient' before)
1133 * @param 	int			$cid 			Id of contact if known
1134 * @param 	int			$socid 			Id of third party if known
1135 * @param 	int			$addlink		0=no link to create action
1136 * @param	int			$max			Max number of characters to show
1137 * @param	int			$showinvalid	Show warning if syntax email is wrong
1138 * @return	string						HTML Link
1139 */
1140function dol_print_email($email,$cid=0,$socid=0,$addlink=0,$max=64,$showinvalid=1)
1141{
1142	global $conf,$user,$langs;
1143
1144	$newemail=$email;
1145
1146	if (empty($email)) return '&nbsp;';
1147
1148	if (! empty($addlink))
1149	{
1150		$newemail='<a href="';
1151		if (! preg_match('/^mailto:/i',$email)) $newemail.='mailto:';
1152		$newemail.=$email;
1153		$newemail.='">';
1154		$newemail.=dol_trunc($email,$max);
1155		$newemail.='</a>';
1156		if ($showinvalid && ! isValidEmail($email))
1157		{
1158			$langs->load("errors");
1159			$newemail.=img_warning($langs->trans("ErrorBadEMail",$email));
1160		}
1161
1162		if (($cid || $socid) && ! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
1163		{
1164			$type='AC_EMAIL'; $link='';
1165			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>';
1166			$newemail='<table class="nobordernopadding"><tr><td>'.$newemail.' </td><td>&nbsp;'.$link.'</td></tr></table>';
1167		}
1168	}
1169	else
1170	{
1171		if ($showinvalid && ! isValidEmail($email))
1172		{
1173			$langs->load("errors");
1174			$newemail.=img_warning($langs->trans("ErrorBadEMail",$email));
1175		}
1176	}
1177	return $newemail;
1178}
1179
1180/**
1181 * 	Format phone numbers according to country
1182 *
1183 * 	@param	string	$phone 		Phone number to format
1184 * 	@param 	string	$country 	Country code to use for formatting
1185 * 	@param 	int		$cid 		Id of contact if known
1186 * 	@param 	int		$socid 		Id of third party if known
1187 * 	@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)
1188 * 	@param 	string	$separ 		Separation between numbers for a better visibility example : xx.xx.xx.xx.xx
1189 * 	@return string 				Formated phone number
1190 */
1191function dol_print_phone($phone,$country='',$cid=0,$socid=0,$addlink='',$separ="&nbsp;")
1192{
1193	global $conf,$user,$langs,$mysoc;
1194
1195	// Clean phone parameter
1196	$phone = preg_replace("/[\s.-]/","",trim($phone));
1197	if (empty($phone)) { return ''; }
1198	if (empty($country)) $country=$mysoc->country_code;
1199
1200	// Short format for small screens
1201	if ($conf->dol_optimize_smallscreen) $separ='';
1202
1203	$newphone=$phone;
1204	if (strtoupper($country) == "FR")
1205	{
1206		// France
1207		if (dol_strlen($phone) == 10) {
1208			$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);
1209		}
1210		elseif (dol_strlen($newphone) == 7)
1211		{
1212			$newphone=substr($newphone,0,3).$separ.substr($newphone,3,2).$separ.substr($newphone,5,2);
1213		}
1214		elseif (dol_strlen($newphone) == 9)
1215		{
1216			$newphone=substr($newphone,0,2).$separ.substr($newphone,2,3).$separ.substr($newphone,5,2).$separ.substr($newphone,7,2);
1217		}
1218		elseif (dol_strlen($newphone) == 11)
1219		{
1220			$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);
1221		}
1222		elseif (dol_strlen($newphone) == 12)
1223		{
1224			$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);
1225		}
1226	}
1227
1228	if (! empty($addlink))	// Link on phone number + link to add action (if conf->global->AGENDA_ADDACTIONFORPHONE set)
1229	{
1230		if (! empty($conf->browser))	// If phone, we use link of phone
1231		{
1232			$newphone ='<a href="tel:'.$phone.'"';
1233			$newphone.='>'.$phone.'</a>';
1234		}
1235		else if (! empty($conf->clicktodial->enabled) && $addlink == 'AC_TEL')		// If click to dial, we use click to dial url
1236		{
1237			if (empty($user->clicktodial_loaded)) $user->fetch_clicktodial();
1238
1239			// Define urlmask
1240			$urlmask='ErrorClickToDialModuleNotConfigured';
1241			if (! empty($conf->global->CLICKTODIAL_URL)) $urlmask=$conf->global->CLICKTODIAL_URL;
1242			if (! empty($user->clicktodial_url)) $urlmask=$user->clicktodial_url;
1243
1244			$clicktodial_poste=(! empty($user->clicktodial_poste)?urlencode($user->clicktodial_poste):'');
1245			$clicktodial_login=(! empty($user->clicktodial_login)?urlencode($user->clicktodial_login):'');
1246			$clicktodial_password=(! empty($user->clicktodial_password)?urlencode($user->clicktodial_password):'');
1247			// This line is for backward compatibility
1248			$url = sprintf($urlmask, urlencode($phone), $clicktodial_poste, $clicktodial_login, $clicktodial_password);
1249			// Thoose lines are for substitution
1250			$substitarray=array('__PHONEFROM__'=>$clicktodial_poste,
1251								'__PHONETO__'=>urlencode($phone),
1252								'__LOGIN__'=>$clicktodial_login,
1253								'__PASS__'=>$clicktodial_password);
1254			$url = make_substitutions($url, $substitarray);
1255			$newphonesav=$newphone;
1256			$newphone ='<a href="'.$url.'"';
1257			if (! empty($conf->global->CLICKTODIAL_FORCENEWTARGET)) $newphone.=' target="_blank"';
1258			$newphone.='>'.$newphonesav.'</a>';
1259		}
1260
1261		//if (($cid || $socid) && ! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
1262		if (! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
1263		{
1264			$type='AC_TEL'; $link='';
1265			if ($addlink == 'AC_FAX') $type='AC_FAX';
1266			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>';
1267			if ($link) $newphone='<table class="nobordernopadding"><tr><td>'.$newphone.' </td><td>&nbsp;'.$link.'</td></tr></table>';
1268		}
1269	}
1270
1271	return $newphone;
1272}
1273
1274/**
1275 * 	Return an IP formated to be shown on screen
1276 *
1277 * 	@param	string	$ip			IP
1278 * 	@param	int		$mode		0=return IP + country/flag, 1=return only country/flag, 2=return only IP
1279 * 	@return string 				Formated IP, with country if GeoIP module is enabled
1280 */
1281function dol_print_ip($ip,$mode=0)
1282{
1283	global $conf,$langs;
1284
1285	$ret='';
1286
1287	if (empty($mode)) $ret.=$ip;
1288
1289	if (! empty($conf->geoipmaxmind->enabled) && $mode != 2)
1290	{
1291		$datafile=$conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
1292		//$ip='24.24.24.24';
1293		//$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)
1294
1295		include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
1296		$geoip=new DolGeoIP('country',$datafile);
1297		//print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
1298		//print "geoip_country_id_by_addr=".geoip_country_id_by_addr($geoip->gi,$ip)."\n";
1299		$countrycode=$geoip->getCountryCodeFromIP($ip);
1300		if ($countrycode)	// If success, countrycode is us, fr, ...
1301		{
1302			if (file_exists(DOL_DOCUMENT_ROOT.'/theme/common/flags/'.$countrycode.'.png'))
1303			{
1304				$ret.=' '.img_picto($countrycode.' '.$langs->trans("AccordingToGeoIPDatabase"),DOL_URL_ROOT.'/theme/common/flags/'.$countrycode.'.png','',1);
1305			}
1306			else $ret.=' ('.$countrycode.')';
1307		}
1308	}
1309
1310	return $ret;
1311}
1312
1313/**
1314 *  Return country code for current user.
1315 *  If software is used inside a local network, detection may fails (we need a public ip)
1316 *
1317 *  @return     string      Country code (fr, es, it, us, ...)
1318 */
1319function dol_user_country()
1320{
1321	global $conf,$langs,$user;
1322
1323	//$ret=$user->xxx;
1324	$ret='';
1325	if (! empty($conf->geoipmaxmind->enabled))
1326	{
1327		$ip=$_SERVER["REMOTE_ADDR"];
1328		$datafile=$conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
1329		//$ip='24.24.24.24';
1330		//$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';
1331		include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
1332		$geoip=new DolGeoIP('country',$datafile);
1333		$countrycode=$geoip->getCountryCodeFromIP($ip);
1334		$ret=$countrycode;
1335	}
1336	return $ret;
1337}
1338
1339/**
1340 *  Format address string
1341 *
1342 *  @param	string	$address     Address
1343 *  @param  int		$htmlid      Html ID (for example 'gmap')
1344 *  @param  int		$mode        thirdparty|contact|member|other
1345 *  @param  int		$id          Id of object
1346 *  @return void
1347 */
1348function dol_print_address($address, $htmlid, $mode, $id)
1349{
1350	global $conf,$user,$langs;
1351
1352	if ($address)
1353	{
1354		print nl2br($address);
1355		$showgmap=$showomap=0;
1356		if ($mode=='thirdparty' && ! empty($conf->google->enabled) && ! empty($conf->global->GOOGLE_ENABLE_GMAPS)) $showgmap=1;
1357		if ($mode=='contact' && ! empty($conf->google->enabled) && ! empty($conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS)) $showgmap=1;
1358		if ($mode=='member' && ! empty($conf->google->enabled) && ! empty($conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS)) $showgmap=1;
1359		if 

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