dolibarr 19.0.3
functions.lib.php
Go to the documentation of this 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-2022 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-2019 Regis Houssin <regis.houssin@inodbox.com>
9 * Copyright (C) 2008 Raphael Bertrand (Resultic) <raphael.bertrand@resultic.fr>
10 * Copyright (C) 2010-2018 Juanjo Menent <jmenent@2byte.es>
11 * Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr>
12 * Copyright (C) 2013-2021 Alexandre Spangaro <aspangaro@open-dsi.fr>
13 * Copyright (C) 2014 Cédric GROSS <c.gross@kreiz-it.fr>
14 * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
15 * Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
16 * Copyright (C) 2018-2023 Frédéric France <frederic.france@netlogic.fr>
17 * Copyright (C) 2019-2023 Thibault Foucart <support@ptibogxiv.net>
18 * Copyright (C) 2020 Open-Dsi <support@open-dsi.fr>
19 * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
20 * Copyright (C) 2022 Anthony Berton <anthony.berton@bb2a.fr>
21 * Copyright (C) 2022 Ferran Marcet <fmarcet@2byte.es>
22 * Copyright (C) 2022 Charlene Benke <charlene@patas-monkey.com>
23 * Copyright (C) 2023 Joachim Kueter <git-jk@bloxera.com>
24 *
25 * This program is free software; you can redistribute it and/or modify
26 * it under the terms of the GNU General Public License as published by
27 * the Free Software Foundation; either version 3 of the License, or
28 * (at your option) any later version.
29 *
30 * This program is distributed in the hope that it will be useful,
31 * but WITHOUT ANY WARRANTY; without even the implied warranty of
32 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
33 * GNU General Public License for more details.
34 *
35 * You should have received a copy of the GNU General Public License
36 * along with this program. If not, see <https://www.gnu.org/licenses/>.
37 * or see https://www.gnu.org/
38 */
39
46include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
47
48// Function for better PHP x compatibility
49if (!function_exists('utf8_encode')) {
56 function utf8_encode($elements)
57 {
58 return mb_convert_encoding($elements, 'UTF-8', 'ISO-8859-1');
59 }
60}
61
62if (!function_exists('utf8_decode')) {
69 function utf8_decode($elements)
70 {
71 return mb_convert_encoding($elements, 'ISO-8859-1', 'UTF-8');
72 }
73}
74if (!function_exists('str_starts_with')) {
82 function str_starts_with($haystack, $needle)
83 {
84 return (string) $needle !== '' && strncmp($haystack, $needle, strlen($needle)) === 0;
85 }
86}
87if (!function_exists('str_ends_with')) {
95 function str_ends_with($haystack, $needle)
96 {
97 return $needle !== '' && substr($haystack, -strlen($needle)) === (string) $needle;
98 }
99}
100if (!function_exists('str_contains')) {
108 function str_contains($haystack, $needle)
109 {
110 return $needle !== '' && mb_strpos($haystack, $needle) !== false;
111 }
112}
113
114
123function getMultidirOutput($object, $module = '')
124{
125 global $conf;
126
127 if (!is_object($object) && empty($module)) {
128 return null;
129 }
130 if (empty($module) && !empty($object->element)) {
131 $module = $object->element;
132 }
133 // Special case for backward compatibility
134 if ($module == 'fichinter') {
135 $module = 'ficheinter';
136 }
137 if (isset($conf->$module) && property_exists($conf->$module, 'multidir_output')) {
138 return $conf->$module->multidir_output[(empty($object->entity) ? $conf->entity : $object->entity)];
139 } else {
140 return 'error-diroutput-not-defined-for-this-object='.$module;
141 }
142}
143
151function getDolGlobalString($key, $default = '')
152{
153 global $conf;
154 return (string) (isset($conf->global->$key) ? $conf->global->$key : $default);
155}
156
165function getDolGlobalInt($key, $default = 0)
166{
167 global $conf;
168 return (int) (isset($conf->global->$key) ? $conf->global->$key : $default);
169}
170
179function getDolUserString($key, $default = '', $tmpuser = null)
180{
181 if (empty($tmpuser)) {
182 global $user;
183 $tmpuser = $user;
184 }
185
186 return (string) (empty($tmpuser->conf->$key) ? $default : $tmpuser->conf->$key);
187}
188
197function getDolUserInt($key, $default = 0, $tmpuser = null)
198{
199 if (empty($tmpuser)) {
200 global $user;
201 $tmpuser = $user;
202 }
203
204 return (int) (empty($tmpuser->conf->$key) ? $default : $tmpuser->conf->$key);
205}
206
213function isModEnabled($module)
214{
215 global $conf;
216
217 // Fix special cases
218 $arrayconv = array(
219 'bank' => 'banque',
220 'category' => 'categorie',
221 'contract' => 'contrat',
222 'project' => 'projet',
223 'delivery_note' => 'expedition'
224 );
225 if (!getDolGlobalString('MAIN_USE_NEW_SUPPLIERMOD')) {
226 $arrayconv['supplier_order'] = 'fournisseur';
227 $arrayconv['supplier_invoice'] = 'fournisseur';
228 }
229 if (!empty($arrayconv[$module])) {
230 $module = $arrayconv[$module];
231 }
232
233 return !empty($conf->modules[$module]);
234 //return !empty($conf->$module->enabled);
235}
236
248function getDoliDBInstance($type, $host, $user, $pass, $name, $port)
249{
250 require_once DOL_DOCUMENT_ROOT."/core/db/".$type.'.class.php';
251
252 $class = 'DoliDB'.ucfirst($type);
253 $dolidb = new $class($type, $host, $user, $pass, $name, $port);
254 return $dolidb;
255}
256
274function getEntity($element, $shared = 1, $currentobject = null)
275{
276 global $conf, $mc, $hookmanager, $object, $action, $db;
277
278 if (!is_object($hookmanager)) {
279 include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
280 $hookmanager = new HookManager($db);
281 }
282
283 // fix different element names (France to English)
284 switch ($element) {
285 case 'projet':
286 $element = 'project';
287 break;
288 case 'contrat':
289 $element = 'contract';
290 break; // "/contrat/class/contrat.class.php"
291 case 'order_supplier':
292 $element = 'supplier_order';
293 break; // "/fourn/class/fournisseur.commande.class.php"
294 case 'invoice_supplier':
295 $element = 'supplier_invoice';
296 break; // "/fourn/class/fournisseur.facture.class.php"
297 }
298
299 if (is_object($mc)) {
300 $out = $mc->getEntity($element, $shared, $currentobject);
301 } else {
302 $out = '';
303 $addzero = array('user', 'usergroup', 'cronjob', 'c_email_templates', 'email_template', 'default_values', 'overwrite_trans');
304 if (in_array($element, $addzero)) {
305 $out .= '0,';
306 }
307 $out .= ((int) $conf->entity);
308 }
309
310 // Manipulate entities to query on the fly
311 $parameters = array(
312 'element' => $element,
313 'shared' => $shared,
314 'object' => $object,
315 'currentobject' => $currentobject,
316 'out' => $out
317 );
318 $reshook = $hookmanager->executeHooks('hookGetEntity', $parameters, $currentobject, $action); // Note that $action and $object may have been modified by some hooks
319
320 if (is_numeric($reshook)) {
321 if ($reshook == 0 && !empty($hookmanager->resPrint)) {
322 $out .= ','.$hookmanager->resPrint; // add
323 } elseif ($reshook == 1) {
324 $out = $hookmanager->resPrint; // replace
325 }
326 }
327
328 return $out;
329}
330
337function setEntity($currentobject)
338{
339 global $conf, $mc;
340
341 if (is_object($mc) && method_exists($mc, 'setEntity')) {
342 return $mc->setEntity($currentobject);
343 } else {
344 return ((is_object($currentobject) && $currentobject->id > 0 && $currentobject->entity > 0) ? $currentobject->entity : $conf->entity);
345 }
346}
347
354function isASecretKey($keyname)
355{
356 return preg_match('/(_pass|password|_pw|_key|securekey|serverkey|secret\d?|p12key|exportkey|_PW_[a-z]+|token)$/i', $keyname);
357}
358
359
366function num2Alpha($n)
367{
368 for ($r = ""; $n >= 0; $n = intval($n / 26) - 1) {
369 $r = chr($n % 26 + 0x41) . $r;
370 }
371 return $r;
372}
373
374
391function getBrowserInfo($user_agent)
392{
393 include_once DOL_DOCUMENT_ROOT.'/includes/mobiledetect/mobiledetectlib/Mobile_Detect.php';
394
395 $name = 'unknown';
396 $version = '';
397 $os = 'unknown';
398 $phone = '';
399
400 $user_agent = substr($user_agent, 0, 512); // Avoid to process too large user agent
401
402 $detectmobile = new Mobile_Detect(null, $user_agent);
403 $tablet = $detectmobile->isTablet();
404
405 if ($detectmobile->isMobile()) {
406 $phone = 'unknown';
407
408 // If phone/smartphone, we set phone os name.
409 if ($detectmobile->is('AndroidOS')) {
410 $os = $phone = 'android';
411 } elseif ($detectmobile->is('BlackBerryOS')) {
412 $os = $phone = 'blackberry';
413 } elseif ($detectmobile->is('iOS')) {
414 $os = 'ios';
415 $phone = 'iphone';
416 } elseif ($detectmobile->is('PalmOS')) {
417 $os = $phone = 'palm';
418 } elseif ($detectmobile->is('SymbianOS')) {
419 $os = 'symbian';
420 } elseif ($detectmobile->is('webOS')) {
421 $os = 'webos';
422 } elseif ($detectmobile->is('MaemoOS')) {
423 $os = 'maemo';
424 } elseif ($detectmobile->is('WindowsMobileOS') || $detectmobile->is('WindowsPhoneOS')) {
425 $os = 'windows';
426 }
427 }
428
429 // OS
430 if (preg_match('/linux/i', $user_agent)) {
431 $os = 'linux';
432 } elseif (preg_match('/macintosh/i', $user_agent)) {
433 $os = 'macintosh';
434 } elseif (preg_match('/windows/i', $user_agent)) {
435 $os = 'windows';
436 }
437
438 // Name
439 $reg = array();
440 if (preg_match('/firefox(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
441 $name = 'firefox';
442 $version = empty($reg[2]) ? '' : $reg[2];
443 } elseif (preg_match('/edge(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
444 $name = 'edge';
445 $version = empty($reg[2]) ? '' : $reg[2];
446 } elseif (preg_match('/chrome(\/|\s)([\d\.]+)/i', $user_agent, $reg)) {
447 $name = 'chrome';
448 $version = empty($reg[2]) ? '' : $reg[2];
449 } elseif (preg_match('/chrome/i', $user_agent, $reg)) {
450 // we can have 'chrome (Mozilla...) chrome x.y' in one string
451 $name = 'chrome';
452 } elseif (preg_match('/iceweasel/i', $user_agent)) {
453 $name = 'iceweasel';
454 } elseif (preg_match('/epiphany/i', $user_agent)) {
455 $name = 'epiphany';
456 } elseif (preg_match('/safari(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
457 $name = 'safari';
458 $version = empty($reg[2]) ? '' : $reg[2];
459 } elseif (preg_match('/opera(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
460 // Safari is often present in string for mobile but its not.
461 $name = 'opera';
462 $version = empty($reg[2]) ? '' : $reg[2];
463 } elseif (preg_match('/(MSIE\s([0-9]+\.[0-9]))|.*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
464 $name = 'ie';
465 $version = end($reg);
466 } elseif (preg_match('/(Windows NT\s([0-9]+\.[0-9])).*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
467 // MS products at end
468 $name = 'ie';
469 $version = end($reg);
470 } elseif (preg_match('/l[iy]n(x|ks)(\‍(|\/|\s)*([\d\.]+)/i', $user_agent, $reg)) {
471 // MS products at end
472 $name = 'lynxlinks';
473 $version = empty($reg[3]) ? '' : $reg[3];
474 }
475
476 if ($tablet) {
477 $layout = 'tablet';
478 } elseif ($phone) {
479 $layout = 'phone';
480 } else {
481 $layout = 'classic';
482 }
483
484 return array(
485 'browsername' => $name,
486 'browserversion' => $version,
487 'browseros' => $os,
488 'browserua' => $user_agent,
489 'layout' => $layout, // tablet, phone, classic
490 'phone' => $phone, // deprecated
491 'tablet' => $tablet // deprecated
492 );
493}
494
500function dol_shutdown()
501{
502 global $db;
503 $disconnectdone = false;
504 $depth = 0;
505 if (is_object($db) && !empty($db->connected)) {
506 $depth = $db->transaction_opened;
507 $disconnectdone = $db->close();
508 }
509 dol_syslog("--- End access to ".(empty($_SERVER["PHP_SELF"]) ? 'unknown' : $_SERVER["PHP_SELF"]).(($disconnectdone && $depth) ? ' (Warn: db disconnection forced, transaction depth was '.$depth.')' : ''), (($disconnectdone && $depth) ? LOG_WARNING : LOG_INFO));
510}
511
521function GETPOSTISSET($paramname)
522{
523 $isset = false;
524
525 $relativepathstring = $_SERVER["PHP_SELF"];
526 // Clean $relativepathstring
527 if (constant('DOL_URL_ROOT')) {
528 $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
529 }
530 $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
531 $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
532 //var_dump($relativepathstring);
533 //var_dump($user->default_values);
534
535 // Code for search criteria persistence.
536 // Retrieve values if restore_lastsearch_values
537 if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
538 if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
539 $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
540 if (is_array($tmp)) {
541 foreach ($tmp as $key => $val) {
542 if ($key == $paramname) { // We are on the requested parameter
543 $isset = true;
544 break;
545 }
546 }
547 }
548 }
549 // If there is saved contextpage, limit, page or mode
550 if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
551 $isset = true;
552 } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
553 $isset = true;
554 } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
555 $isset = true;
556 } elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_'.$relativepathstring])) {
557 $isset = true;
558 }
559 } else {
560 $isset = (isset($_POST[$paramname]) || isset($_GET[$paramname])); // We must keep $_POST and $_GET here
561 }
562
563 return $isset;
564}
565
574function GETPOSTISARRAY($paramname, $method = 0)
575{
576 // for $method test need return the same $val as GETPOST
577 if (empty($method)) {
578 $val = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
579 } elseif ($method == 1) {
580 $val = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
581 } elseif ($method == 2) {
582 $val = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
583 } elseif ($method == 3) {
584 $val = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
585 } else {
586 $val = 'BadFirstParameterForGETPOST';
587 }
588
589 return is_array($val);
590}
591
621function GETPOST($paramname, $check = 'alphanohtml', $method = 0, $filter = null, $options = null, $noreplace = 0)
622{
623 global $mysoc, $user, $conf;
624
625 if (empty($paramname)) {
626 return 'BadFirstParameterForGETPOST';
627 }
628 if (empty($check)) {
629 dol_syslog("Deprecated use of GETPOST, called with 1st param = ".$paramname." and a 2nd param that is '', when calling page ".$_SERVER["PHP_SELF"], LOG_WARNING);
630 // Enable this line to know who call the GETPOST with '' $check parameter.
631 //var_dump(debug_backtrace()[0]);
632 }
633
634 if (empty($method)) {
635 $out = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
636 } elseif ($method == 1) {
637 $out = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
638 } elseif ($method == 2) {
639 $out = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
640 } elseif ($method == 3) {
641 $out = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
642 } else {
643 return 'BadThirdParameterForGETPOST';
644 }
645
646 if (empty($method) || $method == 3 || $method == 4) {
647 $relativepathstring = (empty($_SERVER["PHP_SELF"]) ? '' : $_SERVER["PHP_SELF"]);
648 // Clean $relativepathstring
649 if (constant('DOL_URL_ROOT')) {
650 $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
651 }
652 $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
653 $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
654 //var_dump($relativepathstring);
655 //var_dump($user->default_values);
656
657 // Code for search criteria persistence.
658 // Retrieve saved values if restore_lastsearch_values is set
659 if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
660 if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
661 $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
662 if (is_array($tmp)) {
663 foreach ($tmp as $key => $val) {
664 if ($key == $paramname) { // We are on the requested parameter
665 $out = $val;
666 break;
667 }
668 }
669 }
670 }
671 // If there is saved contextpage, page or limit
672 if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
673 $out = $_SESSION['lastsearch_contextpage_'.$relativepathstring];
674 } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
675 $out = $_SESSION['lastsearch_limit_'.$relativepathstring];
676 } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
677 $out = $_SESSION['lastsearch_page_'.$relativepathstring];
678 } elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_'.$relativepathstring])) {
679 $out = $_SESSION['lastsearch_mode_'.$relativepathstring];
680 }
681 } elseif (!isset($_GET['sortfield'])) {
682 // Else, retrieve default values if we are not doing a sort
683 // If we did a click on a field to sort, we do no apply default values. Same if option MAIN_ENABLE_DEFAULT_VALUES is not set
684 if (!empty($_GET['action']) && $_GET['action'] == 'create' && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
685 // Search default value from $object->field
686 global $object;
687 if (is_object($object) && isset($object->fields[$paramname]['default'])) {
688 $out = $object->fields[$paramname]['default'];
689 }
690 }
691 if (getDolGlobalString('MAIN_ENABLE_DEFAULT_VALUES')) {
692 if (!empty($_GET['action']) && (preg_match('/^create/', $_GET['action']) || preg_match('/^presend/', $_GET['action'])) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
693 // Now search in setup to overwrite default values
694 if (!empty($user->default_values)) { // $user->default_values defined from menu 'Setup - Default values'
695 if (isset($user->default_values[$relativepathstring]['createform'])) {
696 foreach ($user->default_values[$relativepathstring]['createform'] as $defkey => $defval) {
697 $qualified = 0;
698 if ($defkey != '_noquery_') {
699 $tmpqueryarraytohave = explode('&', $defkey);
700 $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
701 $foundintru = 0;
702 foreach ($tmpqueryarraytohave as $tmpquerytohave) {
703 if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
704 $foundintru = 1;
705 }
706 }
707 if (!$foundintru) {
708 $qualified = 1;
709 }
710 //var_dump($defkey.'-'.$qualified);
711 } else {
712 $qualified = 1;
713 }
714
715 if ($qualified) {
716 if (isset($user->default_values[$relativepathstring]['createform'][$defkey][$paramname])) {
717 $out = $user->default_values[$relativepathstring]['createform'][$defkey][$paramname];
718 break;
719 }
720 }
721 }
722 }
723 }
724 } elseif (!empty($paramname) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
725 // Management of default search_filters and sort order
726 if (!empty($user->default_values)) {
727 // $user->default_values defined from menu 'Setup - Default values'
728 //var_dump($user->default_values[$relativepathstring]);
729 if ($paramname == 'sortfield' || $paramname == 'sortorder') {
730 // Sorted on which fields ? ASC or DESC ?
731 if (isset($user->default_values[$relativepathstring]['sortorder'])) {
732 // Even if paramname is sortfield, data are stored into ['sortorder...']
733 foreach ($user->default_values[$relativepathstring]['sortorder'] as $defkey => $defval) {
734 $qualified = 0;
735 if ($defkey != '_noquery_') {
736 $tmpqueryarraytohave = explode('&', $defkey);
737 $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
738 $foundintru = 0;
739 foreach ($tmpqueryarraytohave as $tmpquerytohave) {
740 if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
741 $foundintru = 1;
742 }
743 }
744 if (!$foundintru) {
745 $qualified = 1;
746 }
747 //var_dump($defkey.'-'.$qualified);
748 } else {
749 $qualified = 1;
750 }
751
752 if ($qualified) {
753 $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
754 foreach ($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val) {
755 if ($out) {
756 $out .= ', ';
757 }
758 if ($paramname == 'sortfield') {
759 $out .= dol_string_nospecial($key, '', $forbidden_chars_to_replace);
760 }
761 if ($paramname == 'sortorder') {
762 $out .= dol_string_nospecial($val, '', $forbidden_chars_to_replace);
763 }
764 }
765 //break; // No break for sortfield and sortorder so we can cumulate fields (is it realy usefull ?)
766 }
767 }
768 }
769 } elseif (isset($user->default_values[$relativepathstring]['filters'])) {
770 foreach ($user->default_values[$relativepathstring]['filters'] as $defkey => $defval) { // $defkey is a querystring like 'a=b&c=d', $defval is key of user
771 if (!empty($_GET['disabledefaultvalues'])) { // If set of default values has been disabled by a request parameter
772 continue;
773 }
774 $qualified = 0;
775 if ($defkey != '_noquery_') {
776 $tmpqueryarraytohave = explode('&', $defkey);
777 $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
778 $foundintru = 0;
779 foreach ($tmpqueryarraytohave as $tmpquerytohave) {
780 if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
781 $foundintru = 1;
782 }
783 }
784 if (!$foundintru) {
785 $qualified = 1;
786 }
787 //var_dump($defkey.'-'.$qualified);
788 } else {
789 $qualified = 1;
790 }
791
792 if ($qualified && isset($user->default_values[$relativepathstring]['filters'][$defkey][$paramname])) {
793 // We must keep $_POST and $_GET here
794 if (isset($_POST['sall']) || isset($_POST['search_all']) || isset($_GET['sall']) || isset($_GET['search_all'])) {
795 // We made a search from quick search menu, do we still use default filter ?
796 if (!getDolGlobalString('MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH')) {
797 $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
798 $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
799 }
800 } else {
801 $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
802 $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
803 }
804 break;
805 }
806 }
807 }
808 }
809 }
810 }
811 }
812 }
813
814 // Substitution variables for GETPOST (used to get final url with variable parameters or final default value, when using variable parameters __XXX__ in the GET URL)
815 // Example of variables: __DAY__, __MONTH__, __YEAR__, __MYCOMPANY_COUNTRY_ID__, __USER_ID__, ...
816 // We do this only if var is a GET. If it is a POST, may be we want to post the text with vars as the setup text.
817 if (!is_array($out) && empty($_POST[$paramname]) && empty($noreplace)) {
818 $reg = array();
819 $maxloop = 20;
820 $loopnb = 0; // Protection against infinite loop
821 while (preg_match('/__([A-Z0-9]+_?[A-Z0-9]+)__/i', $out, $reg) && ($loopnb < $maxloop)) { // Detect '__ABCDEF__' as key 'ABCDEF' and '__ABC_DEF__' as key 'ABC_DEF'. Detection is also correct when 2 vars are side by side.
822 $loopnb++;
823 $newout = '';
824
825 if ($reg[1] == 'DAY') {
826 $tmp = dol_getdate(dol_now(), true);
827 $newout = $tmp['mday'];
828 } elseif ($reg[1] == 'MONTH') {
829 $tmp = dol_getdate(dol_now(), true);
830 $newout = $tmp['mon'];
831 } elseif ($reg[1] == 'YEAR') {
832 $tmp = dol_getdate(dol_now(), true);
833 $newout = $tmp['year'];
834 } elseif ($reg[1] == 'PREVIOUS_DAY') {
835 $tmp = dol_getdate(dol_now(), true);
836 $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
837 $newout = $tmp2['day'];
838 } elseif ($reg[1] == 'PREVIOUS_MONTH') {
839 $tmp = dol_getdate(dol_now(), true);
840 $tmp2 = dol_get_prev_month($tmp['mon'], $tmp['year']);
841 $newout = $tmp2['month'];
842 } elseif ($reg[1] == 'PREVIOUS_YEAR') {
843 $tmp = dol_getdate(dol_now(), true);
844 $newout = ($tmp['year'] - 1);
845 } elseif ($reg[1] == 'NEXT_DAY') {
846 $tmp = dol_getdate(dol_now(), true);
847 $tmp2 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
848 $newout = $tmp2['day'];
849 } elseif ($reg[1] == 'NEXT_MONTH') {
850 $tmp = dol_getdate(dol_now(), true);
851 $tmp2 = dol_get_next_month($tmp['mon'], $tmp['year']);
852 $newout = $tmp2['month'];
853 } elseif ($reg[1] == 'NEXT_YEAR') {
854 $tmp = dol_getdate(dol_now(), true);
855 $newout = ($tmp['year'] + 1);
856 } elseif ($reg[1] == 'MYCOMPANY_COUNTRY_ID' || $reg[1] == 'MYCOUNTRY_ID' || $reg[1] == 'MYCOUNTRYID') {
857 $newout = $mysoc->country_id;
858 } elseif ($reg[1] == 'USER_ID' || $reg[1] == 'USERID') {
859 $newout = $user->id;
860 } elseif ($reg[1] == 'USER_SUPERVISOR_ID' || $reg[1] == 'SUPERVISOR_ID' || $reg[1] == 'SUPERVISORID') {
861 $newout = $user->fk_user;
862 } elseif ($reg[1] == 'ENTITY_ID' || $reg[1] == 'ENTITYID') {
863 $newout = $conf->entity;
864 } else {
865 $newout = ''; // Key not found, we replace with empty string
866 }
867 //var_dump('__'.$reg[1].'__ -> '.$newout);
868 $out = preg_replace('/__'.preg_quote($reg[1], '/').'__/', $newout, $out);
869 }
870 }
871
872 // Check type of variable and make sanitization according to this
873 if (preg_match('/^array/', $check)) { // If 'array' or 'array:restricthtml' or 'array:aZ09' or 'array:intcomma'
874 if (!is_array($out) || empty($out)) {
875 $out = array();
876 } else {
877 $tmparray = explode(':', $check);
878 if (!empty($tmparray[1])) {
879 $tmpcheck = $tmparray[1];
880 } else {
881 $tmpcheck = 'alphanohtml';
882 }
883 foreach ($out as $outkey => $outval) {
884 $out[$outkey] = sanitizeVal($outval, $tmpcheck, $filter, $options);
885 }
886 }
887 } else {
888 // If field name is 'search_xxx' then we force the add of space after each < and > (when following char is numeric) because it means
889 // we use the < or > to make a search on a numeric value to do higher or lower so we can add a space to break html tags
890 if (strpos($paramname, 'search_') === 0) {
891 $out = preg_replace('/([<>])([-+]?\d)/', '\1 \2', $out);
892 }
893
894 $out = sanitizeVal($out, $check, $filter, $options);
895 }
896
897 // Sanitizing for special parameters.
898 // Note: There is no reason to allow the backtopage, backtolist or backtourl parameter to contains an external URL. Only relative URLs are allowed.
899 if ($paramname == 'backtopage' || $paramname == 'backtolist' || $paramname == 'backtourl') {
900 $out = str_replace('\\', '/', $out); // Can be before the loop because only 1 char is replaced. No risk to get it after other replacements.
901 $out = str_replace(array(':', ';', '@', "\t", ' '), '', $out); // Can be before the loop because only 1 char is replaced. No risk to retreive it after other replacements.
902 do {
903 $oldstringtoclean = $out;
904 $out = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $out);
905 $out = preg_replace(array('/^[^\?]*%/'), '', $out); // We remove any % chars before the ?. Example in url: '/product/stock/card.php?action=create&backtopage=%2Fdolibarr_dev%2Fhtdocs%2Fpro%25duct%2Fcard.php%3Fid%3Dabc'
906 $out = preg_replace(array('/^[a-z]*\/\s*\/+/i'), '', $out); // We remove schema*// to remove external URL
907 } while ($oldstringtoclean != $out);
908 }
909
910 // Code for search criteria persistence.
911 // Save data into session if key start with 'search_' or is 'smonth', 'syear', 'month', 'year'
912 if (empty($method) || $method == 3 || $method == 4) {
913 if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder', 'sortfield'))) {
914 //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]);
915
916 // We save search key only if $out not empty that means:
917 // - posted value not empty, or
918 // - if posted value is empty and a default value exists that is not empty (it means we did a filter to an empty value when default was not).
919
920 if ($out != '' && isset($user)) {// $out = '0' or 'abc', it is a search criteria to keep
921 $user->lastsearch_values_tmp[$relativepathstring][$paramname] = $out;
922 }
923 }
924 }
925
926 return $out;
927}
928
938function GETPOSTINT($paramname, $method = 0)
939{
940 return (int) GETPOST($paramname, 'int', $method, null, null, 0);
941}
942
943
954function checkVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
955{
956 return sanitizeVal($out, $check, $filter, $options);
957}
958
968function sanitizeVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
969{
970 // TODO : use class "Validate" to perform tests (and add missing tests) if needed for factorize
971 // Check is done after replacement
972 switch ($check) {
973 case 'none':
974 break;
975 case 'int': // Check param is a numeric value (integer but also float or hexadecimal)
976 if (!is_numeric($out)) {
977 $out = '';
978 }
979 break;
980 case 'intcomma':
981 if (is_array($out)) {
982 $out = implode(',', $out);
983 }
984 if (preg_match('/[^0-9,-]+/i', $out)) {
985 $out = '';
986 }
987 break;
988 case 'san_alpha':
989 $out = filter_var($out, FILTER_SANITIZE_STRING);
990 break;
991 case 'email':
992 $out = filter_var($out, FILTER_SANITIZE_EMAIL);
993 break;
994 case 'aZ':
995 if (!is_array($out)) {
996 $out = trim($out);
997 if (preg_match('/[^a-z]+/i', $out)) {
998 $out = '';
999 }
1000 }
1001 break;
1002 case 'aZ09':
1003 if (!is_array($out)) {
1004 $out = trim($out);
1005 if (preg_match('/[^a-z0-9_\-\.]+/i', $out)) {
1006 $out = '';
1007 }
1008 }
1009 break;
1010 case 'aZ09arobase': // great to sanitize $objecttype parameter
1011 if (!is_array($out)) {
1012 $out = trim($out);
1013 if (preg_match('/[^a-z0-9_\-\.@]+/i', $out)) {
1014 $out = '';
1015 }
1016 }
1017 break;
1018 case 'aZ09comma': // great to sanitize $sortfield or $sortorder params that can be 't.abc,t.def_gh'
1019 if (!is_array($out)) {
1020 $out = trim($out);
1021 if (preg_match('/[^a-z0-9_\-\.,]+/i', $out)) {
1022 $out = '';
1023 }
1024 }
1025 break;
1026 case 'alpha': // No html and no ../ and "
1027 case 'alphanohtml': // Recommended for most scalar parameters and search parameters
1028 if (!is_array($out)) {
1029 $out = trim($out);
1030 do {
1031 $oldstringtoclean = $out;
1032 // Remove html tags
1033 $out = dol_string_nohtmltag($out, 0);
1034 // Remove also other dangerous string sequences
1035 // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
1036 // '../' or '..\' is dangerous because it allows dir transversals
1037 // Note &#38, '&#0000038', '&#x26'... is a simple char like '&' alone but there is no reason to accept such way to encode input data.
1038 $out = str_ireplace(array('&#38', '&#0000038', '&#x26', '&quot', '&#34', '&#0000034', '&#x22', '"', '&#47', '&#0000047', '&#92', '&#0000092', '&#x2F', '../', '..\\'), '', $out);
1039 } while ($oldstringtoclean != $out);
1040 // keep lines feed
1041 }
1042 break;
1043 case 'alphawithlgt': // No " and no ../ but we keep balanced < > tags with no special chars inside. Can be used for email string like "Name <email>". Less secured than 'alphanohtml'
1044 if (!is_array($out)) {
1045 $out = trim($out);
1046 do {
1047 $oldstringtoclean = $out;
1048 // Remove html tags
1049 $out = dol_html_entity_decode($out, ENT_COMPAT | ENT_HTML5, 'UTF-8');
1050 // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
1051 // '../' or '..\' is dangerous because it allows dir transversals
1052 // Note &#38, '&#0000038', '&#x26'... is a simple char like '&' alone but there is no reason to accept such way to encode input data.
1053 $out = str_ireplace(array('&#38', '&#0000038', '&#x26', '&quot', '&#34', '&#0000034', '&#x22', '"', '&#47', '&#0000047', '&#92', '&#0000092', '&#x2F', '../', '..\\'), '', $out);
1054 } while ($oldstringtoclean != $out);
1055 }
1056 break;
1057 case 'nohtml': // No html
1058 $out = dol_string_nohtmltag($out, 0);
1059 break;
1060 case 'restricthtmlnolink':
1061 case 'restricthtml': // Recommended for most html textarea
1062 case 'restricthtmlallowclass':
1063 case 'restricthtmlallowunvalid':
1064 $out = dol_htmlwithnojs($out, 1, $check);
1065 break;
1066 case 'custom':
1067 if (!empty($out)) {
1068 if (empty($filter)) {
1069 return 'BadParameterForGETPOST - Param 3 of sanitizeVal()';
1070 }
1071 /*if (empty($options)) {
1072 return 'BadParameterForGETPOST - Param 4 of sanitizeVal()';
1073 }*/
1074 $out = filter_var($out, $filter, $options);
1075 }
1076 break;
1077 default:
1078 dol_syslog("Error, you call sanitizeVal() with a bad value for the check type. Data can't be sanitized.", LOG_ERR);
1079 break;
1080 }
1081
1082 return $out;
1083}
1084
1085
1086if (!function_exists('dol_getprefix')) {
1096 function dol_getprefix($mode = '')
1097 {
1098 // If prefix is for email (we need to have $conf already loaded for this case)
1099 if ($mode == 'email') {
1100 global $conf;
1101
1102 if (getDolGlobalString('MAIL_PREFIX_FOR_EMAIL_ID')) { // If MAIL_PREFIX_FOR_EMAIL_ID is set
1103 if (getDolGlobalString('MAIL_PREFIX_FOR_EMAIL_ID') != 'SERVER_NAME') {
1104 return $conf->global->MAIL_PREFIX_FOR_EMAIL_ID;
1105 } elseif (isset($_SERVER["SERVER_NAME"])) { // If MAIL_PREFIX_FOR_EMAIL_ID is set to 'SERVER_NAME'
1106 return $_SERVER["SERVER_NAME"];
1107 }
1108 }
1109
1110 // The recommended value if MAIL_PREFIX_FOR_EMAIL_ID is not defined (may be not defined for old versions)
1111 if (!empty($conf->file->instance_unique_id)) {
1112 return sha1('dolibarr'.$conf->file->instance_unique_id);
1113 }
1114
1115 // For backward compatibility when instance_unique_id is not set
1116 return sha1(DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
1117 }
1118
1119 // If prefix is for session (no need to have $conf loaded)
1120 global $dolibarr_main_instance_unique_id, $dolibarr_main_cookie_cryptkey; // This is loaded by filefunc.inc.php
1121 $tmp_instance_unique_id = empty($dolibarr_main_instance_unique_id) ? (empty($dolibarr_main_cookie_cryptkey) ? '' : $dolibarr_main_cookie_cryptkey) : $dolibarr_main_instance_unique_id; // Unique id of instance
1122
1123 // The recommended value (may be not defined for old versions)
1124 if (!empty($tmp_instance_unique_id)) {
1125 return sha1('dolibarr'.$tmp_instance_unique_id);
1126 }
1127
1128 // For backward compatibility when instance_unique_id is not set
1129 if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"])) {
1130 return sha1($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
1131 } else {
1132 return sha1(DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
1133 }
1134 }
1135}
1136
1147function dol_include_once($relpath, $classname = '')
1148{
1149 global $conf, $langs, $user, $mysoc; // Do not remove this. They must be defined for files we include. Other globals var must be retrieved with $GLOBALS['var']
1150
1151 $fullpath = dol_buildpath($relpath);
1152
1153 if (!file_exists($fullpath)) {
1154 dol_syslog('functions::dol_include_once Tried to load unexisting file: '.$relpath, LOG_WARNING);
1155 return false;
1156 }
1157
1158 if (!empty($classname) && !class_exists($classname)) {
1159 return include $fullpath;
1160 } else {
1161 return include_once $fullpath;
1162 }
1163}
1164
1165
1176function dol_buildpath($path, $type = 0, $returnemptyifnotfound = 0)
1177{
1178 global $conf;
1179
1180 $path = preg_replace('/^\//', '', $path);
1181
1182 if (empty($type)) { // For a filesystem path
1183 $res = DOL_DOCUMENT_ROOT.'/'.$path; // Standard default path
1184 if (is_array($conf->file->dol_document_root)) {
1185 foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array("main"=>"/home/main/htdocs", "alt0"=>"/home/dirmod/htdocs", ...)
1186 if ($key == 'main') {
1187 continue;
1188 }
1189 // if (@file_exists($dirroot.'/'.$path)) {
1190 if (@file_exists($dirroot.'/'.$path)) { // avoid [php:warn]
1191 $res = $dirroot.'/'.$path;
1192 return $res;
1193 }
1194 }
1195 }
1196 if ($returnemptyifnotfound) {
1197 // Not found into alternate dir
1198 if ($returnemptyifnotfound == 1 || !file_exists($res)) {
1199 return '';
1200 }
1201 }
1202 } else {
1203 // For an url path
1204 // We try to get local path of file on filesystem from url
1205 // Note that trying to know if a file on disk exist by forging path on disk from url
1206 // works only for some web server and some setup. This is bugged when
1207 // using proxy, rewriting, virtual path, etc...
1208 $res = '';
1209 if ($type == 1) {
1210 $res = DOL_URL_ROOT.'/'.$path; // Standard value
1211 }
1212 if ($type == 2) {
1213 $res = DOL_MAIN_URL_ROOT.'/'.$path; // Standard value
1214 }
1215 if ($type == 3) {
1216 $res = DOL_URL_ROOT.'/'.$path;
1217 }
1218
1219 foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
1220 if ($key == 'main') {
1221 if ($type == 3) {
1222 /*global $dolibarr_main_url_root;*/
1223
1224 // Define $urlwithroot
1225 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($conf->file->dol_main_url_root));
1226 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
1227 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
1228
1229 $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : $urlwithroot).'/'.$path; // Test on start with http is for old conf syntax
1230 }
1231 continue;
1232 }
1233 $regs = array();
1234 preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i', $path, $regs); // Take part before '?'
1235 if (!empty($regs[1])) {
1236 //print $key.'-'.$dirroot.'/'.$path.'-'.$conf->file->dol_url_root[$type].'<br>'."\n";
1237 //if (file_exists($dirroot.'/'.$regs[1])) {
1238 if (@file_exists($dirroot.'/'.$regs[1])) { // avoid [php:warn]
1239 if ($type == 1) {
1240 $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
1241 }
1242 if ($type == 2) {
1243 $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_MAIN_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
1244 }
1245 if ($type == 3) {
1246 /*global $dolibarr_main_url_root;*/
1247
1248 // Define $urlwithroot
1249 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($conf->file->dol_main_url_root));
1250 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
1251 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
1252
1253 $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : $urlwithroot).$conf->file->dol_url_root[$key].'/'.$path; // Test on start with http is for old conf syntax
1254 }
1255 break;
1256 }
1257 }
1258 }
1259 }
1260
1261 return $res;
1262}
1263
1275function dol_clone($object, $native = 0)
1276{
1277 if ($native == 0) {
1278 // deprecated method, use the method with native = 2 instead
1279 $tmpsavdb = null;
1280 if (isset($object->db) && isset($object->db->db) && is_object($object->db->db) && get_class($object->db->db) == 'PgSql\Connection') {
1281 $tmpsavdb = $object->db;
1282 unset($object->db); // Such property can not be serialized with pgsl (when object->db->db = 'PgSql\Connection')
1283 }
1284
1285 $myclone = unserialize(serialize($object)); // serialize then unserialize is a hack to be sure to have a new object for all fields
1286
1287 if (!empty($tmpsavdb)) {
1288 $object->db = $tmpsavdb;
1289 }
1290 } elseif ($native == 2) {
1291 // recommended method to have a full isolated cloned object
1292 $myclone = new stdClass();
1293 $tmparray = get_object_vars($object); // return only public properties
1294
1295 if (is_array($tmparray)) {
1296 foreach ($tmparray as $propertykey => $propertyval) {
1297 if (is_scalar($propertyval) || is_array($propertyval)) {
1298 $myclone->$propertykey = $propertyval;
1299 }
1300 }
1301 }
1302 } else {
1303 $myclone = clone $object; // PHP clone is a shallow copy only, not a real clone, so properties of references will keep the reference (refering to the same target/variable)
1304 }
1305
1306 return $myclone;
1307}
1308
1318function dol_size($size, $type = '')
1319{
1320 global $conf;
1321 if (empty($conf->dol_optimize_smallscreen)) {
1322 return $size;
1323 }
1324 if ($type == 'width' && $size > 250) {
1325 return 250;
1326 } else {
1327 return 10;
1328 }
1329}
1330
1331
1343function dol_sanitizeFileName($str, $newstr = '_', $unaccent = 1)
1344{
1345 // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
1346 // Char '>' '<' '|' '$' and ';' are special chars for shells.
1347 // Char '/' and '\' are file delimiters.
1348 // Chars '--' can be used into filename to inject special paramaters like --use-compress-program to make command with file as parameter making remote execution of command
1349 $filesystem_forbidden_chars = array('<', '>', '/', '\\', '?', '*', '|', '"', ':', '°', '$', ';', '`');
1350 $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
1351 $tmp = preg_replace('/\-\-+/', '_', $tmp);
1352 $tmp = preg_replace('/\s+\-([^\s])/', ' _$1', $tmp);
1353 $tmp = preg_replace('/\s+\-$/', '', $tmp);
1354 $tmp = str_replace('..', '', $tmp);
1355 return $tmp;
1356}
1357
1369function dol_sanitizePathName($str, $newstr = '_', $unaccent = 1)
1370{
1371 // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
1372 // Char '>' '<' '|' '$' and ';' are special chars for shells.
1373 // Chars '--' can be used into filename to inject special paramaters like --use-compress-program to make command with file as parameter making remote execution of command
1374 $filesystem_forbidden_chars = array('<', '>', '?', '*', '|', '"', '°', '$', ';', '`');
1375 $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
1376 $tmp = preg_replace('/\-\-+/', '_', $tmp);
1377 $tmp = preg_replace('/\s+\-([^\s])/', ' _$1', $tmp);
1378 $tmp = preg_replace('/\s+\-$/', '', $tmp);
1379 $tmp = str_replace('..', '', $tmp);
1380 return $tmp;
1381}
1382
1390function dol_sanitizeUrl($stringtoclean, $type = 1)
1391{
1392 // We clean string because some hacks try to obfuscate evil strings by inserting non printable chars. Example: 'java(ascci09)scr(ascii00)ipt' is processed like 'javascript' (whatever is place of evil ascii char)
1393 // We should use dol_string_nounprintableascii but function may not be yet loaded/available
1394 $stringtoclean = preg_replace('/[\x00-\x1F\x7F]/u', '', $stringtoclean); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
1395 // We clean html comments because some hacks try to obfuscate evil strings by inserting HTML comments. Example: on<!-- -->error=alert(1)
1396 $stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
1397
1398 $stringtoclean = str_replace('\\', '/', $stringtoclean);
1399 if ($type == 1) {
1400 // removing : should disable links to external url like http:aaa)
1401 // removing ';' should disable "named" html entities encode into an url (we should not have this into an url)
1402 $stringtoclean = str_replace(array(':', ';', '@'), '', $stringtoclean);
1403 }
1404
1405 do {
1406 $oldstringtoclean = $stringtoclean;
1407 // removing '&colon' should disable links to external url like http:aaa)
1408 // removing '&#' should disable "numeric" html entities encode into an url (we should not have this into an url)
1409 $stringtoclean = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $stringtoclean);
1410 } while ($oldstringtoclean != $stringtoclean);
1411
1412 if ($type == 1) {
1413 // removing '//' should disable links to external url like //aaa or http//)
1414 $stringtoclean = preg_replace(array('/^[a-z]*\/\/+/i'), '', $stringtoclean);
1415 }
1416
1417 return $stringtoclean;
1418}
1419
1426function dol_sanitizeEmail($stringtoclean)
1427{
1428 do {
1429 $oldstringtoclean = $stringtoclean;
1430 $stringtoclean = str_ireplace(array('"', ':', '[', ']',"\n", "\r", '\\', '\/'), '', $stringtoclean);
1431 } while ($oldstringtoclean != $stringtoclean);
1432
1433 return $stringtoclean;
1434}
1435
1445{
1446 global $conf;
1447
1448 if (is_null($str)) {
1449 return '';
1450 }
1451
1452 if (utf8_check($str)) {
1453 if (extension_loaded('intl') && getDolGlobalString('MAIN_UNACCENT_USE_TRANSLITERATOR')) {
1454 $transliterator = Transliterator::createFromRules(':: Any-Latin; :: Latin-ASCII; :: NFD; :: [:Nonspacing Mark:] Remove; :: NFC;', Transliterator::FORWARD);
1455 return $transliterator->transliterate($str);
1456 }
1457 // See http://www.utf8-chartable.de/
1458 $string = rawurlencode($str);
1459 $replacements = array(
1460 '%C3%80' => 'A', '%C3%81' => 'A', '%C3%82' => 'A', '%C3%83' => 'A', '%C3%84' => 'A', '%C3%85' => 'A',
1461 '%C3%87' => 'C',
1462 '%C3%88' => 'E', '%C3%89' => 'E', '%C3%8A' => 'E', '%C3%8B' => 'E',
1463 '%C3%8C' => 'I', '%C3%8D' => 'I', '%C3%8E' => 'I', '%C3%8F' => 'I',
1464 '%C3%91' => 'N',
1465 '%C3%92' => 'O', '%C3%93' => 'O', '%C3%94' => 'O', '%C3%95' => 'O', '%C3%96' => 'O',
1466 '%C5%A0' => 'S',
1467 '%C3%99' => 'U', '%C3%9A' => 'U', '%C3%9B' => 'U', '%C3%9C' => 'U',
1468 '%C3%9D' => 'Y', '%C5%B8' => 'y',
1469 '%C3%A0' => 'a', '%C3%A1' => 'a', '%C3%A2' => 'a', '%C3%A3' => 'a', '%C3%A4' => 'a', '%C3%A5' => 'a',
1470 '%C3%A7' => 'c',
1471 '%C3%A8' => 'e', '%C3%A9' => 'e', '%C3%AA' => 'e', '%C3%AB' => 'e',
1472 '%C3%AC' => 'i', '%C3%AD' => 'i', '%C3%AE' => 'i', '%C3%AF' => 'i',
1473 '%C3%B1' => 'n',
1474 '%C3%B2' => 'o', '%C3%B3' => 'o', '%C3%B4' => 'o', '%C3%B5' => 'o', '%C3%B6' => 'o',
1475 '%C5%A1' => 's',
1476 '%C3%B9' => 'u', '%C3%BA' => 'u', '%C3%BB' => 'u', '%C3%BC' => 'u',
1477 '%C3%BD' => 'y', '%C3%BF' => 'y'
1478 );
1479 $string = strtr($string, $replacements);
1480 return rawurldecode($string);
1481 } else {
1482 // See http://www.ascii-code.com/
1483 $string = strtr(
1484 $str,
1485 "\xC0\xC1\xC2\xC3\xC4\xC5\xC7
1486 \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
1487 \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
1488 \xE0\xE1\xE2\xE3\xE4\xE5\xE7\xE8\xE9\xEA\xEB
1489 \xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
1490 \xF9\xFA\xFB\xFC\xFD\xFF",
1491 "AAAAAAC
1492 EEEEIIIIDN
1493 OOOOOUUUY
1494 aaaaaaceeee
1495 iiiidnooooo
1496 uuuuyy"
1497 );
1498 $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"));
1499 return $string;
1500 }
1501}
1502
1516function dol_string_nospecial($str, $newstr = '_', $badcharstoreplace = '', $badcharstoremove = '', $keepspaces = 0)
1517{
1518 $forbidden_chars_to_replace = array("'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°', '$', ';'); // more complete than dol_sanitizeFileName
1519 if (empty($keepspaces)) {
1520 $forbidden_chars_to_replace[] = " ";
1521 }
1522 $forbidden_chars_to_remove = array();
1523 //$forbidden_chars_to_remove=array("(",")");
1524
1525 if (is_array($badcharstoreplace)) {
1526 $forbidden_chars_to_replace = $badcharstoreplace;
1527 }
1528 if (is_array($badcharstoremove)) {
1529 $forbidden_chars_to_remove = $badcharstoremove;
1530 }
1531
1532 return str_replace($forbidden_chars_to_replace, $newstr, str_replace($forbidden_chars_to_remove, "", $str));
1533}
1534
1535
1549function dol_string_nounprintableascii($str, $removetabcrlf = 1)
1550{
1551 if ($removetabcrlf) {
1552 return preg_replace('/[\x00-\x1F\x7F]/u', '', $str); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
1553 } else {
1554 return preg_replace('/[\x00-\x08\x11-\x12\x14-\x1F\x7F]/u', '', $str); // /u operator should make UTF8 valid characters being ignored so are not included into the replace
1555 }
1556}
1557
1566function dol_escape_js($stringtoescape, $mode = 0, $noescapebackslashn = 0)
1567{
1568 if (is_null($stringtoescape)) {
1569 return '';
1570 }
1571
1572 // escape quotes and backslashes, newlines, etc.
1573 $substitjs = array("&#039;"=>"\\'", "\r"=>'\\r');
1574 //$substitjs['</']='<\/'; // We removed this. Should be useless.
1575 if (empty($noescapebackslashn)) {
1576 $substitjs["\n"] = '\\n';
1577 $substitjs['\\'] = '\\\\';
1578 }
1579 if (empty($mode)) {
1580 $substitjs["'"] = "\\'";
1581 $substitjs['"'] = "\\'";
1582 } elseif ($mode == 1) {
1583 $substitjs["'"] = "\\'";
1584 } elseif ($mode == 2) {
1585 $substitjs['"'] = '\\"';
1586 } elseif ($mode == 3) {
1587 $substitjs["'"] = "\\'";
1588 $substitjs['"'] = "\\\"";
1589 }
1590 return strtr($stringtoescape, $substitjs);
1591}
1592
1599function dol_escape_json($stringtoescape)
1600{
1601 return str_replace('"', '\"', $stringtoescape);
1602}
1603
1611function dol_escape_php($stringtoescape, $stringforquotes = 2)
1612{
1613 if (is_null($stringtoescape)) {
1614 return '';
1615 }
1616
1617 if ($stringforquotes == 2) {
1618 return str_replace('"', "'", $stringtoescape);
1619 }
1620 if ($stringforquotes == 1) {
1621 return str_replace("'", "\'", str_replace('"', "'", $stringtoescape));
1622 }
1623
1624 return 'Bad parameter for stringforquotes in dol_escape_php';
1625}
1626
1633function dol_escape_xml($stringtoescape)
1634{
1635 return $stringtoescape;
1636}
1637
1645function dolPrintLabel($s)
1646{
1648}
1649
1658function dolPrintHTML($s, $allowiframe = 0)
1659{
1660 return dol_escape_htmltag(dol_htmlwithnojs(dol_string_onlythesehtmltags(dol_htmlentitiesbr($s), 1, 1, 1, $allowiframe)), 1, 1, 'common', 0, 1);
1661}
1662
1670{
1671 // The dol_htmlentitiesbr will convert simple text into html
1672 // The dol_escape_htmltag will escape html chars.
1673 return dol_escape_htmltag(dol_string_onlythesehtmltags(dol_htmlentitiesbr($s), 1, 0, 0, 0, array('br', 'b', 'font', 'span')), 1, -1, '', 0, 1);
1674}
1675
1684function dolPrintHTMLForTextArea($s, $allowiframe = 0)
1685{
1686 return dol_escape_htmltag(dol_htmlwithnojs(dol_string_onlythesehtmltags(dol_htmlentitiesbr($s), 1, 1, 1, $allowiframe)), 1, 1, '', 0, 1);
1687}
1688
1696{
1697 return htmlspecialchars($s, ENT_COMPAT, 'UTF-8');
1698}
1699
1700
1717function dol_escape_htmltag($stringtoescape, $keepb = 0, $keepn = 0, $noescapetags = '', $escapeonlyhtmltags = 0, $cleanalsojavascript = 0)
1718{
1719 if ($noescapetags == 'common') {
1720 $noescapetags = 'html,body,a,b,em,hr,i,u,ul,li,br,div,img,font,p,span,strong,table,tr,td,th,tbody,h1,h2,h3,h4,h5,h6,h7,h8,h9';
1721 // Add also html5 tags
1722 $noescapetags .= ',header,footer,nav,section,menu,menuitem';
1723 }
1724 if ($cleanalsojavascript) {
1725 $stringtoescape = dol_string_onlythesehtmltags($stringtoescape, 0, 0, $cleanalsojavascript, 0, array(), 0);
1726 }
1727
1728 // escape quotes and backslashes, newlines, etc.
1729 if ($escapeonlyhtmltags) {
1730 $tmp = htmlspecialchars_decode((string) $stringtoescape, ENT_COMPAT);
1731 } else {
1732 $tmp = html_entity_decode((string) $stringtoescape, ENT_COMPAT, 'UTF-8');
1733 }
1734 if (!$keepb) {
1735 $tmp = strtr($tmp, array("<b>"=>'', '</b>'=>'', '<strong>'=>'', '</strong>'=>''));
1736 }
1737 if (!$keepn) {
1738 $tmp = strtr($tmp, array("\r"=>'\\r', "\n"=>'\\n'));
1739 } elseif ($keepn == -1) {
1740 $tmp = strtr($tmp, array("\r"=>'', "\n"=>''));
1741 }
1742
1743 if ($escapeonlyhtmltags) {
1744 return htmlspecialchars($tmp, ENT_COMPAT, 'UTF-8');
1745 } else {
1746 // Escape tags to keep
1747 $tmparrayoftags = array();
1748 if ($noescapetags) {
1749 $tmparrayoftags = explode(',', $noescapetags);
1750 }
1751 if (count($tmparrayoftags)) {
1752 // TODO Does not works yet when there is attributes into tag
1753 foreach ($tmparrayoftags as $tagtoreplace) {
1754 $tmp = str_ireplace('<'.$tagtoreplace.'>', '__BEGINTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
1755 $tmp = str_ireplace('</'.$tagtoreplace.'>', '__ENDTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
1756 $tmp = str_ireplace('<'.$tagtoreplace.' />', '__BEGINENDTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
1757 }
1758 }
1759
1760 $result = htmlentities($tmp, ENT_COMPAT, 'UTF-8');
1761
1762 if (count($tmparrayoftags)) {
1763 foreach ($tmparrayoftags as $tagtoreplace) {
1764 $result = str_ireplace('__BEGINTAGTOREPLACE'.$tagtoreplace.'__', '<'.$tagtoreplace.'>', $result);
1765 $result = str_ireplace('__ENDTAGTOREPLACE'.$tagtoreplace.'__', '</'.$tagtoreplace.'>', $result);
1766 $result = str_ireplace('__BEGINENDTAGTOREPLACE'.$tagtoreplace.'__', '<'.$tagtoreplace.' />', $result);
1767 }
1768 }
1769
1770 return $result;
1771 }
1772}
1773
1781function dol_strtolower($string, $encoding = "UTF-8")
1782{
1783 if (function_exists('mb_strtolower')) {
1784 return mb_strtolower($string, $encoding);
1785 } else {
1786 return strtolower($string);
1787 }
1788}
1789
1798function dol_strtoupper($string, $encoding = "UTF-8")
1799{
1800 if (function_exists('mb_strtoupper')) {
1801 return mb_strtoupper($string, $encoding);
1802 } else {
1803 return strtoupper($string);
1804 }
1805}
1806
1815function dol_ucfirst($string, $encoding = "UTF-8")
1816{
1817 if (function_exists('mb_substr')) {
1818 return mb_strtoupper(mb_substr($string, 0, 1, $encoding), $encoding).mb_substr($string, 1, null, $encoding);
1819 } else {
1820 return ucfirst($string);
1821 }
1822}
1823
1832function dol_ucwords($string, $encoding = "UTF-8")
1833{
1834 if (function_exists('mb_convert_case')) {
1835 return mb_convert_case($string, MB_CASE_TITLE, $encoding);
1836 } else {
1837 return ucwords($string);
1838 }
1839}
1840
1862function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename = '', $restricttologhandler = '', $logcontext = null)
1863{
1864 global $conf, $user, $debugbar;
1865
1866 // If syslog module enabled
1867 if (!isModEnabled('syslog')) {
1868 return;
1869 }
1870
1871 // Check if we are into execution of code of a website
1872 if (defined('USEEXTERNALSERVER') && !defined('USEDOLIBARRSERVER') && !defined('USEDOLIBARREDITOR')) {
1873 global $website, $websitekey;
1874 if (is_object($website) && !empty($website->ref)) {
1875 $suffixinfilename .= '_website_'.$website->ref;
1876 } elseif (!empty($websitekey)) {
1877 $suffixinfilename .= '_website_'.$websitekey;
1878 }
1879 }
1880
1881 // Check if we have a forced suffix
1882 if (defined('USESUFFIXINLOG')) {
1883 $suffixinfilename .= constant('USESUFFIXINLOG');
1884 }
1885
1886 if ($ident < 0) {
1887 foreach ($conf->loghandlers as $loghandlerinstance) {
1888 $loghandlerinstance->setIdent($ident);
1889 }
1890 }
1891
1892 if (!empty($message)) {
1893 // Test log level
1894 $logLevels = array(LOG_EMERG=>'EMERG', LOG_ALERT=>'ALERT', LOG_CRIT=>'CRITICAL', LOG_ERR=>'ERR', LOG_WARNING=>'WARN', LOG_NOTICE=>'NOTICE', LOG_INFO=>'INFO', LOG_DEBUG=>'DEBUG');
1895 if (!array_key_exists($level, $logLevels)) {
1896 throw new Exception('Incorrect log level');
1897 }
1898 if ($level > getDolGlobalInt('SYSLOG_LEVEL')) {
1899 return;
1900 }
1901
1902 if (!getDolGlobalString('MAIN_SHOW_PASSWORD_INTO_LOG')) {
1903 $message = preg_replace('/password=\'[^\']*\'/', 'password=\'hidden\'', $message); // protection to avoid to have value of password in log
1904 }
1905
1906 // If adding log inside HTML page is required
1907 if ((!empty($_REQUEST['logtohtml']) && getDolGlobalString('MAIN_ENABLE_LOG_TO_HTML'))
1908 || (is_object($user) && $user->hasRight('debugbar', 'read') && is_object($debugbar))) {
1909 $conf->logbuffer[] = dol_print_date(time(), "%Y-%m-%d %H:%M:%S")." ".$logLevels[$level]." ".$message;
1910 }
1911
1912 //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output
1913 // If html log tag enabled and url parameter log defined, we show output log on HTML comments
1914 if (getDolGlobalString('MAIN_ENABLE_LOG_INLINE_HTML') && !empty($_GET["log"])) {
1915 print "\n\n<!-- Log start\n";
1916 print dol_escape_htmltag($message)."\n";
1917 print "Log end -->\n";
1918 }
1919
1920 $data = array(
1921 'message' => $message,
1922 'script' => (isset($_SERVER['PHP_SELF']) ? basename($_SERVER['PHP_SELF'], '.php') : false),
1923 'level' => $level,
1924 'user' => ((is_object($user) && $user->id) ? $user->login : false),
1925 'ip' => false
1926 );
1927
1928 $remoteip = getUserRemoteIP(); // Get ip when page run on a web server
1929 if (!empty($remoteip)) {
1930 $data['ip'] = $remoteip;
1931 // This is when server run behind a reverse proxy
1932 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != $remoteip) {
1933 $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'].' -> '.$data['ip'];
1934 } elseif (!empty($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP'] != $remoteip) {
1935 $data['ip'] = $_SERVER['HTTP_CLIENT_IP'].' -> '.$data['ip'];
1936 }
1937 } elseif (!empty($_SERVER['SERVER_ADDR'])) {
1938 // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
1939 $data['ip'] = $_SERVER['SERVER_ADDR'];
1940 } elseif (!empty($_SERVER['COMPUTERNAME'])) {
1941 // This is when PHP session is ran outside a web server, like from Windows command line (Not always defined, but useful if OS defined it).
1942 $data['ip'] = $_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME']) ? '' : '@'.$_SERVER['USERNAME']);
1943 } elseif (!empty($_SERVER['LOGNAME'])) {
1944 // This is when PHP session is ran outside a web server, like from Linux command line (Not always defined, but usefull if OS defined it).
1945 $data['ip'] = '???@'.$_SERVER['LOGNAME'];
1946 }
1947
1948 // Loop on each log handler and send output
1949 foreach ($conf->loghandlers as $loghandlerinstance) {
1950 if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler) {
1951 continue;
1952 }
1953 $loghandlerinstance->export($data, $suffixinfilename);
1954 }
1955 unset($data);
1956 }
1957
1958 if ($ident > 0) {
1959 foreach ($conf->loghandlers as $loghandlerinstance) {
1960 $loghandlerinstance->setIdent($ident);
1961 }
1962 }
1963}
1964
1981function dolButtonToOpenUrlInDialogPopup($name, $label, $buttonstring, $url, $disabled = '', $morecss = 'classlink button bordertransp', $jsonopen = '', $backtopagejsfields = '', $accesskey = '')
1982{
1983 global $conf;
1984
1985 if (strpos($url, '?') > 0) {
1986 $url .= '&dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup='.urlencode($name);
1987 } else {
1988 $url .= '?dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup='.urlencode($name);
1989 }
1990
1991 $out = '';
1992
1993 $backtopagejsfieldsid = '';
1994 $backtopagejsfieldslabel = '';
1995 if ($backtopagejsfields) {
1996 $tmpbacktopagejsfields = explode(':', $backtopagejsfields);
1997 if (empty($tmpbacktopagejsfields[1])) { // If the part 'keyforpopupid:' is missing, we add $name for it.
1998 $backtopagejsfields = $name.":".$backtopagejsfields;
1999 $tmp2backtopagejsfields = explode(',', $tmpbacktopagejsfields[0]);
2000 } else {
2001 $tmp2backtopagejsfields = explode(',', $tmpbacktopagejsfields[1]);
2002 }
2003 $backtopagejsfieldsid = empty($tmp2backtopagejsfields[0]) ? '' : $tmp2backtopagejsfields[0];
2004 $backtopagejsfieldslabel = empty($tmp2backtopagejsfields[1]) ? '' : $tmp2backtopagejsfields[1];
2005 $url .= '&backtopagejsfields='.urlencode($backtopagejsfields);
2006 }
2007
2008 //print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("MediaFiles")).'" name="file_manager">';
2009 $out .= '<!-- a link for button to open url into a dialog popup with backtopagejsfields = '.$backtopagejsfields.' -->';
2010 $out .= '<a '.($accesskey ? ' accesskey="'.$accesskey.'"' : '').' class="cursorpointer reposition button_'.$name.($morecss ? ' '.$morecss : '').'"'.$disabled.' title="'.dol_escape_htmltag($label).'"';
2011 if (empty($conf->use_javascript_ajax)) {
2012 $out .= ' href="'.DOL_URL_ROOT.$url.'" target="_blank"';
2013 } elseif ($jsonopen) {
2014 $out .= ' href="#" onclick="'.$jsonopen.'"';
2015 } else {
2016 $out .= ' href="#"';
2017 }
2018 $out .= '>'.$buttonstring.'</a>';
2019
2020 if (!empty($conf->use_javascript_ajax)) {
2021 // Add code to open url using the popup. Add also hidden field to retreive the returned variables
2022 $out .= '<!-- code to open popup and variables to retreive returned variables -->';
2023 $out .= '<div id="idfordialog'.$name.'" class="hidden">div for dialog</div>';
2024 $out .= '<div id="varforreturndialogid'.$name.'" class="hidden">div for returned id</div>';
2025 $out .= '<div id="varforreturndialoglabel'.$name.'" class="hidden">div for returned label</div>';
2026 $out .= '<!-- Add js code to open dialog popup on dialog -->';
2027 $out .= '<script nonce="'.getNonce().'" type="text/javascript">
2028 jQuery(document).ready(function () {
2029 jQuery(".button_'.$name.'").click(function () {
2030 console.log(\'Open popup with jQuery(...).dialog() on URL '.dol_escape_js(DOL_URL_ROOT.$url).'\');
2031 var $tmpdialog = $(\'#idfordialog'.$name.'\');
2032 $tmpdialog.html(\'<iframe class="iframedialog" id="iframedialog'.$name.'" style="border: 0px;" src="'.DOL_URL_ROOT.$url.'" width="100%" height="98%"></iframe>\');
2033 $tmpdialog.dialog({
2034 autoOpen: false,
2035 modal: true,
2036 height: (window.innerHeight - 150),
2037 width: \'80%\',
2038 title: \''.dol_escape_js($label).'\',
2039 open: function (event, ui) {
2040 console.log("open popup name='.$name.', backtopagejsfields='.$backtopagejsfields.'");
2041 },
2042 close: function (event, ui) {
2043 var returnedid = jQuery("#varforreturndialogid'.$name.'").text();
2044 var returnedlabel = jQuery("#varforreturndialoglabel'.$name.'").text();
2045 console.log("popup has been closed. returnedid (js var defined into parent page)="+returnedid+" returnedlabel="+returnedlabel);
2046 if (returnedid != "" && returnedid != "div for returned id") {
2047 jQuery("#'.(empty($backtopagejsfieldsid) ? "none" : $backtopagejsfieldsid).'").val(returnedid);
2048 }
2049 if (returnedlabel != "" && returnedlabel != "div for returned label") {
2050 jQuery("#'.(empty($backtopagejsfieldslabel) ? "none" : $backtopagejsfieldslabel).'").val(returnedlabel);
2051 }
2052 }
2053 });
2054
2055 $tmpdialog.dialog(\'open\');
2056 return false;
2057 });
2058 });
2059 </script>';
2060 }
2061 return $out;
2062}
2063
2080function dol_fiche_head($links = array(), $active = '0', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
2081{
2082 print dol_get_fiche_head($links, $active, $title, $notab, $picto, $pictoisfullpath, $morehtmlright, $morecss, $limittoshow, $moretabssuffix);
2083}
2084
2101function dol_get_fiche_head($links = array(), $active = '', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '', $dragdropfile = 0)
2102{
2103 global $conf, $langs, $hookmanager;
2104
2105 // Show title
2106 $showtitle = 1;
2107 if (!empty($conf->dol_optimize_smallscreen)) {
2108 $showtitle = 0;
2109 }
2110
2111 $out = "\n".'<!-- dol_fiche_head - dol_get_fiche_head -->';
2112
2113 if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
2114 $out .= '<div class="tabs'.($picto ? '' : ' nopaddingleft').'" data-role="controlgroup" data-type="horizontal">'."\n";
2115 }
2116
2117 // Show right part
2118 if ($morehtmlright) {
2119 $out .= '<div class="inline-block floatright tabsElem">'.$morehtmlright.'</div>'; // Output right area first so when space is missing, text is in front of tabs and not under.
2120 }
2121
2122 // Show title
2123 if (!empty($title) && $showtitle && !getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2124 $limittitle = 30;
2125 $out .= '<a class="tabTitle">';
2126 if ($picto) {
2127 $noprefix = $pictoisfullpath;
2128 if (strpos($picto, 'fontawesome_') !== false) {
2129 $noprefix = 1;
2130 }
2131 $out .= img_picto($title, ($noprefix ? '' : 'object_').$picto, '', $pictoisfullpath, 0, 0, '', 'imgTabTitle').' ';
2132 }
2133 $out .= '<span class="tabTitleText">'.dol_escape_htmltag(dol_trunc($title, $limittitle)).'</span>';
2134 $out .= '</a>';
2135 }
2136
2137 // Show tabs
2138
2139 // Define max of key (max may be higher than sizeof because of hole due to module disabling some tabs).
2140 $maxkey = -1;
2141 if (is_array($links) && !empty($links)) {
2142 $keys = array_keys($links);
2143 if (count($keys)) {
2144 $maxkey = max($keys);
2145 }
2146 }
2147
2148 // Show tabs
2149 // if =0 we don't use the feature
2150 if (empty($limittoshow)) {
2151 $limittoshow = (!getDolGlobalString('MAIN_MAXTABS_IN_CARD') ? 99 : $conf->global->MAIN_MAXTABS_IN_CARD);
2152 }
2153 if (!empty($conf->dol_optimize_smallscreen)) {
2154 $limittoshow = 2;
2155 }
2156
2157 $displaytab = 0;
2158 $nbintab = 0;
2159 $popuptab = 0;
2160 $outmore = '';
2161 for ($i = 0; $i <= $maxkey; $i++) {
2162 if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
2163 // If active tab is already present
2164 if ($i >= $limittoshow) {
2165 $limittoshow--;
2166 }
2167 }
2168 }
2169
2170 for ($i = 0; $i <= $maxkey; $i++) {
2171 if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
2172 $isactive = true;
2173 } else {
2174 $isactive = false;
2175 }
2176
2177 if ($i < $limittoshow || $isactive) {
2178 // Output entry with a visible tab
2179 $out .= '<div class="inline-block tabsElem'.($isactive ? ' tabsElemActive' : '').((!$isactive && getDolGlobalString('MAIN_HIDE_INACTIVETAB_ON_PRINT')) ? ' hideonprint' : '').'"><!-- id tab = '.(empty($links[$i][2]) ? '' : dol_escape_htmltag($links[$i][2])).' -->';
2180
2181 if (isset($links[$i][2]) && $links[$i][2] == 'image') {
2182 if (!empty($links[$i][0])) {
2183 $out .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
2184 } else {
2185 $out .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
2186 }
2187 } elseif (!empty($links[$i][1])) {
2188 //print "x $i $active ".$links[$i][2]." z";
2189 $out .= '<div class="tab tab'.($isactive ? 'active' : 'unactive').'" style="margin: 0 !important">';
2190 if (!empty($links[$i][0])) {
2191 $titletoshow = preg_replace('/<.*$/', '', $links[$i][1]);
2192 $out .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="tab inline-block valignmiddle'.($morecss ? ' '.$morecss : '').(!empty($links[$i][5]) ? ' '.$links[$i][5] : '').'" href="'.$links[$i][0].'" title="'.dol_escape_htmltag($titletoshow).'">';
2193 }
2194 $out .= $links[$i][1];
2195 if (!empty($links[$i][0])) {
2196 $out .= '</a>'."\n";
2197 }
2198 $out .= empty($links[$i][4]) ? '' : $links[$i][4];
2199 $out .= '</div>';
2200 }
2201
2202 $out .= '</div>';
2203 } else {
2204 // Add entry into the combo popup with the other tabs
2205 if (!$popuptab) {
2206 $popuptab = 1;
2207 $outmore .= '<div class="popuptabset wordwrap">'; // The css used to hide/show popup
2208 }
2209 $outmore .= '<div class="popuptab wordwrap" style="display:inherit;">';
2210 if (isset($links[$i][2]) && $links[$i][2] == 'image') {
2211 if (!empty($links[$i][0])) {
2212 $outmore .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
2213 } else {
2214 $outmore .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
2215 }
2216 } elseif (!empty($links[$i][1])) {
2217 $outmore .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="wordwrap inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
2218 $outmore .= preg_replace('/([a-z])\|([a-z])/i', '\\1 | \\2', $links[$i][1]); // Replace x|y with x | y to allow wrap on long composed texts.
2219 $outmore .= '</a>'."\n";
2220 }
2221 $outmore .= '</div>';
2222
2223 $nbintab++;
2224 }
2225 $displaytab = $i;
2226 }
2227 if ($popuptab) {
2228 $outmore .= '</div>';
2229 }
2230
2231 if ($popuptab) { // If there is some tabs not shown
2232 $left = ($langs->trans("DIRECTION") == 'rtl' ? 'right' : 'left');
2233 $right = ($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right');
2234 $widthofpopup = 200;
2235
2236 $tabsname = $moretabssuffix;
2237 if (empty($tabsname)) {
2238 $tabsname = str_replace("@", "", $picto);
2239 }
2240 $out .= '<div id="moretabs'.$tabsname.'" class="inline-block tabsElem valignmiddle">';
2241 $out .= '<div class="tab valignmiddle"><a href="#" class="tab moretab inline-block tabunactive valignmiddle"><span class="hideonsmartphone">'.$langs->trans("More").'</span>... ('.$nbintab.')</a></div>'; // Do not use "reposition" class in the "More".
2242 $out .= '<div id="moretabsList'.$tabsname.'" style="width: '.$widthofpopup.'px; position: absolute; '.$left.': -999em; text-align: '.$left.'; margin:0px; padding:2px; z-index:10;">';
2243 $out .= $outmore;
2244 $out .= '</div>';
2245 $out .= '<div></div>';
2246 $out .= "</div>\n";
2247
2248 $out .= '<script nonce="'.getNonce().'">';
2249 $out .= "$('#moretabs".$tabsname."').mouseenter( function() {
2250 var x = this.offsetLeft, y = this.offsetTop;
2251 console.log('mouseenter ".$left." x='+x+' y='+y+' window.innerWidth='+window.innerWidth);
2252 if ((window.innerWidth - x) < ".($widthofpopup + 10).") {
2253 $('#moretabsList".$tabsname."').css('".$right."','8px');
2254 }
2255 $('#moretabsList".$tabsname."').css('".$left."','auto');
2256 });
2257 ";
2258 $out .= "$('#moretabs".$tabsname."').mouseleave( function() { console.log('mouseleave ".$left."'); $('#moretabsList".$tabsname."').css('".$left."','-999em');});";
2259 $out .= "</script>";
2260 }
2261
2262 if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
2263 $out .= "</div>\n";
2264 }
2265
2266 if (!$notab || $notab == -1 || $notab == -2 || $notab == -3) {
2267 $out .= "\n".'<div id="dragDropAreaTabBar" class="tabBar'.($notab == -1 ? '' : ($notab == -2 ? ' tabBarNoTop' : (($notab == -3 ? ' noborderbottom' : '').' tabBarWithBottom'))).'">'."\n";
2268 }
2269 if (!empty($dragdropfile)) {
2270 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2271 $out .= dragAndDropFileUpload("dragDropAreaTabBar");
2272 }
2273 $parameters = array('tabname' => $active, 'out' => $out);
2274 $reshook = $hookmanager->executeHooks('printTabsHead', $parameters); // This hook usage is called just before output the head of tabs. Take also a look at "completeTabsHead"
2275 if ($reshook > 0) {
2276 $out = $hookmanager->resPrint;
2277 }
2278
2279 return $out;
2280}
2281
2289function dol_fiche_end($notab = 0)
2290{
2291 print dol_get_fiche_end($notab);
2292}
2293
2300function dol_get_fiche_end($notab = 0)
2301{
2302 if (!$notab || $notab == -1) {
2303 return "\n</div>\n";
2304 } else {
2305 return '';
2306 }
2307}
2308
2328function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $onlybanner = 0, $morehtmlright = '')
2329{
2330 global $conf, $form, $user, $langs, $hookmanager, $action;
2331
2332 $error = 0;
2333
2334 $maxvisiblephotos = 1;
2335 $showimage = 1;
2336 $entity = (empty($object->entity) ? $conf->entity : $object->entity);
2337 $showbarcode = empty($conf->barcode->enabled) ? 0 : (empty($object->barcode) ? 0 : 1);
2338 if (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !$user->hasRight('barcode', 'lire_advance')) {
2339 $showbarcode = 0;
2340 }
2341 $modulepart = 'unknown';
2342
2343 if ($object->element == 'societe' || $object->element == 'contact' || $object->element == 'product' || $object->element == 'ticket') {
2344 $modulepart = $object->element;
2345 } elseif ($object->element == 'member') {
2346 $modulepart = 'memberphoto';
2347 } elseif ($object->element == 'user') {
2348 $modulepart = 'userphoto';
2349 }
2350
2351 if (class_exists("Imagick")) {
2352 if ($object->element == 'expensereport' || $object->element == 'propal' || $object->element == 'commande' || $object->element == 'facture' || $object->element == 'supplier_proposal') {
2353 $modulepart = $object->element;
2354 } elseif ($object->element == 'fichinter') {
2355 $modulepart = 'ficheinter';
2356 } elseif ($object->element == 'contrat') {
2357 $modulepart = 'contract';
2358 } elseif ($object->element == 'order_supplier') {
2359 $modulepart = 'supplier_order';
2360 } elseif ($object->element == 'invoice_supplier') {
2361 $modulepart = 'supplier_invoice';
2362 }
2363 }
2364
2365 if ($object->element == 'product') {
2366 $width = 80;
2367 $cssclass = 'photowithmargin photoref';
2368 $showimage = $object->is_photo_available($conf->product->multidir_output[$entity]);
2369 $maxvisiblephotos = (isset($conf->global->PRODUCT_MAX_VISIBLE_PHOTO) ? $conf->global->PRODUCT_MAX_VISIBLE_PHOTO : 5);
2370 if ($conf->browser->layout == 'phone') {
2371 $maxvisiblephotos = 1;
2372 }
2373 if ($showimage) {
2374 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$object->show_photos('product', $conf->product->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, 0, $width, 0, '').'</div>';
2375 } else {
2376 if (getDolGlobalString('PRODUCT_NODISPLAYIFNOPHOTO')) {
2377 $nophoto = '';
2378 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
2379 } else { // Show no photo link
2380 $nophoto = '/public/theme/common/nophoto.png';
2381 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" title="'.dol_escape_htmltag($langs->trans("UploadAnImageToSeeAPhotoHere", $langs->transnoentitiesnoconv("Documents"))).'" alt="No photo"'.($width ? ' style="width: '.$width.'px"' : '').' src="'.DOL_URL_ROOT.$nophoto.'"></div>';
2382 }
2383 }
2384 } elseif ($object->element == 'ticket') {
2385 $width = 80;
2386 $cssclass = 'photoref';
2387 $showimage = $object->is_photo_available($conf->ticket->multidir_output[$entity].'/'.$object->ref);
2388 $maxvisiblephotos = (isset($conf->global->TICKET_MAX_VISIBLE_PHOTO) ? $conf->global->TICKET_MAX_VISIBLE_PHOTO : 2);
2389 if ($conf->browser->layout == 'phone') {
2390 $maxvisiblephotos = 1;
2391 }
2392
2393 if ($showimage) {
2394 $showphoto = $object->show_photos('ticket', $conf->ticket->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0);
2395 if ($object->nbphoto > 0) {
2396 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$showphoto.'</div>';
2397 } else {
2398 $showimage = 0;
2399 }
2400 }
2401 if (!$showimage) {
2402 if (getDolGlobalString('TICKET_NODISPLAYIFNOPHOTO')) {
2403 $nophoto = '';
2404 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
2405 } else { // Show no photo link
2406 $nophoto = img_picto('No photo', 'object_ticket');
2407 $morehtmlleft .= '<!-- No photo to show -->';
2408 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
2409 $morehtmlleft .= $nophoto;
2410 $morehtmlleft .= '</div></div>';
2411 }
2412 }
2413 } else {
2414 if ($showimage) {
2415 if ($modulepart != 'unknown') {
2416 $phototoshow = '';
2417 // Check if a preview file is available
2418 if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice', 'expensereport')) && class_exists("Imagick")) {
2419 $objectref = dol_sanitizeFileName($object->ref);
2420 $dir_output = (empty($conf->$modulepart->multidir_output[$entity]) ? $conf->$modulepart->dir_output : $conf->$modulepart->multidir_output[$entity])."/";
2421 if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice'))) {
2422 $subdir = get_exdir($object->id, 2, 0, 1, $object, $modulepart);
2423 $subdir .= ((!empty($subdir) && !preg_match('/\/$/', $subdir)) ? '/' : '').$objectref; // the objectref dir is not included into get_exdir when used with level=2, so we add it at end
2424 } else {
2425 $subdir = get_exdir($object->id, 0, 0, 1, $object, $modulepart);
2426 }
2427 if (empty($subdir)) {
2428 $subdir = 'errorgettingsubdirofobject'; // Protection to avoid to return empty path
2429 }
2430
2431 $filepath = $dir_output.$subdir."/";
2432
2433 $filepdf = $filepath.$objectref.".pdf";
2434 $relativepath = $subdir.'/'.$objectref.'.pdf';
2435
2436 // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png")
2437 $fileimage = $filepdf.'_preview.png';
2438 $relativepathimage = $relativepath.'_preview.png';
2439
2440 $pdfexists = file_exists($filepdf);
2441
2442 // If PDF file exists
2443 if ($pdfexists) {
2444 // Conversion du PDF en image png si fichier png non existant
2445 if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf))) {
2446 if (!getDolGlobalString('MAIN_DISABLE_PDF_THUMBS')) { // If you experience trouble with pdf thumb generation and imagick, you can disable here.
2447 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2448 $ret = dol_convert_file($filepdf, 'png', $fileimage, '0'); // Convert first page of PDF into a file _preview.png
2449 if ($ret < 0) {
2450 $error++;
2451 }
2452 }
2453 }
2454 }
2455
2456 if ($pdfexists && !$error) {
2457 $heightforphotref = 80;
2458 if (!empty($conf->dol_optimize_smallscreen)) {
2459 $heightforphotref = 60;
2460 }
2461 // If the preview file is found
2462 if (file_exists($fileimage)) {
2463 $phototoshow = '<div class="photoref">';
2464 $phototoshow .= '<img height="'.$heightforphotref.'" class="photo photowithborder" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($relativepathimage).'">';
2465 $phototoshow .= '</div>';
2466 }
2467 }
2468 } elseif (!$phototoshow) { // example if modulepart = 'societe' or 'photo'
2469 $phototoshow .= $form->showphoto($modulepart, $object, 0, 0, 0, 'photowithmargin photoref', 'small', 1, 0, $maxvisiblephotos);
2470 }
2471
2472 if ($phototoshow) {
2473 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">';
2474 $morehtmlleft .= $phototoshow;
2475 $morehtmlleft .= '</div>';
2476 }
2477 }
2478
2479 if (empty($phototoshow)) { // Show No photo link (picto of object)
2480 if ($object->element == 'action') {
2481 $width = 80;
2482 $cssclass = 'photorefcenter';
2483 $nophoto = img_picto('No photo', 'title_agenda');
2484 } else {
2485 $width = 14;
2486 $cssclass = 'photorefcenter';
2487 $picto = $object->picto;
2488 $prefix = 'object_';
2489 if ($object->element == 'project' && !$object->public) {
2490 $picto = 'project'; // instead of projectpub
2491 }
2492 if (strpos($picto, 'fontawesome_') !== false) {
2493 $prefix = '';
2494 }
2495 $nophoto = img_picto('No photo', $prefix.$picto);
2496 }
2497 $morehtmlleft .= '<!-- No photo to show -->';
2498 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
2499 $morehtmlleft .= $nophoto;
2500 $morehtmlleft .= '</div></div>';
2501 }
2502 }
2503 }
2504
2505 // Show barcode
2506 if ($showbarcode) {
2507 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$form->showbarcode($object, 100, 'photoref valignmiddle').'</div>';
2508 }
2509
2510 if ($object->element == 'societe') {
2511 if (!empty($conf->use_javascript_ajax) && $user->hasRight('societe', 'creer') && getDolGlobalString('MAIN_DIRECT_STATUS_UPDATE')) {
2512 $morehtmlstatus .= ajax_object_onoff($object, 'status', 'status', 'InActivity', 'ActivityCeased');
2513 } else {
2514 $morehtmlstatus .= $object->getLibStatut(6);
2515 }
2516 } elseif ($object->element == 'product') {
2517 //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Sell").') ';
2518 if (!empty($conf->use_javascript_ajax) && $user->hasRight('produit', 'creer') && getDolGlobalString('MAIN_DIRECT_STATUS_UPDATE')) {
2519 $morehtmlstatus .= ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell');
2520 } else {
2521 $morehtmlstatus .= '<span class="statusrefsell">'.$object->getLibStatut(6, 0).'</span>';
2522 }
2523 $morehtmlstatus .= ' &nbsp; ';
2524 //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Buy").') ';
2525 if (!empty($conf->use_javascript_ajax) && $user->hasRight('produit', 'creer') && getDolGlobalString('MAIN_DIRECT_STATUS_UPDATE')) {
2526 $morehtmlstatus .= ajax_object_onoff($object, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy');
2527 } else {
2528 $morehtmlstatus .= '<span class="statusrefbuy">'.$object->getLibStatut(6, 1).'</span>';
2529 }
2530 } elseif (in_array($object->element, array('salary'))) {
2531 $tmptxt = $object->getLibStatut(6, $object->alreadypaid);
2532 if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
2533 $tmptxt = $object->getLibStatut(5, $object->alreadypaid);
2534 }
2535 $morehtmlstatus .= $tmptxt;
2536 } elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier', 'chargesociales', 'loan', 'tva'))) { // TODO Move this to use ->alreadypaid
2537 $tmptxt = $object->getLibStatut(6, $object->totalpaid);
2538 if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
2539 $tmptxt = $object->getLibStatut(5, $object->totalpaid);
2540 }
2541 $morehtmlstatus .= $tmptxt;
2542 } elseif ($object->element == 'contrat' || $object->element == 'contract') {
2543 if ($object->statut == 0) {
2544 $morehtmlstatus .= $object->getLibStatut(5);
2545 } else {
2546 $morehtmlstatus .= $object->getLibStatut(4);
2547 }
2548 } elseif ($object->element == 'facturerec') {
2549 if ($object->frequency == 0) {
2550 $morehtmlstatus .= $object->getLibStatut(2);
2551 } else {
2552 $morehtmlstatus .= $object->getLibStatut(5);
2553 }
2554 } elseif ($object->element == 'project_task') {
2555 $object->fk_statut = 1;
2556 if ($object->progress > 0) {
2557 $object->fk_statut = 2;
2558 }
2559 if ($object->progress >= 100) {
2560 $object->fk_statut = 3;
2561 }
2562 $tmptxt = $object->getLibStatut(5);
2563 $morehtmlstatus .= $tmptxt; // No status on task
2564 } elseif (method_exists($object, 'getLibStatut')) { // Generic case for status
2565 $tmptxt = $object->getLibStatut(6);
2566 if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
2567 $tmptxt = $object->getLibStatut(5);
2568 }
2569 $morehtmlstatus .= $tmptxt;
2570 }
2571
2572 // Add if object was dispatched "into accountancy"
2573 if (isModEnabled('accounting') && in_array($object->element, array('bank', 'paiementcharge', 'facture', 'invoice', 'invoice_supplier', 'expensereport', 'payment_various'))) {
2574 // Note: For 'chargesociales', 'salaries'... this is the payments that are dispatched (so element = 'bank')
2575 if (method_exists($object, 'getVentilExportCompta')) {
2576 $accounted = $object->getVentilExportCompta();
2577 $langs->load("accountancy");
2578 $morehtmlstatus .= '</div><div class="statusref statusrefbis"><span class="opacitymedium">'.($accounted > 0 ? $langs->trans("Accounted") : $langs->trans("NotYetAccounted")).'</span>';
2579 }
2580 }
2581
2582 // Add alias for thirdparty
2583 if (!empty($object->name_alias)) {
2584 $morehtmlref .= '<div class="refidno opacitymedium">'.dol_escape_htmltag($object->name_alias).'</div>';
2585 }
2586
2587 // Add label
2588 if (in_array($object->element, array('product', 'bank_account', 'project_task'))) {
2589 if (!empty($object->label)) {
2590 $morehtmlref .= '<div class="refidno opacitymedium">'.$object->label.'</div>';
2591 }
2592 }
2593
2594 // Show address and email
2595 if (method_exists($object, 'getBannerAddress') && !in_array($object->element, array('product', 'bookmark', 'ecm_directories', 'ecm_files'))) {
2596 $moreaddress = $object->getBannerAddress('refaddress', $object); // address, email, url, social networks
2597 if ($moreaddress) {
2598 $morehtmlref .= '<div class="refidno refaddress">';
2599 $morehtmlref .= $moreaddress;
2600 $morehtmlref .= '</div>';
2601 }
2602 }
2603 if (getDolGlobalString('MAIN_SHOW_TECHNICAL_ID') && (getDolGlobalString('MAIN_SHOW_TECHNICAL_ID') == '1' || preg_match('/'.preg_quote($object->element, '/').'/i', $conf->global->MAIN_SHOW_TECHNICAL_ID)) && !empty($object->id)) {
2604 $morehtmlref .= '<div style="clear: both;"></div>';
2605 $morehtmlref .= '<div class="refidno opacitymedium">';
2606 $morehtmlref .= $langs->trans("TechnicalID").': '.((int) $object->id);
2607 $morehtmlref .= '</div>';
2608 }
2609
2610 $parameters=array('morehtmlref'=>$morehtmlref);
2611 $reshook = $hookmanager->executeHooks('formDolBanner', $parameters, $object, $action);
2612 if ($reshook < 0) {
2613 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
2614 } elseif (empty($reshook)) {
2615 $morehtmlref .= $hookmanager->resPrint;
2616 } elseif ($reshook > 0) {
2617 $morehtmlref = $hookmanager->resPrint;
2618 }
2619
2620 print '<div class="'.($onlybanner ? 'arearefnobottom ' : 'arearef ').'heightref valignmiddle centpercent">';
2621 print $form->showrefnav($object, $paramid, $morehtml, $shownav, $fieldid, $fieldref, $morehtmlref, $moreparam, $nodbprefix, $morehtmlleft, $morehtmlstatus, $morehtmlright);
2622 print '</div>';
2623 print '<div class="underrefbanner clearboth"></div>';
2624}
2625
2635function fieldLabel($langkey, $fieldkey, $fieldrequired = 0)
2636{
2637 global $langs;
2638 $ret = '';
2639 if ($fieldrequired) {
2640 $ret .= '<span class="fieldrequired">';
2641 }
2642 $ret .= '<label for="'.$fieldkey.'">';
2643 $ret .= $langs->trans($langkey);
2644 $ret .= '</label>';
2645 if ($fieldrequired) {
2646 $ret .= '</span>';
2647 }
2648 return $ret;
2649}
2650
2658function dol_bc($var, $moreclass = '')
2659{
2660 global $bc;
2661 $ret = ' '.$bc[$var];
2662 if ($moreclass) {
2663 $ret = preg_replace('/class=\"/', 'class="'.$moreclass.' ', $ret);
2664 }
2665 return $ret;
2666}
2667
2681function dol_format_address($object, $withcountry = 0, $sep = "\n", $outputlangs = '', $mode = 0, $extralangcode = '')
2682{
2683 global $conf, $langs, $hookmanager;
2684
2685 $ret = '';
2686 $countriesusingstate = array('AU', 'CA', 'US', 'IN', 'GB', 'ES', 'UK', 'TR', 'CN'); // See also MAIN_FORCE_STATE_INTO_ADDRESS
2687
2688 // See format of addresses on https://en.wikipedia.org/wiki/Address
2689 // Address
2690 if (empty($mode)) {
2691 $ret .= ($extralangcode ? $object->array_languages['address'][$extralangcode] : (empty($object->address) ? '' : preg_replace('/(\r\n|\r|\n)+/', $sep, $object->address)));
2692 }
2693 // Zip/Town/State
2694 if (isset($object->country_code) && in_array($object->country_code, array('AU', 'CA', 'US', 'CN')) || getDolGlobalString('MAIN_FORCE_STATE_INTO_ADDRESS')) {
2695 // US: title firstname name \n address lines \n town, state, zip \n country
2696 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
2697 $ret .= (($ret && $town) ? $sep : '').$town;
2698
2699 if (!empty($object->state)) {
2700 $ret .= ($ret ? ($town ? ", " : $sep) : '').$object->state;
2701 }
2702 if (!empty($object->zip)) {
2703 $ret .= ($ret ? (($town || $object->state) ? ", " : $sep) : '').$object->zip;
2704 }
2705 } elseif (isset($object->country_code) && in_array($object->country_code, array('GB', 'UK'))) {
2706 // UK: title firstname name \n address lines \n town state \n zip \n country
2707 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
2708 $ret .= ($ret ? $sep : '').$town;
2709 if (!empty($object->state)) {
2710 $ret .= ($ret ? ", " : '').$object->state;
2711 }
2712 if (!empty($object->zip)) {
2713 $ret .= ($ret ? $sep : '').$object->zip;
2714 }
2715 } elseif (isset($object->country_code) && in_array($object->country_code, array('ES', 'TR'))) {
2716 // ES: title firstname name \n address lines \n zip town \n state \n country
2717 $ret .= ($ret ? $sep : '').$object->zip;
2718 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
2719 $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
2720 if (!empty($object->state)) {
2721 $ret .= $sep.$object->state;
2722 }
2723 } elseif (isset($object->country_code) && in_array($object->country_code, array('JP'))) {
2724 // JP: In romaji, title firstname name\n address lines \n [state,] town zip \n country
2725 // See https://www.sljfaq.org/afaq/addresses.html
2726 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
2727 $ret .= ($ret ? $sep : '').($object->state ? $object->state.', ' : '').$town.($object->zip ? ' ' : '').$object->zip;
2728 } elseif (isset($object->country_code) && in_array($object->country_code, array('IT'))) {
2729 // IT: title firstname name\n address lines \n zip town state_code \n country
2730 $ret .= ($ret ? $sep : '').$object->zip;
2731 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
2732 $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
2733 $ret .= (empty($object->state_code) ? '' : (' '.$object->state_code));
2734 } else {
2735 // Other: title firstname name \n address lines \n zip town[, state] \n country
2736 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
2737 $ret .= !empty($object->zip) ? (($ret ? $sep : '').$object->zip) : '';
2738 $ret .= ($town ? (($object->zip ? ' ' : ($ret ? $sep : '')).$town) : '');
2739 if (!empty($object->state) && in_array($object->country_code, $countriesusingstate)) {
2740 $ret .= ($ret ? ", " : '').$object->state;
2741 }
2742 }
2743
2744 if (!is_object($outputlangs)) {
2745 $outputlangs = $langs;
2746 }
2747 if ($withcountry) {
2748 $langs->load("dict");
2749 $ret .= (empty($object->country_code) ? '' : ($ret ? $sep : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$object->country_code)));
2750 }
2751 if ($hookmanager) {
2752 $parameters = array('withcountry' => $withcountry, 'sep' => $sep, 'outputlangs' => $outputlangs,'mode' => $mode, 'extralangcode' => $extralangcode);
2753 $reshook = $hookmanager->executeHooks('formatAddress', $parameters, $object);
2754 if ($reshook > 0) {
2755 $ret = '';
2756 }
2757 $ret .= $hookmanager->resPrint;
2758 }
2759
2760 return $ret;
2761}
2762
2763
2764
2773function dol_strftime($fmt, $ts = false, $is_gmt = false)
2774{
2775 if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
2776 return ($is_gmt) ? @gmstrftime($fmt, $ts) : @strftime($fmt, $ts);
2777 } else {
2778 return 'Error date into a not supported range';
2779 }
2780}
2781
2803function dol_print_date($time, $format = '', $tzoutput = 'auto', $outputlangs = '', $encodetooutput = false)
2804{
2805 global $conf, $langs;
2806
2807 // If date undefined or "", we return ""
2808 if (dol_strlen($time) == 0) {
2809 return ''; // $time=0 allowed (it means 01/01/1970 00:00:00)
2810 }
2811
2812 if ($tzoutput === 'auto') {
2813 $tzoutput = (empty($conf) ? 'tzserver' : (isset($conf->tzuserinputkey) ? $conf->tzuserinputkey : 'tzserver'));
2814 }
2815
2816 // Clean parameters
2817 $to_gmt = false;
2818 $offsettz = $offsetdst = 0;
2819 if ($tzoutput) {
2820 $to_gmt = true; // For backward compatibility
2821 if (is_string($tzoutput)) {
2822 if ($tzoutput == 'tzserver') {
2823 $to_gmt = false;
2824 $offsettzstring = @date_default_timezone_get(); // Example 'Europe/Berlin' or 'Indian/Reunion'
2825 $offsettz = 0; // Timezone offset with server timezone (because to_gmt is false), so 0
2826 $offsetdst = 0; // Dst offset with server timezone (because to_gmt is false), so 0
2827 } elseif ($tzoutput == 'tzuser' || $tzoutput == 'tzuserrel') {
2828 $to_gmt = true;
2829 $offsettzstring = (empty($_SESSION['dol_tz_string']) ? 'UTC' : $_SESSION['dol_tz_string']); // Example 'Europe/Berlin' or 'Indian/Reunion'
2830
2831 if (class_exists('DateTimeZone')) {
2832 $user_date_tz = new DateTimeZone($offsettzstring);
2833 $user_dt = new DateTime();
2834 $user_dt->setTimezone($user_date_tz);
2835 $user_dt->setTimestamp($tzoutput == 'tzuser' ? dol_now() : (int) $time);
2836 $offsettz = $user_dt->getOffset(); // should include dst ?
2837 } else { // with old method (The 'tzuser' was processed like the 'tzuserrel')
2838 $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60; // Will not be used anymore
2839 $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60; // Will not be used anymore
2840 }
2841 }
2842 }
2843 }
2844 if (!is_object($outputlangs)) {
2845 $outputlangs = $langs;
2846 }
2847 if (!$format) {
2848 $format = 'daytextshort';
2849 }
2850
2851 // Do we have to reduce the length of date (year on 2 chars) to save space.
2852 // Note: dayinputnoreduce is same than day but no reduction of year length will be done
2853 $reduceformat = (!empty($conf->dol_optimize_smallscreen) && in_array($format, array('day', 'dayhour', 'dayhoursec'))) ? 1 : 0; // Test on original $format param.
2854 $format = preg_replace('/inputnoreduce/', '', $format); // so format 'dayinputnoreduce' is processed like day
2855 $formatwithoutreduce = preg_replace('/reduceformat/', '', $format);
2856 if ($formatwithoutreduce != $format) {
2857 $format = $formatwithoutreduce;
2858 $reduceformat = 1;
2859 } // so format 'dayreduceformat' is processed like day
2860
2861 // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
2862 // TODO Add format daysmallyear and dayhoursmallyear
2863 if ($format == 'day') {
2864 $format = ($outputlangs->trans("FormatDateShort") != "FormatDateShort" ? $outputlangs->trans("FormatDateShort") : $conf->format_date_short);
2865 } elseif ($format == 'hour') {
2866 $format = ($outputlangs->trans("FormatHourShort") != "FormatHourShort" ? $outputlangs->trans("FormatHourShort") : $conf->format_hour_short);
2867 } elseif ($format == 'hourduration') {
2868 $format = ($outputlangs->trans("FormatHourShortDuration") != "FormatHourShortDuration" ? $outputlangs->trans("FormatHourShortDuration") : $conf->format_hour_short_duration);
2869 } elseif ($format == 'daytext') {
2870 $format = ($outputlangs->trans("FormatDateText") != "FormatDateText" ? $outputlangs->trans("FormatDateText") : $conf->format_date_text);
2871 } elseif ($format == 'daytextshort') {
2872 $format = ($outputlangs->trans("FormatDateTextShort") != "FormatDateTextShort" ? $outputlangs->trans("FormatDateTextShort") : $conf->format_date_text_short);
2873 } elseif ($format == 'dayhour') {
2874 $format = ($outputlangs->trans("FormatDateHourShort") != "FormatDateHourShort" ? $outputlangs->trans("FormatDateHourShort") : $conf->format_date_hour_short);
2875 } elseif ($format == 'dayhoursec') {
2876 $format = ($outputlangs->trans("FormatDateHourSecShort") != "FormatDateHourSecShort" ? $outputlangs->trans("FormatDateHourSecShort") : $conf->format_date_hour_sec_short);
2877 } elseif ($format == 'dayhourtext') {
2878 $format = ($outputlangs->trans("FormatDateHourText") != "FormatDateHourText" ? $outputlangs->trans("FormatDateHourText") : $conf->format_date_hour_text);
2879 } elseif ($format == 'dayhourtextshort') {
2880 $format = ($outputlangs->trans("FormatDateHourTextShort") != "FormatDateHourTextShort" ? $outputlangs->trans("FormatDateHourTextShort") : $conf->format_date_hour_text_short);
2881 } elseif ($format == 'dayhourlog') {
2882 // Format not sensitive to language
2883 $format = '%Y%m%d%H%M%S';
2884 } elseif ($format == 'dayhourlogsmall') {
2885 // Format not sensitive to language
2886 $format = '%y%m%d%H%M';
2887 } elseif ($format == 'dayhourldap') {
2888 $format = '%Y%m%d%H%M%SZ';
2889 } elseif ($format == 'dayhourxcard') {
2890 $format = '%Y%m%dT%H%M%SZ';
2891 } elseif ($format == 'dayxcard') {
2892 $format = '%Y%m%d';
2893 } elseif ($format == 'dayrfc') {
2894 $format = '%Y-%m-%d'; // DATE_RFC3339
2895 } elseif ($format == 'dayhourrfc') {
2896 $format = '%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339
2897 } elseif ($format == 'standard') {
2898 $format = '%Y-%m-%d %H:%M:%S';
2899 }
2900
2901 if ($reduceformat) {
2902 $format = str_replace('%Y', '%y', $format);
2903 $format = str_replace('yyyy', 'yy', $format);
2904 }
2905
2906 // Clean format
2907 if (preg_match('/%b/i', $format)) { // There is some text to translate
2908 // We inhibate translation to text made by strftime functions. We will use trans instead later.
2909 $format = str_replace('%b', '__b__', $format);
2910 $format = str_replace('%B', '__B__', $format);
2911 }
2912 if (preg_match('/%a/i', $format)) { // There is some text to translate
2913 // We inhibate translation to text made by strftime functions. We will use trans instead later.
2914 $format = str_replace('%a', '__a__', $format);
2915 $format = str_replace('%A', '__A__', $format);
2916 }
2917
2918 // Analyze date
2919 $reg = array();
2920 if (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)) { // Deprecated. Ex: 1970-01-01, 1970-01-01 01:00:00, 19700101010000
2921 dol_print_error('', "Functions.lib::dol_print_date function called with a bad value from page ".(empty($_SERVER["PHP_SELF"]) ? 'unknown' : $_SERVER["PHP_SELF"]));
2922 return '';
2923 } elseif (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+) ?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i', $time, $reg)) { // Still available to solve problems in extrafields of type date
2924 // This part of code should not be used anymore.
2925 dol_syslog("Functions.lib::dol_print_date function called with a bad value from page ".(empty($_SERVER["PHP_SELF"]) ? 'unknown' : $_SERVER["PHP_SELF"]), LOG_WARNING);
2926 //if (function_exists('debug_print_backtrace')) debug_print_backtrace();
2927 // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
2928 $syear = (!empty($reg[1]) ? $reg[1] : '');
2929 $smonth = (!empty($reg[2]) ? $reg[2] : '');
2930 $sday = (!empty($reg[3]) ? $reg[3] : '');
2931 $shour = (!empty($reg[4]) ? $reg[4] : '');
2932 $smin = (!empty($reg[5]) ? $reg[5] : '');
2933 $ssec = (!empty($reg[6]) ? $reg[6] : '');
2934
2935 $time = dol_mktime($shour, $smin, $ssec, $smonth, $sday, $syear, true);
2936
2937 if ($to_gmt) {
2938 $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
2939 } else {
2940 $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
2941 }
2942 $dtts = new DateTime();
2943 $dtts->setTimestamp($time);
2944 $dtts->setTimezone($tzo);
2945 $newformat = str_replace(
2946 array('%Y', '%y', '%m', '%d', '%H', '%I', '%M', '%S', '%p', 'T', 'Z', '__a__', '__A__', '__b__', '__B__'),
2947 array('Y', 'y', 'm', 'd', 'H', 'h', 'i', 's', 'A', '__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
2948 $format
2949 );
2950 $ret = $dtts->format($newformat);
2951 $ret = str_replace(
2952 array('__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
2953 array('T', 'Z', '__a__', '__A__', '__b__', '__B__'),
2954 $ret
2955 );
2956 } else {
2957 // Date is a timestamps
2958 if ($time < 100000000000) { // Protection against bad date values
2959 $timetouse = $time + $offsettz + $offsetdst; // TODO We could be able to disable use of offsettz and offsetdst to use only offsettzstring.
2960
2961 if ($to_gmt) {
2962 $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
2963 } else {
2964 $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
2965 }
2966 $dtts = new DateTime();
2967 $dtts->setTimestamp($timetouse);
2968 $dtts->setTimezone($tzo);
2969 $newformat = str_replace(
2970 array('%Y', '%y', '%m', '%d', '%H', '%I', '%M', '%S', '%p', '%w', 'T', 'Z', '__a__', '__A__', '__b__', '__B__'),
2971 array('Y', 'y', 'm', 'd', 'H', 'h', 'i', 's', 'A', 'w', '__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
2972 $format
2973 );
2974 $ret = $dtts->format($newformat);
2975 $ret = str_replace(
2976 array('__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
2977 array('T', 'Z', '__a__', '__A__', '__b__', '__B__'),
2978 $ret
2979 );
2980 //var_dump($ret);exit;
2981 } else {
2982 $ret = 'Bad value '.$time.' for date';
2983 }
2984 }
2985
2986 if (preg_match('/__b__/i', $format)) {
2987 $timetouse = $time + $offsettz + $offsetdst; // TODO We could be able to disable use of offsettz and offsetdst to use only offsettzstring.
2988
2989 if ($to_gmt) {
2990 $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
2991 } else {
2992 $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
2993 }
2994 $dtts = new DateTime();
2995 $dtts->setTimestamp($timetouse);
2996 $dtts->setTimezone($tzo);
2997 $month = $dtts->format("m");
2998 $month = sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'.
2999 if ($encodetooutput) {
3000 $monthtext = $outputlangs->transnoentities('Month'.$month);
3001 $monthtextshort = $outputlangs->transnoentities('MonthShort'.$month);
3002 } else {
3003 $monthtext = $outputlangs->transnoentitiesnoconv('Month'.$month);
3004 $monthtextshort = $outputlangs->transnoentitiesnoconv('MonthShort'.$month);
3005 }
3006 //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
3007 $ret = str_replace('__b__', $monthtextshort, $ret);
3008 $ret = str_replace('__B__', $monthtext, $ret);
3009 //print 'x'.$outputlangs->charset_output.'-'.$ret.'x';
3010 //return $ret;
3011 }
3012 if (preg_match('/__a__/i', $format)) {
3013 //print "time=$time offsettz=$offsettz offsetdst=$offsetdst offsettzstring=$offsettzstring";
3014 $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
3015
3016 if ($to_gmt) {
3017 $tzo = new DateTimeZone('UTC');
3018 } else {
3019 $tzo = new DateTimeZone(date_default_timezone_get());
3020 }
3021 $dtts = new DateTime();
3022 $dtts->setTimestamp($timetouse);
3023 $dtts->setTimezone($tzo);
3024 $w = $dtts->format("w");
3025 $dayweek = $outputlangs->transnoentitiesnoconv('Day'.$w);
3026
3027 $ret = str_replace('__A__', $dayweek, $ret);
3028 $ret = str_replace('__a__', dol_substr($dayweek, 0, 3), $ret);
3029 }
3030
3031 return $ret;
3032}
3033
3034
3055function dol_getdate($timestamp, $fast = false, $forcetimezone = '')
3056{
3057 if ($timestamp === '') {
3058 return array();
3059 }
3060
3061 $datetimeobj = new DateTime();
3062 $datetimeobj->setTimestamp($timestamp); // Use local PHP server timezone
3063 if ($forcetimezone) {
3064 $datetimeobj->setTimezone(new DateTimeZone($forcetimezone == 'gmt' ? 'UTC' : $forcetimezone)); // (add timezone relative to the date entered)
3065 }
3066 $arrayinfo = array(
3067 'year'=>((int) date_format($datetimeobj, 'Y')),
3068 'mon'=>((int) date_format($datetimeobj, 'm')),
3069 'mday'=>((int) date_format($datetimeobj, 'd')),
3070 'wday'=>((int) date_format($datetimeobj, 'w')),
3071 'yday'=>((int) date_format($datetimeobj, 'z')),
3072 'hours'=>((int) date_format($datetimeobj, 'H')),
3073 'minutes'=>((int) date_format($datetimeobj, 'i')),
3074 'seconds'=>((int) date_format($datetimeobj, 's')),
3075 '0'=>$timestamp
3076 );
3077
3078 return $arrayinfo;
3079}
3080
3102function dol_mktime($hour, $minute, $second, $month, $day, $year, $gm = 'auto', $check = 1)
3103{
3104 global $conf;
3105 //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
3106
3107 if ($gm === 'auto') {
3108 $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
3109 }
3110 //print 'gm:'.$gm.' gm === auto:'.($gm === 'auto').'<br>';exit;
3111
3112 // Clean parameters
3113 if ($hour == -1 || empty($hour)) {
3114 $hour = 0;
3115 }
3116 if ($minute == -1 || empty($minute)) {
3117 $minute = 0;
3118 }
3119 if ($second == -1 || empty($second)) {
3120 $second = 0;
3121 }
3122
3123 // Check parameters
3124 if ($check) {
3125 if (!$month || !$day) {
3126 return '';
3127 }
3128 if ($day > 31) {
3129 return '';
3130 }
3131 if ($month > 12) {
3132 return '';
3133 }
3134 if ($hour < 0 || $hour > 24) {
3135 return '';
3136 }
3137 if ($minute < 0 || $minute > 60) {
3138 return '';
3139 }
3140 if ($second < 0 || $second > 60) {
3141 return '';
3142 }
3143 }
3144
3145 if (empty($gm) || ($gm === 'server' || $gm === 'tzserver')) {
3146 $default_timezone = @date_default_timezone_get(); // Example 'Europe/Berlin'
3147 $localtz = new DateTimeZone($default_timezone);
3148 } elseif ($gm === 'user' || $gm === 'tzuser' || $gm === 'tzuserrel') {
3149 // We use dol_tz_string first because it is more reliable.
3150 $default_timezone = (empty($_SESSION["dol_tz_string"]) ? @date_default_timezone_get() : $_SESSION["dol_tz_string"]); // Example 'Europe/Berlin'
3151 try {
3152 $localtz = new DateTimeZone($default_timezone);
3153 } catch (Exception $e) {
3154 dol_syslog("Warning dol_tz_string contains an invalid value ".$_SESSION["dol_tz_string"], LOG_WARNING);
3155 $default_timezone = @date_default_timezone_get();
3156 }
3157 } elseif (strrpos($gm, "tz,") !== false) {
3158 $timezone = str_replace("tz,", "", $gm); // Example 'tz,Europe/Berlin'
3159 try {
3160 $localtz = new DateTimeZone($timezone);
3161 } catch (Exception $e) {
3162 dol_syslog("Warning passed timezone contains an invalid value ".$timezone, LOG_WARNING);
3163 }
3164 }
3165
3166 if (empty($localtz)) {
3167 $localtz = new DateTimeZone('UTC');
3168 }
3169 //var_dump($localtz);
3170 //var_dump($year.'-'.$month.'-'.$day.'-'.$hour.'-'.$minute);
3171 $dt = new DateTime('now', $localtz);
3172 $dt->setDate((int) $year, (int) $month, (int) $day);
3173 $dt->setTime((int) $hour, (int) $minute, (int) $second);
3174 $date = $dt->getTimestamp(); // should include daylight saving time
3175 //var_dump($date);
3176 return $date;
3177}
3178
3179
3190function dol_now($mode = 'auto')
3191{
3192 $ret = 0;
3193
3194 if ($mode === 'auto') {
3195 $mode = 'gmt';
3196 }
3197
3198 if ($mode == 'gmt') {
3199 $ret = time(); // Time for now at greenwich.
3200 } elseif ($mode == 'tzserver') { // Time for now with PHP server timezone added
3201 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
3202 $tzsecond = getServerTimeZoneInt('now'); // Contains tz+dayling saving time
3203 $ret = (int) (dol_now('gmt') + ($tzsecond * 3600));
3204 //} elseif ($mode == 'tzref') {// Time for now with parent company timezone is added
3205 // require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
3206 // $tzsecond=getParentCompanyTimeZoneInt(); // Contains tz+dayling saving time
3207 // $ret=dol_now('gmt')+($tzsecond*3600);
3208 //}
3209 } elseif ($mode == 'tzuser' || $mode == 'tzuserrel') {
3210 // Time for now with user timezone added
3211 //print 'time: '.time();
3212 $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60;
3213 $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60;
3214 $ret = (int) (dol_now('gmt') + ($offsettz + $offsetdst));
3215 }
3216
3217 return $ret;
3218}
3219
3220
3229function dol_print_size($size, $shortvalue = 0, $shortunit = 0)
3230{
3231 global $conf, $langs;
3232 $level = 1024;
3233
3234 if (!empty($conf->dol_optimize_smallscreen)) {
3235 $shortunit = 1;
3236 }
3237
3238 // Set value text
3239 if (empty($shortvalue) || $size < ($level * 10)) {
3240 $ret = $size;
3241 $textunitshort = $langs->trans("b");
3242 $textunitlong = $langs->trans("Bytes");
3243 } else {
3244 $ret = round($size / $level, 0);
3245 $textunitshort = $langs->trans("Kb");
3246 $textunitlong = $langs->trans("KiloBytes");
3247 }
3248 // Use long or short text unit
3249 if (empty($shortunit)) {
3250 $ret .= ' '.$textunitlong;
3251 } else {
3252 $ret .= ' '.$textunitshort;
3253 }
3254
3255 return $ret;
3256}
3257
3268function dol_print_url($url, $target = '_blank', $max = 32, $withpicto = 0, $morecss = '')
3269{
3270 global $langs;
3271
3272 if (empty($url)) {
3273 return '';
3274 }
3275
3276 $linkstart = '<a href="';
3277 if (!preg_match('/^http/i', $url)) {
3278 $linkstart .= 'http://';
3279 }
3280 $linkstart .= $url;
3281 $linkstart .= '"';
3282 if ($target) {
3283 $linkstart .= ' target="'.$target.'"';
3284 }
3285 $linkstart .= ' title="'.$langs->trans("URL").': '.$url.'"';
3286 $linkstart .= '>';
3287
3288 $link = '';
3289 if (!preg_match('/^http/i', $url)) {
3290 $link .= 'http://';
3291 }
3292 $link .= dol_trunc($url, $max);
3293
3294 $linkend = '</a>';
3295
3296 if ($morecss == 'float') { // deprecated
3297 return '<div class="nospan'.($morecss ? ' '.$morecss : '').'" style="margin-right: 10px">'.($withpicto ? img_picto($langs->trans("Url"), 'globe', 'class="paddingrightonly"') : '').$link.'</div>';
3298 } else {
3299 return $linkstart.'<span class="nospan'.($morecss ? ' '.$morecss : '').'" style="margin-right: 10px">'.($withpicto ? img_picto('', 'globe', 'class="paddingrightonly"') : '').$link.'</span>'.$linkend;
3300 }
3301}
3302
3315function dol_print_email($email, $cid = 0, $socid = 0, $addlink = 0, $max = 64, $showinvalid = 1, $withpicto = 0)
3316{
3317 global $user, $langs, $hookmanager;
3318
3319 //global $conf; $conf->global->AGENDA_ADDACTIONFOREMAIL = 1;
3320 //$showinvalid = 1; $email = 'rrrrr';
3321
3322 $newemail = dol_escape_htmltag($email);
3323
3324 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') && $withpicto) {
3325 $withpicto = 0;
3326 }
3327
3328 if (empty($email)) {
3329 return '&nbsp;';
3330 }
3331
3332 if (!empty($addlink)) {
3333 $newemail = '<a class="paddingrightonly" style="text-overflow: ellipsis;" href="';
3334 if (!preg_match('/^mailto:/i', $email)) {
3335 $newemail .= 'mailto:';
3336 }
3337 $newemail .= $email;
3338 $newemail .= '">';
3339
3340 $newemail .= ($withpicto ? img_picto($langs->trans("EMail").' : '.$email, (is_numeric($withpicto) ? 'email' : $withpicto), 'class="paddingrightonly"') : '');
3341
3342 $newemail .= dol_trunc($email, $max);
3343 $newemail .= '</a>';
3344 if ($showinvalid && !isValidEmail($email)) {
3345 $langs->load("errors");
3346 $newemail .= img_warning($langs->trans("ErrorBadEMail", $email), '', 'paddingrightonly');
3347 }
3348
3349 if (($cid || $socid) && isModEnabled('agenda') && $user->hasRight("agenda", "myactions", "create")) {
3350 $type = 'AC_EMAIL';
3351 $linktoaddaction = '';
3352 if (getDolGlobalString('AGENDA_ADDACTIONFOREMAIL')) {
3353 $linktoaddaction = '<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create&amp;backtopage=1&amp;actioncode='.urlencode($type).'&amp;contactid='.((int) $cid).'&amp;socid='.((int) $socid).'">'.img_object($langs->trans("AddAction"), "calendar").'</a>';
3354 }
3355 if ($linktoaddaction) {
3356 $newemail = '<div>'.$newemail.' '.$linktoaddaction.'</div>';
3357 }
3358 }
3359 } else {
3360 $newemail = ($withpicto ? img_picto($langs->trans("EMail").' : '.$email, (is_numeric($withpicto) ? 'email' : $withpicto), 'class="paddingrightonly"') : '').$newemail;
3361
3362 if ($showinvalid && !isValidEmail($email)) {
3363 $langs->load("errors");
3364 $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
3365 }
3366 }
3367
3368 //$rep = '<div class="nospan" style="margin-right: 10px">';
3369 //$rep = ($withpicto ? img_picto($langs->trans("EMail").' : '.$email, (is_numeric($withpicto) ? 'email' : $withpicto), 'class="paddingrightonly"') : '').$newemail;
3370 //$rep .= '</div>';
3371 $rep = $newemail;
3372
3373 if ($hookmanager) {
3374 $parameters = array('cid' => $cid, 'socid' => $socid, 'addlink' => $addlink, 'picto' => $withpicto);
3375
3376 $reshook = $hookmanager->executeHooks('printEmail', $parameters, $email);
3377 if ($reshook > 0) {
3378 $rep = '';
3379 }
3380 $rep .= $hookmanager->resPrint;
3381 }
3382
3383 return $rep;
3384}
3385
3392{
3393 global $conf, $db;
3394
3395 $socialnetworks = array();
3396 // Enable caching of array
3397 require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php';
3398 $cachekey = 'socialnetworks_' . $conf->entity;
3399 $dataretrieved = dol_getcache($cachekey);
3400 if (!is_null($dataretrieved)) {
3401 $socialnetworks = $dataretrieved;
3402 } else {
3403 $sql = "SELECT rowid, code, label, url, icon, active FROM ".MAIN_DB_PREFIX."c_socialnetworks";
3404 $sql .= " WHERE entity=".$conf->entity;
3405 $resql = $db->query($sql);
3406 if ($resql) {
3407 while ($obj = $db->fetch_object($resql)) {
3408 $socialnetworks[$obj->code] = array(
3409 'rowid' => $obj->rowid,
3410 'label' => $obj->label,
3411 'url' => $obj->url,
3412 'icon' => $obj->icon,
3413 'active' => $obj->active,
3414 );
3415 }
3416 }
3417 dol_setcache($cachekey, $socialnetworks); // If setting cache fails, this is not a problem, so we do not test result.
3418 }
3419
3420 return $socialnetworks;
3421}
3422
3433function dol_print_socialnetworks($value, $cid, $socid, $type, $dictsocialnetworks = array())
3434{
3435 global $conf, $user, $langs;
3436
3437 $htmllink = $value;
3438
3439 if (empty($value)) {
3440 return '&nbsp;';
3441 }
3442
3443 if (!empty($type)) {
3444 $htmllink = '<div class="divsocialnetwork inline-block valignmiddle">';
3445 // Use dictionary definition for picto $dictsocialnetworks[$type]['icon']
3446 $htmllink .= '<span class="fab pictofixedwidth '.($dictsocialnetworks[$type]['icon'] ? $dictsocialnetworks[$type]['icon'] : 'fa-link').'"></span>';
3447 if ($type == 'skype') {
3448 $htmllink .= dol_escape_htmltag($value);
3449 $htmllink .= '&nbsp; <a href="skype:';
3450 $htmllink .= dol_string_nospecial($value, '_', '', array('@'));
3451 $htmllink .= '?call" alt="'.$langs->trans("Call").'&nbsp;'.$value.'" title="'.dol_escape_htmltag($langs->trans("Call").' '.$value).'">';
3452 $htmllink .= '<img src="'.DOL_URL_ROOT.'/theme/common/skype_callbutton.png" border="0">';
3453 $htmllink .= '</a><a href="skype:';
3454 $htmllink .= dol_string_nospecial($value, '_', '', array('@'));
3455 $htmllink .= '?chat" alt="'.$langs->trans("Chat").'&nbsp;'.$value.'" title="'.dol_escape_htmltag($langs->trans("Chat").' '.$value).'">';
3456 $htmllink .= '<img class="paddingleft" src="'.DOL_URL_ROOT.'/theme/common/skype_chatbutton.png" border="0">';
3457 $htmllink .= '</a>';
3458 if (($cid || $socid) && isModEnabled('agenda') && $user->hasRight('agenda', 'myactions', 'create')) {
3459 $addlink = 'AC_SKYPE';
3460 $link = '';
3461 if (getDolGlobalString('AGENDA_ADDACTIONFORSKYPE')) {
3462 $link = '<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create&amp;backtopage=1&amp;actioncode='.$addlink.'&amp;contactid='.$cid.'&amp;socid='.$socid.'">'.img_object($langs->trans("AddAction"), "calendar").'</a>';
3463 }
3464 $htmllink .= ($link ? ' '.$link : '');
3465 }
3466 } else {
3467 $networkconstname = 'MAIN_INFO_SOCIETE_'.strtoupper($type).'_URL';
3468 if (getDolGlobalString($networkconstname)) {
3469 $link = str_replace('{socialid}', $value, getDolGlobalString($networkconstname));
3470 if (preg_match('/^https?:\/\//i', $link)) {
3471 $htmllink .= '<a href="'.dol_sanitizeUrl($link, 0).'" target="_blank" rel="noopener noreferrer">'.dol_escape_htmltag($value).'</a>';
3472 } else {
3473 $htmllink .= '<a href="'.dol_sanitizeUrl($link, 1).'" target="_blank" rel="noopener noreferrer">'.dol_escape_htmltag($value).'</a>';
3474 }
3475 } elseif (!empty($dictsocialnetworks[$type]['url'])) {
3476 $tmpvirginurl = preg_replace('/\/?{socialid}/', '', $dictsocialnetworks[$type]['url']);
3477 if ($tmpvirginurl) {
3478 $value = preg_replace('/^www\.'.preg_quote($tmpvirginurl, '/').'\/?/', '', $value);
3479 $value = preg_replace('/^'.preg_quote($tmpvirginurl, '/').'\/?/', '', $value);
3480
3481 $tmpvirginurl3 = preg_replace('/^https:\/\//i', 'https://www.', $tmpvirginurl);
3482 if ($tmpvirginurl3) {
3483 $value = preg_replace('/^www\.'.preg_quote($tmpvirginurl3, '/').'\/?/', '', $value);
3484 $value = preg_replace('/^'.preg_quote($tmpvirginurl3, '/').'\/?/', '', $value);
3485 }
3486
3487 $tmpvirginurl2 = preg_replace('/^https?:\/\//i', '', $tmpvirginurl);
3488 if ($tmpvirginurl2) {
3489 $value = preg_replace('/^www\.'.preg_quote($tmpvirginurl2, '/').'\/?/', '', $value);
3490 $value = preg_replace('/^'.preg_quote($tmpvirginurl2, '/').'\/?/', '', $value);
3491 }
3492 }
3493 $link = str_replace('{socialid}', $value, $dictsocialnetworks[$type]['url']);
3494 if (preg_match('/^https?:\/\//i', $link)) {
3495 $htmllink .= '<a href="'.dol_sanitizeUrl($link, 0).'" target="_blank" rel="noopener noreferrer">'.dol_escape_htmltag($value).'</a>';
3496 } else {
3497 $htmllink .= '<a href="'.dol_sanitizeUrl($link, 1).'" target="_blank" rel="noopener noreferrer">'.dol_escape_htmltag($value).'</a>';
3498 }
3499 } else {
3500 $htmllink .= dol_escape_htmltag($value);
3501 }
3502 }
3503 $htmllink .= '</div>';
3504 } else {
3505 $langs->load("errors");
3506 $htmllink .= img_warning($langs->trans("ErrorBadSocialNetworkValue", $value));
3507 }
3508 return $htmllink;
3509}
3510
3520function dol_print_profids($profID, $profIDtype, $countrycode = '', $addcpButton = 1)
3521{
3522 global $mysoc;
3523
3524 if (empty($profID) || empty($profIDtype)) {
3525 return '';
3526 }
3527 if (empty($countrycode)) {
3528 $countrycode = $mysoc->country_code;
3529 }
3530 $newProfID = $profID;
3531 $id = substr($profIDtype, -1);
3532 $ret = '';
3533 if (strtoupper($countrycode) == 'FR') {
3534 // France
3535 // (see https://www.economie.gouv.fr/entreprises/numeros-identification-entreprise)
3536
3537 if ($id == 1 && dol_strlen($newProfID) == 9) {
3538 // SIREN (ex: 123 123 123)
3539 $newProfID = substr($newProfID, 0, 3).' '.substr($newProfID, 3, 3).' '.substr($newProfID, 6, 3);
3540 }
3541 if ($id == 2 && dol_strlen($newProfID) == 14) {
3542 // SIRET (ex: 123 123 123 12345)
3543 $newProfID = substr($newProfID, 0, 3).' '.substr($newProfID, 3, 3).' '.substr($newProfID, 6, 3).' '.substr($newProfID, 9, 5);
3544 }
3545 if ($id == 3 && dol_strlen($newProfID) == 5) {
3546 // NAF/APE (ex: 69.20Z)
3547 $newProfID = substr($newProfID, 0, 2).'.'.substr($newProfID, 2, 3);
3548 }
3549 if ($profIDtype === 'VAT' && dol_strlen($newProfID) == 13) {
3550 // TVA intracommunautaire (ex: FR12 123 123 123)
3551 $newProfID = substr($newProfID, 0, 4).' '.substr($newProfID, 4, 3).' '.substr($newProfID, 7, 3).' '.substr($newProfID, 10, 3);
3552 }
3553 }
3554 if (!empty($addcpButton)) {
3555 $ret = showValueWithClipboardCPButton(dol_escape_htmltag($profID), ($addcpButton == 1 ? 1 : 0), $newProfID);
3556 } else {
3557 $ret = $newProfID;
3558 }
3559 return $ret;
3560}
3561
3576function dol_print_phone($phone, $countrycode = '', $cid = 0, $socid = 0, $addlink = '', $separ = "&nbsp;", $withpicto = '', $titlealt = '', $adddivfloat = 0)
3577{
3578 global $conf, $user, $langs, $mysoc, $hookmanager;
3579
3580 // Clean phone parameter
3581 $phone = is_null($phone) ? '' : preg_replace("/[\s.-]/", "", trim($phone));
3582 if (empty($phone)) {
3583 return '';
3584 }
3585 if (getDolGlobalString('MAIN_PHONE_SEPAR')) {
3586 $separ = $conf->global->MAIN_PHONE_SEPAR;
3587 }
3588 if (empty($countrycode) && is_object($mysoc)) {
3589 $countrycode = $mysoc->country_code;
3590 }
3591
3592 // Short format for small screens
3593 if ($conf->dol_optimize_smallscreen) {
3594 $separ = '';
3595 }
3596
3597 $newphone = $phone;
3598 if (strtoupper($countrycode) == "FR") {
3599 // France
3600 if (dol_strlen($phone) == 10) {
3601 $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);
3602 } elseif (dol_strlen($phone) == 7) {
3603 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 2);
3604 } elseif (dol_strlen($phone) == 9) {
3605 $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 2).$separ.substr($newphone, 7, 2);
3606 } elseif (dol_strlen($phone) == 11) {
3607 $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);
3608 } elseif (dol_strlen($phone) == 12) {
3609 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
3610 } elseif (dol_strlen($phone) == 13) {
3611 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3).$separ.substr($newphone, 11, 2);
3612 }
3613 } elseif (strtoupper($countrycode) == "CA") {
3614 if (dol_strlen($phone) == 10) {
3615 $newphone = ($separ != '' ? '(' : '').substr($newphone, 0, 3).($separ != '' ? ')' : '').$separ.substr($newphone, 3, 3).($separ != '' ? '-' : '').substr($newphone, 6, 4);
3616 }
3617 } elseif (strtoupper($countrycode) == "PT") {//Portugal
3618 if (dol_strlen($phone) == 13) {//ex: +351_ABC_DEF_GHI
3619 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
3620 }
3621 } elseif (strtoupper($countrycode) == "SR") {//Suriname
3622 if (dol_strlen($phone) == 10) {//ex: +597_ABC_DEF
3623 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3);
3624 } elseif (dol_strlen($phone) == 11) {//ex: +597_ABC_DEFG
3625 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 4);
3626 }
3627 } elseif (strtoupper($countrycode) == "DE") {//Allemagne
3628 if (dol_strlen($phone) == 14) {//ex: +49_ABCD_EFGH_IJK
3629 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 4).$separ.substr($newphone, 11, 3);
3630 } elseif (dol_strlen($phone) == 13) {//ex: +49_ABC_DEFG_HIJ
3631 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 4).$separ.substr($newphone, 10, 3);
3632 }
3633 } elseif (strtoupper($countrycode) == "ES") {//Espagne
3634 if (dol_strlen($phone) == 12) {//ex: +34_ABC_DEF_GHI
3635 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
3636 }
3637 } elseif (strtoupper($countrycode) == "BF") {// Burkina Faso
3638 if (dol_strlen($phone) == 12) {//ex : +22 A BC_DE_FG_HI
3639 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
3640 }
3641 } elseif (strtoupper($countrycode) == "RO") {// Roumanie
3642 if (dol_strlen($phone) == 12) {//ex : +40 AB_CDE_FG_HI
3643 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
3644 }
3645 } elseif (strtoupper($countrycode) == "TR") {//Turquie
3646 if (dol_strlen($phone) == 13) {//ex : +90 ABC_DEF_GHIJ
3647 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
3648 }
3649 } elseif (strtoupper($countrycode) == "US") {//Etat-Unis
3650 if (dol_strlen($phone) == 12) {//ex: +1 ABC_DEF_GHIJ
3651 $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
3652 }
3653 } elseif (strtoupper($countrycode) == "MX") {//Mexique
3654 if (dol_strlen($phone) == 12) {//ex: +52 ABCD_EFG_HI
3655 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
3656 } elseif (dol_strlen($phone) == 11) {//ex: +52 AB_CD_EF_GH
3657 $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);
3658 } elseif (dol_strlen($phone) == 13) {//ex: +52 ABC_DEF_GHIJ
3659 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
3660 }
3661 } elseif (strtoupper($countrycode) == "ML") {//Mali
3662 if (dol_strlen($phone) == 12) {//ex: +223 AB_CD_EF_GH
3663 $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);
3664 }
3665 } elseif (strtoupper($countrycode) == "TH") {//Thaïlande
3666 if (dol_strlen($phone) == 11) {//ex: +66_ABC_DE_FGH
3667 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
3668 } elseif (dol_strlen($phone) == 12) {//ex: +66_A_BCD_EF_GHI
3669 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 3);
3670 }
3671 } elseif (strtoupper($countrycode) == "MU") {
3672 //Maurice
3673 if (dol_strlen($phone) == 11) {//ex: +230_ABC_DE_FG
3674 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2);
3675 } elseif (dol_strlen($phone) == 12) {//ex: +230_ABCD_EF_GH
3676 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
3677 }
3678 } elseif (strtoupper($countrycode) == "ZA") {//Afrique du sud
3679 if (dol_strlen($phone) == 12) {//ex: +27_AB_CDE_FG_HI
3680 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
3681 }
3682 } elseif (strtoupper($countrycode) == "SY") {//Syrie
3683 if (dol_strlen($phone) == 12) {//ex: +963_AB_CD_EF_GH
3684 $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);
3685 } elseif (dol_strlen($phone) == 13) {//ex: +963_AB_CD_EF_GHI
3686 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 3);
3687 }
3688 } elseif (strtoupper($countrycode) == "AE") {//Emirats Arabes Unis
3689 if (dol_strlen($phone) == 12) {//ex: +971_ABC_DEF_GH
3690 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
3691 } elseif (dol_strlen($phone) == 13) {//ex: +971_ABC_DEF_GHI
3692 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
3693 } elseif (dol_strlen($phone) == 14) {//ex: +971_ABC_DEF_GHIK
3694 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 4);
3695 }
3696 } elseif (strtoupper($countrycode) == "DZ") {//Algérie
3697 if (dol_strlen($phone) == 13) {//ex: +213_ABC_DEF_GHI
3698 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
3699 }
3700 } elseif (strtoupper($countrycode) == "BE") {//Belgique
3701 if (dol_strlen($phone) == 11) {//ex: +32_ABC_DE_FGH
3702 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
3703 } elseif (dol_strlen($phone) == 12) {//ex: +32_ABC_DEF_GHI
3704 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
3705 }
3706 } elseif (strtoupper($countrycode) == "PF") {//Polynésie française
3707 if (dol_strlen($phone) == 12) {//ex: +689_AB_CD_EF_GH
3708 $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);
3709 }
3710 } elseif (strtoupper($countrycode) == "CO") {//Colombie
3711 if (dol_strlen($phone) == 13) {//ex: +57_ABC_DEF_GH_IJ
3712 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 2).$separ.substr($newphone, 11, 2);
3713 }
3714 } elseif (strtoupper($countrycode) == "JO") {//Jordanie
3715 if (dol_strlen($phone) == 12) {//ex: +962_A_BCD_EF_GH
3716 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 1).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2);
3717 }
3718 } elseif (strtoupper($countrycode) == "JM") {//Jamaïque
3719 if (dol_strlen($newphone) == 12) {//ex: +1867_ABC_DEFG
3720 $newphone = substr($newphone, 0, 5).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
3721 }
3722 } elseif (strtoupper($countrycode) == "MG") {//Madagascar
3723 if (dol_strlen($phone) == 13) {//ex: +261_AB_CD_EFG_HI
3724 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3).$separ.substr($newphone, 11, 2);
3725 }
3726 } elseif (strtoupper($countrycode) == "GB") {//Royaume uni
3727 if (dol_strlen($phone) == 13) {//ex: +44_ABCD_EFG_HIJ
3728 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
3729 }
3730 } elseif (strtoupper($countrycode) == "CH") {//Suisse
3731 if (dol_strlen($phone) == 12) {//ex: +41_AB_CDE_FG_HI
3732 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
3733 } elseif (dol_strlen($phone) == 15) {// +41_AB_CDE_FGH_IJKL
3734 $newphone = $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 3).$separ.substr($newphone, 11, 4);
3735 }
3736 } elseif (strtoupper($countrycode) == "TN") {//Tunisie
3737 if (dol_strlen($phone) == 12) {//ex: +216_AB_CDE_FGH
3738 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
3739 }
3740 } elseif (strtoupper($countrycode) == "GF") {//Guyane francaise
3741 if (dol_strlen($phone) == 13) {//ex: +594_ABC_DE_FG_HI (ABC=594 de nouveau)
3742 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2).$separ.substr($newphone, 11, 2);
3743 }
3744 } elseif (strtoupper($countrycode) == "GP") {//Guadeloupe
3745 if (dol_strlen($phone) == 13) {//ex: +590_ABC_DE_FG_HI (ABC=590 de nouveau)
3746 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2).$separ.substr($newphone, 11, 2);
3747 }
3748 } elseif (strtoupper($countrycode) == "MQ") {//Martinique
3749 if (dol_strlen($phone) == 13) {//ex: +596_ABC_DE_FG_HI (ABC=596 de nouveau)
3750 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2).$separ.substr($newphone, 11, 2);
3751 }
3752 } elseif (strtoupper($countrycode) == "IT") {//Italie
3753 if (dol_strlen($phone) == 12) {//ex: +39_ABC_DEF_GHI
3754 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
3755 } elseif (dol_strlen($phone) == 13) {//ex: +39_ABC_DEF_GH_IJ
3756 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 2).$separ.substr($newphone, 11, 2);
3757 }
3758 } elseif (strtoupper($countrycode) == "AU") {
3759 //Australie
3760 if (dol_strlen($phone) == 12) {
3761 //ex: +61_A_BCDE_FGHI
3762 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 4);
3763 }
3764 } elseif (strtoupper($countrycode) == "LU") {
3765 // Luxembourg
3766 if (dol_strlen($phone) == 10) {// fixe 6 chiffres +352_AA_BB_CC
3767 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2);
3768 } elseif (dol_strlen($phone) == 11) {// fixe 7 chiffres +352_AA_BB_CC_D
3769 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 1);
3770 } elseif (dol_strlen($phone) == 12) {// fixe 8 chiffres +352_AA_BB_CC_DD
3771 $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);
3772 } elseif (dol_strlen($phone) == 13) {// mobile +352_AAA_BB_CC_DD
3773 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2).$separ.substr($newphone, 11, 2);
3774 }
3775 }
3776
3777 $newphoneastart = $newphoneaend = '';
3778 if (!empty($addlink)) { // Link on phone number (+ link to add action if conf->global->AGENDA_ADDACTIONFORPHONE set)
3779 if ($addlink == 'tel' || $conf->browser->layout == 'phone' || (isModEnabled('clicktodial') && getDolGlobalString('CLICKTODIAL_USE_TEL_LINK_ON_PHONE_NUMBERS'))) { // If phone or option for, we use link of phone
3780 $newphoneastart = '<a href="tel:'.$phone.'">';
3781 $newphoneaend .= '</a>';
3782 } elseif (isModEnabled('clicktodial') && $addlink == 'AC_TEL') { // If click to dial, we use click to dial url
3783 if (empty($user->clicktodial_loaded)) {
3784 $user->fetch_clicktodial();
3785 }
3786
3787 // Define urlmask
3788 $urlmask = getDolGlobalString('CLICKTODIAL_URL', 'ErrorClickToDialModuleNotConfigured');
3789 if (!empty($user->clicktodial_url)) {
3790 $urlmask = $user->clicktodial_url;
3791 }
3792
3793 $clicktodial_poste = (!empty($user->clicktodial_poste) ? urlencode($user->clicktodial_poste) : '');
3794 $clicktodial_login = (!empty($user->clicktodial_login) ? urlencode($user->clicktodial_login) : '');
3795 $clicktodial_password = (!empty($user->clicktodial_password) ? urlencode($user->clicktodial_password) : '');
3796 // This line is for backward compatibility
3797 $url = sprintf($urlmask, urlencode($phone), $clicktodial_poste, $clicktodial_login, $clicktodial_password);
3798 // Thoose lines are for substitution
3799 $substitarray = array('__PHONEFROM__'=>$clicktodial_poste,
3800 '__PHONETO__'=>urlencode($phone),
3801 '__LOGIN__'=>$clicktodial_login,
3802 '__PASS__'=>$clicktodial_password);
3803 $url = make_substitutions($url, $substitarray);
3804 if (!getDolGlobalString('CLICKTODIAL_DO_NOT_USE_AJAX_CALL')) {
3805 // Default and recommended: New method using ajax without submiting a page making a javascript history.go(-1) back
3806 $newphoneastart = '<a href="'.$url.'" class="cssforclicktodial">'; // Call of ajax is handled by the lib_foot.js.php on class 'cssforclicktodial'
3807 $newphoneaend = '</a>';
3808 } else {
3809 // Old method
3810 $newphoneastart = '<a href="'.$url.'"';
3811 if (getDolGlobalString('CLICKTODIAL_FORCENEWTARGET')) {
3812 $newphoneastart .= ' target="_blank" rel="noopener noreferrer"';
3813 }
3814 $newphoneastart .= '>';
3815 $newphoneaend .= '</a>';
3816 }
3817 }
3818
3819 //if (($cid || $socid) && isModEnabled('agenda') && $user->hasRight('agenda', 'myactions', 'create'))
3820 if (isModEnabled('agenda') && $user->hasRight("agenda", "myactions", "create")) {
3821 $type = 'AC_TEL';
3822 $addlinktoagenda = '';
3823 if ($addlink == 'AC_FAX') {
3824 $type = 'AC_FAX';
3825 }
3826 if (getDolGlobalString('AGENDA_ADDACTIONFORPHONE')) {
3827 $addlinktoagenda = '<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create&amp;backtopage='. urlencode($_SERVER['REQUEST_URI']) .'&amp;actioncode='.$type.($cid ? '&amp;contactid='.$cid : '').($socid ? '&amp;socid='.$socid : '').'">'.img_object($langs->trans("AddAction"), "calendar").'</a>';
3828 }
3829 if ($addlinktoagenda) {
3830 $newphone = '<span>'.$newphone.' '.$addlinktoagenda.'</span>';
3831 }
3832 }
3833 }
3834
3835 if (empty($titlealt)) {
3836 $titlealt = ($withpicto == 'fax' ? $langs->trans("Fax") : $langs->trans("Phone"));
3837 }
3838 $rep = '';
3839
3840 if ($hookmanager) {
3841 $parameters = array('countrycode' => $countrycode, 'cid' => $cid, 'socid' => $socid, 'titlealt' => $titlealt, 'picto' => $withpicto);
3842 $reshook = $hookmanager->executeHooks('printPhone', $parameters, $phone);
3843 $rep .= $hookmanager->resPrint;
3844 }
3845 if (empty($reshook)) {
3846 $picto = '';
3847 if ($withpicto) {
3848 if ($withpicto == 'fax') {
3849 $picto = 'phoning_fax';
3850 } elseif ($withpicto == 'phone') {
3851 $picto = 'phoning';
3852 } elseif ($withpicto == 'mobile') {
3853 $picto = 'phoning_mobile';
3854 } else {
3855 $picto = '';
3856 }
3857 }
3858 if ($adddivfloat == 1) {
3859 $rep .= '<div class="nospan float" style="margin-right: 10px">';
3860 } elseif (empty($adddivfloat)) {
3861 $rep .= '<span style="margin-right: 10px;">';
3862 }
3863
3864 $rep .= $newphoneastart;
3865 $rep .= ($withpicto ? img_picto($titlealt, 'object_'.$picto.'.png') : '');
3866 if ($separ != 'hidenum') {
3867 $rep .= ($withpicto ? ' ' : '').$newphone;
3868 }
3869 $rep .= $newphoneaend;
3870
3871 if ($adddivfloat == 1) {
3872 $rep .= '</div>';
3873 } elseif (empty($adddivfloat)) {
3874 $rep .= '</span>';
3875 }
3876 }
3877
3878 return $rep;
3879}
3880
3888function dol_print_ip($ip, $mode = 0)
3889{
3890 global $langs;
3891
3892 $ret = '';
3893
3894 if (empty($mode)) {
3895 $ret .= $ip;
3896 }
3897
3898 if ($mode != 2) {
3899 $countrycode = dolGetCountryCodeFromIp($ip);
3900 if ($countrycode) { // If success, countrycode is us, fr, ...
3901 if (file_exists(DOL_DOCUMENT_ROOT.'/theme/common/flags/'.$countrycode.'.png')) {
3902 $ret .= ' '.img_picto($countrycode.' '.$langs->trans("AccordingToGeoIPDatabase"), DOL_URL_ROOT.'/theme/common/flags/'.$countrycode.'.png', '', 1);
3903 } else {
3904 $ret .= ' ('.$countrycode.')';
3905 }
3906 } else {
3907 // Nothing
3908 }
3909 }
3910
3911 return $ret;
3912}
3913
3923{
3924 if (empty($_SERVER['HTTP_X_FORWARDED_FOR']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {
3925 if (empty($_SERVER['HTTP_CLIENT_IP']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_CLIENT_IP'])) {
3926 if (empty($_SERVER["HTTP_CF_CONNECTING_IP"])) {
3927 $ip = (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']); // value may have been the IP of the proxy and not the client
3928 } else {
3929 $ip = $_SERVER["HTTP_CF_CONNECTING_IP"]; // value here may have been forged by client
3930 }
3931 } else {
3932 $ip = $_SERVER['HTTP_CLIENT_IP']; // value is clean here but may have been forged by proxy
3933 }
3934 } else {
3935 $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; // value is clean here but may have been forged by proxy
3936 }
3937 return $ip;
3938}
3939
3948function isHTTPS()
3949{
3950 $isSecure = false;
3951 if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
3952 $isSecure = true;
3953 } elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') {
3954 $isSecure = true;
3955 }
3956 return $isSecure;
3957}
3958
3966{
3967 global $conf;
3968
3969 $countrycode = '';
3970
3971 if (!empty($conf->geoipmaxmind->enabled)) {
3972 $datafile = getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE');
3973 //$ip='24.24.24.24';
3974 //$datafile='/usr/share/GeoIP/GeoIP.dat'; Note that this must be downloaded datafile (not same than datafile provided with ubuntu packages)
3975 include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
3976 $geoip = new DolGeoIP('country', $datafile);
3977 //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
3978 $countrycode = $geoip->getCountryCodeFromIP($ip);
3979 }
3980
3981 return $countrycode;
3982}
3983
3984
3992{
3993 global $conf, $langs, $user;
3994
3995 //$ret=$user->xxx;
3996 $ret = '';
3997 if (!empty($conf->geoipmaxmind->enabled)) {
3998 $ip = getUserRemoteIP();
3999 $datafile = getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE');
4000 //$ip='24.24.24.24';
4001 //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';
4002 include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
4003 $geoip = new DolGeoIP('country', $datafile);
4004 $countrycode = $geoip->getCountryCodeFromIP($ip);
4005 $ret = $countrycode;
4006 }
4007 return $ret;
4008}
4009
4022function dol_print_address($address, $htmlid, $element, $id, $noprint = 0, $charfornl = '')
4023{
4024 global $conf, $user, $langs, $hookmanager;
4025
4026 $out = '';
4027
4028 if ($address) {
4029 if ($hookmanager) {
4030 $parameters = array('element' => $element, 'id' => $id);
4031 $reshook = $hookmanager->executeHooks('printAddress', $parameters, $address);
4032 $out .= $hookmanager->resPrint;
4033 }
4034 if (empty($reshook)) {
4035 if (empty($charfornl)) {
4036 $out .= nl2br($address);
4037 } else {
4038 $out .= preg_replace('/[\r\n]+/', $charfornl, $address);
4039 }
4040
4041 // TODO Remove this block, we can add this using the hook now
4042 $showgmap = $showomap = 0;
4043 if (($element == 'thirdparty' || $element == 'societe') && isModEnabled('google') && getDolGlobalString('GOOGLE_ENABLE_GMAPS')) {
4044 $showgmap = 1;
4045 }
4046 if ($element == 'contact' && isModEnabled('google') && getDolGlobalString('GOOGLE_ENABLE_GMAPS_CONTACTS')) {
4047 $showgmap = 1;
4048 }
4049 if ($element == 'member' && isModEnabled('google') && getDolGlobalString('GOOGLE_ENABLE_GMAPS_MEMBERS')) {
4050 $showgmap = 1;
4051 }
4052 if ($element == 'user' && isModEnabled('google') && getDolGlobalString('GOOGLE_ENABLE_GMAPS_USERS')) {
4053 $showgmap = 1;
4054 }
4055 if (($element == 'thirdparty' || $element == 'societe') && isModEnabled('openstreetmap') && getDolGlobalString('OPENSTREETMAP_ENABLE_MAPS')) {
4056 $showomap = 1;
4057 }
4058 if ($element == 'contact' && isModEnabled('openstreetmap') && getDolGlobalString('OPENSTREETMAP_ENABLE_MAPS_CONTACTS')) {
4059 $showomap = 1;
4060 }
4061 if ($element == 'member' && isModEnabled('openstreetmap') && getDolGlobalString('OPENSTREETMAP_ENABLE_MAPS_MEMBERS')) {
4062 $showomap = 1;
4063 }
4064 if ($element == 'user' && isModEnabled('openstreetmap') && getDolGlobalString('OPENSTREETMAP_ENABLE_MAPS_USERS')) {
4065 $showomap = 1;
4066 }
4067 if ($showgmap) {
4068 $url = dol_buildpath('/google/gmaps.php?mode='.$element.'&id='.$id, 1);
4069 $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
4070 }
4071 if ($showomap) {
4072 $url = dol_buildpath('/openstreetmap/maps.php?mode='.$element.'&id='.$id, 1);
4073 $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'_openstreetmap" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
4074 }
4075 }
4076 }
4077 if ($noprint) {
4078 return $out;
4079 } else {
4080 print $out;
4081 }
4082}
4083
4084
4094function isValidEmail($address, $acceptsupervisorkey = 0, $acceptuserkey = 0)
4095{
4096 if ($acceptsupervisorkey && $address == '__SUPERVISOREMAIL__') {
4097 return true;
4098 }
4099 if ($acceptuserkey && $address == '__USER_EMAIL__') {
4100 return true;
4101 }
4102 if (filter_var($address, FILTER_VALIDATE_EMAIL)) {
4103 return true;
4104 }
4105
4106 return false;
4107}
4108
4117function isValidMXRecord($domain)
4118{
4119 if (function_exists('idn_to_ascii') && function_exists('checkdnsrr')) {
4120 if (!checkdnsrr(idn_to_ascii($domain), 'MX')) {
4121 return 0;
4122 }
4123 if (function_exists('getmxrr')) {
4124 $mxhosts = array();
4125 $weight = array();
4126 getmxrr(idn_to_ascii($domain), $mxhosts, $weight);
4127 if (count($mxhosts) > 1) {
4128 return 1;
4129 }
4130 if (count($mxhosts) == 1 && !empty($mxhosts[0])) {
4131 return 1;
4132 }
4133
4134 return 0;
4135 }
4136 }
4137
4138 // function idn_to_ascii or checkdnsrr or getmxrr does not exists
4139 return -1;
4140}
4141
4149function isValidPhone($phone)
4150{
4151 return true;
4152}
4153
4154
4164function dolGetFirstLetters($s, $nbofchar = 1)
4165{
4166 $ret = '';
4167 $tmparray = explode(' ', $s);
4168 foreach ($tmparray as $tmps) {
4169 $ret .= dol_substr($tmps, 0, $nbofchar);
4170 }
4171
4172 return $ret;
4173}
4174
4175
4183function dol_strlen($string, $stringencoding = 'UTF-8')
4184{
4185 if (is_null($string)) {
4186 return 0;
4187 }
4188
4189 if (function_exists('mb_strlen')) {
4190 return mb_strlen($string, $stringencoding);
4191 } else {
4192 return strlen($string);
4193 }
4194}
4195
4206function dol_substr($string, $start, $length = null, $stringencoding = '', $trunconbytes = 0)
4207{
4208 global $langs;
4209
4210 if (empty($stringencoding)) {
4211 $stringencoding = $langs->charset_output;
4212 }
4213
4214 $ret = '';
4215 if (empty($trunconbytes)) {
4216 if (function_exists('mb_substr')) {
4217 $ret = mb_substr($string, $start, $length, $stringencoding);
4218 } else {
4219 $ret = substr($string, $start, $length);
4220 }
4221 } else {
4222 if (function_exists('mb_strcut')) {
4223 $ret = mb_strcut($string, $start, $length, $stringencoding);
4224 } else {
4225 $ret = substr($string, $start, $length);
4226 }
4227 }
4228 return $ret;
4229}
4230
4231
4245function dol_trunc($string, $size = 40, $trunc = 'right', $stringencoding = 'UTF-8', $nodot = 0, $display = 0)
4246{
4247 global $conf;
4248
4249 if (empty($size) || getDolGlobalString('MAIN_DISABLE_TRUNC')) {
4250 return $string;
4251 }
4252
4253 if (empty($stringencoding)) {
4254 $stringencoding = 'UTF-8';
4255 }
4256 // reduce for small screen
4257 if ($conf->dol_optimize_smallscreen == 1 && $display == 1) {
4258 $size = round($size / 3);
4259 }
4260
4261 // We go always here
4262 if ($trunc == 'right') {
4263 $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
4264 if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
4265 // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
4266 return dol_substr($newstring, 0, $size, $stringencoding).($nodot ? '' : '…');
4267 } else {
4268 //return 'u'.$size.'-'.$newstring.'-'.dol_strlen($newstring,$stringencoding).'-'.$string;
4269 return $string;
4270 }
4271 } elseif ($trunc == 'middle') {
4272 $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
4273 if (dol_strlen($newstring, $stringencoding) > 2 && dol_strlen($newstring, $stringencoding) > ($size + 1)) {
4274 $size1 = round($size / 2);
4275 $size2 = round($size / 2);
4276 return dol_substr($newstring, 0, $size1, $stringencoding).'…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size2, $size2, $stringencoding);
4277 } else {
4278 return $string;
4279 }
4280 } elseif ($trunc == 'left') {
4281 $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
4282 if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
4283 // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
4284 return '…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size, $size, $stringencoding);
4285 } else {
4286 return $string;
4287 }
4288 } elseif ($trunc == 'wrap') {
4289 $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
4290 if (dol_strlen($newstring, $stringencoding) > ($size + 1)) {
4291 return dol_substr($newstring, 0, $size, $stringencoding)."\n".dol_trunc(dol_substr($newstring, $size, dol_strlen($newstring, $stringencoding) - $size, $stringencoding), $size, $trunc);
4292 } else {
4293 return $string;
4294 }
4295 } else {
4296 return 'BadParam3CallingDolTrunc';
4297 }
4298}
4299
4306function getPictoForType($key)
4307{
4308 // Set array with type -> picto
4309 $type2picto = array(
4310 'varchar'=>'font',
4311 'text'=>'font',
4312 'html'=>'code',
4313 'int'=>'sort-numeric-down',
4314 'double'=>'sort-numeric-down',
4315 'price'=>'currency',
4316 'pricecy'=>'multicurrency',
4317 'password' => 'key',
4318 'boolean'=>'check-square',
4319 'date'=>'calendar',
4320 'datetime'=>'calendar',
4321 'phone'=> 'phone',
4322 'mail'=> 'email',
4323 'url'=> 'url',
4324 'ip'=> 'country',
4325 'select' => 'list',
4326 'sellist' => 'list',
4327 'radio' => 'check-circle',
4328 'checkbox' => 'check-square',
4329 'chkbxlst' => 'check-square',
4330 'link' => 'link',
4331 'separate'=> 'minus'
4332 );
4333
4334 if (!empty($type2picto[$key])) {
4335 return img_picto('', $type2picto[$key], 'class="pictofixedwidth"');
4336 }
4337
4338 return img_picto('', 'generic', 'class="pictofixedwidth"');
4339}
4340
4341
4363function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0, $alt = '', $morecss = '', $marginleftonlyshort = 2)
4364{
4365 global $conf, $langs;
4366
4367 // We forge fullpathpicto for image to $path/img/$picto. By default, we take DOL_URL_ROOT/theme/$conf->theme/img/$picto
4368 $url = DOL_URL_ROOT;
4369 $theme = isset($conf->theme) ? $conf->theme : null;
4370 $path = 'theme/'.$theme;
4371 if (empty($picto)) {
4372 $picto = 'generic';
4373 }
4374
4375 // Define fullpathpicto to use into src
4376 if ($pictoisfullpath) {
4377 // Clean parameters
4378 if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
4379 $picto .= '.png';
4380 }
4381 $fullpathpicto = $picto;
4382 $reg = array();
4383 if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
4384 $morecss .= ($morecss ? ' ' : '').$reg[1];
4385 $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
4386 }
4387 } else {
4388 $pictowithouttext = preg_replace('/(\.png|\.gif|\.svg)$/', '', (is_null($picto) ? '' : $picto));
4389 $pictowithouttext = str_replace('object_', '', $pictowithouttext);
4390 $pictowithouttext = str_replace('_nocolor', '', $pictowithouttext);
4391
4392 if (strpos($pictowithouttext, 'fontawesome_') === 0 || strpos($pictowithouttext, 'fa-') === 0) {
4393 // This is a font awesome image 'fontawesome_xxx' or 'fa-xxx'
4394 $pictowithouttext = str_replace('fontawesome_', '', $pictowithouttext);
4395 $pictowithouttext = str_replace('fa-', '', $pictowithouttext);
4396
4397 // Compatibility with old fontawesome versions
4398 if ($pictowithouttext == 'file-o') {
4399 $pictowithouttext = 'file';
4400 }
4401
4402 $pictowithouttextarray = explode('_', $pictowithouttext);
4403 $marginleftonlyshort = 0;
4404
4405 if (!empty($pictowithouttextarray[1])) {
4406 // Syntax is 'fontawesome_fakey_faprefix_facolor_fasize' or 'fa-fakey_faprefix_facolor_fasize'
4407 $fakey = 'fa-'.$pictowithouttextarray[0];
4408 $faprefix = empty($pictowithouttextarray[1]) ? 'fas' : $pictowithouttextarray[1];
4409 $facolor = empty($pictowithouttextarray[2]) ? '' : $pictowithouttextarray[2];
4410 $fasize = empty($pictowithouttextarray[3]) ? '' : $pictowithouttextarray[3];
4411 } else {
4412 $fakey = 'fa-'.$pictowithouttext;
4413 $faprefix = 'fas';
4414 $facolor = '';
4415 $fasize = '';
4416 }
4417
4418 // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
4419 // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
4420 $morestyle = '';
4421 $reg = array();
4422 if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
4423 $morecss .= ($morecss ? ' ' : '').$reg[1];
4424 $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
4425 }
4426 if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
4427 $morestyle = $reg[1];
4428 $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt);
4429 }
4430 $moreatt = trim($moreatt);
4431
4432 $enabledisablehtml = '<span class="'.$faprefix.' '.$fakey.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
4433 $enabledisablehtml .= ($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').($morestyle ? ' '.$morestyle : '').'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : '').'>';
4434 /*if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
4435 $enabledisablehtml .= $titlealt;
4436 }*/
4437 $enabledisablehtml .= '</span>';
4438
4439 return $enabledisablehtml;
4440 }
4441
4442 if (empty($srconly) && in_array($pictowithouttext, array(
4443 '1downarrow', '1uparrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected',
4444 'accountancy', 'accounting_account', 'account', 'accountline', 'action', 'add', 'address', 'angle-double-down', 'angle-double-up', 'asset',
4445 'bank_account', 'barcode', 'bank', 'bell', 'bill', 'billa', 'billr', 'billd', 'birthday-cake', 'bookmark', 'bom', 'briefcase-medical', 'bug', 'building',
4446 'card', 'calendarlist', 'calendar', 'calendarmonth', 'calendarweek', 'calendarday', 'calendarperuser', 'calendarpertype',
4447 'cash-register', 'category', 'chart', 'check', 'clock', 'clone', 'close_title', 'code', 'cog', 'collab', 'company', 'contact', 'country', 'contract', 'conversation', 'cron', 'cross', 'cubes',
4448 'check-circle', 'check-square', 'currency', 'multicurrency',
4449 'chevron-left', 'chevron-right', 'chevron-down', 'chevron-top', 'commercial', 'companies',
4450 'delete', 'dolly', 'dollyrevert', 'donation', 'download', 'dynamicprice',
4451 'edit', 'ellipsis-h', 'email', 'entity', 'envelope', 'eraser', 'establishment', 'expensereport', 'external-link-alt', 'external-link-square-alt', 'eye',
4452 'filter', 'file', 'file-o', 'file-code', 'file-export', 'file-import', 'file-upload', 'autofill', 'folder', 'folder-open', 'folder-plus', 'font',
4453 'gears', 'generate', 'generic', 'globe', 'globe-americas', 'graph', 'grip', 'grip_title', 'group',
4454 'hands-helping', 'help', 'holiday',
4455 'id-card', 'images', 'incoterm', 'info', 'intervention', 'inventory', 'intracommreport', 'jobprofile',
4456 'key', 'knowledgemanagement',
4457 'label', 'language', 'line', 'link', 'list', 'list-alt', 'listlight', 'loan', 'lock', 'lot', 'long-arrow-alt-right',
4458 'margin', 'map-marker-alt', 'member', 'meeting', 'minus', 'money-bill-alt', 'movement', 'mrp', 'note', 'next',
4459 'off', 'on', 'order',
4460 'paiment', 'paragraph', 'play', 'pdf', 'phone', 'phoning', 'phoning_mobile', 'phoning_fax', 'playdisabled', 'previous', 'poll', 'pos', 'printer', 'product', 'propal', 'proposal', 'puce',
4461 'stock', 'resize', 'service', 'stats',
4462 'security', 'setup', 'share-alt', 'sign-out', 'split', 'stripe', 'stripe-s', 'switch_off', 'switch_on', 'switch_on_warning', 'switch_on_red', 'tools', 'unlink', 'uparrow', 'user', 'user-tie', 'vcard', 'wrench',
4463 'github', 'google', 'jabber', 'microsoft', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'youtube', 'google-plus-g', 'whatsapp',
4464 'generic', 'home', 'hrm', 'members', 'products', 'invoicing',
4465 'partnership', 'payment', 'payment_vat', 'pencil-ruler', 'pictoconfirm', 'preview', 'project', 'projectpub', 'projecttask', 'question', 'refresh', 'region',
4466 'salary', 'shipment', 'state', 'supplier_invoice', 'supplier_invoicea', 'supplier_invoicer', 'supplier_invoiced',
4467 'technic', 'ticket',
4468 'error', 'warning',
4469 'recent', 'reception', 'recruitmentcandidature', 'recruitmentjobposition', 'replacement', 'resource', 'recurring','rss',
4470 'shapes', 'skill', 'square', 'sort-numeric-down', 'stop-circle', 'supplier', 'supplier_proposal', 'supplier_order', 'supplier_invoice',
4471 'tick', 'timespent', 'title_setup', 'title_accountancy', 'title_bank', 'title_hrm', 'title_agenda',
4472 'uncheck', 'url', 'user-cog', 'user-injured', 'user-md', 'vat', 'website', 'workstation', 'webhook', 'world', 'private',
4473 'conferenceorbooth', 'eventorganization',
4474 'stamp', 'signature'
4475 ))) {
4476 $fakey = $pictowithouttext;
4477 $facolor = '';
4478 $fasize = '';
4479 $fa = getDolGlobalString('MAIN_FONTAWESOME_ICON_STYLE', 'fas');
4480 if (in_array($pictowithouttext, array('card', 'bell', 'clock', 'establishment', 'file', 'file-o', 'generic', 'minus-square', 'object_generic', 'pdf', 'plus-square', 'timespent', 'note', 'off', 'on', 'object_bookmark', 'bookmark', 'vcard'))) {
4481 $fa = 'far';
4482 }
4483 if (in_array($pictowithouttext, array('black-tie', 'github', 'google', 'microsoft', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'stripe', 'stripe-s', 'youtube', 'google-plus-g', 'whatsapp'))) {
4484 $fa = 'fab';
4485 }
4486
4487 $arrayconvpictotofa = array(
4488 'account'=>'university', 'accounting_account'=>'clipboard-list', 'accountline'=>'receipt', 'accountancy'=>'search-dollar', 'action'=>'calendar-alt', 'add'=>'plus-circle', 'address'=> 'address-book', 'asset'=>'money-check-alt', 'autofill'=>'fill',
4489 'bank_account'=>'university',
4490 'bill'=>'file-invoice-dollar', 'billa'=>'file-excel', 'billr'=>'file-invoice-dollar', 'billd'=>'file-medical',
4491 'supplier_invoice'=>'file-invoice-dollar', 'supplier_invoicea'=>'file-excel', 'supplier_invoicer'=>'file-invoice-dollar', 'supplier_invoiced'=>'file-medical',
4492 'bom'=>'shapes',
4493 'card'=>'address-card', 'chart'=>'chart-line', 'company'=>'building', 'contact'=>'address-book', 'contract'=>'suitcase', 'collab'=>'people-arrows', 'conversation'=>'comments', 'country'=>'globe-americas', 'cron'=>'business-time', 'cross'=>'times',
4494 'donation'=>'file-alt', 'dynamicprice'=>'hand-holding-usd',
4495 'setup'=>'cog', 'companies'=>'building', 'products'=>'cube', 'commercial'=>'suitcase', 'invoicing'=>'coins',
4496 'accounting'=>'search-dollar', 'category'=>'tag', 'dollyrevert'=>'dolly',
4497 'file-o'=>'file', 'generate'=>'plus-square', 'hrm'=>'user-tie', 'incoterm'=>'truck-loading',
4498 'margin'=>'calculator', 'members'=>'user-friends', 'ticket'=>'ticket-alt', 'globe'=>'external-link-alt', 'lot'=>'barcode',
4499 'email'=>'at', 'establishment'=>'building', 'edit'=>'pencil-alt', 'entity'=>'globe',
4500 'graph'=>'chart-line', 'grip_title'=>'arrows-alt', 'grip'=>'arrows-alt', 'help'=>'question-circle',
4501 'generic'=>'file', 'holiday'=>'umbrella-beach',
4502 'info'=>'info-circle', 'inventory'=>'boxes', 'intracommreport'=>'globe-europe', 'jobprofile'=>'cogs',
4503 'knowledgemanagement'=>'ticket-alt', 'label'=>'layer-group', 'line'=>'bars', 'loan'=>'money-bill-alt',
4504 'member'=>'user-alt', 'meeting'=>'chalkboard-teacher', 'mrp'=>'cubes', 'next'=>'arrow-alt-circle-right',
4505 'trip'=>'wallet', 'expensereport'=>'wallet', 'group'=>'users', 'movement'=>'people-carry',
4506 'sign-out'=>'sign-out-alt',
4507 'switch_off'=>'toggle-off', 'switch_on'=>'toggle-on', 'switch_on_warning'=>'toggle-on', 'switch_on_red'=>'toggle-on', 'check'=>'check', 'bookmark'=>'star',
4508 'bank'=>'university', 'close_title'=>'times', 'delete'=>'trash', 'filter'=>'filter',
4509 'list-alt'=>'list-alt', 'calendarlist'=>'bars', 'calendar'=>'calendar-alt', 'calendarmonth'=>'calendar-alt', 'calendarweek'=>'calendar-week', 'calendarday'=>'calendar-day', 'calendarperuser'=>'table',
4510 'intervention'=>'ambulance', 'invoice'=>'file-invoice-dollar', 'order'=>'file-invoice',
4511 'error'=>'exclamation-triangle', 'warning'=>'exclamation-triangle',
4512 'other'=>'square',
4513 'playdisabled'=>'play', 'pdf'=>'file-pdf', 'poll'=>'check-double', 'pos'=>'cash-register', 'preview'=>'binoculars', 'project'=>'project-diagram', 'projectpub'=>'project-diagram', 'projecttask'=>'tasks', 'propal'=>'file-signature', 'proposal'=>'file-signature',
4514 'partnership'=>'handshake', 'payment'=>'money-check-alt', 'payment_vat'=>'money-check-alt', 'pictoconfirm'=>'check-square', 'phoning'=>'phone', 'phoning_mobile'=>'mobile-alt', 'phoning_fax'=>'fax', 'previous'=>'arrow-alt-circle-left', 'printer'=>'print', 'product'=>'cube', 'puce'=>'angle-right',
4515 'recent' => 'check-square', 'reception'=>'dolly', 'recruitmentjobposition'=>'id-card-alt', 'recruitmentcandidature'=>'id-badge',
4516 'resize'=>'crop', 'supplier_order'=>'dol-order_supplier', 'supplier_proposal'=>'file-signature',
4517 'refresh'=>'redo', 'region'=>'map-marked', 'replacement'=>'exchange-alt', 'resource'=>'laptop-house', 'recurring'=>'history',
4518 'service'=>'concierge-bell',
4519 'skill'=>'shapes', 'state'=>'map-marked-alt', 'security'=>'key', 'salary'=>'wallet', 'shipment'=>'dolly', 'stock'=>'box-open', 'stats' => 'chart-bar', 'split'=>'code-branch', 'stripe'=>'stripe-s',
4520 'supplier'=>'building', 'technic'=>'cogs',
4521 'timespent'=>'clock', 'tick' => 'check', 'title_setup'=>'tools', 'title_accountancy'=>'money-check-alt', 'title_bank'=>'university', 'title_hrm'=>'umbrella-beach',
4522 'title_agenda'=>'calendar-alt',
4523 'uncheck'=>'times', 'uparrow'=>'share', 'url'=>'external-link-alt', 'vat'=>'money-check-alt', 'vcard'=>'arrow-alt-circle-down',
4524 'jabber'=>'comment-o',
4525 'website'=>'globe-americas', 'workstation'=>'pallet', 'webhook'=>'bullseye', 'world'=>'globe', 'private'=>'user-lock',
4526 'conferenceorbooth'=>'chalkboard-teacher', 'eventorganization'=>'project-diagram'
4527 );
4528 if ($conf->currency == 'EUR') {
4529 $arrayconvpictotofa['currency'] = 'euro-sign';
4530 $arrayconvpictotofa['multicurrency'] = 'dollar-sign';
4531 } else {
4532 $arrayconvpictotofa['currency'] = 'dollar-sign';
4533 $arrayconvpictotofa['multicurrency'] = 'euro-sign';
4534 }
4535 if ($pictowithouttext == 'off') {
4536 $fakey = 'fa-square';
4537 $fasize = '1.3em';
4538 } elseif ($pictowithouttext == 'on') {
4539 $fakey = 'fa-check-square';
4540 $fasize = '1.3em';
4541 } elseif ($pictowithouttext == 'listlight') {
4542 $fakey = 'fa-download';
4543 $marginleftonlyshort = 1;
4544 } elseif ($pictowithouttext == 'printer') {
4545 $fakey = 'fa-print';
4546 $fasize = '1.2em';
4547 } elseif ($pictowithouttext == 'note') {
4548 $fakey = 'fa-sticky-note';
4549 $marginleftonlyshort = 1;
4550 } elseif (in_array($pictowithouttext, array('1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'))) {
4551 $convertarray = array('1uparrow'=>'caret-up', '1downarrow'=>'caret-down', '1leftarrow'=>'caret-left', '1rightarrow'=>'caret-right', '1uparrow_selected'=>'caret-up', '1downarrow_selected'=>'caret-down', '1leftarrow_selected'=>'caret-left', '1rightarrow_selected'=>'caret-right');
4552 $fakey = 'fa-'.$convertarray[$pictowithouttext];
4553 if (preg_match('/selected/', $pictowithouttext)) {
4554 $facolor = '#888';
4555 }
4556 $marginleftonlyshort = 1;
4557 } elseif (!empty($arrayconvpictotofa[$pictowithouttext])) {
4558 $fakey = 'fa-'.$arrayconvpictotofa[$pictowithouttext];
4559 } else {
4560 $fakey = 'fa-'.$pictowithouttext;
4561 }
4562
4563 if (in_array($pictowithouttext, array('dollyrevert', 'member', 'members', 'contract', 'group', 'resource', 'shipment'))) {
4564 $morecss .= ' em092';
4565 }
4566 if (in_array($pictowithouttext, array('conferenceorbooth', 'collab', 'eventorganization', 'holiday', 'info', 'project', 'workstation'))) {
4567 $morecss .= ' em088';
4568 }
4569 if (in_array($pictowithouttext, array('asset', 'intervention', 'payment', 'loan', 'partnership', 'stock', 'technic'))) {
4570 $morecss .= ' em080';
4571 }
4572
4573 // Define $marginleftonlyshort
4574 $arrayconvpictotomarginleftonly = array(
4575 'bank', 'check', 'delete', 'generic', 'grip', 'grip_title', 'jabber',
4576 'grip_title', 'grip', 'listlight', 'note', 'on', 'off', 'playdisabled', 'printer', 'resize', 'sign-out', 'stats', 'switch_on', 'switch_on_red', 'switch_off',
4577 'uparrow', '1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'
4578 );
4579 if (!isset($arrayconvpictotomarginleftonly[$pictowithouttext])) {
4580 $marginleftonlyshort = 0;
4581 }
4582
4583 // Add CSS
4584 $arrayconvpictotomorcess = array(
4585 'action'=>'infobox-action', 'account'=>'infobox-bank_account', 'accounting_account'=>'infobox-bank_account', 'accountline'=>'infobox-bank_account', 'accountancy'=>'infobox-bank_account', 'asset'=>'infobox-bank_account',
4586 'bank_account'=>'infobox-bank_account',
4587 'bill'=>'infobox-commande', 'billa'=>'infobox-commande', 'billr'=>'infobox-commande', 'billd'=>'infobox-commande',
4588 'margin'=>'infobox-bank_account', 'conferenceorbooth'=>'infobox-project',
4589 'cash-register'=>'infobox-bank_account', 'contract'=>'infobox-contrat', 'check'=>'font-status4', 'collab'=>'infobox-action', 'conversation'=>'infobox-contrat',
4590 'donation'=>'infobox-commande', 'dolly'=>'infobox-commande', 'dollyrevert'=>'flip infobox-order_supplier',
4591 'ecm'=>'infobox-action', 'eventorganization'=>'infobox-project',
4592 'hrm'=>'infobox-adherent', 'group'=>'infobox-adherent', 'intervention'=>'infobox-contrat',
4593 'incoterm'=>'infobox-supplier_proposal',
4594 'currency'=>'infobox-bank_account', 'multicurrency'=>'infobox-bank_account',
4595 'members'=>'infobox-adherent', 'member'=>'infobox-adherent', 'money-bill-alt'=>'infobox-bank_account',
4596 'order'=>'infobox-commande',
4597 'user'=>'infobox-adherent', 'users'=>'infobox-adherent',
4598 'error'=>'pictoerror', 'warning'=>'pictowarning', 'switch_on'=>'font-status4', 'switch_on_warning'=>'font-status4 warning', 'switch_on_red'=>'font-status8',
4599 'holiday'=>'infobox-holiday', 'info'=>'opacityhigh', 'invoice'=>'infobox-commande',
4600 'knowledgemanagement'=>'infobox-contrat rotate90', 'loan'=>'infobox-bank_account',
4601 'payment'=>'infobox-bank_account', 'payment_vat'=>'infobox-bank_account', 'poll'=>'infobox-adherent', 'pos'=>'infobox-bank_account', 'project'=>'infobox-project', 'projecttask'=>'infobox-project',
4602 'propal'=>'infobox-propal', 'proposal'=>'infobox-propal','private'=>'infobox-project',
4603 'reception'=>'flip', 'recruitmentjobposition'=>'infobox-adherent', 'recruitmentcandidature'=>'infobox-adherent',
4604 'resource'=>'infobox-action',
4605 'salary'=>'infobox-bank_account', 'shapes'=>'infobox-adherent', 'shipment'=>'infobox-commande', 'supplier_invoice'=>'infobox-order_supplier', 'supplier_invoicea'=>'infobox-order_supplier', 'supplier_invoiced'=>'infobox-order_supplier',
4606 'supplier'=>'infobox-order_supplier', 'supplier_order'=>'infobox-order_supplier', 'supplier_proposal'=>'infobox-supplier_proposal',
4607 'ticket'=>'infobox-contrat', 'title_accountancy'=>'infobox-bank_account', 'title_hrm'=>'infobox-holiday', 'expensereport'=>'infobox-expensereport', 'trip'=>'infobox-expensereport', 'title_agenda'=>'infobox-action',
4608 'vat'=>'infobox-bank_account',
4609 //'title_setup'=>'infobox-action', 'tools'=>'infobox-action',
4610 'list-alt'=>'imgforviewmode', 'calendar'=>'imgforviewmode', 'calendarweek'=>'imgforviewmode', 'calendarmonth'=>'imgforviewmode', 'calendarday'=>'imgforviewmode', 'calendarperuser'=>'imgforviewmode'
4611 );
4612 if (!empty($arrayconvpictotomorcess[$pictowithouttext]) && strpos($picto, '_nocolor') === false) {
4613 $morecss .= ($morecss ? ' ' : '').$arrayconvpictotomorcess[$pictowithouttext];
4614 }
4615
4616 // Define $color
4617 $arrayconvpictotocolor = array(
4618 'address'=>'#6c6aa8', 'building'=>'#6c6aa8', 'bom'=>'#a69944',
4619 'clone'=>'#999', 'cog'=>'#999', 'companies'=>'#6c6aa8', 'company'=>'#6c6aa8', 'contact'=>'#6c6aa8', 'cron'=>'#555',
4620 'dynamicprice'=>'#a69944',
4621 'edit'=>'#444', 'note'=>'#999', 'error'=>'', 'help'=>'#bbb', 'listlight'=>'#999', 'language'=>'#555',
4622 //'dolly'=>'#a69944', 'dollyrevert'=>'#a69944',
4623 'lock'=>'#ddd', 'lot'=>'#a69944',
4624 'map-marker-alt'=>'#aaa', 'mrp'=>'#a69944', 'product'=>'#a69944', 'service'=>'#a69944', 'inventory'=>'#a69944', 'stock'=>'#a69944', 'movement'=>'#a69944',
4625 'other'=>'#ddd', 'world'=>'#986c6a',
4626 'partnership'=>'#6c6aa8', 'playdisabled'=>'#ccc', 'printer'=>'#444', 'projectpub'=>'#986c6a', 'reception'=>'#a69944', 'resize'=>'#444', 'rss'=>'#cba',
4627 //'shipment'=>'#a69944',
4628 'security'=>'#999', 'square'=>'#888', 'stop-circle'=>'#888', 'stats'=>'#444', 'switch_off'=>'#999',
4629 'technic' => '#999', 'tick' => '#282', 'timespent' => '#555',
4630 'uncheck'=>'#800', 'uparrow'=>'#555', 'user-cog'=>'#999', 'country'=>'#aaa', 'globe-americas'=>'#aaa', 'region'=>'#aaa', 'state'=>'#aaa',
4631 'website'=>'#304', 'workstation'=>'#a69944'
4632 );
4633 if (isset($arrayconvpictotocolor[$pictowithouttext]) && strpos($picto, '_nocolor') === false) {
4634 $facolor = $arrayconvpictotocolor[$pictowithouttext];
4635 }
4636
4637 // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
4638 // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
4639 $morestyle = '';
4640 $reg = array();
4641 if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
4642 $morecss .= ($morecss ? ' ' : '').$reg[1];
4643 $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
4644 }
4645 if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
4646 $morestyle = $reg[1];
4647 $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt);
4648 }
4649 $moreatt = trim($moreatt);
4650
4651 $enabledisablehtml = '<span class="'.$fa.' '.$fakey.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
4652 $enabledisablehtml .= ($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').($morestyle ? ' '.$morestyle : '').'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : '').'>';
4653 /*if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
4654 $enabledisablehtml .= $titlealt;
4655 }*/
4656 $enabledisablehtml .= '</span>';
4657
4658 return $enabledisablehtml;
4659 }
4660
4661 if (getDolGlobalString('MAIN_OVERWRITE_THEME_PATH')) {
4662 $path = getDolGlobalString('MAIN_OVERWRITE_THEME_PATH') . '/theme/'.$theme; // If the theme does not have the same name as the module
4663 } elseif (getDolGlobalString('MAIN_OVERWRITE_THEME_RES')) {
4664 $path = getDolGlobalString('MAIN_OVERWRITE_THEME_RES') . '/theme/' . getDolGlobalString('MAIN_OVERWRITE_THEME_RES'); // To allow an external module to overwrite image resources whatever is activated theme
4665 } elseif (!empty($conf->modules_parts['theme']) && array_key_exists($theme, $conf->modules_parts['theme'])) {
4666 $path = $theme.'/theme/'.$theme; // If the theme have the same name as the module
4667 }
4668
4669 // If we ask an image into $url/$mymodule/img (instead of default path)
4670 $regs = array();
4671 if (preg_match('/^([^@]+)@([^@]+)$/i', $picto, $regs)) {
4672 $picto = $regs[1];
4673 $path = $regs[2]; // $path is $mymodule
4674 }
4675
4676 // Clean parameters
4677 if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
4678 $picto .= '.png';
4679 }
4680 // If alt path are defined, define url where img file is, according to physical path
4681 // ex: array(["main"]=>"/home/maindir/htdocs", ["alt0"]=>"/home/moddir0/htdocs", ...)
4682 foreach ($conf->file->dol_document_root as $type => $dirroot) {
4683 if ($type == 'main') {
4684 continue;
4685 }
4686 // This need a lot of time, that's why enabling alternative dir like "custom" dir is not recommanded
4687 if (file_exists($dirroot.'/'.$path.'/img/'.$picto)) {
4688 $url = DOL_URL_ROOT.$conf->file->dol_url_root[$type];
4689 break;
4690 }
4691 }
4692
4693 // $url is '' or '/custom', $path is current theme or
4694 $fullpathpicto = $url.'/'.$path.'/img/'.$picto;
4695 }
4696
4697 if ($srconly) {
4698 return $fullpathpicto;
4699 }
4700
4701 // tag title is used for tooltip on <a>, tag alt can be used with very simple text on image for blind people
4702 return '<img src="'.$fullpathpicto.'"'.($notitle ? '' : ' alt="'.dol_escape_htmltag($alt).'"').(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt.($morecss ? ' class="'.$morecss.'"' : '') : ' class="inline-block'.($morecss ? ' '.$morecss : '').'"').'>'; // Alt is used for accessibility, title for popup
4703}
4704
4718function img_object($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0)
4719{
4720 if (strpos($picto, '^') === 0) {
4721 return img_picto($titlealt, str_replace('^', '', $picto), $moreatt, $pictoisfullpath, $srconly, $notitle);
4722 } else {
4723 return img_picto($titlealt, 'object_'.$picto, $moreatt, $pictoisfullpath, $srconly, $notitle);
4724 }
4725}
4726
4738function img_weather($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $morecss = '')
4739{
4740 global $conf;
4741
4742 if (is_numeric($picto)) {
4743 //$leveltopicto = array(0=>'weather-clear.png', 1=>'weather-few-clouds.png', 2=>'weather-clouds.png', 3=>'weather-many-clouds.png', 4=>'weather-storm.png');
4744 //$picto = $leveltopicto[$picto];
4745 return '<i class="fa fa-weather-level'.$picto.'"></i>';
4746 } elseif (!preg_match('/(\.png|\.gif)$/i', $picto)) {
4747 $picto .= '.png';
4748 }
4749
4750 $path = DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/weather/'.$picto;
4751
4752 return img_picto($titlealt, $path, $moreatt, 1, 0, 0, '', $morecss);
4753}
4754
4766function img_picto_common($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $notitle = 0)
4767{
4768 global $conf;
4769
4770 if (!preg_match('/(\.png|\.gif)$/i', $picto)) {
4771 $picto .= '.png';
4772 }
4773
4774 if ($pictoisfullpath) {
4775 $path = $picto;
4776 } else {
4777 $path = DOL_URL_ROOT.'/theme/common/'.$picto;
4778
4779 if (getDolGlobalInt('MAIN_MODULE_CAN_OVERWRITE_COMMONICONS')) {
4780 $themepath = DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/'.$picto;
4781
4782 if (file_exists($themepath)) {
4783 $path = $themepath;
4784 }
4785 }
4786 }
4787
4788 return img_picto($titlealt, $path, $moreatt, 1, 0, $notitle);
4789}
4790
4804function img_action($titlealt, $numaction, $picto = '', $moreatt = '')
4805{
4806 global $langs;
4807
4808 if (empty($titlealt) || $titlealt == 'default') {
4809 if ($numaction == '-1' || $numaction == 'ST_NO') {
4810 $numaction = -1;
4811 $titlealt = $langs->transnoentitiesnoconv('ChangeDoNotContact');
4812 } elseif ($numaction == '0' || $numaction == 'ST_NEVER') {
4813 $numaction = 0;
4814 $titlealt = $langs->transnoentitiesnoconv('ChangeNeverContacted');
4815 } elseif ($numaction == '1' || $numaction == 'ST_TODO') {
4816 $numaction = 1;
4817 $titlealt = $langs->transnoentitiesnoconv('ChangeToContact');
4818 } elseif ($numaction == '2' || $numaction == 'ST_PEND') {
4819 $numaction = 2;
4820 $titlealt = $langs->transnoentitiesnoconv('ChangeContactInProcess');
4821 } elseif ($numaction == '3' || $numaction == 'ST_DONE') {
4822 $numaction = 3;
4823 $titlealt = $langs->transnoentitiesnoconv('ChangeContactDone');
4824 } else {
4825 $titlealt = $langs->transnoentitiesnoconv('ChangeStatus '.$numaction);
4826 $numaction = 0;
4827 }
4828 }
4829 if (!is_numeric($numaction)) {
4830 $numaction = 0;
4831 }
4832
4833 return img_picto($titlealt, (empty($picto) ? 'stcomm'.$numaction.'.png' : $picto), $moreatt);
4834}
4835
4843function img_pdf($titlealt = 'default', $size = 3)
4844{
4845 global $langs;
4846
4847 if ($titlealt == 'default') {
4848 $titlealt = $langs->trans('Show');
4849 }
4850
4851 return img_picto($titlealt, 'pdf'.$size.'.png');
4852}
4853
4861function img_edit_add($titlealt = 'default', $other = '')
4862{
4863 global $langs;
4864
4865 if ($titlealt == 'default') {
4866 $titlealt = $langs->trans('Add');
4867 }
4868
4869 return img_picto($titlealt, 'edit_add.png', $other);
4870}
4878function img_edit_remove($titlealt = 'default', $other = '')
4879{
4880 global $langs;
4881
4882 if ($titlealt == 'default') {
4883 $titlealt = $langs->trans('Remove');
4884 }
4885
4886 return img_picto($titlealt, 'edit_remove.png', $other);
4887}
4888
4897function img_edit($titlealt = 'default', $float = 0, $other = '')
4898{
4899 global $langs;
4900
4901 if ($titlealt == 'default') {
4902 $titlealt = $langs->trans('Modify');
4903 }
4904
4905 return img_picto($titlealt, 'edit.png', ($float ? 'style="float: '.($langs->tab_translate["DIRECTION"] == 'rtl' ? 'left' : 'right').'"' : "").($other ? ' '.$other : ''));
4906}
4907
4916function img_view($titlealt = 'default', $float = 0, $other = 'class="valignmiddle"')
4917{
4918 global $langs;
4919
4920 if ($titlealt == 'default') {
4921 $titlealt = $langs->trans('View');
4922 }
4923
4924 $moreatt = ($float ? 'style="float: right" ' : '').$other;
4925
4926 return img_picto($titlealt, 'eye', $moreatt);
4927}
4928
4937function img_delete($titlealt = 'default', $other = 'class="pictodelete"', $morecss = '')
4938{
4939 global $langs;
4940
4941 if ($titlealt == 'default') {
4942 $titlealt = $langs->trans('Delete');
4943 }
4944
4945 return img_picto($titlealt, 'delete.png', $other, false, 0, 0, '', $morecss);
4946}
4947
4955function img_printer($titlealt = "default", $other = '')
4956{
4957 global $langs;
4958 if ($titlealt == "default") {
4959 $titlealt = $langs->trans("Print");
4960 }
4961 return img_picto($titlealt, 'printer.png', $other);
4962}
4963
4971function img_split($titlealt = 'default', $other = 'class="pictosplit"')
4972{
4973 global $langs;
4974
4975 if ($titlealt == 'default') {
4976 $titlealt = $langs->trans('Split');
4977 }
4978
4979 return img_picto($titlealt, 'split.png', $other);
4980}
4981
4989function img_help($usehelpcursor = 1, $usealttitle = 1)
4990{
4991 global $langs;
4992
4993 if ($usealttitle) {
4994 if (is_string($usealttitle)) {
4995 $usealttitle = dol_escape_htmltag($usealttitle);
4996 } else {
4997 $usealttitle = $langs->trans('Info');
4998 }
4999 }
5000
5001 return img_picto($usealttitle, 'info.png', 'style="vertical-align: middle;'.($usehelpcursor == 1 ? ' cursor: help' : ($usehelpcursor == 2 ? ' cursor: pointer' : '')).'"');
5002}
5003
5010function img_info($titlealt = 'default')
5011{
5012 global $langs;
5013
5014 if ($titlealt == 'default') {
5015 $titlealt = $langs->trans('Informations');
5016 }
5017
5018 return img_picto($titlealt, 'info.png', 'style="vertical-align: middle;"');
5019}
5020
5029function img_warning($titlealt = 'default', $moreatt = '', $morecss = 'pictowarning')
5030{
5031 global $langs;
5032
5033 if ($titlealt == 'default') {
5034 $titlealt = $langs->trans('Warning');
5035 }
5036
5037 //return '<div class="imglatecoin">'.img_picto($titlealt, 'warning_white.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): '')).'</div>';
5038 return img_picto($titlealt, 'warning.png', 'class="'.$morecss.'"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt) : ''));
5039}
5040
5047function img_error($titlealt = 'default')
5048{
5049 global $langs;
5050
5051 if ($titlealt == 'default') {
5052 $titlealt = $langs->trans('Error');
5053 }
5054
5055 return img_picto($titlealt, 'error.png');
5056}
5057
5065function img_next($titlealt = 'default', $moreatt = '')
5066{
5067 global $langs;
5068
5069 if ($titlealt == 'default') {
5070 $titlealt = $langs->trans('Next');
5071 }
5072
5073 //return img_picto($titlealt, 'next.png', $moreatt);
5074 return '<span class="fa fa-chevron-right paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
5075}
5076
5084function img_previous($titlealt = 'default', $moreatt = '')
5085{
5086 global $langs;
5087
5088 if ($titlealt == 'default') {
5089 $titlealt = $langs->trans('Previous');
5090 }
5091
5092 //return img_picto($titlealt, 'previous.png', $moreatt);
5093 return '<span class="fa fa-chevron-left paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
5094}
5095
5104function img_down($titlealt = 'default', $selected = 0, $moreclass = '')
5105{
5106 global $langs;
5107
5108 if ($titlealt == 'default') {
5109 $titlealt = $langs->trans('Down');
5110 }
5111
5112 return img_picto($titlealt, ($selected ? '1downarrow_selected.png' : '1downarrow.png'), 'class="imgdown'.($moreclass ? " ".$moreclass : "").'"');
5113}
5114
5123function img_up($titlealt = 'default', $selected = 0, $moreclass = '')
5124{
5125 global $langs;
5126
5127 if ($titlealt == 'default') {
5128 $titlealt = $langs->trans('Up');
5129 }
5130
5131 return img_picto($titlealt, ($selected ? '1uparrow_selected.png' : '1uparrow.png'), 'class="imgup'.($moreclass ? " ".$moreclass : "").'"');
5132}
5133
5142function img_left($titlealt = 'default', $selected = 0, $moreatt = '')
5143{
5144 global $langs;
5145
5146 if ($titlealt == 'default') {
5147 $titlealt = $langs->trans('Left');
5148 }
5149
5150 return img_picto($titlealt, ($selected ? '1leftarrow_selected.png' : '1leftarrow.png'), $moreatt);
5151}
5152
5161function img_right($titlealt = 'default', $selected = 0, $moreatt = '')
5162{
5163 global $langs;
5164
5165 if ($titlealt == 'default') {
5166 $titlealt = $langs->trans('Right');
5167 }
5168
5169 return img_picto($titlealt, ($selected ? '1rightarrow_selected.png' : '1rightarrow.png'), $moreatt);
5170}
5171
5179function img_allow($allow, $titlealt = 'default')
5180{
5181 global $langs;
5182
5183 if ($titlealt == 'default') {
5184 $titlealt = $langs->trans('Active');
5185 }
5186
5187 if ($allow == 1) {
5188 return img_picto($titlealt, 'tick.png');
5189 }
5190
5191 return '-';
5192}
5193
5201function img_credit_card($brand, $morecss = null)
5202{
5203 if (is_null($morecss)) {
5204 $morecss = 'fa-2x';
5205 }
5206
5207 if ($brand == 'visa' || $brand == 'Visa') {
5208 $brand = 'cc-visa';
5209 } elseif ($brand == 'mastercard' || $brand == 'MasterCard') {
5210 $brand = 'cc-mastercard';
5211 } elseif ($brand == 'amex' || $brand == 'American Express') {
5212 $brand = 'cc-amex';
5213 } elseif ($brand == 'discover' || $brand == 'Discover') {
5214 $brand = 'cc-discover';
5215 } elseif ($brand == 'jcb' || $brand == 'JCB') {
5216 $brand = 'cc-jcb';
5217 } elseif ($brand == 'diners' || $brand == 'Diners club') {
5218 $brand = 'cc-diners-club';
5219 } elseif (!in_array($brand, array('cc-visa', 'cc-mastercard', 'cc-amex', 'cc-discover', 'cc-jcb', 'cc-diners-club'))) {
5220 $brand = 'credit-card';
5221 }
5222
5223 return '<span class="fa fa-'.$brand.' fa-fw'.($morecss ? ' '.$morecss : '').'"></span>';
5224}
5225
5234function img_mime($file, $titlealt = '', $morecss = '')
5235{
5236 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
5237
5238 $mimetype = dol_mimetype($file, '', 1);
5239 $mimeimg = dol_mimetype($file, '', 2);
5240 $mimefa = dol_mimetype($file, '', 4);
5241
5242 if (empty($titlealt)) {
5243 $titlealt = 'Mime type: '.$mimetype;
5244 }
5245
5246 //return img_picto_common($titlealt, 'mime/'.$mimeimg, 'class="'.$morecss.'"');
5247 return '<i class="fa fa-'.$mimefa.' paddingright'.($morecss ? ' '.$morecss : '').'"'.($titlealt ? ' title="'.$titlealt.'"' : '').'></i>';
5248}
5249
5250
5258function img_search($titlealt = 'default', $other = '')
5259{
5260 global $conf, $langs;
5261
5262 if ($titlealt == 'default') {
5263 $titlealt = $langs->trans('Search');
5264 }
5265
5266 $img = img_picto($titlealt, 'search.png', $other, false, 1);
5267
5268 $input = '<input type="image" class="liste_titre" name="button_search" src="'.$img.'" ';
5269 $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
5270
5271 return $input;
5272}
5273
5281function img_searchclear($titlealt = 'default', $other = '')
5282{
5283 global $conf, $langs;
5284
5285 if ($titlealt == 'default') {
5286 $titlealt = $langs->trans('Search');
5287 }
5288
5289 $img = img_picto($titlealt, 'searchclear.png', $other, false, 1);
5290
5291 $input = '<input type="image" class="liste_titre" name="button_removefilter" src="'.$img.'" ';
5292 $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
5293
5294 return $input;
5295}
5296
5308function info_admin($text, $infoonimgalt = 0, $nodiv = 0, $admin = '1', $morecss = 'hideonsmartphone', $textfordropdown = '')
5309{
5310 global $conf, $langs;
5311
5312 if ($infoonimgalt) {
5313 $result = img_picto($text, 'info', 'class="'.($morecss ? ' '.$morecss : '').'"');
5314 } else {
5315 if (empty($conf->use_javascript_ajax)) {
5316 $textfordropdown = '';
5317 }
5318
5319 $class = (empty($admin) ? 'undefined' : ($admin == '1' ? 'info' : $admin));
5320 $result = ($nodiv ? '' : '<div class="'.$class.($morecss ? ' '.$morecss : '').($textfordropdown ? ' hidden' : '').'">').'<span class="fa fa-info-circle" title="'.dol_escape_htmltag($admin ? $langs->trans('InfoAdmin') : $langs->trans('Note')).'"></span> '.$text.($nodiv ? '' : '</div>');
5321
5322 if ($textfordropdown) {
5323 $tmpresult = '<span class="'.$class.'text opacitymedium cursorpointer">'.$langs->trans($textfordropdown).' '.img_picto($langs->trans($textfordropdown), '1downarrow').'</span>';
5324 $tmpresult .= '<script nonce="'.getNonce().'" type="text/javascript">
5325 jQuery(document).ready(function() {
5326 jQuery(".'.$class.'text").click(function() {
5327 console.log("toggle text");
5328 jQuery(".'.$class.'").toggle();
5329 });
5330 });
5331 </script>';
5332
5333 $result = $tmpresult.$result;
5334 }
5335 }
5336
5337 return $result;
5338}
5339
5340
5352function dol_print_error($db = '', $error = '', $errors = null)
5353{
5354 global $conf, $langs, $argv;
5355 global $dolibarr_main_prod;
5356
5357 $out = '';
5358 $syslog = '';
5359
5360 // If error occurs before the $lang object was loaded
5361 if (!$langs) {
5362 require_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
5363 $langs = new Translate('', $conf);
5364 $langs->load("main");
5365 }
5366
5367 // Load translation files required by the error messages
5368 $langs->loadLangs(array('main', 'errors'));
5369
5370 if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
5371 $out .= $langs->trans("DolibarrHasDetectedError").".<br>\n";
5372 if (getDolGlobalInt('MAIN_FEATURES_LEVEL') > 0) {
5373 $out .= "You use an experimental or develop level of features, so please do NOT report any bugs or vulnerability, except if problem is confirmed after moving option MAIN_FEATURES_LEVEL back to 0.<br>\n";
5374 }
5375 $out .= $langs->trans("InformationToHelpDiagnose").":<br>\n";
5376
5377 $out .= "<b>".$langs->trans("Date").":</b> ".dol_print_date(time(), 'dayhourlog')."<br>\n";
5378 $out .= "<b>".$langs->trans("Dolibarr").":</b> ".DOL_VERSION." - https://www.dolibarr.org<br>\n";
5379 if (isset($conf->global->MAIN_FEATURES_LEVEL)) {
5380 $out .= "<b>".$langs->trans("LevelOfFeature").":</b> ".getDolGlobalInt('MAIN_FEATURES_LEVEL')."<br>\n";
5381 }
5382 if (function_exists("phpversion")) {
5383 $out .= "<b>".$langs->trans("PHP").":</b> ".phpversion()."<br>\n";
5384 }
5385 $out .= "<b>".$langs->trans("Server").":</b> ".(isset($_SERVER["SERVER_SOFTWARE"]) ? dol_htmlentities($_SERVER["SERVER_SOFTWARE"], ENT_COMPAT) : '')."<br>\n";
5386 if (function_exists("php_uname")) {
5387 $out .= "<b>".$langs->trans("OS").":</b> ".php_uname()."<br>\n";
5388 }
5389 $out .= "<b>".$langs->trans("UserAgent").":</b> ".(isset($_SERVER["HTTP_USER_AGENT"]) ? dol_htmlentities($_SERVER["HTTP_USER_AGENT"], ENT_COMPAT) : '')."<br>\n";
5390 $out .= "<br>\n";
5391 $out .= "<b>".$langs->trans("RequestedUrl").":</b> ".dol_htmlentities($_SERVER["REQUEST_URI"], ENT_COMPAT)."<br>\n";
5392 $out .= "<b>".$langs->trans("Referer").":</b> ".(isset($_SERVER["HTTP_REFERER"]) ? dol_htmlentities($_SERVER["HTTP_REFERER"], ENT_COMPAT) : '')."<br>\n";
5393 $out .= "<b>".$langs->trans("MenuManager").":</b> ".(isset($conf->standard_menu) ? dol_htmlentities($conf->standard_menu, ENT_COMPAT) : '')."<br>\n";
5394 $out .= "<br>\n";
5395 $syslog .= "url=".dol_escape_htmltag($_SERVER["REQUEST_URI"]);
5396 $syslog .= ", query_string=".dol_escape_htmltag($_SERVER["QUERY_STRING"]);
5397 } else { // Mode CLI
5398 $out .= '> '.$langs->transnoentities("ErrorInternalErrorDetected").":\n".$argv[0]."\n";
5399 $syslog .= "pid=".dol_getmypid();
5400 }
5401
5402 if (!empty($conf->modules)) {
5403 $out .= "<b>".$langs->trans("Modules").":</b> ".join(', ', $conf->modules)."<br>\n";
5404 }
5405
5406 if (is_object($db)) {
5407 if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
5408 $out .= "<b>".$langs->trans("DatabaseTypeManager").":</b> ".$db->type."<br>\n";
5409 $lastqueryerror = $db->lastqueryerror();
5410 if (!utf8_check($lastqueryerror)) {
5411 $lastqueryerror = "SQL error string is not a valid UTF8 string. We can't show it.";
5412 }
5413 $out .= "<b>".$langs->trans("RequestLastAccessInError").":</b> ".($lastqueryerror ? dol_escape_htmltag($lastqueryerror) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
5414 $out .= "<b>".$langs->trans("ReturnCodeLastAccessInError").":</b> ".($db->lasterrno() ? dol_escape_htmltag($db->lasterrno()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
5415 $out .= "<b>".$langs->trans("InformationLastAccessInError").":</b> ".($db->lasterror() ? dol_escape_htmltag($db->lasterror()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
5416 $out .= "<br>\n";
5417 } else { // Mode CLI
5418 // No dol_escape_htmltag for output, we are in CLI mode
5419 $out .= '> '.$langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n";
5420 $out .= '> '.$langs->transnoentities("RequestLastAccessInError").":\n".($db->lastqueryerror() ? $db->lastqueryerror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
5421 $out .= '> '.$langs->transnoentities("ReturnCodeLastAccessInError").":\n".($db->lasterrno() ? $db->lasterrno() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
5422 $out .= '> '.$langs->transnoentities("InformationLastAccessInError").":\n".($db->lasterror() ? $db->lasterror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
5423 }
5424 $syslog .= ", sql=".$db->lastquery();
5425 $syslog .= ", db_error=".$db->lasterror();
5426 }
5427
5428 if ($error || $errors) {
5429 $langs->load("errors");
5430
5431 // Merge all into $errors array
5432 if (is_array($error) && is_array($errors)) {
5433 $errors = array_merge($error, $errors);
5434 } elseif (is_array($error)) {
5435 $errors = $error;
5436 } elseif (is_array($errors)) {
5437 $errors = array_merge(array($error), $errors);
5438 } else {
5439 $errors = array_merge(array($error), array($errors));
5440 }
5441
5442 foreach ($errors as $msg) {
5443 if (empty($msg)) {
5444 continue;
5445 }
5446 if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
5447 $out .= "<b>".$langs->trans("Message").":</b> ".dol_escape_htmltag($msg)."<br>\n";
5448 } else { // Mode CLI
5449 $out .= '> '.$langs->transnoentities("Message").":\n".$msg."\n";
5450 }
5451 $syslog .= ", msg=".$msg;
5452 }
5453 }
5454 if (empty($dolibarr_main_prod) && $_SERVER['DOCUMENT_ROOT'] && function_exists('xdebug_print_function_stack') && function_exists('xdebug_call_file')) {
5455 xdebug_print_function_stack();
5456 $out .= '<b>XDebug informations:</b>'."<br>\n";
5457 $out .= 'File: '.xdebug_call_file()."<br>\n";
5458 $out .= 'Line: '.xdebug_call_line()."<br>\n";
5459 $out .= 'Function: '.xdebug_call_function()."<br>\n";
5460 $out .= "<br>\n";
5461 }
5462
5463 // Return a http header with error code if possible
5464 if (!headers_sent()) {
5465 if (function_exists('top_httphead')) { // In CLI context, the method does not exists
5466 top_httphead();
5467 }
5468 //http_response_code(500); // If we use 500, message is not ouput with some command line tools
5469 http_response_code(202); // If we use 202, this is not really an error message, but this allow to ouput message on command line tools
5470 }
5471
5472 if (empty($dolibarr_main_prod)) {
5473 print $out;
5474 } else {
5475 if (empty($langs->defaultlang)) {
5476 $langs->setDefaultLang();
5477 }
5478 $langs->loadLangs(array("main", "errors")); // Reload main because language may have been set only on previous line so we have to reload files we need.
5479 // This should not happen, except if there is a bug somewhere. Enabled and check log in such case.
5480 print 'This website or feature is currently temporarly not available or failed after a technical error.<br><br>This may be due to a maintenance operation. Current status of operation ('.dol_print_date(dol_now(), 'dayhourrfc').') are on next line...<br><br>'."\n";
5481 print $langs->trans("DolibarrHasDetectedError").'. ';
5482 print $langs->trans("YouCanSetOptionDolibarrMainProdToZero");
5483 if (!defined("MAIN_CORE_ERROR")) {
5484 define("MAIN_CORE_ERROR", 1);
5485 }
5486 }
5487
5488 dol_syslog("Error ".$syslog, LOG_ERR);
5489}
5490
5501function dol_print_error_email($prefixcode, $errormessage = '', $errormessages = array(), $morecss = 'error', $email = '')
5502{
5503 global $langs, $conf;
5504
5505 if (empty($email)) {
5506 $email = $conf->global->MAIN_INFO_SOCIETE_MAIL;
5507 }
5508
5509 $langs->load("errors");
5510 $now = dol_now();
5511
5512 print '<br><div class="center login_main_message"><div class="'.$morecss.'">';
5513 print $langs->trans("ErrorContactEMail", $email, $prefixcode.'-'.dol_print_date($now, '%Y%m%d%H%M%S'));
5514 if ($errormessage) {
5515 print '<br><br>'.$errormessage;
5516 }
5517 if (is_array($errormessages) && count($errormessages)) {
5518 foreach ($errormessages as $mesgtoshow) {
5519 print '<br><br>'.$mesgtoshow;
5520 }
5521 }
5522 print '</div></div>';
5523}
5524
5541function print_liste_field_titre($name, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $tooltip = "", $forcenowrapcolumntitle = 0)
5542{
5543 print getTitleFieldOfList($name, 0, $file, $field, $begin, $moreparam, $moreattrib, $sortfield, $sortorder, $prefix, 0, $tooltip, $forcenowrapcolumntitle);
5544}
5545
5564function getTitleFieldOfList($name, $thead = 0, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $disablesortlink = 0, $tooltip = '', $forcenowrapcolumntitle = 0)
5565{
5566 global $conf, $langs, $form;
5567 //print "$name, $file, $field, $begin, $options, $moreattrib, $sortfield, $sortorder<br>\n";
5568
5569 if ($moreattrib == 'class="right"') {
5570 $prefix .= 'right '; // For backward compatibility
5571 }
5572
5573 $sortorder = strtoupper($sortorder);
5574 $out = '';
5575 $sortimg = '';
5576
5577 $tag = 'th';
5578 if ($thead == 2) {
5579 $tag = 'div';
5580 }
5581
5582 $tmpsortfield = explode(',', $sortfield);
5583 $sortfield1 = trim($tmpsortfield[0]); // If $sortfield is 'd.datep,d.id', it becomes 'd.datep'
5584 $tmpfield = explode(',', $field);
5585 $field1 = trim($tmpfield[0]); // If $field is 'd.datep,d.id', it becomes 'd.datep'
5586
5587 if (!getDolGlobalString('MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE') && empty($forcenowrapcolumntitle)) {
5588 $prefix = 'wrapcolumntitle '.$prefix;
5589 }
5590
5591 //var_dump('field='.$field.' field1='.$field1.' sortfield='.$sortfield.' sortfield1='.$sortfield1);
5592 // If field is used as sort criteria we use a specific css class liste_titre_sel
5593 // Example if (sortfield,field)=("nom","xxx.nom") or (sortfield,field)=("nom","nom")
5594 $liste_titre = 'liste_titre';
5595 if ($field1 && ($sortfield1 == $field1 || $sortfield1 == preg_replace("/^[^\.]+\./", "", $field1))) {
5596 $liste_titre = 'liste_titre_sel';
5597 }
5598
5599 $tagstart = '<'.$tag.' class="'.$prefix.$liste_titre.'" '.$moreattrib;
5600 //$out .= (($field && empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && preg_match('/^[a-zA-Z_0-9\s\.\-:&;]*$/', $name)) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '');
5601 $tagstart .= ($name && !getDolGlobalString('MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE') && empty($forcenowrapcolumntitle) && !dol_textishtml($name)) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '';
5602 $tagstart .= '>';
5603
5604 if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
5605 $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
5606 $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
5607 $options = preg_replace('/&+/i', '&', $options);
5608 if (!preg_match('/^&/', $options)) {
5609 $options = '&'.$options;
5610 }
5611
5612 $sortordertouseinlink = '';
5613 if ($field1 != $sortfield1) { // We are on another field than current sorted field
5614 if (preg_match('/^DESC/i', $sortorder)) {
5615 $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
5616 } else { // We reverse the var $sortordertouseinlink
5617 $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
5618 }
5619 } else { // We are on field that is the first current sorting criteria
5620 if (preg_match('/^ASC/i', $sortorder)) { // We reverse the var $sortordertouseinlink
5621 $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
5622 } else {
5623 $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
5624 }
5625 }
5626 $sortordertouseinlink = preg_replace('/,$/', '', $sortordertouseinlink);
5627 $out .= '<a class="reposition" href="'.$file.'?sortfield='.$field.'&sortorder='.$sortordertouseinlink.'&begin='.$begin.$options.'"';
5628 //$out .= (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '');
5629 $out .= '>';
5630 }
5631 if ($tooltip) {
5632 // You can also use 'TranslationString:keyfortooltiponclick' for a tooltip on click.
5633 if (preg_match('/:\w+$/', $tooltip)) {
5634 $tmptooltip = explode(':', $tooltip);
5635 } else {
5636 $tmptooltip = array($tooltip);
5637 }
5638 $out .= $form->textwithpicto($langs->trans($name), $langs->trans($tmptooltip[0]), 1, 'help', '', 0, 3, (empty($tmptooltip[1]) ? '' : 'extra_'.str_replace('.', '_', $field).'_'.$tmptooltip[1]));
5639 } else {
5640 $out .= $langs->trans($name);
5641 }
5642
5643 if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
5644 $out .= '</a>';
5645 }
5646
5647 if (empty($thead) && $field) { // If this is a sort field
5648 $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
5649 $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
5650 $options = preg_replace('/&+/i', '&', $options);
5651 if (!preg_match('/^&/', $options)) {
5652 $options = '&'.$options;
5653 }
5654
5655 if (!$sortorder || ($field1 != $sortfield1)) {
5656 //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
5657 //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
5658 } else {
5659 if (preg_match('/^DESC/', $sortorder)) {
5660 //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
5661 //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",1).'</a>';
5662 $sortimg .= '<span class="nowrap">'.img_up("Z-A", 0, 'paddingright').'</span>';
5663 }
5664 if (preg_match('/^ASC/', $sortorder)) {
5665 //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",1).'</a>';
5666 //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
5667 $sortimg .= '<span class="nowrap">'.img_down("A-Z", 0, 'paddingright').'</span>';
5668 }
5669 }
5670 }
5671
5672 $tagend = '</'.$tag.'>';
5673
5674 $out = $tagstart.$sortimg.$out.$tagend;
5675
5676 return $out;
5677}
5678
5687function print_titre($title)
5688{
5689 dol_syslog(__FUNCTION__." is deprecated", LOG_WARNING);
5690
5691 print '<div class="titre">'.$title.'</div>';
5692}
5693
5705function print_fiche_titre($title, $mesg = '', $picto = 'generic', $pictoisfullpath = 0, $id = '')
5706{
5707 print load_fiche_titre($title, $mesg, $picto, $pictoisfullpath, $id);
5708}
5709
5723function load_fiche_titre($titre, $morehtmlright = '', $picto = 'generic', $pictoisfullpath = 0, $id = '', $morecssontable = '', $morehtmlcenter = '')
5724{
5725 global $conf;
5726
5727 $return = '';
5728
5729 if ($picto == 'setup') {
5730 $picto = 'generic';
5731 }
5732
5733 $return .= "\n";
5734 $return .= '<table '.($id ? 'id="'.$id.'" ' : '').'class="centpercent notopnoleftnoright table-fiche-title'.($morecssontable ? ' '.$morecssontable : '').'">'; // maring bottom must be same than into print_barre_list
5735 $return .= '<tr class="titre">';
5736 if ($picto) {
5737 $return .= '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle widthpictotitle pictotitle"', $pictoisfullpath).'</td>';
5738 }
5739 $return .= '<td class="nobordernopadding valignmiddle col-title">';
5740 $return .= '<div class="titre inline-block">'.$titre.'</div>';
5741 $return .= '</td>';
5742 if (dol_strlen($morehtmlcenter)) {
5743 $return .= '<td class="nobordernopadding center valignmiddle col-center">'.$morehtmlcenter.'</td>';
5744 }
5745 if (dol_strlen($morehtmlright)) {
5746 $return .= '<td class="nobordernopadding titre_right wordbreakimp right valignmiddle col-right">'.$morehtmlright.'</td>';
5747 }
5748 $return .= '</tr></table>'."\n";
5749
5750 return $return;
5751}
5752
5776function print_barre_liste($titre, $page, $file, $options = '', $sortfield = '', $sortorder = '', $morehtmlcenter = '', $num = -1, $totalnboflines = '', $picto = 'generic', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limit = -1, $hideselectlimit = 0, $hidenavigation = 0, $pagenavastextinput = 0, $morehtmlrightbeforearrow = '')
5777{
5778 global $conf;
5779
5780 $savlimit = $limit;
5781 $savtotalnboflines = $totalnboflines;
5782 $totalnboflines = abs((int) $totalnboflines);
5783
5784 $page = (int) $page;
5785
5786 if ($picto == 'setup') {
5787 $picto = 'title_setup.png';
5788 }
5789 if (($conf->browser->name == 'ie') && $picto == 'generic') {
5790 $picto = 'title.gif';
5791 }
5792 if ($limit < 0) {
5793 $limit = $conf->liste_limit;
5794 }
5795
5796 if ($savlimit != 0 && (($num > $limit) || ($num == -1) || ($limit == 0))) {
5797 $nextpage = 1;
5798 } else {
5799 $nextpage = 0;
5800 }
5801 //print 'totalnboflines='.$totalnboflines.'-savlimit='.$savlimit.'-limit='.$limit.'-num='.$num.'-nextpage='.$nextpage.'-hideselectlimit='.$hideselectlimit.'-hidenavigation='.$hidenavigation;
5802
5803 print "\n";
5804 print "<!-- Begin title -->\n";
5805 print '<table class="centpercent notopnoleftnoright table-fiche-title'.($morecss ? ' '.$morecss : '').'"><tr>'; // maring bottom must be same than into load_fiche_tire
5806
5807 // Left
5808
5809 if ($picto && $titre) {
5810 print '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle pictotitle widthpictotitle"', $pictoisfullpath).'</td>';
5811 }
5812
5813 print '<td class="nobordernopadding valignmiddle col-title">';
5814 print '<div class="titre inline-block">'.$titre;
5815 if (!empty($titre) && $savtotalnboflines >= 0 && (string) $savtotalnboflines != '') {
5816 print '<span class="opacitymedium colorblack paddingleft">('.$totalnboflines.')</span>';
5817 }
5818 print '</div></td>';
5819
5820 // Center
5821 if ($morehtmlcenter && empty($conf->dol_optimize_smallscreen)) {
5822 print '<td class="nobordernopadding center valignmiddle col-center">'.$morehtmlcenter.'</td>';
5823 }
5824
5825 // Right
5826 print '<td class="nobordernopadding valignmiddle right col-right">';
5827 print '<input type="hidden" name="pageplusoneold" value="'.((int) $page + 1).'">';
5828 if ($sortfield) {
5829 $options .= "&sortfield=".urlencode($sortfield);
5830 }
5831 if ($sortorder) {
5832 $options .= "&sortorder=".urlencode($sortorder);
5833 }
5834 // Show navigation bar
5835 $pagelist = '';
5836 if ($savlimit != 0 && ($page > 0 || $num > $limit)) {
5837 if ($totalnboflines) { // If we know total nb of lines
5838 // Define nb of extra page links before and after selected page + ... + first or last
5839 $maxnbofpage = (empty($conf->dol_optimize_smallscreen) ? 4 : 0);
5840
5841 if ($limit > 0) {
5842 $nbpages = ceil($totalnboflines / $limit);
5843 } else {
5844 $nbpages = 1;
5845 }
5846 $cpt = ($page - $maxnbofpage);
5847 if ($cpt < 0) {
5848 $cpt = 0;
5849 }
5850
5851 if ($cpt >= 1) {
5852 if (empty($pagenavastextinput)) {
5853 $pagelist .= '<li class="pagination"><a class="reposition" href="'.$file.'?page=0'.$options.'">1</a></li>';
5854 if ($cpt > 2) {
5855 $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
5856 } elseif ($cpt == 2) {
5857 $pagelist .= '<li class="pagination"><a class="reposition" href="'.$file.'?page=1'.$options.'">2</a></li>';
5858 }
5859 }
5860 }
5861
5862 do {
5863 if ($pagenavastextinput) {
5864 if ($cpt == $page) {
5865 $pagelist .= '<li class="pagination"><input type="text" class="'.($totalnboflines > 100 ? 'width40' : 'width25').' center pageplusone" name="pageplusone" value="'.($page + 1).'"></li>';
5866 $pagelist .= '/';
5867 }
5868 } else {
5869 if ($cpt == $page) {
5870 $pagelist .= '<li class="pagination"><span class="active">'.($page + 1).'</span></li>';
5871 } else {
5872 $pagelist .= '<li class="pagination"><a class="reposition" href="'.$file.'?page='.$cpt.$options.'">'.($cpt + 1).'</a></li>';
5873 }
5874 }
5875 $cpt++;
5876 } while ($cpt < $nbpages && $cpt <= ($page + $maxnbofpage));
5877
5878 if (empty($pagenavastextinput)) {
5879 if ($cpt < $nbpages) {
5880 if ($cpt < $nbpages - 2) {
5881 $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
5882 } elseif ($cpt == $nbpages - 2) {
5883 $pagelist .= '<li class="pagination"><a class="reposition" href="'.$file.'?page='.($nbpages - 2).$options.'">'.($nbpages - 1).'</a></li>';
5884 }
5885 $pagelist .= '<li class="pagination"><a class="reposition" href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
5886 }
5887 } else {
5888 //var_dump($page.' '.$cpt.' '.$nbpages);
5889 $pagelist .= '<li class="pagination paginationlastpage"><a class="reposition" href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
5890 }
5891 } else {
5892 $pagelist .= '<li class="pagination"><span class="active">'.($page + 1)."</li>";
5893 }
5894 }
5895
5896 if ($savlimit || $morehtmlright || $morehtmlrightbeforearrow) {
5897 print_fleche_navigation($page, $file, $options, $nextpage, $pagelist, $morehtmlright, $savlimit, $totalnboflines, $hideselectlimit, $morehtmlrightbeforearrow, $hidenavigation); // output the div and ul for previous/last completed with page numbers into $pagelist
5898 }
5899
5900 // js to autoselect page field on focus
5901 if ($pagenavastextinput) {
5902 print ajax_autoselect('.pageplusone');
5903 }
5904
5905 print '</td>';
5906 print '</tr>';
5907
5908 print '</table>'."\n";
5909
5910 // Center
5911 if ($morehtmlcenter && !empty($conf->dol_optimize_smallscreen)) {
5912 print '<div class="nobordernopadding marginbottomonly center valignmiddle col-center centpercent">'.$morehtmlcenter.'</div>';
5913 }
5914
5915 print "<!-- End title -->\n\n";
5916}
5917
5934function print_fleche_navigation($page, $file, $options = '', $nextpage = 0, $betweenarrows = '', $afterarrows = '', $limit = -1, $totalnboflines = 0, $hideselectlimit = 0, $beforearrows = '', $hidenavigation = 0)
5935{
5936 global $conf, $langs;
5937
5938 print '<div class="pagination"><ul>';
5939 if ($beforearrows) {
5940 print '<li class="paginationbeforearrows">';
5941 print $beforearrows;
5942 print '</li>';
5943 }
5944
5945 if (empty($hidenavigation)) {
5946 if ((int) $limit > 0 && empty($hideselectlimit)) {
5947 $pagesizechoices = '10:10,15:15,20:20,30:30,40:40,50:50,100:100,250:250,500:500,1000:1000';
5948 $pagesizechoices .= ',5000:5000,10000:10000,20000:20000';
5949 //$pagesizechoices.=',0:'.$langs->trans("All"); // Not yet supported
5950 //$pagesizechoices.=',2:2';
5951 if (getDolGlobalString('MAIN_PAGESIZE_CHOICES')) {
5952 $pagesizechoices = $conf->global->MAIN_PAGESIZE_CHOICES;
5953 }
5954
5955 print '<li class="pagination">';
5956 print '<select class="flat selectlimit" name="limit" title="'.dol_escape_htmltag($langs->trans("MaxNbOfRecordPerPage")).'">';
5957 $tmpchoice = explode(',', $pagesizechoices);
5958 $tmpkey = $limit.':'.$limit;
5959 if (!in_array($tmpkey, $tmpchoice)) {
5960 $tmpchoice[] = $tmpkey;
5961 }
5962 $tmpkey = $conf->liste_limit.':'.$conf->liste_limit;
5963 if (!in_array($tmpkey, $tmpchoice)) {
5964 $tmpchoice[] = $tmpkey;
5965 }
5966 asort($tmpchoice, SORT_NUMERIC);
5967 foreach ($tmpchoice as $val) {
5968 $selected = '';
5969 $tmp = explode(':', $val);
5970 $key = $tmp[0];
5971 $val = $tmp[1];
5972 if ($key != '' && $val != '') {
5973 if ((int) $key == (int) $limit) {
5974 $selected = ' selected="selected"';
5975 }
5976 print '<option name="'.$key.'"'.$selected.'>'.dol_escape_htmltag($val).'</option>'."\n";
5977 }
5978 }
5979 print '</select>';
5980 if ($conf->use_javascript_ajax) {
5981 print '<!-- JS CODE TO ENABLE select limit to launch submit of page -->
5982 <script>
5983 jQuery(document).ready(function () {
5984 jQuery(".selectlimit").change(function() {
5985 console.log("Change limit. Send submit");
5986 $(this).parents(\'form:first\').submit();
5987 });
5988 });
5989 </script>
5990 ';
5991 }
5992 print '</li>';
5993 }
5994 if ($page > 0) {
5995 print '<li class="pagination paginationpage paginationpageleft"><a class="paginationprevious reposition" href="'.$file.'?page='.($page - 1).$options.'"><i class="fa fa-chevron-left" title="'.dol_escape_htmltag($langs->trans("Previous")).'"></i></a></li>';
5996 }
5997 if ($betweenarrows) {
5998 print '<!--<div class="betweenarrows nowraponall inline-block">-->';
5999 print $betweenarrows;
6000 print '<!--</div>-->';
6001 }
6002 if ($nextpage > 0) {
6003 print '<li class="pagination paginationpage paginationpageright"><a class="paginationnext reposition" href="'.$file.'?page='.($page + 1).$options.'"><i class="fa fa-chevron-right" title="'.dol_escape_htmltag($langs->trans("Next")).'"></i></a></li>';
6004 }
6005 if ($afterarrows) {
6006 print '<li class="paginationafterarrows">';
6007 print $afterarrows;
6008 print '</li>';
6009 }
6010 }
6011 print '</ul></div>'."\n";
6012}
6013
6014
6026function vatrate($rate, $addpercent = false, $info_bits = 0, $usestarfornpr = 0, $html = 0)
6027{
6028 $morelabel = '';
6029
6030 if (preg_match('/%/', $rate)) {
6031 $rate = str_replace('%', '', $rate);
6032 $addpercent = true;
6033 }
6034 $reg = array();
6035 if (preg_match('/\‍((.*)\‍)/', $rate, $reg)) {
6036 $morelabel = ' ('.$reg[1].')';
6037 $rate = preg_replace('/\s*'.preg_quote($morelabel, '/').'/', '', $rate);
6038 $morelabel = ' '.($html ? '<span class="opacitymedium">' : '').'('.$reg[1].')'.($html ? '</span>' : '');
6039 }
6040 if (preg_match('/\*/', $rate)) {
6041 $rate = str_replace('*', '', $rate);
6042 $info_bits |= 1;
6043 }
6044
6045 // If rate is '9/9/9' we don't change it. If rate is '9.000' we apply price()
6046 if (!preg_match('/\//', $rate)) {
6047 $ret = price($rate, 0, '', 0, 0).($addpercent ? '%' : '');
6048 } else {
6049 // TODO Split on / and output with a price2num to have clean numbers without ton of 000.
6050 $ret = $rate.($addpercent ? '%' : '');
6051 }
6052 if (($info_bits & 1) && $usestarfornpr >= 0) {
6053 $ret .= ' *';
6054 }
6055 $ret .= $morelabel;
6056 return $ret;
6057}
6058
6059
6075function price($amount, $form = 0, $outlangs = '', $trunc = 1, $rounding = -1, $forcerounding = -1, $currency_code = '')
6076{
6077 global $langs, $conf;
6078
6079 // Clean parameters
6080 if (empty($amount)) {
6081 $amount = 0; // To have a numeric value if amount not defined or = ''
6082 }
6083 $amount = (is_numeric($amount) ? $amount : 0); // Check if amount is numeric, for example, an error occured when amount value = o (letter) instead 0 (number)
6084 if ($rounding == -1) {
6085 $rounding = min(getDolGlobalString('MAIN_MAX_DECIMALS_UNIT'), getDolGlobalString('MAIN_MAX_DECIMALS_TOT'));
6086 }
6087 $nbdecimal = $rounding;
6088
6089 if ($outlangs === 'none') {
6090 // Use international separators
6091 $dec = '.';
6092 $thousand = '';
6093 } else {
6094 // Output separators by default (french)
6095 $dec = ',';
6096 $thousand = ' ';
6097
6098 // If $outlangs not forced, we use use language
6099 if (!is_object($outlangs)) {
6100 $outlangs = $langs;
6101 }
6102
6103 if ($outlangs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
6104 $dec = $outlangs->transnoentitiesnoconv("SeparatorDecimal");
6105 }
6106 if ($outlangs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
6107 $thousand = $outlangs->transnoentitiesnoconv("SeparatorThousand");
6108 }
6109 if ($thousand == 'None') {
6110 $thousand = '';
6111 } elseif ($thousand == 'Space') {
6112 $thousand = ' ';
6113 }
6114 }
6115 //print "outlangs=".$outlangs->defaultlang." amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
6116
6117 //print "amount=".$amount."-";
6118 $amount = str_replace(',', '.', $amount); // should be useless
6119 //print $amount."-";
6120 $datas = explode('.', $amount);
6121 $decpart = isset($datas[1]) ? $datas[1] : '';
6122 $decpart = preg_replace('/0+$/i', '', $decpart); // Supprime les 0 de fin de partie decimale
6123 //print "decpart=".$decpart."<br>";
6124 $end = '';
6125
6126 // We increase nbdecimal if there is more decimal than asked (to not loose information)
6127 if (dol_strlen($decpart) > $nbdecimal) {
6128 $nbdecimal = dol_strlen($decpart);
6129 }
6130 // If nbdecimal is higher than max to show
6131 $nbdecimalmaxshown = (int) str_replace('...', '', getDolGlobalString('MAIN_MAX_DECIMALS_SHOWN'));
6132 if ($trunc && $nbdecimal > $nbdecimalmaxshown) {
6133 $nbdecimal = $nbdecimalmaxshown;
6134 if (preg_match('/\.\.\./i', getDolGlobalString('MAIN_MAX_DECIMALS_SHOWN'))) {
6135 // If output is truncated, we show ...
6136 $end = '...';
6137 }
6138 }
6139
6140 // If force rounding
6141 if ((string) $forcerounding != '-1') {
6142 if ($forcerounding === 'MU') {
6143 $nbdecimal = getDolGlobalInt('MAIN_MAX_DECIMALS_UNIT');
6144 } elseif ($forcerounding === 'MT') {
6145 $nbdecimal = getDolGlobalInt('MAIN_MAX_DECIMALS_TOT');
6146 } elseif ($forcerounding >= 0) {
6147 $nbdecimal = $forcerounding;
6148 }
6149 }
6150
6151 // Format number
6152 $output = number_format($amount, $nbdecimal, $dec, $thousand);
6153 if ($form) {
6154 $output = preg_replace('/\s/', '&nbsp;', $output);
6155 $output = preg_replace('/\'/', '&#039;', $output);
6156 }
6157 // Add symbol of currency if requested
6158 $cursymbolbefore = $cursymbolafter = '';
6159 if ($currency_code && is_object($outlangs)) {
6160 if ($currency_code == 'auto') {
6161 $currency_code = $conf->currency;
6162 }
6163
6164 $listofcurrenciesbefore = array('AUD', 'CAD', 'CNY', 'COP', 'CLP', 'GBP', 'HKD', 'MXN', 'PEN', 'USD', 'CRC', 'ZAR');
6165 $listoflanguagesbefore = array('nl_NL');
6166 if (in_array($currency_code, $listofcurrenciesbefore) || in_array($outlangs->defaultlang, $listoflanguagesbefore)) {
6167 $cursymbolbefore .= $outlangs->getCurrencySymbol($currency_code);
6168 } else {
6169 $tmpcur = $outlangs->getCurrencySymbol($currency_code);
6170 $cursymbolafter .= ($tmpcur == $currency_code ? ' '.$tmpcur : $tmpcur);
6171 }
6172 }
6173 $output = $cursymbolbefore.$output.$end.($cursymbolafter ? ' ' : '').$cursymbolafter;
6174
6175 return $output;
6176}
6177
6202function price2num($amount, $rounding = '', $option = 0)
6203{
6204 global $langs, $conf;
6205
6206 // Clean parameters
6207 if (is_null($amount)) {
6208 $amount = '';
6209 }
6210
6211 // Round PHP function does not allow number like '1,234.56' nor '1.234,56' nor '1 234,56'
6212 // Numbers must be '1234.56'
6213 // Decimal delimiter for PHP and database SQL requests must be '.'
6214 $dec = ',';
6215 $thousand = ' ';
6216 if (is_null($langs)) { // $langs is not defined, we use english values.
6217 $dec = '.';
6218 $thousand = ',';
6219 } else {
6220 if ($langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
6221 $dec = $langs->transnoentitiesnoconv("SeparatorDecimal");
6222 }
6223 if ($langs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
6224 $thousand = $langs->transnoentitiesnoconv("SeparatorThousand");
6225 }
6226 }
6227 if ($thousand == 'None') {
6228 $thousand = '';
6229 } elseif ($thousand == 'Space') {
6230 $thousand = ' ';
6231 }
6232 //print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
6233
6234 // Convert value to universal number format (no thousand separator, '.' as decimal separator)
6235 if ($option != 1) { // If not a PHP number or unknown, we change or clean format
6236 //print "\n".'PP'.$amount.' - '.$dec.' - '.$thousand.' - '.intval($amount).'<br>';
6237 if (!is_numeric($amount)) {
6238 $amount = preg_replace('/[a-zA-Z\/\\\*\‍(\‍)<>\_]/', '', $amount);
6239 }
6240
6241 if ($option == 2 && $thousand == '.' && preg_match('/\.(\d\d\d)$/', (string) $amount)) { // It means the . is used as a thousand separator and string come from input data, so 1.123 is 1123
6242 $amount = str_replace($thousand, '', $amount);
6243 }
6244
6245 // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
6246 // to format defined by LC_NUMERIC after a calculation and we want source format to be like defined by Dolibarr setup.
6247 // So if number was already a good number, it is converted into local Dolibarr setup.
6248 if (is_numeric($amount)) {
6249 // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
6250 $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
6251 $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
6252 $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
6253 $amount = number_format($amount, $nbofdec, $dec, $thousand);
6254 }
6255 //print "QQ".$amount."<br>\n";
6256
6257 // Now make replace (the main goal of function)
6258 if ($thousand != ',' && $thousand != '.') {
6259 $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
6260 }
6261
6262 $amount = str_replace(' ', '', $amount); // To avoid spaces
6263 $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
6264 $amount = str_replace($dec, '.', $amount);
6265
6266 $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
6267 }
6268 //print ' XX'.$amount.' '.$rounding;
6269
6270 // Now, $amount is a real PHP float number. We make a rounding if required.
6271 if ($rounding) {
6272 $nbofdectoround = '';
6273 if ($rounding == 'MU') {
6274 $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_UNIT;
6275 } elseif ($rounding == 'MT') {
6276 $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_TOT;
6277 } elseif ($rounding == 'MS') {
6278 $nbofdectoround = isset($conf->global->MAIN_MAX_DECIMALS_STOCK) ? $conf->global->MAIN_MAX_DECIMALS_STOCK : 5;
6279 } elseif ($rounding == 'CU') {
6280 $nbofdectoround = max(getDolGlobalString('MAIN_MAX_DECIMALS_UNIT'), 8); // TODO Use param of currency
6281 } elseif ($rounding == 'CT') {
6282 $nbofdectoround = max(getDolGlobalString('MAIN_MAX_DECIMALS_TOT'), 8); // TODO Use param of currency
6283 } elseif (is_numeric($rounding)) {
6284 $nbofdectoround = (int) $rounding;
6285 }
6286
6287 //print " RR".$amount.' - '.$nbofdectoround.'<br>';
6288 if (dol_strlen($nbofdectoround)) {
6289 $amount = round(is_string($amount) ? (float) $amount : $amount, $nbofdectoround); // $nbofdectoround can be 0.
6290 } else {
6291 return 'ErrorBadParameterProvidedToFunction';
6292 }
6293 //print ' SS'.$amount.' - '.$nbofdec.' - '.$dec.' - '.$thousand.' - '.$nbofdectoround.'<br>';
6294
6295 // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
6296 // to format defined by LC_NUMERIC after a calculation and we want source format to be defined by Dolibarr setup.
6297 if (is_numeric($amount)) {
6298 // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
6299 $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
6300 $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
6301 $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
6302 $amount = number_format($amount, min($nbofdec, $nbofdectoround), $dec, $thousand); // Convert amount to format with dolibarr dec and thousand
6303 }
6304 //print "TT".$amount.'<br>';
6305
6306 // Always make replace because each math function (like round) replace
6307 // with local values and we want a number that has a SQL string format x.y
6308 if ($thousand != ',' && $thousand != '.') {
6309 $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
6310 }
6311
6312 $amount = str_replace(' ', '', $amount); // To avoid spaces
6313 $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
6314 $amount = str_replace($dec, '.', $amount);
6315
6316 $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
6317 }
6318
6319 return $amount;
6320}
6321
6334function showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round = -1, $forceunitoutput = 'no', $use_short_label = 0)
6335{
6336 require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
6337
6338 if (($forceunitoutput == 'no' && $dimension < 1 / 10000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -6)) {
6339 $dimension = $dimension * 1000000;
6340 $unit = $unit - 6;
6341 } elseif (($forceunitoutput == 'no' && $dimension < 1 / 10 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -3)) {
6342 $dimension = $dimension * 1000;
6343 $unit = $unit - 3;
6344 } elseif (($forceunitoutput == 'no' && $dimension > 100000000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 6)) {
6345 $dimension = $dimension / 1000000;
6346 $unit = $unit + 6;
6347 } elseif (($forceunitoutput == 'no' && $dimension > 100000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 3)) {
6348 $dimension = $dimension / 1000;
6349 $unit = $unit + 3;
6350 }
6351 // Special case when we want output unit into pound or ounce
6352 /* TODO
6353 if ($unit < 90 && $type == 'weight' && is_numeric($forceunitoutput) && (($forceunitoutput == 98) || ($forceunitoutput == 99))
6354 {
6355 $dimension = // convert dimension from standard unit into ounce or pound
6356 $unit = $forceunitoutput;
6357 }
6358 if ($unit > 90 && $type == 'weight' && is_numeric($forceunitoutput) && $forceunitoutput < 90)
6359 {
6360 $dimension = // convert dimension from standard unit into ounce or pound
6361 $unit = $forceunitoutput;
6362 }*/
6363
6364 $ret = price($dimension, 0, $outputlangs, 0, 0, $round);
6365 $ret .= ' '.measuringUnitString(0, $type, $unit, $use_short_label, $outputlangs);
6366
6367 return $ret;
6368}
6369
6370
6383function get_localtax($vatrate, $local, $thirdparty_buyer = "", $thirdparty_seller = "", $vatnpr = 0)
6384{
6385 global $db, $conf, $mysoc;
6386
6387 if (empty($thirdparty_seller) || !is_object($thirdparty_seller)) {
6388 $thirdparty_seller = $mysoc;
6389 }
6390
6391 dol_syslog("get_localtax tva=".$vatrate." local=".$local." thirdparty_buyer id=".(is_object($thirdparty_buyer) ? $thirdparty_buyer->id : '')."/country_code=".(is_object($thirdparty_buyer) ? $thirdparty_buyer->country_code : '')." thirdparty_seller id=".$thirdparty_seller->id."/country_code=".$thirdparty_seller->country_code." thirdparty_seller localtax1_assuj=".$thirdparty_seller->localtax1_assuj." thirdparty_seller localtax2_assuj=".$thirdparty_seller->localtax2_assuj);
6392
6393 $vatratecleaned = $vatrate;
6394 $reg = array();
6395 if (preg_match('/^(.*)\s*\‍((.*)\‍)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
6396 $vatratecleaned = trim($reg[1]);
6397 $vatratecode = $reg[2];
6398 }
6399
6400 /*if ($thirdparty_buyer->country_code != $thirdparty_seller->country_code)
6401 {
6402 return 0;
6403 }*/
6404
6405 // Some test to guess with no need to make database access
6406 if ($mysoc->country_code == 'ES') { // For spain localtaxes 1 and 2, tax is qualified if buyer use local tax
6407 if ($local == 1) {
6408 if (!$mysoc->localtax1_assuj || (string) $vatratecleaned == "0") {
6409 return 0;
6410 }
6411 if ($thirdparty_seller->id == $mysoc->id) {
6412 if (!$thirdparty_buyer->localtax1_assuj) {
6413 return 0;
6414 }
6415 } else {
6416 if (!$thirdparty_seller->localtax1_assuj) {
6417 return 0;
6418 }
6419 }
6420 }
6421
6422 if ($local == 2) {
6423 //if (! $mysoc->localtax2_assuj || (string) $vatratecleaned == "0") return 0;
6424 if (!$mysoc->localtax2_assuj) {
6425 return 0; // If main vat is 0, IRPF may be different than 0.
6426 }
6427 if ($thirdparty_seller->id == $mysoc->id) {
6428 if (!$thirdparty_buyer->localtax2_assuj) {
6429 return 0;
6430 }
6431 } else {
6432 if (!$thirdparty_seller->localtax2_assuj) {
6433 return 0;
6434 }
6435 }
6436 }
6437 } else {
6438 if ($local == 1 && !$thirdparty_seller->localtax1_assuj) {
6439 return 0;
6440 }
6441 if ($local == 2 && !$thirdparty_seller->localtax2_assuj) {
6442 return 0;
6443 }
6444 }
6445
6446 // For some country MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY is forced to on.
6447 if (in_array($mysoc->country_code, array('ES'))) {
6448 $conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY = 1;
6449 }
6450
6451 // Search local taxes
6452 if (getDolGlobalString('MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY')) {
6453 if ($local == 1) {
6454 if ($thirdparty_seller != $mysoc) {
6455 if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
6456 return $thirdparty_seller->localtax1_value;
6457 }
6458 } else { // i am the seller
6459 if (!isOnlyOneLocalTax($local)) { // TODO If seller is me, why not always returning this, even if there is only one locatax vat.
6460 return $conf->global->MAIN_INFO_VALUE_LOCALTAX1;
6461 }
6462 }
6463 }
6464 if ($local == 2) {
6465 if ($thirdparty_seller != $mysoc) {
6466 if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
6467 // TODO We should also return value defined on thirdparty only if defined
6468 return $thirdparty_seller->localtax2_value;
6469 }
6470 } else { // i am the seller
6471 if (in_array($mysoc->country_code, array('ES'))) {
6472 return $thirdparty_buyer->localtax2_value;
6473 } else {
6474 return $conf->global->MAIN_INFO_VALUE_LOCALTAX2;
6475 }
6476 }
6477 }
6478 }
6479
6480 // By default, search value of local tax on line of common tax
6481 $sql = "SELECT t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
6482 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
6483 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($thirdparty_seller->country_code)."'";
6484 $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
6485 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
6486 if (!empty($vatratecode)) {
6487 $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; // If we have the code, we use it in priority
6488 } else {
6489 $sql .= " AND t.recuperableonly = '".$db->escape($vatnpr)."'";
6490 }
6491
6492 $resql = $db->query($sql);
6493
6494 if ($resql) {
6495 $obj = $db->fetch_object($resql);
6496 if ($obj) {
6497 if ($local == 1) {
6498 return $obj->localtax1;
6499 } elseif ($local == 2) {
6500 return $obj->localtax2;
6501 }
6502 }
6503 }
6504
6505 return 0;
6506}
6507
6508
6517function isOnlyOneLocalTax($local)
6518{
6519 $tax = get_localtax_by_third($local);
6520
6521 $valors = explode(":", $tax);
6522
6523 if (count($valors) > 1) {
6524 return false;
6525 } else {
6526 return true;
6527 }
6528}
6529
6537{
6538 global $db, $mysoc;
6539
6540 $sql = " SELECT t.localtax".$local." as localtax";
6541 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t INNER JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = t.fk_pays";
6542 $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND t.active = 1 AND t.entity IN (".getEntity('c_tva').") AND t.taux = (";
6543 $sql .= "SELECT MAX(tt.taux) FROM ".MAIN_DB_PREFIX."c_tva as tt INNER JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = tt.fk_pays";
6544 $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND t.entity IN (".getEntity('c_tva').") AND tt.active = 1)";
6545 $sql .= " AND t.localtax".$local."_type <> '0'";
6546 $sql .= " ORDER BY t.rowid DESC";
6547
6548 $resql = $db->query($sql);
6549 if ($resql) {
6550 $obj = $db->fetch_object($resql);
6551 if ($obj) {
6552 return $obj->localtax;
6553 } else {
6554 return '0';
6555 }
6556 }
6557
6558 return 'Error';
6559}
6560
6561
6573function getTaxesFromId($vatrate, $buyer = null, $seller = null, $firstparamisid = 1)
6574{
6575 global $db, $mysoc;
6576
6577 dol_syslog("getTaxesFromId vat id or rate = ".$vatrate);
6578