/htdocs/core/lib/functions.lib.php
PHP | 4404 lines | 2848 code | 388 blank | 1168 comment | 669 complexity | f73a6d613c2c1e88da8b11d652cceeae MD5 | raw file
Possible License(s): GPL-3.0
Large files files are truncated, but you can click here to view the full file
- <?php
- /* Copyright (C) 2000-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
- * Copyright (C) 2003 Jean-Louis Bergamo <jlb@j1b.org>
- * Copyright (C) 2004-2013 Laurent Destailleur <eldy@users.sourceforge.net>
- * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
- * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
- * Copyright (C) 2004 Christophe Combelles <ccomb@free.fr>
- * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@capnetworks.com>
- * Copyright (C) 2008 Raphael Bertrand (Resultic) <raphael.bertrand@resultic.fr>
- * Copyright (C) 2010-2011 Juanjo Menent <jmenent@2byte.es>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * or see http://www.gnu.org/
- */
- /**
- * \file htdocs/core/lib/functions.lib.php
- * \brief A set of functions for Dolibarr
- * This file contains all frequently used functions.
- */
- if (! function_exists('json_encode'))
- {
- include_once DOL_DOCUMENT_ROOT .'/core/lib/json.lib.php';
- }
- /**
- * Function to return value of a static property when class
- * name is dynamically defined (not hard coded).
- * This is because $myclass::$myvar works from PHP 5.3.0+ only
- *
- * @param string $class Class name
- * @param string $member Name of property
- * @return string Return value of static property.
- */
- function getStaticMember($class, $member)
- {
- if (is_object($class)) $class = get_class($class);
- $classObj = new ReflectionClass($class);
- $result = null;
- $found=0;
- foreach($classObj->getStaticProperties() as $prop => $value)
- {
- if ($prop == $member)
- {
- $result = $value;
- $found++;
- break;
- }
- }
- if (! $found) dol_print_error('','Try to get a static member "'.$member.'" in class "'.$class.'" that does not exists or is not static.');
- return $result;
- }
- /**
- * Return a DoliDB instance (database handler).
- *
- * @param string $type Type of database (mysql, pgsql...)
- * @param string $host Address of database server
- * @param string $user Nom de l'utilisateur autorise
- * @param string $pass Mot de passe
- * @param string $name Nom de la database
- * @param int $port Port of database server
- * @return DoliDB A DoliDB instance
- */
- function getDoliDBInstance($type, $host, $user, $pass, $name, $port)
- {
- require_once DOL_DOCUMENT_ROOT ."/core/db/".$type.'.class.php';
- $class='DoliDB'.ucfirst($type);
- $dolidb=new $class($type, $host, $user, $pass, $name, $port);
- return $dolidb;
- }
- /**
- * Get entity to use
- *
- * @param string $element Current element
- * @param int $shared 1=Return shared entities
- * @return mixed Entity id(s) to use
- */
- function getEntity($element=false, $shared=false)
- {
- global $conf, $mc;
- if (is_object($mc))
- {
- return $mc->getEntity($element, $shared);
- }
- else
- {
- $out='';
- $addzero = array('user', 'usergroup');
- if (in_array($element, $addzero)) $out.= '0,';
- $out.= $conf->entity;
- return $out;
- }
- }
- /**
- * Return information about user browser
- *
- * @return array Array of information ('browsername'=>,'browseros'=>,'phone'=>,'browserfirefox'=>)
- */
- function getBrowserInfo()
- {
- $name='unknown'; $version=''; $os='unknown'; $phone='';
- // If phone/smartphone, we set phone os name.
- if (preg_match('/android/i',$_SERVER["HTTP_USER_AGENT"])) { $os=$phone='android'; }
- elseif (preg_match('/blackberry/i',$_SERVER["HTTP_USER_AGENT"])) { $os=$phone='blackberry'; }
- elseif (preg_match('/iphone/i',$_SERVER["HTTP_USER_AGENT"])) { $os='ios'; $phone='iphone'; }
- elseif (preg_match('/ipod/i',$_SERVER["HTTP_USER_AGENT"])) { $os='ios'; $phone='iphone'; }
- elseif (preg_match('/palm/i',$_SERVER["HTTP_USER_AGENT"])) { $os=$phone='palm'; }
- elseif (preg_match('/symbian/i',$_SERVER["HTTP_USER_AGENT"])) { $os='symbian'; $phone='unknown'; }
- elseif (preg_match('/webos/i',$_SERVER["HTTP_USER_AGENT"])) { $os='webos'; $phone='unknown'; }
- elseif (preg_match('/maemo/i',$_SERVER["HTTP_USER_AGENT"])) { $os='maemo'; $phone='unknown'; }
- // MS products at end
- elseif (preg_match('/iemobile/i',$_SERVER["HTTP_USER_AGENT"])) { $os='windows'; $phone='unkown'; }
- elseif (preg_match('/windows ce/i',$_SERVER["HTTP_USER_AGENT"])) { $os='windows'; $phone='unkown'; }
- // Name
- if (preg_match('/firefox(\/|\s)([\d\.]*)/i', $_SERVER["HTTP_USER_AGENT"], $reg)) { $name='firefox'; $version=$reg[2]; }
- 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
- elseif (preg_match('/chrome/i', $_SERVER["HTTP_USER_AGENT"], $reg)) { $name='chrome'; }
- elseif (preg_match('/iceweasel/i',$_SERVER["HTTP_USER_AGENT"])) { $name='iceweasel'; $version=$reg[2]; }
- elseif (preg_match('/epiphany/i',$_SERVER["HTTP_USER_AGENT"])) { $name='epiphany'; $version=$reg[2]; }
- 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.
- elseif (preg_match('/opera(\/|\s)([\d\.]*)/i', $_SERVER["HTTP_USER_AGENT"], $reg)) { $name='opera'; $version=$reg[2]; }
- elseif (preg_match('/msie(\/|\s)([\d\.]*)/i', $_SERVER["HTTP_USER_AGENT"], $reg)) { $name='ie'; $version=$reg[2]; } // MS products at end
- // Other
- $firefox=0;
- if (in_array($name,array('firefox','iceweasel'))) $firefox=1;
- return array('browsername'=>$name, 'browserversion'=>$version, 'browseros'=>$os, 'phone'=>$phone, 'browserfirefox'=>$firefox);
- }
- /**
- * Function called at end of web php process
- *
- * @return void
- */
- function dol_shutdown()
- {
- global $conf,$user,$langs,$db;
- $disconnectdone=false; $depth=0;
- if (is_object($db) && ! empty($db->connected)) { $depth=$db->transaction_opened; $disconnectdone=$db->close(); }
- dol_syslog("--- End access to ".$_SERVER["PHP_SELF"].(($disconnectdone && $depth)?' (Warn: db disconnection forced, transaction depth was '.$depth.')':''), (($disconnectdone && $depth)?LOG_WARNING:LOG_DEBUG));
- }
- /**
- * Return value of a param into GET or POST supervariable
- *
- * @param string $paramname Name of parameter to found
- * @param string $check Type of check (''=no check, 'int'=check it's numeric, 'alpha'=check it's alpha only, 'array'=check it's array)
- * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
- * @return string Value found or '' if check fails
- */
- function GETPOST($paramname,$check='',$method=0)
- {
- if (empty($method)) $out = isset($_GET[$paramname])?$_GET[$paramname]:(isset($_POST[$paramname])?$_POST[$paramname]:'');
- elseif ($method==1) $out = isset($_GET[$paramname])?$_GET[$paramname]:'';
- elseif ($method==2) $out = isset($_POST[$paramname])?$_POST[$paramname]:'';
- elseif ($method==3) $out = isset($_POST[$paramname])?$_POST[$paramname]:(isset($_GET[$paramname])?$_GET[$paramname]:'');
- else return 'BadParameter';
- if (! empty($check))
- {
- // Check if numeric
- if ($check == 'int' && ! preg_match('/^[-\.,0-9]+$/i',$out))
- {
- $out=trim($out);
- $out='';
- }
- // Check if alpha
- elseif ($check == 'alpha')
- {
- $out=trim($out);
- // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
- // '../' is dangerous because it allows dir transversals
- if (preg_match('/"/',$out)) $out='';
- else if (preg_match('/\.\.\//',$out)) $out='';
- }
- elseif ($check == 'array')
- {
- if (! is_array($out) || empty($out)) $out=array();
- }
- }
- return $out;
- }
- /**
- * Return a prefix to use for this Dolibarr instance for session or cookie names.
- * This prefix is unique for instance and avoid conflict between multi-instances,
- * even when having two instances with one root dir or two instances in virtual servers
- *
- * @return string A calculated prefix
- */
- function dol_getprefix()
- {
- return dol_hash($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
- }
- /**
- * Make an include_once using default root and alternate root if it fails.
- * WARNING: In most cases, you should not use this function:
- * To link to a core file, use include(DOL_DOCUMENT_ROOT.'/pathtofile')
- * To link to a module file from a module file, use include './mymodulefile';
- * To link to a module file from a core file, then this function can be used
- *
- * @param string $relpath Relative path to file (Ie: mydir/myfile, ../myfile, ...)
- * @param string $classname Class name
- * @return int false if include fails.
- */
- function dol_include_once($relpath, $classname='')
- {
- global $conf,$langs,$user,$mysoc; // Other global var must be retreived with $GLOBALS['var']
- if (! empty($classname) && ! class_exists($classname)) {
- return @include dol_buildpath($relpath); // Remove @ to find error into php log file if you have problems
- } else {
- return @include_once dol_buildpath($relpath); // Remove @ to find error into php log file if you have problems
- }
- }
- /**
- * Return path of url or filesystem. Return default_root or alternate root if file_exist fails
- *
- * @param string $path Relative path to file (if mode=0, ie: mydir/myfile, ../myfile, ...) or relative url (if mode=1).
- * @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)
- * @return string Full filsystem path (if mode=0), Full url path (if mode=1)
- */
- function dol_buildpath($path, $type=0)
- {
- if (empty($type)) // For a filesystem path
- {
- $res = DOL_DOCUMENT_ROOT.$path; // Standard value
- if (defined('DOL_DOCUMENT_ROOT_ALT') && DOL_DOCUMENT_ROOT_ALT) // We check only if alternate feature is used
- {
- if (! file_exists(DOL_DOCUMENT_ROOT.$path)) $res = DOL_DOCUMENT_ROOT_ALT.$path;
- }
- }
- else // For an url path
- {
- // We try to get local path of file on filesystem from url
- // Note that trying to know if a file on disk exist by forging path on disk from url
- // works only for some web server and some setup. This is bugged when
- // using proxy, rewriting, virtual path, etc...
- if ($type == 1)
- {
- $res = DOL_URL_ROOT.$path; // Standard value
- if (defined('DOL_URL_ROOT_ALT') && DOL_URL_ROOT_ALT) // We check only if alternate feature is used
- {
- preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i',$path,$regs); // Take part before '?'
- if (! empty($regs[1]))
- {
- if (! file_exists(DOL_DOCUMENT_ROOT.$regs[1])) $res = DOL_URL_ROOT_ALT.$path;
- }
- }
- }
- else if ($type == 2)
- {
- $res = DOL_MAIN_URL_ROOT.$path; // Standard value
- if (defined('DOL_URL_ROOT_ALT') && DOL_URL_ROOT_ALT) // We check only if alternate feature is used
- {
- preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i',$path,$regs); // Take part before '?'
- if (! empty($regs[1]))
- {
- if (! file_exists(DOL_DOCUMENT_ROOT.$regs[1])) $res = DOL_MAIN_URL_ROOT_ALT.$path;
- }
- }
- }
- }
- return $res;
- }
- /**
- * Create a clone of instance of object (new instance with same properties)
- * This function works for both PHP4 and PHP5
- *
- * @param object $object Object to clone
- * @return object Object clone
- */
- function dol_clone($object)
- {
- dol_syslog("Functions.lib::dol_clone Clone object");
- // We create dynamically a clone function, making a =
- if (version_compare(phpversion(), '5.0') < 0 && ! function_exists('clone'))
- {
- eval('function clone($object){return($object);}');
- }
- $myclone=clone($object);
- return $myclone;
- }
- /**
- * Optimize a size for some browsers (phone, smarphone, ...)
- *
- * @param int $size Size we want
- * @param string $type Type of optimizing:
- * '' = function used to define a size for truncation
- * 'width' = function is used to define a width
- * @return int New size after optimizing
- */
- function dol_size($size,$type='')
- {
- global $conf;
- if (empty($conf->dol_optimize_smallscreen)) return $size;
- if ($type == 'width' && $size > 250) return 250;
- else return 10;
- }
- /**
- * Clean a string to use it as a file name
- *
- * @param string $str String to clean
- * @param string $newstr String to replace bad chars with
- * @param string $unaccent 1=Remove also accent (default), 0 do not remove them
- * @return string String cleaned (a-zA-Z_)
- *
- * @see dol_string_nospecial, dol_string_unaccent
- */
- function dol_sanitizeFileName($str,$newstr='_',$unaccent=1)
- {
- $filesystem_forbidden_chars = array('<','>',':','/','\\','?','*','|','"');
- return dol_string_nospecial($unaccent?dol_string_unaccent($str):$str, $newstr, $filesystem_forbidden_chars);
- }
- /**
- * Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName
- *
- * @param string $str String to clean
- * @return string Cleaned string
- *
- * @see dol_sanitizeFilename, dol_string_nospecial
- */
- function dol_string_unaccent($str)
- {
- if (utf8_check($str))
- {
- $string = rawurlencode($str);
- $replacements = array(
- '%C3%80' => 'A','%C3%81' => 'A',
- '%C3%88' => 'E','%C3%89' => 'E',
- '%C3%8C' => 'I','%C3%8D' => 'I',
- '%C3%92' => 'O','%C3%93' => 'O',
- '%C3%99' => 'U','%C3%9A' => 'U',
- '%C3%A0' => 'a','%C3%A1' => 'a','%C3%A2' => 'a',
- '%C3%A8' => 'e','%C3%A9' => 'e','%C3%AA' => 'e','%C3%AB' => 'e',
- '%C3%AC' => 'i','%C3%AD' => 'i','%C3%AE' => 'i',
- '%C3%B2' => 'o','%C3%B3' => 'o',
- '%C3%B9' => 'u','%C3%BA' => 'u'
- );
- $string=strtr($string, $replacements);
- return rawurldecode($string);
- }
- else
- {
- $string = strtr(
- $str,
- "\xC0\xC1\xC2\xC3\xC5\xC7
- \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
- \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
- \xE0\xE1\xE2\xE3\xE5\xE7\xE8\xE9\xEA\xEB
- \xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
- \xF9\xFA\xFB\xFD\xFF",
- "AAAAAC
- EEEEIIIIDN
- OOOOOUUUY
- aaaaaceeee
- iiiidnooooo
- uuuyy"
- );
- $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"));
- return $string;
- }
- }
- /**
- * Clean a string from all punctuation characters to use it as a ref or login
- *
- * @param string $str String to clean
- * @param string $newstr String to replace forbidden chars with
- * @param array $badchars List of forbidden characters
- * @return string Cleaned string
- *
- * @see dol_sanitizeFilename, dol_string_unaccent
- */
- function dol_string_nospecial($str,$newstr='_',$badchars='')
- {
- $forbidden_chars_to_replace=array(" ","'","/","\\",":","*","?","\"","<",">","|","[","]",",",";","=");
- $forbidden_chars_to_remove=array();
- if (is_array($badchars)) $forbidden_chars_to_replace=$badchars;
- //$forbidden_chars_to_remove=array("(",")");
- return str_replace($forbidden_chars_to_replace,$newstr,str_replace($forbidden_chars_to_remove,"",$str));
- }
- /**
- * Returns text escaped for inclusion into javascript code
- *
- * @param string $stringtoescape String to escape
- * @return string Escaped string
- */
- function dol_escape_js($stringtoescape)
- {
- // escape quotes and backslashes, newlines, etc.
- $substitjs=array("'"=>"\\'",'\\'=>'\\\\',"'"=>"\\'",'"'=>"\\'","\r"=>'\\r',"\n"=>'\\n','</'=>'<\/');
- return strtr($stringtoescape, $substitjs);
- }
- /**
- * Returns text escaped for inclusion in HTML alt or title tags
- *
- * @param string $stringtoescape String to escape
- * @param int $keepb Do not clean b tags
- * @return string Escaped string
- */
- function dol_escape_htmltag($stringtoescape,$keepb=0)
- {
- // escape quotes and backslashes, newlines, etc.
- $tmp=dol_html_entity_decode($stringtoescape,ENT_COMPAT,'UTF-8');
- if ($keepb) $tmp=strtr($tmp, array("\r"=>'\\r',"\n"=>'\\n'));
- else $tmp=strtr($tmp, array("\r"=>'\\r',"\n"=>'\\n',"<b>"=>'','</b>'=>''));
- return dol_htmlentities($tmp,ENT_COMPAT,'UTF-8');
- }
- /**
- * Convert a string to lower. Never use strtolower because it does not works with UTF8 strings.
- *
- * @param string $utf8_string String to encode
- * @return string String converted
- */
- function dol_strtolower($utf8_string)
- {
- return mb_strtolower($utf8_string, "UTF-8");
- }
- /**
- * Convert a string to upper. Never use strtolower because it does not works with UTF8 strings.
- *
- * @param string $utf8_string String to encode
- * @return string String converted
- */
- function dol_strtoupper($utf8_string)
- {
- return mb_strtoupper($utf8_string, "UTF-8");
- }
- /**
- * Write log message into outputs. Possible outputs can be:
- * SYSLOG_HANDLERS = ["mod_syslog_file"] file name is then defined by SYSLOG_FILE
- * SYSLOG_HANDLERS = ["mod_syslog_syslog"] facility is then defined by SYSLOG_FACILITY
- * Warning, syslog functions are bugged on Windows, generating memory protection faults. To solve
- * this, use logging to files instead of syslog (see setup of module).
- * Note: If SYSLOG_FILE_NO_ERROR defined, we never output any error message when writing to log fails.
- * Note: You can get log message into html sources by adding parameter &logtohtml=1 (constant MAIN_LOGTOHTML must be set)
- * This function works only if syslog module is enabled.
- * This must not use any call to other function calling dol_syslog (avoid infinite loop).
- *
- * @param string $message Line to log. Ne doit pas etre traduit si level = LOG_ERR
- * @param int $level Log level
- * 0=Show nothing
- * 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
- * On Linux LOG_ERR=3, LOG_WARNING=4, LOG_INFO=6, LOG_DEBUG=7
- * @param int $ident 1=Increase ident of 1, -1=Decrease ident of 1
- * @param string $suffixinfilename When output is a file, append this suffix into default log filename.
- * @return void
- */
- function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename='')
- {
- global $conf, $user;
- // If syslog module enabled
- if (empty($conf->syslog->enabled)) return false;
- if (! empty($level))
- {
- // Test log level
- $logLevels = array( LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG);
- if (!in_array($level, $logLevels))
- {
- throw new Exception('Incorrect log level');
- }
- if ($level > $conf->global->SYSLOG_LEVEL) return false;
- // If adding log inside HTML page is required
- if (! empty($_REQUEST['logtohtml']) && ! empty($conf->global->MAIN_LOGTOHTML))
- {
- $conf->logbuffer[] = dol_print_date(time(),"%Y-%m-%d %H:%M:%S")." ".$message;
- }
- // If enable html log tag enabled and url parameter log defined, we show output log on HTML comments
- if (! empty($conf->global->MAIN_ENABLE_LOG_HTML) && ! empty($_GET["log"]))
- {
- print "\n\n<!-- Log start\n";
- print $message."\n";
- print "Log end -->\n";
- }
- $data = array(
- 'message' => $message,
- 'script' => (isset($_SERVER['PHP_SELF'])? basename($_SERVER['PHP_SELF'],'.php') : false),
- 'level' => $level,
- 'user' => ((is_object($user) && $user->id) ? $user->login : false),
- 'ip' => false
- );
- if (! empty($_SERVER["REMOTE_ADDR"])) $data['ip'] = $_SERVER['REMOTE_ADDR'];
- // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
- else if (! empty($_SERVER['SERVER_ADDR'])) $data['ip'] = $_SERVER['SERVER_ADDR'];
- // 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).
- else if (! empty($_SERVER['COMPUTERNAME'])) $data['ip'] = $_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME'])?'':'@'.$_SERVER['USERNAME']);
- // 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).
- else if (! empty($_SERVER['LOGNAME'])) $data['ip'] = '???@'.$_SERVER['LOGNAME'];
- // Loop on each log handler and send output
- foreach ($conf->loghandlers as $loghandlerinstance)
- {
- $loghandlerinstance->export($data,$suffixinfilename);
- }
- unset($data);
- }
- if (! empty($ident))
- {
- foreach ($conf->loghandlers as $loghandlerinstance)
- {
- $loghandlerinstance->setIdent($ident);
- }
- }
- }
- /**
- * Show tab header of a card
- *
- * @param array $links Array of tabs
- * @param string $active Active tab name (document', 'info', 'ldap', ....)
- * @param string $title Title
- * @param int $notab 0=Add tab header, 1=no tab header
- * @param string $picto Add a picto on tab title
- * @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.
- * @return void
- */
- function dol_fiche_head($links=array(), $active='0', $title='', $notab=0, $picto='', $pictoisfullpath=0)
- {
- print dol_get_fiche_head($links, $active, $title, $notab, $picto, $pictoisfullpath);
- }
- /**
- * Show tab header of a card
- *
- * @param array $links Array of tabs
- * @param int $active Active tab name
- * @param string $title Title
- * @param int $notab 0=Add tab header, 1=no tab header
- * @param string $picto Add a picto on tab title
- * @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.
- * @return void
- */
- function dol_get_fiche_head($links=array(), $active='0', $title='', $notab=0, $picto='', $pictoisfullpath=0)
- {
- global $conf;
- $out="\n".'<div class="tabs">'."\n";
- // Show title
- $showtitle=1;
- if (! empty($conf->dol_optimize_smallscreen)) $showtitle=0;
- if (! empty($title) && $showtitle)
- {
- $limittitle=30;
- $out.='<a class="tabTitle">';
- if ($picto) $out.=img_picto('',($pictoisfullpath?'':'object_').$picto,'',$pictoisfullpath).' ';
- $out.=dol_trunc($title,$limittitle);
- $out.='</a>';
- }
- // Define max of key (max may be higher than sizeof because of hole due to module disabling some tabs).
- $maxkey=-1;
- if (is_array($links) && ! empty($links))
- {
- $keys=array_keys($links);
- if (count($keys)) $maxkey=max($keys);
- }
- // Show tabs
- for ($i = 0 ; $i <= $maxkey ; $i++)
- {
- if (isset($links[$i][2]) && $links[$i][2] == 'image')
- {
- if (!empty($links[$i][0]))
- {
- $out.='<a class="tabimage" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
- }
- else
- {
- $out.='<span class="tabspan">'.$links[$i][1].'</span>'."\n";
- }
- }
- else if (! empty($links[$i][1]))
- {
- //print "x $i $active ".$links[$i][2]." z";
- if ((is_numeric($active) && $i == $active)
- || (! is_numeric($active) && $active == $links[$i][2]))
- {
- $out.='<a id="active" class="tab" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
- }
- else
- {
- $out.='<a'.(! empty($links[$i][2])?' id="'.$links[$i][2].'"':'').' class="tab" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
- }
- }
- }
- $out.="</div>\n";
- if (! $notab) $out.="\n".'<div class="tabBar">'."\n";
- return $out;
- }
- /**
- * Show tab footer of a card
- *
- * @param int $notab 0=Add tab footer, 1=no tab footer
- * @return void
- */
- function dol_fiche_end($notab=0)
- {
- print dol_get_fiche_end($notab);
- }
- /**
- * Return tab footer of a card
- *
- * @param int $notab 0=Add tab footer, 1=no tab footer
- * @return void
- */
- function dol_get_fiche_end($notab=0)
- {
- if (! $notab) return "\n</div>\n";
- else return '';
- }
- /**
- * Return string to add class property on html element with pair/impair.
- *
- * @param string $var 0 or 1
- * @param string $moreclass More class to add
- * @return string String to add class onto HTML element
- */
- function dol_bc($var,$moreclass='')
- {
- global $bc;
- $ret=' '.$bc[$var];
- if ($moreclass) $ret=preg_replace('/class=\"/','class="'.$moreclass.' ',$ret);
- return $ret;
- }
- /**
- * Return a formated address (part address/zip/town/state) according to country rules
- *
- * @param Object $object A company or contact object
- * @param int $withcountry 1=Add country into address string
- * @param string $sep Separator to use to build string
- * @return string Formated string
- */
- function dol_format_address($object,$withcountry=0,$sep="\n")
- {
- $ret='';
- $countriesusingstate=array('AU','US','IN','GB','ES');
- // Address
- $ret .= $object->address;
- // Zip/Town/State
- if (in_array($object->country_code,array('US','AU'))) // US: title firstname name \n address lines \n town, state, zip \n country
- {
- $ret .= ($ret ? $sep : '' ).$object->town;
- if ($object->state && in_array($object->country_code,$countriesusingstate))
- {
- $ret.=", ".$object->state;
- }
- if ($object->zip) $ret .= ', '.$object->zip;
- }
- else if (in_array($object->country_code,array('GB'))) // UK: title firstname name \n address lines \n town state \n zip \n country
- {
- $ret .= ($ret ? $sep : '' ).$object->town;
- if ($object->state && in_array($object->country_code,$countriesusingstate))
- {
- $ret.=", ".$object->state;
- }
- if ($object->zip) $ret .= ($ret ? $sep : '' ).$object->zip;
- }
- else if (in_array($object->country_code,array('ES'))) // ES: title firstname name \n address lines \n zip town \n state \n country
- {
- $ret .= ($ret ? $sep : '' ).$object->zip;
- $ret .= ' '.$object->town;
- if ($object->state && in_array($object->country_code,$countriesusingstate))
- {
- $ret.="\n".$object->state;
- }
- }
- else // Other: title firstname name \n address lines \n zip town \n country
- {
- $ret .= ($ret ? $sep : '' ).$object->zip;
- $ret .= ' '.$object->town;
- if ($object->state && in_array($object->country_code,$countriesusingstate))
- {
- $ret.=", ".$object->state;
- }
- }
- if ($withcountry) $ret.=($object->country?$sep.$object->country:'');
- return $ret;
- }
- /**
- * Format a string.
- *
- * @param string $fmt Format of strftime function (http://php.net/manual/fr/function.strftime.php)
- * @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)
- * @param int $is_gmt See comment of timestamp parameter
- * @return string A formatted string
- */
- function dol_strftime($fmt, $ts=false, $is_gmt=false)
- {
- if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
- return ($is_gmt)? @gmstrftime($fmt,$ts): @strftime($fmt,$ts);
- }
- else return 'Error date into a not supported range';
- }
- /**
- * Output date in a string format according to outputlangs (or langs if not defined).
- * Return charset is always UTF-8, except if encodetoouput is defined. In this case charset is output charset
- *
- * @param timestamp $time GM Timestamps date
- * @param string $format Output date format
- * "%d %b %Y",
- * "%d/%m/%Y %H:%M",
- * "%d/%m/%Y %H:%M:%S",
- * "day", "daytext", "dayhour", "dayhourldap", "dayhourtext", "dayrfc", "dayhourrfc"
- * @param string $tzoutput true or 'gmt' => string is for Greenwich location
- * false or 'tzserver' => output string is for local PHP server TZ usage
- * 'tzuser' => output string is for local browser TZ usage
- * @param Tranlsate $outputlangs Object lang that contains language for text translation.
- * @param boolean $encodetooutput false=no convert into output pagecode
- * @return string Formated date or '' if time is null
- *
- * @see dol_mktime, dol_stringtotime, dol_getdate
- */
- function dol_print_date($time,$format='',$tzoutput='tzserver',$outputlangs='',$encodetooutput=false)
- {
- global $conf,$langs;
- // Clean parameters
- $to_gmt=false;
- $offsettz=$offsetdst=0;
- if ($tzoutput)
- {
- $to_gmt=true; // For backward compatibility
- if (is_string($tzoutput))
- {
- if ($tzoutput == 'tzserver')
- {
- $to_gmt=false;
- $offsettz=$offsetdst=0;
- }
- elseif ($tzoutput == 'tzuser')
- {
- $to_gmt=true;
- $offsettz=(empty($_SESSION['dol_tz'])?0:$_SESSION['dol_tz'])*60*60;
- $offsetdst=(empty($_SESSION['dol_dst'])?0:$_SESSION['dol_dst'])*60*60;
- }
- elseif ($tzoutput == 'tzcompany')
- {
- $to_gmt=false;
- $offsettz=$offsetdst=0; // TODO Define this and use it later
- }
- }
- }
- if (! is_object($outputlangs)) $outputlangs=$langs;
- if (! $format) $format='daytextshort';
- $reduceformat=(! empty($conf->dol_optimize_smallscreen) && in_array($format,array('day','hour')))?1:0;
-
- // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
- if ($format == 'day') $format=($outputlangs->trans("FormatDateShort")!="FormatDateShort"?$outputlangs->trans("FormatDateShort"):$conf->format_date_short);
- else if ($format == 'hour') $format=($outputlangs->trans("FormatHourShort")!="FormatHourShort"?$outputlangs->trans("FormatHourShort"):$conf->format_hour_short);
- else if ($format == 'hourduration') $format=($outputlangs->trans("FormatHourShortDuration")!="FormatHourShortDuration"?$outputlangs->trans("FormatHourShortDuration"):$conf->format_hour_short_duration);
- else if ($format == 'daytext') $format=($outputlangs->trans("FormatDateText")!="FormatDateText"?$outputlangs->trans("FormatDateText"):$conf->format_date_text);
- else if ($format == 'daytextshort') $format=($outputlangs->trans("FormatDateTextShort")!="FormatDateTextShort"?$outputlangs->trans("FormatDateTextShort"):$conf->format_date_text_short);
- else if ($format == 'dayhour') $format=($outputlangs->trans("FormatDateHourShort")!="FormatDateHourShort"?$outputlangs->trans("FormatDateHourShort"):$conf->format_date_hour_short);
- else if ($format == 'dayhoursec') $format=($outputlangs->trans("FormatDateHourSecShort")!="FormatDateHourSecShort"?$outputlangs->trans("FormatDateHourSecShort"):$conf->format_date_hour_sec_short);
- else if ($format == 'dayhourtext') $format=($outputlangs->trans("FormatDateHourText")!="FormatDateHourText"?$outputlangs->trans("FormatDateHourText"):$conf->format_date_hour_text);
- else if ($format == 'dayhourtextshort') $format=($outputlangs->trans("FormatDateHourTextShort")!="FormatDateHourTextShort"?$outputlangs->trans("FormatDateHourTextShort"):$conf->format_date_hour_text_short);
- // Format not sensitive to language
- else if ($format == 'dayhourlog') $format='%Y%m%d%H%M%S';
- else if ($format == 'dayhourldap') $format='%Y%m%d%H%M%SZ';
- else if ($format == 'dayhourxcard') $format='%Y%m%dT%H%M%SZ';
- else if ($format == 'dayxcard') $format='%Y%m%d';
- else if ($format == 'dayrfc') $format='%Y-%m-%d'; // DATE_RFC3339
- else if ($format == 'dayhourrfc') $format='%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339
- else if ($format == 'standard') $format='%Y-%m-%d %H:%M:%S';
- if ($reduceformat)
- {
- $format=str_replace('%Y','%y',$format);
- $format=str_replace('yyyy','yy',$format);
- }
-
- // If date undefined or "", we return ""
- if (dol_strlen($time) == 0) return ''; // $time=0 allowed (it means 01/01/1970 00:00:00)
- // Clean format
- if (preg_match('/%b/i',$format)) // There is some text to translate
- {
- // We inhibate translation to text made by strftime functions. We will use trans instead later.
- $format=str_replace('%b','__b__',$format);
- $format=str_replace('%B','__B__',$format);
- }
- if (preg_match('/%a/i',$format)) // There is some text to translate
- {
- // We inhibate translation to text made by strftime functions. We will use trans instead later.
- $format=str_replace('%a','__a__',$format);
- $format=str_replace('%A','__A__',$format);
- }
- // Analyze date (deprecated) Ex: 1970-01-01, 1970-01-01 01:00:00, 19700101010000
- if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+) ?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i',$time,$reg)
- || 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))
- {
- // This part of code should not be used.
- dol_syslog("Functions.lib::dol_print_date function call with deprecated value of time in page ".$_SERVER["PHP_SELF"], LOG_WARNING);
- // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS' or 'YYYYMMDDHHMMSS'
- $syear = (! empty($reg[1]) ? $reg[1] : '');
- $smonth = (! empty($reg[2]) ? $reg[2] : '');
- $sday = (! empty($reg[3]) ? $reg[3] : '');
- $shour = (! empty($reg[4]) ? $reg[4] : '');
- $smin = (! empty($reg[5]) ? $reg[5] : '');
- $ssec = (! empty($reg[6]) ? $reg[6] : '');
- $time=dol_mktime($shour,$smin,$ssec,$smonth,$sday,$syear,true);
- $ret=adodb_strftime($format,$time+$offsettz+$offsetdst,$to_gmt);
- }
- else
- {
- // Date is a timestamps
- if ($time < 100000000000) // Protection against bad date values
- {
- $ret=adodb_strftime($format,$time+$offsettz+$offsetdst,$to_gmt);
- }
- else $ret='Bad value '.$time.' for date';
- }
- if (preg_match('/__b__/i',$format))
- {
- // Here ret is string in PHP setup language (strftime was used). Now we convert to $outputlangs.
- $month=adodb_strftime('%m',$time+$offsettz+$offsetdst);
- if ($encodetooutput)
- {
- $monthtext=$outputlangs->transnoentities('Month'.$month);
- $monthtextshort=$outputlangs->transnoentities('MonthShort'.$month);
- }
- else
- {
- $monthtext=$outputlangs->transnoentitiesnoconv('Month'.$month);
- $monthtextshort=$outputlangs->transnoentitiesnoconv('MonthShort'.$month);
- }
- //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
- $ret=str_replace('__b__',$monthtextshort,$ret);
- $ret=str_replace('__B__',$monthtext,$ret);
- //print 'x'.$outputlangs->charset_output.'-'.$ret.'x';
- //return $ret;
- }
- if (preg_match('/__a__/i',$format))
- {
- $w=adodb_strftime('%w',$time+$offsettz+$offsetdst);
- $dayweek=$outputlangs->transnoentitiesnoconv('Day'.$w);
- $ret=str_replace('__A__',$dayweek,$ret);
- $ret=str_replace('__a__',dol_substr($dayweek,0,3),$ret);
- }
- return $ret;
- }
- /**
- * Return an array with locale date info.
- * PHP getdate is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
- * WARNING: This function always use PHP server timezone to return locale informations.
- * Usage must be avoid.
- *
- * @param timestamp $timestamp Timestamp
- * @param boolean $fast Fast mode
- * @return array Array of informations
- * If no fast mode:
- * 'seconds' => $secs,
- * 'minutes' => $min,
- * 'hours' => $hour,
- * 'mday' => $day,
- * 'wday' => $dow,
- * 'mon' => $month,
- * 'year' => $year,
- * 'yday' => floor($secsInYear/$_day_power),
- * 'weekday' => gmdate('l',$_day_power*(3+$dow)),
- * 'month' => gmdate('F',mktime(0,0,0,$month,2,1971)),
- * If fast mode:
- * 'seconds' => $secs,
- * 'minutes' => $min,
- * 'hours' => $hour,
- * 'mday' => $day,
- * 'mon' => $month,
- * 'year' => $year,
- * 'yday' => floor($secsInYear/$_day_power),
- * 'leap' => $leaf,
- * 'ndays' => $ndays
- * @see dol_print_date, dol_stringtotime, dol_mktime
- */
- function dol_getdate($timestamp,$fast=false)
- {
- $usealternatemethod=false;
- if ($timestamp <= 0) $usealternatemethod=true; // <= 1970
- if ($timestamp >= 2145913200) $usealternatemethod=true; // >= 2038
- if ($usealternatemethod)
- {
- $arrayinfo=adodb_getdate($timestamp,$fast);
- }
- else
- {
- $arrayinfo=getdate($timestamp);
- }
- return $arrayinfo;
- }
- /**
- * Return a timestamp date built from detailed informations (by default a local PHP server timestamp)
- * Replace function mktime not available under Windows if year < 1970
- * PHP mktime is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
- *
- * @param int $hour Hour (can be -1 for undefined)
- * @param int $minute Minute (can be -1 for undefined)
- * @param int $second Second (can be -1 for undefined)
- * @param int $month Month (1 to 12)
- * @param int $day Day (1 to 31)
- * @param int $year Year
- * @param int $gm 1=Input informations are GMT values, otherwise local to server TZ
- * @param int $check 0=No check on parameters (Can use day 32, etc...)
- * @return timestamp Date as a timestamp, '' if error
- * @see dol_print_date, dol_stringtotime, dol_getdate
- */
- function dol_mktime($hour,$minute,$second,$month,$day,$year,$gm=false,$check=1)
- {
- global $conf;
- //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
- // Clean parameters
- if ($hour == -1 || empty($hour)) $hour=0;
- if ($minute == -1 || empty($minute)) $minute=0;
- if ($second == -1 || empty($second)) $second=0;
- // Check parameters
- if ($check)
- {
- if (! $month || ! $day) return '';
- if ($day > 31) return '';
- if ($month > 12) return '';
- if ($hour < 0 || $hour > 24) return '';
- if ($minute< 0 || $minute > 60) return '';
- if ($second< 0 || $second > 60) return '';
- }
- if (method_exists('DateTime','getTimestamp') && empty($conf->global->MAIN_OLD_DATE))
- {
- if (empty($gm)) $localtz = new DateTimeZone(date_default_timezone_get());
- else $localtz = new DateTimeZone('UTC');
- $dt = new DateTime(null,$localtz);
- $dt->setDate($year,$month,$day);
- $dt->setTime((int) $hour, (int) $minute, (int) $second);
- $date=$dt->getTimestamp();
- }
- else
- {
- $usealternatemethod=false;
- if ($year <= 1970) $usealternatemethod=true; // <= 1970
- if ($year >= 2038) $usealternatemethod=true; // >= 2038
- if ($usealternatemethod || $gm) // Si time gm, seule adodb peut convertir
- {
- $date=adodb_mktime($hour,$minute,$second,$month,$day,$year,0,$gm);
- }
- else
- {
- $date=mktime($hour,$minute,$second,$month,$day,$year);
- }
- }
- return $date;
- }
- /**
- * Return date for now. We should always use this function without parameters (that means GMT time)
- *
- * @param string $mode 'gmt' => we return GMT timestamp,
- * 'tzserver' => we add the PHP server timezone
- * 'tzref' => we add the company timezone
- * 'tzuser' => we add the user timezone
- * @return timestamp $date Timestamp
- */
- function dol_now($mode='gmt')
- {
- // Note that gmmktime and mktime return same value (GMT) whithout parameters
- //if ($mode == 'gmt') $ret=gmmktime(); // Strict Standards: gmmktime(): You should be using the time() function instead
- if ($mode == 'gmt') $ret=time(); // Time for now at greenwich.
- else if ($mode == 'tzserver') // Time for now with PHP server timezone added
- {
- require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
- $tzsecond=getServerTimeZoneInt('now'); // Contains tz+dayling saving time
- $ret=dol_now('gmt')+($tzsecond*3600);
- }
- /*else if ($mode == 'tzref') // Time for now with parent company timezone is added
- {
- require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
- $tzsecond=getParentCompanyTimeZoneInt(); // Contains tz+dayling saving time
- $ret=dol_now('gmt')+($tzsecond*3600);
- }*/
- else if ($mode == 'tzuser') // Time for now with user timezone is added
- {
- //print 'eeee'.time().'-'.mktime().'-'.gmmktime();
- $offsettz=(empty($_SESSION['dol_tz'])?0:$_SESSION['dol_tz'])*60*60;
- $offsetdst=(empty($_SESSION['dol_dst'])?0:$_SESSION['dol_dst'])*60*60;
- $ret=dol_now('gmt')+($offsettz+$offsetdst);
- }
- return $ret;
- }
- /**
- * Return string with formated size
- *
- * @param int $size Size to print
- * @param int $shortvalue Tell if we want long value to use another unit (Ex: 1.5Kb instead of 1500b)
- * @param int $shortunit Use short value of size unit
- * @return string Link
- */
- function dol_print_size($size,$shortvalue=0,$shortunit=0)
- {
- global $conf,$langs;
- $level=1024;
-
- if (! empty($conf->dol_optimize_smallscreen)) $shortunit=1;
-
- // Set value text
- if (empty($shortvalue) || $size < ($level*10))
- {
- $ret=$size;
- $textunitshort=$langs->trans("b");
- $textunitlong=$langs->trans("Bytes");
- }
- else
- {
- $ret=round($size/$level,0);
- $textunitshort=$langs->trans("Kb");
- $textunitlong=$langs->trans("KiloBytes");
- }
- // Use long or short text unit
- if (empty($shortunit)) { $ret.=' '.$textunitlong; }
- else { $ret.=' '.$textunitshort; }
- return $ret;
- }
- /**
- * Show Url link
- *
- * @param string $url Url to show
- * @param string $target Target for link
- * @param int $max Max number of characters to show
- * @return string HTML Link
- */
- function dol_print_url($url,$target='_blank',$max=32)
- {
- if (empty($url)) return '';
- $link='<a href="';
- if (! preg_match('/^http/i',$url)) $link.='http://';
- $link.=$url;
- if ($target) $link.='" target="'.$target.'">';
- if (! preg_match('/^http/i',$url)) $link.='http://';
- $link.=dol_trunc($url,$max);
- $link.='</a>';
- return $link;
- }
- /**
- * Show EMail link
- *
- * @param string $email EMail to show (only email, without 'Name of recipient' before)
- * @param int $cid Id of contact if known
- * @param int $socid Id of third party if known
- * @param int $addlink 0=no link to create action
- * @param int $max Max number of characters to show
- * @param int $showinvalid Show warning if syntax email is wrong
- * @return string HTML Link
- */
- function dol_print_email($email,$cid=0,$socid=0,$addlink=0,$max=64,$showinvalid=1)
- {
- global $conf,$user,$langs;
- $newemail=$email;
- if (empty($email)) return ' ';
- if (! empty($addlink))
- {
- $newemail='<a href="';
- if (! preg_match('/^mailto:/i',$email)) $newemail.='mailto:';
- $newemail.=$email;
- $newemail.='">';
- $newemail.=dol_trunc($email,$max);
- $newemail.='</a>';
- if ($showinvalid && ! isValidEmail($email))
- {
- $langs->load("errors");
- $newemail.=img_warning($langs->trans("ErrorBadEMail",$email));
- }
- if (($cid || $socid) && ! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
- {
- $type='AC_EMAIL'; $link='';
- if (! empty($conf->global->AGENDA_ADDACTIONFOREMAIL)) $link='<a href="'.DOL_URL_ROOT.'/comm/action/fiche.php?action=create&backtopage=1&actioncode='.$type.'&contactid='.$cid.'&socid='.$socid.'">'.img_object($langs->trans("AddAction"),"calendar").'</a>';
- $newemail='<table class="nobordernopadding"><tr><td>'.$newemail.' </td><td> '.$link.'</td></tr></table>';
- }
- }
- else
- {
- if ($showinvalid && ! isValidEmail($email))
- {
- $langs->load("errors");
- $newemail.=img_warning($langs->trans("ErrorBadEMail",$email));
- }
- }
- return $newemail;
- }
- /**
- * Format phone numbers according to country
- *
- * @param string $phone Phone number to format
- * @param string $country Country code to use for formatting
- * @param int $cid Id of contact if known
- * @param int $socid Id of third party if known
- * @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)
- * @param string $separ Separation between numbers for a better visibility example : xx.xx.xx.xx.xx
- * @return string Formated phone number
- */
- function dol_print_phone($phone,$country='',$cid=0,$socid=0,$addlink='',$separ=" ")
- {
- global $conf,$user,$langs,$mysoc;
- // Clean phone parameter
- $phone = preg_replace("/[\s.-]/","",trim($phone));
- if (empty($phone)) { return ''; }
- if (empty($country)) $country=$mysoc->country_code;
- // Short format for small screens
- if ($conf->dol_optimize_smallscreen) $separ='';
- $newphone=$phone;
- if (strtoupper($country) == "FR")
- {
- // France
- if (dol_strlen($phone) == 10) {
- $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);
- }
- elseif (dol_strlen($newphone) == 7)
- {
- $newphone=substr($newphone,0,3).$separ.substr($newphone,3,2).$separ.substr($newphone,5,2);
- }
- elseif (dol_strlen($newphone) == 9)
- {
- $newphone=substr($newphone,0,2).$separ.substr($newphone,2,3).$separ.substr($newphone,5,2).$separ.substr($newphone,7,2);
- }
- elseif (dol_strlen($newphone) == 11)
- {
- $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);
- }
- elseif (dol_strlen($newphone) == 12)
- {
- $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);
- }
- }
- if (! empty($addlink)) // Link on phone number + link to add action (if conf->global->AGENDA_ADDACTIONFORPHONE set)
- {
- if (! empty($conf->browser)) // If phone, we use link of phone
- {
- $newphone ='<a href="tel:'.$phone.'"';
- $newphone.='>'.$phone.'</a>';
- }
- else if (! empty($conf->clicktodial->enabled) && $addlink == 'AC_TEL') // If click to dial, we use click to dial url
- {
- if (empty($user->clicktodial_loaded)) $user->fetch_clicktodial();
- // Define urlmask
- $urlmask='ErrorClickToDialModuleNotConfigured';
- if (! empty($conf->global->CLICKTODIAL_URL)) $urlmask=$conf->global->CLICKTODIAL_URL;
- if (! empty($user->clicktodial_url)) $urlmask=$user->clicktodial_url;
- $clicktodial_poste=(! empty($user->clicktodial_poste)?urlencode($user->clicktodial_poste):'');
- $clicktodial_login=(! empty($user->clicktodial_login)?urlencode($user->clicktodial_login):'');
- $clicktodial_password=(! empty($user->clicktodial_password)?urlencode($user->clicktodial_password):'');
- // This line is for backward compatibility
- $url = sprintf($urlmask, urlencode($phone), $clicktodial_poste, $clicktodial_login, $clicktodial_password);
- // Thoose lines are for substitution
- $substitarray=array('__PHONEFROM__'=>$clicktodial_poste,
- '__PHONETO__'=>urlencode($phone),
- '__LOGIN__'=>$clicktodial_login,
- '__PASS__'=>$clicktodial_password);
- $url = make_substitutions($url, $substitarray);
- $newphonesav=$newphone;
- $newphone ='<a href="'.$url.'"';
- if (! empty($conf->global->CLICKTODIAL_FORCENEWTARGET)) $newphone.=' target="_blank"';
- $newphone.='>'.$newphonesav.'</a>';
- }
- //if (($cid || $socid) && ! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
- if (! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
- {
- $type='AC_TEL'; $link='';
- if ($addlink == 'AC_FAX') $type='AC_FAX';
- if (! empty($conf->global->AGENDA_ADDACTIONFORPHONE)) $link='<a href="'.DOL_URL_ROOT.'/comm/action/fiche.php?action=create&backtopage=1&actioncode='.$type.($cid?'&contactid='.$cid:'').($socid?'&socid='.$socid:'').'">'.img_object($langs->trans("AddAction"),"calendar").'</a>';
- if ($link) $newphone='<table class="nobordernopadding"><tr><td>'.$newphone.' </td><td> '.$link.'</td></tr></table>';
- }
- }
- return $newphone;
- }
- /**
- * Return an IP formated to be shown on screen
- *
- * @param string $ip IP
- * @param int $mode 0=return IP + country/flag, 1=return only country/flag, 2=return only IP
- * @return string Formated IP, with country if GeoIP module is enabled
- */
- function dol_print_ip($ip,$mode=0)
- {
- global $conf,$langs;
- $ret='';
- if (empty($mode)) $ret.=$ip;
- if (! empty($conf->geoipmaxmind->enabled) && $mode != 2)
- {
- $datafile=$conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
- //$ip='24.24.24.24';
- //$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)
- include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
- $geoip=new DolGeoIP('country',$datafile);
- //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
- //print "geoip_country_id_by_addr=".geoip_country_id_by_addr($geoip->gi,$ip)."\n";
- $countrycode=$geoip->getCountryCodeFromIP($ip);
- if ($countrycode) // If success, countrycode is us, fr, ...
- {
- if (file_exists(DOL_DOCUMENT_ROOT.'/theme/common/flags/'.$countrycode.'.png'))
- {
- $ret.=' '.img_picto($countrycode.' '.$langs->trans("AccordingToGeoIPDatabase"),DOL_URL_ROOT.'/theme/common/flags/'.$countrycode.'.png','',1);
- }
- else $ret.=' ('.$countrycode.')';
- }
- }
- return $ret;
- }
- /**
- * Return country code for current user.
- * If software is used inside a local network, detection may fails (we need a public ip)
- *
- * @return string Country code (fr, es, it, us, ...)
- */
- function dol_user_country()
- {
- global $conf,$langs,$user;
- //$ret=$user->xxx;
- $ret='';
- if (! empty($conf->geoipmaxmind->enabled))
- {
- $ip=$_SERVER["REMOTE_ADDR"];
- $datafile=$conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
- //$ip='24.24.24.24';
- //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';
- include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
- $geoip=new DolGeoIP('country',$datafile);
- $countrycode=$geoip->getCountryCodeFromIP($ip);
- $ret=$countrycode;
- }
- return $ret;
- }
- /**
- * Format address string
- *
- * @param string $address Address
- * @param int $htmlid Html ID (for example 'gmap')
- * @param int $mode thirdparty|contact|member|other
- * @param int $id Id of object
- * @return void
- */
- function dol_print_address($address, $htmlid, $mode, $id)
- {
- global $conf,$user,$langs;
- if ($address)
- {
- print nl2br($address);
- $showgmap=$showomap=0;
- if ($mode=='thirdparty' && ! empty($conf->google->enabled) && ! empty($conf->global->GOOGLE_ENABLE_GMAPS)) $showgmap=1;
- if ($mode=='contact' && ! empty($conf->google->enabled) && ! empty($conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS)) $showgmap=1;
- if ($mode=='member' && ! empty($conf->google->enabled) && ! empty($conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS)) $showgmap=1;
- if …
Large files files are truncated, but you can click here to view the full file