PageRenderTime 68ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

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

https://bitbucket.org/speedealing/speedealing
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

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

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