dolibarr 21.0.0-alpha
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-2024 Frédéric France <frederic.france@free.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 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
25 * Copyright (C) 2024 Lenin Rivas <lenin.rivas777@gmail.com>
26 *
27 * This program is free software; you can redistribute it and/or modify
28 * it under the terms of the GNU General Public License as published by
29 * the Free Software Foundation; either version 3 of the License, or
30 * (at your option) any later version.
31 *
32 * This program is distributed in the hope that it will be useful,
33 * but WITHOUT ANY WARRANTY; without even the implied warranty of
34 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
35 * GNU General Public License for more details.
36 *
37 * You should have received a copy of the GNU General Public License
38 * along with this program. If not, see <https://www.gnu.org/licenses/>.
39 * or see https://www.gnu.org/
40 */
41
48//include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
49
50// Function for better PHP x compatibility
51if (!function_exists('utf8_encode')) {
59 function utf8_encode($elements)
60 {
61 return mb_convert_encoding($elements, 'UTF-8', 'ISO-8859-1');
62 }
63}
64
65if (!function_exists('utf8_decode')) {
73 function utf8_decode($elements)
74 {
75 return mb_convert_encoding($elements, 'ISO-8859-1', 'UTF-8');
76 }
77}
78if (!function_exists('str_starts_with')) {
87 function str_starts_with($haystack, $needle)
88 {
89 return (string) $needle !== '' && strncmp($haystack, $needle, strlen($needle)) === 0;
90 }
91}
92if (!function_exists('str_ends_with')) {
101 function str_ends_with($haystack, $needle)
102 {
103 return $needle !== '' && substr($haystack, -strlen($needle)) === (string) $needle;
104 }
105}
106if (!function_exists('str_contains')) {
115 function str_contains($haystack, $needle)
116 {
117 return $needle !== '' && mb_strpos($haystack, $needle) !== false;
118 }
119}
120
121
133function getMultidirOutput($object, $module = '', $forobject = 0, $mode = 'output')
134{
135 global $conf;
136
137 if (!is_object($object) && empty($module)) {
138 return null;
139 }
140 if (empty($module) && !empty($object->element)) {
141 $module = $object->element;
142 }
143
144 // Special case for backward compatibility
145 if ($module == 'fichinter') {
146 $module = 'ficheinter';
147 } elseif ($module == 'invoice_supplier') {
148 $module = 'supplier_invoice';
149 } elseif ($module == 'order_supplier') {
150 $module = 'supplier_order';
151 }
152
153 // Get the relative path of directory
154 if ($mode == 'output' || $mode == 'outputrel' || $mode == 'version') {
155 if (isset($conf->$module) && property_exists($conf->$module, 'multidir_output')) {
156 $s = '';
157 if ($mode != 'outputrel') {
158 $s = $conf->$module->multidir_output[(empty($object->entity) ? $conf->entity : $object->entity)];
159 }
160 if ($forobject && $object->id > 0) {
161 $s .= ($mode != 'outputrel' ? '/' : '').get_exdir(0, 0, 0, 0, $object);
162 }
163 return $s;
164 } else {
165 return 'error-diroutput-not-defined-for-this-object='.$module;
166 }
167 } elseif ($mode == 'temp') {
168 if (isset($conf->$module) && property_exists($conf->$module, 'multidir_temp')) {
169 return $conf->$module->multidir_temp[(empty($object->entity) ? $conf->entity : $object->entity)];
170 } else {
171 return 'error-dirtemp-not-defined-for-this-object='.$module;
172 }
173 } else {
174 return 'error-bad-value-for-mode';
175 }
176}
177
187function getMultidirTemp($object, $module = '', $forobject = 0)
188{
189 return getMultidirOutput($object, $module, $forobject, 'temp');
190}
191
201function getMultidirVersion($object, $module = '', $forobject = 0)
202{
203 return getMultidirOutput($object, $module, $forobject, 'version');
204}
205
206
215function getDolGlobalString($key, $default = '')
216{
217 global $conf;
218 return (string) (isset($conf->global->$key) ? $conf->global->$key : $default);
219}
220
230function getDolGlobalInt($key, $default = 0)
231{
232 global $conf;
233 return (int) (isset($conf->global->$key) ? $conf->global->$key : $default);
234}
235
244function getDolGlobalBool($key, $default = false)
245{
246 global $conf;
247 return (bool) ($conf->global->$key ?? $default);
248}
249
259function getDolUserString($key, $default = '', $tmpuser = null)
260{
261 if (empty($tmpuser)) {
262 global $user;
263 $tmpuser = $user;
264 }
265
266 return (string) (isset($tmpuser->conf->$key) ? $tmpuser->conf->$key : $default);
267}
268
277function getDolUserInt($key, $default = 0, $tmpuser = null)
278{
279 if (empty($tmpuser)) {
280 global $user;
281 $tmpuser = $user;
282 }
283
284 return (int) (isset($tmpuser->conf->$key) ? $tmpuser->conf->$key : $default);
285}
286
287
297define(
298 'MODULE_MAPPING',
299 array(
300 // Map deprecated names to new names
301 'adherent' => 'member', // Has new directory
302 'member_type' => 'adherent_type', // No directory, but file called adherent_type
303 'banque' => 'bank', // Has new directory
304 'contrat' => 'contract', // Has new directory
305 'entrepot' => 'stock', // Has new directory
306 'projet' => 'project', // Has new directory
307 'categorie' => 'category', // Has old directory
308 'commande' => 'order', // Has old directory
309 'expedition' => 'shipping', // Has old directory
310 'facture' => 'invoice', // Has old directory
311 'fichinter' => 'intervention', // Has old directory
312 'ficheinter' => 'intervention', // Backup for 'fichinter'
313 'propale' => 'propal', // Has old directory
314 'socpeople' => 'contact', // Has old directory
315 'fournisseur' => 'supplier', // Has old directory
316
317 'actioncomm' => 'agenda', // NO module directory (public dir agenda)
318 'product_price' => 'productprice', // NO directory
319 'product_fournisseur_price' => 'productsupplierprice', // NO directory
320 )
321);
322
329function isModEnabled($module)
330{
331 global $conf;
332
333 // Fix old names (map to new names)
334 $arrayconv = MODULE_MAPPING;
335 $arrayconvbis = array_flip(MODULE_MAPPING);
336
337 if (!getDolGlobalString('MAIN_USE_NEW_SUPPLIERMOD')) {
338 // Special cases: both use the same module.
339 $arrayconv['supplier_order'] = 'fournisseur';
340 $arrayconv['supplier_invoice'] = 'fournisseur';
341 }
342 // Special case.
343 // @TODO Replace isModEnabled('delivery_note') with
344 // isModEnabled('shipping') && getDolGlobalString('MAIN_SUBMODULE_EXPEDITION')
345 if ($module == 'delivery_note') {
346 if (!getDolGlobalString('MAIN_SUBMODULE_EXPEDITION')) {
347 return false;
348 } else {
349 $module = 'shipping';
350 }
351 }
352
353 $module_alt = $module;
354 if (!empty($arrayconv[$module])) {
355 $module_alt = $arrayconv[$module];
356 }
357 $module_bis = $module;
358 if (!empty($arrayconvbis[$module])) {
359 $module_bis = $arrayconvbis[$module];
360 }
361
362 return !empty($conf->modules[$module]) || !empty($conf->modules[$module_alt]) || !empty($conf->modules[$module_bis]);
363 //return !empty($conf->$module->enabled);
364}
365
372function isDolTms($timestamp)
373{
374 if ($timestamp === '') {
375 dol_syslog('Using empty string for a timestamp is deprecated, prefer use of null when calling page '.$_SERVER["PHP_SELF"], LOG_NOTICE);
376 return false;
377 }
378 if (is_null($timestamp) || !is_numeric($timestamp)) {
379 return false;
380 }
381
382 return true;
383}
384
396function getDoliDBInstance($type, $host, $user, $pass, $name, $port)
397{
398 require_once DOL_DOCUMENT_ROOT."/core/db/".$type.'.class.php';
399
400 $class = 'DoliDB'.ucfirst($type);
401 $db = new $class($type, $host, $user, $pass, $name, $port);
402 return $db;
403}
404
422function getEntity($element, $shared = 1, $currentobject = null)
423{
424 global $conf, $mc, $hookmanager, $object, $action, $db;
425
426 if (!is_object($hookmanager)) {
427 include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
428 $hookmanager = new HookManager($db);
429 }
430
431 // fix different element names (France to English)
432 switch ($element) {
433 case 'projet':
434 $element = 'project';
435 break;
436 case 'contrat':
437 $element = 'contract';
438 break; // "/contrat/class/contrat.class.php"
439 case 'order_supplier':
440 $element = 'supplier_order';
441 break; // "/fourn/class/fournisseur.commande.class.php"
442 case 'invoice_supplier':
443 $element = 'supplier_invoice';
444 break; // "/fourn/class/fournisseur.facture.class.php"
445 }
446
447 if (is_object($mc)) {
448 $out = $mc->getEntity($element, $shared, $currentobject);
449 } else {
450 $out = '';
451 $addzero = array('user', 'usergroup', 'cronjob', 'c_email_templates', 'c_holiday_types', 'email_template', 'default_values', 'overwrite_trans');
452 if (in_array($element, $addzero)) {
453 $out .= '0,';
454 }
455 $out .= ((int) $conf->entity);
456 }
457
458 // Manipulate entities to query on the fly
459 $parameters = array(
460 'element' => $element,
461 'shared' => $shared,
462 'object' => $object,
463 'currentobject' => $currentobject,
464 'out' => $out
465 );
466 $reshook = $hookmanager->executeHooks('hookGetEntity', $parameters, $currentobject, $action); // Note that $action and $object may have been modified by some hooks
467
468 if (is_numeric($reshook)) {
469 if ($reshook == 0 && !empty($hookmanager->resPrint)) {
470 $out .= ','.$hookmanager->resPrint; // add
471 } elseif ($reshook == 1) {
472 $out = $hookmanager->resPrint; // replace
473 }
474 }
475
476 return $out;
477}
478
485function setEntity($currentobject)
486{
487 global $conf, $mc;
488
489 if (is_object($mc) && method_exists($mc, 'setEntity')) {
490 return $mc->setEntity($currentobject);
491 } else {
492 return ((is_object($currentobject) && $currentobject->id > 0 && $currentobject->entity > 0) ? $currentobject->entity : $conf->entity);
493 }
494}
495
502function isASecretKey($keyname)
503{
504 return preg_match('/(_pass|password|_pw|_key|securekey|serverkey|secret\d?|p12key|exportkey|_PW_[a-z]+|token)$/i', $keyname);
505}
506
507
514function num2Alpha($n)
515{
516 for ($r = ""; $n >= 0; $n = intval($n / 26) - 1) {
517 $r = chr($n % 26 + 0x41) . $r;
518 }
519 return $r;
520}
521
522
539function getBrowserInfo($user_agent)
540{
541 include_once DOL_DOCUMENT_ROOT.'/includes/mobiledetect/mobiledetectlib/Mobile_Detect.php';
542
543 $name = 'unknown';
544 $version = '';
545 $os = 'unknown';
546 $phone = '';
547
548 $user_agent = substr($user_agent, 0, 512); // Avoid to process too large user agent
549
550 $detectmobile = new Mobile_Detect(null, $user_agent);
551 $tablet = $detectmobile->isTablet();
552
553 if ($detectmobile->isMobile()) {
554 $phone = 'unknown';
555
556 // If phone/smartphone, we set phone os name.
557 if ($detectmobile->is('AndroidOS')) {
558 $os = $phone = 'android';
559 } elseif ($detectmobile->is('BlackBerryOS')) {
560 $os = $phone = 'blackberry';
561 } elseif ($detectmobile->is('iOS')) {
562 $os = 'ios';
563 $phone = 'iphone';
564 } elseif ($detectmobile->is('PalmOS')) {
565 $os = $phone = 'palm';
566 } elseif ($detectmobile->is('SymbianOS')) {
567 $os = 'symbian';
568 } elseif ($detectmobile->is('webOS')) {
569 $os = 'webos';
570 } elseif ($detectmobile->is('MaemoOS')) {
571 $os = 'maemo';
572 } elseif ($detectmobile->is('WindowsMobileOS') || $detectmobile->is('WindowsPhoneOS')) {
573 $os = 'windows';
574 }
575 }
576
577 // OS
578 if (preg_match('/linux/i', $user_agent)) {
579 $os = 'linux';
580 } elseif (preg_match('/macintosh/i', $user_agent)) {
581 $os = 'macintosh';
582 } elseif (preg_match('/windows/i', $user_agent)) {
583 $os = 'windows';
584 }
585
586 // Name
587 $reg = array();
588 if (preg_match('/firefox(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
589 $name = 'firefox';
590 $version = empty($reg[2]) ? '' : $reg[2];
591 } elseif (preg_match('/edge(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
592 $name = 'edge';
593 $version = empty($reg[2]) ? '' : $reg[2];
594 } elseif (preg_match('/chrome(\/|\s)([\d\.]+)/i', $user_agent, $reg)) {
595 $name = 'chrome';
596 $version = empty($reg[2]) ? '' : $reg[2];
597 } elseif (preg_match('/chrome/i', $user_agent, $reg)) {
598 // we can have 'chrome (Mozilla...) chrome x.y' in one string
599 $name = 'chrome';
600 } elseif (preg_match('/iceweasel/i', $user_agent)) {
601 $name = 'iceweasel';
602 } elseif (preg_match('/epiphany/i', $user_agent)) {
603 $name = 'epiphany';
604 } elseif (preg_match('/safari(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
605 $name = 'safari';
606 $version = empty($reg[2]) ? '' : $reg[2];
607 } elseif (preg_match('/opera(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
608 // Safari is often present in string for mobile but its not.
609 $name = 'opera';
610 $version = empty($reg[2]) ? '' : $reg[2];
611 } elseif (preg_match('/(MSIE\s([0-9]+\.[0-9]))|.*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
612 $name = 'ie';
613 $version = end($reg);
614 } elseif (preg_match('/(Windows NT\s([0-9]+\.[0-9])).*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
615 // MS products at end
616 $name = 'ie';
617 $version = end($reg);
618 } elseif (preg_match('/l[iy]n(x|ks)(\‍(|\/|\s)*([\d\.]+)/i', $user_agent, $reg)) {
619 // MS products at end
620 $name = 'lynxlinks';
621 $version = empty($reg[3]) ? '' : $reg[3];
622 }
623
624 if ($tablet) {
625 $layout = 'tablet';
626 } elseif ($phone) {
627 $layout = 'phone';
628 } else {
629 $layout = 'classic';
630 }
631
632 return array(
633 'browsername' => $name,
634 'browserversion' => $version,
635 'browseros' => $os,
636 'browserua' => $user_agent,
637 'layout' => $layout, // tablet, phone, classic
638 'phone' => $phone, // deprecated
639 'tablet' => $tablet // deprecated
640 );
641}
642
648function dol_shutdown()
649{
650 global $db;
651 $disconnectdone = false;
652 $depth = 0;
653 if (is_object($db) && !empty($db->connected)) {
654 $depth = $db->transaction_opened;
655 $disconnectdone = $db->close();
656 }
657 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));
658}
659
669function GETPOSTISSET($paramname)
670{
671 $isset = false;
672
673 $relativepathstring = $_SERVER["PHP_SELF"];
674 // Clean $relativepathstring
675 if (constant('DOL_URL_ROOT')) {
676 $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
677 }
678 $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
679 $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
680 //var_dump($relativepathstring);
681 //var_dump($user->default_values);
682
683 // Code for search criteria persistence.
684 // Retrieve values if restore_lastsearch_values
685 if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
686 if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
687 $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
688 if (is_array($tmp)) {
689 foreach ($tmp as $key => $val) {
690 if ($key == $paramname) { // We are on the requested parameter
691 $isset = true;
692 break;
693 }
694 }
695 }
696 }
697 // If there is saved contextpage, limit, page or mode
698 if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
699 $isset = true;
700 } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
701 $isset = true;
702 } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
703 $isset = true;
704 } elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_'.$relativepathstring])) {
705 $isset = true;
706 }
707 } else {
708 $isset = (isset($_POST[$paramname]) || isset($_GET[$paramname])); // We must keep $_POST and $_GET here
709 }
710
711 return $isset;
712}
713
722function GETPOSTISARRAY($paramname, $method = 0)
723{
724 // for $method test need return the same $val as GETPOST
725 if (empty($method)) {
726 $val = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
727 } elseif ($method == 1) {
728 $val = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
729 } elseif ($method == 2) {
730 $val = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
731 } elseif ($method == 3) {
732 $val = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
733 } else {
734 $val = 'BadFirstParameterForGETPOST';
735 }
736
737 return is_array($val);
738}
739
770function GETPOST($paramname, $check = 'alphanohtml', $method = 0, $filter = null, $options = null, $noreplace = 0)
771{
772 global $mysoc, $user, $conf;
773
774 if (empty($paramname)) { // Explicit test for null for phan.
775 return 'BadFirstParameterForGETPOST';
776 }
777 if (empty($check)) {
778 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);
779 // Enable this line to know who call the GETPOST with '' $check parameter.
780 //var_dump(debug_backtrace()[0]);
781 }
782
783 if (empty($method)) {
784 $out = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
785 } elseif ($method == 1) {
786 $out = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
787 } elseif ($method == 2) {
788 $out = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
789 } elseif ($method == 3) {
790 $out = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
791 } else {
792 return 'BadThirdParameterForGETPOST';
793 }
794
795 $relativepathstring = ''; // For static analysis - looks possibly undefined if not set.
796
797 if (empty($method) || $method == 3 || $method == 4) {
798 $relativepathstring = (empty($_SERVER["PHP_SELF"]) ? '' : $_SERVER["PHP_SELF"]);
799 // Clean $relativepathstring
800 if (constant('DOL_URL_ROOT')) {
801 $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
802 }
803 $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
804 $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
805 //var_dump($relativepathstring);
806 //var_dump($user->default_values);
807
808 // Code for search criteria persistence.
809 // Retrieve saved values if restore_lastsearch_values is set
810 if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
811 if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
812 $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
813 if (is_array($tmp)) {
814 foreach ($tmp as $key => $val) {
815 if ($key == $paramname) { // We are on the requested parameter
816 $out = $val;
817 break;
818 }
819 }
820 }
821 }
822 // If there is saved contextpage, page or limit
823 if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
824 $out = $_SESSION['lastsearch_contextpage_'.$relativepathstring];
825 } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
826 $out = $_SESSION['lastsearch_limit_'.$relativepathstring];
827 } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
828 $out = $_SESSION['lastsearch_page_'.$relativepathstring];
829 } elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_'.$relativepathstring])) {
830 $out = $_SESSION['lastsearch_mode_'.$relativepathstring];
831 }
832 } elseif (!isset($_GET['sortfield'])) {
833 // Else, retrieve default values if we are not doing a sort
834 // 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
835 if (!empty($_GET['action']) && $_GET['action'] == 'create' && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
836 // Search default value from $object->field
837 global $object;
838 '@phan-var-force CommonObject $object'; // Suppose it's a CommonObject for analysis, but other objects have the $fields field as well
839 if (is_object($object) && isset($object->fields[$paramname]['default'])) {
840 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
841 $out = $object->fields[$paramname]['default'];
842 }
843 }
844 if (getDolGlobalString('MAIN_ENABLE_DEFAULT_VALUES')) {
845 if (!empty($_GET['action']) && (preg_match('/^create/', $_GET['action']) || preg_match('/^presend/', $_GET['action'])) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
846 // Now search in setup to overwrite default values
847 if (!empty($user->default_values)) { // $user->default_values defined from menu 'Setup - Default values'
848 if (isset($user->default_values[$relativepathstring]['createform'])) {
849 foreach ($user->default_values[$relativepathstring]['createform'] as $defkey => $defval) {
850 $qualified = 0;
851 if ($defkey != '_noquery_') {
852 $tmpqueryarraytohave = explode('&', $defkey);
853 $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
854 $foundintru = 0;
855 foreach ($tmpqueryarraytohave as $tmpquerytohave) {
856 if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
857 $foundintru = 1;
858 }
859 }
860 if (!$foundintru) {
861 $qualified = 1;
862 }
863 //var_dump($defkey.'-'.$qualified);
864 } else {
865 $qualified = 1;
866 }
867
868 if ($qualified) {
869 if (isset($user->default_values[$relativepathstring]['createform'][$defkey][$paramname])) {
870 $out = $user->default_values[$relativepathstring]['createform'][$defkey][$paramname];
871 break;
872 }
873 }
874 }
875 }
876 }
877 } elseif (!empty($paramname) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
878 // Management of default search_filters and sort order
879 if (!empty($user->default_values)) {
880 // $user->default_values defined from menu 'Setup - Default values'
881 //var_dump($user->default_values[$relativepathstring]);
882 if ($paramname == 'sortfield' || $paramname == 'sortorder') {
883 // Sorted on which fields ? ASC or DESC ?
884 if (isset($user->default_values[$relativepathstring]['sortorder'])) {
885 // Even if paramname is sortfield, data are stored into ['sortorder...']
886 foreach ($user->default_values[$relativepathstring]['sortorder'] as $defkey => $defval) {
887 $qualified = 0;
888 if ($defkey != '_noquery_') {
889 $tmpqueryarraytohave = explode('&', $defkey);
890 $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
891 $foundintru = 0;
892 foreach ($tmpqueryarraytohave as $tmpquerytohave) {
893 if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
894 $foundintru = 1;
895 }
896 }
897 if (!$foundintru) {
898 $qualified = 1;
899 }
900 //var_dump($defkey.'-'.$qualified);
901 } else {
902 $qualified = 1;
903 }
904
905 if ($qualified) {
906 $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
907 foreach ($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val) {
908 if ($out) {
909 $out .= ', ';
910 }
911 if ($paramname == 'sortfield') {
912 $out .= dol_string_nospecial($key, '', $forbidden_chars_to_replace);
913 }
914 if ($paramname == 'sortorder') {
915 $out .= dol_string_nospecial($val, '', $forbidden_chars_to_replace);
916 }
917 }
918 //break; // No break for sortfield and sortorder so we can cumulate fields (is it really useful ?)
919 }
920 }
921 }
922 } elseif (isset($user->default_values[$relativepathstring]['filters'])) {
923 foreach ($user->default_values[$relativepathstring]['filters'] as $defkey => $defval) { // $defkey is a querystring like 'a=b&c=d', $defval is key of user
924 if (!empty($_GET['disabledefaultvalues'])) { // If set of default values has been disabled by a request parameter
925 continue;
926 }
927 $qualified = 0;
928 if ($defkey != '_noquery_') {
929 $tmpqueryarraytohave = explode('&', $defkey);
930 $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
931 $foundintru = 0;
932 foreach ($tmpqueryarraytohave as $tmpquerytohave) {
933 if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
934 $foundintru = 1;
935 }
936 }
937 if (!$foundintru) {
938 $qualified = 1;
939 }
940 //var_dump($defkey.'-'.$qualified);
941 } else {
942 $qualified = 1;
943 }
944
945 if ($qualified && isset($user->default_values[$relativepathstring]['filters'][$defkey][$paramname])) {
946 // We must keep $_POST and $_GET here
947 if (isset($_POST['sall']) || isset($_POST['search_all']) || isset($_GET['sall']) || isset($_GET['search_all'])) {
948 // We made a search from quick search menu, do we still use default filter ?
949 if (!getDolGlobalString('MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH')) {
950 $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
951 $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
952 }
953 } else {
954 $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
955 $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
956 }
957 break;
958 }
959 }
960 }
961 }
962 }
963 }
964 }
965 }
966
967 // 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)
968 // Example of variables: __DAY__, __MONTH__, __YEAR__, __MYCOMPANY_COUNTRY_ID__, __USER_ID__, ...
969 // 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.
970 '@phan-var-force string $paramname';
971 if (!is_array($out) && empty($_POST[$paramname]) && empty($noreplace)) {
972 $reg = array();
973 $maxloop = 20;
974 $loopnb = 0; // Protection against infinite loop
975 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.
976 $loopnb++;
977 $newout = '';
978
979 if ($reg[1] == 'DAY') {
980 $tmp = dol_getdate(dol_now(), true);
981 $newout = $tmp['mday'];
982 } elseif ($reg[1] == 'MONTH') {
983 $tmp = dol_getdate(dol_now(), true);
984 $newout = $tmp['mon'];
985 } elseif ($reg[1] == 'YEAR') {
986 $tmp = dol_getdate(dol_now(), true);
987 $newout = $tmp['year'];
988 } elseif ($reg[1] == 'PREVIOUS_DAY') {
989 $tmp = dol_getdate(dol_now(), true);
990 $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
991 $newout = $tmp2['day'];
992 } elseif ($reg[1] == 'PREVIOUS_MONTH') {
993 $tmp = dol_getdate(dol_now(), true);
994 $tmp2 = dol_get_prev_month($tmp['mon'], $tmp['year']);
995 $newout = $tmp2['month'];
996 } elseif ($reg[1] == 'PREVIOUS_YEAR') {
997 $tmp = dol_getdate(dol_now(), true);
998 $newout = ($tmp['year'] - 1);
999 } elseif ($reg[1] == 'NEXT_DAY') {
1000 $tmp = dol_getdate(dol_now(), true);
1001 $tmp2 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
1002 $newout = $tmp2['day'];
1003 } elseif ($reg[1] == 'NEXT_MONTH') {
1004 $tmp = dol_getdate(dol_now(), true);
1005 $tmp2 = dol_get_next_month($tmp['mon'], $tmp['year']);
1006 $newout = $tmp2['month'];
1007 } elseif ($reg[1] == 'NEXT_YEAR') {
1008 $tmp = dol_getdate(dol_now(), true);
1009 $newout = ($tmp['year'] + 1);
1010 } elseif ($reg[1] == 'MYCOMPANY_COUNTRY_ID' || $reg[1] == 'MYCOUNTRY_ID' || $reg[1] == 'MYCOUNTRYID') {
1011 $newout = $mysoc->country_id;
1012 } elseif ($reg[1] == 'USER_ID' || $reg[1] == 'USERID') {
1013 $newout = $user->id;
1014 } elseif ($reg[1] == 'USER_SUPERVISOR_ID' || $reg[1] == 'SUPERVISOR_ID' || $reg[1] == 'SUPERVISORID') {
1015 $newout = $user->fk_user;
1016 } elseif ($reg[1] == 'ENTITY_ID' || $reg[1] == 'ENTITYID') {
1017 $newout = $conf->entity;
1018 } elseif ($reg[1] == 'ID') {
1019 $newout = '__ID__'; // We keep __ID__ we find into backtopage url
1020 } else {
1021 $newout = ''; // Key not found, we replace with empty string
1022 }
1023 //var_dump('__'.$reg[1].'__ -> '.$newout);
1024 $out = preg_replace('/__'.preg_quote($reg[1], '/').'__/', $newout, $out);
1025 }
1026 }
1027
1028 // Check type of variable and make sanitization according to this
1029 if (preg_match('/^array/', $check)) { // If 'array' or 'array:restricthtml' or 'array:aZ09' or 'array:intcomma'
1030 if (!is_array($out) || empty($out)) {
1031 $out = array();
1032 } else {
1033 $tmparray = explode(':', $check);
1034 if (!empty($tmparray[1])) {
1035 $tmpcheck = $tmparray[1];
1036 } else {
1037 $tmpcheck = 'alphanohtml';
1038 }
1039 foreach ($out as $outkey => $outval) {
1040 $out[$outkey] = sanitizeVal($outval, $tmpcheck, $filter, $options);
1041 }
1042 }
1043 } else {
1044 // If field name is 'search_xxx' then we force the add of space after each < and > (when following char is numeric) because it means
1045 // 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
1046 if (strpos($paramname, 'search_') === 0) {
1047 $out = preg_replace('/([<>])([-+]?\d)/', '\1 \2', $out);
1048 }
1049
1050 // @phan-suppress-next-line UnknownSanitizeType
1051 $out = sanitizeVal($out, $check, $filter, $options);
1052 }
1053
1054 // Sanitizing for special parameters.
1055 // Note: There is no reason to allow the backtopage, backtolist or backtourl parameter to contains an external URL. Only relative URLs are allowed.
1056 if ($paramname == 'backtopage' || $paramname == 'backtolist' || $paramname == 'backtourl') {
1057 $out = str_replace('\\', '/', $out); // Can be before the loop because only 1 char is replaced. No risk to get it after other replacements.
1058 $out = str_replace(array(':', ';', '@', "\t", ' '), '', $out); // Can be before the loop because only 1 char is replaced. No risk to retrieve it after other replacements.
1059 do {
1060 $oldstringtoclean = $out;
1061 $out = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $out);
1062 $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'
1063 $out = preg_replace(array('/^[a-z]*\/\s*\/+/i'), '', $out); // We remove schema*// to remove external URL
1064 } while ($oldstringtoclean != $out);
1065 }
1066
1067 // Code for search criteria persistence.
1068 // Save data into session if key start with 'search_'
1069 if (empty($method) || $method == 3 || $method == 4) {
1070 if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder', 'sortfield'))) {
1071 //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]);
1072
1073 // We save search key only if $out not empty that means:
1074 // - posted value not empty, or
1075 // - 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).
1076
1077 if ($out != '' && isset($user)) {// $out = '0' or 'abc', it is a search criteria to keep
1078 $user->lastsearch_values_tmp[$relativepathstring][$paramname] = $out;
1079 }
1080 }
1081 }
1082
1083 return $out;
1084}
1085
1095function GETPOSTINT($paramname, $method = 0)
1096{
1097 return (int) GETPOST($paramname, 'int', $method, null, null, 0);
1098}
1099
1100
1109function GETPOSTFLOAT($paramname, $rounding = '')
1110{
1111 // price2num() is used to sanitize any valid user input (such as "1 234.5", "1 234,5", "1'234,5", "1·234,5", "1,234.5", etc.)
1112 return (float) price2num(GETPOST($paramname), $rounding, 2);
1113}
1114
1115
1126function GETPOSTDATE($prefix, $hourTime = '', $gm = 'auto')
1127{
1128 $m = array();
1129 if ($hourTime === 'getpost') {
1130 $hour = GETPOSTINT($prefix . 'hour');
1131 $minute = GETPOSTINT($prefix . 'minute');
1132 $second = GETPOSTINT($prefix . 'second');
1133 } elseif (preg_match('/^(\d\d):(\d\d):(\d\d)$/', $hourTime, $m)) {
1134 $hour = intval($m[1]);
1135 $minute = intval($m[2]);
1136 $second = intval($m[3]);
1137 } else {
1138 $hour = $minute = $second = 0;
1139 }
1140 // normalize out of range values
1141 $hour = min($hour, 23);
1142 $minute = min($minute, 59);
1143 $second = min($second, 59);
1144 return dol_mktime($hour, $minute, $second, GETPOSTINT($prefix . 'month'), GETPOSTINT($prefix . 'day'), GETPOSTINT($prefix . 'year'), $gm);
1145}
1146
1147
1158function checkVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
1159{
1160 return sanitizeVal($out, $check, $filter, $options);
1161}
1162
1172function sanitizeVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
1173{
1174 // TODO : use class "Validate" to perform tests (and add missing tests) if needed for factorize
1175 // Check is done after replacement
1176 switch ($check) {
1177 case 'none':
1178 case 'password':
1179 break;
1180 case 'int': // Check param is a numeric value (integer but also float or hexadecimal)
1181 if (!is_numeric($out)) {
1182 $out = '';
1183 }
1184 break;
1185 case 'intcomma':
1186 if (is_array($out)) {
1187 $out = implode(',', $out);
1188 }
1189 if (preg_match('/[^0-9,-]+/i', $out)) {
1190 $out = '';
1191 }
1192 break;
1193 case 'san_alpha':
1194 $out = filter_var($out, FILTER_SANITIZE_STRING);
1195 break;
1196 case 'email':
1197 $out = filter_var($out, FILTER_SANITIZE_EMAIL);
1198 break;
1199 case 'aZ':
1200 if (!is_array($out)) {
1201 $out = trim($out);
1202 if (preg_match('/[^a-z]+/i', $out)) {
1203 $out = '';
1204 }
1205 }
1206 break;
1207 case 'aZ09':
1208 if (!is_array($out)) {
1209 $out = trim($out);
1210 if (preg_match('/[^a-z0-9_\-\.]+/i', $out)) {
1211 $out = '';
1212 }
1213 }
1214 break;
1215 case 'aZ09arobase': // great to sanitize $objecttype parameter
1216 if (!is_array($out)) {
1217 $out = trim($out);
1218 if (preg_match('/[^a-z0-9_\-\.@]+/i', $out)) {
1219 $out = '';
1220 }
1221 }
1222 break;
1223 case 'aZ09comma': // great to sanitize $sortfield or $sortorder params that can be 't.abc,t.def_gh'
1224 if (!is_array($out)) {
1225 $out = trim($out);
1226 if (preg_match('/[^a-z0-9_\-\.,]+/i', $out)) {
1227 $out = '';
1228 }
1229 }
1230 break;
1231 case 'alpha': // No html and no ../ and "
1232 case 'alphanohtml': // Recommended for most scalar parameters and search parameters
1233 if (!is_array($out)) {
1234 $out = trim($out);
1235 do {
1236 $oldstringtoclean = $out;
1237 // Remove html tags
1238 $out = dol_string_nohtmltag($out, 0);
1239 // Refuse octal syntax \999, hexa syntax \x999 and unicode syntax \u{999} by replacing the \ into / (so if it is a \ for a windows path, it is still ok).
1240 $out = preg_replace('/\\\‍([0-9xu])/', '/\1', $out);
1241 // Remove also other dangerous string sequences
1242 // '../' or '..\' is dangerous because it allows dir transversals
1243 // '&#38', '&#0000038', '&#x26'... is a the char '&' alone but there is no reason to accept such way to encode input char
1244 // '"' = '&#34' = '&#0000034' = '&#x22' is dangerous because param in url can close the href= or src= and add javascript functions.
1245 // '&#47', '&#0000047', '&#x2F' is the char '/' but there is no reason to accept such way to encode this input char
1246 // '&#92' = '&#0000092' = '&#x5C' is the char '\' but there is no reason to accept such way to encode this input char
1247 $out = str_ireplace(array('../', '..\\', '&#38', '&#0000038', '&#x26', '&quot', '"', '&#34', '&#0000034', '&#x22', '&#47', '&#0000047', '&#x2F', '&#92', '&#0000092', '&#x5C'), '', $out);
1248 } while ($oldstringtoclean != $out);
1249 // keep lines feed
1250 }
1251 break;
1252 case 'alphawithlgt': // No " and no ../ but we keep balanced < > tags with no special chars inside. Can be used for email string like "Name <email@domain.com>". Less secured than 'alphanohtml'
1253 if (!is_array($out)) {
1254 $out = trim($out);
1255 do {
1256 $oldstringtoclean = $out;
1257 // Decode html entities
1258 $out = dol_html_entity_decode($out, ENT_COMPAT | ENT_HTML5, 'UTF-8');
1259 // Refuse octal syntax \999, hexa syntax \x999 and unicode syntax \u{999} by replacing the \ into / (so if it is a \ for a windows path, it is still ok).
1260 $out = preg_replace('/\\\‍([0-9xu])/', '/\1', $out);
1261 // Remove also other dangerous string sequences
1262 // '../' or '..\' is dangerous because it allows dir transversals
1263 // '&#38', '&#0000038', '&#x26'... is a the char '&' alone but there is no reason to accept such way to encode input char
1264 // '"' = '&#34' = '&#0000034' = '&#x22' is dangerous because param in url can close the href= or src= and add javascript functions.
1265 // '&#47', '&#0000047', '&#x2F' is the char '/' but there is no reason to accept such way to encode this input char
1266 // '&#92' = '&#0000092' = '&#x5C' is the char '\' but there is no reason to accept such way to encode this input char
1267 $out = str_ireplace(array('../', '..\\', '&#38', '&#0000038', '&#x26', '&quot', '"', '&#34', '&#0000034', '&#x22', '&#47', '&#0000047', '&#x2F', '&#92', '&#0000092', '&#x5C'), '', $out);
1268 } while ($oldstringtoclean != $out);
1269 }
1270 break;
1271 case 'nohtml': // No html
1272 $out = dol_string_nohtmltag($out, 0);
1273 break;
1274 case 'restricthtmlnolink':
1275 case 'restricthtml': // Recommended for most html textarea
1276 case 'restricthtmlallowclass':
1277 case 'restricthtmlallowlinkscript': // Allow link and script tag for head section.
1278 case 'restricthtmlallowunvalid':
1279 $out = dol_htmlwithnojs($out, 1, $check);
1280 break;
1281 case 'custom':
1282 if (!empty($out)) {
1283 if (empty($filter)) {
1284 return 'BadParameterForGETPOST - Param 3 of sanitizeVal()';
1285 }
1286 if (is_null($options)) {
1287 $options = 0;
1288 }
1289 $out = filter_var($out, $filter, $options);
1290 }
1291 break;
1292 default:
1293 dol_syslog("Error, you call sanitizeVal() with a bad value for the check type. Data will be sanitized with alphanohtml.", LOG_ERR);
1294 $out = GETPOST($out, 'alphanohtml');
1295 break;
1296 }
1297
1298 return $out;
1299}
1300
1301
1302if (!function_exists('dol_getprefix')) {
1313 function dol_getprefix($mode = '')
1314 {
1315 // If prefix is for email (we need to have $conf already loaded for this case)
1316 if ($mode == 'email') {
1317 global $conf;
1318
1319 if (getDolGlobalString('MAIL_PREFIX_FOR_EMAIL_ID')) { // If MAIL_PREFIX_FOR_EMAIL_ID is set
1320 if (getDolGlobalString('MAIL_PREFIX_FOR_EMAIL_ID') != 'SERVER_NAME') {
1321 return $conf->global->MAIL_PREFIX_FOR_EMAIL_ID;
1322 } elseif (isset($_SERVER["SERVER_NAME"])) { // If MAIL_PREFIX_FOR_EMAIL_ID is set to 'SERVER_NAME'
1323 return $_SERVER["SERVER_NAME"];
1324 }
1325 }
1326
1327 // The recommended value if MAIL_PREFIX_FOR_EMAIL_ID is not defined (may be not defined for old versions)
1328 if (!empty($conf->file->instance_unique_id)) {
1329 return sha1('dolibarr'.$conf->file->instance_unique_id);
1330 }
1331
1332 // For backward compatibility when instance_unique_id is not set
1333 return sha1(DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
1334 }
1335
1336 // If prefix is for session (no need to have $conf loaded)
1337 global $dolibarr_main_instance_unique_id, $dolibarr_main_cookie_cryptkey; // This is loaded by filefunc.inc.php
1338 $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
1339
1340 // The recommended value (may be not defined for old versions)
1341 if (!empty($tmp_instance_unique_id)) {
1342 return sha1('dolibarr'.$tmp_instance_unique_id);
1343 }
1344
1345 // For backward compatibility when instance_unique_id is not set
1346 if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"])) {
1347 return sha1($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
1348 } else {
1349 return sha1(DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
1350 }
1351 }
1352}
1353
1364function dol_include_once($relpath, $classname = '')
1365{
1366 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']
1367
1368 $fullpath = dol_buildpath($relpath);
1369
1370 if (!file_exists($fullpath)) {
1371 dol_syslog('functions::dol_include_once Tried to load unexisting file: '.$relpath, LOG_WARNING);
1372 return false;
1373 }
1374
1375 if (!empty($classname) && !class_exists($classname)) {
1376 return include $fullpath;
1377 } else {
1378 return include_once $fullpath;
1379 }
1380}
1381
1382
1393function dol_buildpath($path, $type = 0, $returnemptyifnotfound = 0)
1394{
1395 global $conf;
1396
1397 $path = preg_replace('/^\//', '', $path);
1398
1399 if (empty($type)) { // For a filesystem path
1400 $res = DOL_DOCUMENT_ROOT.'/'.$path; // Standard default path
1401 if (is_array($conf->file->dol_document_root)) {
1402 foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array("main"=>"/home/main/htdocs", "alt0"=>"/home/dirmod/htdocs", ...)
1403 if ($key == 'main') {
1404 continue;
1405 }
1406 // if (@file_exists($dirroot.'/'.$path)) {
1407 if (@file_exists($dirroot.'/'.$path)) { // avoid [php:warn]
1408 $res = $dirroot.'/'.$path;
1409 return $res;
1410 }
1411 }
1412 }
1413 if ($returnemptyifnotfound) {
1414 // Not found into alternate dir
1415 if ($returnemptyifnotfound == 1 || !file_exists($res)) {
1416 return '';
1417 }
1418 }
1419 } else {
1420 // For an url path
1421 // We try to get local path of file on filesystem from url
1422 // Note that trying to know if a file on disk exist by forging path on disk from url
1423 // works only for some web server and some setup. This is bugged when
1424 // using proxy, rewriting, virtual path, etc...
1425 $res = '';
1426 if ($type == 1) {
1427 $res = DOL_URL_ROOT.'/'.$path; // Standard value
1428 }
1429 if ($type == 2) {
1430 $res = DOL_MAIN_URL_ROOT.'/'.$path; // Standard value
1431 }
1432 if ($type == 3) {
1433 $res = DOL_URL_ROOT.'/'.$path;
1434 }
1435
1436 foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
1437 if ($key == 'main') {
1438 if ($type == 3) {
1439 /*global $dolibarr_main_url_root;*/
1440
1441 // Define $urlwithroot
1442 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($conf->file->dol_main_url_root));
1443 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
1444 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
1445
1446 $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : $urlwithroot).'/'.$path; // Test on start with http is for old conf syntax
1447 }
1448 continue;
1449 }
1450 $regs = array();
1451 preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i', $path, $regs); // Take part before '?'
1452 if (!empty($regs[1])) {
1453 //print $key.'-'.$dirroot.'/'.$path.'-'.$conf->file->dol_url_root[$type].'<br>'."\n";
1454 //if (file_exists($dirroot.'/'.$regs[1])) {
1455 if (@file_exists($dirroot.'/'.$regs[1])) { // avoid [php:warn]
1456 if ($type == 1) {
1457 $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
1458 }
1459 if ($type == 2) {
1460 $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_MAIN_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
1461 }
1462 if ($type == 3) {
1463 /*global $dolibarr_main_url_root;*/
1464
1465 // Define $urlwithroot
1466 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($conf->file->dol_main_url_root));
1467 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
1468 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
1469
1470 $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
1471 }
1472 break;
1473 }
1474 }
1475 }
1476 }
1477
1478 return $res;
1479}
1480
1491function dol_get_object_properties($obj, $properties = [])
1492{
1493 // Get real properties using get_object_vars() if $properties is empty
1494 if (empty($properties)) {
1495 return get_object_vars($obj);
1496 }
1497
1498 $existingProperties = [];
1499 $realProperties = get_object_vars($obj);
1500
1501 // Get the real or magic property values
1502 foreach ($properties as $property) {
1503 if (array_key_exists($property, $realProperties)) {
1504 // Real property, add the value
1505 $existingProperties[$property] = $obj->{$property};
1506 } elseif (property_exists($obj, $property)) {
1507 // Magic property
1508 $existingProperties[$property] = $obj->{$property};
1509 }
1510 }
1511
1512 return $existingProperties;
1513}
1514
1515
1530function dol_clone($object, $native = 0)
1531{
1532 if ($native == 0) {
1533 // deprecated method, use the method with native = 2 instead
1534 $tmpsavdb = null;
1535 if (isset($object->db) && isset($object->db->db) && is_object($object->db->db) && get_class($object->db->db) == 'PgSql\Connection') {
1536 $tmpsavdb = $object->db;
1537 unset($object->db); // Such property can not be serialized with pgsl (when object->db->db = 'PgSql\Connection')
1538 }
1539
1540 $myclone = unserialize(serialize($object)); // serialize then unserialize is a hack to be sure to have a new object for all fields
1541
1542 if (!empty($tmpsavdb)) {
1543 $object->db = $tmpsavdb;
1544 }
1545 } elseif ($native == 2) {
1546 // recommended method to have a full isolated cloned object
1547 $myclone = new stdClass();
1548 $tmparray = get_object_vars($object); // return only public properties
1549
1550 if (is_array($tmparray)) {
1551 foreach ($tmparray as $propertykey => $propertyval) {
1552 if (is_scalar($propertyval) || is_array($propertyval)) {
1553 $myclone->$propertykey = $propertyval;
1554 }
1555 }
1556 }
1557 } else {
1558 $myclone = clone $object; // PHP clone is a shallow copy only, not a real clone, so properties of references will keep the reference (referring to the same target/variable)
1559 }
1560
1561 return $myclone;
1562}
1563
1573function dol_size($size, $type = '')
1574{
1575 global $conf;
1576 if (empty($conf->dol_optimize_smallscreen)) {
1577 return $size;
1578 }
1579 if ($type == 'width' && $size > 250) {
1580 return 250;
1581 } else {
1582 return 10;
1583 }
1584}
1585
1586
1598function dol_sanitizeFileName($str, $newstr = '_', $unaccent = 1)
1599{
1600 // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
1601 // Char '>' '<' '|' '$' and ';' are special chars for shells.
1602 // Char '/' and '\' are file delimiters.
1603 // Chars '--' can be used into filename to inject special parameters like --use-compress-program to make command with file as parameter making remote execution of command
1604 $filesystem_forbidden_chars = array('<', '>', '/', '\\', '?', '*', '|', '"', ':', '°', '$', ';', '`');
1605 $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
1606 $tmp = preg_replace('/\-\-+/', '_', $tmp);
1607 $tmp = preg_replace('/\s+\-([^\s])/', ' _$1', $tmp);
1608 $tmp = preg_replace('/\s+\-$/', '', $tmp);
1609 $tmp = str_replace('..', '', $tmp);
1610 return $tmp;
1611}
1612
1613
1625function dol_sanitizePathName($str, $newstr = '_', $unaccent = 1)
1626{
1627 // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
1628 // Char '>' '<' '|' '$' and ';' are special chars for shells.
1629 // Chars '--' can be used into filename to inject special parameters like --use-compress-program to make command with file as parameter making remote execution of command
1630 $filesystem_forbidden_chars = array('<', '>', '?', '*', '|', '"', '°', '$', ';', '`');
1631 $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
1632 $tmp = preg_replace('/\-\-+/', '_', $tmp);
1633 $tmp = preg_replace('/\s+\-([^\s])/', ' _$1', $tmp);
1634 $tmp = preg_replace('/\s+\-$/', '', $tmp);
1635 $tmp = str_replace('..', '', $tmp);
1636 return $tmp;
1637}
1638
1646function dol_sanitizeUrl($stringtoclean, $type = 1)
1647{
1648 // 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)
1649 // We should use dol_string_nounprintableascii but function may not be yet loaded/available
1650 $stringtoclean = preg_replace('/[\x00-\x1F\x7F]/u', '', $stringtoclean); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
1651 // We clean html comments because some hacks try to obfuscate evil strings by inserting HTML comments. Example: on<!-- -->error=alert(1)
1652 $stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
1653
1654 $stringtoclean = str_replace('\\', '/', $stringtoclean);
1655 if ($type == 1) {
1656 // removing : should disable links to external url like http:aaa)
1657 // removing ';' should disable "named" html entities encode into an url (we should not have this into an url)
1658 $stringtoclean = str_replace(array(':', ';', '@'), '', $stringtoclean);
1659 }
1660
1661 do {
1662 $oldstringtoclean = $stringtoclean;
1663 // removing '&colon' should disable links to external url like http:aaa)
1664 // removing '&#' should disable "numeric" html entities encode into an url (we should not have this into an url)
1665 $stringtoclean = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $stringtoclean);
1666 } while ($oldstringtoclean != $stringtoclean);
1667
1668 if ($type == 1) {
1669 // removing '//' should disable links to external url like //aaa or http//)
1670 $stringtoclean = preg_replace(array('/^[a-z]*\/\/+/i'), '', $stringtoclean);
1671 }
1672
1673 return $stringtoclean;
1674}
1675
1682function dol_sanitizeEmail($stringtoclean)
1683{
1684 do {
1685 $oldstringtoclean = $stringtoclean;
1686 $stringtoclean = str_ireplace(array('"', ':', '[', ']',"\n", "\r", '\\', '\/'), '', $stringtoclean);
1687 } while ($oldstringtoclean != $stringtoclean);
1688
1689 return $stringtoclean;
1690}
1691
1700function dol_sanitizeKeyCode($str)
1701{
1702 return preg_replace('/[^\w]+/', '', $str);
1703}
1704
1705
1714function dol_string_unaccent($str)
1715{
1716 if (is_null($str)) {
1717 return '';
1718 }
1719
1720 if (utf8_check($str)) {
1721 if (extension_loaded('intl') && getDolGlobalString('MAIN_UNACCENT_USE_TRANSLITERATOR')) {
1722 $transliterator = Transliterator::createFromRules(':: Any-Latin; :: Latin-ASCII; :: NFD; :: [:Nonspacing Mark:] Remove; :: NFC;', Transliterator::FORWARD);
1723 return $transliterator->transliterate($str);
1724 }
1725 // See http://www.utf8-chartable.de/
1726 $string = rawurlencode($str);
1727 $replacements = array(
1728 '%C3%80' => 'A', '%C3%81' => 'A', '%C3%82' => 'A', '%C3%83' => 'A', '%C3%84' => 'A', '%C3%85' => 'A',
1729 '%C3%87' => 'C',
1730 '%C3%88' => 'E', '%C3%89' => 'E', '%C3%8A' => 'E', '%C3%8B' => 'E',
1731 '%C3%8C' => 'I', '%C3%8D' => 'I', '%C3%8E' => 'I', '%C3%8F' => 'I',
1732 '%C3%91' => 'N',
1733 '%C3%92' => 'O', '%C3%93' => 'O', '%C3%94' => 'O', '%C3%95' => 'O', '%C3%96' => 'O',
1734 '%C5%A0' => 'S',
1735 '%C3%99' => 'U', '%C3%9A' => 'U', '%C3%9B' => 'U', '%C3%9C' => 'U',
1736 '%C3%9D' => 'Y', '%C5%B8' => 'y',
1737 '%C3%A0' => 'a', '%C3%A1' => 'a', '%C3%A2' => 'a', '%C3%A3' => 'a', '%C3%A4' => 'a', '%C3%A5' => 'a',
1738 '%C3%A7' => 'c',
1739 '%C3%A8' => 'e', '%C3%A9' => 'e', '%C3%AA' => 'e', '%C3%AB' => 'e',
1740 '%C3%AC' => 'i', '%C3%AD' => 'i', '%C3%AE' => 'i', '%C3%AF' => 'i',
1741 '%C3%B1' => 'n',
1742 '%C3%B2' => 'o', '%C3%B3' => 'o', '%C3%B4' => 'o', '%C3%B5' => 'o', '%C3%B6' => 'o',
1743 '%C5%A1' => 's',
1744 '%C3%B9' => 'u', '%C3%BA' => 'u', '%C3%BB' => 'u', '%C3%BC' => 'u',
1745 '%C3%BD' => 'y', '%C3%BF' => 'y'
1746 );
1747 $string = strtr($string, $replacements);
1748 return rawurldecode($string);
1749 } else {
1750 // See http://www.ascii-code.com/
1751 $string = strtr(
1752 $str,
1753 "\xC0\xC1\xC2\xC3\xC4\xC5\xC7
1754 \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
1755 \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
1756 \xE0\xE1\xE2\xE3\xE4\xE5\xE7\xE8\xE9\xEA\xEB
1757 \xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
1758 \xF9\xFA\xFB\xFC\xFD\xFF",
1759 "AAAAAAC
1760 EEEEIIIIDN
1761 OOOOOUUUY
1762 aaaaaaceeee
1763 iiiidnooooo
1764 uuuuyy"
1765 );
1766 $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"));
1767 return $string;
1768 }
1769}
1770
1784function dol_string_nospecial($str, $newstr = '_', $badcharstoreplace = '', $badcharstoremove = '', $keepspaces = 0)
1785{
1786 $forbidden_chars_to_replace = array("'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°', '$', ';'); // more complete than dol_sanitizeFileName
1787 if (empty($keepspaces)) {
1788 $forbidden_chars_to_replace[] = " ";
1789 }
1790 $forbidden_chars_to_remove = array();
1791 //$forbidden_chars_to_remove=array("(",")");
1792
1793 if (is_array($badcharstoreplace)) {
1794 $forbidden_chars_to_replace = $badcharstoreplace;
1795 }
1796 if (is_array($badcharstoremove)) {
1797 $forbidden_chars_to_remove = $badcharstoremove;
1798 }
1799
1800 // @phan-suppress-next-line PhanPluginSuspiciousParamOrderInternal
1801 return str_replace($forbidden_chars_to_replace, $newstr, str_replace($forbidden_chars_to_remove, "", $str));
1802}
1803
1804
1818function dol_string_nounprintableascii($str, $removetabcrlf = 1)
1819{
1820 if ($removetabcrlf) {
1821 return preg_replace('/[\x00-\x1F\x7F]/u', '', $str); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
1822 } else {
1823 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
1824 }
1825}
1826
1835function dol_escape_js($stringtoescape, $mode = 0, $noescapebackslashn = 0)
1836{
1837 if (is_null($stringtoescape)) {
1838 return '';
1839 }
1840
1841 // escape quotes and backslashes, newlines, etc.
1842 $substitjs = array("&#039;" => "\\'", "\r" => '\\r');
1843 //$substitjs['</']='<\/'; // We removed this. Should be useless.
1844 if (empty($noescapebackslashn)) {
1845 $substitjs["\n"] = '\\n';
1846 $substitjs['\\'] = '\\\\';
1847 }
1848 if (empty($mode)) {
1849 $substitjs["'"] = "\\'";
1850 $substitjs['"'] = "\\'";
1851 } elseif ($mode == 1) {
1852 $substitjs["'"] = "\\'";
1853 } elseif ($mode == 2) {
1854 $substitjs['"'] = '\\"';
1855 } elseif ($mode == 3) {
1856 $substitjs["'"] = "\\'";
1857 $substitjs['"'] = "\\\"";
1858 }
1859 return strtr($stringtoescape, $substitjs);
1860}
1861
1868function dol_escape_json($stringtoescape)
1869{
1870 return str_replace('"', '\"', $stringtoescape);
1871}
1872
1880function dol_escape_php($stringtoescape, $stringforquotes = 2)
1881{
1882 if (is_null($stringtoescape)) {
1883 return '';
1884 }
1885
1886 if ($stringforquotes == 2) {
1887 return str_replace('"', "'", $stringtoescape);
1888 } elseif ($stringforquotes == 1) {
1889 // We remove the \ char.
1890 // If we allow the \ char, we can have $stringtoescape =
1891 // abc\';phpcodedanger; so the escapement will become
1892 // abc\\';phpcodedanger; and injecting this into
1893 // $a='...' will give $ac='abc\\';phpcodedanger;
1894 $stringtoescape = str_replace('\\', '', $stringtoescape);
1895 return str_replace("'", "\'", str_replace('"', "'", $stringtoescape));
1896 }
1897
1898 return 'Bad parameter for stringforquotes in dol_escape_php';
1899}
1900
1907function dol_escape_all($stringtoescape)
1908{
1909 return preg_replace('/[^a-z0-9_]/i', '', $stringtoescape);
1910}
1911
1918function dol_escape_xml($stringtoescape)
1919{
1920 return $stringtoescape;
1921}
1922
1930function dolPrintLabel($s)
1931{
1932 return dol_escape_htmltag(dol_string_nohtmltag($s, 1, 'UTF-8', 0, 0), 0, 0, '', 0, 1);
1933}
1934
1942function dolPrintText($s)
1943{
1944 return dol_escape_htmltag(dol_string_nohtmltag($s, 2, 'UTF-8', 0, 0), 0, 1, '', 0, 1);
1945}
1946
1956function dolPrintHTML($s, $allowiframe = 0)
1957{
1958 return dol_escape_htmltag(dol_htmlwithnojs(dol_string_onlythesehtmltags(dol_htmlentitiesbr($s), 1, 1, 1, $allowiframe)), 1, 1, 'common', 0, 1);
1959}
1960
1968function dolPrintHTMLForAttribute($s)
1969{
1970 // The dol_htmlentitiesbr will convert simple text into html
1971 // The dol_escape_htmltag will escape html chars.
1972 return dol_escape_htmltag(dol_string_onlythesehtmltags(dol_htmlentitiesbr($s), 1, 0, 0, 0, array('br', 'b', 'font', 'span')), 1, -1, '', 0, 1);
1973}
1974
1984function dolPrintHTMLForTextArea($s, $allowiframe = 0)
1985{
1986 return dol_escape_htmltag(dol_htmlwithnojs(dol_string_onlythesehtmltags(dol_htmlentitiesbr($s), 1, 1, 1, $allowiframe)), 1, 1, '', 0, 1);
1987}
1988
1995function dolPrintPassword($s)
1996{
1997 return htmlspecialchars($s, ENT_COMPAT, 'UTF-8');
1998}
1999
2000
2017function dol_escape_htmltag($stringtoescape, $keepb = 0, $keepn = 0, $noescapetags = '', $escapeonlyhtmltags = 0, $cleanalsojavascript = 0)
2018{
2019 if ($noescapetags == 'common') {
2020 $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';
2021 // Add also html5 tags
2022 $noescapetags .= ',header,footer,nav,section,menu,menuitem';
2023 }
2024 if ($cleanalsojavascript) {
2025 $stringtoescape = dol_string_onlythesehtmltags($stringtoescape, 0, 0, $cleanalsojavascript, 0, array(), 0);
2026 }
2027
2028 // escape quotes and backslashes, newlines, etc.
2029 if ($escapeonlyhtmltags) {
2030 $tmp = htmlspecialchars_decode((string) $stringtoescape, ENT_COMPAT);
2031 } else {
2032 $tmp = html_entity_decode((string) $stringtoescape, ENT_COMPAT, 'UTF-8'); // This decode &egrave; into è so string is UTF8 (but &#39; is not decoded).
2033 $tmp = str_ireplace('&#39;', '__SIMPLEQUOTE', $tmp);
2034 }
2035 if (!$keepb) {
2036 $tmp = strtr($tmp, array("<b>" => '', '</b>' => '', '<strong>' => '', '</strong>' => ''));
2037 }
2038 if (!$keepn) {
2039 $tmp = strtr($tmp, array("\r" => '\\r', "\n" => '\\n'));
2040 } elseif ($keepn == -1) {
2041 $tmp = strtr($tmp, array("\r" => '', "\n" => ''));
2042 }
2043
2044 if ($escapeonlyhtmltags) {
2045 return htmlspecialchars($tmp, ENT_COMPAT, 'UTF-8');
2046 } else {
2047 // Escape tags to keep
2048 $tmparrayoftags = array();
2049 if ($noescapetags) {
2050 $tmparrayoftags = explode(',', $noescapetags);
2051 }
2052 if (count($tmparrayoftags)) {
2053 $reg = array();
2054 $tmp = str_ireplace('__DOUBLEQUOTE', '', $tmp); // The keyword DOUBLEQUOTE is forbidden. Reserved, so we removed it if we find it.
2055
2056 foreach ($tmparrayoftags as $tagtoreplace) {
2057 $tmp = preg_replace('/<'.preg_quote($tagtoreplace, '/').'>/', '__BEGINTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
2058 $tmp = str_ireplace('</'.$tagtoreplace.'>', '__ENDTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
2059 $tmp = preg_replace('/<'.preg_quote($tagtoreplace, '/').' \/>/', '__BEGINENDTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
2060
2061 // For case of tag with attribute
2062 do {
2063 $tmpold = $tmp;
2064
2065 if (preg_match('/<'.preg_quote($tagtoreplace, '/').'\s+([^>]+)>/', $tmp, $reg)) {
2066 $tmpattributes = str_ireplace(array('[', ']'), '_', $reg[1]); // We must never have [ ] inside the attribute string
2067 $tmpattributes = str_ireplace('href="http:', '__HREFHTTPA', $tmpattributes);
2068 $tmpattributes = str_ireplace('href="https:', '__HREFHTTPSA', $tmpattributes);
2069 $tmpattributes = str_ireplace('src="http:', '__SRCHTTPIMG', $tmpattributes);
2070 $tmpattributes = str_ireplace('src="https:', '__SRCHTTPSIMG', $tmpattributes);
2071 $tmpattributes = str_ireplace('"', '__DOUBLEQUOTE', $tmpattributes);
2072 $tmpattributes = preg_replace('/[^a-z0-9_\/\?\;\s=&\.\-@:\.#\+]/i', '', $tmpattributes);
2073 //$tmpattributes = preg_replace("/float:\s*(left|right)/", "", $tmpattributes); // Disabled: we must not remove content
2074 $tmp = preg_replace('/<'.preg_quote($tagtoreplace, '/').'\s+'.preg_quote($reg[1], '/').'>/', '__BEGINTAGTOREPLACE'.$tagtoreplace.'['.$tmpattributes.']__', $tmp);
2075 }
2076 if (preg_match('/<'.preg_quote($tagtoreplace, '/').'\s+([^>]+)\s+\/>/', $tmp, $reg)) {
2077 $tmpattributes = str_ireplace(array('[', ']'), '_', $reg[1]); // We must not have [ ] inside the attribute string
2078 $tmpattributes = str_ireplace('"', '__DOUBLEQUOTE', $tmpattributes);
2079 $tmpattributes = preg_replace('/[^a-z0-9_\/\?\;\s=&\.\-@:\.#\+]/i', '', $tmpattributes);
2080 //$tmpattributes = preg_replace("/float:\s*(left|right)/", "", $tmpattributes); // Disabled: we must not remove content.
2081 $tmp = preg_replace('/<'.preg_quote($tagtoreplace, '/').'\s+'.preg_quote($reg[1], '/').'\s+\/>/', '__BEGINENDTAGTOREPLACE'.$tagtoreplace.'['.$tmpattributes.']__', $tmp);
2082 }
2083
2084 $diff = strcmp($tmpold, $tmp);
2085 } while ($diff);
2086 }
2087 }
2088
2089 $result = htmlentities($tmp, ENT_COMPAT, 'UTF-8'); // Convert & into &amp; and more...
2090
2091 //print $result;
2092
2093 if (count($tmparrayoftags)) {
2094 foreach ($tmparrayoftags as $tagtoreplace) {
2095 $result = str_ireplace('__BEGINTAGTOREPLACE'.$tagtoreplace.'__', '<'.$tagtoreplace.'>', $result);
2096 $result = preg_replace('/__BEGINTAGTOREPLACE'.$tagtoreplace.'\[([^\]]*)\]__/', '<'.$tagtoreplace.' \1>', $result);
2097 $result = str_ireplace('__ENDTAGTOREPLACE'.$tagtoreplace.'__', '</'.$tagtoreplace.'>', $result);
2098 $result = str_ireplace('__BEGINENDTAGTOREPLACE'.$tagtoreplace.'__', '<'.$tagtoreplace.' />', $result);
2099 $result = preg_replace('/__BEGINENDTAGTOREPLACE'.$tagtoreplace.'\[([^\]]*)\]__/', '<'.$tagtoreplace.' \1 />', $result);
2100 }
2101
2102 $result = str_ireplace('__HREFHTTPA', 'href="http:', $result);
2103 $result = str_ireplace('__HREFHTTPSA', 'href="https:', $result);
2104 $result = str_ireplace('__SRCHTTPIMG', 'src="http:', $result);
2105 $result = str_ireplace('__SRCHTTPSIMG', 'src="https:', $result);
2106 $result = str_ireplace('__DOUBLEQUOTE', '"', $result);
2107 }
2108
2109 $result = str_ireplace('__SIMPLEQUOTE', '&#39;', $result);
2110
2111 //$result="\n\n\n".var_export($tmp, true)."\n\n\n".var_export($result, true);
2112
2113 return $result;
2114 }
2115}
2116
2124function dol_strtolower($string, $encoding = "UTF-8")
2125{
2126 if (function_exists('mb_strtolower')) {
2127 return mb_strtolower($string, $encoding);
2128 } else {
2129 return strtolower($string);
2130 }
2131}
2132
2141function dol_strtoupper($string, $encoding = "UTF-8")
2142{
2143 if (function_exists('mb_strtoupper')) {
2144 return mb_strtoupper($string, $encoding);
2145 } else {
2146 return strtoupper($string);
2147 }
2148}
2149
2158function dol_ucfirst($string, $encoding = "UTF-8")
2159{
2160 if (function_exists('mb_substr')) {
2161 return mb_strtoupper(mb_substr($string, 0, 1, $encoding), $encoding).mb_substr($string, 1, null, $encoding);
2162 } else {
2163 return ucfirst($string);
2164 }
2165}
2166
2175function dol_ucwords($string, $encoding = "UTF-8")
2176{
2177 if (function_exists('mb_convert_case')) {
2178 return mb_convert_case($string, MB_CASE_TITLE, $encoding);
2179 } else {
2180 return ucwords($string);
2181 }
2182}
2183
2206function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename = '', $restricttologhandler = '', $logcontext = null)
2207{
2208 global $conf, $user, $debugbar;
2209
2210 // If syslog module enabled
2211 if (!isModEnabled('syslog')) {
2212 return;
2213 }
2214
2215 // Check if we are into execution of code of a website
2216 if (defined('USEEXTERNALSERVER') && !defined('USEDOLIBARRSERVER') && !defined('USEDOLIBARREDITOR')) {
2217 global $website, $websitekey;
2218 if (is_object($website) && !empty($website->ref)) {
2219 $suffixinfilename .= '_website_'.$website->ref;
2220 } elseif (!empty($websitekey)) {
2221 $suffixinfilename .= '_website_'.$websitekey;
2222 }
2223 }
2224
2225 // Check if we have a forced suffix
2226 if (defined('USESUFFIXINLOG')) {
2227 $suffixinfilename .= constant('USESUFFIXINLOG');
2228 }
2229
2230 if ($ident < 0) {
2231 foreach ($conf->loghandlers as $loghandlerinstance) {
2232 $loghandlerinstance->setIdent($ident);
2233 }
2234 }
2235
2236 if (!empty($message)) {
2237 // Test log level @phan-suppress-next-line PhanPluginDuplicateArrayKey
2238 $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');
2239 if (!array_key_exists($level, $logLevels)) {
2240 throw new Exception('Incorrect log level');
2241 }
2242 if ($level > getDolGlobalInt('SYSLOG_LEVEL')) {
2243 return;
2244 }
2245
2246 if (!getDolGlobalString('MAIN_SHOW_PASSWORD_INTO_LOG')) {
2247 $message = preg_replace('/password=\'[^\']*\'/', 'password=\'hidden\'', $message); // protection to avoid to have value of password in log
2248 }
2249
2250 // If adding log inside HTML page is required
2251 if ((!empty($_REQUEST['logtohtml']) && getDolGlobalString('MAIN_ENABLE_LOG_TO_HTML'))
2252 || (is_object($user) && $user->hasRight('debugbar', 'read') && is_object($debugbar))) {
2253 $ospid = sprintf("%7s", dol_trunc((string) getmypid(), 7, 'right', 'UTF-8', 1));
2254 $osuser = " ".sprintf("%6s", dol_trunc(function_exists('posix_getuid') ? posix_getuid() : '', 6, 'right', 'UTF-8', 1));
2255
2256 $conf->logbuffer[] = dol_print_date(time(), "%Y-%m-%d %H:%M:%S")." ".sprintf("%-7s", $logLevels[$level])." ".$ospid." ".$osuser." ".$message;
2257 }
2258
2259 //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output
2260 // If html log tag enabled and url parameter log defined, we show output log on HTML comments
2261 if (getDolGlobalString('MAIN_ENABLE_LOG_INLINE_HTML') && GETPOSTINT("log")) {
2262 print "\n\n<!-- Log start\n";
2263 print dol_escape_htmltag($message)."\n";
2264 print "Log end -->\n";
2265 }
2266
2267 $data = array(
2268 'message' => $message,
2269 'script' => (isset($_SERVER['PHP_SELF']) ? basename($_SERVER['PHP_SELF'], '.php') : false),
2270 'level' => $level,
2271 'user' => ((is_object($user) && $user->id) ? $user->login : false),
2272 'ip' => false,
2273 'osuser' => function_exists('posix_getuid') ? posix_getuid() : false,
2274 'ospid' => getmypid() // on linux, max value is defined into cat /proc/sys/kernel/pid_max
2275 );
2276
2277 $remoteip = getUserRemoteIP(); // Get ip when page run on a web server
2278 if (!empty($remoteip)) {
2279 $data['ip'] = $remoteip;
2280 // This is when server run behind a reverse proxy
2281 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != $remoteip) {
2282 $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'].' -> '.$data['ip'];
2283 } elseif (!empty($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP'] != $remoteip) {
2284 $data['ip'] = $_SERVER['HTTP_CLIENT_IP'].' -> '.$data['ip'];
2285 }
2286 } elseif (!empty($_SERVER['SERVER_ADDR'])) {
2287 // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
2288 $data['ip'] = $_SERVER['SERVER_ADDR'];
2289 } elseif (!empty($_SERVER['COMPUTERNAME'])) {
2290 // This is when PHP session is ran outside a web server, like from Windows command line (Not always defined, but useful if OS defines it).
2291 $data['ip'] = $_SERVER['COMPUTERNAME'];
2292 } else {
2293 $data['ip'] = '???';
2294 }
2295
2296 if (!empty($_SERVER['USERNAME'])) {
2297 // This is when PHP session is ran outside a web server, like from Linux command line (Not always defined, but useful if OS defines it).
2298 $data['osuser'] = $_SERVER['USERNAME'];
2299 } elseif (!empty($_SERVER['LOGNAME'])) {
2300 // This is when PHP session is ran outside a web server, like from Linux command line (Not always defined, but useful if OS defines it).
2301 $data['osuser'] = $_SERVER['LOGNAME'];
2302 }
2303
2304 // Loop on each log handler and send output
2305 foreach ($conf->loghandlers as $loghandlerinstance) {
2306 if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler) {
2307 continue;
2308 }
2309 $loghandlerinstance->export($data, $suffixinfilename);
2310 }
2311 unset($data);
2312 }
2313
2314 if ($ident > 0) {
2315 foreach ($conf->loghandlers as $loghandlerinstance) {
2316 $loghandlerinstance->setIdent($ident);
2317 }
2318 }
2319}
2320
2332function dolButtonToOpenExportDialog($name, $label, $buttonstring, $exportSiteName, $overwriteGitUrl, $website)
2333{
2334 global $langs, $db;
2335
2336 $form = new Form($db);
2337
2338 $templatenameforexport = $website->name_template; // Example 'website_template-corporate'
2339 if (empty($templatenameforexport)) {
2340 $templatenameforexport = 'website_'.$website->ref;
2341 }
2342
2343 $out = '';
2344 $out .= '<input type="button" class="cursorpointer button bordertransp" id="open-dialog-' . $name . '" value="'.dol_escape_htmltag($buttonstring).'"/>';
2345
2346 // for generate popup
2347 $out .= '<script nonce="' . getNonce() . '" type="text/javascript">';
2348 $out .= 'jQuery(document).ready(function () {';
2349 $out .= ' jQuery("#open-dialog-' . $name . '").click(function () {';
2350 $out .= ' var dialogHtml = \'';
2351
2352 $dialogcontent = ' <div id="custom-dialog-' . $name . '">';
2353 $dialogcontent .= ' <div style="margin-top: 20px;">';
2354 $dialogcontent .= ' <label for="export-site-' . $name . '"><strong>'.$langs->trans("ExportSiteLabel").'...</label><br>';
2355 $dialogcontent .= ' <button class="button smallpaddingimp" id="export-site-' . $name . '">' . dol_escape_htmltag($langs->trans("DownloadZip")) . '</button>';
2356 $dialogcontent .= ' </div>';
2357 $dialogcontent .= ' <br>';
2358 $dialogcontent .= ' <div style="margin-top: 20px;">';
2359 $dialogcontent .= ' <strong>'.$langs->trans("ExportSiteGitLabel").' '.$form->textwithpicto('', $langs->trans("SourceFiles"), 1, 'help', '', 0, 3, '').'</strong><br>';
2360 $dialogcontent .= ' <form action="'.dol_escape_htmltag($overwriteGitUrl).'" method="POST">';
2361 $dialogcontent .= ' <input type="hidden" name="action" value="overwritesite">';
2362 $dialogcontent .= ' <input type="hidden" name="token" value="'.newToken().'">';
2363 $dialogcontent .= ' <input type="text" autofocus name="export_path" id="export-path-'.$name.'" placeholder="'.$langs->trans('ExportPath').'" style="width:400px " value="'.dol_escape_htmltag($templatenameforexport).'"/><br>';
2364 $dialogcontent .= ' <button type="submit" class="button smallpaddingimp" id="overwrite-git-' . $name . '">' . dol_escape_htmltag($langs->trans("ExportIntoGIT")) . '</button>';
2365 $dialogcontent .= ' </form>';
2366 $dialogcontent .= ' </div>';
2367 $dialogcontent .= ' </div>';
2368
2369 $out .= dol_escape_js($dialogcontent);
2370
2371 $out .= '\';';
2372
2373
2374 // Add the content of the dialog to the body of the page
2375 $out .= ' var $dialog = jQuery("#custom-dialog-' . $name . '");';
2376 $out .= ' if ($dialog.length > 0) {
2377 $dialog.remove();
2378 }
2379 jQuery("body").append(dialogHtml);';
2380
2381 // Configuration of popup
2382 $out .= ' jQuery("#custom-dialog-' . $name . '").dialog({';
2383 $out .= ' autoOpen: false,';
2384 $out .= ' modal: true,';
2385 $out .= ' height: 290,';
2386 $out .= ' width: "40%",';
2387 $out .= ' title: "' . dol_escape_js($label) . '",';
2388 $out .= ' });';
2389
2390 // Simulate a click on the original "submit" input to export the site.
2391 $out .= ' jQuery("#export-site-' . $name . '").click(function () {';
2392 $out .= ' console.log("Clic on exportsite.");';
2393 $out .= ' var target = jQuery("input[name=\'' . dol_escape_js($exportSiteName) . '\']");';
2394 $out .= ' console.log("element founded:", target.length > 0);';
2395 $out .= ' if (target.length > 0) { target.click(); }';
2396 $out .= ' jQuery("#custom-dialog-' . $name . '").dialog("close");';
2397 $out .= ' });';
2398
2399 // open popup
2400 $out .= ' jQuery("#custom-dialog-' . $name . '").dialog("open");';
2401 $out .= ' return false;';
2402 $out .= ' });';
2403 $out .= '});';
2404 $out .= '</script>';
2405
2406 return $out;
2407}
2408
2409
2426function dolButtonToOpenUrlInDialogPopup($name, $label, $buttonstring, $url, $disabled = '', $morecss = 'classlink button bordertransp', $jsonopen = '', $backtopagejsfields = '', $accesskey = '')
2427{
2428 global $conf;
2429
2430 if (strpos($url, '?') > 0) {
2431 $url .= '&dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup='.urlencode($name);
2432 } else {
2433 $url .= '?dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup='.urlencode($name);
2434 }
2435
2436 $out = '';
2437
2438 $backtopagejsfieldsid = '';
2439 $backtopagejsfieldslabel = '';
2440 if ($backtopagejsfields) {
2441 $tmpbacktopagejsfields = explode(':', $backtopagejsfields);
2442 if (empty($tmpbacktopagejsfields[1])) { // If the part 'keyforpopupid:' is missing, we add $name for it.
2443 $backtopagejsfields = $name.":".$backtopagejsfields;
2444 $tmp2backtopagejsfields = explode(',', $tmpbacktopagejsfields[0]);
2445 } else {
2446 $tmp2backtopagejsfields = explode(',', $tmpbacktopagejsfields[1]);
2447 }
2448 $backtopagejsfieldsid = empty($tmp2backtopagejsfields[0]) ? '' : $tmp2backtopagejsfields[0];
2449 $backtopagejsfieldslabel = empty($tmp2backtopagejsfields[1]) ? '' : $tmp2backtopagejsfields[1];
2450 $url .= '&backtopagejsfields='.urlencode($backtopagejsfields);
2451 }
2452
2453 //print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("MediaFiles")).'" name="file_manager">';
2454 $out .= '<!-- a link for button to open url into a dialog popup with backtopagejsfields = '.$backtopagejsfields.' -->';
2455 $out .= '<a '.($accesskey ? ' accesskey="'.$accesskey.'"' : '').' class="cursorpointer reposition button_'.$name.($morecss ? ' '.$morecss : '').'"'.$disabled.' title="'.dol_escape_htmltag($label).'"';
2456 if (empty($conf->use_javascript_ajax)) {
2457 $out .= ' href="'.DOL_URL_ROOT.$url.'" target="_blank"';
2458 } elseif ($jsonopen) {
2459 $out .= ' href="#" onclick="'.$jsonopen.'"';
2460 } else {
2461 $out .= ' href="#"';
2462 }
2463 $out .= '>'.$buttonstring.'</a>';
2464
2465 if (!empty($conf->use_javascript_ajax)) {
2466 // Add code to open url using the popup. Add also hidden field to retrieve the returned variables
2467 $out .= '<!-- code to open popup and variables to retrieve returned variables -->';
2468 $out .= '<div id="idfordialog'.$name.'" class="hidden">'.(getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER') < 2 ? 'div for dialog' : '').'</div>';
2469 $out .= '<div id="varforreturndialogid'.$name.'" class="hidden">'.(getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER') < 2 ? 'div for returned id' : '').'</div>';
2470 $out .= '<div id="varforreturndialoglabel'.$name.'" class="hidden">'.(getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER') < 2 ? 'div for returned label' : '').'</div>';
2471
2472 $out .= '<!-- Add js code to open dialog popup on dialog -->';
2473 $out .= '<script nonce="'.getNonce().'" type="text/javascript">
2474 jQuery(document).ready(function () {
2475 jQuery(".button_'.$name.'").click(function () {
2476 console.log(\'Open popup with jQuery(...).dialog() on URL '.dol_escape_js(DOL_URL_ROOT.$url).'\');
2477 var $tmpdialog = $(\'#idfordialog'.$name.'\');
2478 $tmpdialog.html(\'<iframe class="iframedialog" id="iframedialog'.$name.'" style="border: 0px;" src="'.DOL_URL_ROOT.$url.'" width="100%" height="98%"></iframe>\');
2479 $tmpdialog.dialog({
2480 autoOpen: false,
2481 modal: true,
2482 height: (window.innerHeight - 150),
2483 width: \'80%\',
2484 title: \''.dol_escape_js($label).'\',
2485 open: function (event, ui) {
2486 console.log("open popup name='.$name.', backtopagejsfields='.$backtopagejsfields.'");
2487 },
2488 close: function (event, ui) {
2489 var returnedid = jQuery("#varforreturndialogid'.$name.'").text();
2490 var returnedlabel = jQuery("#varforreturndialoglabel'.$name.'").text();
2491 console.log("popup has been closed. returnedid (js var defined into parent page)="+returnedid+" returnedlabel="+returnedlabel);
2492 if (returnedid != "" && returnedid != "div for returned id") {
2493 jQuery("#'.(empty($backtopagejsfieldsid) ? "none" : $backtopagejsfieldsid).'").val(returnedid);
2494 }
2495 if (returnedlabel != "" && returnedlabel != "div for returned label") {
2496 jQuery("#'.(empty($backtopagejsfieldslabel) ? "none" : $backtopagejsfieldslabel).'").val(returnedlabel);
2497 }
2498 }
2499 });
2500
2501 $tmpdialog.dialog(\'open\');
2502 return false;
2503 });
2504 });
2505 </script>';
2506 }
2507 return $out;
2508}
2509
2526function dol_fiche_head($links = array(), $active = '0', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
2527{
2528 print dol_get_fiche_head($links, $active, $title, $notab, $picto, $pictoisfullpath, $morehtmlright, $morecss, $limittoshow, $moretabssuffix);
2529}
2530
2547function dol_get_fiche_head($links = array(), $active = '', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '', $dragdropfile = 0)
2548{
2549 global $conf, $langs, $hookmanager;
2550
2551 // Show title
2552 $showtitle = 1;
2553 if (!empty($conf->dol_optimize_smallscreen)) {
2554 $showtitle = 0;
2555 }
2556
2557 $out = "\n".'<!-- dol_fiche_head - dol_get_fiche_head -->';
2558
2559 if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
2560 $out .= '<div class="tabs'.($picto ? '' : ' nopaddingleft').'" data-role="controlgroup" data-type="horizontal">'."\n";
2561 }
2562
2563 // Show right part
2564 if ($morehtmlright) {
2565 $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.
2566 }
2567
2568 // Show title
2569 /*
2570 if (!empty($title) && $showtitle && !getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2571 $limittitle = 30;
2572 $out .= '<a class="tabTitle">';
2573 if ($picto) {
2574 $noprefix = $pictoisfullpath;
2575 if (strpos($picto, 'fontawesome_') !== false) {
2576 $noprefix = 1;
2577 }
2578 $out .= img_picto($title, ($noprefix ? '' : 'object_').$picto, '', $pictoisfullpath, 0, 0, '', 'imgTabTitle').' ';
2579 }
2580 $out .= '<span class="tabTitleText">'.dol_escape_htmltag(dol_trunc($title, $limittitle)).'</span>';
2581 $out .= '</a>';
2582 }
2583 */
2584
2585 // Show tabs
2586
2587 // Define max of key (max may be higher than sizeof because of hole due to module disabling some tabs).
2588 $maxkey = -1;
2589 if (is_array($links) && !empty($links)) {
2590 $keys = array_keys($links);
2591 if (count($keys)) {
2592 $maxkey = max($keys);
2593 }
2594 }
2595
2596 // Show tabs
2597 // if =0 we don't use the feature
2598 if (empty($limittoshow)) {
2599 $limittoshow = (!getDolGlobalString('MAIN_MAXTABS_IN_CARD') ? 99 : $conf->global->MAIN_MAXTABS_IN_CARD);
2600 }
2601 if (!empty($conf->dol_optimize_smallscreen)) {
2602 $limittoshow = 2;
2603 }
2604
2605 $displaytab = 0;
2606 $nbintab = 0;
2607 $popuptab = 0;
2608 $outmore = '';
2609 for ($i = 0; $i <= $maxkey; $i++) {
2610 if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
2611 // If active tab is already present
2612 if ($i >= $limittoshow) {
2613 $limittoshow--;
2614 }
2615 }
2616 }
2617
2618 for ($i = 0; $i <= $maxkey; $i++) {
2619 if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
2620 $isactive = true;
2621 } else {
2622 $isactive = false;
2623 }
2624
2625 if ($i < $limittoshow || $isactive) {
2626 // Output entry with a visible tab
2627 $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])).' -->';
2628
2629 if (isset($links[$i][2]) && $links[$i][2] == 'image') {
2630 if (!empty($links[$i][0])) {
2631 $out .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
2632 } else {
2633 $out .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
2634 }
2635 } elseif (!empty($links[$i][1])) {
2636 //print "x $i $active ".$links[$i][2]." z";
2637 $out .= '<div class="tab tab'.($isactive ? 'active' : 'unactive').'" style="margin: 0 !important">';
2638
2639 if (!empty($links[$i][0])) {
2640 $titletoshow = preg_replace('/<.*$/', '', $links[$i][1]);
2641 $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).'">';
2642 }
2643
2644 if ($displaytab == 0) {
2645 $out .= img_picto($title, $picto, '', $pictoisfullpath, 0, 0, '', 'imgTabTitle paddingright marginrightonlyshort');
2646 }
2647
2648 $out .= $links[$i][1];
2649 if (!empty($links[$i][0])) {
2650 $out .= '</a>'."\n";
2651 }
2652 $out .= empty($links[$i][4]) ? '' : $links[$i][4];
2653 $out .= '</div>';
2654 }
2655
2656 $out .= '</div>';
2657 } else {
2658 // Add entry into the combo popup with the other tabs
2659 if (!$popuptab) {
2660 $popuptab = 1;
2661 $outmore .= '<div class="popuptabset wordwrap">'; // The css used to hide/show popup
2662 }
2663 $outmore .= '<div class="popuptab wordwrap" style="display:inherit;">';
2664 if (isset($links[$i][2]) && $links[$i][2] == 'image') {
2665 if (!empty($links[$i][0])) {
2666 $outmore .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
2667 } else {
2668 $outmore .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
2669 }
2670 } elseif (!empty($links[$i][1])) {
2671 $outmore .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="wordwrap inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
2672 $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.
2673 $outmore .= '</a>'."\n";
2674 }
2675 $outmore .= '</div>';
2676
2677 $nbintab++;
2678 }
2679
2680 $displaytab = $i + 1;
2681 }
2682 if ($popuptab) {
2683 $outmore .= '</div>';
2684 }
2685
2686 if ($popuptab) { // If there is some tabs not shown
2687 $left = ($langs->trans("DIRECTION") == 'rtl' ? 'right' : 'left');
2688 $right = ($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right');
2689 $widthofpopup = 200;
2690
2691 $tabsname = $moretabssuffix;
2692 if (empty($tabsname)) {
2693 $tabsname = str_replace("@", "", $picto);
2694 }
2695 $out .= '<div id="moretabs'.$tabsname.'" class="inline-block tabsElem valignmiddle">';
2696 if (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER') < 2) {
2697 $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".
2698 }
2699 $out .= '<div id="moretabsList'.$tabsname.'" style="width: '.$widthofpopup.'px; position: absolute; '.$left.': -999em; text-align: '.$left.'; margin:0px; padding:2px; z-index:10;">';
2700 $out .= $outmore;
2701 $out .= '</div>';
2702 $out .= '<div></div>';
2703 $out .= "</div>\n";
2704
2705 $out .= '<script nonce="'.getNonce().'">';
2706 $out .= "$('#moretabs".$tabsname."').mouseenter( function() {
2707 var x = this.offsetLeft, y = this.offsetTop;
2708 console.log('mouseenter ".$left." x='+x+' y='+y+' window.innerWidth='+window.innerWidth);
2709 if ((window.innerWidth - x) < ".($widthofpopup + 10).") {
2710 $('#moretabsList".$tabsname."').css('".$right."','8px');
2711 }
2712 $('#moretabsList".$tabsname."').css('".$left."','auto');
2713 });
2714 ";
2715 $out .= "$('#moretabs".$tabsname."').mouseleave( function() { console.log('mouseleave ".$left."'); $('#moretabsList".$tabsname."').css('".$left."','-999em');});";
2716 $out .= "</script>";
2717 }
2718
2719 if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
2720 $out .= "</div>\n";
2721 }
2722
2723 if (!$notab || $notab == -1 || $notab == -2 || $notab == -3) {
2724 $out .= "\n".'<div id="dragDropAreaTabBar" class="tabBar'.($notab == -1 ? '' : ($notab == -2 ? ' tabBarNoTop' : (($notab == -3 ? ' noborderbottom' : '').' tabBarWithBottom')));
2725 $out .= '">'."\n";
2726 }
2727 if (!empty($dragdropfile)) {
2728 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2729 $out .= dragAndDropFileUpload("dragDropAreaTabBar");
2730 }
2731 $parameters = array('tabname' => $active, 'out' => $out);
2732 $reshook = $hookmanager->executeHooks('printTabsHead', $parameters); // This hook usage is called just before output the head of tabs. Take also a look at "completeTabsHead"
2733 if ($reshook > 0) {
2734 $out = $hookmanager->resPrint;
2735 }
2736
2737 return $out;
2738}
2739
2747function dol_fiche_end($notab = 0)
2748{
2749 print dol_get_fiche_end($notab);
2750}
2751
2758function dol_get_fiche_end($notab = 0)
2759{
2760 if (!$notab || $notab == -1) {
2761 return "\n</div>\n";
2762 } else {
2763 return '';
2764 }
2765}
2766
2786function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $onlybanner = 0, $morehtmlright = '')
2787{
2788 global $conf, $form, $user, $langs, $hookmanager, $action;
2789
2790 $error = 0;
2791
2792 $maxvisiblephotos = 1;
2793 $showimage = 1;
2794 $entity = (empty($object->entity) ? $conf->entity : $object->entity);
2795 // @phan-suppress-next-line PhanUndeclaredMethod
2796 $showbarcode = !isModEnabled('barcode') ? 0 : (empty($object->barcode) ? 0 : 1);
2797 if (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !$user->hasRight('barcode', 'lire_advance')) {
2798 $showbarcode = 0;
2799 }
2800 $modulepart = 'unknown';
2801
2802 if (in_array($object->element, ['societe', 'contact', 'product', 'ticket', 'bom'])) {
2803 $modulepart = $object->element;
2804 } elseif ($object->element == 'member') {
2805 $modulepart = 'memberphoto';
2806 } elseif ($object->element == 'user') {
2807 $modulepart = 'userphoto';
2808 }
2809
2810 if (class_exists("Imagick")) {
2811 if ($object->element == 'expensereport' || $object->element == 'propal' || $object->element == 'commande' || $object->element == 'facture' || $object->element == 'supplier_proposal') {
2812 $modulepart = $object->element;
2813 } elseif ($object->element == 'fichinter' || $object->element == 'intervention') {
2814 $modulepart = 'ficheinter';
2815 } elseif ($object->element == 'contrat' || $object->element == 'contract') {
2816 $modulepart = 'contract';
2817 } elseif ($object->element == 'order_supplier') {
2818 $modulepart = 'supplier_order';
2819 } elseif ($object->element == 'invoice_supplier') {
2820 $modulepart = 'supplier_invoice';
2821 }
2822 }
2823
2824 if ($object->element == 'product') {
2826 '@phan-var-force Product $object';
2827 $width = 80;
2828 $cssclass = 'photowithmargin photoref';
2829 $showimage = $object->is_photo_available($conf->product->multidir_output[$entity]);
2830 $maxvisiblephotos = getDolGlobalInt('PRODUCT_MAX_VISIBLE_PHOTO', 5);
2831 if ($conf->browser->layout == 'phone') {
2832 $maxvisiblephotos = 1;
2833 }
2834 if ($showimage) {
2835 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$object->show_photos('product', $conf->product->multidir_output[$entity], 1, $maxvisiblephotos, 0, 0, 0, 0, $width, 0, '').'</div>';
2836 } else {
2837 if (getDolGlobalString('PRODUCT_NODISPLAYIFNOPHOTO')) {
2838 $nophoto = '';
2839 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
2840 } else { // Show no photo link
2841 $nophoto = '/public/theme/common/nophoto.png';
2842 $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>';
2843 }
2844 }
2845 } elseif ($object->element == 'category') {
2847 '@phan-var-force Categorie $object';
2848 $width = 80;
2849 $cssclass = 'photowithmargin photoref';
2850 $showimage = $object->isAnyPhotoAvailable($conf->categorie->multidir_output[$entity]);
2851 $maxvisiblephotos = getDolGlobalInt('CATEGORY_MAX_VISIBLE_PHOTO', 5);
2852 if ($conf->browser->layout == 'phone') {
2853 $maxvisiblephotos = 1;
2854 }
2855 if ($showimage) {
2856 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$object->show_photos('category', $conf->categorie->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, 0, $width, 0, '').'</div>';
2857 } else {
2858 if (getDolGlobalString('CATEGORY_NODISPLAYIFNOPHOTO')) {
2859 $nophoto = '';
2860 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
2861 } else { // Show no photo link
2862 $nophoto = '/public/theme/common/nophoto.png';
2863 $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>';
2864 }
2865 }
2866 } elseif ($object->element == 'bom') {
2868 '@phan-var-force Bom $object';
2869 $width = 80;
2870 $cssclass = 'photowithmargin photoref';
2871 $showimage = $object->is_photo_available($conf->bom->multidir_output[$entity]);
2872 $maxvisiblephotos = getDolGlobalInt('BOM_MAX_VISIBLE_PHOTO', 5);
2873 if ($conf->browser->layout == 'phone') {
2874 $maxvisiblephotos = 1;
2875 }
2876 if ($showimage) {
2877 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$object->show_photos('bom', $conf->bom->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, 0, $width, 0, '').'</div>';
2878 } else {
2879 if (getDolGlobalString('BOM_NODISPLAYIFNOPHOTO')) {
2880 $nophoto = '';
2881 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
2882 } else { // Show no photo link
2883 $nophoto = '/public/theme/common/nophoto.png';
2884 $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>';
2885 }
2886 }
2887 } elseif ($object->element == 'ticket') {
2888 $width = 80;
2889 $cssclass = 'photoref';
2891 '@phan-var-force Ticket $object';
2892 $showimage = $object->is_photo_available($conf->ticket->multidir_output[$entity].'/'.$object->ref);
2893 $maxvisiblephotos = getDolGlobalInt('TICKET_MAX_VISIBLE_PHOTO', 2);
2894 if ($conf->browser->layout == 'phone') {
2895 $maxvisiblephotos = 1;
2896 }
2897
2898 if ($showimage) {
2899 $showphoto = $object->show_photos('ticket', $conf->ticket->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0);
2900 if ($object->nbphoto > 0) {
2901 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$showphoto.'</div>';
2902 } else {
2903 $showimage = 0;
2904 }
2905 }
2906 if (!$showimage) {
2907 if (getDolGlobalString('TICKET_NODISPLAYIFNOPHOTO')) {
2908 $nophoto = '';
2909 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
2910 } else { // Show no photo link
2911 $nophoto = img_picto('No photo', 'object_ticket');
2912 $morehtmlleft .= '<!-- No photo to show -->';
2913 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
2914 $morehtmlleft .= $nophoto;
2915 $morehtmlleft .= '</div></div>';
2916 }
2917 }
2918 } else {
2919 if ($showimage) {
2920 if ($modulepart != 'unknown' || method_exists($object, 'getDataToShowPhoto')) {
2921 $phototoshow = '';
2922 // Check if a preview file is available
2923 if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice', 'expensereport')) && class_exists("Imagick")) {
2924 $objectref = dol_sanitizeFileName($object->ref);
2925 $dir_output = (empty($conf->$modulepart->multidir_output[$entity]) ? $conf->$modulepart->dir_output : $conf->$modulepart->multidir_output[$entity])."/";
2926 if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice'))) {
2927 $subdir = get_exdir($object->id, 2, 0, 1, $object, $modulepart);
2928 $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
2929 } else {
2930 $subdir = get_exdir($object->id, 0, 0, 1, $object, $modulepart);
2931 }
2932 if (empty($subdir)) {
2933 $subdir = 'errorgettingsubdirofobject'; // Protection to avoid to return empty path
2934 }
2935
2936 $filepath = $dir_output.$subdir."/";
2937
2938 $filepdf = $filepath.$objectref.".pdf";
2939 $relativepath = $subdir.'/'.$objectref.'.pdf';
2940
2941 // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png")
2942 $fileimage = $filepdf.'_preview.png';
2943 $relativepathimage = $relativepath.'_preview.png';
2944
2945 $pdfexists = file_exists($filepdf);
2946
2947 // If PDF file exists
2948 if ($pdfexists) {
2949 // Conversion du PDF en image png si fichier png non existent
2950 if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf))) {
2951 if (!getDolGlobalString('MAIN_DISABLE_PDF_THUMBS')) { // If you experience trouble with pdf thumb generation and imagick, you can disable here.
2952 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2953 $ret = dol_convert_file($filepdf, 'png', $fileimage, '0'); // Convert first page of PDF into a file _preview.png
2954 if ($ret < 0) {
2955 $error++;
2956 }
2957 }
2958 }
2959 }
2960
2961 if ($pdfexists && !$error) {
2962 $heightforphotref = 80;
2963 if (!empty($conf->dol_optimize_smallscreen)) {
2964 $heightforphotref = 60;
2965 }
2966 // If the preview file is found
2967 if (file_exists($fileimage)) {
2968 $phototoshow = '<div class="photoref">';
2969 $phototoshow .= '<img height="'.$heightforphotref.'" class="photo photowithborder" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($relativepathimage).'">';
2970 $phototoshow .= '</div>';
2971 }
2972 }
2973 } elseif (!$phototoshow) { // example if modulepart = 'societe' or 'photo' or 'memberphoto'
2974 $phototoshow .= $form->showphoto($modulepart, $object, 0, 0, 0, 'photowithmargin photoref', 'small', 1, 0, $maxvisiblephotos);
2975 }
2976
2977 if ($phototoshow) {
2978 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">';
2979 $morehtmlleft .= $phototoshow;
2980 $morehtmlleft .= '</div>';
2981 }
2982 }
2983
2984 if (empty($phototoshow)) { // Show No photo link (picto of object)
2985 if ($object->element == 'action') {
2986 $width = 80;
2987 $cssclass = 'photorefcenter';
2988 $nophoto = img_picto('No photo', 'title_agenda');
2989 } else {
2990 $width = 14;
2991 $cssclass = 'photorefcenter';
2992 $picto = $object->picto; // @phan-suppress-current-line PhanUndeclaredProperty
2993 $prefix = 'object_';
2994 if ($object->element == 'project' && !$object->public) { // @phan-suppress-current-line PhanUndeclaredProperty
2995 $picto = 'project'; // instead of projectpub
2996 }
2997 if (strpos($picto, 'fontawesome_') !== false) {
2998 $prefix = '';
2999 }
3000 $nophoto = img_picto('No photo', $prefix.$picto);
3001 }
3002 $morehtmlleft .= '<!-- No photo to show -->';
3003 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
3004 $morehtmlleft .= $nophoto;
3005 $morehtmlleft .= '</div></div>';
3006 }
3007 }
3008 }
3009
3010 // Show barcode
3011 if ($showbarcode) {
3012 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$form->showbarcode($object, 100, 'photoref valignmiddle').'</div>';
3013 }
3014
3015 if ($object->element == 'societe') {
3016 if (!empty($conf->use_javascript_ajax) && $user->hasRight('societe', 'creer') && getDolGlobalString('MAIN_DIRECT_STATUS_UPDATE')) {
3017 $morehtmlstatus .= ajax_object_onoff($object, 'status', 'status', 'InActivity', 'ActivityCeased');
3018 } else {
3019 $morehtmlstatus .= $object->getLibStatut(6);
3020 }
3021 } elseif ($object->element == 'product') {
3022 //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Sell").') ';
3023 if (!empty($conf->use_javascript_ajax) && $user->hasRight('produit', 'creer') && getDolGlobalString('MAIN_DIRECT_STATUS_UPDATE')) {
3024 $morehtmlstatus .= ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell');
3025 } else {
3026 $morehtmlstatus .= '<span class="statusrefsell">'.$object->getLibStatut(6, 0).'</span>';
3027 }
3028 $morehtmlstatus .= ' &nbsp; ';
3029 //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Buy").') ';
3030 if (!empty($conf->use_javascript_ajax) && $user->hasRight('produit', 'creer') && getDolGlobalString('MAIN_DIRECT_STATUS_UPDATE')) {
3031 $morehtmlstatus .= ajax_object_onoff($object, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy');
3032 } else {
3033 $morehtmlstatus .= '<span class="statusrefbuy">'.$object->getLibStatut(6, 1).'</span>';
3034 }
3035 } elseif (in_array($object->element, array('salary'))) {
3036 $tmptxt = $object->getLibStatut(6, $object->alreadypaid);
3037 if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
3038 $tmptxt = $object->getLibStatut(5, $object->alreadypaid);
3039 }
3040 $morehtmlstatus .= $tmptxt;
3041 } elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier', 'chargesociales', 'loan', 'tva'))) { // TODO Move this to use ->alreadypaid
3042 $tmptxt = $object->getLibStatut(6, $object->totalpaid);
3043 if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
3044 $tmptxt = $object->getLibStatut(5, $object->totalpaid);
3045 }
3046 $morehtmlstatus .= $tmptxt;
3047 } elseif ($object->element == 'contrat' || $object->element == 'contract') {
3048 if ($object->statut == 0) {
3049 $morehtmlstatus .= $object->getLibStatut(5);
3050 } else {
3051 $morehtmlstatus .= $object->getLibStatut(4);
3052 }
3053 } elseif ($object->element == 'facturerec') {
3054 '@phan-var-force FactureRec $object';
3055 if ($object->frequency == 0) {
3056 $morehtmlstatus .= $object->getLibStatut(2);
3057 } else {
3058 $morehtmlstatus .= $object->getLibStatut(5);
3059 }
3060 } elseif ($object->element == 'project_task') {
3061 $object->fk_statut = 1;
3062 $object->status = 1;
3063 if ($object->progress > 0) {
3064 $object->fk_statut = 2;
3065 $object->status = 2;
3066 }
3067 if ($object->progress >= 100) {
3068 $object->fk_statut = 3;
3069 $object->status = 3;
3070 }
3071 $tmptxt = $object->getLibStatut(5);
3072 $morehtmlstatus .= $tmptxt; // No status on task
3073 } elseif (method_exists($object, 'getLibStatut')) { // Generic case for status
3074 $tmptxt = $object->getLibStatut(6);
3075 if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
3076 $tmptxt = $object->getLibStatut(5);
3077 }
3078 $morehtmlstatus .= $tmptxt;
3079 }
3080
3081 // Add if object was dispatched "into accountancy"
3082 if (isModEnabled('accounting') && in_array($object->element, array('bank', 'paiementcharge', 'facture', 'invoice', 'invoice_supplier', 'expensereport', 'payment_various'))) {
3083 // Note: For 'chargesociales', 'salaries'... this is the payments that are dispatched (so element = 'bank')
3084 if (method_exists($object, 'getVentilExportCompta')) {
3085 $accounted = $object->getVentilExportCompta();
3086 $langs->load("accountancy");
3087 $morehtmlstatus .= '</div><div class="statusref statusrefbis"><span class="opacitymedium">'.($accounted > 0 ? $langs->trans("Accounted") : $langs->trans("NotYetAccounted")).'</span>';
3088 }
3089 }
3090
3091 // Add alias for thirdparty
3092 if (!empty($object->name_alias)) {
3093 '@phan-var-force Societe $object';
3094 $morehtmlref .= '<div class="refidno opacitymedium">'.dol_escape_htmltag($object->name_alias).'</div>';
3095 }
3096
3097 // Add label
3098 if (in_array($object->element, array('product', 'bank_account', 'project_task'))) {
3099 if (!empty($object->label)) {
3100 $morehtmlref .= '<div class="refidno opacitymedium">'.$object->label.'</div>';
3101 }
3102 }
3103 // Show address and email
3104 if (method_exists($object, 'getBannerAddress') && !in_array($object->element, array('product', 'bookmark', 'ecm_directories', 'ecm_files'))) {
3105 $moreaddress = $object->getBannerAddress('refaddress', $object); // address, email, url, social networks
3106 if ($moreaddress) {
3107 $morehtmlref .= '<div class="refidno refaddress">';
3108 $morehtmlref .= $moreaddress;
3109 $morehtmlref .= '</div>';
3110 }
3111 }
3112 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)) {
3113 $morehtmlref .= '<div style="clear: both;"></div>';
3114 $morehtmlref .= '<div class="refidno opacitymedium">';
3115 $morehtmlref .= $langs->trans("TechnicalID").': '.((int) $object->id);
3116 $morehtmlref .= '</div>';
3117 }
3118
3119 $parameters = array('morehtmlref' => &$morehtmlref, 'moreparam' => &$moreparam, 'morehtmlleft' => &$morehtmlleft, 'morehtmlstatus' => &$morehtmlstatus, 'morehtmlright' => &$morehtmlright);
3120 $reshook = $hookmanager->executeHooks('formDolBanner', $parameters, $object, $action);
3121 if ($reshook < 0) {
3122 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
3123 } elseif (empty($reshook)) {
3124 $morehtmlref .= $hookmanager->resPrint;
3125 } elseif ($reshook > 0) {
3126 $morehtmlref = $hookmanager->resPrint;
3127 }
3128
3129 // $morehtml is the right part (link "Back to list")
3130 // $morehtmlleft is the picto or photo of banner
3131 // $morehtmlstatus is part under the status
3132 // $morehtmlright is part of htmlright
3133
3134 print '<div class="'.($onlybanner ? 'arearefnobottom ' : 'arearef ').'heightref valignmiddle centpercent">';
3135 print $form->showrefnav($object, $paramid, $morehtml, $shownav, $fieldid, $fieldref, $morehtmlref, $moreparam, $nodbprefix, $morehtmlleft, $morehtmlstatus, $morehtmlright);
3136 print '</div>';
3137 print '<div class="underrefbanner clearboth"></div>';
3138}
3139
3149function fieldLabel($langkey, $fieldkey, $fieldrequired = 0)
3150{
3151 global $langs;
3152 $ret = '';
3153 if ($fieldrequired) {
3154 $ret .= '<span class="fieldrequired">';
3155 }
3156 $ret .= '<label for="'.$fieldkey.'">';
3157 $ret .= $langs->trans($langkey);
3158 $ret .= '</label>';
3159 if ($fieldrequired) {
3160 $ret .= '</span>';
3161 }
3162 return $ret;
3163}
3164
3172function dol_bc($var, $moreclass = '')
3173{
3174 global $bc;
3175 $ret = ' '.$bc[$var];
3176 if ($moreclass) {
3177 $ret = preg_replace('/class=\"/', 'class="'.$moreclass.' ', $ret);
3178 }
3179 return $ret;
3180}
3181
3195function dol_format_address($object, $withcountry = 0, $sep = "\n", $outputlangs = null, $mode = 0, $extralangcode = '')
3196{
3197 global $langs, $hookmanager;
3198
3199 $ret = '';
3200 $countriesusingstate = array('AU', 'CA', 'US', 'IN', 'GB', 'ES', 'UK', 'TR', 'CN'); // See also MAIN_FORCE_STATE_INTO_ADDRESS
3201
3202 // See format of addresses on https://en.wikipedia.org/wiki/Address
3203 // Address
3204 if (empty($mode)) {
3205 $ret .= ($extralangcode ? $object->array_languages['address'][$extralangcode] : (empty($object->address) ? '' : preg_replace('/(\r\n|\r|\n)+/', $sep, $object->address)));
3206 }
3207 // Zip/Town/State
3208 if (isset($object->country_code) && in_array($object->country_code, array('AU', 'CA', 'US', 'CN')) || getDolGlobalString('MAIN_FORCE_STATE_INTO_ADDRESS')) {
3209 // US: title firstname name \n address lines \n town, state, zip \n country
3210 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
3211 $ret .= (($ret && $town) ? $sep : '').$town;
3212
3213 if (!empty($object->state)) {
3214 $ret .= ($ret ? ($town ? ", " : $sep) : '').$object->state;
3215 }
3216 if (!empty($object->zip)) {
3217 $ret .= ($ret ? (($town || $object->state) ? ", " : $sep) : '').$object->zip;
3218 }
3219 } elseif (isset($object->country_code) && in_array($object->country_code, array('GB', 'UK'))) {
3220 // UK: title firstname name \n address lines \n town state \n zip \n country
3221 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
3222 $ret .= ($ret ? $sep : '').$town;
3223 if (!empty($object->state)) {
3224 $ret .= ($ret ? ", " : '').$object->state;
3225 }
3226 if (!empty($object->zip)) {
3227 $ret .= ($ret ? $sep : '').$object->zip;
3228 }
3229 } elseif (isset($object->country_code) && in_array($object->country_code, array('ES', 'TR'))) {
3230 // ES: title firstname name \n address lines \n zip town \n state \n country
3231 $ret .= ($ret ? $sep : '').$object->zip;
3232 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
3233 $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
3234 if (!empty($object->state)) {
3235 $ret .= $sep.$object->state;
3236 }
3237 } elseif (isset($object->country_code) && in_array($object->country_code, array('JP'))) {
3238 // JP: In romaji, title firstname name\n address lines \n [state,] town zip \n country
3239 // See https://www.sljfaq.org/afaq/addresses.html
3240 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
3241 $ret .= ($ret ? $sep : '').($object->state ? $object->state.', ' : '').$town.($object->zip ? ' ' : '').$object->zip;
3242 } elseif (isset($object->country_code) && in_array($object->country_code, array('IT'))) {
3243 // IT: title firstname name\n address lines \n zip town state_code \n country
3244 $ret .= ($ret ? $sep : '').$object->zip;
3245 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
3246 $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
3247 $ret .= (empty($object->state_code) ? '' : (' '.$object->state_code));
3248 } else {
3249 // Other: title firstname name \n address lines \n zip town[, state] \n country
3250 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
3251 $ret .= !empty($object->zip) ? (($ret ? $sep : '').$object->zip) : '';
3252 $ret .= ($town ? (($object->zip ? ' ' : ($ret ? $sep : '')).$town) : '');
3253 if (!empty($object->state) && in_array($object->country_code, $countriesusingstate)) {
3254 $ret .= ($ret ? ", " : '').$object->state;
3255 }
3256 }
3257
3258 if (!is_object($outputlangs)) {
3259 $outputlangs = $langs;
3260 }
3261 if ($withcountry) {
3262 $langs->load("dict");
3263 $ret .= (empty($object->country_code) ? '' : ($ret ? $sep : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$object->country_code)));
3264 }
3265 if ($hookmanager) {
3266 $parameters = array('withcountry' => $withcountry, 'sep' => $sep, 'outputlangs' => $outputlangs,'mode' => $mode, 'extralangcode' => $extralangcode);
3267 $reshook = $hookmanager->executeHooks('formatAddress', $parameters, $object);
3268 if ($reshook > 0) {
3269 $ret = '';
3270 }
3271 $ret .= $hookmanager->resPrint;
3272 }
3273
3274 return $ret;
3275}
3276
3277
3278
3288function dol_strftime($fmt, $ts = false, $is_gmt = false)
3289{
3290 if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
3291 return dol_print_date($ts, $fmt, $is_gmt);
3292 } else {
3293 return 'Error date outside supported range';
3294 }
3295}
3296
3318function dol_print_date($time, $format = '', $tzoutput = 'auto', $outputlangs = null, $encodetooutput = false)
3319{
3320 global $conf, $langs;
3321
3322 // If date undefined or "", we return ""
3323 if (dol_strlen($time) == 0) {
3324 return ''; // $time=0 allowed (it means 01/01/1970 00:00:00)
3325 }
3326
3327 if ($tzoutput === 'auto') {
3328 $tzoutput = (empty($conf) ? 'tzserver' : (isset($conf->tzuserinputkey) ? $conf->tzuserinputkey : 'tzserver'));
3329 }
3330
3331 // Clean parameters
3332 $to_gmt = false;
3333 $offsettz = $offsetdst = 0;
3334 if ($tzoutput) {
3335 $to_gmt = true; // For backward compatibility
3336 if (is_string($tzoutput)) {
3337 if ($tzoutput == 'tzserver') {
3338 $to_gmt = false;
3339 $offsettzstring = @date_default_timezone_get(); // Example 'Europe/Berlin' or 'Indian/Reunion'
3340 // @phan-suppress-next-line PhanPluginRedundantAssignment
3341 $offsettz = 0; // Timezone offset with server timezone (because to_gmt is false), so 0
3342 // @phan-suppress-next-line PhanPluginRedundantAssignment
3343 $offsetdst = 0; // Dst offset with server timezone (because to_gmt is false), so 0
3344 } elseif ($tzoutput == 'tzuser' || $tzoutput == 'tzuserrel') {
3345 $to_gmt = true;
3346 $offsettzstring = (empty($_SESSION['dol_tz_string']) ? 'UTC' : $_SESSION['dol_tz_string']); // Example 'Europe/Berlin' or 'Indian/Reunion'
3347
3348 if (class_exists('DateTimeZone')) {
3349 $user_date_tz = new DateTimeZone($offsettzstring);
3350 $user_dt = new DateTime();
3351 $user_dt->setTimezone($user_date_tz);
3352 $user_dt->setTimestamp($tzoutput == 'tzuser' ? dol_now() : (int) $time);
3353 $offsettz = $user_dt->getOffset(); // should include dst ?
3354 } else { // with old method (The 'tzuser' was processed like the 'tzuserrel')
3355 $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60; // Will not be used anymore
3356 $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60; // Will not be used anymore
3357 }
3358 }
3359 }
3360 }
3361 if (!is_object($outputlangs)) {
3362 $outputlangs = $langs;
3363 }
3364 if (!$format) {
3365 $format = 'daytextshort';
3366 }
3367
3368 // Do we have to reduce the length of date (year on 2 chars) to save space.
3369 // Note: dayinputnoreduce is same than day but no reduction of year length will be done
3370 $reduceformat = (!empty($conf->dol_optimize_smallscreen) && in_array($format, array('day', 'dayhour', 'dayhoursec'))) ? 1 : 0; // Test on original $format param.
3371 $format = preg_replace('/inputnoreduce/', '', $format); // so format 'dayinputnoreduce' is processed like day
3372 $formatwithoutreduce = preg_replace('/reduceformat/', '', $format);
3373 if ($formatwithoutreduce != $format) {
3374 $format = $formatwithoutreduce;
3375 $reduceformat = 1;
3376 } // so format 'dayreduceformat' is processed like day
3377
3378 // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
3379 // TODO Add format daysmallyear and dayhoursmallyear
3380 if ($format == 'day') {
3381 $format = ($outputlangs->trans("FormatDateShort") != "FormatDateShort" ? $outputlangs->trans("FormatDateShort") : $conf->format_date_short);
3382 } elseif ($format == 'hour') {
3383 $format = ($outputlangs->trans("FormatHourShort") != "FormatHourShort" ? $outputlangs->trans("FormatHourShort") : $conf->format_hour_short);
3384 } elseif ($format == 'hourduration') {
3385 $format = ($outputlangs->trans("FormatHourShortDuration") != "FormatHourShortDuration" ? $outputlangs->trans("FormatHourShortDuration") : $conf->format_hour_short_duration);
3386 } elseif ($format == 'daytext') {
3387 $format = ($outputlangs->trans("FormatDateText") != "FormatDateText" ? $outputlangs->trans("FormatDateText") : $conf->format_date_text);
3388 } elseif ($format == 'daytextshort') {
3389 $format = ($outputlangs->trans("FormatDateTextShort") != "FormatDateTextShort" ? $outputlangs->trans("FormatDateTextShort") : $conf->format_date_text_short);
3390 } elseif ($format == 'dayhour') {
3391 $format = ($outputlangs->trans("FormatDateHourShort") != "FormatDateHourShort" ? $outputlangs->trans("FormatDateHourShort") : $conf->format_date_hour_short);
3392 } elseif ($format == 'dayhoursec') {
3393 $format = ($outputlangs->trans("FormatDateHourSecShort") != "FormatDateHourSecShort" ? $outputlangs->trans("FormatDateHourSecShort") : $conf->format_date_hour_sec_short);
3394 } elseif ($format == 'dayhourtext') {
3395 $format = ($outputlangs->trans("FormatDateHourText") != "FormatDateHourText" ? $outputlangs->trans("FormatDateHourText") : $conf->format_date_hour_text);
3396 } elseif ($format == 'dayhourtextshort') {
3397 $format = ($outputlangs->trans("FormatDateHourTextShort") != "FormatDateHourTextShort" ? $outputlangs->trans("FormatDateHourTextShort") : $conf->format_date_hour_text_short);
3398 } elseif ($format == 'dayhourlog') {
3399 // Format not sensitive to language
3400 $format = '%Y%m%d%H%M%S';
3401 } elseif ($format == 'dayhourlogsmall') {
3402 // Format not sensitive to language
3403 $format = '%y%m%d%H%M';
3404 } elseif ($format == 'dayhourldap') {
3405 $format = '%Y%m%d%H%M%SZ';
3406 } elseif ($format == 'dayhourxcard') {
3407 $format = '%Y%m%dT%H%M%SZ';
3408 } elseif ($format == 'dayxcard') {
3409 $format = '%Y%m%d';
3410 } elseif ($format == 'dayrfc') {
3411 $format = '%Y-%m-%d'; // DATE_RFC3339
3412 } elseif ($format == 'dayhourrfc') {
3413 $format = '%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339
3414 } elseif ($format == 'standard') {
3415 $format = '%Y-%m-%d %H:%M:%S';
3416 }
3417
3418 if ($reduceformat) {
3419 $format = str_replace('%Y', '%y', $format);
3420 $format = str_replace('yyyy', 'yy', $format);
3421 }
3422
3423 // Clean format
3424 if (preg_match('/%b/i', $format)) { // There is some text to translate
3425 // We inhibit translation to text made by strftime functions. We will use trans instead later.
3426 $format = str_replace('%b', '__b__', $format);
3427 $format = str_replace('%B', '__B__', $format);
3428 }
3429 if (preg_match('/%a/i', $format)) { // There is some text to translate
3430 // We inhibit translation to text made by strftime functions. We will use trans instead later.
3431 $format = str_replace('%a', '__a__', $format);
3432 $format = str_replace('%A', '__A__', $format);
3433 }
3434
3435 // Analyze date
3436 $reg = array();
3437 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', (string) $time, $reg)) { // Deprecated. Ex: 1970-01-01, 1970-01-01 01:00:00, 19700101010000
3438 dol_print_error(null, "Functions.lib::dol_print_date function called with a bad value from page ".(empty($_SERVER["PHP_SELF"]) ? 'unknown' : $_SERVER["PHP_SELF"]));
3439 return '';
3440 } elseif (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+) ?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i', (string) $time, $reg)) { // Still available to solve problems in extrafields of type date
3441 // This part of code should not be used anymore.
3442 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);
3443 //if (function_exists('debug_print_backtrace')) debug_print_backtrace();
3444 // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
3445 $syear = (!empty($reg[1]) ? $reg[1] : '');
3446 $smonth = (!empty($reg[2]) ? $reg[2] : '');
3447 $sday = (!empty($reg[3]) ? $reg[3] : '');
3448 $shour = (!empty($reg[4]) ? $reg[4] : '');
3449 $smin = (!empty($reg[5]) ? $reg[5] : '');
3450 $ssec = (!empty($reg[6]) ? $reg[6] : '');
3451
3452 $time = dol_mktime((int) $shour, (int) $smin, (int) $ssec, (int) $smonth, (int) $sday, (int) $syear, true);
3453
3454 if ($to_gmt) {
3455 $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
3456 } else {
3457 $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
3458 }
3459 $dtts = new DateTime();
3460 $dtts->setTimestamp($time);
3461 $dtts->setTimezone($tzo);
3462 $newformat = str_replace(
3463 array('%Y', '%y', '%m', '%d', '%H', '%I', '%M', '%S', '%p', 'T', 'Z', '__a__', '__A__', '__b__', '__B__'),
3464 array('Y', 'y', 'm', 'd', 'H', 'h', 'i', 's', 'A', '__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
3465 $format
3466 );
3467 $ret = $dtts->format($newformat);
3468 $ret = str_replace(
3469 array('__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
3470 array('T', 'Z', '__a__', '__A__', '__b__', '__B__'),
3471 $ret
3472 );
3473 } else {
3474 // Date is a timestamps
3475 if ($time < 100000000000) { // Protection against bad date values
3476 $timetouse = $time + $offsettz + $offsetdst; // TODO We could be able to disable use of offsettz and offsetdst to use only offsettzstring.
3477
3478 if ($to_gmt) {
3479 $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
3480 } else {
3481 $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
3482 }
3483 $dtts = new DateTime();
3484 $dtts->setTimestamp($timetouse);
3485 $dtts->setTimezone($tzo);
3486 $newformat = str_replace(
3487 array('%Y', '%y', '%m', '%d', '%H', '%I', '%M', '%S', '%p', '%w', 'T', 'Z', '__a__', '__A__', '__b__', '__B__'),
3488 array('Y', 'y', 'm', 'd', 'H', 'h', 'i', 's', 'A', 'w', '__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
3489 $format
3490 );
3491 $ret = $dtts->format($newformat);
3492 $ret = str_replace(
3493 array('__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
3494 array('T', 'Z', '__a__', '__A__', '__b__', '__B__'),
3495 $ret
3496 );
3497 //var_dump($ret);exit;
3498 } else {
3499 $ret = 'Bad value '.$time.' for date';
3500 }
3501 }
3502
3503 if (preg_match('/__b__/i', $format)) {
3504 $timetouse = $time + $offsettz + $offsetdst; // TODO We could be able to disable use of offsettz and offsetdst to use only offsettzstring.
3505
3506 if ($to_gmt) {
3507 $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
3508 } else {
3509 $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
3510 }
3511 $dtts = new DateTime();
3512 $dtts->setTimestamp($timetouse);
3513 $dtts->setTimezone($tzo);
3514 $month = (int) $dtts->format("m");
3515 $month = sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'.
3516 if ($encodetooutput) {
3517 $monthtext = $outputlangs->transnoentities('Month'.$month);
3518 $monthtextshort = $outputlangs->transnoentities('MonthShort'.$month);
3519 } else {
3520 $monthtext = $outputlangs->transnoentitiesnoconv('Month'.$month);
3521 $monthtextshort = $outputlangs->transnoentitiesnoconv('MonthShort'.$month);
3522 }
3523 //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
3524 $ret = str_replace('__b__', $monthtextshort, $ret);
3525 $ret = str_replace('__B__', $monthtext, $ret);
3526 //print 'x'.$outputlangs->charset_output.'-'.$ret.'x';
3527 //return $ret;
3528 }
3529 if (preg_match('/__a__/i', $format)) {
3530 //print "time=$time offsettz=$offsettz offsetdst=$offsetdst offsettzstring=$offsettzstring";
3531 $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
3532
3533 if ($to_gmt) {
3534 $tzo = new DateTimeZone('UTC');
3535 } else {
3536 $tzo = new DateTimeZone(date_default_timezone_get());
3537 }
3538 $dtts = new DateTime();
3539 $dtts->setTimestamp($timetouse);
3540 $dtts->setTimezone($tzo);
3541 $w = $dtts->format("w");
3542 $dayweek = $outputlangs->transnoentitiesnoconv('Day'.$w);
3543
3544 $ret = str_replace('__A__', $dayweek, $ret);
3545 $ret = str_replace('__a__', dol_substr($dayweek, 0, 3), $ret);
3546 }
3547
3548 return $ret;
3549}
3550
3551
3572function dol_getdate($timestamp, $fast = false, $forcetimezone = '')
3573{
3574 if ($timestamp === '') {
3575 return array();
3576 }
3577
3578 $datetimeobj = new DateTime();
3579 $datetimeobj->setTimestamp($timestamp); // Use local PHP server timezone
3580 if ($forcetimezone) {
3581 $datetimeobj->setTimezone(new DateTimeZone($forcetimezone == 'gmt' ? 'UTC' : $forcetimezone)); // (add timezone relative to the date entered)
3582 }
3583 $arrayinfo = array(
3584 'year' => ((int) date_format($datetimeobj, 'Y')),
3585 'mon' => ((int) date_format($datetimeobj, 'm')),
3586 'mday' => ((int) date_format($datetimeobj, 'd')),
3587 'wday' => ((int) date_format($datetimeobj, 'w')),
3588 'yday' => ((int) date_format($datetimeobj, 'z')),
3589 'hours' => ((int) date_format($datetimeobj, 'H')),
3590 'minutes' => ((int) date_format($datetimeobj, 'i')),
3591 'seconds' => ((int) date_format($datetimeobj, 's')),
3592 '0' => $timestamp
3593 );
3594
3595 return $arrayinfo;
3596}
3597
3619function dol_mktime($hour, $minute, $second, $month, $day, $year, $gm = 'auto', $check = 1)
3620{
3621 global $conf;
3622 //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
3623
3624 if ($gm === 'auto') {
3625 $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
3626 }
3627 //print 'gm:'.$gm.' gm === auto:'.($gm === 'auto').'<br>';exit;
3628
3629 // Clean parameters
3630 if ($hour == -1 || empty($hour)) {
3631 $hour = 0;
3632 }
3633 if ($minute == -1 || empty($minute)) {
3634 $minute = 0;
3635 }
3636 if ($second == -1 || empty($second)) {
3637 $second = 0;
3638 }
3639
3640 // Check parameters
3641 if ($check) {
3642 if (!$month || !$day) {
3643 return '';
3644 }
3645 if ($day > 31) {
3646 return '';
3647 }
3648 if ($month > 12) {
3649 return '';
3650 }
3651 if ($hour < 0 || $hour > 24) {
3652 return '';
3653 }
3654 if ($minute < 0 || $minute > 60) {
3655 return '';
3656 }
3657 if ($second < 0 || $second > 60) {
3658 return '';
3659 }
3660 }
3661
3662 if (empty($gm) || ($gm === 'server' || $gm === 'tzserver')) {
3663 $default_timezone = @date_default_timezone_get(); // Example 'Europe/Berlin'
3664 $localtz = new DateTimeZone($default_timezone);
3665 } elseif ($gm === 'user' || $gm === 'tzuser' || $gm === 'tzuserrel') {
3666 // We use dol_tz_string first because it is more reliable.
3667 $default_timezone = (empty($_SESSION["dol_tz_string"]) ? @date_default_timezone_get() : $_SESSION["dol_tz_string"]); // Example 'Europe/Berlin'
3668 try {
3669 $localtz = new DateTimeZone($default_timezone);
3670 } catch (Exception $e) {
3671 dol_syslog("Warning dol_tz_string contains an invalid value ".json_encode($_SESSION["dol_tz_string"] ?? null), LOG_WARNING);
3672 $default_timezone = @date_default_timezone_get();
3673 }
3674 } elseif (strrpos($gm, "tz,") !== false) {
3675 $timezone = str_replace("tz,", "", $gm); // Example 'tz,Europe/Berlin'
3676 try {
3677 $localtz = new DateTimeZone($timezone);
3678 } catch (Exception $e) {
3679 dol_syslog("Warning passed timezone contains an invalid value ".$timezone, LOG_WARNING);
3680 }
3681 }
3682
3683 if (empty($localtz)) {
3684 $localtz = new DateTimeZone('UTC');
3685 }
3686 //var_dump($localtz);
3687 //var_dump($year.'-'.$month.'-'.$day.'-'.$hour.'-'.$minute);
3688 $dt = new DateTime('now', $localtz);
3689 $dt->setDate((int) $year, (int) $month, (int) $day);
3690 $dt->setTime((int) $hour, (int) $minute, (int) $second);
3691 $date = $dt->getTimestamp(); // should include daylight saving time
3692 //var_dump($date);
3693 return $date;
3694}
3695
3696
3707function dol_now($mode = 'auto')
3708{
3709 $ret = 0;
3710
3711 if ($mode === 'auto') {
3712 $mode = 'gmt';
3713 }
3714
3715 if ($mode == 'gmt') {
3716 $ret = time(); // Time for now at greenwich.
3717 } elseif ($mode == 'tzserver') { // Time for now with PHP server timezone added
3718 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
3719 $tzsecond = getServerTimeZoneInt('now'); // Contains tz+dayling saving time
3720 $ret = (int) (dol_now('gmt') + ($tzsecond * 3600));
3721 //} elseif ($mode == 'tzref') {// Time for now with parent company timezone is added
3722 // require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
3723 // $tzsecond=getParentCompanyTimeZoneInt(); // Contains tz+dayling saving time
3724 // $ret=dol_now('gmt')+($tzsecond*3600);
3725 //}
3726 } elseif ($mode == 'tzuser' || $mode == 'tzuserrel') {
3727 // Time for now with user timezone added
3728 //print 'time: '.time();
3729 $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60;
3730 $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60;
3731 $ret = (int) (dol_now('gmt') + ($offsettz + $offsetdst));
3732 }
3733
3734 return $ret;
3735}
3736
3737
3746function dol_print_size($size, $shortvalue = 0, $shortunit = 0)
3747{
3748 global $conf, $langs;
3749 $level = 1024;
3750
3751 if (!empty($conf->dol_optimize_smallscreen)) {
3752 $shortunit = 1;
3753 }
3754
3755 // Set value text
3756 if (empty($shortvalue) || $size < ($level * 10)) {
3757 $ret = $size;
3758 $textunitshort = $langs->trans("b");
3759 $textunitlong = $langs->trans("Bytes");
3760 } else {
3761 $ret = round($size / $level, 0);
3762 $textunitshort = $langs->trans("Kb");
3763 $textunitlong = $langs->trans("KiloBytes");
3764 }
3765 // Use long or short text unit
3766 if (empty($shortunit)) {
3767 $ret .= ' '.$textunitlong;
3768 } else {
3769 $ret .= ' '.$textunitshort;
3770 }
3771
3772 return $ret;
3773}
3774
3785function dol_print_url($url, $target = '_blank', $max = 32, $withpicto = 0, $morecss = '')
3786{
3787 global $langs;
3788
3789 if (empty($url)) {
3790 return '';
3791 }
3792
3793 $linkstart = '<a href="';
3794 if (!preg_match('/^http/i', $url)) {
3795 $linkstart .= 'http://';
3796 }
3797 $linkstart .= $url;
3798 $linkstart .= '"';
3799 if ($target) {
3800 $linkstart .= ' target="'.$target.'"';
3801 }
3802 $linkstart .= ' title="'.$langs->trans("URL").': '.$url.'"';
3803 $linkstart .= '>';
3804
3805 $link = '';
3806 if (!preg_match('/^http/i', $url)) {
3807 $link .= 'http://';
3808 }
3809 $link .= dol_trunc($url, $max);
3810
3811 $linkend = '</a>';
3812
3813 if ($morecss == 'float') { // deprecated
3814 return '<div class="nospan'.($morecss ? ' '.$morecss : '').'" style="margin-right: 10px">'.($withpicto ? img_picto($langs->trans("Url"), 'globe', 'class="paddingrightonly"') : '').$link.'</div>';
3815 } else {
3816 return $linkstart.'<span class="nospan'.($morecss ? ' '.$morecss : '').'" style="margin-right: 10px">'.($withpicto ? img_picto('', 'globe', 'class="paddingrightonly"') : '').$link.'</span>'.$linkend;
3817 }
3818}
3819
3833function dol_print_email($email, $cid = 0, $socid = 0, $addlink = 0, $max = 64, $showinvalid = 1, $withpicto = 0, $morecss = 'paddingrightonly')
3834{
3835 global $user, $langs, $hookmanager;
3836
3837 //global $conf; $conf->global->AGENDA_ADDACTIONFOREMAIL = 1;
3838 //$showinvalid = 1; $email = 'rrrrr';
3839
3840 $newemail = dol_escape_htmltag($email);
3841
3842 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') && $withpicto) {
3843 $withpicto = 0;
3844 }
3845
3846 if (empty($email)) {
3847 return '&nbsp;';
3848 }
3849
3850 if ($addlink == 1) {
3851 $newemail = '<a class="'.($morecss ? $morecss : '').'" style="text-overflow: ellipsis;" href="';
3852 if (!preg_match('/^mailto:/i', $email)) {
3853 $newemail .= 'mailto:';
3854 }
3855 $newemail .= $email;
3856 $newemail .= '">';
3857
3858 $newemail .= ($withpicto ? img_picto($langs->trans("EMail").' : '.$email, (is_numeric($withpicto) ? 'email' : $withpicto), 'class="paddingrightonly"') : '');
3859
3860 if ($max > 0) {
3861 $newemail .= dol_trunc($email, $max);
3862 } else {
3863 $newemail .= $email;
3864 }
3865 $newemail .= '</a>';
3866 if ($showinvalid && !isValidEmail($email)) {
3867 $langs->load("errors");
3868 $newemail .= img_warning($langs->trans("ErrorBadEMail", $email), '', 'paddingrightonly');
3869 }
3870
3871 if (($cid || $socid) && isModEnabled('agenda') && $user->hasRight("agenda", "myactions", "create")) {
3872 $type = 'AC_EMAIL';
3873 $linktoaddaction = '';
3874 if (getDolGlobalString('AGENDA_ADDACTIONFOREMAIL')) {
3875 $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>';
3876 }
3877 if ($linktoaddaction) {
3878 $newemail = '<div>'.$newemail.' '.$linktoaddaction.'</div>';
3879 }
3880 }
3881 } elseif ($addlink === 'thirdparty') {
3882 $tmpnewemail = '<a class="'.($morecss ? $morecss : '').'" style="text-overflow: ellipsis;" href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$socid.'&action=presend&mode=init#formmailbeforetitle">';
3883 $tmpnewemail .= ($withpicto ? img_picto($langs->trans("EMail").' : '.$email, (is_numeric($withpicto) ? 'email' : $withpicto), 'class="paddingrightonly"') : '');
3884 if ($withpicto == 1) {
3885 $tmpnewemail .= $newemail;
3886 }
3887 $tmpnewemail .= '</a>';
3888
3889 $newemail = $tmpnewemail;
3890 } else {
3891 $newemail = ($withpicto ? img_picto($langs->trans("EMail").' : '.$email, (is_numeric($withpicto) ? 'email' : $withpicto), 'class="paddingrightonly"') : '').$newemail;
3892
3893 if ($showinvalid && !isValidEmail($email)) {
3894 $langs->load("errors");
3895 $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
3896 }
3897 }
3898
3899 //$rep = '<div class="nospan" style="margin-right: 10px">';
3900 //$rep = ($withpicto ? img_picto($langs->trans("EMail").' : '.$email, (is_numeric($withpicto) ? 'email' : $withpicto), 'class="paddingrightonly"') : '').$newemail;
3901 //$rep .= '</div>';
3902 $rep = $newemail;
3903
3904 if ($hookmanager) {
3905 $parameters = array('cid' => $cid, 'socid' => $socid, 'addlink' => $addlink, 'picto' => $withpicto);
3906
3907 $reshook = $hookmanager->executeHooks('printEmail', $parameters, $email);
3908 if ($reshook > 0) {
3909 $rep = '';
3910 }
3911 $rep .= $hookmanager->resPrint;
3912 }
3913
3914 return $rep;
3915}
3916
3922function getArrayOfSocialNetworks()
3923{
3924 global $conf, $db;
3925
3926 $socialnetworks = array();
3927 // Enable caching of array
3928 require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php';
3929 $cachekey = 'socialnetworks_' . $conf->entity;
3930 $dataretrieved = dol_getcache($cachekey);
3931 if (!is_null($dataretrieved)) {
3932 $socialnetworks = $dataretrieved;
3933 } else {
3934 $sql = "SELECT rowid, code, label, url, icon, active FROM ".MAIN_DB_PREFIX."c_socialnetworks";
3935 $sql .= " WHERE entity=".$conf->entity;
3936 $resql = $db->query($sql);
3937 if ($resql) {
3938 while ($obj = $db->fetch_object($resql)) {
3939 $socialnetworks[$obj->code] = array(
3940 'rowid' => $obj->rowid,
3941 'label' => $obj->label,
3942 'url' => $obj->url,
3943 'icon' => $obj->icon,
3944 'active' => $obj->active,
3945 );
3946 }
3947 }
3948 dol_setcache($cachekey, $socialnetworks); // If setting cache fails, this is not a problem, so we do not test result.
3949 }
3950 return $socialnetworks;
3951}
3952
3963function dol_print_socialnetworks($value, $cid, $socid, $type, $dictsocialnetworks = array())
3964{
3965 global $hookmanager, $langs, $user;
3966
3967 $htmllink = $value;
3968
3969 if (empty($value)) {
3970 return '&nbsp;';
3971 }
3972
3973 if (!empty($type)) {
3974 $htmllink = '<div class="divsocialnetwork inline-block valignmiddle">';
3975 // Use dictionary definition for picto $dictsocialnetworks[$type]['icon']
3976 $htmllink .= '<span class="fab pictofixedwidth '.($dictsocialnetworks[$type]['icon'] ? $dictsocialnetworks[$type]['icon'] : 'fa-link').'"></span>';
3977 if ($type == 'skype') {
3978 $htmllink .= dol_escape_htmltag($value);
3979 $htmllink .= '&nbsp; <a href="skype:';
3980 $htmllink .= dol_string_nospecial($value, '_', '', array('@'));
3981 $htmllink .= '?call" alt="'.$langs->trans("Call").'&nbsp;'.$value.'" title="'.dol_escape_htmltag($langs->trans("Call").' '.$value).'">';
3982 $htmllink .= '<img src="'.DOL_URL_ROOT.'/theme/common/skype_callbutton.png" border="0">';
3983 $htmllink .= '</a><a href="skype:';
3984 $htmllink .= dol_string_nospecial($value, '_', '', array('@'));
3985 $htmllink .= '?chat" alt="'.$langs->trans("Chat").'&nbsp;'.$value.'" title="'.dol_escape_htmltag($langs->trans("Chat").' '.$value).'">';
3986 $htmllink .= '<img class="paddingleft" src="'.DOL_URL_ROOT.'/theme/common/skype_chatbutton.png" border="0">';
3987 $htmllink .= '</a>';
3988 if (($cid || $socid) && isModEnabled('agenda') && $user->hasRight('agenda', 'myactions', 'create')) {
3989 $addlink = 'AC_SKYPE';
3990 $link = '';
3991 if (getDolGlobalString('AGENDA_ADDACTIONFORSKYPE')) {
3992 $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>';
3993 }
3994 $htmllink .= ($link ? ' '.$link : '');
3995 }
3996 } else {
3997 $networkconstname = 'MAIN_INFO_SOCIETE_'.strtoupper($type).'_URL';
3998 if (getDolGlobalString($networkconstname)) {
3999 $link = str_replace('{socialid}', $value, getDolGlobalString($networkconstname));
4000 if (preg_match('/^https?:\/\//i', $link)) {
4001 $htmllink .= '<a href="'.dol_sanitizeUrl($link, 0).'" target="_blank" rel="noopener noreferrer">'.dol_escape_htmltag($value).'</a>';
4002 } else {
4003 $htmllink .= '<a href="'.dol_sanitizeUrl($link, 1).'" target="_blank" rel="noopener noreferrer">'.dol_escape_htmltag($value).'</a>';
4004 }
4005 } elseif (!empty($dictsocialnetworks[$type]['url'])) {
4006 $tmpvirginurl = preg_replace('/\/?{socialid}/', '', $dictsocialnetworks[$type]['url']);
4007 if ($tmpvirginurl) {
4008 $value = preg_replace('/^www\.'.preg_quote($tmpvirginurl, '/').'\/?/', '', $value);
4009 $value = preg_replace('/^'.preg_quote($tmpvirginurl, '/').'\/?/', '', $value);
4010
4011 $tmpvirginurl3 = preg_replace('/^https:\/\//i', 'https://www.', $tmpvirginurl);
4012 if ($tmpvirginurl3) {
4013 $value = preg_replace('/^www\.'.preg_quote($tmpvirginurl3, '/').'\/?/', '', $value);
4014 $value = preg_replace('/^'.preg_quote($tmpvirginurl3, '/').'\/?/', '', $value);
4015 }
4016
4017 $tmpvirginurl2 = preg_replace('/^https?:\/\//i', '', $tmpvirginurl);
4018 if ($tmpvirginurl2) {
4019 $value = preg_replace('/^www\.'.preg_quote($tmpvirginurl2, '/').'\/?/', '', $value);
4020 $value = preg_replace('/^'.preg_quote($tmpvirginurl2, '/').'\/?/', '', $value);
4021 }
4022 }
4023 $link = str_replace('{socialid}', $value, $dictsocialnetworks[$type]['url']);
4024 if (preg_match('/^https?:\/\//i', $link)) {
4025 $htmllink .= '<a href="'.dol_sanitizeUrl($link, 0).'" target="_blank" rel="noopener noreferrer">'.dol_escape_htmltag($value).'</a>';
4026 } else {
4027 $htmllink .= '<a href="'.dol_sanitizeUrl($link, 1).'" target="_blank" rel="noopener noreferrer">'.dol_escape_htmltag($value).'</a>';
4028 }
4029 } else {
4030 $htmllink .= dol_escape_htmltag($value);
4031 }
4032 }
4033 $htmllink .= '</div>';
4034 } else {
4035 $langs->load("errors");
4036 $htmllink .= img_warning($langs->trans("ErrorBadSocialNetworkValue", $value));
4037 }
4038
4039 if ($hookmanager) {
4040 $parameters = array(
4041 'value' => $value,
4042 'cid' => $cid,
4043 'socid' => $socid,
4044 'type' => $type,
4045 'dictsocialnetworks' => $dictsocialnetworks,
4046 );
4047
4048 $reshook = $hookmanager->executeHooks('printSocialNetworks', $parameters);
4049 if ($reshook > 0) {
4050 $htmllink = '';
4051 }
4052 $htmllink .= $hookmanager->resPrint;
4053 }
4054
4055 return $htmllink;
4056}
4057
4067function dol_print_profids($profID, $profIDtype, $countrycode = '', $addcpButton = 1)
4068{
4069 global $mysoc;
4070
4071 if (empty($profID) || empty($profIDtype)) {
4072 return '';
4073 }
4074 if (empty($countrycode)) {
4075 $countrycode = $mysoc->country_code;
4076 }
4077 $newProfID = $profID;
4078 $id = substr($profIDtype, -1);
4079 $ret = '';
4080 if (strtoupper($countrycode) == 'FR') {
4081 // France
4082 // (see https://www.economie.gouv.fr/entreprises/numeros-identification-entreprise)
4083
4084 if ($id == 1 && dol_strlen($newProfID) == 9) {
4085 // SIREN (ex: 123 123 123)
4086 $newProfID = substr($newProfID, 0, 3).' '.substr($newProfID, 3, 3).' '.substr($newProfID, 6, 3);
4087 }
4088 if ($id == 2 && dol_strlen($newProfID) == 14) {
4089 // SIRET (ex: 123 123 123 12345)
4090 $newProfID = substr($newProfID, 0, 3).' '.substr($newProfID, 3, 3).' '.substr($newProfID, 6, 3).' '.substr($newProfID, 9, 5);
4091 }
4092 if ($id == 3 && dol_strlen($newProfID) == 5) {
4093 // NAF/APE (ex: 69.20Z)
4094 $newProfID = substr($newProfID, 0, 2).'.'.substr($newProfID, 2, 3);
4095 }
4096 if ($profIDtype === 'VAT' && dol_strlen($newProfID) == 13) {
4097 // TVA intracommunautaire (ex: FR12 123 123 123)
4098 $newProfID = substr($newProfID, 0, 4).' '.substr($newProfID, 4, 3).' '.substr($newProfID, 7, 3).' '.substr($newProfID, 10, 3);
4099 }
4100 }
4101 if (!empty($addcpButton)) {
4102 $ret = showValueWithClipboardCPButton(dol_escape_htmltag($profID), ($addcpButton == 1 ? 1 : 0), $newProfID);
4103 } else {
4104 $ret = $newProfID;
4105 }
4106 return $ret;
4107}
4108
4124function dol_print_phone($phone, $countrycode = '', $cid = 0, $socid = 0, $addlink = '', $separ = "&nbsp;", $withpicto = '', $titlealt = '', $adddivfloat = 0, $morecss = 'paddingright')
4125{
4126 global $conf, $user, $langs, $mysoc, $hookmanager;
4127
4128 // Clean phone parameter
4129 $phone = is_null($phone) ? '' : preg_replace("/[\s.-]/", "", trim($phone));
4130 if (empty($phone)) {
4131 return '';
4132 }
4133 if (getDolGlobalString('MAIN_PHONE_SEPAR')) {
4134 $separ = getDolGlobalString('MAIN_PHONE_SEPAR');
4135 }
4136 if (empty($countrycode) && is_object($mysoc)) {
4137 $countrycode = $mysoc->country_code;
4138 }
4139
4140 // Short format for small screens
4141 if (!empty($conf->dol_optimize_smallscreen) && $separ != 'hidenum') {
4142 $separ = '';
4143 }
4144
4145 $newphone = $phone;
4146 $newphonewa = $phone;
4147 if (strtoupper($countrycode) == "FR") {
4148 // France
4149 if (dol_strlen($phone) == 10) {
4150 $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);
4151 } elseif (dol_strlen($phone) == 7) {
4152 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 2);
4153 } elseif (dol_strlen($phone) == 9) {
4154 $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 2).$separ.substr($newphone, 7, 2);
4155 } elseif (dol_strlen($phone) == 11) {
4156 $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);
4157 } elseif (dol_strlen($phone) == 12) {
4158 $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);
4159 } elseif (dol_strlen($phone) == 13) {
4160 $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);
4161 }
4162 } elseif (strtoupper($countrycode) == "CA") {
4163 if (dol_strlen($phone) == 10) {
4164 $newphone = ($separ != '' ? '(' : '').substr($newphone, 0, 3).($separ != '' ? ')' : '').$separ.substr($newphone, 3, 3).($separ != '' ? '-' : '').substr($newphone, 6, 4);
4165 }
4166 } elseif (strtoupper($countrycode) == "PT") {//Portugal
4167 if (dol_strlen($phone) == 13) {//ex: +351_ABC_DEF_GHI
4168 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
4169 }
4170 } elseif (strtoupper($countrycode) == "SR") {//Suriname
4171 if (dol_strlen($phone) == 10) {//ex: +597_ABC_DEF
4172 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3);
4173 } elseif (dol_strlen($phone) == 11) {//ex: +597_ABC_DEFG
4174 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 4);
4175 }
4176 } elseif (strtoupper($countrycode) == "DE") {//Allemagne
4177 if (dol_strlen($phone) == 14) {//ex: +49_ABCD_EFGH_IJK
4178 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 4).$separ.substr($newphone, 11, 3);
4179 } elseif (dol_strlen($phone) == 13) {//ex: +49_ABC_DEFG_HIJ
4180 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 4).$separ.substr($newphone, 10, 3);
4181 }
4182 } elseif (strtoupper($countrycode) == "ES") {//Espagne
4183 if (dol_strlen($phone) == 12) {//ex: +34_ABC_DEF_GHI
4184 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
4185 }
4186 } elseif (strtoupper($countrycode) == "BF") {// Burkina Faso
4187 if (dol_strlen($phone) == 12) {//ex : +22 A BC_DE_FG_HI
4188 $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);
4189 }
4190 } elseif (strtoupper($countrycode) == "RO") {// Roumanie
4191 if (dol_strlen($phone) == 12) {//ex : +40 AB_CDE_FG_HI
4192 $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);
4193 }
4194 } elseif (strtoupper($countrycode) == "TR") {//Turquie
4195 if (dol_strlen($phone) == 13) {//ex : +90 ABC_DEF_GHIJ
4196 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
4197 }
4198 } elseif (strtoupper($countrycode) == "US") {//Etat-Unis
4199 if (dol_strlen($phone) == 12) {//ex: +1 ABC_DEF_GHIJ
4200 $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
4201 }
4202 } elseif (strtoupper($countrycode) == "MX") {//Mexique
4203 if (dol_strlen($phone) == 12) {//ex: +52 ABCD_EFG_HI
4204 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
4205 } elseif (dol_strlen($phone) == 11) {//ex: +52 AB_CD_EF_GH
4206 $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);
4207 } elseif (dol_strlen($phone) == 13) {//ex: +52 ABC_DEF_GHIJ
4208 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
4209 }
4210 } elseif (strtoupper($countrycode) == "ML") {//Mali
4211 if (dol_strlen($phone) == 12) {//ex: +223 AB_CD_EF_GH
4212 $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);
4213 }
4214 } elseif (strtoupper($countrycode) == "TH") {//Thaïlande
4215 if (dol_strlen($phone) == 11) {//ex: +66_ABC_DE_FGH
4216 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
4217 } elseif (dol_strlen($phone) == 12) {//ex: +66_A_BCD_EF_GHI
4218 $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);
4219 }
4220 } elseif (strtoupper($countrycode) == "MU") {
4221 //Maurice
4222 if (dol_strlen($phone) == 11) {//ex: +230_ABC_DE_FG
4223 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2);
4224 } elseif (dol_strlen($phone) == 12) {//ex: +230_ABCD_EF_GH
4225 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
4226 }
4227 } elseif (strtoupper($countrycode) == "ZA") {//Afrique du sud
4228 if (dol_strlen($phone) == 12) {//ex: +27_AB_CDE_FG_HI
4229 $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);
4230 }
4231 } elseif (strtoupper($countrycode) == "SY") {//Syrie
4232 if (dol_strlen($phone) == 12) {//ex: +963_AB_CD_EF_GH
4233 $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);
4234 } elseif (dol_strlen($phone) == 13) {//ex: +963_AB_CD_EF_GHI
4235 $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);
4236 }
4237 } elseif (strtoupper($countrycode) == "AE") {//Emirats Arabes Unis
4238 if (dol_strlen($phone) == 12) {//ex: +971_ABC_DEF_GH
4239 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
4240 } elseif (dol_strlen($phone) == 13) {//ex: +971_ABC_DEF_GHI
4241 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
4242 } elseif (dol_strlen($phone) == 14) {//ex: +971_ABC_DEF_GHIK
4243 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 4);
4244 }
4245 } elseif (strtoupper($countrycode) == "DZ") {//Algérie
4246 if (dol_strlen($phone) == 13) {//ex: +213_ABC_DEF_GHI
4247 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
4248 }
4249 } elseif (strtoupper($countrycode) == "BE") {//Belgique
4250 if (dol_strlen($phone) == 11) {//ex: +32_ABC_DE_FGH
4251 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
4252 } elseif (dol_strlen($phone) == 12) {//ex: +32_ABC_DEF_GHI
4253 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
4254 }
4255 } elseif (strtoupper($countrycode) == "PF") {//Polynésie française
4256 if (dol_strlen($phone) == 12) {//ex: +689_AB_CD_EF_GH
4257 $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);
4258 }
4259 } elseif (strtoupper($countrycode) == "CO") {//Colombie
4260 if (dol_strlen($phone) == 13) {//ex: +57_ABC_DEF_GH_IJ
4261 $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);
4262 }
4263 } elseif (strtoupper($countrycode) == "JO") {//Jordanie
4264 if (dol_strlen($phone) == 12) {//ex: +962_A_BCD_EF_GH
4265 $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);
4266 }
4267 } elseif (strtoupper($countrycode) == "JM") {//Jamaïque
4268 if (dol_strlen($newphone) == 12) {//ex: +1867_ABC_DEFG
4269 $newphone = substr($newphone, 0, 5).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
4270 }
4271 } elseif (strtoupper($countrycode) == "MG") {//Madagascar
4272 if (dol_strlen($phone) == 13) {//ex: +261_AB_CD_EFG_HI
4273 $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);
4274 }
4275 } elseif (strtoupper($countrycode) == "GB") {//Royaume uni
4276 if (dol_strlen($phone) == 13) {//ex: +44_ABCD_EFG_HIJ
4277 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
4278 }
4279 } elseif (strtoupper($countrycode) == "CH") {//Suisse
4280 if (dol_strlen($phone) == 12) {//ex: +41_AB_CDE_FG_HI
4281 $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);
4282 } elseif (dol_strlen($phone) == 15) {// +41_AB_CDE_FGH_IJKL
4283 $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);
4284 }
4285 } elseif (strtoupper($countrycode) == "TN") {//Tunisie
4286 if (dol_strlen($phone) == 12) {//ex: +216_AB_CDE_FGH
4287 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
4288 }
4289 } elseif (strtoupper($countrycode) == "GF") {//Guyane francaise
4290 if (dol_strlen($phone) == 13) {//ex: +594_ABC_DE_FG_HI (ABC=594 de nouveau)
4291 $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);
4292 }
4293 } elseif (strtoupper($countrycode) == "GP") {//Guadeloupe
4294 if (dol_strlen($phone) == 13) {//ex: +590_ABC_DE_FG_HI (ABC=590 de nouveau)
4295 $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);
4296 }
4297 } elseif (strtoupper($countrycode) == "MQ") {//Martinique
4298 if (dol_strlen($phone) == 13) {//ex: +596_ABC_DE_FG_HI (ABC=596 de nouveau)
4299 $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);
4300 }
4301 } elseif (strtoupper($countrycode) == "IT") {//Italie
4302 if (dol_strlen($phone) == 12) {//ex: +39_ABC_DEF_GHI
4303 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
4304 } elseif (dol_strlen($phone) == 13) {//ex: +39_ABC_DEF_GH_IJ
4305 $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);
4306 }
4307 } elseif (strtoupper($countrycode) == "AU") {
4308 //Australie
4309 if (dol_strlen($phone) == 12) {
4310 //ex: +61_A_BCDE_FGHI
4311 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 4);
4312 }
4313 } elseif (strtoupper($countrycode) == "LU") {
4314 // Luxembourg
4315 if (dol_strlen($phone) == 10) {// fix 6 digits +352_AA_BB_CC
4316 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2);
4317 } elseif (dol_strlen($phone) == 11) {// fix 7 digits +352_AA_BB_CC_D
4318 $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);
4319 } elseif (dol_strlen($phone) == 12) {// fix 8 digits +352_AA_BB_CC_DD
4320 $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);
4321 } elseif (dol_strlen($phone) == 13) {// mobile +352_AAA_BB_CC_DD
4322 $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);
4323 }
4324 } elseif (strtoupper($countrycode) == "PE") {
4325 // Peru
4326 if (dol_strlen($phone) == 7) {// fix 7 chiffres without code AAA_BBBB
4327 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4);
4328 } elseif (dol_strlen($phone) == 9) {// mobile add code and fix 9 chiffres +51_AAA_BBB_CCC
4329 $newphonewa = '+51'.$newphone;
4330 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 10, 3);
4331 } elseif (dol_strlen($phone) == 11) {// fix 11 chiffres +511_AAA_BBBB
4332 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 8, 4);
4333 } elseif (dol_strlen($phone) == 12) {// mobile +51_AAA_BBB_CCC
4334 $newphonewa = $newphone;
4335 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 10, 3).$separ.substr($newphone, 14, 3);
4336 }
4337 }
4338
4339 $newphoneastart = $newphoneaend = '';
4340 if (!empty($addlink)) { // Link on phone number (+ link to add action if conf->global->AGENDA_ADDACTIONFORPHONE set)
4341 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
4342 $newphoneastart = '<a href="tel:'.urlencode($phone).'">';
4343 $newphoneaend .= '</a>';
4344 } elseif (isModEnabled('clicktodial') && $addlink == 'AC_TEL') { // If click to dial, we use click to dial url
4345 if (empty($user->clicktodial_loaded)) {
4346 $user->fetch_clicktodial();
4347 }
4348
4349 // Define urlmask
4350 $urlmask = getDolGlobalString('CLICKTODIAL_URL', 'ErrorClickToDialModuleNotConfigured');
4351 if (!empty($user->clicktodial_url)) {
4352 $urlmask = $user->clicktodial_url;
4353 }
4354
4355 $clicktodial_poste = (!empty($user->clicktodial_poste) ? urlencode($user->clicktodial_poste) : '');
4356 $clicktodial_login = (!empty($user->clicktodial_login) ? urlencode($user->clicktodial_login) : '');
4357 $clicktodial_password = (!empty($user->clicktodial_password) ? urlencode($user->clicktodial_password) : '');
4358 // This line is for backward compatibility @phan-suppress-next-line PhanPluginPrintfVariableFormatString
4359 $url = sprintf($urlmask, urlencode($phone), $clicktodial_poste, $clicktodial_login, $clicktodial_password);
4360 // Those lines are for substitution
4361 $substitarray = array('__PHONEFROM__' => $clicktodial_poste,
4362 '__PHONETO__' => urlencode($phone),
4363 '__LOGIN__' => $clicktodial_login,
4364 '__PASS__' => $clicktodial_password);
4365 $url = make_substitutions($url, $substitarray);
4366 if (!getDolGlobalString('CLICKTODIAL_DO_NOT_USE_AJAX_CALL')) {
4367 // Default and recommended: New method using ajax without submitting a page making a javascript history.go(-1) back
4368 $newphoneastart = '<a href="'.$url.'" class="cssforclicktodial">'; // Call of ajax is handled by the lib_foot.js.php on class 'cssforclicktodial'
4369 $newphoneaend = '</a>';
4370 } else {
4371 // Old method
4372 $newphoneastart = '<a href="'.$url.'"';
4373 if (getDolGlobalString('CLICKTODIAL_FORCENEWTARGET')) {
4374 $newphoneastart .= ' target="_blank" rel="noopener noreferrer"';
4375 }
4376 $newphoneastart .= '>';
4377 $newphoneaend .= '</a>';
4378 }
4379 }
4380
4381 //if (($cid || $socid) && isModEnabled('agenda') && $user->hasRight('agenda', 'myactions', 'create'))
4382 if (isModEnabled('agenda') && $user->hasRight("agenda", "myactions", "create")) {
4383 $type = 'AC_TEL';
4384 $addlinktoagenda = '';
4385 if ($addlink == 'AC_FAX') {
4386 $type = 'AC_FAX';
4387 }
4388 if (getDolGlobalString('AGENDA_ADDACTIONFORPHONE')) {
4389 $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>';
4390 }
4391 if ($addlinktoagenda) {
4392 $newphone = '<span>'.$newphone.' '.$addlinktoagenda.'</span>';
4393 }
4394 }
4395 }
4396
4397 if (getDolGlobalString('CONTACT_PHONEMOBILE_SHOW_LINK_TO_WHATSAPP') && $withpicto == 'mobile') {
4398 // Link to Whatsapp
4399 $newphone .= ' <a href="https://wa.me/'.$newphonewa.'" target="_blank"';// Use api to whatasapp contacts
4400 $newphone .= '><span class="paddingright fab fa-whatsapp" style="color:#25D366;" title="WhatsApp"></span></a>';
4401 }
4402
4403 if (empty($titlealt)) {
4404 $titlealt = ($withpicto == 'fax' ? $langs->trans("Fax") : $langs->trans("Phone"));
4405 }
4406 $rep = '';
4407
4408 if ($hookmanager) {
4409 $parameters = array('countrycode' => $countrycode, 'cid' => $cid, 'socid' => $socid, 'titlealt' => $titlealt, 'picto' => $withpicto);
4410 $reshook = $hookmanager->executeHooks('printPhone', $parameters, $phone);
4411 $rep .= $hookmanager->resPrint;
4412 }
4413 if (empty($reshook)) {
4414 $picto = '';
4415 if ($withpicto) {
4416 if ($withpicto == 'fax') {
4417 $picto = 'phoning_fax';
4418 } elseif ($withpicto == 'phone') {
4419 $picto = 'phoning';
4420 } elseif ($withpicto == 'mobile') {
4421 $picto = 'phoning_mobile';
4422 } else {
4423 $picto = '';
4424 }
4425 }
4426 if ($adddivfloat == 1) {
4427 $rep .= '<div class="nospan float'.($morecss ? ' '.$morecss : '').'">';
4428 } elseif (empty($adddivfloat)) {
4429 $rep .= '<span'.($morecss ? ' class="'.$morecss.'"' : '').'>';
4430 }
4431
4432 $rep .= $newphoneastart;
4433 $rep .= ($withpicto ? img_picto($titlealt, 'object_'.$picto.'.png') : '');
4434 if ($separ != 'hidenum') {
4435 $rep .= ($withpicto ? ' ' : '').$newphone;
4436 }
4437 $rep .= $newphoneaend;
4438
4439 if ($adddivfloat == 1) {
4440 $rep .= '</div>';
4441 } elseif (empty($adddivfloat)) {
4442 $rep .= '</span>';
4443 }
4444 }
4445
4446 return $rep;
4447}
4448
4456function dol_print_ip($ip, $mode = 0)
4457{
4458 global $langs;
4459
4460 $ret = '';
4461
4462 if (empty($mode)) {
4463 $ret .= $ip;
4464 }
4465
4466 if ($mode != 2) {
4467 $countrycode = dolGetCountryCodeFromIp($ip);
4468 if ($countrycode) { // If success, countrycode is us, fr, ...
4469 if (file_exists(DOL_DOCUMENT_ROOT.'/theme/common/flags/'.$countrycode.'.png')) {
4470 $ret .= ' '.img_picto($countrycode.' '.$langs->trans("AccordingToGeoIPDatabase"), DOL_URL_ROOT.'/theme/common/flags/'.$countrycode.'.png', '', 1);
4471 } else {
4472 $ret .= ' ('.$countrycode.')';
4473 }
4474 } else {
4475 // Nothing
4476 }
4477 }
4478
4479 return $ret;
4480}
4481
4490function getUserRemoteIP()
4491{
4492 if (empty($_SERVER['HTTP_X_FORWARDED_FOR']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {
4493 if (empty($_SERVER['HTTP_CLIENT_IP']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_CLIENT_IP'])) {
4494 if (empty($_SERVER["HTTP_CF_CONNECTING_IP"])) {
4495 $ip = (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']); // value may have been the IP of the proxy and not the client
4496 } else {
4497 $ip = $_SERVER["HTTP_CF_CONNECTING_IP"]; // value here may have been forged by client
4498 }
4499 } else {
4500 $ip = $_SERVER['HTTP_CLIENT_IP']; // value is clean here but may have been forged by proxy
4501 }
4502 } else {
4503 $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; // value is clean here but may have been forged by proxy
4504 }
4505 return $ip;
4506}
4507
4516function isHTTPS()
4517{
4518 $isSecure = false;
4519 if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
4520 $isSecure = true;
4521 } 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') {
4522 $isSecure = true;
4523 }
4524 return $isSecure;
4525}
4526
4533function dolGetCountryCodeFromIp($ip)
4534{
4535 global $conf;
4536
4537 $countrycode = '';
4538
4539 if (!empty($conf->geoipmaxmind->enabled)) {
4540 $datafile = getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE');
4541 //$ip='24.24.24.24';
4542 //$datafile='/usr/share/GeoIP/GeoIP.dat'; Note that this must be downloaded datafile (not same than datafile provided with ubuntu packages)
4543 include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
4544 $geoip = new DolGeoIP('country', $datafile);
4545 //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
4546 $countrycode = $geoip->getCountryCodeFromIP($ip);
4547 }
4548
4549 return $countrycode;
4550}
4551
4552
4559function dol_user_country()
4560{
4561 global $conf, $langs, $user;
4562
4563 //$ret=$user->xxx;
4564 $ret = '';
4565 if (!empty($conf->geoipmaxmind->enabled)) {
4566 $ip = getUserRemoteIP();
4567 $datafile = getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE');
4568 //$ip='24.24.24.24';
4569 //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';
4570 include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
4571 $geoip = new DolGeoIP('country', $datafile);
4572 $countrycode = $geoip->getCountryCodeFromIP($ip);
4573 $ret = $countrycode;
4574 }
4575 return $ret;
4576}
4577
4590function dol_print_address($address, $htmlid, $element, $id, $noprint = 0, $charfornl = '')
4591{
4592 global $conf, $user, $langs, $hookmanager;
4593
4594 $out = '';
4595
4596 if ($address) {
4597 if ($hookmanager) {
4598 $parameters = array('element' => $element, 'id' => $id);
4599 $reshook = $hookmanager->executeHooks('printAddress', $parameters, $address);
4600 $out .= $hookmanager->resPrint;
4601 }
4602 if (empty($reshook)) {
4603 if (empty($charfornl)) {
4604 $out .= nl2br($address);
4605 } else {
4606 $out .= preg_replace('/[\r\n]+/', $charfornl, $address);
4607 }
4608
4609 // TODO Remove this block, we can add this using the hook now
4610 $showgmap = $showomap = 0;
4611 if (($element == 'thirdparty' || $element == 'societe') && isModEnabled('google') && getDolGlobalString('GOOGLE_ENABLE_GMAPS')) {
4612 $showgmap = 1;
4613 }
4614 if ($element == 'contact' && isModEnabled('google') && getDolGlobalString('GOOGLE_ENABLE_GMAPS_CONTACTS')) {
4615 $showgmap = 1;
4616 }
4617 if ($element == 'member' && isModEnabled('google') && getDolGlobalString('GOOGLE_ENABLE_GMAPS_MEMBERS')) {
4618 $showgmap = 1;
4619 }
4620 if ($element == 'user' && isModEnabled('google') && getDolGlobalString('GOOGLE_ENABLE_GMAPS_USERS')) {
4621 $showgmap = 1;
4622 }
4623 if (($element == 'thirdparty' || $element == 'societe') && isModEnabled('openstreetmap') && getDolGlobalString('OPENSTREETMAP_ENABLE_MAPS')) {
4624 $showomap = 1;
4625 }
4626 if ($element == 'contact' && isModEnabled('openstreetmap') && getDolGlobalString('OPENSTREETMAP_ENABLE_MAPS_CONTACTS')) {
4627 $showomap = 1;
4628 }
4629 if ($element == 'member' && isModEnabled('openstreetmap') && getDolGlobalString('OPENSTREETMAP_ENABLE_MAPS_MEMBERS')) {
4630 $showomap = 1;
4631 }
4632 if ($element == 'user' && isModEnabled('openstreetmap') && getDolGlobalString('OPENSTREETMAP_ENABLE_MAPS_USERS')) {
4633 $showomap = 1;
4634 }
4635 if ($showgmap) {
4636 $url = dol_buildpath('/google/gmaps.php?mode='.$element.'&id='.$id, 1);
4637 $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
4638 }
4639 if ($showomap) {
4640 $url = dol_buildpath('/openstreetmap/maps.php?mode='.$element.'&id='.$id, 1);
4641 $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'_openstreetmap" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
4642 }
4643 }
4644 }
4645 if ($noprint) {
4646 return $out;
4647 } else {
4648 print $out;
4649 return null;
4650 }
4651}
4652
4653
4663function isValidEmail($address, $acceptsupervisorkey = 0, $acceptuserkey = 0)
4664{
4665 if ($acceptsupervisorkey && $address == '__SUPERVISOREMAIL__') {
4666 return true;
4667 }
4668 if ($acceptuserkey && $address == '__USER_EMAIL__') {
4669 return true;
4670 }
4671 if (filter_var($address, FILTER_VALIDATE_EMAIL)) {
4672 return true;
4673 }
4674
4675 return false;
4676}
4677
4687function isValidMXRecord($domain)
4688{
4689 if (function_exists('idn_to_ascii') && function_exists('checkdnsrr')) {
4690 if (!checkdnsrr(idn_to_ascii($domain), 'MX')) {
4691 return 0;
4692 }
4693 if (function_exists('getmxrr')) {
4694 $mxhosts = array();
4695 $weight = array();
4696 getmxrr(idn_to_ascii($domain), $mxhosts, $weight);
4697 if (count($mxhosts) > 1) {
4698 return 1;
4699 }
4700 if (count($mxhosts) == 1 && !in_array((string) $mxhosts[0], array('', '.'))) {
4701 return 1;
4702 }
4703
4704 return 0;
4705 }
4706 }
4707
4708 // function idn_to_ascii or checkdnsrr or getmxrr does not exists
4709 return -1;
4710}
4711
4719function isValidPhone($phone)
4720{
4721 return true;
4722}
4723
4724
4734function dolGetFirstLetters($s, $nbofchar = 1)
4735{
4736 $ret = '';
4737 $tmparray = explode(' ', $s);
4738 foreach ($tmparray as $tmps) {
4739 $ret .= dol_substr($tmps, 0, $nbofchar);
4740 }
4741
4742 return $ret;
4743}
4744
4745
4753function dol_strlen($string, $stringencoding = 'UTF-8')
4754{
4755 if (is_null($string)) {
4756 return 0;
4757 }
4758
4759 if (function_exists('mb_strlen')) {
4760 return mb_strlen($string, $stringencoding);
4761 } else {
4762 return strlen($string);
4763 }
4764}
4765
4776function dol_substr($string, $start, $length = null, $stringencoding = '', $trunconbytes = 0)
4777{
4778 global $langs;
4779
4780 if (empty($stringencoding)) {
4781 $stringencoding = (empty($langs) ? 'UTF-8' : $langs->charset_output);
4782 }
4783
4784 $ret = '';
4785 if (empty($trunconbytes)) {
4786 if (function_exists('mb_substr')) {
4787 $ret = mb_substr($string, $start, $length, $stringencoding);
4788 } else {
4789 $ret = substr($string, $start, $length);
4790 }
4791 } else {
4792 if (function_exists('mb_strcut')) {
4793 $ret = mb_strcut($string, $start, $length, $stringencoding);
4794 } else {
4795 $ret = substr($string, $start, $length);
4796 }
4797 }
4798 return $ret;
4799}
4800
4801
4815function dol_trunc($string, $size = 40, $trunc = 'right', $stringencoding = 'UTF-8', $nodot = 0, $display = 0)
4816{
4817 global $conf;
4818
4819 if (empty($size) || getDolGlobalString('MAIN_DISABLE_TRUNC')) {
4820 return $string;
4821 }
4822
4823 if (empty($stringencoding)) {
4824 $stringencoding = 'UTF-8';
4825 }
4826 // reduce for small screen
4827 if (!empty($conf->dol_optimize_smallscreen) && $conf->dol_optimize_smallscreen == 1 && $display == 1) {
4828 $size = round($size / 3);
4829 }
4830
4831 // We go always here
4832 if ($trunc == 'right') {
4833 $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
4834 if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
4835 // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
4836 return dol_substr($newstring, 0, $size, $stringencoding).($nodot ? '' : '…');
4837 } else {
4838 //return 'u'.$size.'-'.$newstring.'-'.dol_strlen($newstring,$stringencoding).'-'.$string;
4839 return $string;
4840 }
4841 } elseif ($trunc == 'middle') {
4842 $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
4843 if (dol_strlen($newstring, $stringencoding) > 2 && dol_strlen($newstring, $stringencoding) > ($size + 1)) {
4844 $size1 = round($size / 2);
4845 $size2 = round($size / 2);
4846 return dol_substr($newstring, 0, $size1, $stringencoding).'…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size2, $size2, $stringencoding);
4847 } else {
4848 return $string;
4849 }
4850 } elseif ($trunc == 'left') {
4851 $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
4852 if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
4853 // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
4854 return '…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size, $size, $stringencoding);
4855 } else {
4856 return $string;
4857 }
4858 } elseif ($trunc == 'wrap') {
4859 $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
4860 if (dol_strlen($newstring, $stringencoding) > ($size + 1)) {
4861 return dol_substr($newstring, 0, $size, $stringencoding)."\n".dol_trunc(dol_substr($newstring, $size, dol_strlen($newstring, $stringencoding) - $size, $stringencoding), $size, $trunc);
4862 } else {
4863 return $string;
4864 }
4865 } else {
4866 return 'BadParam3CallingDolTrunc';
4867 }
4868}
4869
4877function getPictoForType($key, $morecss = '')
4878{
4879 // Set array with type -> picto
4880 $type2picto = array(
4881 'varchar' => 'font',
4882 'text' => 'font',
4883 'html' => 'code',
4884 'int' => 'sort-numeric-down',
4885 'double' => 'sort-numeric-down',
4886 'price' => 'currency',
4887 'pricecy' => 'multicurrency',
4888 'password' => 'key',
4889 'boolean' => 'check-square',
4890 'date' => 'calendar',
4891 'datetime' => 'calendar',
4892 'phone' => 'phone',
4893 'mail' => 'email',
4894 'url' => 'url',
4895 'ip' => 'country',
4896 'select' => 'list',
4897 'sellist' => 'list',
4898 'radio' => 'check-circle',
4899 'checkbox' => 'list',
4900 'chkbxlst' => 'list',
4901 'link' => 'link',
4902 'icon' => "question",
4903 'point' => "country",
4904 'multipts' => 'country',
4905 'linestrg' => "country",
4906 'polygon' => "country",
4907 'separate' => 'minus'
4908 );
4909
4910 if (!empty($type2picto[$key])) {
4911 return img_picto('', $type2picto[$key], 'class="pictofixedwidth'.($morecss ? ' '.$morecss : '').'"');
4912 }
4913
4914 return img_picto('', 'generic', 'class="pictofixedwidth'.($morecss ? ' '.$morecss : '').'"');
4915}
4916
4917
4939function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $srconly = 0, $notitle = 0, $alt = '', $morecss = '', $marginleftonlyshort = 2)
4940{
4941 global $conf;
4942
4943 // We forge fullpathpicto for image to $path/img/$picto. By default, we take DOL_URL_ROOT/theme/$conf->theme/img/$picto
4944 $url = DOL_URL_ROOT;
4945 $theme = isset($conf->theme) ? $conf->theme : null;
4946 $path = 'theme/'.$theme;
4947 if (empty($picto)) {
4948 $picto = 'generic';
4949 }
4950
4951 // Define fullpathpicto to use into src
4952 if ($pictoisfullpath) {
4953 // Clean parameters
4954 if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
4955 $picto .= '.png';
4956 }
4957 $fullpathpicto = $picto;
4958 $reg = array();
4959 if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
4960 $morecss .= ($morecss ? ' ' : '').$reg[1];
4961 $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
4962 }
4963 } else {
4964 // $picto can not be null since replaced with 'generic' in that case
4965 //$pictowithouttext = preg_replace('/(\.png|\.gif|\.svg)$/', '', (is_null($picto) ? '' : $picto));
4966 $pictowithouttext = preg_replace('/(\.png|\.gif|\.svg)$/', '', $picto);
4967 $pictowithouttext = str_replace('object_', '', $pictowithouttext);
4968 $pictowithouttext = str_replace('_nocolor', '', $pictowithouttext);
4969
4970 // Fix some values of $pictowithouttext
4971 $pictoconvertkey = array('facture' => 'bill', 'shipping' => 'shipment', 'fichinter' => 'intervention', 'agenda' => 'calendar', 'invoice_supplier' => 'supplier_invoice', 'order_supplier' => 'supplier_order');
4972 if (in_array($pictowithouttext, array_keys($pictoconvertkey))) {
4973 $pictowithouttext = $pictoconvertkey[$pictowithouttext];
4974 }
4975
4976 if (strpos($pictowithouttext, 'fontawesome_') === 0 || strpos($pictowithouttext, 'fa-') === 0) {
4977 // This is a font awesome image 'fontawesome_xxx' or 'fa-xxx'
4978 $pictowithouttext = str_replace('fontawesome_', '', $pictowithouttext);
4979 $pictowithouttext = str_replace('fa-', '', $pictowithouttext);
4980
4981 // Compatibility with old fontawesome versions
4982 if ($pictowithouttext == 'file-o') {
4983 $pictowithouttext = 'file';
4984 }
4985
4986 $pictowithouttextarray = explode('_', $pictowithouttext);
4987 $marginleftonlyshort = 0;
4988
4989 if (!empty($pictowithouttextarray[1])) {
4990 // Syntax is 'fontawesome_fakey_faprefix_facolor_fasize' or 'fa-fakey_faprefix_facolor_fasize'
4991 $fakey = 'fa-'.$pictowithouttextarray[0];
4992 $faprefix = empty($pictowithouttextarray[1]) ? 'fas' : $pictowithouttextarray[1];
4993 $facolor = empty($pictowithouttextarray[2]) ? '' : $pictowithouttextarray[2];
4994 $fasize = empty($pictowithouttextarray[3]) ? '' : $pictowithouttextarray[3];
4995 } else {
4996 $fakey = 'fa-'.$pictowithouttext;
4997 $faprefix = 'fas';
4998 $facolor = '';
4999 $fasize = '';
5000 }
5001
5002 // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
5003 // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
5004 $morestyle = '';
5005 $reg = array();
5006 if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
5007 $morecss .= ($morecss ? ' ' : '').$reg[1];
5008 $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
5009 }
5010 if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
5011 $morestyle = $reg[1];
5012 $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt);
5013 }
5014 $moreatt = trim($moreatt);
5015
5016 $enabledisablehtml = '<span class="'.$faprefix.' '.$fakey.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
5017 $enabledisablehtml .= ($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').($morestyle ? ' '.$morestyle : '').'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : '').'>';
5018 /*if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
5019 $enabledisablehtml .= $titlealt;
5020 }*/
5021 $enabledisablehtml .= '</span>';
5022
5023 return $enabledisablehtml;
5024 }
5025
5026 if (empty($srconly) && in_array($pictowithouttext, array(
5027 '1downarrow', '1uparrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected',
5028 'accountancy', 'accounting_account', 'account', 'accountline', 'action', 'add', 'address', 'ai', 'angle-double-down', 'angle-double-up', 'asset',
5029 'bank_account', 'barcode', 'bank', 'bell', 'bill', 'billa', 'billr', 'billd', 'birthday-cake', 'bom', 'bookcal', 'bookmark', 'briefcase-medical', 'bug', 'building',
5030 'card', 'calendarlist', 'calendar', 'calendarmonth', 'calendarweek', 'calendarday', 'calendarperuser', 'calendarpertype',
5031 'cash-register', 'category', 'chart', 'check', 'clock', 'clone', 'close_title', 'code', 'cog', 'collab', 'company', 'contact', 'country', 'contract', 'conversation', 'cron', 'cross', 'cubes',
5032 'check-circle', 'check-square', 'circle', 'stop-circle', 'currency', 'multicurrency',
5033 'chevron-left', 'chevron-right', 'chevron-down', 'chevron-top',
5034 'chevron-double-left', 'chevron-double-right', 'chevron-double-down', 'chevron-double-top',
5035 'commercial', 'companies',
5036 'delete', 'dolly', 'dollyrevert', 'donation', 'download', 'dynamicprice',
5037 'edit', 'ellipsis-h', 'email', 'entity', 'envelope', 'eraser', 'establishment', 'expensereport', 'external-link-alt', 'external-link-square-alt', 'eye',
5038 'filter', 'file', 'file-o', 'file-code', 'file-export', 'file-import', 'file-upload', 'autofill', 'folder', 'folder-open', 'folder-plus', 'font',
5039 'gears', 'generate', 'generic', 'globe', 'globe-americas', 'graph', 'grip', 'grip_title', 'group',
5040 'hands-helping', 'help', 'holiday',
5041 'id-card', 'images', 'incoterm', 'info', 'intervention', 'inventory', 'intracommreport', 'jobprofile',
5042 'key', 'knowledgemanagement',
5043 'label', 'language', 'layout', 'line', 'link', 'list', 'list-alt', 'listlight', 'loan', 'lock', 'lot', 'long-arrow-alt-right',
5044 'margin', 'map-marker-alt', 'member', 'meeting', 'minus', 'money-bill-alt', 'movement', 'mrp', 'note', 'next',
5045 'off', 'on', 'order',
5046 'paiment', 'paragraph', 'play', 'pdf', 'phone', 'phoning', 'phoning_mobile', 'phoning_fax', 'playdisabled', 'previous', 'poll', 'pos', 'printer', 'product', 'propal', 'proposal', 'puce',
5047 'stock', 'resize', 'service', 'stats',
5048 'security', 'setup', 'share-alt', 'sign-out', 'split', 'stripe', 'stripe-s', 'switch_off', 'switch_on', 'switch_on_grey', 'switch_on_warning', 'switch_on_red', 'tools', 'unlink', 'uparrow', 'user', 'user-tie', 'vcard', 'wrench',
5049 'github', 'google', 'jabber', 'microsoft', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'youtube', 'google-plus-g', 'whatsapp',
5050 'generic', 'home', 'hrm', 'members', 'products', 'invoicing',
5051 'partnership', 'payment', 'payment_vat', 'pencil-ruler', 'pictoconfirm', 'preview', 'project', 'projectpub', 'projecttask', 'question', 'refresh', 'region',
5052 'salary', 'shipment', 'state', 'supplier_invoice', 'supplier_invoicea', 'supplier_invoicer', 'supplier_invoiced',
5053 'technic', 'ticket',
5054 'error', 'warning',
5055 'recent', 'reception', 'recruitmentcandidature', 'recruitmentjobposition', 'replacement', 'resource', 'recurring','rss',
5056 'shapes', 'skill', 'square', 'sort-numeric-down', 'status', 'stop-circle', 'supplier', 'supplier_proposal', 'supplier_order', 'supplier_invoice',
5057 'terminal', 'tick', 'timespent', 'title_setup', 'title_accountancy', 'title_bank', 'title_hrm', 'title_agenda', 'trip',
5058 'uncheck', 'undo', 'url', 'user-cog', 'user-injured', 'user-md', 'vat', 'website', 'workstation', 'webhook', 'world', 'private',
5059 'conferenceorbooth', 'eventorganization',
5060 'stamp', 'signature',
5061 'webportal'
5062 ))) {
5063 $fakey = $pictowithouttext;
5064 $facolor = '';
5065 $fasize = '';
5066 $fa = getDolGlobalString('MAIN_FONTAWESOME_ICON_STYLE', 'fas');
5067 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'))) {
5068 $fa = 'far';
5069 }
5070 if (in_array($pictowithouttext, array('black-tie', 'github', 'google', 'microsoft', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'stripe', 'stripe-s', 'youtube', 'google-plus-g', 'whatsapp'))) {
5071 $fa = 'fab';
5072 }
5073
5074 $arrayconvpictotofa = array(
5075 'account' => 'university', 'accounting_account' => 'clipboard-list', 'accountline' => 'receipt', 'accountancy' => 'search-dollar', 'action' => 'calendar-alt', 'add' => 'plus-circle', 'address' => 'address-book', 'ai' => 'magic',
5076 'asset' => 'money-check-alt', 'autofill' => 'fill',
5077 'bank_account' => 'university',
5078 'bill' => 'file-invoice-dollar', 'billa' => 'file-excel', 'billr' => 'file-invoice-dollar', 'billd' => 'file-medical',
5079 'bookcal' => 'calendar-check',
5080 'supplier_invoice' => 'file-invoice-dollar', 'supplier_invoicea' => 'file-excel', 'supplier_invoicer' => 'file-invoice-dollar', 'supplier_invoiced' => 'file-medical',
5081 'bom' => 'shapes',
5082 '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',
5083 'chevron-double-left' => 'angle-double-left', 'chevron-double-right' => 'angle-double-right', 'chevron-double-down' => 'angle-double-down', 'chevron-double-top' => 'angle-double-up',
5084 'donation' => 'file-alt', 'dynamicprice' => 'hand-holding-usd',
5085 'setup' => 'cog', 'companies' => 'building', 'products' => 'cube', 'commercial' => 'suitcase', 'invoicing' => 'coins',
5086 'accounting' => 'search-dollar', 'category' => 'tag', 'dollyrevert' => 'dolly',
5087 'file-o' => 'file', 'generate' => 'plus-square', 'hrm' => 'user-tie', 'incoterm' => 'truck-loading',
5088 'margin' => 'calculator', 'members' => 'user-friends', 'ticket' => 'ticket-alt', 'globe' => 'external-link-alt', 'lot' => 'barcode',
5089 'email' => 'at', 'establishment' => 'building', 'edit' => 'pencil-alt', 'entity' => 'globe',
5090 'graph' => 'chart-line', 'grip_title' => 'arrows-alt', 'grip' => 'arrows-alt', 'help' => 'question-circle',
5091 'generic' => 'file', 'holiday' => 'umbrella-beach',
5092 'info' => 'info-circle', 'inventory' => 'boxes', 'intracommreport' => 'globe-europe', 'jobprofile' => 'cogs',
5093 'knowledgemanagement' => 'ticket-alt', 'label' => 'layer-group', 'layout' => 'columns', 'line' => 'bars', 'loan' => 'money-bill-alt',
5094 'member' => 'user-alt', 'meeting' => 'chalkboard-teacher', 'mrp' => 'cubes', 'next' => 'arrow-alt-circle-right',
5095 'trip' => 'wallet', 'expensereport' => 'wallet', 'group' => 'users', 'movement' => 'people-carry',
5096 'sign-out' => 'sign-out-alt',
5097 'switch_off' => 'toggle-off', 'switch_on' => 'toggle-on', 'switch_on_grey' => 'toggle-on', 'switch_on_warning' => 'toggle-on', 'switch_on_red' => 'toggle-on', 'check' => 'check', 'bookmark' => 'star',
5098 'bank' => 'university', 'close_title' => 'times', 'delete' => 'trash', 'filter' => 'filter',
5099 'list-alt' => 'list-alt', 'calendarlist' => 'bars', 'calendar' => 'calendar-alt', 'calendarmonth' => 'calendar-alt', 'calendarweek' => 'calendar-week', 'calendarday' => 'calendar-day', 'calendarperuser' => 'table',
5100 'intervention' => 'ambulance', 'invoice' => 'file-invoice-dollar', 'order' => 'file-invoice',
5101 'error' => 'exclamation-triangle', 'warning' => 'exclamation-triangle',
5102 'other' => 'square',
5103 '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',
5104 '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',
5105 'recent' => 'check-square', 'reception' => 'dolly', 'recruitmentjobposition' => 'id-card-alt', 'recruitmentcandidature' => 'id-badge',
5106 'resize' => 'crop', 'supplier_order' => 'dol-order_supplier', 'supplier_proposal' => 'file-signature',
5107 'refresh' => 'redo', 'region' => 'map-marked', 'replacement' => 'exchange-alt', 'resource' => 'laptop-house', 'recurring' => 'history',
5108 'service' => 'concierge-bell',
5109 'skill' => 'shapes', 'state' => 'map-marked-alt', 'security' => 'key', 'salary' => 'wallet', 'shipment' => 'dolly', 'stock' => 'box-open', 'stats' => 'chart-bar', 'split' => 'code-branch',
5110 'status' => 'stop-circle',
5111 'stripe' => 'stripe-s', 'supplier' => 'building',
5112 'technic' => 'cogs', 'tick' => 'check', 'timespent' => 'clock', 'title_setup' => 'tools', 'title_accountancy' => 'money-check-alt', 'title_bank' => 'university', 'title_hrm' => 'umbrella-beach',
5113 'title_agenda' => 'calendar-alt',
5114 'uncheck' => 'times', 'uparrow' => 'share', 'url' => 'external-link-alt', 'vat' => 'money-check-alt', 'vcard' => 'arrow-alt-circle-down',
5115 'jabber' => 'comment-o',
5116 'website' => 'globe-americas', 'workstation' => 'pallet', 'webhook' => 'bullseye', 'world' => 'globe', 'private' => 'user-lock',
5117 'conferenceorbooth' => 'chalkboard-teacher', 'eventorganization' => 'project-diagram',
5118 'webportal' => 'door-open'
5119 );
5120 if ($conf->currency == 'EUR') {
5121 $arrayconvpictotofa['currency'] = 'euro-sign';
5122 $arrayconvpictotofa['multicurrency'] = 'dollar-sign';
5123 } else {
5124 $arrayconvpictotofa['currency'] = 'dollar-sign';
5125 $arrayconvpictotofa['multicurrency'] = 'euro-sign';
5126 }
5127 if ($pictowithouttext == 'off') {
5128 $fakey = 'fa-square';
5129 $fasize = '1.3em';
5130 } elseif ($pictowithouttext == 'on') {
5131 $fakey = 'fa-check-square';
5132 $fasize = '1.3em';
5133 } elseif ($pictowithouttext == 'listlight') {
5134 $fakey = 'fa-download';
5135 $marginleftonlyshort = 1;
5136 } elseif ($pictowithouttext == 'printer') {
5137 $fakey = 'fa-print';
5138 $fasize = '1.2em';
5139 } elseif ($pictowithouttext == 'note') {
5140 $fakey = 'fa-sticky-note';
5141 $marginleftonlyshort = 1;
5142 } elseif (in_array($pictowithouttext, array('1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'))) {
5143 $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');
5144 $fakey = 'fa-'.$convertarray[$pictowithouttext];
5145 if (preg_match('/selected/', $pictowithouttext)) {
5146 $facolor = '#888';
5147 }
5148 $marginleftonlyshort = 1;
5149 } elseif (!empty($arrayconvpictotofa[$pictowithouttext])) {
5150 $fakey = 'fa-'.$arrayconvpictotofa[$pictowithouttext];
5151 } else {
5152 $fakey = 'fa-'.$pictowithouttext;
5153 }
5154
5155 if (in_array($pictowithouttext, array('dollyrevert', 'member', 'members', 'contract', 'group', 'resource', 'shipment', 'reception'))) {
5156 $morecss .= ' em092';
5157 }
5158 if (in_array($pictowithouttext, array('conferenceorbooth', 'collab', 'eventorganization', 'holiday', 'info', 'project', 'workstation'))) {
5159 $morecss .= ' em088';
5160 }
5161 if (in_array($pictowithouttext, array('asset', 'intervention', 'payment', 'loan', 'partnership', 'stock', 'technic'))) {
5162 $morecss .= ' em080';
5163 }
5164
5165 // Define $marginleftonlyshort
5166 $arrayconvpictotomarginleftonly = array(
5167 'bank', 'check', 'delete', 'generic', 'grip', 'grip_title', 'jabber',
5168 'grip_title', 'grip', 'listlight', 'note', 'on', 'off', 'playdisabled', 'printer', 'resize', 'sign-out', 'stats', 'switch_on', 'switch_on_grey', 'switch_on_red', 'switch_off',
5169 'uparrow', '1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'
5170 );
5171 if (!array_key_exists($pictowithouttext, $arrayconvpictotomarginleftonly)) {
5172 $marginleftonlyshort = 0;
5173 }
5174
5175 // Add CSS
5176 $arrayconvpictotomorcess = array(
5177 'action' => 'infobox-action', 'account' => 'infobox-bank_account', 'accounting_account' => 'infobox-bank_account', 'accountline' => 'infobox-bank_account', 'accountancy' => 'infobox-bank_account', 'asset' => 'infobox-bank_account',
5178 'bank_account' => 'infobox-bank_account',
5179 'bill' => 'infobox-commande', 'billa' => 'infobox-commande', 'billr' => 'infobox-commande', 'billd' => 'infobox-commande',
5180 'bookcal' => 'infobox-action',
5181 'margin' => 'infobox-bank_account', 'conferenceorbooth' => 'infobox-project',
5182 'cash-register' => 'infobox-bank_account', 'contract' => 'infobox-contrat', 'check' => 'font-status4', 'collab' => 'infobox-action', 'conversation' => 'infobox-contrat',
5183 'donation' => 'infobox-commande', 'dolly' => 'infobox-commande', 'dollyrevert' => 'flip infobox-order_supplier',
5184 'ecm' => 'infobox-action', 'eventorganization' => 'infobox-project',
5185 'hrm' => 'infobox-adherent', 'group' => 'infobox-adherent', 'intervention' => 'infobox-contrat',
5186 'incoterm' => 'infobox-supplier_proposal',
5187 'currency' => 'infobox-bank_account', 'multicurrency' => 'infobox-bank_account',
5188 'members' => 'infobox-adherent', 'member' => 'infobox-adherent', 'money-bill-alt' => 'infobox-bank_account',
5189 'order' => 'infobox-commande',
5190 'user' => 'infobox-adherent', 'users' => 'infobox-adherent',
5191 'error' => 'pictoerror', 'warning' => 'pictowarning', 'switch_on' => 'font-status4', 'switch_on_warning' => 'font-status4 warning', 'switch_on_red' => 'font-status8',
5192 'holiday' => 'infobox-holiday', 'info' => 'opacityhigh', 'invoice' => 'infobox-commande',
5193 'knowledgemanagement' => 'infobox-contrat rotate90', 'loan' => 'infobox-bank_account',
5194 'payment' => 'infobox-bank_account', 'payment_vat' => 'infobox-bank_account', 'poll' => 'infobox-adherent', 'pos' => 'infobox-bank_account', 'project' => 'infobox-project', 'projecttask' => 'infobox-project',
5195 'propal' => 'infobox-propal', 'proposal' => 'infobox-propal','private' => 'infobox-project',
5196 'reception' => 'flip infobox-order_supplier', 'recruitmentjobposition' => 'infobox-adherent', 'recruitmentcandidature' => 'infobox-adherent',
5197 'resource' => 'infobox-action',
5198 'salary' => 'infobox-bank_account', 'shapes' => 'infobox-adherent', 'shipment' => 'infobox-commande', 'stripe' => 'infobox-bank_account', 'supplier_invoice' => 'infobox-order_supplier', 'supplier_invoicea' => 'infobox-order_supplier', 'supplier_invoiced' => 'infobox-order_supplier',
5199 'supplier' => 'infobox-order_supplier', 'supplier_order' => 'infobox-order_supplier', 'supplier_proposal' => 'infobox-supplier_proposal',
5200 'ticket' => 'infobox-contrat', 'title_accountancy' => 'infobox-bank_account', 'title_hrm' => 'infobox-holiday', 'expensereport' => 'infobox-expensereport', 'trip' => 'infobox-expensereport', 'title_agenda' => 'infobox-action',
5201 'vat' => 'infobox-bank_account',
5202 //'title_setup'=>'infobox-action', 'tools'=>'infobox-action',
5203 'list-alt' => 'imgforviewmode', 'calendar' => 'imgforviewmode', 'calendarweek' => 'imgforviewmode', 'calendarmonth' => 'imgforviewmode', 'calendarday' => 'imgforviewmode', 'calendarperuser' => 'imgforviewmode'
5204 );
5205 if (!empty($arrayconvpictotomorcess[$pictowithouttext]) && strpos($picto, '_nocolor') === false) {
5206 $morecss .= ($morecss ? ' ' : '').$arrayconvpictotomorcess[$pictowithouttext];
5207 }
5208
5209 // Define $color
5210 $arrayconvpictotocolor = array(
5211 'address' => '#6c6aa8', 'building' => '#6c6aa8', 'bom' => '#a69944',
5212 'clone' => '#999', 'cog' => '#999', 'companies' => '#6c6aa8', 'company' => '#6c6aa8', 'contact' => '#6c6aa8', 'cron' => '#555',
5213 'dynamicprice' => '#a69944',
5214 'edit' => '#444', 'note' => '#999', 'error' => '', 'help' => '#bbb', 'listlight' => '#999', 'language' => '#555',
5215 //'dolly'=>'#a69944', 'dollyrevert'=>'#a69944',
5216 'lock' => '#ddd', 'lot' => '#a69944',
5217 'map-marker-alt' => '#aaa', 'mrp' => '#a69944', 'product' => '#a69944', 'service' => '#a69944', 'inventory' => '#a69944', 'stock' => '#a69944', 'movement' => '#a69944',
5218 'other' => '#ddd', 'world' => '#986c6a',
5219 'partnership' => '#6c6aa8', 'playdisabled' => '#ccc', 'printer' => '#444', 'projectpub' => '#986c6a', 'resize' => '#444', 'rss' => '#cba',
5220 //'shipment'=>'#a69944',
5221 'security' => '#999', 'square' => '#888', 'stop-circle' => '#888', 'stats' => '#444', 'switch_off' => '#999',
5222 'technic' => '#999', 'tick' => '#282', 'timespent' => '#555',
5223 'uncheck' => '#800', 'uparrow' => '#555', 'user-cog' => '#999', 'country' => '#aaa', 'globe-americas' => '#aaa', 'region' => '#aaa', 'state' => '#aaa',
5224 'website' => '#304', 'workstation' => '#a69944'
5225 );
5226 if (isset($arrayconvpictotocolor[$pictowithouttext]) && strpos($picto, '_nocolor') === false) {
5227 $facolor = $arrayconvpictotocolor[$pictowithouttext];
5228 }
5229
5230 // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
5231 // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
5232 $morestyle = '';
5233 $reg = array();
5234 if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
5235 $morecss .= ($morecss ? ' ' : '').$reg[1];
5236 $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
5237 }
5238 if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
5239 $morestyle = $reg[1];
5240 $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt);
5241 }
5242 $moreatt = trim($moreatt);
5243
5244 $enabledisablehtml = '<span class="'.$fa.' '.$fakey.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
5245 $enabledisablehtml .= ($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').($morestyle ? ' '.$morestyle : '').'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : '').'>';
5246 /*if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
5247 $enabledisablehtml .= $titlealt;
5248 }*/
5249 $enabledisablehtml .= '</span>';
5250
5251 return $enabledisablehtml;
5252 }
5253
5254 if (getDolGlobalString('MAIN_OVERWRITE_THEME_PATH')) {
5255 $path = getDolGlobalString('MAIN_OVERWRITE_THEME_PATH') . '/theme/'.$theme; // If the theme does not have the same name as the module
5256 } elseif (getDolGlobalString('MAIN_OVERWRITE_THEME_RES')) {
5257 $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
5258 } elseif (!empty($conf->modules_parts['theme']) && array_key_exists($theme, $conf->modules_parts['theme'])) {
5259 $path = $theme.'/theme/'.$theme; // If the theme have the same name as the module
5260 }
5261
5262 // If we ask an image into $url/$mymodule/img (instead of default path)
5263 $regs = array();
5264 if (preg_match('/^([^@]+)@([^@]+)$/i', $picto, $regs)) {
5265 $picto = $regs[1];
5266 $path = $regs[2]; // $path is $mymodule
5267 }
5268
5269 // Clean parameters
5270 if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
5271 $picto .= '.png';
5272 }
5273 // If alt path are defined, define url where img file is, according to physical path
5274 // ex: array(["main"]=>"/home/maindir/htdocs", ["alt0"]=>"/home/moddir0/htdocs", ...)
5275 foreach ($conf->file->dol_document_root as $type => $dirroot) {
5276 if ($type == 'main') {
5277 continue;
5278 }
5279 // This need a lot of time, that's why enabling alternative dir like "custom" dir is not recommended
5280 if (file_exists($dirroot.'/'.$path.'/img/'.$picto)) {
5281 $url = DOL_URL_ROOT.$conf->file->dol_url_root[$type];
5282 break;
5283 }
5284 }
5285
5286 // $url is '' or '/custom', $path is current theme or
5287 $fullpathpicto = $url.'/'.$path.'/img/'.$picto;
5288 }
5289
5290 if ($srconly) {
5291 return $fullpathpicto;
5292 }
5293
5294 // tag title is used for tooltip on <a>, tag alt can be used with very simple text on image for blind people
5295 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
5296}
5297
5311function img_object($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $srconly = 0, $notitle = 0)
5312{
5313 if (strpos($picto, '^') === 0) {
5314 return img_picto($titlealt, str_replace('^', '', $picto), $moreatt, $pictoisfullpath, $srconly, $notitle);
5315 } else {
5316 return img_picto($titlealt, 'object_'.$picto, $moreatt, $pictoisfullpath, $srconly, $notitle);
5317 }
5318}
5319
5331function img_weather($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $morecss = '')
5332{
5333 global $conf;
5334
5335 if (is_numeric($picto)) {
5336 //$leveltopicto = array(0=>'weather-clear.png', 1=>'weather-few-clouds.png', 2=>'weather-clouds.png', 3=>'weather-many-clouds.png', 4=>'weather-storm.png');
5337 //$picto = $leveltopicto[$picto];
5338 return '<i class="fa fa-weather-level'.$picto.'"></i>';
5339 } elseif (!preg_match('/(\.png|\.gif)$/i', $picto)) {
5340 $picto .= '.png';
5341 }
5342
5343 $path = DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/weather/'.$picto;
5344
5345 return img_picto($titlealt, $path, $moreatt, 1, 0, 0, '', $morecss);
5346}
5347
5359function img_picto_common($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $notitle = 0)
5360{
5361 global $conf;
5362
5363 if (!preg_match('/(\.png|\.gif)$/i', $picto)) {
5364 $picto .= '.png';
5365 }
5366
5367 if ($pictoisfullpath) {
5368 $path = $picto;
5369 } else {
5370 $path = DOL_URL_ROOT.'/theme/common/'.$picto;
5371
5372 if (getDolGlobalInt('MAIN_MODULE_CAN_OVERWRITE_COMMONICONS')) {
5373 $themepath = DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/'.$picto;
5374
5375 if (file_exists($themepath)) {
5376 $path = $themepath;
5377 }
5378 }
5379 }
5380
5381 return img_picto($titlealt, $path, $moreatt, 1, 0, $notitle);
5382}
5383
5397function img_action($titlealt, $numaction, $picto = '', $moreatt = '')
5398{
5399 global $langs;
5400
5401 if (empty($titlealt) || $titlealt == 'default') {
5402 if ($numaction == '-1' || $numaction == 'ST_NO') {
5403 $numaction = -1;
5404 $titlealt = $langs->transnoentitiesnoconv('ChangeDoNotContact');
5405 } elseif ($numaction == '0' || $numaction == 'ST_NEVER') {
5406 $numaction = 0;
5407 $titlealt = $langs->transnoentitiesnoconv('ChangeNeverContacted');
5408 } elseif ($numaction == '1' || $numaction == 'ST_TODO') {
5409 $numaction = 1;
5410 $titlealt = $langs->transnoentitiesnoconv('ChangeToContact');
5411 } elseif ($numaction == '2' || $numaction == 'ST_PEND') {
5412 $numaction = 2;
5413 $titlealt = $langs->transnoentitiesnoconv('ChangeContactInProcess');
5414 } elseif ($numaction == '3' || $numaction == 'ST_DONE') {
5415 $numaction = 3;
5416 $titlealt = $langs->transnoentitiesnoconv('ChangeContactDone');
5417 } else {
5418 $titlealt = $langs->transnoentitiesnoconv('ChangeStatus '.$numaction);
5419 $numaction = 0;
5420 }
5421 }
5422 if (!is_numeric($numaction)) {
5423 $numaction = 0;
5424 }
5425
5426 return img_picto($titlealt, (empty($picto) ? 'stcomm'.$numaction.'.png' : $picto), $moreatt);
5427}
5428
5436function img_pdf($titlealt = 'default', $size = 3)
5437{
5438 global $langs;
5439
5440 if ($titlealt == 'default') {
5441 $titlealt = $langs->trans('Show');
5442 }
5443
5444 return img_picto($titlealt, 'pdf'.$size.'.png');
5445}
5446
5454function img_edit_add($titlealt = 'default', $other = '')
5455{
5456 global $langs;
5457
5458 if ($titlealt == 'default') {
5459 $titlealt = $langs->trans('Add');
5460 }
5461
5462 return img_picto($titlealt, 'edit_add.png', $other);
5463}
5471function img_edit_remove($titlealt = 'default', $other = '')
5472{
5473 global $langs;
5474
5475 if ($titlealt == 'default') {
5476 $titlealt = $langs->trans('Remove');
5477 }
5478
5479 return img_picto($titlealt, 'edit_remove.png', $other);
5480}
5481
5490function img_edit($titlealt = 'default', $float = 0, $other = '')
5491{
5492 global $langs;
5493
5494 if ($titlealt == 'default') {
5495 $titlealt = $langs->trans('Modify');
5496 }
5497
5498 return img_picto($titlealt, 'edit.png', ($float ? 'style="float: '.($langs->tab_translate["DIRECTION"] == 'rtl' ? 'left' : 'right').'"' : "").($other ? ' '.$other : ''));
5499}
5500
5509function img_view($titlealt = 'default', $float = 0, $other = 'class="valignmiddle"')
5510{
5511 global $langs;
5512
5513 if ($titlealt == 'default') {
5514 $titlealt = $langs->trans('View');
5515 }
5516
5517 $moreatt = ($float ? 'style="float: right" ' : '').$other;
5518
5519 return img_picto($titlealt, 'eye', $moreatt);
5520}
5521
5530function img_delete($titlealt = 'default', $other = 'class="pictodelete"', $morecss = '')
5531{
5532 global $langs;
5533
5534 if ($titlealt == 'default') {
5535 $titlealt = $langs->trans('Delete');
5536 }
5537
5538 return img_picto($titlealt, 'delete.png', $other, 0, 0, 0, '', $morecss);
5539}
5540
5548function img_printer($titlealt = "default", $other = '')
5549{
5550 global $langs;
5551 if ($titlealt == "default") {
5552 $titlealt = $langs->trans("Print");
5553 }
5554 return img_picto($titlealt, 'printer.png', $other);
5555}
5556
5564function img_split($titlealt = 'default', $other = 'class="pictosplit"')
5565{
5566 global $langs;
5567
5568 if ($titlealt == 'default') {
5569 $titlealt = $langs->trans('Split');
5570 }
5571
5572 return img_picto($titlealt, 'split.png', $other);
5573}
5574
5582function img_help($usehelpcursor = 1, $usealttitle = 1)
5583{
5584 global $langs;
5585
5586 if ($usealttitle) {
5587 if (is_string($usealttitle)) {
5588 $usealttitle = dol_escape_htmltag($usealttitle);
5589 } else {
5590 $usealttitle = $langs->trans('Info');
5591 }
5592 }
5593
5594 return img_picto($usealttitle, 'info.png', 'style="vertical-align: middle;'.($usehelpcursor == 1 ? ' cursor: help' : ($usehelpcursor == 2 ? ' cursor: pointer' : '')).'"');
5595}
5596
5603function img_info($titlealt = 'default')
5604{
5605 global $langs;
5606
5607 if ($titlealt == 'default') {
5608 $titlealt = $langs->trans('Informations');
5609 }
5610
5611 return img_picto($titlealt, 'info.png', 'style="vertical-align: middle;"');
5612}
5613
5622function img_warning($titlealt = 'default', $moreatt = '', $morecss = 'pictowarning')
5623{
5624 global $langs;
5625
5626 if ($titlealt == 'default') {
5627 $titlealt = $langs->trans('Warning');
5628 }
5629
5630 //return '<div class="imglatecoin">'.img_picto($titlealt, 'warning_white.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): '')).'</div>';
5631 return img_picto($titlealt, 'warning.png', 'class="'.$morecss.'"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt) : ''));
5632}
5633
5640function img_error($titlealt = 'default')
5641{
5642 global $langs;
5643
5644 if ($titlealt == 'default') {
5645 $titlealt = $langs->trans('Error');
5646 }
5647
5648 return img_picto($titlealt, 'error.png');
5649}
5650
5658function img_next($titlealt = 'default', $moreatt = '')
5659{
5660 global $langs;
5661
5662 if ($titlealt == 'default') {
5663 $titlealt = $langs->trans('Next');
5664 }
5665
5666 //return img_picto($titlealt, 'next.png', $moreatt);
5667 return '<span class="fa fa-chevron-right paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
5668}
5669
5677function img_previous($titlealt = 'default', $moreatt = '')
5678{
5679 global $langs;
5680
5681 if ($titlealt == 'default') {
5682 $titlealt = $langs->trans('Previous');
5683 }
5684
5685 //return img_picto($titlealt, 'previous.png', $moreatt);
5686 return '<span class="fa fa-chevron-left paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
5687}
5688
5697function img_down($titlealt = 'default', $selected = 0, $moreclass = '')
5698{
5699 global $langs;
5700
5701 if ($titlealt == 'default') {
5702 $titlealt = $langs->trans('Down');
5703 }
5704
5705 return img_picto($titlealt, ($selected ? '1downarrow_selected.png' : '1downarrow.png'), 'class="imgdown'.($moreclass ? " ".$moreclass : "").'"');
5706}
5707
5716function img_up($titlealt = 'default', $selected = 0, $moreclass = '')
5717{
5718 global $langs;
5719
5720 if ($titlealt == 'default') {
5721 $titlealt = $langs->trans('Up');
5722 }
5723
5724 return img_picto($titlealt, ($selected ? '1uparrow_selected.png' : '1uparrow.png'), 'class="imgup'.($moreclass ? " ".$moreclass : "").'"');
5725}
5726
5735function img_left($titlealt = 'default', $selected = 0, $moreatt = '')
5736{
5737 global $langs;
5738
5739 if ($titlealt == 'default') {
5740 $titlealt = $langs->trans('Left');
5741 }
5742
5743 return img_picto($titlealt, ($selected ? '1leftarrow_selected.png' : '1leftarrow.png'), $moreatt);
5744}
5745
5754function img_right($titlealt = 'default', $selected = 0, $moreatt = '')
5755{
5756 global $langs;
5757
5758 if ($titlealt == 'default') {
5759 $titlealt = $langs->trans('Right');
5760 }
5761
5762 return img_picto($titlealt, ($selected ? '1rightarrow_selected.png' : '1rightarrow.png'), $moreatt);
5763}
5764
5772function img_allow($allow, $titlealt = 'default')
5773{
5774 global $langs;
5775
5776 if ($titlealt == 'default') {
5777 $titlealt = $langs->trans('Active');
5778 }
5779
5780 if ($allow == 1) {
5781 return img_picto($titlealt, 'tick.png');
5782 }
5783
5784 return '-';
5785}
5786
5794function img_credit_card($brand, $morecss = null)
5795{
5796 if (is_null($morecss)) {
5797 $morecss = 'fa-2x';
5798 }
5799
5800 if ($brand == 'visa' || $brand == 'Visa') {
5801 $brand = 'cc-visa';
5802 } elseif ($brand == 'mastercard' || $brand == 'MasterCard') {
5803 $brand = 'cc-mastercard';
5804 } elseif ($brand == 'amex' || $brand == 'American Express') {
5805 $brand = 'cc-amex';
5806 } elseif ($brand == 'discover' || $brand == 'Discover') {
5807 $brand = 'cc-discover';
5808 } elseif ($brand == 'jcb' || $brand == 'JCB') {
5809 $brand = 'cc-jcb';
5810 } elseif ($brand == 'diners' || $brand == 'Diners club') {
5811 $brand = 'cc-diners-club';
5812 } elseif (!in_array($brand, array('cc-visa', 'cc-mastercard', 'cc-amex', 'cc-discover', 'cc-jcb', 'cc-diners-club'))) {
5813 $brand = 'credit-card';
5814 }
5815
5816 return '<span class="fa fa-'.$brand.' fa-fw'.($morecss ? ' '.$morecss : '').'"></span>';
5817}
5818
5827function img_mime($file, $titlealt = '', $morecss = '')
5828{
5829 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
5830
5831 $mimetype = dol_mimetype($file, '', 1);
5832 $mimeimg = dol_mimetype($file, '', 2);
5833 $mimefa = dol_mimetype($file, '', 4);
5834
5835 if (empty($titlealt)) {
5836 $titlealt = 'Mime type: '.$mimetype;
5837 }
5838
5839 //return img_picto_common($titlealt, 'mime/'.$mimeimg, 'class="'.$morecss.'"');
5840 return '<i class="fa fa-'.$mimefa.' paddingright'.($morecss ? ' '.$morecss : '').'"'.($titlealt ? ' title="'.$titlealt.'"' : '').'></i>';
5841}
5842
5843
5851function img_search($titlealt = 'default', $other = '')
5852{
5853 global $langs;
5854
5855 if ($titlealt == 'default') {
5856 $titlealt = $langs->trans('Search');
5857 }
5858
5859 $img = img_picto($titlealt, 'search.png', $other, 0, 1);
5860
5861 $input = '<input type="image" class="liste_titre" name="button_search" src="'.$img.'" ';
5862 $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
5863
5864 return $input;
5865}
5866
5874function img_searchclear($titlealt = 'default', $other = '')
5875{
5876 global $langs;
5877
5878 if ($titlealt == 'default') {
5879 $titlealt = $langs->trans('Search');
5880 }
5881
5882 $img = img_picto($titlealt, 'searchclear.png', $other, 0, 1);
5883
5884 $input = '<input type="image" class="liste_titre" name="button_removefilter" src="'.$img.'" ';
5885 $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
5886
5887 return $input;
5888}
5889
5902function info_admin($text, $infoonimgalt = 0, $nodiv = 0, $admin = '1', $morecss = 'hideonsmartphone', $textfordropdown = '', $picto = '')
5903{
5904 global $conf, $langs;
5905
5906 if ($infoonimgalt) {
5907 $result = img_picto($text, 'info', 'class="'.($morecss ? ' '.$morecss : '').'"');
5908 } else {
5909 if (empty($conf->use_javascript_ajax)) {
5910 $textfordropdown = '';
5911 }
5912
5913 $class = (empty($admin) ? 'undefined' : ($admin == '1' ? 'info' : $admin));
5914 $fa = 'info-circle';
5915 if ($picto == 'warning') {
5916 $fa = 'exclamation-triangle';
5917 }
5918 $result = ($nodiv ? '' : '<div class="wordbreak '.$class.($morecss ? ' '.$morecss : '').($textfordropdown ? ' hidden' : '').'">').'<span class="fa fa-'.$fa.'" title="'.dol_escape_htmltag($admin ? $langs->trans('InfoAdmin') : $langs->trans('Note')).'"></span> ';
5919 $result .= dol_escape_htmltag($text, 1, 0, 'div,span,b,br,a');
5920 $result .= ($nodiv ? '' : '</div>');
5921
5922 if ($textfordropdown) {
5923 $tmpresult = '<span class="'.$class.'text opacitymedium cursorpointer">'.$langs->trans($textfordropdown).' '.img_picto($langs->trans($textfordropdown), '1downarrow').'</span>';
5924 $tmpresult .= '<script nonce="'.getNonce().'" type="text/javascript">
5925 jQuery(document).ready(function() {
5926 jQuery(".'.$class.'text").click(function() {
5927 console.log("toggle text");
5928 jQuery(".'.$class.'").toggle();
5929 });
5930 });
5931 </script>';
5932
5933 $result = $tmpresult.$result;
5934 }
5935 }
5936
5937 return $result;
5938}
5939
5940
5952function dol_print_error($db = null, $error = '', $errors = null)
5953{
5954 global $conf, $langs, $user, $argv;
5955 global $dolibarr_main_prod;
5956
5957 $out = '';
5958 $syslog = '';
5959
5960 // If error occurs before the $lang object was loaded
5961 if (!$langs) {
5962 require_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
5963 $langs = new Translate('', $conf);
5964 $langs->load("main");
5965 }
5966
5967 // Load translation files required by the error messages
5968 $langs->loadLangs(array('main', 'errors'));
5969
5970 if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
5971 $out .= $langs->trans("DolibarrHasDetectedError").".<br>\n";
5972 if (getDolGlobalInt('MAIN_FEATURES_LEVEL') > 0) {
5973 $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";
5974 }
5975 $out .= $langs->trans("InformationToHelpDiagnose").":<br>\n";
5976
5977 $out .= "<b>".$langs->trans("Date").":</b> ".dol_print_date(time(), 'dayhourlog')."<br>\n";
5978 $out .= "<b>".$langs->trans("Dolibarr").":</b> ".DOL_VERSION." - https://www.dolibarr.org<br>\n";
5979 if (isset($conf->global->MAIN_FEATURES_LEVEL)) {
5980 $out .= "<b>".$langs->trans("LevelOfFeature").":</b> ".getDolGlobalInt('MAIN_FEATURES_LEVEL')."<br>\n";
5981 }
5982 if ($user instanceof User) {
5983 $out .= "<b>".$langs->trans("Login").":</b> ".$user->login."<br>\n";
5984 }
5985 if (function_exists("phpversion")) {
5986 $out .= "<b>".$langs->trans("PHP").":</b> ".phpversion()."<br>\n";
5987 }
5988 $out .= "<b>".$langs->trans("Server").":</b> ".(isset($_SERVER["SERVER_SOFTWARE"]) ? dol_htmlentities($_SERVER["SERVER_SOFTWARE"], ENT_COMPAT) : '')."<br>\n";
5989 if (function_exists("php_uname")) {
5990 $out .= "<b>".$langs->trans("OS").":</b> ".php_uname()."<br>\n";
5991 }
5992 $out .= "<b>".$langs->trans("UserAgent").":</b> ".(isset($_SERVER["HTTP_USER_AGENT"]) ? dol_htmlentities($_SERVER["HTTP_USER_AGENT"], ENT_COMPAT) : '')."<br>\n";
5993 $out .= "<br>\n";
5994 $out .= "<b>".$langs->trans("RequestedUrl").":</b> ".dol_htmlentities($_SERVER["REQUEST_URI"], ENT_COMPAT)."<br>\n";
5995 $out .= "<b>".$langs->trans("Referer").":</b> ".(isset($_SERVER["HTTP_REFERER"]) ? dol_htmlentities($_SERVER["HTTP_REFERER"], ENT_COMPAT) : '')."<br>\n";
5996 $out .= "<b>".$langs->trans("MenuManager").":</b> ".(isset($conf->standard_menu) ? dol_htmlentities($conf->standard_menu, ENT_COMPAT) : '')."<br>\n";
5997 $out .= "<br>\n";
5998 $syslog .= "url=".dol_escape_htmltag($_SERVER["REQUEST_URI"]);
5999 $syslog .= ", query_string=".dol_escape_htmltag($_SERVER["QUERY_STRING"]);
6000 } else { // Mode CLI
6001 $out .= '> '.$langs->transnoentities("ErrorInternalErrorDetected").":\n".$argv[0]."\n";
6002 $syslog .= "pid=".dol_getmypid();
6003 }
6004
6005 if (!empty($conf->modules)) {
6006 $out .= "<b>".$langs->trans("Modules").":</b> ".implode(', ', $conf->modules)."<br>\n";
6007 }
6008
6009 if (is_object($db)) {
6010 if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
6011 $out .= "<b>".$langs->trans("DatabaseTypeManager").":</b> ".$db->type."<br>\n";
6012 $lastqueryerror = $db->lastqueryerror();
6013 if (!utf8_check($lastqueryerror)) {
6014 $lastqueryerror = "SQL error string is not a valid UTF8 string. We can't show it.";
6015 }
6016 $out .= "<b>".$langs->trans("RequestLastAccessInError").":</b> ".($lastqueryerror ? dol_escape_htmltag($lastqueryerror) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
6017 $out .= "<b>".$langs->trans("ReturnCodeLastAccessInError").":</b> ".($db->lasterrno() ? dol_escape_htmltag($db->lasterrno()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
6018 $out .= "<b>".$langs->trans("InformationLastAccessInError").":</b> ".($db->lasterror() ? dol_escape_htmltag($db->lasterror()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
6019 $out .= "<br>\n";
6020 } else { // Mode CLI
6021 // No dol_escape_htmltag for output, we are in CLI mode
6022 $out .= '> '.$langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n";
6023 $out .= '> '.$langs->transnoentities("RequestLastAccessInError").":\n".($db->lastqueryerror() ? $db->lastqueryerror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
6024 $out .= '> '.$langs->transnoentities("ReturnCodeLastAccessInError").":\n".($db->lasterrno() ? $db->lasterrno() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
6025 $out .= '> '.$langs->transnoentities("InformationLastAccessInError").":\n".($db->lasterror() ? $db->lasterror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
6026 }
6027 $syslog .= ", sql=".$db->lastquery();
6028 $syslog .= ", db_error=".$db->lasterror();
6029 }
6030
6031 if ($error || $errors) {
6032 // Merge all into $errors array
6033 if (is_array($error) && is_array($errors)) {
6034 $errors = array_merge($error, $errors);
6035 } elseif (is_array($error)) { // deprecated, use second parameters
6036 $errors = $error;
6037 } elseif (is_array($errors) && !empty($error)) {
6038 $errors = array_merge(array($error), $errors);
6039 } elseif (!empty($error)) {
6040 $errors = array_merge(array($error), array($errors));
6041 }
6042
6043 $langs->load("errors");
6044
6045 foreach ($errors as $msg) {
6046 if (empty($msg)) {
6047 continue;
6048 }
6049 if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
6050 $out .= "<b>".$langs->trans("Message").":</b> ".dol_escape_htmltag($msg)."<br>\n";
6051 } else { // Mode CLI
6052 $out .= '> '.$langs->transnoentities("Message").":\n".$msg."\n";
6053 }
6054 $syslog .= ", msg=".$msg;
6055 }
6056 }
6057 if (empty($dolibarr_main_prod) && $_SERVER['DOCUMENT_ROOT'] && function_exists('xdebug_print_function_stack') && function_exists('xdebug_call_file')) {
6058 xdebug_print_function_stack();
6059 $out .= '<b>XDebug information:</b>'."<br>\n";
6060 $out .= 'File: '.xdebug_call_file()."<br>\n";
6061 $out .= 'Line: '.xdebug_call_line()."<br>\n";
6062 $out .= 'Function: '.xdebug_call_function()."<br>\n";
6063 $out .= "<br>\n";
6064 }
6065
6066 // Return a http header with error code if possible
6067 if (!headers_sent()) {
6068 if (function_exists('top_httphead')) { // In CLI context, the method does not exists
6069 top_httphead();
6070 }
6071 //http_response_code(500); // If we use 500, message is not output with some command line tools
6072 http_response_code(202); // If we use 202, this is not really an error message, but this allow to output message on command line tools
6073 }
6074
6075 if (empty($dolibarr_main_prod)) {
6076 print $out;
6077 } else {
6078 if (empty($langs->defaultlang)) {
6079 $langs->setDefaultLang();
6080 }
6081 $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.
6082 // This should not happen, except if there is a bug somewhere. Enabled and check log in such case.
6083 print 'This website or feature is currently temporarily 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";
6084 print $langs->trans("DolibarrHasDetectedError").'. ';
6085 print $langs->trans("YouCanSetOptionDolibarrMainProdToZero");
6086 if (!defined("MAIN_CORE_ERROR")) {
6087 define("MAIN_CORE_ERROR", 1);
6088 }
6089 }
6090
6091 dol_syslog("Error ".$syslog, LOG_ERR);
6092}
6093
6104function dol_print_error_email($prefixcode, $errormessage = '', $errormessages = array(), $morecss = 'error', $email = '')
6105{
6106 global $langs;
6107
6108 if (empty($email)) {
6109 $email = getDolGlobalString('MAIN_INFO_SOCIETE_MAIL');
6110 }
6111
6112 $langs->load("errors");
6113 $now = dol_now();
6114
6115 print '<br><div class="center login_main_message"><div class="'.$morecss.'">';
6116 print $langs->trans("ErrorContactEMail", $email, $prefixcode.'-'.dol_print_date($now, '%Y%m%d%H%M%S'));
6117 if ($errormessage) {
6118 print '<br><br>'.$errormessage;
6119 }
6120 if (is_array($errormessages) && count($errormessages)) {
6121 foreach ($errormessages as $mesgtoshow) {
6122 print '<br><br>'.$mesgtoshow;
6123 }
6124 }
6125 print '</div></div>';
6126}
6127
6144function print_liste_field_titre($name, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $tooltip = "", $forcenowrapcolumntitle = 0)
6145{
6146 print getTitleFieldOfList($name, 0, $file, $field, $begin, $moreparam, $moreattrib, $sortfield, $sortorder, $prefix, 0, $tooltip, $forcenowrapcolumntitle);
6147}
6148
6167function getTitleFieldOfList($name, $thead = 0, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $disablesortlink = 0, $tooltip = '', $forcenowrapcolumntitle = 0)
6168{
6169 global $langs, $form;
6170 //print "$name, $file, $field, $begin, $options, $moreattrib, $sortfield, $sortorder<br>\n";
6171
6172 if ($moreattrib == 'class="right"') {
6173 $prefix .= 'right '; // For backward compatibility
6174 }
6175
6176 $sortorder = strtoupper($sortorder);
6177 $out = '';
6178 $sortimg = '';
6179
6180 $tag = 'th';
6181 if ($thead == 2) {
6182 $tag = 'div';
6183 }
6184
6185 $tmpsortfield = explode(',', $sortfield);
6186 $sortfield1 = trim($tmpsortfield[0]); // If $sortfield is 'd.datep,d.id', it becomes 'd.datep'
6187 $tmpfield = explode(',', $field);
6188 $field1 = trim($tmpfield[0]); // If $field is 'd.datep,d.id', it becomes 'd.datep'
6189
6190 if (!getDolGlobalString('MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE') && empty($forcenowrapcolumntitle)) {
6191 $prefix = 'wrapcolumntitle '.$prefix;
6192 }
6193
6194 //var_dump('field='.$field.' field1='.$field1.' sortfield='.$sortfield.' sortfield1='.$sortfield1);
6195 // If field is used as sort criteria we use a specific css class liste_titre_sel
6196 // Example if (sortfield,field)=("nom","xxx.nom") or (sortfield,field)=("nom","nom")
6197 $liste_titre = 'liste_titre';
6198 if ($field1 && ($sortfield1 == $field1 || $sortfield1 == preg_replace("/^[^\.]+\./", "", $field1))) {
6199 $liste_titre = 'liste_titre_sel';
6200 }
6201
6202 $tagstart = '<'.$tag.' class="'.$prefix.$liste_titre.'" '.$moreattrib;
6203 //$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)).'"' : '');
6204 $tagstart .= ($name && !getDolGlobalString('MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE') && empty($forcenowrapcolumntitle) && !dol_textishtml($name)) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '';
6205 $tagstart .= '>';
6206
6207 if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
6208 $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
6209 $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
6210 $options = preg_replace('/&+/i', '&', $options);
6211 if (!preg_match('/^&/', $options)) {
6212 $options = '&'.$options;
6213 }
6214
6215 $sortordertouseinlink = '';
6216 if ($field1 != $sortfield1) { // We are on another field than current sorted field
6217 if (preg_match('/^DESC/i', $sortorder)) {
6218 $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
6219 } else { // We reverse the var $sortordertouseinlink
6220 $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
6221 }
6222 } else { // We are on field that is the first current sorting criteria
6223 if (preg_match('/^ASC/i', $sortorder)) { // We reverse the var $sortordertouseinlink
6224 $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
6225 } else {
6226 $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
6227 }
6228 }
6229 $sortordertouseinlink = preg_replace('/,$/', '', $sortordertouseinlink);
6230 $out .= '<a class="reposition" href="'.$file.'?sortfield='.$field.'&sortorder='.$sortordertouseinlink.'&begin='.$begin.$options.'"';
6231 //$out .= (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '');
6232 $out .= '>';
6233 }
6234 if ($tooltip) {
6235 // You can also use 'TranslationString:keyfortooltiponclick' for a tooltip on click.
6236 if (preg_match('/:\w+$/', $tooltip)) {
6237 $tmptooltip = explode(':', $tooltip);
6238 } else {
6239 $tmptooltip = array($tooltip);
6240 }
6241 $out .= $form->textwithpicto($langs->trans($name), $langs->trans($tmptooltip[0]), 1, 'help', '', 0, 3, (empty($tmptooltip[1]) ? '' : 'extra_'.str_replace('.', '_', $field).'_'.$tmptooltip[1]));
6242 } else {
6243 $out .= $langs->trans($name);
6244 }
6245
6246 if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
6247 $out .= '</a>';
6248 }
6249
6250 if (empty($thead) && $field) { // If this is a sort field
6251 $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
6252 $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
6253 $options = preg_replace('/&+/i', '&', $options);
6254 if (!preg_match('/^&/', $options)) {
6255 $options = '&'.$options;
6256 }
6257
6258 if (!$sortorder || ($field1 != $sortfield1)) {
6259 //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
6260 //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
6261 } else {
6262 if (preg_match('/^DESC/', $sortorder)) {
6263 //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
6264 //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",1).'</a>';
6265 $sortimg .= '<span class="nowrap">'.img_up("Z-A", 0, 'paddingright').'</span>';
6266 }
6267 if (preg_match('/^ASC/', $sortorder)) {
6268 //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",1).'</a>';
6269 //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
6270 $sortimg .= '<span class="nowrap">'.img_down("A-Z", 0, 'paddingright').'</span>';
6271 }
6272 }
6273 }
6274
6275 $tagend = '</'.$tag.'>';
6276
6277 $out = $tagstart.$sortimg.$out.$tagend;
6278
6279 return $out;
6280}
6281
6290function print_titre($title)
6291{
6292 dol_syslog(__FUNCTION__." is deprecated", LOG_WARNING);
6293
6294 print '<div class="titre">'.$title.'</div>';
6295}
6296
6308function print_fiche_titre($title, $mesg = '', $picto = 'generic', $pictoisfullpath = 0, $id = '')
6309{
6310 print load_fiche_titre($title, $mesg, $picto, $pictoisfullpath, $id);
6311}
6312
6326function load_fiche_titre($title, $morehtmlright = '', $picto = 'generic', $pictoisfullpath = 0, $id = '', $morecssontable = '', $morehtmlcenter = '')
6327{
6328 $return = '';
6329
6330 if ($picto == 'setup') {
6331 $picto = 'generic';
6332 }
6333
6334 $return .= "\n";
6335 $return .= '<table '.($id ? 'id="'.$id.'" ' : '').'class="centpercent notopnoleftnoright table-fiche-title'.($morecssontable ? ' '.$morecssontable : '').'">'; // maring bottom must be same than into print_barre_list
6336 $return .= '<tr class="titre">';
6337 if ($picto) {
6338 $return .= '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle widthpictotitle pictotitle"', $pictoisfullpath).'</td>';
6339 }
6340 $return .= '<td class="nobordernopadding valignmiddle col-title">';
6341 $return .= '<div class="titre inline-block">';
6342 $return .= $title; // $title is already HTML sanitized content
6343 $return .= '</div>';
6344 $return .= '</td>';
6345 if (dol_strlen($morehtmlcenter)) {
6346 $return .= '<td class="nobordernopadding center valignmiddle col-center">'.$morehtmlcenter.'</td>';
6347 }
6348 if (dol_strlen($morehtmlright)) {
6349 $return .= '<td class="nobordernopadding titre_right wordbreakimp right valignmiddle col-right">'.$morehtmlright.'</td>';
6350 }
6351 $return .= '</tr></table>'."\n";
6352
6353 return $return;
6354}
6355
6379function print_barre_liste($title, $page, $file, $options = '', $sortfield = '', $sortorder = '', $morehtmlcenter = '', $num = -1, $totalnboflines = '', $picto = 'generic', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limit = -1, $hideselectlimit = 0, $hidenavigation = 0, $pagenavastextinput = 0, $morehtmlrightbeforearrow = '')
6380{
6381 global $conf, $langs;
6382
6383 $savlimit = $limit;
6384 $savtotalnboflines = $totalnboflines;
6385 if (is_numeric($totalnboflines)) {
6386 $totalnboflines = abs($totalnboflines);
6387 }
6388
6389 $page = (int) $page;
6390
6391 if ($picto == 'setup') {
6392 $picto = 'title_setup.png';
6393 }
6394 if (($conf->browser->name == 'ie') && $picto == 'generic') {
6395 $picto = 'title.gif';
6396 }
6397 if ($limit < 0) {
6398 $limit = $conf->liste_limit;
6399 }
6400
6401 if ($savlimit != 0 && (($num > $limit) || ($num == -1) || ($limit == 0))) {
6402 $nextpage = 1;
6403 } else {
6404 $nextpage = 0;
6405 }
6406 //print 'totalnboflines='.$totalnboflines.'-savlimit='.$savlimit.'-limit='.$limit.'-num='.$num.'-nextpage='.$nextpage.'-hideselectlimit='.$hideselectlimit.'-hidenavigation='.$hidenavigation;
6407
6408 print "\n";
6409 print "<!-- Begin print_barre_liste -->\n";
6410 print '<table class="centpercent notopnoleftnoright table-fiche-title'.($morecss ? ' '.$morecss : '').'"><tr>'; // maring bottom must be same than into load_fiche_tire
6411
6412 // Left
6413
6414 if ($picto && $title) {
6415 print '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle pictotitle widthpictotitle"', $pictoisfullpath).'</td>';
6416 }
6417
6418 print '<td class="nobordernopadding valignmiddle col-title">';
6419 print '<div class="titre inline-block">';
6420 print '<span class="inline-block valignmiddle">'.dolPrintLabel($title).'</span>'; // $title may contains HTML
6421 if (!empty($title) && $savtotalnboflines >= 0 && (string) $savtotalnboflines != '') {
6422 print '<span class="opacitymedium colorblack marginleftonly totalnboflines valignmiddle" title="'.$langs->trans("NbRecordQualified").'">('.$totalnboflines.')</span>';
6423 }
6424 print '</div></td>';
6425
6426 // Center
6427 if ($morehtmlcenter && empty($conf->dol_optimize_smallscreen)) {
6428 print '<td class="nobordernopadding center valignmiddle col-center">'.$morehtmlcenter.'</td>';
6429 }
6430
6431 // Right
6432 print '<td class="nobordernopadding valignmiddle right col-right">';
6433 print '<input type="hidden" name="pageplusoneold" value="'.((int) $page + 1).'">';
6434 if ($sortfield) {
6435 $options .= "&sortfield=".urlencode($sortfield);
6436 }
6437 if ($sortorder) {
6438 $options .= "&sortorder=".urlencode($sortorder);
6439 }
6440 // Show navigation bar
6441 $pagelist = '';
6442 if ($savlimit != 0 && ($page > 0 || $num > $limit)) {
6443 if ($totalnboflines) { // If we know total nb of lines
6444 // Define nb of extra page links before and after selected page + ... + first or last
6445 $maxnbofpage = (empty($conf->dol_optimize_smallscreen) ? 4 : 0);
6446
6447 if ($limit > 0) {
6448 $nbpages = ceil($totalnboflines / $limit);
6449 } else {
6450 $nbpages = 1;
6451 }
6452 $cpt = ($page - $maxnbofpage);
645