/htdocs/core/lib/functions.lib.php
PHP | 4174 lines | 4010 code | 26 blank | 138 comment | 55 complexity | 3e9cd8b513b776388c29c401933f3b89 MD5 | raw file
Possible License(s): LGPL-3.0, LGPL-2.1, GPL-3.0, MIT
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-2012 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-2013 Regis Houssin <regis.houssin@capnetworks.com>
- * Copyright (C) 2008 Raphael Bertrand <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;
- foreach ($classObj->getStaticProperties() as $prop => $value) {
- if ($prop == $member) {
- $result = $value;
- break;
- }
- }
- 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 ? ' (Warn: db disconnection forced, transaction depth was ' . $depth . ')' : ''), ($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, '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["HTTP_HOST"] . $_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)) {
- if (!class_exists($classname))
- return @include dol_buildpath($relpath);
- }
- else
- 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;
- }
- }
- }
- 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->browser->phone))
- 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');
- }
- /**
- * 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, 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
- * 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
- * @deprecated
- */
- function dol_syslog($message, $level = LOG_INFO) {
- // nothing
- }
- /**
- * 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
- * @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>' . "\n";
- // 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 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 a formated address (part address/zip/town/state) according to country rules
- *
- * @param Object $object A company or contact object
- * @return string Formated string
- */
- function dol_format_address($object) {
- $ret = '';
- $countriesusingstate = array('US', 'IN', 'GB');
- // Address
- $ret .= $object->address;
- // Zip/Town/State
- if (in_array($object->country_code, array('US'))) { // US: title firstname name \n address lines \n town, state, zip \n country
- $ret .= ($ret ? "\n" : '' ) . $object->town;
- if ($object->state && in_array($object->country_code, $countriesusingstate)) {
- $ret.=", " . $object->departement;
- }
- 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 ? "\n" : '' ) . $object->town;
- if ($object->state && in_array($object->country_code, $countriesusingstate)) {
- $ret.=", " . $object->departement;
- }
- if ($object->zip)
- $ret .= ($ret ? "\n" : '' ) . $object->zip;
- }
- else { // Other: title firstname name \n address lines \n zip town \n country
- $ret .= ($ret ? "\n" : '' ) . $object->zip;
- $ret .= ' ' . $object->town;
- if ($object->state && in_array($object->country_code, $countriesusingstate)) {
- $ret.=", " . $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 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=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;
- require_once DOL_DOCUMENT_ROOT . '/includes/adodbtime/adodb-time.inc.php';
- $time = strtotime($time);
- $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;
- // 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 = (!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("c", $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 = time() + ($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 = time() + ($offsettz + $offsetdst);
- }
- return date("c", $ret); // ISO date format
- }
- /**
- * 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) && !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 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 (!empty($conf->clicktodial->enabled) && $addlink == 'AC_TEL') {
- if (empty($user->clicktodial_loaded))
- $user->fetch_clicktodial();
- if (empty($conf->global->CLICKTODIAL_URL))
- $urlmask = 'ErrorClickToDialModuleNotConfigured';
- else
- $urlmask = $conf->global->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>';
- $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
- * @param bool $gps See MAP
- * @return void
- */
- function dol_print_address($address, $htmlid, $mode, $id, $gps = false) {
- global $conf, $user, $langs;
- $rtr = "";
- if ($address) {
- $rtr.= 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 ($mode == 'thirdparty' && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS))
- $showomap = 1;
- if ($mode == 'contact' && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_CONTACTS))
- $showomap = 1;
- if ($mode == 'member' && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_MEMBERS))
- $showomap = 1;
- if ($conf->map->enabled && $gps) {
- $url = dol_buildpath('/map/map.php?id=' . $id, 1);
- $rtr.= ' <a href="' . $url . '" target="_gmaps"><img id="' . $htmlid . '" border="0" src="' . DOL_URL_ROOT . '/theme/common/gmap.png"></a>';
- }
- // TODO Add a hook here
- if ($showgmap) {
- $url = dol_buildpath('/google/gmaps.php?mode=' . $mode . '&id=' . $id, 1);
- $rtr.= ' <a href="' . $url . '" target="_gmaps"><img id="' . $htmlid . '" border="0" src="' . DOL_URL_ROOT . '/theme/common/gmap.png"></a>';
- }
- if ($showomap) {
- $url = dol_buildpath('/openstreetmap/maps.php?mode=' . $mode . '&id=' . $id, 1);
- $rtr.= ' <a href="' . $url . '" target="_gmaps"><img id="' . $htmlid . '_openstreetmap" border="0" src="' . DOL_URL_ROOT . '/theme/common/gmap.png"></a>';
- }
- }
- return $rtr;
- }
- /**
- * Return true if email syntax is ok
- *
- * @param string $address email (Ex: "toto@titi.com", "John Do <johndo@titi.com>")
- * @return boolean true if email syntax is OK, false if KO or empty string
- */
- function isValidEmail($address) {
- if (preg_match("/.*<(.+)>/i", $address, $regs)) {
- $address = $regs[1];
- }
- // 2 letters domains extensions are for countries
- // 3 letters domains extensions: biz|com|edu|gov|int|mil|net|org|pro|...
- if (preg_match("/^[^@\s\t]+@([a-zA-Z0-9\-]+\.)+([a-zA-Z0-9\-]{2,3}|asso|aero|coop|info|name)\$/i", $address)) {
- return true;
- } else {
- return false;
- }
- }
- /**
- * Return true if phone number syntax is ok
- *
- * @param string $phone phone (Ex: "0601010101")
- * @return boolean true if phone syntax is OK, false if KO or empty string
- */
- function isValidPhone($phone) {
- return true;
- }
- /**
- * Make a strlen call. Works even if mbstring module not enabled
- *
- * @param string $string String to calculate length
- * @param string $stringencoding Encoding of string
- * @return int Length of string
- */
- function dol_strlen($string, $stringencoding = 'UTF-8') {
- if (function_exists('mb_strlen'))
- return mb_strlen($string, $stringencoding);
- else
- return strlen($string);
- }
- /**
- * Make a substring. Works even in mbstring module is not enabled.
- *
- * @param string $string String to scan
- * @param string $start Start position
- * @param int $length Length
- * @param string $stringencoding Page code used for input string encoding
- * @return string substring
- */
- function dol_substr($string, $start, $length, $stringencoding = '') {
- global $langs;
- if (empty($stringencoding))
- $stringencoding = $langs->charset_output;
- $ret = '';
- if (function_exists('mb_substr')) {
- $ret = mb_substr($string, $start, $length, $stringencoding);
- } else {
- $ret = substr($string, $start, $length);
- }
- return $ret;
- }
- /**
- * Show a javascript graph.
- * Do not use this function anymore. Use DolGraph class instead.
- *
- * @param string $htmlid Html id name
- * @param int $width Width in pixel
- * @param int $height Height in pixel
- * @param array $data Data array
- * @param int $showlegend 1 to show legend, 0 otherwise
- * @param string $type Type of graph ('pie', 'barline')
- * @param int $showpercent Show percent (with type='pie' only)
- * @param string $url Param to add an url to click values
- * @return void
- * @deprecated
- */
- function dol_print_graph($htmlid, $width, $height, $data, $showlegend = 0, $type = 'pie', $showpercent = 0, $url = '') {
- global $conf, $langs;
- global $theme_datacolor; // To have var kept when function is called several times
- if (empty($conf->use_javascript_ajax))
- return;
- $jsgraphlib = 'flot';
- $datacolor = array();
- // Load colors of theme into $datacolor array
- $color_file = DOL_DOCUMENT_ROOT . "/theme/" . $conf->theme . "/graph-color.php";
- if (is_readable($color_file)) {
- include_once $color_file;
- if (isset($theme_datacolor)) {
- $datacolor = array();
- foreach ($theme_datacolor as $val) {
- $datacolor[] = "#" . sprintf("%02x", $val[0]) . sprintf("%02x", $val[1]) . sprintf("%02x", $val[2]);
- }
- }
- }
- print '<div id="' . $htmlid . '" style="width:' . $width . 'px;height:' . $height . 'px;"></div>';
- // We use Flot js lib
- if ($jsgraphlib == 'flot') {
- if ($type == 'pie') {
- // data is array('series'=>array(serie1,serie2,...),
- // 'seriestype'=>array('bar','line',...),
- // 'seriescolor'=>array(0=>'#999999',1=>'#999999',...)
- // 'xlabel'=>array(0=>labelx1,1=>labelx2,...));
- // serieX is array('label'=>'label', data=>val)
- print '
- <script type="text/javascript">
- $(function () {
- var data = ' . json_encode($data['series']) . ';
- function plotWithOptions() {
- $.plot($("#' . $htmlid . '"), data,
- {
- series: {
- pie: {
- show: true,
- radius: 3/4,
- label: {
- show: true,
- radius: 3/4,
- formatter: function(label, series) {
- var percent=Math.round(series.percent);
- var number=series.data[0][1];
- return \'';
- print '<div style="font-size:8pt;text-align:center;padding:2px;color:white;">';
- if ($url)
- print '<a style="color: #FFFFFF;" border="0" href="' . $url . '=">';
- print '\'+' . ($showlegend ? 'number' : 'label+\'<br/>\'+number');
- if (!empty($showpercent))
- pr…
Large files files are truncated, but you can click here to view the full file