/htdocs/core/lib/functions.lib.php
PHP | 4480 lines | 2707 code | 400 blank | 1373 comment | 930 complexity | 1cdd3126dd381b0536d2d331e41c8c37 MD5 | raw file
Possible License(s): LGPL-2.0
Large files files are truncated, but you can click here to view the full file
- <?php
- /* Copyright (C) 2000-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
- * Copyright (C) 2003 Jean-Louis Bergamo <jlb@j1b.org>
- * Copyright (C) 2004-2011 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-2010 Regis Houssin <regis@dolibarr.fr>
- * 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 2 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'))
- {
- /**
- * Implement json_encode for PHP that does not support it
- *
- * @param mixed $elements PHP Object to json encode
- * @return string Json encoded string
- */
- function json_encode($elements)
- {
- $num = count($elements);
- // determine type
- if (is_numeric(key($elements)))
- {
- // indexed (list)
- $output = '[';
- for ($i = 0, $last = ($num - 1); isset($elements[$i]); ++$i)
- {
- if (is_array($elements[$i])) $output.= json_encode($elements[$i]);
- else $output .= _val($elements[$i]);
- if($i !== $last) $output.= ',';
- }
- $output.= ']';
- }
- else
- {
- // associative (object)
- $output = '{';
- $last = $num - 1;
- $i = 0;
- foreach($elements as $key => $value)
- {
- $output .= '"'.$key.'":';
- if (is_array($value)) $output.= json_encode($value);
- else $output .= _val($value);
- if ($i !== $last) $output.= ',';
- ++$i;
- }
- $output.= '}';
- }
- // return
- return $output;
- }
- function _val($val)
- {
- if (is_string($val)) return '"'.rawurlencode($val).'"';
- elseif (is_int($val)) return sprintf('%d', $val);
- elseif (is_float($val)) return sprintf('%F', $val);
- elseif (is_bool($val)) return ($val ? 'true' : 'false');
- else return 'null';
- }
- }
- if (! function_exists('json_decode'))
- {
- /**
- * Implement json_decode for PHP that does not support it
- *
- * @param string $json Json encoded to PHP Object or Array
- * @param bool $assoc False return an object, true return an array
- * @return mixed Object or Array
- */
- function json_decode($json, $assoc=false)
- {
- $comment = false;
- $strLength = dol_strlen($json);
- for ($i=0; $i<$strLength; $i++)
- {
- if (! $comment)
- {
- if (($json[$i] == '{') || ($json[$i] == '[')) $out.= 'array(';
- else if (($json[$i] == '}') || ($json[$i] == ']')) $out.= ')';
- else if ($json[$i] == ':') $out.= ' => ';
- else $out.= $json[$i];
- }
- else $out.= $json[$i];
- if ($json[$i] == '"' && $json[($i-1)]!="\\") $comment = !$comment;
- }
- // Return an array
- eval('$array = '.$out.';');
- // Return an object
- if (! $assoc)
- {
- if (! empty($array))
- {
- $object = false;
- foreach ($array as $key => $value)
- {
- $object->{$key} = $value;
- }
- return $object;
- }
- return false;
- }
- return $array;
- }
- }
- /**
- * 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;
- }
- /**
- * Function called at end of web php process
- *
- * @return void
- */
- function dol_shutdown()
- {
- global $conf,$user,$langs,$db;
- $disconnectdone=false;
- if (is_object($db) && ! empty($db->connected)) $disconnectdone=$db->close();
- dol_syslog("--- End access to ".$_SERVER["PHP_SELF"].($disconnectdone?' (Warn: db disconnection forced)':''), ($disconnectdone?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)
- * @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]:'');
- if (!empty($check))
- {
- // Check if numeric
- if ($check == 'int' && ! preg_match('/^[\.,0-9]+$/i',trim($out))) $out='';
- // Check if alpha
- //if ($check == 'alpha' && ! preg_match('/^[ =:@#\/\\\(\)\-\._a-z0-9]+$/i',trim($out))) $out='';
- // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
- if ($check == 'alpha' && preg_match('/"/',trim($out))) $out='';
- }
- 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, ...)
- * @return int false if include fails.
- */
- function dol_include_once($relpath)
- {
- global $conf,$langs,$user,$mysoc; // Other global var must be retreived with $GLOBALS['var']
- return @include_once(dol_buildpath($relpath));
- }
- /**
- * 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;
- }
- }
- }
- 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->browser->phone)) return $size;
- if ($type == 'width' && $size > 250) return 250;
- else return 10;
- }
- /**
- * 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(); // Time for now at greenwich.
- else if ($mode == 'tzserver') // Time for now with PHP server timezone added
- {
- $tzsecond=-dol_mktime(0,0,0,1,1,1970);
- $ret=gmmktime()+$tzsecond;
- }
- else if ($mode == 'tzref') // Time for now where parent company timezone is added
- {
- // TODO Should add the company timezone
- $ret=gmmktime();
- }
- else if ($mode == 'tzuser') // Time for now where user timezone is added
- {
- //print 'eeee'.time().'-'.mktime().'-'.gmmktime();
- $tzhour=isset($_SESSION['dol_tz'])?$_SESSION['dol_tz']:0;
- $ret=gmmktime()+($tzhour*60*60);
- }
- return $ret;
- }
- /**
- * 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
- * @return string String cleaned (a-zA-Z_)
- *
- * @see dol_string_nospecial, dol_string_unaccent
- */
- function dol_sanitizeFileName($str,$newstr='_')
- {
- global $conf;
- return dol_string_nospecial(dol_string_unaccent($str),$newstr,$conf->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');
- }
- /**
- * Write log message into outputs. Possible outputs can be:
- * A file if SYSLOG_FILE_ON defined: file name is then defined by SYSLOG_FILE
- * Syslog if SYSLOG_SYSLOG_ON defined: facility is then defined by SYSLOG_FACILITY
- * Warning, les fonctions syslog sont buggues sous Windows et generent des
- * fautes de protection memoire. Pour resoudre, utiliser le loggage fichier,
- * au lieu du loggage syslog (configuration du module).
- * Note: If SYSLOG_FILE_NO_ERROR defined, we never output error message when writing to log fails.
- *
- * 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
- * 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
- * @return void
- */
- function dol_syslog($message, $level=LOG_INFO)
- {
- global $conf,$user,$langs,$_REQUEST;
- // 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 syslog module enabled
- if (! empty($conf->syslog->enabled))
- {
- //print $level.' - '.$conf->global->SYSLOG_LEVEL.' - '.$conf->syslog->enabled." \n";
- if ($level > $conf->global->SYSLOG_LEVEL) return;
- // Translate error message if this is an error message (rare) and langs is loaded
- if ($level == LOG_ERR)
- {
- if (is_object($langs))
- {
- $langs->load("errors");
- if ($message != $langs->trans($message)) $message = $langs->trans($message);
- }
- }
- // Add page/script name to log message
- $script=isset($_SERVER['PHP_SELF'])?basename($_SERVER['PHP_SELF'],'.php').' ':'';
- $message=$script.$message;
- // Add user to log message
- $login='nologin';
- if (is_object($user) && $user->id) $login=$user->login;
- $message=sprintf("%-8s",$login)." ".$message;
- // Check if log is to a file (SYSLOG_FILE_ON defined)
- if (defined("SYSLOG_FILE_ON") && constant("SYSLOG_FILE_ON"))
- {
- $filelog=SYSLOG_FILE;
- $filelog=preg_replace('/DOL_DATA_ROOT/i',DOL_DATA_ROOT,$filelog);
- //print "filelog=".$filelog."\n";
- if (defined("SYSLOG_FILE_NO_ERROR")) $file=@fopen($filelog,"a+");
- else $file=fopen($filelog,"a+");
- if ($file)
- {
- $ip='???'; // $ip contains information to identify computer that run the code
- if (! empty($_SERVER["REMOTE_ADDR"])) $ip=$_SERVER["REMOTE_ADDR"]; // In most cases.
- else if (! empty($_SERVER['SERVER_ADDR'])) $ip=$_SERVER['SERVER_ADDR']; // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
- else if (! empty($_SERVER['COMPUTERNAME'])) $ip=$_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME'])?'':'@'.$_SERVER['USERNAME']); // This is when PHP session is ran outside a web server, like from Windows command line (Not always defined, but usefull if OS defined it).
- else if (! empty($_SERVER['LOGNAME'])) $ip='???@'.$_SERVER['LOGNAME']; // This is when PHP session is ran outside a web server, like from Linux command line (Not always defined, but usefull if OS defined it).
- $liblevelarray=array(LOG_ERR=>'ERROR',LOG_WARNING=>'WARN',LOG_INFO=>'INFO',LOG_DEBUG=>'DEBUG');
- $liblevel=$liblevelarray[$level];
- if (! $liblevel) $liblevel='UNDEF';
- $message=dol_print_date(time(),"%Y-%m-%d %H:%M:%S")." ".sprintf("%-5s",$liblevel)." ".sprintf("%-15s",$ip)." ".$message;
- fwrite($file,$message."\n");
- fclose($file);
- // This is for log file, we do not change permissions
- // 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";
- }
- }
- elseif (! defined("SYSLOG_FILE_NO_ERROR"))
- {
- // Do not use here a call to functions that make call to dol_syslog so making call to langs. A simple print is enough.
- print "Error, failed to open file ".$filelog."\n";
- }
- }
- // Check if log is to syslog (SYSLOG_SYSLOG_ON defined)
- if (defined("SYSLOG_SYSLOG_ON") && constant("SYSLOG_SYSLOG_ON"))
- {
- if (function_exists('openlog')) // This function does not exists on some ISP (Ex: Free in France)
- {
- $facility = LOG_USER;
- if (defined("SYSLOG_FACILITY") && constant("SYSLOG_FACILITY"))
- {
- // Exemple: SYSLOG_FACILITY vaut LOG_USER qui vaut 8. On a besoin de 8 dans $facility.
- $facility = constant("SYSLOG_FACILITY");
- }
- openlog("dolibarr", LOG_PID | LOG_PERROR, (int) $facility); // (int) is required to avoid error parameter 3 expected to be long
- if (! $level) syslog(LOG_ERR, $message);
- else syslog($level, $message);
- closelog();
- }
- }
- // Check if log is to syslog (SYSLOG_FIREPHP_ON defined)
- if (defined("SYSLOG_FIREPHP_ON") && constant("SYSLOG_FIREPHP_ON") && ! empty($_SERVER["SERVER_NAME"])) //! empty($_SERVER["SERVER_NAME"]) to be sure to enable this in Web mode only
- {
- try
- {
- // Warning FirePHPCore must be into PHP include path. It is not possible to use into require_once() a constant from
- // database or config file because we must be able to log data before database or config file read.
- $oldinclude=get_include_path();
- set_include_path('/usr/share/php/');
- require_once('FirePHPCore/FirePHP.class.php');
- set_include_path($oldinclude);
- ob_start();
- $firephp = FirePHP::getInstance(true);
- if ($level == LOG_ERR) $firephp->error($message);
- elseif ($level == LOG_WARNING) $firephp->warn($message);
- elseif ($level == LOG_INFO) $firephp->log($message);
- else $firephp->log($message);
- }
- catch(Exception $e)
- {
- }
- }
- }
- }
- /**
- * 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
- * @return void
- */
- function dol_fiche_head($links=array(), $active='0', $title='', $notab=0, $picto='')
- {
- print dol_get_fiche_head($links, $active, $title, $notab, $picto);
- }
- /**
- * 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
- * @return void
- */
- function dol_get_fiche_head($links=array(), $active='0', $title='', $notab=0, $picto='')
- {
- $out="\n".'<div class="tabs">'."\n";
- // Affichage titre
- if ($title)
- {
- $limittitle=30;
- $out.='<a class="tabTitle">';
- if ($picto) $out.=img_object('',$picto).' ';
- $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))
- {
- $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 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 '';
- }
- /* For backward compatibility */
- function dolibarr_print_date($time,$format='',$to_gmt=false,$outputlangs='',$encodetooutput=false)
- {
- return dol_print_date($time,$format,$to_gmt,$outputlangs,$encodetooutput);
- }
- /**
- * Return a formated address (part address/zip/town/state) according to country rules
- *
- * @param outputlangs Output langs object
- * @param object A company or contact object
- * @return string Formated string
- */
- function dol_format_address($outputlangs,$object)
- {
- $ret='';
- $countriesusingstate=array('US','IN');
- // Address
- $ret .= $outputlangs->convToOutputCharset($object->address);
- // Zip/Town/State
- if (in_array($object->country_code,array('US'))) // US: town, state, zip
- {
- $ret .= ($ret ? "\n" : '' ).$outputlangs->convToOutputCharset($object->town);
- if ($object->state && in_array($object->country_code,$countriesusingstate))
- {
- $ret.=", ".$outputlangs->convToOutputCharset($object->departement);
- }
- if ($object->zip) $ret .= ', '.$outputlangs->convToOutputCharset($object->zip);
- }
- else // Other: zip town, state
- {
- $ret .= ($ret ? "\n" : '' ).$outputlangs->convToOutputCharset($object->zip);
- $ret .= ' '.$outputlangs->convToOutputCharset($object->town);
- if ($object->state && in_array($object->country_code,$countriesusingstate))
- {
- $ret.=", ".$outputlangs->convToOutputCharset($object->state);
- }
- }
- return $ret;
- }
- /**
- * 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 cas charset is output charset
- *
- * @param timestamp $time GM Timestamps date (or deprecated strings 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS')
- * @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"
- * @param string $tzoutput true=output 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;
- $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;
- }
- if ($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;
- }
- if ($tzoutput == 'tzcompany')
- {
- $to_gmt=false;
- $offsettz=$offsetdst=0; // TODO Define this and use it later
- }
- }
- }
- if (! is_object($outputlangs)) $outputlangs=$langs;
- // Si format non defini, on prend $conf->format_date_text_short sinon %Y-%m-%d %H:%M:%S
- if (! $format) $format=(isset($conf->format_date_text_short) ? $conf->format_date_text_short : '%Y-%m-%d %H:%M:%S');
- // 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);
- if ($format == 'hour') $format=($outputlangs->trans("FormatHourShort")!="FormatHourShort"?$outputlangs->trans("FormatHourShort"):$conf->format_hour_short);
- if ($format == 'hourduration') $format=($outputlangs->trans("FormatHourShortDuration")!="FormatHourShortDuration"?$outputlangs->trans("FormatHourShortDuration"):$conf->format_hour_short_duration);
- if ($format == 'daytext') $format=($outputlangs->trans("FormatDateText")!="FormatDateText"?$outputlangs->trans("FormatDateText"):$conf->format_date_text);
- if ($format == 'daytextshort') $format=($outputlangs->trans("FormatDateTextShort")!="FormatDateTextShort"?$outputlangs->trans("FormatDateTextShort"):$conf->format_date_text_short);
- if ($format == 'dayhour') $format=($outputlangs->trans("FormatDateHourShort")!="FormatDateHourShort"?$outputlangs->trans("FormatDateHourShort"):$conf->format_date_hour_short);
- if ($format == 'dayhourtext') $format=($outputlangs->trans("FormatDateHourText")!="FormatDateHourText"?$outputlangs->trans("FormatDateHourText"):$conf->format_date_hour_text);
- if ($format == 'dayhourtextshort') $format=($outputlangs->trans("FormatDateHourTextShort")!="FormatDateHourTextShort"?$outputlangs->trans("FormatDateHourTextShort"):$conf->format_date_hour_text_short);
- // Format not sensitive to language
- if ($format == 'dayhourlog') $format='%Y%m%d%H%M%S';
- if ($format == 'dayhourldap') $format='%Y%m%d%H%M%SZ';
- if ($format == 'dayhourxcard') $format='%Y%m%dT%H%M%SZ';
- if ($format == 'dayxcard') $format='%Y%m%d';
- if ($format == 'dayrfc') $format='%Y-%m-%d'; // DATE_RFC3339
- if ($format == 'dayhourrfc') $format='%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339
- // If date undefined or "", we return ""
- if (dol_strlen($time) == 0) return ''; // $time=0 allowed (it means 01/01/1970 00:00:00)
- //print 'x'.$time;
- 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 = $reg[1];
- $smonth = $reg[2];
- $sday = $reg[3];
- $shour = $reg[4];
- $smin = $reg[5];
- $ssec = $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;
- }
- /**
- * Convert a string date into a GM Timestamps date
- *
- * @param string $string Date in a string
- * YYYYMMDD
- * YYYYMMDDHHMMSS
- * YYYY-MM-DDTHH:MM:SSZ (RFC3339)
- * DD/MM/YY or DD/MM/YYYY (this format should not be used anymore)
- * DD/MM/YY HH:MM:SS or DD/MM/YYYY HH:MM:SS (this format should not be used anymore)
- * @param int $gm 1=Input date is GM date, 0=Input date is local date
- * 19700101020000 -> 7200 with gm=1
- * @return date Date
- *
- * @see dol_print_date, dol_mktime, dol_getdate
- */
- function dol_stringtotime($string, $gm=1)
- {
- if (preg_match('/^([0-9]+)\/([0-9]+)\/([0-9]+)\s?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i',$string,$reg))
- {
- // This part of code should not be used.
- dol_syslog("Functions.lib::dol_stringtotime call to function with deprecated parameter", LOG_WARNING);
- // Date est au format 'DD/MM/YY' ou 'DD/MM/YY HH:MM:SS'
- // Date est au format 'DD/MM/YYYY' ou 'DD/MM/YYYY HH:MM:SS'
- $sday = $reg[1];
- $smonth = $reg[2];
- $syear = $reg[3];
- $shour = $reg[4];
- $smin = $reg[5];
- $ssec = $reg[6];
- if ($syear < 50) $syear+=1900;
- if ($syear >= 50 && $syear < 100) $syear+=2000;
- $string=sprintf("%04d%02d%02d%02d%02d%02d",$syear,$smonth,$sday,$shour,$smin,$ssec);
- }
- // Convert date RFC3339
- else if (preg_match('/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})Z$/i',$string,$reg))
- {
- $syear = $reg[1];
- $smonth = $reg[2];
- $sday = $reg[3];
- $shour = $reg[4];
- $smin = $reg[5];
- $ssec = $reg[6];
- $string=sprintf("%04d%02d%02d%02d%02d%02d",$syear,$smonth,$sday,$shour,$smin,$ssec);
- }
- $string=preg_replace('/([^0-9])/i','',$string);
- $tmp=$string.'000000';
- $date=dol_mktime(substr($tmp,8,2),substr($tmp,10,2),substr($tmp,12,2),substr($tmp,4,2),substr($tmp,6,2),substr($tmp,0,4),$gm);
- return $date;
- }
- /**
- * Return an array with date info
- * PHP getdate is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
- *
- * @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
- */
- 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;
- }
- /* For backward compatibility */
- function dolibarr_mktime($hour,$minute,$second,$month,$day,$year,$gm=false,$check=1)
- {
- return dol_mktime($hour,$minute,$second,$month,$day,$year,$gm,$check);
- }
- /**
- * 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 hour Hour (can be -1 for undefined)
- * @param minute Minute (can be -1 for undefined)
- * @param second Second (can be -1 for undefined)
- * @param month Month (1 to 12)
- * @param day Day (1 to 31)
- * @param year Year
- * @param gm 1=Input informations are GMT values, otherwise local to server TZ
- * @param check 0=No check on parameters (Can use day 32, etc...)
- * @param isdst Dayling saving time
- * @return timestamp Date as a timestamp, '' if error
- * @see dol_print_date, dol_stringtotime
- */
- function dol_mktime($hour,$minute,$second,$month,$day,$year,$gm=false,$check=1,$isdst=true)
- {
- //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
- // Clean parameters
- if ($hour == -1) $hour=0;
- if ($minute == -1) $minute=0;
- if ($second == -1) $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 '';
- }
- $usealternatemethod=false;
- if ($year <= 1970) $usealternatemethod=true; // <= 1970
- if ($year >= 2038) $usealternatemethod=true; // >= 2038
- if ($usealternatemethod || $gm) // Si time gm, seule adodb peut convertir
- {
- /*
- // On peut utiliser strtotime pour obtenir la traduction.
- // strtotime is ok for range: Friday 13 December 1901 20:45:54 GMT to Tuesday 19 January 2038 03:14:07 GMT.
- $montharray=array(1=>'january',2=>'february',3=>'march',4=>'april',5=>'may',6=>'june',
- 7=>'july',8=>'august',9=>'september',10=>'october',11=>'november',12=>'december');
- $string=$day." ".$montharray[0+$month]." ".$year." ".$hour.":".$minute.":".$second." GMT";
- $date=strtotime($string);
- print "- ".$string." ".$date." -";
- */
- $date=adodb_mktime($hour,$minute,$second,$month,$day,$year,$isdst,$gm);
- }
- else
- {
- $date=mktime($hour,$minute,$second,$month,$day,$year);
- }
- return $date;
- }
- /* For backward compatibility */
- function dolibarr_date($fmt, $timestamp, $gm=false)
- {
- return dol_date($fmt, $timestamp, $gm);
- }
- /**
- * Returns formated date
- *
- * @param string $fmt Format (Exemple: 'Y-m-d H:i:s')
- * @param timestamp $timestamp Date. Example: If timestamp=0 and gm=1, return 01/01/1970 00:00:00
- * @param boolean $gm 1 if timestamp was built with gmmktime, 0 if timestamp was build with mktime
- * @return string Formated date
- *
- * @deprecated Replaced by dol_print_date
- */
- function dol_date($fmt, $timestamp, $gm=false)
- {
- $usealternatemethod=false;
- if ($timestamp <= 0) $usealternatemethod=true;
- if ($timestamp >= 2145913200) $usealternatemethod=true;
- if ($usealternatemethod || $gm) // Si time gm, seule adodb peut convertir
- {
- $string=adodb_date($fmt,$timestamp,$gm);
- }
- else
- {
- $string=date($fmt,$timestamp);
- }
- return $string;
- }
- /**
- * 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 $langs;
- $level=1024;
- // 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) && $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;
- }
- /* For backward compatibility */
- function dolibarr_print_phone($phone,$country="FR",$cid=0,$socid=0,$addlink=0,$separ=" ")
- {
- return dol_print_phone($phone,$country,$cid,$socid,$addlink,$separ);
- }
- /**
- * 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 0=no link to create action
- * @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="FR",$cid=0,$socid=0,$addlink=0,$separ=" ")
- {
- global $conf,$user,$langs;
- // Clean phone parameter
- $phone = preg_replace("/[\s.-]/","",trim($phone));
- if (empty($phone)) { return ''; }
- $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))
- {
- if ($conf->clicktodial->enabled)
- {
- if (empty($user->clicktodial_loaded)) $user->fetch_clicktodial();
- if (empty($conf->global->CLICKTODIAL_URL)) $urlmask='ErrorClickToDialModuleNotConfigured';
- else $urlmask=$conf->global->CLICKTODIAL_URL;
- // This line is for backward compatibility
- $url = sprintf($urlmask, urlencode($phone), urlencode($user->clicktodial_poste), urlencode($user->clicktodial_login), urlencode($user->clicktodial_password));
- // Thoose lines are for substitution
- $substitarray=array('__PHONEFROM__'=>urlencode($user->clicktodial_poste),
- '__PHONETO__'=>urlencode($phone),
- '__LOGIN__'=>urlencode($user->clicktodial_login),
- '__PASS__'=>urlencode($user->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) && $conf->agenda->enabled && $user->rights->agenda->myactions->create)
- if ($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>';
- $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 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, …
Large files files are truncated, but you can click here to view the full file