dolibarr 22.0.5
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-2025 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-2024 Alexandre Spangaro <alexandre@inovea-conseil.com>
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-2025 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-2025 Charlene Benke <charlene@patas-monkey.com>
23 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
24 * Copyright (C) 2023-2024 Joachim Kueter <git-jk@bloxera.com>
25 * Copyright (C) 2024 Lenin Rivas <lenin.rivas777@gmail.com>
26 * Copyright (C) 2024 Josep Lluís Amador Teruel <joseplluis@lliuretic.cat>
27 * Copyright (C) 2024 Benoît PASCAL <contact@p-ben.com>
28 * Copyright (C) 2026 Benjamin Falière <benjamin@faliere.com>
29 *
30 * This program is free software; you can redistribute it and/or modify
31 * it under the terms of the GNU General Public License as published by
32 * the Free Software Foundation; either version 3 of the License, or
33 * (at your option) any later version.
34 *
35 * This program is distributed in the hope that it will be useful,
36 * but WITHOUT ANY WARRANTY; without even the implied warranty of
37 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
38 * GNU General Public License for more details.
39 *
40 * You should have received a copy of the GNU General Public License
41 * along with this program. If not, see <https://www.gnu.org/licenses/>.
42 * or see https://www.gnu.org/
43 */
44
51//include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
52
53// Function for better PHP x compatibility
54if (!function_exists('utf8_encode')) {
62 function utf8_encode($elements)
63 {
64 return mb_convert_encoding($elements, 'UTF-8', 'ISO-8859-1');
65 }
66}
67
68if (!function_exists('utf8_decode')) {
76 function utf8_decode($elements)
77 {
78 return mb_convert_encoding($elements, 'ISO-8859-1', 'UTF-8');
79 }
80}
81if (!function_exists('str_starts_with')) {
90 function str_starts_with($haystack, $needle)
91 {
92 return (string) $needle !== '' && strncmp($haystack, $needle, strlen($needle)) === 0;
93 }
94}
95if (!function_exists('str_ends_with')) {
104 function str_ends_with($haystack, $needle)
105 {
106 return $needle !== '' && substr($haystack, -strlen($needle)) === (string) $needle;
107 }
108}
109if (!function_exists('str_contains')) {
118 function str_contains($haystack, $needle)
119 {
120 return $needle !== '' && mb_strpos($haystack, $needle) !== false;
121 }
122}
123
124
136function getMultidirOutput($object, $module = '', $forobject = 0, $mode = 'output')
137{
138 global $conf;
139
140 if (!is_object($object) && empty($module)) {
141 return null;
142 }
143 if (empty($module) && !empty($object->element)) {
144 $module = $object->element;
145 }
146
147 // Special case for backward compatibility
148 if ($module == 'fichinter') {
149 $module = 'ficheinter';
150 } elseif ($module == 'invoice_supplier') {
151 $module = 'supplier_invoice';
152 } elseif ($module == 'order_supplier') {
153 $module = 'supplier_order';
154 }
155
156 // Get the relative path of directory
157 if ($mode == 'output' || $mode == 'outputrel' || $mode == 'version') {
158 if (isset($conf->$module) && property_exists($conf->$module, 'multidir_output')) {
159 $s = '';
160 if ($mode != 'outputrel') {
161 // An entity with no declared directory returned an undefined index, so an empty path that
162 // made the caller read or write a relative path under the web root. Answer the error instead.
163 $entity = (int) (empty($object->entity) ? $conf->entity : $object->entity);
164 if (!isset($conf->$module->multidir_output[$entity])) {
165 return 'error-diroutput-not-defined-for-this-entity-and-object='.$module;
166 }
167 $s = $conf->$module->multidir_output[$entity];
168 }
169 if ($forobject && $object->id > 0) {
170 $s .= ($mode != 'outputrel' ? '/' : '').get_exdir(0, 0, 0, 0, $object);
171 }
172 return $s;
173 } elseif (isset($conf->$module) && property_exists($conf->$module, 'dir_output')) {
174 $s = '';
175 if ($mode != 'outputrel') {
176 $s = $conf->$module->dir_output;
177 }
178 if ($forobject && $object->id > 0) {
179 $s .= ($mode != 'outputrel' ? '/' : '').get_exdir(0, 0, 0, 0, $object);
180 }
181 return $s;
182 } else {
183 return 'error-diroutput-not-defined-for-this-entity-and-object='.$module;
184 }
185 } elseif ($mode == 'temp') {
186 if (isset($conf->$module) && property_exists($conf->$module, 'multidir_temp')) {
187 // Same guard as the 'output' mode above, see the comment there
188 $entity = (int) (empty($object->entity) ? $conf->entity : $object->entity);
189 if (!isset($conf->$module->multidir_temp[$entity])) {
190 return 'error-dirtemp-not-defined-for-this-entity-and-object='.$module;
191 }
192 return $conf->$module->multidir_temp[$entity];
193 } elseif (isset($conf->$module) && property_exists($conf->$module, 'dir_temp')) {
194 return $conf->$module->dir_temp;
195 } else {
196 return 'error-dirtemp-not-defined-for-this-entity-and-object='.$module;
197 }
198 } else {
199 return 'error-bad-value-for-mode';
200 }
201}
202
212function getMultidirTemp($object, $module = '', $forobject = 0)
213{
214 return getMultidirOutput($object, $module, $forobject, 'temp');
215}
216
226function getMultidirVersion($object, $module = '', $forobject = 0)
227{
228 return getMultidirOutput($object, $module, $forobject, 'version');
229}
230
231
240function getDolGlobalString($key, $default = '')
241{
242 global $conf;
243 return (string) (isset($conf->global->$key) ? $conf->global->$key : $default);
244}
245
255function getDolGlobalInt($key, $default = 0)
256{
257 global $conf;
258 return (int) (isset($conf->global->$key) ? $conf->global->$key : $default);
259}
260
270function getDolGlobalFloat($key, $default = 0)
271{
272 global $conf;
273 return (float) (isset($conf->global->$key) ? $conf->global->$key : $default);
274}
275
284function getDolGlobalBool($key, $default = false)
285{
286 global $conf;
287 return (bool) ($conf->global->$key ?? $default);
288}
289
299function getDolUserString($key, $default = '', $tmpuser = null)
300{
301 if (empty($tmpuser)) {
302 global $user;
303 $tmpuser = $user;
304 }
305
306 return (string) (isset($tmpuser->conf->$key) ? $tmpuser->conf->$key : $default);
307}
308
317function getDolUserInt($key, $default = 0, $tmpuser = null)
318{
319 if (empty($tmpuser)) {
320 global $user;
321 $tmpuser = $user;
322 }
323
324 return (int) (isset($tmpuser->conf->$key) ? $tmpuser->conf->$key : $default);
325}
326
327
337define(
338 'MODULE_MAPPING',
339 array(
340 // Map deprecated names to new names
341 'adherent' => 'member', // Has new directory
342 'member_type' => 'adherent_type', // No directory, but file called adherent_type
343 'banque' => 'bank', // Has new directory
344 'contrat' => 'contract', // Has new directory
345 'entrepot' => 'stock', // Has new directory
346 'projet' => 'project', // Has new directory
347 'categorie' => 'category', // Has old directory
348 'commande' => 'order', // Has old directory
349 'expedition' => 'shipping', // Has old directory
350 'facture' => 'invoice', // Has old directory
351 'fichinter' => 'intervention', // Has old directory
352 'ficheinter' => 'intervention', // Backup for 'fichinter'
353 'propale' => 'propal', // Has old directory
354 'socpeople' => 'contact', // Has old directory
355 'fournisseur' => 'supplier', // Has old directory
356
357 'actioncomm' => 'agenda', // NO module directory (public dir agenda)
358 'product_price' => 'productprice', // NO directory
359 'product_fournisseur_price' => 'productsupplierprice', // NO directory
360 )
361);
362
369function isModEnabled($module)
370{
371 global $conf;
372
373 // Fix old names (map to new names)
374 $arrayconv = MODULE_MAPPING;
375 $arrayconvbis = array_flip(MODULE_MAPPING);
376
377 if (!getDolGlobalString('MAIN_USE_NEW_SUPPLIERMOD')) {
378 // Special cases: both use the same module.
379 $arrayconv['supplier_order'] = 'fournisseur';
380 $arrayconv['supplier_invoice'] = 'fournisseur';
381 }
382 // Special case.
383 // @TODO Replace isModEnabled('delivery_note') with
384 // isModEnabled('shipping') && getDolGlobalString('MAIN_SUBMODULE_EXPEDITION')
385 if ($module == 'delivery_note') {
386 if (!getDolGlobalString('MAIN_SUBMODULE_EXPEDITION')) {
387 return false;
388 } else {
389 $module = 'shipping';
390 }
391 }
392
393 $module_alt = $module;
394 if (!empty($arrayconv[$module])) {
395 $module_alt = $arrayconv[$module];
396 }
397 $module_bis = $module;
398 if (!empty($arrayconvbis[$module])) {
399 $module_bis = $arrayconvbis[$module];
400 }
401
402 return !empty($conf->modules[$module]) || !empty($conf->modules[$module_alt]) || !empty($conf->modules[$module_bis]);
403 //return !empty($conf->$module->enabled);
404}
405
416function getWarningDelay($module, $parmlevel1, $parmlevel2 = '')
417{
418 global $conf;
419
420 // For compatibility with bad naming on module
421 $moduletomoduletouse = array(
422 'invoice' => 'facture',
423 );
424 $moduleParmsMapping = array(
425 'product' => 'produit',
426 );
427
428 if (!empty($moduletomoduletouse[$module])) {
429 $module = $moduletomoduletouse[$module];
430 }
431
432 $warningDelayPath = $parmlevel1;
433 if (!empty($moduleParmsMapping[$warningDelayPath])) {
434 $warningDelayPath = $moduleParmsMapping[$warningDelayPath];
435 }
436
437 if ($parmlevel2) {
438 if (!empty($conf->$module->$warningDelayPath->warning_delay)) {
439 if (!empty($conf->$module->$warningDelayPath->$parmlevel2->warning_delay)) {
440 return (int) $conf->$module->$warningDelayPath->$parmlevel2->warning_delay;
441 }
442 }
443 } else {
444 if (!empty($conf->$module->$warningDelayPath->warning_delay)) {
445 return (int) $conf->$module->$warningDelayPath->$parmlevel1->warning_delay;
446 }
447 }
448
449 return 0;
450}
451
458function isDolTms($timestamp)
459{
460 if ($timestamp === '') {
461 dol_syslog('Using empty string for a timestamp is deprecated, prefer use of null when calling page '.$_SERVER["PHP_SELF"] . getCallerInfoString(), LOG_NOTICE);
462 return false;
463 }
464 if (is_null($timestamp) || !is_numeric($timestamp)) {
465 return false;
466 }
467
468 return true;
469}
470
482function getDoliDBInstance($type, $host, $user, $pass, $name, $port)
483{
484 require_once DOL_DOCUMENT_ROOT."/core/db/".$type.'.class.php';
485
486 $class = 'DoliDB'.ucfirst($type);
487 $db = new $class($type, $host, $user, $pass, $name, $port);
488 return $db;
489}
490
508function getEntity($element, $shared = 1, $currentobject = null)
509{
510 global $conf, $mc, $hookmanager, $object, $action, $db;
511
512 if (!is_object($hookmanager)) {
513 include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
514 $hookmanager = new HookManager($db);
515 }
516
517 // fix different element names (France to English)
518 switch ($element) {
519 case 'projet':
520 $element = 'project';
521 break;
522 case 'contrat':
523 $element = 'contract';
524 break; // "/contrat/class/contrat.class.php"
525 case 'order_supplier':
526 $element = 'supplier_order';
527 break; // "/fourn/class/fournisseur.commande.class.php"
528 case 'invoice_supplier':
529 $element = 'supplier_invoice';
530 break; // "/fourn/class/fournisseur.facture.class.php"
531 }
532
533 if (is_object($mc)) {
534 $out = $mc->getEntity($element, $shared, $currentobject);
535 } else {
536 $out = '';
537 $addzero = array('user', 'usergroup', 'cronjob', 'c_email_templates', 'email_template', 'default_values', 'overwrite_trans', 'extrafields');
538 if (getDolGlobalString('HOLIDAY_ALLOW_ZERO_IN_DIC')) { // this constant break the dictionary admin without Multicompany
539 $addzero[] = 'c_holiday_types';
540 }
541 if (in_array($element, $addzero)) {
542 $out .= '0,';
543 }
544 $out .= ((int) $conf->entity);
545 }
546
547 // Manipulate entities to query on the fly
548 $parameters = array(
549 'element' => $element,
550 'shared' => $shared,
551 'object' => $object,
552 'currentobject' => $currentobject,
553 'out' => $out
554 );
555 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable
556 $reshook = $hookmanager->executeHooks('hookGetEntity', $parameters, $currentobject, $action); // Note that $action and $object may have been modified by some hooks
557
558 if (is_numeric($reshook)) {
559 if ($reshook == 0 && !empty($hookmanager->resPrint)) {
560 $out .= ','.$hookmanager->resPrint; // add
561 } elseif ($reshook == 1) {
562 $out = $hookmanager->resPrint; // replace
563 }
564 }
565
566 return $out;
567}
568
575function setEntity($currentobject)
576{
577 global $conf, $mc;
578
579 if (is_object($mc) && method_exists($mc, 'setEntity')) {
580 return $mc->setEntity($currentobject);
581 } else {
582 return ((is_object($currentobject) && $currentobject->id > 0 && $currentobject->entity > 0) ? $currentobject->entity : $conf->entity);
583 }
584}
585
592function isASecretKey($keyname)
593{
594 return preg_match('/(_pass|password|_pw|_key|securekey|serverkey|secret\d?|p12key|exportkey|_PW_[a-z]+|token)$/i', $keyname);
595}
596
597
604function num2Alpha($n)
605{
606 for ($r = ""; $n >= 0; $n = intval($n / 26) - 1) {
607 $r = chr($n % 26 + 0x41) . $r;
608 }
609 return $r;
610}
611
612
629function getBrowserInfo($user_agent)
630{
631 include_once DOL_DOCUMENT_ROOT.'/includes/mobiledetect/mobiledetectlib/Mobile_Detect.php';
632
633 $name = 'unknown';
634 $version = '';
635 $os = 'unknown';
636 $phone = '';
637
638 $user_agent = substr($user_agent, 0, 512); // Avoid to process too large user agent
639
640 $detectmobile = new Mobile_Detect(null, $user_agent);
641 $tablet = $detectmobile->isTablet();
642
643 if ($detectmobile->isMobile()) {
644 $phone = 'unknown';
645
646 // If phone/smartphone, we set phone os name.
647 if ($detectmobile->is('AndroidOS')) {
648 $os = $phone = 'android';
649 } elseif ($detectmobile->is('BlackBerryOS')) {
650 $os = $phone = 'blackberry';
651 } elseif ($detectmobile->is('iOS')) {
652 $os = 'ios';
653 $phone = 'iphone';
654 } elseif ($detectmobile->is('PalmOS')) {
655 $os = $phone = 'palm';
656 } elseif ($detectmobile->is('SymbianOS')) {
657 $os = 'symbian';
658 } elseif ($detectmobile->is('webOS')) {
659 $os = 'webos';
660 } elseif ($detectmobile->is('MaemoOS')) {
661 $os = 'maemo';
662 } elseif ($detectmobile->is('WindowsMobileOS') || $detectmobile->is('WindowsPhoneOS')) {
663 $os = 'windows';
664 }
665 }
666
667 // OS
668 if (preg_match('/linux/i', $user_agent)) {
669 $os = 'linux';
670 } elseif (preg_match('/macintosh/i', $user_agent)) {
671 $os = 'macintosh';
672 } elseif (preg_match('/windows/i', $user_agent)) {
673 $os = 'windows';
674 }
675
676 // Name
677 $reg = array();
678 if (preg_match('/firefox(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
679 $name = 'firefox';
680 $version = empty($reg[2]) ? '' : $reg[2];
681 } elseif (preg_match('/edge(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
682 $name = 'edge';
683 $version = empty($reg[2]) ? '' : $reg[2];
684 } elseif (preg_match('/chrome(\/|\s)([\d\.]+)/i', $user_agent, $reg)) {
685 $name = 'chrome';
686 $version = empty($reg[2]) ? '' : $reg[2];
687 } elseif (preg_match('/chrome/i', $user_agent, $reg)) {
688 // we can have 'chrome (Mozilla...) chrome x.y' in one string
689 $name = 'chrome';
690 } elseif (preg_match('/iceweasel/i', $user_agent)) {
691 $name = 'iceweasel';
692 } elseif (preg_match('/epiphany/i', $user_agent)) {
693 $name = 'epiphany';
694 } elseif (preg_match('/safari(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
695 $name = 'safari';
696 $version = empty($reg[2]) ? '' : $reg[2];
697 } elseif (preg_match('/opera(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
698 // Safari is often present in string for mobile but its not.
699 $name = 'opera';
700 $version = empty($reg[2]) ? '' : $reg[2];
701 } elseif (preg_match('/(MSIE\s([0-9]+\.[0-9]))|.*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
702 $name = 'ie';
703 $version = end($reg);
704 } elseif (preg_match('/(Windows NT\s([0-9]+\.[0-9])).*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
705 // MS products at end
706 $name = 'ie';
707 $version = end($reg);
708 } elseif (preg_match('/l[iy]n(x|ks)(\‍(|\/|\s)*([\d\.]+)/i', $user_agent, $reg)) {
709 // MS products at end
710 $name = 'textbrowser';
711 $version = empty($reg[3]) ? '' : $reg[3];
712 } elseif (preg_match('/w3m\/([\d\.]+)/i', $user_agent, $reg)) {
713 // MS products at end
714 $name = 'textbrowser';
715 $version = empty($reg[1]) ? '' : $reg[1];
716 }
717
718 if ($tablet) {
719 $layout = 'tablet';
720 } elseif ($phone) {
721 $layout = 'phone';
722 } else {
723 $layout = 'classic';
724 }
725
726 return array(
727 'browsername' => $name,
728 'browserversion' => $version,
729 'browseros' => $os,
730 'browserua' => $user_agent,
731 'layout' => $layout, // tablet, phone, classic
732 'phone' => $phone, // deprecated
733 'tablet' => $tablet // deprecated
734 );
735}
736
742function dol_shutdown()
743{
744 global $db;
745 $disconnectdone = false;
746 $depth = 0;
747 if (is_object($db) && !empty($db->connected)) {
748 $depth = $db->transaction_opened;
749 $disconnectdone = $db->close();
750 }
751 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));
752}
753
763function GETPOSTISSET($paramname)
764{
765 $isset = false;
766
767 $relativepathstring = $_SERVER["PHP_SELF"];
768 // Clean $relativepathstring
769 if (constant('DOL_URL_ROOT')) {
770 $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
771 }
772 $relativepathstring = ltrim($relativepathstring, '/');
773 $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
774 //var_dump($relativepathstring);
775 //var_dump($user->default_values);
776
777 // Code for search criteria persistence.
778 // Retrieve values if restore_lastsearch_values
779 if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
780 if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
781 $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
782 if (is_array($tmp)) {
783 foreach ($tmp as $key => $val) {
784 if ($key == $paramname) { // We are on the requested parameter
785 $isset = true;
786 break;
787 }
788 }
789 }
790 }
791 // If there is saved contextpage, limit, page or mode
792 if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
793 $isset = true;
794 } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
795 $isset = true;
796 } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
797 $isset = true;
798 } elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_'.$relativepathstring])) {
799 $isset = true;
800 }
801 } else {
802 $isset = (isset($_POST[$paramname]) || isset($_GET[$paramname])); // We must keep $_POST and $_GET here
803 }
804
805 return $isset;
806}
807
816function GETPOSTISARRAY($paramname, $method = 0)
817{
818 // for $method test need return the same $val as GETPOST
819 if (empty($method)) {
820 $val = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
821 } elseif ($method == 1) {
822 $val = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
823 } elseif ($method == 2) {
824 $val = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
825 } elseif ($method == 3) {
826 $val = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
827 } else {
828 $val = 'BadFirstParameterForGETPOST';
829 }
830
831 return is_array($val);
832}
833
864function GETPOST($paramname, $check = 'alphanohtml', $method = 0, $filter = null, $options = null, $noreplace = 0)
865{
866 global $mysoc, $user, $conf;
867
868 if (empty($paramname)) { // Explicit test for null for phan.
869 return 'BadFirstParameterForGETPOST';
870 }
871 if (empty($check)) {
872 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);
873 // Enable this line to know who call the GETPOST with '' $check parameter.
874 //var_dump(getCallerInfoString());
875 }
876
877 if (empty($method)) {
878 $out = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
879 } elseif ($method == 1) {
880 $out = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
881 } elseif ($method == 2) {
882 $out = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
883 } elseif ($method == 3) {
884 $out = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
885 } else {
886 return 'BadThirdParameterForGETPOST';
887 }
888
889 $relativepathstring = ''; // For static analysis - looks possibly undefined if not set.
890
891 if (empty($method) || $method == 3 || $method == 4) {
892 $relativepathstring = (empty($_SERVER["PHP_SELF"]) ? '' : $_SERVER["PHP_SELF"]);
893 // Clean $relativepathstring
894 if (constant('DOL_URL_ROOT')) {
895 $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
896 }
897 $relativepathstring = ltrim($relativepathstring, '/');
898 $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
899 //var_dump($relativepathstring);
900 //var_dump($user->default_values);
901
902 // Code for search criteria persistence.
903 // Retrieve saved values if restore_lastsearch_values is set
904 if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
905 if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
906 $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
907 if (is_array($tmp)) {
908 foreach ($tmp as $key => $val) {
909 if ($key == $paramname) { // We are on the requested parameter
910 $out = $val;
911 break;
912 }
913 }
914 }
915 }
916 // If there is saved contextpage, page or limit
917 if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
918 $out = $_SESSION['lastsearch_contextpage_'.$relativepathstring];
919 } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
920 $out = $_SESSION['lastsearch_limit_'.$relativepathstring];
921 } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
922 $out = $_SESSION['lastsearch_page_'.$relativepathstring];
923 } elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_'.$relativepathstring])) {
924 $out = $_SESSION['lastsearch_mode_'.$relativepathstring];
925 }
926 } elseif (!isset($_GET['sortfield'])) {
927 // Else, retrieve default values if we are not doing a sort
928 // 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
929 if (!empty($_GET['action']) && $_GET['action'] == 'create' && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
930 // Search default value from $object->field
931 global $object;
932 '@phan-var-force CommonObject $object'; // Suppose it's a CommonObject for analysis, but other objects have the $fields field as well
933 if (is_object($object) && isset($object->fields[$paramname]['default'])) {
934 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
935 $out = $object->fields[$paramname]['default'];
936 }
937 }
938 if (getDolGlobalString('MAIN_ENABLE_DEFAULT_VALUES')) {
939 if (!empty($_GET['action']) && (preg_match('/^create/', $_GET['action']) || preg_match('/^presend/', $_GET['action'])) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
940 // Now search in setup to overwrite default values
941 if (!empty($user->default_values)) { // $user->default_values defined from menu 'Setup - Default values'
942 if (isset($user->default_values[$relativepathstring]['createform'])) {
943 foreach ($user->default_values[$relativepathstring]['createform'] as $defkey => $defval) {
944 $qualified = 0;
945 if ($defkey != '_noquery_') {
946 $tmpqueryarraytohave = explode('&', $defkey);
947 $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
948 $foundintru = 0;
949 foreach ($tmpqueryarraytohave as $tmpquerytohave) {
950 if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
951 $foundintru = 1;
952 }
953 }
954 if (!$foundintru) {
955 $qualified = 1;
956 }
957 //var_dump($defkey.'-'.$qualified);
958 } else {
959 $qualified = 1;
960 }
961
962 if ($qualified) {
963 if (isset($user->default_values[$relativepathstring]['createform'][$defkey][$paramname])) {
964 $out = $user->default_values[$relativepathstring]['createform'][$defkey][$paramname];
965 break;
966 }
967 }
968 }
969 }
970 }
971 } elseif (!empty($paramname) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
972 // Management of default search_filters and sort order
973 if (!empty($user->default_values)) {
974 // $user->default_values defined from menu 'Setup - Default values'
975 //var_dump($user->default_values[$relativepathstring]);
976 if ($paramname == 'sortfield' || $paramname == 'sortorder') {
977 // Sorted on which fields ? ASC or DESC ?
978 if (isset($user->default_values[$relativepathstring]['sortorder'])) {
979 // Even if paramname is sortfield, data are stored into ['sortorder...']
980 foreach ($user->default_values[$relativepathstring]['sortorder'] as $defkey => $defval) {
981 $qualified = 0;
982 if ($defkey != '_noquery_') {
983 $tmpqueryarraytohave = explode('&', $defkey);
984 $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
985 $foundintru = 0;
986 foreach ($tmpqueryarraytohave as $tmpquerytohave) {
987 if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
988 $foundintru = 1;
989 }
990 }
991 if (!$foundintru) {
992 $qualified = 1;
993 }
994 //var_dump($defkey.'-'.$qualified);
995 } else {
996 $qualified = 1;
997 }
998
999 if ($qualified) {
1000 $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
1001 foreach ($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val) {
1002 if ($out) {
1003 $out .= ', ';
1004 }
1005 if ($paramname == 'sortfield') {
1006 $out .= dol_string_nospecial($key, '', $forbidden_chars_to_replace);
1007 }
1008 if ($paramname == 'sortorder') {
1009 $out .= dol_string_nospecial($val, '', $forbidden_chars_to_replace);
1010 }
1011 }
1012 //break; // No break for sortfield and sortorder so we can cumulate fields (is it really useful ?)
1013 }
1014 }
1015 }
1016 } elseif (isset($user->default_values[$relativepathstring]['filters'])) {
1017 foreach ($user->default_values[$relativepathstring]['filters'] as $defkey => $defval) { // $defkey is a querystring like 'a=b&c=d', $defval is key of user
1018 if (!empty($_GET['disabledefaultvalues'])) { // If set of default values has been disabled by a request parameter
1019 continue;
1020 }
1021 $qualified = 0;
1022 if ($defkey != '_noquery_') {
1023 $tmpqueryarraytohave = explode('&', $defkey);
1024 $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
1025 $foundintru = 0;
1026 foreach ($tmpqueryarraytohave as $tmpquerytohave) {
1027 if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
1028 $foundintru = 1;
1029 }
1030 }
1031 if (!$foundintru) {
1032 $qualified = 1;
1033 }
1034 //var_dump($defkey.'-'.$qualified);
1035 } else {
1036 $qualified = 1;
1037 }
1038
1039 if ($qualified && isset($user->default_values[$relativepathstring]['filters'][$defkey][$paramname])) {
1040 // We must keep $_POST and $_GET here
1041 if (isset($_POST['search_all']) || isset($_GET['search_all'])) {
1042 // We made a search from quick search menu, do we still use default filter ?
1043 if (!getDolGlobalString('MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH')) {
1044 $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
1045 $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
1046 }
1047 } else {
1048 $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
1049 $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
1050 }
1051 break;
1052 }
1053 }
1054 }
1055 }
1056 }
1057 }
1058 }
1059 }
1060
1061 // 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)
1062 // Example of variables: __DAY__, __MONTH__, __YEAR__, __MYCOMPANY_COUNTRY_ID__, __USER_ID__, ...
1063 // 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.
1064 '@phan-var-force string $paramname';
1065 if (!is_array($out) && empty($_POST[$paramname]) && empty($noreplace)) {
1066 $reg = array();
1067 $regreplace = array();
1068 $maxloop = 20;
1069 $loopnb = 0; // Protection against infinite loop
1070
1071 while (preg_match('/__([A-Z0-9]+(?:_[A-Z0-9]+){0,3})__/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.
1072 $loopnb++;
1073 $newout = '';
1074
1075 if ($reg[1] == 'DAY') {
1076 $tmp = dol_getdate(dol_now(), true);
1077 $newout = $tmp['mday'];
1078 } elseif ($reg[1] == 'MONTH') {
1079 $tmp = dol_getdate(dol_now(), true);
1080 $newout = $tmp['mon'];
1081 } elseif ($reg[1] == 'YEAR') {
1082 $tmp = dol_getdate(dol_now(), true);
1083 $newout = $tmp['year'];
1084 } elseif ($reg[1] == 'PREVIOUS_DAY') {
1085 $tmp = dol_getdate(dol_now(), true);
1086 $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
1087 $newout = $tmp2['day'];
1088 } elseif ($reg[1] == 'PREVIOUS_MONTH') {
1089 $tmp = dol_getdate(dol_now(), true);
1090 $tmp2 = dol_get_prev_month($tmp['mon'], $tmp['year']);
1091 $newout = $tmp2['month'];
1092 } elseif ($reg[1] == 'PREVIOUS_YEAR') {
1093 $tmp = dol_getdate(dol_now(), true);
1094 $newout = ($tmp['year'] - 1);
1095 } elseif ($reg[1] == 'NEXT_DAY') {
1096 $tmp = dol_getdate(dol_now(), true);
1097 $tmp2 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
1098 $newout = $tmp2['day'];
1099 } elseif ($reg[1] == 'NEXT_MONTH') {
1100 $tmp = dol_getdate(dol_now(), true);
1101 $tmp2 = dol_get_next_month($tmp['mon'], $tmp['year']);
1102 $newout = $tmp2['month'];
1103 } elseif ($reg[1] == 'NEXT_YEAR') {
1104 $tmp = dol_getdate(dol_now(), true);
1105 $newout = ($tmp['year'] + 1);
1106 } elseif ($reg[1] == 'MYCOMPANY_COUNTRY_ID' || $reg[1] == 'MYCOUNTRY_ID' || $reg[1] == 'MYCOUNTRYID') {
1107 $newout = $mysoc->country_id;
1108 } elseif ($reg[1] == 'USER_ID' || $reg[1] == 'USERID') {
1109 $newout = $user->id;
1110 } elseif ($reg[1] == 'USER_SUPERVISOR_ID' || $reg[1] == 'SUPERVISOR_ID' || $reg[1] == 'SUPERVISORID') {
1111 $newout = $user->fk_user;
1112 } elseif ($reg[1] == 'ENTITY_ID' || $reg[1] == 'ENTITYID') {
1113 $newout = $conf->entity;
1114 } elseif ($reg[1] == 'ID') {
1115 $newout = '__ID__'; // We keep __ID__ we find into backtopage url
1116 } else {
1117 $newout = 'REGREPLACE_'.$loopnb; // Key not found, we replace with temporary string to reload later
1118 $regreplace[$loopnb] = $reg[0];
1119 }
1120 //var_dump('__'.$reg[1].'__ -> '.$newout);
1121 $out = preg_replace('/__'.preg_quote($reg[1], '/').'__/', $newout, $out);
1122 }
1123 if (!empty($regreplace)) {
1124 foreach ($regreplace as $key => $value) {
1125 $out = preg_replace('/REGREPLACE_'.$key.'/', $value, $out);
1126 }
1127 }
1128 }
1129
1130 // Check type of variable and make sanitization according to this
1131 if (preg_match('/^array/', $check)) { // If 'array' or 'array:restricthtml' or 'array:aZ09' or 'array:intcomma'
1132 $tmpcheck = 'alphanohtml';
1133 if (empty($out)) {
1134 $out = array();
1135 } elseif (!is_array($out)) {
1136 $out = explode(',', $out);
1137 } else {
1138 $tmparray = explode(':', $check);
1139 if (!empty($tmparray[1])) {
1140 $tmpcheck = $tmparray[1];
1141 }
1142 }
1143 foreach ($out as $outkey => $outval) {
1144 $out[$outkey] = sanitizeVal($outval, $tmpcheck, $filter, $options);
1145 }
1146 } else {
1147 // If field name is 'search_xxx' then we force the add of space after each < and > (when following char is numeric) because it means
1148 // 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
1149 if (strpos($paramname, 'search_') === 0) {
1150 $out = preg_replace('/([<>])([-+]?\d)/', '\1 \2', $out);
1151 }
1152
1153 // @phan-suppress-next-line UnknownSanitizeType
1154 $out = sanitizeVal($out, $check, $filter, $options);
1155 }
1156
1157 // Sanitizing for special parameters.
1158 // Note: There is no reason to allow the backtopage/backtopageforcancel/backtopagejs, backtolist or backtourl parameter to contains an external URL. Only relative URLs are allowed.
1159 // @TODO Merge backtopage with backtourl
1160 // @TODO Rename backtolist into backtopagelist
1161 if (preg_match('/^backto/i', $paramname)) {
1162 $out = str_replace('\\', '/', $out); // Can be before the loop because only 1 char is replaced. No risk to get it after other replacements.
1163 $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.
1164 do {
1165 $oldstringtoclean = $out;
1166 $out = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $out);
1167 $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'
1168 $out = preg_replace(array('/^[a-z]*\/\s*\/+/i'), '', $out); // We remove schema*// to remove external URL
1169 } while ($oldstringtoclean != $out);
1170 }
1171
1172 // Code for search criteria persistence.
1173 // Save data into session if key start with 'search_'
1174 if (empty($method) || $method == 3 || $method == 4) {
1175 if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder', 'sortfield'))) {
1176 //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]);
1177
1178 // We save search key only if $out not empty that means:
1179 // - posted value not empty, or
1180 // - 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).
1181
1182 if ($out != '' && isset($user)) {// $out = '0' or 'abc', it is a search criteria to keep
1183 $user->lastsearch_values_tmp[$relativepathstring][$paramname] = $out;
1184 }
1185 }
1186 }
1187
1188 if ($paramname == 'hashp' && $out == 'shared') {
1189 $out = ''; // We refuse to have hashp=shared as a parameter
1190 }
1191
1192 return $out;
1193}
1194
1204function GETPOSTINT($paramname, $method = 0)
1205{
1206 return (int) GETPOST($paramname, 'int', $method, null, null, 0);
1207}
1208
1217function GETPOSTFLOAT($paramname, $rounding = '')
1218{
1219 // 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.)
1220 return (float) price2num(GETPOST($paramname), $rounding, 2);
1221}
1222
1238function GETPOSTDATE($prefix, $hourTime = '', $gm = 'auto', $saverestore = '')
1239{
1240 $m = array();
1241 if ($hourTime === 'getpost' || $hourTime === 'getpostend') {
1242 $hour = (GETPOSTISSET($prefix . 'hour') && GETPOSTINT($prefix . 'hour') >= 0) ? GETPOSTINT($prefix . 'hour') : ($hourTime === 'getpostend' ? 23 : 0);
1243 $minute = (GETPOSTISSET($prefix . 'min') && GETPOSTINT($prefix . 'min') >= 0) ? GETPOSTINT($prefix . 'min') : ($hourTime === 'getpostend' ? 59 : 0);
1244 $second = (GETPOSTISSET($prefix . 'sec') && GETPOSTINT($prefix . 'sec') >= 0) ? GETPOSTINT($prefix . 'sec') : ($hourTime === 'getpostend' ? 59 : 0);
1245 } elseif (preg_match('/^(\d\d):(\d\d):(\d\d)$/', $hourTime, $m)) {
1246 $hour = intval($m[1]);
1247 $minute = intval($m[2]);
1248 $second = intval($m[3]);
1249 } elseif ($hourTime === 'end') {
1250 $hour = 23;
1251 $minute = 59;
1252 $second = 59;
1253 } else {
1254 $hour = $minute = $second = 0;
1255 }
1256
1257 if (
1258 $saverestore
1259 && !GETPOSTISSET($prefix . 'day')
1260 && !GETPOSTISSET($prefix . 'month')
1261 && !GETPOSTISSET($prefix . 'year')
1262 && isset($_SESSION['DOLDATE_' . $saverestore . '_day'])
1263 && isset($_SESSION['DOLDATE_' . $saverestore . '_month'])
1264 && isset($_SESSION['DOLDATE_' . $saverestore . '_year'])
1265 ) {
1266 $day = $_SESSION['DOLDATE_'.$saverestore.'_day'];
1267 $month = $_SESSION['DOLDATE_'.$saverestore.'_month'];
1268 $year = $_SESSION['DOLDATE_'.$saverestore.'_year'];
1269 } else {
1270 $month = GETPOSTINT($prefix . 'month');
1271 $day = GETPOSTINT($prefix . 'day');
1272 $year = GETPOSTINT($prefix . 'year');
1273 }
1274
1275 // normalize out of range values
1276 $hour = (int) min($hour, 23);
1277 $minute = (int) min($minute, 59);
1278 $second = (int) min($second, 59);
1279
1280 if ($saverestore) {
1281 $_SESSION['DOLDATE_'.$saverestore.'_day'] = $day;
1282 $_SESSION['DOLDATE_'.$saverestore.'_month'] = $month;
1283 $_SESSION['DOLDATE_'.$saverestore.'_year'] = $year;
1284 }
1285
1286 //print "$hour, $minute, $second, $month, $day, $year, $gm<br>";
1287 return dol_mktime($hour, $minute, $second, $month, $day, $year, $gm);
1288}
1289
1290
1301function checkVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
1302{
1303 return sanitizeVal($out, $check, $filter, $options);
1304}
1305
1315function sanitizeVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
1316{
1317 // TODO : use class "Validate" to perform tests (and add missing tests) if needed for factorize
1318 // Check is done after replacement
1319 if ($out === null) {
1320 $out = '';
1321 }
1322 switch ($check) {
1323 case 'none':
1324 case 'password':
1325 break;
1326 case 'int': // Check param is a numeric value (integer but also float or hexadecimal)
1327 if (!is_numeric($out)) {
1328 $out = '';
1329 }
1330 break;
1331 case 'intcomma':
1332 if (is_array($out)) {
1333 $out = implode(',', $out);
1334 }
1335 if (preg_match('/[^0-9,-]+/i', $out)) {
1336 $out = '';
1337 }
1338 break;
1339 case 'san_alpha':
1340 $out = filter_var($out, FILTER_SANITIZE_STRING);
1341 break;
1342 case 'email':
1343 $out = filter_var($out, FILTER_SANITIZE_EMAIL);
1344 break;
1345 case 'url':
1346 //$out = filter_var($out, FILTER_SANITIZE_URL); // Not reliable, replaced with FILTER_VALIDATE_URL
1347 $out = preg_replace('/[^:\/\[\]a-z0-9@\$\'\*\~\.\-_,;\?\!=%&+#]+/i', '', $out);
1348 // TODO Allow ( ) but only into password of https://login:password@domain...
1349 break;
1350 case 'aZ':
1351 if (!is_array($out)) {
1352 $out = trim($out);
1353 if (preg_match('/[^a-z]+/i', $out)) {
1354 $out = '';
1355 }
1356 }
1357 break;
1358 case 'aZ09':
1359 if (!is_array($out)) {
1360 $out = trim($out);
1361 if (preg_match('/[^a-z0-9_\-\.]+/i', $out)) {
1362 $out = '';
1363 }
1364 }
1365 break;
1366 case 'aZ09arobase': // great to sanitize $objecttype parameter
1367 if (!is_array($out)) {
1368 $out = trim($out);
1369 if (preg_match('/[^a-z0-9_\-\.@]+/i', $out)) {
1370 $out = '';
1371 }
1372 }
1373 break;
1374 case 'aZ09comma': // great to sanitize $sortfield or $sortorder params that can be 't.abc,t.def_gh'
1375 if (!is_array($out)) {
1376 $out = trim($out);
1377 if (preg_match('/[^a-z0-9_\-\.,]+/i', $out)) {
1378 $out = '';
1379 }
1380 }
1381 break;
1382 case 'alpha': // No html and no ../ and "
1383 case 'alphanohtml': // Recommended for most scalar parameters and search parameters. Not valid for json string.
1384 if (!is_array($out)) {
1385 $out = trim($out);
1386 do {
1387 $oldstringtoclean = $out;
1388 // Remove html tags
1389 $out = dol_string_nohtmltag($out, 0);
1390 // 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).
1391 $out = preg_replace('/\\\‍([0-9xu])/', '/\1', $out);
1392 // Remove also other dangerous string sequences
1393 // '../' or '..\' is dangerous because it allows dir transversals
1394 // '&#38', '&#0000038', '&#x26'... is a the char '&' alone but there is no reason to accept such way to encode input char
1395 // '"' = '&#34' = '&#0000034' = '&#x22' is dangerous because param in url can close the href= or src= and add javascript functions.
1396 // '&#47', '&#0000047', '&#x2F' is the char '/' but there is no reason to accept such way to encode this input char
1397 // '&#92' = '&#0000092' = '&#x5C' is the char '\' but there is no reason to accept such way to encode this input char
1398 $out = str_ireplace(array('../', '..\\', '&#38', '&#0000038', '&#x26', '&quot', '"', '&#34', '&#0000034', '&#x22', '&#47', '&#0000047', '&#x2F', '&#92', '&#0000092', '&#x5C'), '', $out);
1399 } while ($oldstringtoclean != $out);
1400 // keep lines feed
1401 }
1402 break;
1403 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'
1404 if (!is_array($out)) {
1405 $out = trim($out);
1406 do {
1407 $oldstringtoclean = $out;
1408 // Decode html entities
1409 $out = dol_html_entity_decode($out, ENT_COMPAT | ENT_HTML5, 'UTF-8');
1410 // 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).
1411 $out = preg_replace('/\\\‍([0-9xu])/', '/\1', $out);
1412 // Remove also other dangerous string sequences
1413 // '../' or '..\' is dangerous because it allows dir transversals
1414 // '&#38', '&#0000038', '&#x26'... is a the char '&' alone but there is no reason to accept such way to encode input char
1415 // '"' = '&#34' = '&#0000034' = '&#x22' is dangerous because param in url can close the href= or src= and add javascript functions.
1416 // '&#47', '&#0000047', '&#x2F' is the char '/' but there is no reason to accept such way to encode this input char
1417 // '&#92' = '&#0000092' = '&#x5C' is the char '\' but there is no reason to accept such way to encode this input char
1418 $out = str_ireplace(array('../', '..\\', '&#38', '&#0000038', '&#x26', '&quot', '"', '&#34', '&#0000034', '&#x22', '&#47', '&#0000047', '&#x2F', '&#92', '&#0000092', '&#x5C'), '', $out);
1419 } while ($oldstringtoclean != $out);
1420 }
1421 break;
1422 case 'nohtml': // No html. Valid for JSON strings.
1423 $out = dol_string_nohtmltag($out, 0);
1424 break;
1425 case 'restricthtmlnolink':
1426 case 'restricthtml': // Recommended for most html textarea
1427 case 'restricthtmlallowclass':
1428 case 'restricthtmlallowiframe':
1429 case 'restricthtmlallowlinkscript': // Allow link and script tag for head section.
1430 case 'restricthtmlallowunvalid':
1431 $out = dol_htmlwithnojs($out, 1, $check);
1432 break;
1433 case 'custom':
1434 if (!empty($out)) {
1435 if (empty($filter)) {
1436 return 'BadParameterForGETPOST - Param 3 of sanitizeVal()';
1437 }
1438 if (is_null($options)) {
1439 $options = 0;
1440 }
1441 $out = filter_var($out, $filter, $options);
1442 }
1443 break;
1444 default:
1445 dol_syslog("Error, you call sanitizeVal() with a bad value for the check type. Data will be sanitized with alphanohtml.", LOG_ERR);
1446 $out = GETPOST($out, 'alphanohtml');
1447 break;
1448 }
1449
1450 return $out;
1451}
1452
1461function dolSetCookie(string $cookiename, string $cookievalue, int $expire = -1)
1462{
1463 global $dolibarr_main_force_https;
1464
1465 if ($expire == -1) {
1466 $expire = (time() + (86400 * 354)); // keep cookie 1 year.
1467 }
1468
1469 if (PHP_VERSION_ID < 70300) {
1470 setcookie($cookiename, empty($cookievalue) ? '' : $cookievalue, empty($cookievalue) ? 0 : $expire, '/', '', !(empty($dolibarr_main_force_https) && isHTTPS() === false), true); // add tag httponly
1471 } else {
1472 // Only available for php >= 7.3
1473 $cookieparams = array(
1474 'expires' => empty($cookievalue) ? 0 : $expire,
1475 'path' => '/',
1476 //'domain' => '.mywebsite.com', // the dot at the beginning allows compatibility with subdomains
1477 'secure' => !(empty($dolibarr_main_force_https) && isHTTPS() === false),
1478 'httponly' => true,
1479 'samesite' => 'Lax' // None || Lax || Strict
1480 );
1481 setcookie($cookiename, empty($cookievalue) ? '' : $cookievalue, $cookieparams);
1482 }
1483 if (empty($cookievalue)) {
1484 unset($_COOKIE[$cookiename]);
1485 }
1486}
1487
1488if (!function_exists('dol_getprefix')) {
1499 function dol_getprefix($mode = '')
1500 {
1501 // If prefix is for email (we need to have $conf already loaded for this case)
1502 if ($mode == 'email') {
1503 global $conf;
1504
1505 if (getDolGlobalString('MAIL_PREFIX_FOR_EMAIL_ID')) { // If MAIL_PREFIX_FOR_EMAIL_ID is set
1506 if (getDolGlobalString('MAIL_PREFIX_FOR_EMAIL_ID') != 'SERVER_NAME') {
1507 return getDolGlobalString('MAIL_PREFIX_FOR_EMAIL_ID');
1508 } elseif (isset($_SERVER["SERVER_NAME"])) { // If MAIL_PREFIX_FOR_EMAIL_ID is set to 'SERVER_NAME'
1509 return $_SERVER["SERVER_NAME"];
1510 }
1511 }
1512
1513 // The recommended value if MAIL_PREFIX_FOR_EMAIL_ID is not defined (may be not defined for old versions)
1514 if (!empty($conf->file->instance_unique_id)) {
1515 return sha1('dolibarr'.$conf->file->instance_unique_id);
1516 }
1517
1518 // For backward compatibility when instance_unique_id is not set
1519 return sha1(DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
1520 }
1521
1522 // If prefix is for session (no need to have $conf loaded)
1523 global $dolibarr_main_instance_unique_id, $dolibarr_main_cookie_cryptkey; // This is loaded by filefunc.inc.php
1524 $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
1525
1526 // The recommended value (may be not defined for old versions)
1527 if (!empty($tmp_instance_unique_id)) {
1528 return sha1('dolibarr'.$tmp_instance_unique_id);
1529 }
1530
1531 // For backward compatibility when instance_unique_id is not set
1532 if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"])) {
1533 return sha1($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
1534 } else {
1535 return sha1(DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
1536 }
1537 }
1538}
1539
1550function dol_include_once($relpath, $classname = '')
1551{
1552 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']
1553
1554 $fullpath = dol_buildpath($relpath);
1555
1556 if (!file_exists($fullpath)) {
1557 dol_syslog('functions::dol_include_once Tried to load unexisting file: '.$relpath, LOG_WARNING);
1558 return false;
1559 }
1560 if (!empty($classname) && !class_exists($classname)) {
1561 return include $fullpath;
1562 } else {
1563 return include_once $fullpath;
1564 }
1565}
1566
1567
1581function dol_buildpath($path, $type = 0, $returnemptyifnotfound = 0)
1582{
1583 global $conf;
1584
1585 $path = preg_replace('/^\//', '', $path);
1586
1587 if (empty($type)) { // For a filesystem path
1588 $res = DOL_DOCUMENT_ROOT.'/'.$path; // Standard default path
1589 if (is_array($conf->file->dol_document_root)) {
1590 foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array("main"=>"/home/main/htdocs", "alt0"=>"/home/dirmod/htdocs", ...)
1591 if ($key == 'main') {
1592 continue;
1593 }
1594 // if (@file_exists($dirroot.'/'.$path)) {
1595 if (@file_exists($dirroot.'/'.$path)) { // avoid [php:warn]
1596 $res = $dirroot.'/'.$path;
1597 return $res;
1598 }
1599 }
1600 }
1601 if ($returnemptyifnotfound) {
1602 // Not found into alternate dir
1603 if ($returnemptyifnotfound == 1 || !file_exists($res)) {
1604 return '';
1605 }
1606 }
1607 } else {
1608 // For an url path
1609 // We try to get local path of file on filesystem from url
1610 // Note that trying to know if a file on disk exist by forging path on disk from url
1611 // works only for some web server and some setup. This is bugged when
1612 // using proxy, rewriting, virtual path, etc...
1613 $res = '';
1614 if ($type == 1) {
1615 $res = DOL_URL_ROOT.'/'.$path; // Standard value
1616 }
1617 if ($type == 2) {
1618 $res = DOL_MAIN_URL_ROOT.'/'.$path; // Standard value
1619 }
1620 if ($type == 3) {
1621 $res = DOL_URL_ROOT.'/'.$path;
1622 }
1623
1624 foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
1625 if ($key == 'main') {
1626 if ($type == 3) {
1627 /*global $dolibarr_main_url_root;*/
1628
1629 // Define $urlwithroot
1630 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($conf->file->dol_main_url_root));
1631 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
1632 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
1633
1634 $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : $urlwithroot).'/'.$path; // Test on start with http is for old conf syntax
1635 }
1636 continue;
1637 }
1638 $regs = array();
1639 preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i', $path, $regs); // Take part before '?'
1640 if (!empty($regs[1])) {
1641 //print $key.'-'.$dirroot.'/'.$path.'-'.$conf->file->dol_url_root[$type].'<br>'."\n";
1642 //if (file_exists($dirroot.'/'.$regs[1])) {
1643 if (@file_exists($dirroot.'/'.$regs[1])) { // avoid [php:warn]
1644 if ($type == 1) {
1645 $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
1646 } elseif ($type == 2) {
1647 $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_MAIN_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
1648 } elseif ($type == 3) {
1649 /*global $dolibarr_main_url_root;*/
1650
1651 // Define $urlwithroot
1652 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($conf->file->dol_main_url_root));
1653 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
1654 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
1655
1656 $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
1657 }
1658 break;
1659 }
1660 }
1661 }
1662 }
1663
1664 return $res;
1665}
1666
1677function dol_get_object_properties($obj, $properties = [])
1678{
1679 // Get real properties using get_object_vars() if $properties is empty
1680 if (empty($properties)) {
1681 return get_object_vars($obj);
1682 }
1683
1684 $existingProperties = [];
1685 $realProperties = get_object_vars($obj);
1686
1687 // Get the real or magic property values
1688 foreach ($properties as $property) {
1689 if (array_key_exists($property, $realProperties)) {
1690 // Real property, add the value
1691 $existingProperties[$property] = $obj->{$property};
1692 } elseif (property_exists($obj, $property)) {
1693 // Magic property
1694 $existingProperties[$property] = $obj->{$property};
1695 }
1696 }
1697
1698 return $existingProperties;
1699}
1700
1701
1717function dol_clone($object, $native = 2)
1718{
1719 if ($native == 0) {
1720 // deprecated method, use the method with native = 2 instead
1721 $tmpsavdb = null;
1722 if (isset($object->db) && isset($object->db->db) && is_object($object->db->db) && get_class($object->db->db) == 'PgSql\Connection') {
1723 $tmpsavdb = $object->db;
1724 unset($object->db); // Such property can not be serialized with pgsl (when object->db->db = 'PgSql\Connection')
1725 }
1726
1727 $myclone = unserialize(serialize($object)); // serialize then unserialize is a hack to be sure to have a new object for all fields
1728
1729 if (!empty($tmpsavdb)) {
1730 $object->db = $tmpsavdb;
1731 }
1732 } elseif ($native == 2) {
1733 // recommended method to have a full isolated cloned object
1734 $myclone = new stdClass();
1735 $tmparray = get_object_vars($object); // return only public properties
1736
1737 if (is_array($tmparray)) {
1738 foreach ($tmparray as $propertykey => $propertyval) {
1739 if (is_scalar($propertyval) || is_array($propertyval)) {
1740 $myclone->$propertykey = $propertyval;
1741 }
1742 }
1743 }
1744 } else {
1745 $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)
1746 }
1747
1748 return $myclone;
1749}
1750
1760function dol_size($size, $type = '')
1761{
1762 global $conf;
1763 if (empty($conf->dol_optimize_smallscreen)) {
1764 return $size;
1765 }
1766 if ($type == 'width' && $size > 250) {
1767 return 250;
1768 } else {
1769 return 10;
1770 }
1771}
1772
1773
1786function dol_sanitizeFileName($str, $newstr = '_', $unaccent = 1, $includequotes = 0)
1787{
1788 // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
1789 // Char '>' '<' '|' '$' and ';' are special chars for shells.
1790 // Char '/' and '\' are file delimiters.
1791 // 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
1792 $filesystem_forbidden_chars = array('<', '>', '/', '\\', '?', '*', '|', '"', ':', '°', '$', ';', '`');
1793 if ($includequotes) {
1794 $filesystem_forbidden_chars[] = "'";
1795 }
1796 $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
1797 $tmp = preg_replace('/\-\-+/', '_', $tmp);
1798 $tmp = preg_replace('/\s+\-([^\s])/', ' _$1', $tmp);
1799 $tmp = preg_replace('/\s+\-$/', '', $tmp);
1800 $tmp = str_replace('..', '', $tmp);
1801 $tmp = preg_replace('/\s{2,}/', ' ', $tmp);
1802
1803 return $tmp;
1804}
1805
1806
1818function dol_sanitizePathName($str, $newstr = '_', $unaccent = 1)
1819{
1820 // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
1821 // Char '>' '<' '|' '$' and ';' are special chars for shells.
1822 // 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
1823 $filesystem_forbidden_chars = array('<', '>', '?', '*', '|', '"', '°', '$', ';', '`');
1824
1825 $tmp = $str;
1826 if ($unaccent) {
1827 $tmp = dol_string_unaccent($tmp);
1828 }
1829 $tmp = dol_string_nospecial($tmp, $newstr, $filesystem_forbidden_chars);
1830 $tmp = preg_replace('/\-\-+/', '_', $tmp);
1831 $tmp = preg_replace('/\s+\-([^\s])/', ' _$1', $tmp);
1832 $tmp = preg_replace('/\s+\-$/', '', $tmp);
1833 $tmp = str_replace('..', '', $tmp);
1834 $tmp = preg_replace('/\s{2,}/', ' ', $tmp);
1835
1836 return $tmp;
1837}
1838
1846function dol_sanitizeUrl($stringtoclean, $type = 1)
1847{
1848 // 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)
1849 // We should use dol_string_nounprintableascii but function may not be yet loaded/available
1850 $stringtoclean = preg_replace('/[\x00-\x1F\x7F]/u', '', $stringtoclean); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
1851 // We clean html comments because some hacks try to obfuscate evil strings by inserting HTML comments. Example: on<!-- -->error=alert(1)
1852 $stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
1853
1854 $stringtoclean = str_replace('\\', '/', $stringtoclean);
1855 if ($type == 1) {
1856 // removing : should disable links to external url like http:aaa)
1857 // removing ';' should disable "named" html entities encode into an url (we should not have this into an url)
1858 $stringtoclean = str_replace(array(':', ';', '@'), '', $stringtoclean);
1859 }
1860
1861 do {
1862 $oldstringtoclean = $stringtoclean;
1863 // removing '&colon' should disable links to external url like http:aaa)
1864 // removing '&#' should disable "numeric" html entities encode into an url (we should not have this into an url)
1865 $stringtoclean = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $stringtoclean);
1866 } while ($oldstringtoclean != $stringtoclean);
1867
1868 if ($type == 1) {
1869 // removing '//' should disable links to external url like //aaa or http//)
1870 $stringtoclean = preg_replace(array('/^[a-z]*\/\/+/i'), '', $stringtoclean);
1871 }
1872
1873 return $stringtoclean;
1874}
1875
1882function dol_sanitizeEmail($stringtoclean)
1883{
1884 do {
1885 $oldstringtoclean = $stringtoclean;
1886 $stringtoclean = str_ireplace(array('"', ':', '[', ']',"\n", "\r", '\\', '\/'), '', $stringtoclean);
1887 } while ($oldstringtoclean != $stringtoclean);
1888
1889 return $stringtoclean;
1890}
1891
1900function dol_sanitizeKeyCode($str)
1901{
1902 return preg_replace('/[^\w]+/', '', $str);
1903}
1904
1905
1914function dol_string_unaccent($str)
1915{
1916 if (is_null($str)) {
1917 return '';
1918 }
1919
1920 if (utf8_check($str)) {
1921 if (extension_loaded('intl') && getDolGlobalString('MAIN_UNACCENT_USE_TRANSLITERATOR')) {
1922 $transliterator = Transliterator::createFromRules(':: Any-Latin; :: Latin-ASCII; :: NFD; :: [:Nonspacing Mark:] Remove; :: NFC;', Transliterator::FORWARD);
1923 return $transliterator->transliterate($str);
1924 }
1925 // See http://www.utf8-chartable.de/
1926 $string = rawurlencode($str);
1927 $replacements = array(
1928 '%C3%80' => 'A', '%C3%81' => 'A', '%C3%82' => 'A', '%C3%83' => 'A', '%C3%84' => 'A', '%C3%85' => 'A',
1929 '%C3%87' => 'C',
1930 '%C3%88' => 'E', '%C3%89' => 'E', '%C3%8A' => 'E', '%C3%8B' => 'E',
1931 '%C3%8C' => 'I', '%C3%8D' => 'I', '%C3%8E' => 'I', '%C3%8F' => 'I',
1932 '%C3%91' => 'N',
1933 '%C3%92' => 'O', '%C3%93' => 'O', '%C3%94' => 'O', '%C3%95' => 'O', '%C3%96' => 'O', '%C5%90' => 'O',
1934 '%C5%A0' => 'S',
1935 '%C3%99' => 'U', '%C3%9A' => 'U', '%C3%9B' => 'U', '%C3%9C' => 'U', '%C5%B0' => 'U',
1936 '%C3%9D' => 'Y', '%C5%B8' => 'y',
1937 '%C3%A0' => 'a', '%C3%A1' => 'a', '%C3%A2' => 'a', '%C3%A3' => 'a', '%C3%A4' => 'a', '%C3%A5' => 'a',
1938 '%C3%A7' => 'c',
1939 '%C3%A8' => 'e', '%C3%A9' => 'e', '%C3%AA' => 'e', '%C3%AB' => 'e',
1940 '%C3%AC' => 'i', '%C3%AD' => 'i', '%C3%AE' => 'i', '%C3%AF' => 'i',
1941 '%C3%B1' => 'n',
1942 '%C3%B2' => 'o', '%C3%B3' => 'o', '%C3%B4' => 'o', '%C3%B5' => 'o', '%C3%B6' => 'o', '%C5%91' => 'o',
1943 '%C5%A1' => 's',
1944 '%C3%B9' => 'u', '%C3%BA' => 'u', '%C3%BB' => 'u', '%C3%BC' => 'u', '%C5%B1' => 'u',
1945 '%C3%BD' => 'y', '%C3%BF' => 'y'
1946 );
1947 $string = strtr($string, $replacements);
1948 return rawurldecode($string);
1949 } else {
1950 // See http://www.ascii-code.com/
1951 $string = strtr(
1952 $str,
1953 "\xC0\xC1\xC2\xC3\xC4\xC5\xC7
1954 \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
1955 \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
1956 \xE0\xE1\xE2\xE3\xE4\xE5\xE7\xE8\xE9\xEA\xEB
1957 \xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
1958 \xF9\xFA\xFB\xFC\xFD\xFF",
1959 "AAAAAAC
1960 EEEEIIIIDN
1961 OOOOOUUUY
1962 aaaaaaceeee
1963 iiiidnooooo
1964 uuuuyy"
1965 );
1966 $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"));
1967 return $string;
1968 }
1969}
1970
1984function dol_string_nospecial($str, $newstr = '_', $badcharstoreplace = '', $badcharstoremove = '', $keepspaces = 0)
1985{
1986 $forbidden_chars_to_replace = array("'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°', '$', ';'); // more complete than dol_sanitizeFileName
1987 if (empty($keepspaces)) {
1988 $forbidden_chars_to_replace[] = " ";
1989 }
1990 $forbidden_chars_to_remove = array();
1991 //$forbidden_chars_to_remove=array("(",")");
1992
1993 if (is_array($badcharstoreplace)) {
1994 $forbidden_chars_to_replace = $badcharstoreplace;
1995 }
1996 if (is_array($badcharstoremove)) {
1997 $forbidden_chars_to_remove = $badcharstoremove;
1998 }
1999
2000 // @phan-suppress-next-line PhanPluginSuspiciousParamOrderInternal
2001 return str_replace($forbidden_chars_to_replace, $newstr, str_replace($forbidden_chars_to_remove, "", $str));
2002}
2003
2004
2018function dol_string_nounprintableascii($str, $removetabcrlf = 1)
2019{
2020 if ($removetabcrlf) {
2021 return preg_replace('/[\x00-\x1F\x7F]/u', '', $str); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
2022 } else {
2023 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
2024 }
2025}
2026
2033function dolSlugify($stringtoslugify)
2034{
2035 $slug = dol_string_unaccent($stringtoslugify);
2036
2037 // Convert special characters to their ASCII equivalents
2038 if (function_exists('iconv')) {
2039 $slug = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $slug);
2040 }
2041
2042 // Convert to lowercase
2043 $slug = strtolower($slug);
2044
2045 // Replace non-alphanumeric characters with hyphens
2046 $slug = preg_replace('/[^a-z0-9]+/', '-', $slug);
2047
2048 // Remove leading and trailing hyphens
2049 $slug = trim($slug, '-');
2050
2051 return $slug;
2052}
2053
2062function dol_escape_js($stringtoescape, $mode = 0, $noescapebackslashn = 0)
2063{
2064 if (is_null($stringtoescape)) {
2065 return '';
2066 }
2067
2068 // escape quotes and backslashes, newlines, etc.
2069 $substitjs = array("&#039;" => "\\'", "\r" => '\\r');
2070 //$substitjs['</']='<\/'; // We removed this. Should be useless.
2071 if (empty($noescapebackslashn)) {
2072 $substitjs["\n"] = '\\n';
2073 $substitjs['\\'] = '\\\\';
2074 }
2075 if (empty($mode)) {
2076 $substitjs["'"] = "\\'";
2077 $substitjs['"'] = "\\'";
2078 } elseif ($mode == 1) {
2079 $substitjs["'"] = "\\'";
2080 } elseif ($mode == 2) {
2081 $substitjs['"'] = '\\"';
2082 } elseif ($mode == 3) {
2083 $substitjs["'"] = "\\'";
2084 $substitjs['"'] = "\\\"";
2085 }
2086 return strtr((string) $stringtoescape, $substitjs);
2087}
2088
2098function dol_escape_uri($stringtoescape)
2099{
2100 return rawurlencode($stringtoescape);
2101}
2102
2109function dol_escape_json($stringtoescape)
2110{
2111 return str_replace('"', '\"', $stringtoescape);
2112}
2113
2121function dol_escape_php($stringtoescape, $stringforquotes = 2)
2122{
2123 if (is_null($stringtoescape)) {
2124 return '';
2125 }
2126
2127 if ($stringforquotes == 2) {
2128 return str_replace('"', "'", $stringtoescape);
2129 } elseif ($stringforquotes == 1) {
2130 // We remove the \ char.
2131 // If we allow the \ char, we can have $stringtoescape =
2132 // abc\';phpcodedanger; so the escapement will become
2133 // abc\\';phpcodedanger; and injecting this into
2134 // $a='...' will give $ac='abc\\';phpcodedanger;
2135 $stringtoescape = str_replace('\\', '', $stringtoescape);
2136 return str_replace("'", "\'", str_replace('"', "'", $stringtoescape));
2137 }
2138
2139 return 'Bad parameter for stringforquotes in dol_escape_php';
2140}
2141
2148function dol_escape_all($stringtoescape)
2149{
2150 return preg_replace('/[^a-z0-9_]/i', '', $stringtoescape);
2151}
2152
2159function dol_escape_xml($stringtoescape)
2160{
2161 $stringtoescape = (string) preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', '', (string) $stringtoescape); // Characters not allowed in XML 1.0
2162
2163 return htmlspecialchars($stringtoescape, ENT_XML1 | ENT_QUOTES, 'UTF-8');
2164}
2165
2175function dolPrintLabel($s, $escapeonlyhtmltags = 0)
2176{
2177 return dol_escape_htmltag(dol_string_nohtmltag($s, 1, 'UTF-8', 0, 0), 0, 0, '', $escapeonlyhtmltags, 1);
2178}
2179
2188function dolPrintText($s)
2189{
2190 return dol_escape_htmltag(dol_string_nohtmltag($s, 2, 'UTF-8', 0, 0), 0, 1, '', 0, 1);
2191}
2192
2203function dolPrintHTML($s, $allowiframe = 0)
2204{
2205 // If text is already HTML, we want to escape only dangerous chars else we want to escape all content.
2206 //$isAlreadyHTML = dol_textishtml($s);
2207
2208 // dol_htmlentitiesbr encode all chars except "'" if string is not already HTML, but
2209 // encode only special char like é but not &, <, >, ", ' if already HTML.
2210 $stringWithEntitesForSpecialChar = dol_htmlentitiesbr((string) $s);
2211
2212 return dol_escape_htmltag(dol_htmlwithnojs(dol_string_onlythesehtmltags($stringWithEntitesForSpecialChar, 1, 1, 1, $allowiframe)), 1, 1, 'common', 0, 1);
2213}
2214
2225function dolPrintHTMLForAttribute($s, $escapeonlyhtmltags = 0, $allowothertags = array())
2226{
2227 $allowedtags = array('br', 'b', 'font', 'hr', 'span');
2228 if (!empty($allowothertags) && is_array($allowothertags)) {
2229 $allowedtags = array_merge($allowedtags, $allowothertags);
2230 }
2231 // The dol_htmlentitiesbr will convert simple text into html, including switching accent into HTML entities
2232 // The dol_escape_htmltag will escape html tags.
2233 if ($escapeonlyhtmltags) {
2234 return dol_escape_htmltag(dol_string_onlythesehtmltags($s, 1, 0, 0, 0, $allowedtags), 1, -1, '', 1, 1);
2235 } else {
2236 return dol_escape_htmltag(dol_string_onlythesehtmltags(dol_htmlentitiesbr($s), 1, 0, 0, 0, $allowedtags), 1, -1, '', 0, 1);
2237 }
2238}
2239
2248function dolPrintHTMLForAttributeUrl($s)
2249{
2250 // The dol_htmlentitiesbr has been removed compared to dolPrintHTMLForAttribute because we know content is a HTML URL string (even if we have no way to detect it automatically)
2251 // The dol_escape_htmltag will escape html chars.
2252 $escapeonlyhtmltags = 1;
2253 return dol_escape_htmltag(dol_string_onlythesehtmltags($s, 1, 1, 1, 0, array()), 0, 0, '', $escapeonlyhtmltags, 1);
2254}
2255
2265function dolPrintHTMLForTextArea($s, $allowiframe = 0)
2266{
2267 return dol_escape_htmltag(dol_htmlwithnojs(dol_string_onlythesehtmltags(dol_htmlentitiesbr($s), 1, 1, 1, $allowiframe)), 1, 1, '', 0, 1);
2268}
2269
2276function dolPrintPassword($s)
2277{
2278 return htmlspecialchars($s, ENT_HTML5, 'UTF-8');
2279}
2280
2281
2298function dol_escape_htmltag($stringtoescape, $keepb = 0, $keepn = 0, $noescapetags = '', $escapeonlyhtmltags = 0, $cleanalsojavascript = 0)
2299{
2300 if ($noescapetags == 'common') {
2301 $noescapetags = 'html,body,a,b,em,hr,i,u,ul,ol,li,br,div,img,font,p,span,strong,table,tr,td,th,tbody,h1,h2,h3,h4,h5,h6,h7,h8,h9';
2302 // Add also html5 tags
2303 $noescapetags .= ',header,footer,nav,section,menu,menuitem';
2304 }
2305 if ($cleanalsojavascript) {
2306 $stringtoescape = dol_string_onlythesehtmltags($stringtoescape, 0, 0, $cleanalsojavascript, 0, array(), 0);
2307 }
2308
2309 // escape quotes and backslashes, newlines, etc.
2310 if ($escapeonlyhtmltags) {
2311 $tmp = htmlspecialchars_decode((string) $stringtoescape, ENT_COMPAT);
2312 } else {
2313 // We make a manipulation by calling the html_entity_decode() to convert content into NON HTML UTF8 string.
2314 // Because content can be or not already HTML.
2315 // For example, this decode &egrave; into è so string is UTF8 (but numbers entities like &#39; is not decoded).
2316 // In a future, we should not need this
2317
2318 $tmp = (string) $stringtoescape;
2319
2320 // We protect the 6 special entities that we don't want to decode.
2321 $tmp = str_ireplace('&lt', '__DONOTDECODELT', $tmp);
2322 $tmp = str_ireplace('&gt', '__DONOTDECODEGT', $tmp);
2323 $tmp = str_ireplace('&amp', '__DONOTDECODEAMP', $tmp);
2324 $tmp = str_ireplace('&quot', '__DONOTDECODEQUOT', $tmp);
2325 $tmp = str_ireplace('&apos', '__DONOTDECODEAPOS', $tmp);
2326 $tmp = str_ireplace('&#39', '__DONOTDECODE39', $tmp);
2327
2328 $tmp = html_entity_decode((string) $tmp, ENT_COMPAT, 'UTF-8'); // Convert entities into UTF8
2329
2330 // We restore the 6 special entities that we don't want to have been decoded by previous command
2331 $tmp = str_ireplace('__DONOTDECODELT', '&lt', $tmp);
2332 $tmp = str_ireplace('__DONOTDECODEGT', '&gt', $tmp);
2333 $tmp = str_ireplace('__DONOTDECODEAMP', '&amp', $tmp);
2334 $tmp = str_ireplace('__DONOTDECODEQUOT', '&quot', $tmp);
2335 $tmp = str_ireplace('__DONOTDECODEAPOS', '&apos', $tmp);
2336 $tmp = str_ireplace('__DONOTDECODE39', '&#39', $tmp);
2337
2338 $tmp = str_ireplace('&#39;', '__SIMPLEQUOTE__', $tmp); // HTML 4
2339 }
2340 if (!$keepb) {
2341 $tmp = strtr($tmp, array("<b>" => '', '</b>' => '', '<strong>' => '', '</strong>' => ''));
2342 }
2343 if (!$keepn) {
2344 $tmp = strtr($tmp, array("\r" => '\\r', "\n" => '\\n'));
2345 } elseif ($keepn == -1) {
2346 $tmp = strtr($tmp, array("\r" => '', "\n" => ''));
2347 }
2348
2349 if ($escapeonlyhtmltags) {
2350 $tmp = htmlspecialchars($tmp, ENT_COMPAT, 'UTF-8');
2351 return $tmp;
2352 } else {
2353 // Now we protect all the tags we want to keep
2354 $tmparrayoftags = array();
2355 if ($noescapetags) {
2356 $tmparrayoftags = explode(',', $noescapetags);
2357 }
2358
2359 if (count($tmparrayoftags)) {
2360 // Now we will protect tags (defined into $tmparrayoftags) that we want to keep untouched
2361
2362 $reg = array();
2363 // Remove reserved keywords. They are forbidden in a source string
2364 $tmp = str_ireplace(array('__DOUBLEQUOTE', '__BEGINTAGTOREPLACE', '__ENDTAGTOREPLACE', '__BEGINENDTAGTOREPLACE'), '', $tmp);
2365
2366 foreach ($tmparrayoftags as $tagtoreplace) {
2367 // For case of tag without attributes '<abc>', '</abc>', '<abc />', we protect them to avoid transformation by htmlentities() later
2368 $tmp = preg_replace('/<'.preg_quote($tagtoreplace, '/').'>/', '__BEGINTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
2369 $tmp = str_ireplace('</'.$tagtoreplace.'>', '__ENDTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
2370 $tmp = preg_replace('/<'.preg_quote($tagtoreplace, '/').' \/>/', '__BEGINENDTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
2371
2372 // For case of tag with attributes
2373 do {
2374 $tmpold = $tmp;
2375
2376 if (preg_match('/<'.preg_quote($tagtoreplace, '/').'(\s+)([^>]+)>/', $tmp, $reg)) {
2377 // We want to protect the attribute part ... in '<xxx ...>' to avoid transformation by htmlentities() later
2378 $tmpattributes = str_ireplace(array('[', ']'), '_', $reg[2]); // We must never have [ ] inside the attribute string
2379 $tmpattributes = str_ireplace('"', '__DOUBLEQUOTE__', $tmpattributes);
2380 $tmpattributes = preg_replace('/[^a-z0-9_%,\/\?\;\s=&\.\-@:\.#\+]/i', '', $tmpattributes);
2381 //$tmpattributes = preg_replace("/float:\s*(left|right)/", "", $tmpattributes); // Disabled: we must not remove content
2382 $tmp = str_replace('<'.$tagtoreplace.$reg[1].$reg[2].'>', '__BEGINTAGTOREPLACE'.$tagtoreplace.'['.$tmpattributes.']__', $tmp);
2383 }
2384
2385 $diff = strcmp($tmpold, $tmp);
2386 } while ($diff);
2387 }
2388
2389 $tmp = str_ireplace('&amp', '__ANDNOSEMICOLON__', $tmp);
2390 $tmp = str_ireplace('&quot', '__DOUBLEQUOTENOSEMICOLON__', $tmp);
2391 $tmp = str_ireplace('&lt', '__LESSTHAN__', $tmp);
2392 $tmp = str_ireplace('&gt', '__GREATERTHAN__', $tmp);
2393 }
2394
2395 // Warning: htmlentities encode all special chars that remains (except "'" with ENT_COMPAT).
2396 $result = htmlentities($tmp, ENT_COMPAT, 'UTF-8');
2397
2398 //print $result;
2399
2400 if (count($tmparrayoftags)) {
2401 // Restore protected tags
2402 foreach ($tmparrayoftags as $tagtoreplace) {
2403 $result = str_ireplace('__BEGINTAGTOREPLACE'.$tagtoreplace.'__', '<'.$tagtoreplace.'>', $result);
2404 $result = preg_replace('/__BEGINTAGTOREPLACE'.$tagtoreplace.'\[([^\]]*)\]__/', '<'.$tagtoreplace.' \1>', $result);
2405 $result = str_ireplace('__ENDTAGTOREPLACE'.$tagtoreplace.'__', '</'.$tagtoreplace.'>', $result);
2406 $result = str_ireplace('__BEGINENDTAGTOREPLACE'.$tagtoreplace.'__', '<'.$tagtoreplace.' />', $result);
2407 $result = preg_replace('/__BEGINENDTAGTOREPLACE'.$tagtoreplace.'\[([^\]]*)\]__/', '<'.$tagtoreplace.' \1 />', $result);
2408 }
2409
2410 $result = str_ireplace('__DOUBLEQUOTE__', '"', $result);
2411
2412 $result = str_ireplace('__ANDNOSEMICOLON__', '&amp', $result);
2413 $result = str_ireplace('__DOUBLEQUOTENOSEMICOLON__', '&quot', $result);
2414 $result = str_ireplace('__LESSTHAN__', '&lt', $result);
2415 $result = str_ireplace('__GREATERTHAN__', '&gt', $result);
2416 }
2417
2418 $result = str_ireplace('__SIMPLEQUOTE__', '&#39;', $result);
2419
2420 //$result="\n\n\n".var_export($tmp, true)."\n\n\n".var_export($result, true);
2421
2422 return $result;
2423 }
2424}
2425
2433function dol_strtolower($string, $encoding = "UTF-8")
2434{
2435 if (function_exists('mb_strtolower')) {
2436 return mb_strtolower($string, $encoding);
2437 } else {
2438 return strtolower($string);
2439 }
2440}
2441
2450function dol_strtoupper($string, $encoding = "UTF-8")
2451{
2452 if (function_exists('mb_strtoupper')) {
2453 return mb_strtoupper($string, $encoding);
2454 } else {
2455 return strtoupper($string);
2456 }
2457}
2458
2467function dol_ucfirst($string, $encoding = "UTF-8")
2468{
2469 if (function_exists('mb_substr')) {
2470 return mb_strtoupper(mb_substr($string, 0, 1, $encoding), $encoding).mb_substr($string, 1, null, $encoding);
2471 } else {
2472 return ucfirst($string);
2473 }
2474}
2475
2484function dol_ucwords($string, $encoding = "UTF-8")
2485{
2486 if (function_exists('mb_convert_case')) {
2487 return mb_convert_case($string, MB_CASE_TITLE, $encoding);
2488 } else {
2489 return ucwords($string);
2490 }
2491}
2492
2493
2499function getCallerInfoString()
2500{
2501 $backtrace = debug_backtrace();
2502 $msg = "";
2503 if (count($backtrace) >= 1) {
2504 $pos = 1;
2505 if (count($backtrace) == 1) {
2506 $pos = 0;
2507 }
2508 $trace = $backtrace[$pos];
2509 if (isset($trace['file'], $trace['line'])) {
2510 $msg = " From {$trace['file']}:{$trace['line']}.";
2511 }
2512 }
2513 return $msg;
2514}
2515
2538function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename = '', $restricttologhandler = '', $logcontext = null)
2539{
2540 global $conf, $user, $debugbar;
2541
2542 // If syslog module enabled
2543 if (!isModEnabled('syslog')) {
2544 return;
2545 }
2546
2547 // Check if we are into execution of code of a website
2548 if (defined('USEEXTERNALSERVER') && !defined('USEDOLIBARRSERVER') && !defined('USEDOLIBARREDITOR')) {
2549 global $website, $websitekey;
2550 if (is_object($website) && !empty($website->ref)) {
2551 $suffixinfilename .= '_website_'.$website->ref;
2552 } elseif (!empty($websitekey)) {
2553 $suffixinfilename .= '_website_'.$websitekey;
2554 }
2555 }
2556
2557 // Check if we have a forced suffix
2558 if (defined('USESUFFIXINLOG')) {
2559 $suffixinfilename .= constant('USESUFFIXINLOG');
2560 }
2561
2562 if ($ident < 0) {
2563 foreach ($conf->loghandlers as $loghandlerinstance) {
2564 $loghandlerinstance->setIdent($ident);
2565 }
2566 }
2567
2568 if (!empty($message)) {
2569 // Test log level
2570 // @phan-suppress-next-line PhanPluginDuplicateArrayKey
2571 $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');
2572
2573 if (!array_key_exists($level, $logLevels)) {
2574 dol_syslog('Error Bad Log Level '.$level, LOG_ERR);
2575 $level = LOG_ERR;
2576 }
2577 if ($level > getDolGlobalInt('SYSLOG_LEVEL')) {
2578 return;
2579 }
2580
2581 if (!getDolGlobalString('MAIN_SHOW_PASSWORD_INTO_LOG')) {
2582 $message = preg_replace('/password=\'[^\']*\'/', 'password=\'hidden\'', $message); // protection to avoid to have value of password in log
2583 }
2584
2585 // If adding log inside HTML page is required
2586 if ((!empty($_REQUEST['logtohtml']) && getDolGlobalString('MAIN_ENABLE_LOG_TO_HTML'))
2587 || (is_object($user) && $user->hasRight('debugbar', 'read') && is_object($debugbar))) {
2588 $ospid = sprintf("%7s", dol_trunc((string) getmypid(), 7, 'right', 'UTF-8', 1));
2589 $osuser = " ".sprintf("%6s", dol_trunc(function_exists('posix_getuid') ? posix_getuid() : '', 6, 'right', 'UTF-8', 1));
2590
2591 $conf->logbuffer[] = dol_print_date(time(), "%Y-%m-%d %H:%M:%S")." ".sprintf("%-7s", $logLevels[$level])." ".$ospid." ".$osuser." ".$message;
2592 }
2593
2594 //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output
2595 // If html log tag enabled and url parameter log defined, we show output log on HTML comments
2596 if (getDolGlobalString('MAIN_ENABLE_LOG_INLINE_HTML') && GETPOSTINT("log")) {
2597 print "\n\n<!-- Log start\n";
2598 print dol_escape_htmltag($message)."\n";
2599 print "Log end -->\n";
2600 }
2601
2602 $data = array(
2603 'message' => $message,
2604 'script' => (isset($_SERVER['PHP_SELF']) ? basename($_SERVER['PHP_SELF'], '.php') : ''),
2605 'level' => $level,
2606 'user' => ((is_object($user) && $user->id) ? $user->login : ''),
2607 'ip' => '',
2608 'osuser' => function_exists('posix_getuid') ? (string) posix_getuid() : '',
2609 'ospid' => (string) getmypid() // on linux, max value is defined into cat /proc/sys/kernel/pid_max
2610 );
2611
2612 // For log, we want the reliable IP first.
2613 $remoteip = getUserRemoteIP(1); // Get ip when page run on a web server
2614 if (!empty($remoteip)) {
2615 $data['ip'] = $remoteip;
2616 // This is when server run behind a reverse proxy
2617 // A HTTP_X_FORWARDED_FOR as format "ip real of user, ip of proxy1, ip of proxy2, ..."
2618 // $data['ip'] is last
2619 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
2620 $tmpips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
2621 $data['ip'] = '';
2622 $foundremoteip = 0;
2623 $j = 0;
2624 foreach ($tmpips as $tmpip) {
2625 $tmpip = trim($tmpip);
2626 if (strtolower($tmpip) == strtolower($remoteip)) {
2627 $foundremoteip = 1;
2628 }
2629 if (empty($data['ip'])) {
2630 $data['ip'] = $tmpip;
2631 } else {
2632 $j++;
2633 $data['ip'] .= (($j == 1) ? ' [via ' : ',').$tmpip;
2634 }
2635 }
2636 if (!$foundremoteip) {
2637 $j++;
2638 $data['ip'] .= (($j == 1) ? ' [via ' : ',').$remoteip;
2639 }
2640 $data['ip'] .= (($j > 0) ? ']' : '');
2641 } elseif (!empty($_SERVER['HTTP_CLIENT_IP'])) {
2642 $tmpips = explode(',', $_SERVER['HTTP_CLIENT_IP']);
2643 $data['ip'] = '';
2644 $foundremoteip = 0;
2645 $j = 0;
2646 foreach ($tmpips as $tmpip) {
2647 $tmpip = trim($tmpip);
2648 if (strtolower($tmpip) == strtolower($remoteip)) {
2649 $foundremoteip = 1;
2650 }
2651 if (empty($data['ip'])) {
2652 $data['ip'] = $tmpip;
2653 } else {
2654 $j++;
2655 $data['ip'] .= (($j == 1) ? ' [via ' : ',').$tmpip;
2656 }
2657 }
2658 if (!$foundremoteip) {
2659 $j++;
2660 $data['ip'] .= (($j == 1) ? ' [via ' : ',').$remoteip;
2661 }
2662 $data['ip'] .= (($j > 0) ? ']' : '');
2663 }
2664 } elseif (!empty($_SERVER['SERVER_ADDR'])) {
2665 // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
2666 $data['ip'] = (string) $_SERVER['SERVER_ADDR'];
2667 } elseif (!empty($_SERVER['COMPUTERNAME'])) {
2668 // 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).
2669 $data['ip'] = (string) $_SERVER['COMPUTERNAME'];
2670 } else {
2671 $data['ip'] = '???';
2672 }
2673
2674 if (!empty($_SERVER['USERNAME'])) {
2675 // 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).
2676 $data['osuser'] = (string) $_SERVER['USERNAME'];
2677 } elseif (!empty($_SERVER['LOGNAME'])) {
2678 // 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).
2679 $data['osuser'] = (string) $_SERVER['LOGNAME'];
2680 }
2681
2682 // Loop on each log handler and send output
2683 foreach ($conf->loghandlers as $loghandlerinstance) {
2684 if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler) {
2685 continue;
2686 }
2687 $loghandlerinstance->export($data, $suffixinfilename);
2688 }
2689 unset($data);
2690 }
2691
2692 if ($ident > 0) {
2693 foreach ($conf->loghandlers as $loghandlerinstance) {
2694 $loghandlerinstance->setIdent($ident);
2695 }
2696 }
2697}
2698
2710function dolButtonToOpenExportDialog($name, $label, $buttonstring, $exportSiteName, $overwriteGitUrl, $website)
2711{
2712 global $langs, $db;
2713
2714 $form = new Form($db);
2715
2716 $templatenameforexport = $website->name_template; // Example 'website_template-corporate'
2717 if (empty($templatenameforexport)) {
2718 $templatenameforexport = 'website_'.$website->ref;
2719 }
2720
2721 $out = '';
2722 $out .= '<input type="button" class="cursorpointer button bordertransp" id="open-dialog-' . $name . '" value="'.dol_escape_htmltag($buttonstring).'"/>';
2723
2724 // for generate popup
2725 $out .= '<script nonce="' . getNonce() . '" type="text/javascript">';
2726 $out .= 'jQuery(document).ready(function () {';
2727 $out .= ' jQuery("#open-dialog-' . $name . '").click(function () {';
2728 $out .= ' var dialogHtml = \'';
2729
2730 $dialogcontent = ' <div id="custom-dialog-' . $name . '">';
2731 $dialogcontent .= ' <div style="margin-top: 20px;">';
2732 $dialogcontent .= ' <label for="export-site-' . $name . '"><strong>'.$langs->trans("ExportSiteLabel").'...</label><br>';
2733 $dialogcontent .= ' <button class="button smallpaddingimp" id="export-site-' . $name . '">' . dol_escape_htmltag($langs->trans("DownloadZip")) . '</button>';
2734 $dialogcontent .= ' </div>';
2735 $dialogcontent .= ' <br>';
2736 $dialogcontent .= ' <div style="margin-top: 20px;">';
2737 $dialogcontent .= ' <strong>'.$langs->trans("ExportSiteGitLabel").' '.$form->textwithpicto('', $langs->trans("SourceFiles"), 1, 'help', '', 0, 3, '').'</strong><br>';
2738 $dialogcontent .= ' <form action="'.dol_escape_htmltag($overwriteGitUrl).'" method="POST">';
2739 $dialogcontent .= ' <input type="hidden" name="action" value="overwritesite">';
2740 $dialogcontent .= ' <input type="hidden" name="token" value="'.newToken().'">';
2741 $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>';
2742 $dialogcontent .= ' <button type="submit" class="button smallpaddingimp" id="overwrite-git-' . $name . '">' . dol_escape_htmltag($langs->trans("ExportIntoGIT")) . '</button>';
2743 $dialogcontent .= ' </form>';
2744 $dialogcontent .= ' </div>';
2745 $dialogcontent .= ' </div>';
2746
2747 $out .= dol_escape_js($dialogcontent);
2748
2749 $out .= '\';';
2750
2751
2752 // Add the content of the dialog to the body of the page
2753 $out .= ' var $dialog = jQuery("#custom-dialog-' . $name . '");';
2754 $out .= ' if ($dialog.length > 0) {
2755 $dialog.remove();
2756 }
2757 jQuery("body").append(dialogHtml);';
2758
2759 // Configuration of popup
2760 $out .= ' jQuery("#custom-dialog-' . $name . '").dialog({';
2761 $out .= ' autoOpen: false,';
2762 $out .= ' modal: true,';
2763 $out .= ' height: 290,';
2764 $out .= ' width: "40%",';
2765 $out .= ' title: "' . dol_escape_js($label) . '",';
2766 $out .= ' });';
2767
2768 // Simulate a click on the original "submit" input to export the site.
2769 $out .= ' jQuery("#export-site-' . $name . '").click(function () {';
2770 $out .= ' console.log("Clic on exportsite.");';
2771 $out .= ' var target = jQuery("input[name=\'' . dol_escape_js($exportSiteName) . '\']");';
2772 $out .= ' console.log("element founded:", target.length > 0);';
2773 $out .= ' if (target.length > 0) { target.click(); }';
2774 $out .= ' jQuery("#custom-dialog-' . $name . '").dialog("close");';
2775 $out .= ' });';
2776
2777 // open popup
2778 $out .= ' jQuery("#custom-dialog-' . $name . '").dialog("open");';
2779 $out .= ' return false;';
2780 $out .= ' });';
2781 $out .= '});';
2782 $out .= '</script>';
2783
2784 return $out;
2785}
2786
2787
2804function dolButtonToOpenUrlInDialogPopup($name, $label, $buttonstring, $url, $disabled = '', $morecss = 'classlink button bordertransp', $jsonopen = '', $jsonclose = '', $accesskey = '')
2805{
2806 global $conf;
2807
2808 if (strpos($url, '?') > 0) {
2809 $url .= '&dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup='.urlencode($name);
2810 } else {
2811 $url .= '?dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup='.urlencode($name);
2812 }
2813
2814 $out = '';
2815
2816 //print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("MediaFiles")).'" name="file_manager">';
2817 $out .= '<!-- a link for button to open url into a dialog popup -->';
2818 $out .= '<a '.($accesskey ? ' accesskey="'.$accesskey.'"' : '').' class="cursorpointer reposition button_'.$name.($morecss ? ' '.$morecss : '').'"'.$disabled.' title="'.dol_escape_htmltag($label).'"';
2819 if (empty($conf->use_javascript_ajax)) {
2820 $out .= ' href="'.DOL_URL_ROOT.$url.'" target="_blank"';
2821 } elseif ($jsonopen) {
2822 $out .= ' href="#" onclick="'.$jsonopen.'"';
2823 } else {
2824 $out .= ' href="#"';
2825 }
2826 $out .= '>'.$buttonstring.'</a>';
2827
2828 if (!empty($conf->use_javascript_ajax)) {
2829 // Add code to open url using the popup.
2830 $out .= '<!-- code to open popup and variables to retrieve returned variables -->';
2831 $out .= '<div id="idfordialog'.$name.'" class="hidden">'.(getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER') < 2 ? 'div for dialog' : '').'</div>';
2832
2833 $out .= '<!-- Add js code to open dialog popup on dialog -->';
2834 $out .= '<script nonce="'.getNonce().'" type="text/javascript">
2835 jQuery(document).ready(function () {
2836 jQuery(".button_'.$name.'").click(function () {
2837 console.log(\'Open popup with jQuery(...).dialog() on URL '.dol_escape_js(DOL_URL_ROOT.$url).'\');
2838 var $tmpdialog = $(\'#idfordialog'.$name.'\');
2839 $tmpdialog.html(\'<iframe class="iframedialog" id="iframedialog'.$name.'" style="border: 0px;" src="'.DOL_URL_ROOT.$url.'" width="100%" height="98%"></iframe>\');
2840 $tmpdialog.dialog({
2841 autoOpen: false,
2842 modal: true,
2843 height: (window.innerHeight - 150),
2844 width: \'80%\',
2845 title: \''.dol_escape_js($label).'\',
2846 open: function (event, ui) {
2847 console.log("open popup name='.$name.'");
2848 },
2849 close: function (event, ui) {
2850 console.log("Popup is closed, run jsonclose = '.$jsonclose.'");
2851 '.(empty($jsonclose) ? '' : $jsonclose.';').'
2852 }
2853 });
2854
2855 $tmpdialog.dialog(\'open\');
2856 return false;
2857 });
2858 });
2859 </script>';
2860 }
2861 return $out;
2862}
2863
2880function dol_fiche_head($links = array(), $active = '0', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
2881{
2882 print dol_get_fiche_head($links, $active, $title, $notab, $picto, $pictoisfullpath, $morehtmlright, $morecss, $limittoshow, $moretabssuffix);
2883}
2884
2902function dol_get_fiche_head($links = array(), $active = '', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '', $dragdropfile = 0, $morecssdiv = '')
2903{
2904 global $conf, $langs, $hookmanager;
2905
2906 // Show title
2907 $showtitle = 1;
2908 if (!empty($conf->dol_optimize_smallscreen)) {
2909 $showtitle = 0;
2910 }
2911
2912 $out = "\n".'<!-- dol_fiche_head - dol_get_fiche_head -->';
2913
2914 if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
2915 $out .= '<div class="tabs'.($picto ? '' : ' nopaddingleft').'" data-role="controlgroup" data-type="horizontal">'."\n";
2916 }
2917
2918 // Show right part
2919 if ($morehtmlright) {
2920 $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.
2921 }
2922
2923 // Show tabs
2924
2925 // Define max of key (max may be higher than sizeof because of hole due to module disabling some tabs).
2926 $maxkey = -1;
2927 if (is_array($links) && !empty($links)) {
2928 $keys = array_keys($links);
2929 if (count($keys)) {
2930 $maxkey = max($keys);
2931 }
2932 }
2933
2934 // Show tabs
2935 // if =0 we don't use the feature
2936 if (empty($limittoshow)) {
2937 $limittoshow = getDolGlobalInt('MAIN_MAXTABS_IN_CARD', 99);
2938 }
2939 if (!empty($conf->dol_optimize_smallscreen)) {
2940 $limittoshow = 2;
2941 }
2942
2943 $displaytab = 0;
2944 $nbintab = 0;
2945 $popuptab = 0;
2946 $outmore = '';
2947 for ($i = 0; $i <= $maxkey; $i++) {
2948 if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
2949 // If active tab is already present
2950 if ($i >= $limittoshow) {
2951 $limittoshow--;
2952 }
2953 }
2954 }
2955
2956 for ($i = 0; $i <= $maxkey; $i++) {
2957 if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
2958 $isactive = true;
2959 } else {
2960 $isactive = false;
2961 }
2962
2963 if ($i < $limittoshow || $isactive) {
2964 // Output entry with a visible tab
2965 $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])).' -->';
2966
2967 if (isset($links[$i][2]) && $links[$i][2] == 'image') {
2968 if (!empty($links[$i][0])) {
2969 $out .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
2970 } else {
2971 $out .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
2972 }
2973 } elseif (!empty($links[$i][1])) {
2974 //print "x $i $active ".$links[$i][2]." z";
2975 $out .= '<div class="tab tab'.($isactive ? 'active' : 'unactive').'" style="margin: 0 !important">';
2976
2977 if (!empty($links[$i][0])) {
2978 $titletoshow = preg_replace('/<.*$/', '', $links[$i][1]);
2979 $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).'">';
2980 }
2981
2982 if ($displaytab == 0 && $picto) {
2983 $out .= img_picto($title, $picto, '', $pictoisfullpath, 0, 0, '', 'imgTabTitle paddingright marginrightonlyshort');
2984 }
2985
2986 $out .= $links[$i][1];
2987 if (!empty($links[$i][0])) {
2988 $out .= '</a>'."\n";
2989 }
2990 $out .= empty($links[$i][4]) ? '' : $links[$i][4];
2991 $out .= '</div>';
2992 }
2993
2994 $out .= '</div>';
2995 } else {
2996 // Add entry into the combo popup with the other tabs
2997 if (!$popuptab) {
2998 $popuptab = 1;
2999 $outmore .= '<div class="popuptabset wordwrap">'; // The css used to hide/show popup
3000 }
3001 $outmore_content = '';
3002
3003 if (isset($links[$i][2]) && $links[$i][2] == 'image') {
3004 if (!empty($links[$i][0])) {
3005 $outmore_content .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
3006 } else {
3007 $outmore_content .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
3008 }
3009 } elseif (!empty($links[$i][1])) {
3010 $outmore_content .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="wordwrap inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
3011 $outmore_content .= 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.
3012 $outmore_content .= '</a>'."\n";
3013 }
3014 if ($outmore_content !== '') {
3015 $outmore .= '<div class="popuptab wordwrap" style="display:inherit;">' . $outmore_content . '</div>';
3016 }
3017
3018 $nbintab++;
3019 }
3020
3021 $displaytab = $i + 1;
3022 }
3023 if ($popuptab) {
3024 $outmore .= '</div>';
3025 }
3026
3027 if ($popuptab) { // If there is some tabs not shown
3028 $left = ($langs->trans("DIRECTION") == 'rtl' ? 'right' : 'left');
3029 $right = ($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right');
3030 $widthofpopup = 240;
3031
3032 $tabsname = $moretabssuffix;
3033 if (empty($tabsname)) {
3034 $tabsname = str_replace("@", "", $picto);
3035 }
3036 $out .= '<div id="moretabs'.$tabsname.'" class="inline-block tabsElem valignmiddle">';
3037 if (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER') < 2) {
3038 $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".
3039 }
3040 $out .= '<div id="moretabsList'.$tabsname.'" style="width: '.$widthofpopup.'px; position: absolute; '.$left.': -999em; text-align: '.$left.'; margin:0px; padding:2px; z-index:10;">';
3041 $out .= $outmore;
3042 $out .= '</div>';
3043 $out .= '<div></div>';
3044 $out .= "</div>\n";
3045
3046 $out .= '<script nonce="'.getNonce().'">';
3047 $out .= "$('#moretabs".$tabsname."').mouseenter( function() {
3048 var x = this.offsetLeft, y = this.offsetTop;
3049 console.log('mouseenter ".$left." x='+x+' y='+y+' window.innerWidth='+window.innerWidth);
3050 if ((window.innerWidth - x) < ".($widthofpopup + 10).") {
3051 $('#moretabsList".$tabsname."').css('".$right."','8px');
3052 }
3053 $('#moretabsList".$tabsname."').css('".$left."','auto');
3054 });
3055 ";
3056 $out .= "$('#moretabs".$tabsname."').mouseleave( function() { console.log('mouseleave ".$left."'); $('#moretabsList".$tabsname."').css('".$left."','-999em');});";
3057 $out .= "</script>";
3058 }
3059
3060 if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
3061 $out .= "</div>\n";
3062 }
3063
3064 if (!$notab || $notab == -1 || $notab == -2 || $notab == -3 || $notab == -4) {
3065 $out .= "\n".'<div id="dragDropAreaTabBar" class="tabBar'.($notab == -1 ? '' : ($notab == -2 ? ' tabBarNoTop' : ((($notab == -3 || $notab == -4) ? ' noborderbottom' : '').($notab == -4 ? '' : ' tabBarWithBottom'))));
3066 $out .= ($morecssdiv ? ' '.$morecssdiv : '');
3067 $out .= '">'."\n";
3068 }
3069 if (!empty($dragdropfile)) {
3070 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
3071 $out .= dragAndDropFileUpload("dragDropAreaTabBar");
3072 }
3073 $parameters = array('tabname' => $active, 'out' => $out);
3074 $reshook = $hookmanager->executeHooks('printTabsHead', $parameters); // This hook usage is called just before output the head of tabs. Take also a look at "completeTabsHead"
3075 if ($reshook > 0) {
3076 $out = $hookmanager->resPrint;
3077 }
3078
3079 return $out;
3080}
3081
3089function dol_fiche_end($notab = 0)
3090{
3091 print dol_get_fiche_end($notab);
3092}
3093
3100function dol_get_fiche_end($notab = 0)
3101{
3102 if (!$notab || $notab == -1) {
3103 return "\n</div>\n";
3104 } else {
3105 return '';
3106 }
3107}
3108
3128function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $onlybanner = 0, $morehtmlright = '')
3129{
3130 global $conf, $form, $user, $langs, $hookmanager, $action;
3131
3132 $error = 0;
3133
3134 $maxvisiblephotos = 1;
3135 $showimage = 1;
3136 $entity = (empty($object->entity) ? $conf->entity : $object->entity);
3137 // @phan-suppress-next-line PhanUndeclaredMethod
3138 $showbarcode = !isModEnabled('barcode') ? 0 : (empty($object->barcode) ? 0 : 1);
3139 if (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !$user->hasRight('barcode', 'lire_advance')) {
3140 $showbarcode = 0;
3141 }
3142 $modulepart = 'unknown';
3143
3144 if (in_array($object->element, ['societe', 'contact', 'product', 'ticket', 'bom'])) {
3145 $modulepart = $object->element;
3146 } elseif ($object->element == 'member') {
3147 $modulepart = 'memberphoto';
3148 } elseif ($object->element == 'user') {
3149 $modulepart = 'userphoto';
3150 }
3151
3152 if (class_exists("Imagick")) {
3153 if ($object->element == 'expensereport' || $object->element == 'propal' || $object->element == 'commande' || $object->element == 'facture' || $object->element == 'supplier_proposal') {
3154 $modulepart = $object->element;
3155 } elseif ($object->element == 'fichinter' || $object->element == 'intervention') {
3156 $modulepart = 'ficheinter';
3157 } elseif ($object->element == 'contrat' || $object->element == 'contract') {
3158 $modulepart = 'contract';
3159 } elseif ($object->element == 'order_supplier') {
3160 $modulepart = 'supplier_order';
3161 } elseif ($object->element == 'invoice_supplier') {
3162 $modulepart = 'supplier_invoice';
3163 }
3164 }
3165
3166 if ($object->element == 'product') {
3168 '@phan-var-force Product $object';
3169 $width = 80;
3170 $cssclass = 'photowithmargin photoref';
3171 $showimage = $object->is_photo_available($conf->product->multidir_output[$entity]);
3172 $maxvisiblephotos = getDolGlobalInt('PRODUCT_MAX_VISIBLE_PHOTO', 5);
3173 if ($conf->browser->layout == 'phone') {
3174 $maxvisiblephotos = 1;
3175 }
3176 if ($showimage) {
3177 $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>';
3178 } else {
3179 if (getDolGlobalString('PRODUCT_NODISPLAYIFNOPHOTO')) {
3180 $nophoto = '';
3181 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
3182 } else { // Show no photo link
3183 $nophoto = '/public/theme/common/nophoto.png';
3184 $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>';
3185 }
3186 }
3187 } elseif ($object->element == 'category') {
3189 '@phan-var-force Categorie $object';
3190 $width = 80;
3191 $cssclass = 'photowithmargin photoref';
3192 $showimage = $object->isAnyPhotoAvailable($conf->categorie->multidir_output[$entity]);
3193 $maxvisiblephotos = getDolGlobalInt('CATEGORY_MAX_VISIBLE_PHOTO', 5);
3194 if ($conf->browser->layout == 'phone') {
3195 $maxvisiblephotos = 1;
3196 }
3197 if ($showimage) {
3198 $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>';
3199 } else {
3200 if (getDolGlobalString('CATEGORY_NODISPLAYIFNOPHOTO')) {
3201 $nophoto = '';
3202 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
3203 } else { // Show no photo link
3204 $nophoto = '/public/theme/common/nophoto.png';
3205 $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>';
3206 }
3207 }
3208 } elseif ($object->element == 'bom') {
3210 '@phan-var-force Bom $object';
3211 $width = 80;
3212 $cssclass = 'photowithmargin photoref';
3213 $showimage = $object->is_photo_available($conf->bom->multidir_output[$entity]);
3214 $maxvisiblephotos = getDolGlobalInt('BOM_MAX_VISIBLE_PHOTO', 5);
3215 if ($conf->browser->layout == 'phone') {
3216 $maxvisiblephotos = 1;
3217 }
3218 if ($showimage) {
3219 $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>';
3220 } else {
3221 if (getDolGlobalString('BOM_NODISPLAYIFNOPHOTO')) {
3222 $nophoto = '';
3223 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
3224 } else { // Show no photo link
3225 $nophoto = '/public/theme/common/nophoto.png';
3226 $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>';
3227 }
3228 }
3229 } elseif ($object->element == 'ticket') {
3230 $width = 80;
3231 $cssclass = 'photoref';
3233 '@phan-var-force Ticket $object';
3234 $showimage = $object->is_photo_available($conf->ticket->multidir_output[$entity].'/'.$object->ref);
3235 $maxvisiblephotos = getDolGlobalInt('TICKET_MAX_VISIBLE_PHOTO', 2);
3236 if ($conf->browser->layout == 'phone') {
3237 $maxvisiblephotos = 1;
3238 }
3239
3240 if ($showimage) {
3241 $showphoto = $object->show_photos('ticket', $conf->ticket->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0);
3242 if ($object->nbphoto > 0) {
3243 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$showphoto.'</div>';
3244 } else {
3245 $showimage = 0;
3246 }
3247 }
3248 if (!$showimage) {
3249 if (getDolGlobalString('TICKET_NODISPLAYIFNOPHOTO')) {
3250 $nophoto = '';
3251 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
3252 } else { // Show no photo link
3253 $nophoto = img_picto('No photo', 'object_ticket');
3254 $morehtmlleft .= '<!-- No photo to show -->';
3255 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
3256 $morehtmlleft .= $nophoto;
3257 $morehtmlleft .= '</div></div>';
3258 }
3259 }
3260 } else {
3261 if ($showimage) {
3262 if ($modulepart != 'unknown' || method_exists($object, 'getDataToShowPhoto')) {
3263 $phototoshow = '';
3264 // Check if a preview file is available
3265 if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice', 'expensereport')) && class_exists("Imagick")) {
3266 $objectref = dol_sanitizeFileName($object->ref);
3267 $dir_output = (empty($conf->$modulepart->multidir_output[$entity]) ? $conf->$modulepart->dir_output : $conf->$modulepart->multidir_output[$entity])."/";
3268 if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice'))) {
3269 $subdir = get_exdir($object->id, 2, 0, 1, $object, $modulepart);
3270 $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
3271 } else {
3272 $subdir = get_exdir($object->id, 0, 0, 1, $object, $modulepart);
3273 }
3274 if (empty($subdir)) {
3275 $subdir = 'errorgettingsubdirofobject'; // Protection to avoid to return empty path
3276 }
3277
3278 $filepath = $dir_output.$subdir."/";
3279
3280 $filepdf = $filepath.$objectref.".pdf";
3281 $relativepath = $subdir.'/'.$objectref.'.pdf';
3282
3283 // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png")
3284 $fileimage = $filepdf.'_preview.png';
3285 $relativepathimage = $relativepath.'_preview.png';
3286
3287 $pdfexists = file_exists($filepdf);
3288
3289 // If PDF file exists
3290 if ($pdfexists) {
3291 // Conversion du PDF en image png si fichier png non existent
3292 if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf))) {
3293 if (!getDolGlobalString('MAIN_DISABLE_PDF_THUMBS')) { // If you experience trouble with pdf thumb generation and imagick, you can disable here.
3294 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
3295 $ret = dol_convert_file($filepdf, 'png', $fileimage, '0'); // Convert first page of PDF into a file _preview.png
3296 if ($ret < 0) {
3297 $error++;
3298 }
3299 }
3300 }
3301 }
3302
3303 if ($pdfexists && !$error) {
3304 $heightforphotref = 80;
3305 if (!empty($conf->dol_optimize_smallscreen)) {
3306 $heightforphotref = 60;
3307 }
3308 // If the preview file is found
3309 if (file_exists($fileimage)) {
3310 $phototoshow = '<div class="photoref">';
3311 $phototoshow .= '<img height="'.$heightforphotref.'" class="photo photowithborder" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($relativepathimage).'">';
3312 $phototoshow .= '</div>';
3313 }
3314 }
3315 } elseif (!$phototoshow) { // example if modulepart = 'societe' or 'photo' or 'memberphoto'
3316 $phototoshow .= $form->showphoto($modulepart, $object, 0, 0, 0, 'photowithmargin photoref', 'small', 1, 0);
3317 }
3318
3319 if ($phototoshow) {
3320 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">';
3321 $morehtmlleft .= $phototoshow;
3322 $morehtmlleft .= '</div>';
3323 }
3324 }
3325
3326 if (empty($phototoshow)) { // Show No photo link (picto of object)
3327 if ($object->element == 'action') {
3328 $width = 80;
3329 $cssclass = 'photorefcenter';
3330 $nophoto = img_picto('No photo', 'title_agenda');
3331 } else {
3332 $width = 14;
3333 $cssclass = 'photorefcenter';
3334 $picto = $object->picto; // @phan-suppress-current-line PhanUndeclaredProperty
3335 $prefix = 'object_';
3336 if ($object->element == 'project' && !$object->public) { // @phan-suppress-current-line PhanUndeclaredProperty
3337 $picto = 'project'; // instead of projectpub
3338 }
3339 if (strpos($picto, 'fontawesome_') !== false) {
3340 $prefix = '';
3341 }
3342 $nophoto = img_picto('No photo', $prefix.$picto);
3343 }
3344 $morehtmlleft .= '<!-- No photo to show -->';
3345 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
3346 $morehtmlleft .= $nophoto;
3347 $morehtmlleft .= '</div></div>';
3348 }
3349 }
3350 }
3351
3352 // Show barcode
3353 if ($showbarcode) {
3354 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$form->showbarcode($object, 100, 'photoref valignmiddle').'</div>';
3355 }
3356
3357 if ($object->element == 'societe') {
3358 if (!empty($conf->use_javascript_ajax) && $user->hasRight('societe', 'creer') && getDolGlobalString('MAIN_DIRECT_STATUS_UPDATE')) {
3359 $morehtmlstatus .= ajax_object_onoff($object, 'status', 'status', 'InActivity', 'ActivityCeased');
3360 } else {
3361 $morehtmlstatus .= $object->getLibStatut(6);
3362 }
3363 } elseif ($object->element == 'product') {
3364 //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Sell").') ';
3365 if (!empty($conf->use_javascript_ajax) && $user->hasRight('produit', 'creer') && getDolGlobalString('MAIN_DIRECT_STATUS_UPDATE')) {
3366 $morehtmlstatus .= ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell');
3367 } else {
3368 $morehtmlstatus .= '<span class="statusrefsell">'.$object->getLibStatut(6, 0).'</span>';
3369 }
3370 $morehtmlstatus .= ' &nbsp; ';
3371 //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Buy").') ';
3372 if (!empty($conf->use_javascript_ajax) && $user->hasRight('produit', 'creer') && getDolGlobalString('MAIN_DIRECT_STATUS_UPDATE')) {
3373 $morehtmlstatus .= ajax_object_onoff($object, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy');
3374 } else {
3375 $morehtmlstatus .= '<span class="statusrefbuy">'.$object->getLibStatut(6, 1).'</span>';
3376 }
3377 } elseif (in_array($object->element, array('salary'))) {
3378 '@phan-var-force Salary $object';
3379 $tmptxt = $object->getLibStatut(6, $object->alreadypaid);
3380 if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
3381 $tmptxt = $object->getLibStatut(5, $object->alreadypaid);
3382 }
3383 $morehtmlstatus .= $tmptxt;
3384 } elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier'))) { // TODO Move this to use ->alreadypaid
3385 '@phan-var-force Facture|FactureFournisseur|CommonInvoice $object';
3386 $totalallpayments = $object->getSommePaiement(0);
3387 $totalallpayments += $object->getSumCreditNotesUsed(0);
3388 $totalallpayments += $object->getSumDepositsUsed(0);
3389 $tmptxt = $object->getLibStatut(6, $totalallpayments);
3390 if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
3391 $tmptxt = $object->getLibStatut(5, $totalallpayments);
3392 }
3393 $morehtmlstatus .= $tmptxt;
3394 } elseif (in_array($object->element, array('chargesociales', 'loan', 'tva'))) { // TODO Move this to use ->alreadypaid
3395 '@phan-var-force ChargeSociales|Loan|Tva $object';
3396 $tmptxt = $object->getLibStatut(6, $object->totalpaid);
3397 if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
3398 $tmptxt = $object->getLibStatut(5, $object->totalpaid);
3399 }
3400 $morehtmlstatus .= $tmptxt;
3401 } elseif ($object->element == 'contrat' || $object->element == 'contract') {
3402 if ($object->statut == 0) {
3403 $morehtmlstatus .= $object->getLibStatut(5);
3404 } else {
3405 $morehtmlstatus .= $object->getLibStatut(4);
3406 }
3407 } elseif ($object->element == 'facturerec') {
3408 '@phan-var-force FactureRec $object';
3409 if ($object->frequency == 0) {
3410 $morehtmlstatus .= $object->getLibStatut(2);
3411 } else {
3412 $morehtmlstatus .= $object->getLibStatut(5);
3413 }
3414 } elseif ($object->element == 'project_task') {
3415 $tmptxt = $object->getLibStatut(4);
3416 $morehtmlstatus .= $tmptxt;
3417 } elseif (method_exists($object, 'getLibStatut')) { // Generic case for status
3418 $tmptxt = $object->getLibStatut(6);
3419 if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
3420 $tmptxt = $object->getLibStatut(5);
3421 }
3422 $morehtmlstatus .= $tmptxt;
3423 }
3424
3425 // Say if object was dispatched/transferred "into accountancy"
3426 if (isModEnabled('accounting') && in_array($object->element, array('bank', 'paiementcharge', 'facture', 'invoice', 'invoice_supplier', 'expensereport', 'payment_various'))) {
3427 // Note: For 'chargesociales', 'salaries'... this is the payments that are dispatched (so element = 'bank')
3428 if (method_exists($object, 'getVentilExportCompta')) {
3429 $accounted = $object->getVentilExportCompta(1);
3430 $langs->load("accountancy");
3431 $morehtmlstatus .= '</div><div class="statusref statusrefbis"><span class="opacitymedium">'.($accounted > 0 ? '<a href="'.DOL_URL_ROOT.'/accountancy/bookkeeping/list.php?search_mvt_num='.((int) $accounted).'">'.$langs->trans("Accounted").'</a>' : $langs->trans("NotYetAccounted")).'</span>';
3432 }
3433 }
3434
3435 // Add alias for thirdparty
3436 if (!empty($object->name_alias)) {
3437 '@phan-var-force Societe $object';
3438 $morehtmlref .= '<div class="refidno opacitymedium">'.dol_escape_htmltag($object->name_alias).'</div>';
3439 }
3440
3441 // Add label
3442 if (in_array($object->element, array('product', 'bank_account', 'project_task'))) {
3443 if (!empty($object->label)) {
3444 $morehtmlref .= '<div class="refidno opacitymedium">'.$object->label.'</div>';
3445 }
3446 }
3447 // Show address and email
3448 if (method_exists($object, 'getBannerAddress') && !in_array($object->element, array('product', 'bookmark', 'ecm_directories', 'ecm_files'))) {
3449 $moreaddress = $object->getBannerAddress('refaddress', $object); // address, email, url, social networks
3450 if ($moreaddress) {
3451 $morehtmlref .= '<div class="refidno refaddress">';
3452 $morehtmlref .= $moreaddress;
3453 $morehtmlref .= '</div>';
3454 }
3455 }
3456 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)) {
3457 $morehtmlref .= '<div style="clear: both;"></div>';
3458 $morehtmlref .= '<div class="refidno opacitymedium">';
3459 $morehtmlref .= $langs->trans("TechnicalID").': '.((int) $object->id);
3460 $morehtmlref .= '</div>';
3461 }
3462
3463 $parameters = array('morehtmlref' => &$morehtmlref, 'moreparam' => &$moreparam, 'morehtmlleft' => &$morehtmlleft, 'morehtmlstatus' => &$morehtmlstatus, 'morehtmlright' => &$morehtmlright);
3464 $reshook = $hookmanager->executeHooks('formDolBanner', $parameters, $object, $action);
3465 if ($reshook < 0) {
3466 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
3467 } elseif (empty($reshook)) {
3468 $morehtmlref .= $hookmanager->resPrint;
3469 } elseif ($reshook > 0) {
3470 $morehtmlref = $hookmanager->resPrint;
3471 }
3472
3473 // $morehtml is the right part (link "Back to list")
3474 // $morehtmlleft is the picto or photo of banner
3475 // $morehtmlstatus is part under the status
3476 // $morehtmlright is part of htmlright
3477
3478 print '<div class="'.($onlybanner ? 'arearefnobottom ' : 'arearef ').'heightref valignmiddle centpercent">';
3479 print $form->showrefnav($object, $paramid, $morehtml, $shownav, $fieldid, $fieldref, $morehtmlref, $moreparam, $nodbprefix, $morehtmlleft, $morehtmlstatus, $morehtmlright);
3480 print '</div>';
3481 print '<div class="underrefbanner clearboth"></div>';
3482}
3483
3493function fieldLabel($langkey, $fieldkey, $fieldrequired = 0)
3494{
3495 global $langs;
3496 $ret = '';
3497 if ($fieldrequired) {
3498 $ret .= '<span class="fieldrequired">';
3499 }
3500 $ret .= '<label for="'.$fieldkey.'">';
3501 $ret .= $langs->trans($langkey);
3502 $ret .= '</label>';
3503 if ($fieldrequired) {
3504 $ret .= '</span>';
3505 }
3506 return $ret;
3507}
3508
3522function dol_format_address($object, $withcountry = 0, $sep = "\n", $outputlangs = null, $mode = 0, $extralangcode = '')
3523{
3524 global $langs, $hookmanager;
3525
3526 $ret = '';
3527 $countriesusingstate = array('AU', 'CA', 'US', 'IN', 'GB', 'ES', 'UK', 'TR', 'CN'); // See also MAIN_FORCE_STATE_INTO_ADDRESS
3528
3529 // See format of addresses on https://en.wikipedia.org/wiki/Address
3530 // Address
3531 if (empty($mode)) {
3532 $ret .= (($extralangcode && !empty($object->array_languages['address'][$extralangcode])) ? $object->array_languages['address'][$extralangcode] : (empty($object->address) ? '' : preg_replace('/(\r\n|\r|\n)+/', $sep, $object->address)));
3533 }
3534 // Zip/Town/State
3535 if (isset($object->country_code) && in_array($object->country_code, array('AU', 'CA', 'US', 'CN')) || getDolGlobalString('MAIN_FORCE_STATE_INTO_ADDRESS')) {
3536 // US: title firstname name \n address lines \n town, state, zip \n country
3537 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
3538 $ret .= (($ret && $town) ? $sep : '').$town;
3539
3540 if (!empty($object->state)) {
3541 $ret .= ($ret ? ($town ? ", " : $sep) : '').$object->state;
3542 }
3543 if (!empty($object->zip)) {
3544 $ret .= ($ret ? (($town || $object->state) ? ", " : $sep) : '').$object->zip;
3545 }
3546 } elseif (isset($object->country_code) && in_array($object->country_code, array('GB', 'UK'))) {
3547 // UK: title firstname name \n address lines \n town state \n zip \n country
3548 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
3549 $ret .= ($ret ? $sep : '').$town;
3550 if (!empty($object->state)) {
3551 $ret .= ($ret ? ", " : '').$object->state;
3552 }
3553 if (!empty($object->zip)) {
3554 $ret .= ($ret ? $sep : '').$object->zip;
3555 }
3556 } elseif (isset($object->country_code) && in_array($object->country_code, array('ES', 'TR'))) {
3557 // ES: title firstname name \n address lines \n zip town \n state \n country
3558 $ret .= ($ret ? $sep : '').$object->zip;
3559 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
3560 $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
3561 if (!empty($object->state)) {
3562 $ret .= $sep.$object->state;
3563 }
3564 } elseif (isset($object->country_code) && in_array($object->country_code, array('JP'))) {
3565 // JP: In romaji, title firstname name\n address lines \n [state,] town zip \n country
3566 // See https://www.sljfaq.org/afaq/addresses.html
3567 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
3568 $ret .= ($ret ? $sep : '').($object->state ? $object->state.', ' : '').$town.($object->zip ? ' ' : '').$object->zip;
3569 } elseif (isset($object->country_code) && in_array($object->country_code, array('IT'))) {
3570 // IT: title firstname name\n address lines \n zip town state_code \n country
3571 $ret .= ($ret ? $sep : '').$object->zip;
3572 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
3573 $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
3574 $ret .= (empty($object->state_code) ? '' : (' '.$object->state_code));
3575 } else {
3576 // Other: title firstname name \n address lines \n zip town[, state] \n country
3577 $town = (($extralangcode && !empty($object->array_languages['address'][$extralangcode])) ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
3578 $ret .= !empty($object->zip) ? (($ret ? $sep : '').$object->zip) : '';
3579 $ret .= ($town ? (($object->zip ? ' ' : ($ret ? $sep : '')).$town) : '');
3580 if (!empty($object->state) && in_array($object->country_code, $countriesusingstate)) {
3581 $ret .= ($ret ? ", " : '').$object->state;
3582 }
3583 }
3584
3585 if (!is_object($outputlangs)) {
3586 $outputlangs = $langs;
3587 }
3588 if ($withcountry) {
3589 $langs->load("dict");
3590 $ret .= (empty($object->country_code) ? '' : ($ret ? $sep : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$object->country_code)));
3591 }
3592 if ($hookmanager) {
3593 $parameters = array('withcountry' => $withcountry, 'sep' => $sep, 'outputlangs' => $outputlangs,'mode' => $mode, 'extralangcode' => $extralangcode);
3594 $reshook = $hookmanager->executeHooks('formatAddress', $parameters, $object);
3595 if ($reshook > 0) {
3596 $ret = '';
3597 }
3598 $ret .= $hookmanager->resPrint;
3599 }
3600
3601 return $ret;
3602}
3603
3604
3605
3615function dol_strftime($fmt, $ts = false, $is_gmt = false)
3616{
3617 if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
3618 return dol_print_date($ts, $fmt, $is_gmt);
3619 } else {
3620 return 'Error date outside supported range';
3621 }
3622}
3623
3645function dol_print_date($time, $format = '', $tzoutput = 'auto', $outputlangs = null, $encodetooutput = false)
3646{
3647 global $conf, $langs;
3648
3649 // If date undefined or "", we return ""
3650 if (dol_strlen((string) $time) == 0) {
3651 return ''; // $time=0 allowed (it means 01/01/1970 00:00:00)
3652 }
3653
3654 if ($tzoutput === 'auto') {
3655 $tzoutput = (empty($conf) ? 'tzserver' : (isset($conf->tzuserinputkey) ? $conf->tzuserinputkey : 'tzserver'));
3656 }
3657
3658 // Clean parameters
3659 $to_gmt = false;
3660 $offsettz = $offsetdst = 0;
3661 if ($tzoutput) {
3662 $to_gmt = true; // For backward compatibility
3663 if (is_string($tzoutput)) {
3664 if ($tzoutput == 'tzserver') {
3665 $to_gmt = false;
3666 $offsettzstring = @date_default_timezone_get(); // Example 'Europe/Berlin' or 'Indian/Reunion'
3667 // @phan-suppress-next-line PhanPluginRedundantAssignment
3668 $offsettz = 0; // Timezone offset with server timezone (because to_gmt is false), so 0
3669 // @phan-suppress-next-line PhanPluginRedundantAssignment
3670 $offsetdst = 0; // Dst offset with server timezone (because to_gmt is false), so 0
3671 } elseif ($tzoutput == 'tzuser' || $tzoutput == 'tzuserrel') {
3672 $to_gmt = true;
3673 $offsettzstring = (empty($_SESSION['dol_tz_string']) ? 'UTC' : $_SESSION['dol_tz_string']); // Example 'Europe/Berlin' or 'Indian/Reunion'
3674
3675 if (class_exists('DateTimeZone')) {
3676 $user_date_tz = new DateTimeZone($offsettzstring);
3677 $user_dt = new DateTime();
3678 $user_dt->setTimezone($user_date_tz);
3679 $user_dt->setTimestamp($tzoutput == 'tzuser' ? dol_now() : (int) $time);
3680 $offsettz = $user_dt->getOffset(); // should include dst ?
3681 } else { // with old method (The 'tzuser' was processed like the 'tzuserrel')
3682 $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60; // Will not be used anymore
3683 $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60; // Will not be used anymore
3684 }
3685 }
3686 }
3687 }
3688 if (!is_object($outputlangs)) {
3689 $outputlangs = $langs;
3690 }
3691 if (!$format) {
3692 $format = 'daytextshort';
3693 }
3694
3695 // Do we have to reduce the length of date (year on 2 chars) to save space.
3696 // Note: dayinputnoreduce is same than day but no reduction of year length will be done
3697 $reduceformat = (!empty($conf->dol_optimize_smallscreen) && in_array($format, array('day', 'dayhour', 'dayhoursec'))) ? 1 : 0; // Test on original $format param.
3698 $format = preg_replace('/inputnoreduce/', '', $format); // so format 'dayinputnoreduce' is processed like day
3699 $formatwithoutreduce = preg_replace('/reduceformat/', '', $format);
3700 if ($formatwithoutreduce != $format) {
3701 $format = $formatwithoutreduce;
3702 $reduceformat = 1;
3703 } // so format 'dayreduceformat' is processed like day
3704
3705 // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
3706 // TODO Add format daysmallyear and dayhoursmallyear
3707 if ($format == 'day') {
3708 $format = ($outputlangs->trans("FormatDateShort") != "FormatDateShort" ? $outputlangs->trans("FormatDateShort") : $conf->format_date_short);
3709 } elseif ($format == 'hour') {
3710 $format = ($outputlangs->trans("FormatHourShort") != "FormatHourShort" ? $outputlangs->trans("FormatHourShort") : $conf->format_hour_short);
3711 } elseif ($format == 'hourduration') {
3712 $format = ($outputlangs->trans("FormatHourShortDuration") != "FormatHourShortDuration" ? $outputlangs->trans("FormatHourShortDuration") : $conf->format_hour_short_duration);
3713 } elseif ($format == 'daytext') {
3714 $format = ($outputlangs->trans("FormatDateText") != "FormatDateText" ? $outputlangs->trans("FormatDateText") : $conf->format_date_text);
3715 } elseif ($format == 'daytextshort') {
3716 $format = ($outputlangs->trans("FormatDateTextShort") != "FormatDateTextShort" ? $outputlangs->trans("FormatDateTextShort") : $conf->format_date_text_short);
3717 } elseif ($format == 'dayhour') {
3718 $format = ($outputlangs->trans("FormatDateHourShort") != "FormatDateHourShort" ? $outputlangs->trans("FormatDateHourShort") : $conf->format_date_hour_short);
3719 } elseif ($format == 'dayhoursec') {
3720 $format = ($outputlangs->trans("FormatDateHourSecShort") != "FormatDateHourSecShort" ? $outputlangs->trans("FormatDateHourSecShort") : $conf->format_date_hour_sec_short);
3721 } elseif ($format == 'dayhourtext') {
3722 $format = ($outputlangs->trans("FormatDateHourText") != "FormatDateHourText" ? $outputlangs->trans("FormatDateHourText") : $conf->format_date_hour_text);
3723 } elseif ($format == 'dayhourtextshort') {
3724 $format = ($outputlangs->trans("FormatDateHourTextShort") != "FormatDateHourTextShort" ? $outputlangs->trans("FormatDateHourTextShort") : $conf->format_date_hour_text_short);
3725 } elseif ($format == 'dayhourlog') {
3726 // Format not sensitive to language
3727 $format = '%Y%m%d%H%M%S';
3728 } elseif ($format == 'dayhourlogsmall') {
3729 // Format not sensitive to language
3730 $format = '%y%m%d%H%M';
3731 } elseif ($format == 'dayhourldap') {
3732 $format = '%Y%m%d%H%M%SZ';
3733 } elseif ($format == 'dayhourxcard') {
3734 $format = '%Y%m%dT%H%M%SZ';
3735 } elseif ($format == 'dayxcard') {
3736 $format = '%Y%m%d';
3737 } elseif ($format == 'dayrfc') {
3738 $format = '%Y-%m-%d'; // DATE_RFC3339
3739 } elseif ($format == 'dayhourrfc') {
3740 $format = '%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339
3741 } elseif ($format == 'standard') {
3742 $format = '%Y-%m-%d %H:%M:%S';
3743 }
3744
3745 if ($reduceformat) {
3746 $format = str_replace('%Y', '%y', $format);
3747 $format = str_replace('yyyy', 'yy', $format);
3748 }
3749
3750 // Clean format
3751 if (preg_match('/%b/i', $format)) { // There is some text to translate
3752 // We inhibit translation to text made by strftime functions. We will use trans instead later.
3753 $format = str_replace('%b', '__b__', $format);
3754 $format = str_replace('%B', '__B__', $format);
3755 }
3756 if (preg_match('/%a/i', $format)) { // There is some text to translate
3757 // We inhibit translation to text made by strftime functions. We will use trans instead later.
3758 $format = str_replace('%a', '__a__', $format);
3759 $format = str_replace('%A', '__A__', $format);
3760 }
3761
3762 // Analyze date
3763 $reg = array();
3764 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
3765 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"]));
3766 return '';
3767 } 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
3768 // This part of code should not be used anymore.
3769 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);
3770 //if (function_exists('debug_print_backtrace')) debug_print_backtrace();
3771 // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
3772 $syear = (!empty($reg[1]) ? $reg[1] : '');
3773 $smonth = (!empty($reg[2]) ? $reg[2] : '');
3774 $sday = (!empty($reg[3]) ? $reg[3] : '');
3775 $shour = (!empty($reg[4]) ? $reg[4] : '');
3776 $smin = (!empty($reg[5]) ? $reg[5] : '');
3777 $ssec = (!empty($reg[6]) ? $reg[6] : '');
3778
3779 $time = dol_mktime((int) $shour, (int) $smin, (int) $ssec, (int) $smonth, (int) $sday, (int) $syear, true);
3780
3781 if ($to_gmt) {
3782 $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
3783 } else {
3784 $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
3785 }
3786 $dtts = new DateTime();
3787 $dtts->setTimestamp($time);
3788 $dtts->setTimezone($tzo);
3789 $newformat = str_replace(
3790 array('%Y', '%y', '%m', '%d', '%H', '%I', '%M', '%S', '%p', 'T', 'Z', '__a__', '__A__', '__b__', '__B__'),
3791 array('Y', 'y', 'm', 'd', 'H', 'h', 'i', 's', 'A', '__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
3792 $format
3793 );
3794 $ret = $dtts->format($newformat);
3795 $ret = str_replace(
3796 array('__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
3797 array('T', 'Z', '__a__', '__A__', '__b__', '__B__'),
3798 $ret
3799 );
3800 } else {
3801 // Date is a timestamps
3802 if ($time < 100000000000) { // Protection against bad date values
3803 $timetouse = $time + $offsettz + $offsetdst; // TODO We could be able to disable use of offsettz and offsetdst to use only offsettzstring.
3804
3805 if ($to_gmt) {
3806 $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
3807 } else {
3808 $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
3809 }
3810 $dtts = new DateTime();
3811 $dtts->setTimestamp($timetouse);
3812 $dtts->setTimezone($tzo);
3813 $newformat = str_replace(
3814 array('%Y', '%y', '%m', '%d', '%H', '%I', '%M', '%S', '%p', '%w', 'T', 'Z', '__a__', '__A__', '__b__', '__B__'),
3815 array('Y', 'y', 'm', 'd', 'H', 'h', 'i', 's', 'A', 'w', '__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
3816 $format
3817 );
3818 $ret = $dtts->format($newformat);
3819 $ret = str_replace(
3820 array('__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
3821 array('T', 'Z', '__a__', '__A__', '__b__', '__B__'),
3822 $ret
3823 );
3824 //var_dump($ret);exit;
3825 } else {
3826 $ret = 'Bad value '.$time.' for date';
3827 }
3828 }
3829
3830 if (preg_match('/__b__/i', $format)) {
3831 $timetouse = $time + $offsettz + $offsetdst; // TODO We could be able to disable use of offsettz and offsetdst to use only offsettzstring.
3832
3833 if ($to_gmt) {
3834 $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
3835 } else {
3836 $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
3837 }
3838 $dtts = new DateTime();
3839 $dtts->setTimestamp($timetouse);
3840 $dtts->setTimezone($tzo);
3841 $month = (int) $dtts->format("m");
3842 $month = sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'.
3843 if ($encodetooutput) {
3844 $monthtext = $outputlangs->transnoentities('Month'.$month);
3845 $monthtextshort = $outputlangs->transnoentities('MonthShort'.$month);
3846 } else {
3847 $monthtext = $outputlangs->transnoentitiesnoconv('Month'.$month);
3848 $monthtextshort = $outputlangs->transnoentitiesnoconv('MonthShort'.$month);
3849 }
3850 //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
3851 $ret = str_replace('__b__', $monthtextshort, $ret);
3852 $ret = str_replace('__B__', $monthtext, $ret);
3853 //print 'x'.$outputlangs->charset_output.'-'.$ret.'x';
3854 //return $ret;
3855 }
3856 if (preg_match('/__a__/i', $format)) {
3857 //print "time=$time offsettz=$offsettz offsetdst=$offsetdst offsettzstring=$offsettzstring";
3858 $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
3859
3860 if ($to_gmt) {
3861 $tzo = new DateTimeZone('UTC');
3862 } else {
3863 $tzo = new DateTimeZone(date_default_timezone_get());
3864 }
3865 $dtts = new DateTime();
3866 $dtts->setTimestamp($timetouse);
3867 $dtts->setTimezone($tzo);
3868 $w = $dtts->format("w");
3869 $dayweek = $outputlangs->transnoentitiesnoconv('Day'.$w);
3870
3871 $ret = str_replace('__A__', $dayweek, $ret);
3872 $ret = str_replace('__a__', dol_substr($dayweek, 0, 3), $ret);
3873 }
3874
3875 return $ret;
3876}
3877
3878
3899function dol_getdate($timestamp, $fast = false, $forcetimezone = '')
3900{
3901 if ($timestamp === '') {
3902 return array();
3903 }
3904
3905 $datetimeobj = new DateTime();
3906 $datetimeobj->setTimestamp($timestamp); // Use local PHP server timezone
3907 if ($forcetimezone) {
3908 $datetimeobj->setTimezone(new DateTimeZone($forcetimezone == 'gmt' ? 'UTC' : $forcetimezone)); // (add timezone relative to the date entered)
3909 }
3910 $arrayinfo = array(
3911 'year' => ((int) date_format($datetimeobj, 'Y')),
3912 'mon' => ((int) date_format($datetimeobj, 'm')),
3913 'mday' => ((int) date_format($datetimeobj, 'd')),
3914 'wday' => ((int) date_format($datetimeobj, 'w')),
3915 'yday' => ((int) date_format($datetimeobj, 'z')),
3916 'hours' => ((int) date_format($datetimeobj, 'H')),
3917 'minutes' => ((int) date_format($datetimeobj, 'i')),
3918 'seconds' => ((int) date_format($datetimeobj, 's')),
3919 '0' => $timestamp
3920 );
3921
3922 return $arrayinfo;
3923}
3924
3946function dol_mktime($hour, $minute, $second, $month, $day, $year, $gm = 'auto', $check = 1)
3947{
3948 global $conf;
3949 //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
3950
3951 if ($gm === 'auto') {
3952 $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
3953 }
3954 //print 'gm:'.$gm.' gm === auto:'.($gm === 'auto').'<br>';exit;
3955
3956 // Clean parameters
3957 if ($hour == -1 || empty($hour)) {
3958 $hour = 0;
3959 }
3960 if ($minute == -1 || empty($minute)) {
3961 $minute = 0;
3962 }
3963 if ($second == -1 || empty($second)) {
3964 $second = 0;
3965 }
3966
3967 // Check parameters
3968 if ($check) {
3969 if (!$month || !$day) {
3970 return '';
3971 }
3972 if ($day > 31) {
3973 return '';
3974 }
3975 if ($month > 12) {
3976 return '';
3977 }
3978 if ($hour < 0 || $hour > 24) {
3979 return '';
3980 }
3981 if ($minute < 0 || $minute > 60) {
3982 return '';
3983 }
3984 if ($second < 0 || $second > 60) {
3985 return '';
3986 }
3987 }
3988
3989 if (empty($gm) || ($gm === 'server' || $gm === 'tzserver')) {
3990 $default_timezone = @date_default_timezone_get(); // Example 'Europe/Berlin'
3991 $localtz = new DateTimeZone($default_timezone);
3992 } elseif ($gm === 'user' || $gm === 'tzuser' || $gm === 'tzuserrel') {
3993 // We use dol_tz_string first because it is more reliable.
3994 $default_timezone = (empty($_SESSION["dol_tz_string"]) ? @date_default_timezone_get() : $_SESSION["dol_tz_string"]); // Example 'Europe/Berlin'
3995 try {
3996 $localtz = new DateTimeZone($default_timezone);
3997 } catch (Exception $e) {
3998 dol_syslog("Warning dol_tz_string contains an invalid value ".json_encode($_SESSION["dol_tz_string"] ?? null), LOG_WARNING);
3999 $default_timezone = @date_default_timezone_get();
4000 }
4001 } elseif (strrpos($gm, "tz,") !== false) {
4002 $timezone = str_replace("tz,", "", $gm); // Example 'tz,Europe/Berlin'
4003 try {
4004 $localtz = new DateTimeZone($timezone);
4005 } catch (Exception $e) {
4006 dol_syslog("Warning passed timezone contains an invalid value ".$timezone, LOG_WARNING);
4007 }
4008 }
4009
4010 if (empty($localtz)) {
4011 $localtz = new DateTimeZone('UTC');
4012 }
4013 //var_dump($localtz);
4014 //var_dump($year.'-'.$month.'-'.$day.'-'.$hour.'-'.$minute);
4015 $dt = new DateTime('now', $localtz);
4016 $dt->setDate((int) $year, (int) $month, (int) $day);
4017 $dt->setTime((int) $hour, (int) $minute, (int) $second);
4018 $date = $dt->getTimestamp(); // should include daylight saving time
4019 //var_dump($date);
4020 return $date;
4021}
4022
4023
4034function dol_now($mode = 'auto')
4035{
4036 $ret = 0;
4037
4038 if ($mode === 'auto') {
4039 $mode = 'gmt';
4040 }
4041
4042 if ($mode == 'gmt') {
4043 $ret = time(); // Time for now at greenwich.
4044 } elseif ($mode == 'tzserver') { // Time for now with PHP server timezone added
4045 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
4046 $tzsecond = getServerTimeZoneInt('now'); // Contains tz+dayling saving time
4047 $ret = (int) (dol_now('gmt') + ($tzsecond * 3600));
4048 //} elseif ($mode == 'tzref') {// Time for now with parent company timezone is added
4049 // require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
4050 // $tzsecond=getParentCompanyTimeZoneInt(); // Contains tz+dayling saving time
4051 // $ret=dol_now('gmt')+($tzsecond*3600);
4052 //}
4053 } elseif ($mode == 'tzuser' || $mode == 'tzuserrel') {
4054 // Time for now with user timezone added
4055 //print 'time: '.time();
4056 $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60;
4057 $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60;
4058 $ret = (int) (dol_now('gmt') + ($offsettz + $offsetdst));
4059 }
4060
4061 return $ret;
4062}
4063
4064
4073function dol_print_size($size, $shortvalue = 0, $shortunit = 0)
4074{
4075 global $conf, $langs;
4076 $level = 1024;
4077
4078 if (!empty($conf->dol_optimize_smallscreen)) {
4079 $shortunit = 1;
4080 }
4081
4082 // Set value text
4083 if (empty($shortvalue) || $size < ($level * 10)) {
4084 $ret = $size;
4085 $textunitshort = $langs->trans("b");
4086 $textunitlong = $langs->trans("Bytes");
4087 } else {
4088 $ret = round($size / $level, 0);
4089 $textunitshort = $langs->trans("Kb");
4090 $textunitlong = $langs->trans("KiloBytes");
4091 }
4092 // Use long or short text unit
4093 if (empty($shortunit)) {
4094 $ret .= ' '.$textunitlong;
4095 } else {
4096 $ret .= ' '.$textunitshort;
4097 }
4098
4099 return $ret;
4100}
4101
4112function dol_print_url($url, $target = '_blank', $max = 32, $withpicto = 0, $morecss = '')
4113{
4114 global $langs;
4115
4116 if (empty($url)) {
4117 return '';
4118 }
4119
4120 $linkstart = '<a href="';
4121 if (!preg_match('/^http/i', $url)) {
4122 $linkstart .= 'http://';
4123 }
4124 $linkstart .= $url;
4125 $linkstart .= '"';
4126 if ($target) {
4127 $linkstart .= ' target="'.$target.'"';
4128 }
4129 $linkstart .= ' title="'.$langs->trans("URL").': '.$url.'"';
4130 $linkstart .= '>';
4131
4132 $link = '';
4133 if (!preg_match('/^http/i', $url)) {
4134 $link .= 'http://';
4135 }
4136 $link .= dol_trunc($url, $max);
4137
4138 $linkend = '</a>';
4139
4140 if ($morecss == 'float') { // deprecated
4141 return '<div class="nospan'.($morecss ? ' '.$morecss : '').'" style="margin-right: 10px">'.($withpicto ? img_picto($langs->trans("Url"), 'globe', 'class="paddingrightonly"') : '').$link.'</div>';
4142 } else {
4143 return $linkstart.'<span class="nospan'.($morecss ? ' '.$morecss : '').'" style="margin-right: 10px">'.($withpicto ? img_picto('', 'globe', 'class="paddingrightonly"') : '').$link.'</span>'.$linkend;
4144 }
4145}
4146
4160function dol_print_email($email, $cid = 0, $socid = 0, $addlink = 0, $max = 64, $showinvalid = 1, $withpicto = 0, $morecss = 'paddingrightonly')
4161{
4162 global $user, $langs, $hookmanager;
4163
4164 //global $conf; $conf->global->AGENDA_ADDACTIONFOREMAIL = 1;
4165 //$showinvalid = 1; $email = 'rrrrr';
4166
4167 $newemail = dol_escape_htmltag($email);
4168
4169 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') && $withpicto) {
4170 $withpicto = 0;
4171 }
4172
4173 if (empty($email)) {
4174 return '&nbsp;';
4175 }
4176
4177 if ($addlink == 1) {
4178 $newemail = '<a class="'.($morecss ? $morecss : '').'" style="text-overflow: ellipsis;" href="';
4179 if (!preg_match('/^mailto:/i', $email)) {
4180 $newemail .= 'mailto:';
4181 }
4182 $newemail .= $email;
4183 $newemail .= '" target="_blank">';
4184
4185 $newemail .= ($withpicto ? img_picto($langs->trans("EMail").' : '.$email, (is_numeric($withpicto) ? 'email' : $withpicto), 'class="paddingrightonly"') : '');
4186
4187 if ($max > 0) {
4188 $newemail .= dol_trunc($email, $max);
4189 } else {
4190 $newemail .= $email;
4191 }
4192 $newemail .= '</a>';
4193 if ($showinvalid && !isValidEmail($email)) {
4194 $langs->load("errors");
4195 $newemail .= img_warning($langs->trans("ErrorBadEMail", $email), '', 'paddingrightonly');
4196 }
4197
4198 if (($cid || $socid) && isModEnabled('agenda') && $user->hasRight("agenda", "myactions", "create")) {
4199 $type = 'AC_EMAIL';
4200 $linktoaddaction = '';
4201 if (getDolGlobalString('AGENDA_ADDACTIONFOREMAIL')) {
4202 $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>';
4203 }
4204 if ($linktoaddaction) {
4205 $newemail = '<div>'.$newemail.' '.$linktoaddaction.'</div>';
4206 }
4207 }
4208 } elseif ($addlink === 'thirdparty') {
4209 $tmpnewemail = '<a class="'.($morecss ? $morecss : '').'" style="text-overflow: ellipsis;" href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$socid.'&action=presend&mode=init#formmailbeforetitle">';
4210 $tmpnewemail .= ($withpicto ? img_picto($langs->trans("EMail").' : '.$email, (is_numeric($withpicto) ? 'email' : $withpicto), 'class="paddingrightonly"') : '');
4211 if ($withpicto == 1) {
4212 $tmpnewemail .= $newemail;
4213 }
4214 $tmpnewemail .= '</a>';
4215
4216 $newemail = $tmpnewemail;
4217 } else {
4218 $newemail = ($withpicto ? img_picto($langs->trans("EMail").' : '.$email, (is_numeric($withpicto) ? 'email' : $withpicto), 'class="paddingrightonly"') : '').$newemail;
4219
4220 if ($showinvalid && !isValidEmail($email)) {
4221 $langs->load("errors");
4222 $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
4223 }
4224 }
4225
4226 //$rep = '<div class="nospan" style="margin-right: 10px">';
4227 //$rep = ($withpicto ? img_picto($langs->trans("EMail").' : '.$email, (is_numeric($withpicto) ? 'email' : $withpicto), 'class="paddingrightonly"') : '').$newemail;
4228 //$rep .= '</div>';
4229 $rep = $newemail;
4230
4231 if ($hookmanager) {
4232 $parameters = array('cid' => $cid, 'socid' => $socid, 'addlink' => $addlink, 'picto' => $withpicto);
4233
4234 $reshook = $hookmanager->executeHooks('printEmail', $parameters, $email);
4235 if ($reshook > 0) {
4236 $rep = '';
4237 }
4238 $rep .= $hookmanager->resPrint;
4239 }
4240
4241 return $rep;
4242}
4243
4249function getArrayOfSocialNetworks()
4250{
4251 global $conf, $db;
4252
4253 $socialnetworks = array();
4254 // Enable caching of array
4255 require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php';
4256 $cachekey = 'socialnetworks_' . $conf->entity;
4257 $dataretrieved = dol_getcache($cachekey);
4258 if (!is_null($dataretrieved)) {
4259 $socialnetworks = $dataretrieved;
4260 } else {
4261 $sql = "SELECT rowid, code, label, url, icon, active FROM ".MAIN_DB_PREFIX."c_socialnetworks";
4262 $sql .= " WHERE entity=".$conf->entity;
4263 $resql = $db->query($sql);
4264 if ($resql) {
4265 while ($obj = $db->fetch_object($resql)) {
4266 $socialnetworks[$obj->code] = array(
4267 'rowid' => $obj->rowid,
4268 'label' => $obj->label,
4269 'url' => $obj->url,
4270 'icon' => $obj->icon,
4271 'active' => $obj->active,
4272 );
4273 }
4274 }
4275 dol_setcache($cachekey, $socialnetworks); // If setting cache fails, this is not a problem, so we do not test result.
4276 }
4277 return $socialnetworks;
4278}
4279
4290function dol_print_socialnetworks($value, $contactid, $socid, $type, $dictsocialnetworks = array())
4291{
4292 global $hookmanager, $langs, $user;
4293
4294 $htmllink = $value;
4295
4296 if (empty($value)) {
4297 return '&nbsp;';
4298 }
4299
4300 if (!empty($type)) {
4301 $htmllink = '<div class="divsocialnetwork inline-block valignmiddle">';
4302 // Use dictionary definition for picto $dictsocialnetworks[$type]['icon']
4303 $htmllink .= '<span class="fab pictofixedwidth ' . ($dictsocialnetworks[$type]['icon'] ? $dictsocialnetworks[$type]['icon'] : 'fa-link') . '"></span>';
4304 if ($type == 'skype') {
4305 $htmllink .= dol_escape_htmltag($value);
4306 $htmllink .= '&nbsp; <a href="skype:';
4307 $htmllink .= dol_string_nospecial($value, '_', '', array('@'));
4308 $htmllink .= '?call" alt="' . $langs->trans("Call") . '&nbsp;' . $value . '" title="' . dol_escape_htmltag($langs->trans("Call") . ' ' . $value) . '">';
4309 $htmllink .= '<img src="' . DOL_URL_ROOT . '/theme/common/skype_callbutton.png" border="0">';
4310 $htmllink .= '</a><a href="skype:';
4311 $htmllink .= dol_string_nospecial($value, '_', '', array('@'));
4312 $htmllink .= '?chat" alt="' . $langs->trans("Chat") . '&nbsp;' . $value . '" title="' . dol_escape_htmltag($langs->trans("Chat") . ' ' . $value) . '">';
4313 $htmllink .= '<img class="paddingleft" src="' . DOL_URL_ROOT . '/theme/common/skype_chatbutton.png" border="0">';
4314 $htmllink .= '</a>';
4315 if (($contactid || $socid) && isModEnabled('agenda') && $user->hasRight('agenda', 'myactions', 'create')) {
4316 $addlink = 'AC_SKYPE';
4317 $link = '';
4318 if (getDolGlobalString('AGENDA_ADDACTIONFORSKYPE')) {
4319 $link = '<a href="' . DOL_URL_ROOT . '/comm/action/card.php?action=create&backtopage=1&actioncode=' . $addlink . '&contactid=' . $contactid . '&socid=' . $socid . '">' . img_object($langs->trans("AddAction"), "calendar") . '</a>';
4320 }
4321 $htmllink .= ($link ? ' ' . $link : '');
4322 }
4323 } else {
4324 if (!empty($dictsocialnetworks[$type]['url'])) {
4325 $tmpvirginurl = preg_replace('/\/?{socialid}/', '', $dictsocialnetworks[$type]['url']);
4326 if ($tmpvirginurl) {
4327 $value = preg_replace('/^www\.' . preg_quote($tmpvirginurl, '/') . '\/?/', '', $value);
4328 $value = preg_replace('/^' . preg_quote($tmpvirginurl, '/') . '\/?/', '', $value);
4329
4330 $tmpvirginurl3 = preg_replace('/^https:\/\//i', 'https://www.', $tmpvirginurl);
4331 if ($tmpvirginurl3) {
4332 $value = preg_replace('/^www\.' . preg_quote($tmpvirginurl3, '/') . '\/?/', '', $value);
4333 $value = preg_replace('/^' . preg_quote($tmpvirginurl3, '/') . '\/?/', '', $value);
4334 }
4335
4336 $tmpvirginurl2 = preg_replace('/^https?:\/\//i', '', $tmpvirginurl);
4337 if ($tmpvirginurl2) {
4338 $value = preg_replace('/^www\.' . preg_quote($tmpvirginurl2, '/') . '\/?/', '', $value);
4339 $value = preg_replace('/^' . preg_quote($tmpvirginurl2, '/') . '\/?/', '', $value);
4340 }
4341 }
4342 if (preg_match('/^https?:\/\//i', $value)) {
4343 $link = $value;
4344 } else {
4345 $link = str_replace('{socialid}', $value, $dictsocialnetworks[$type]['url']);
4346 }
4347 $valuetoshow = $value;
4348 $valuetoshow = preg_replace('/https:\/\/www\.(twitter|x|linkedin)\.com\/?/', '', $valuetoshow);
4349 if (preg_match('/^https?:\/\//i', $link)) {
4350 $htmllink .= '<a href="' . dol_sanitizeUrl($link, 0) . '" target="_blank" rel="noopener noreferrer">' . dol_escape_htmltag($valuetoshow) . '</a>';
4351 } else {
4352 $htmllink .= '<a href="' . dol_sanitizeUrl($link, 1) . '" target="_blank" rel="noopener noreferrer">' . dol_escape_htmltag($valuetoshow) . '</a>';
4353 }
4354 } else {
4355 $htmllink .= dol_escape_htmltag($value);
4356 }
4357 }
4358 $htmllink .= '</div>';
4359 } else {
4360 $langs->load("errors");
4361 $htmllink .= img_warning($langs->trans("ErrorBadSocialNetworkValue", $value));
4362 }
4363
4364 if ($hookmanager) {
4365 $parameters = array(
4366 'value' => $value,
4367 'cid' => $contactid,
4368 'socid' => $socid,
4369 'type' => $type,
4370 'dictsocialnetworks' => $dictsocialnetworks,
4371 );
4372
4373 $reshook = $hookmanager->executeHooks('printSocialNetworks', $parameters);
4374 if ($reshook > 0) {
4375 $htmllink = '';
4376 }
4377 $htmllink .= $hookmanager->resPrint;
4378 }
4379
4380 return $htmllink;
4381}
4382
4392function dol_print_profids($profID, $profIDtype, $countrycode = '', $addcpButton = 1)
4393{
4394 global $mysoc;
4395
4396 if (empty($profID) || empty($profIDtype)) {
4397 return '';
4398 }
4399 if (empty($countrycode)) {
4400 $countrycode = $mysoc->country_code;
4401 }
4402 $newProfID = $profID;
4403 $id = substr($profIDtype, -1);
4404 $ret = '';
4405 if (strtoupper($countrycode) == 'FR') {
4406 // France
4407 // (see https://www.economie.gouv.fr/entreprises/numeros-identification-entreprise)
4408
4409 if ($id == 1 && dol_strlen($newProfID) == 9) {
4410 // SIREN (ex: 123 123 123)
4411 $newProfID = substr($newProfID, 0, 3).' '.substr($newProfID, 3, 3).' '.substr($newProfID, 6, 3);
4412 }
4413 if ($id == 2 && dol_strlen($newProfID) == 14) {
4414 // SIRET (ex: 123 123 123 12345)
4415 $newProfID = substr($newProfID, 0, 3).' '.substr($newProfID, 3, 3).' '.substr($newProfID, 6, 3).' '.substr($newProfID, 9, 5);
4416 }
4417 if ($id == 3 && dol_strlen($newProfID) == 5) {
4418 // NAF/APE (ex: 69.20Z)
4419 $newProfID = substr($newProfID, 0, 2).'.'.substr($newProfID, 2, 3);
4420 }
4421 if ($profIDtype === 'VAT' && dol_strlen($newProfID) == 13) {
4422 // TVA intracommunautaire (ex: FR12 123 123 123)
4423 $newProfID = substr($newProfID, 0, 4).' '.substr($newProfID, 4, 3).' '.substr($newProfID, 7, 3).' '.substr($newProfID, 10, 3);
4424 }
4425 }
4426 if (!empty($addcpButton)) {
4427 $ret = showValueWithClipboardCPButton(dol_escape_htmltag($profID), ($addcpButton == 1 ? 1 : 0), $newProfID);
4428 } else {
4429 $ret = $newProfID;
4430 }
4431 return $ret;
4432}
4433
4449function dol_print_phone($phone, $countrycode = '', $cid = 0, $socid = 0, $addlink = '', $separ = "&nbsp;", $withpicto = '', $titlealt = '', $adddivfloat = 0, $morecss = 'paddingright')
4450{
4451 global $conf, $user, $langs, $mysoc, $hookmanager;
4452
4453 // Clean phone parameter
4454 $phone = is_null($phone) ? '' : preg_replace("/[\s.-]/", "", trim($phone));
4455 if (empty($phone)) {
4456 return '';
4457 }
4458 if (getDolGlobalString('MAIN_PHONE_SEPAR')) {
4459 $separ = getDolGlobalString('MAIN_PHONE_SEPAR');
4460 }
4461 if (empty($countrycode) && is_object($mysoc)) {
4462 $countrycode = $mysoc->country_code;
4463 }
4464
4465 // Short format for small screens
4466 if (!empty($conf->dol_optimize_smallscreen) && $separ != 'hidenum') {
4467 $separ = '';
4468 }
4469
4470 $newphone = $phone;
4471 $newphonewa = $phone;
4472 if (strtoupper($countrycode) == "FR") {
4473 // France
4474 if (dol_strlen($phone) == 10) {
4475 $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);
4476 } elseif (dol_strlen($phone) == 7) {
4477 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 2);
4478 } elseif (dol_strlen($phone) == 9) {
4479 $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 2).$separ.substr($newphone, 7, 2);
4480 } elseif (dol_strlen($phone) == 11) {
4481 $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);
4482 } elseif (dol_strlen($phone) == 12) {
4483 $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);
4484 } elseif (dol_strlen($phone) == 13) {
4485 $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);
4486 }
4487 } elseif (strtoupper($countrycode) == "CA") {
4488 if (dol_strlen($phone) == 10) {
4489 $newphone = ($separ != '' ? '(' : '').substr($newphone, 0, 3).($separ != '' ? ')' : '').$separ.substr($newphone, 3, 3).($separ != '' ? '-' : '').substr($newphone, 6, 4);
4490 }
4491 } elseif (strtoupper($countrycode) == "PT") {//Portugal
4492 if (dol_strlen($phone) == 13) {//ex: +351_ABC_DEF_GHI
4493 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
4494 }
4495 } elseif (strtoupper($countrycode) == "SR") {//Suriname
4496 if (dol_strlen($phone) == 10) {//ex: +597_ABC_DEF
4497 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3);
4498 } elseif (dol_strlen($phone) == 11) {//ex: +597_ABC_DEFG
4499 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 4);
4500 }
4501 } elseif (strtoupper($countrycode) == "DE") {//Allemagne
4502 if (dol_strlen($phone) == 14) {//ex: +49_ABCD_EFGH_IJK
4503 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 4).$separ.substr($newphone, 11, 3);
4504 } elseif (dol_strlen($phone) == 13) {//ex: +49_ABC_DEFG_HIJ
4505 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 4).$separ.substr($newphone, 10, 3);
4506 }
4507 } elseif (strtoupper($countrycode) == "ES") {//Espagne
4508 if (dol_strlen($phone) == 12) {//ex: +34_ABC_DEF_GHI
4509 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
4510 }
4511 } elseif (strtoupper($countrycode) == "BF") {// Burkina Faso
4512 if (dol_strlen($phone) == 12) {//ex : +22 A BC_DE_FG_HI
4513 $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);
4514 }
4515 } elseif (strtoupper($countrycode) == "RO") {// Roumanie
4516 if (dol_strlen($phone) == 12) {//ex : +40 AB_CDE_FG_HI
4517 $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);
4518 }
4519 } elseif (strtoupper($countrycode) == "TR") {//Turquie
4520 if (dol_strlen($phone) == 13) {//ex : +90 ABC_DEF_GHIJ
4521 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
4522 }
4523 } elseif (strtoupper($countrycode) == "US") {//Etat-Unis
4524 if (dol_strlen($phone) == 12) {//ex: +1 ABC_DEF_GHIJ
4525 $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
4526 }
4527 } elseif (strtoupper($countrycode) == "MX") {//Mexique
4528 if (dol_strlen($phone) == 12) {//ex: +52 ABCD_EFG_HI
4529 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
4530 } elseif (dol_strlen($phone) == 11) {//ex: +52 AB_CD_EF_GH
4531 $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);
4532 } elseif (dol_strlen($phone) == 13) {//ex: +52 ABC_DEF_GHIJ
4533 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
4534 }
4535 } elseif (strtoupper($countrycode) == "ML") {//Mali
4536 if (dol_strlen($phone) == 12) {//ex: +223 AB_CD_EF_GH
4537 $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);
4538 }
4539 } elseif (strtoupper($countrycode) == "TH") {//Thaïlande
4540 if (dol_strlen($phone) == 11) {//ex: +66_ABC_DE_FGH
4541 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
4542 } elseif (dol_strlen($phone) == 12) {//ex: +66_A_BCD_EF_GHI
4543 $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);
4544 }
4545 } elseif (strtoupper($countrycode) == "MU") {
4546 //Maurice
4547 if (dol_strlen($phone) == 11) {//ex: +230_ABC_DE_FG
4548 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2);
4549 } elseif (dol_strlen($phone) == 12) {//ex: +230_ABCD_EF_GH
4550 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
4551 }
4552 } elseif (strtoupper($countrycode) == "ZA") {//Afrique du sud
4553 if (dol_strlen($phone) == 12) {//ex: +27_AB_CDE_FG_HI
4554 $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);
4555 }
4556 } elseif (strtoupper($countrycode) == "SY") {//Syrie
4557 if (dol_strlen($phone) == 12) {//ex: +963_AB_CD_EF_GH
4558 $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);
4559 } elseif (dol_strlen($phone) == 13) {//ex: +963_AB_CD_EF_GHI
4560 $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);
4561 }
4562 } elseif (strtoupper($countrycode) == "AE") {//Emirats Arabes Unis
4563 if (dol_strlen($phone) == 12) {//ex: +971_ABC_DEF_GH
4564 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
4565 } elseif (dol_strlen($phone) == 13) {//ex: +971_ABC_DEF_GHI
4566 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
4567 } elseif (dol_strlen($phone) == 14) {//ex: +971_ABC_DEF_GHIK
4568 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 4);
4569 }
4570 } elseif (strtoupper($countrycode) == "DZ") {//Algérie
4571 if (dol_strlen($phone) == 13) {//ex: +213_ABC_DEF_GHI
4572 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
4573 }
4574 } elseif (strtoupper($countrycode) == "BE") {//Belgique
4575 if (dol_strlen($phone) == 11) {//ex: +32_ABC_DE_FGH
4576 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
4577 } elseif (dol_strlen($phone) == 12) {//ex: +32_ABC_DEF_GHI
4578 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
4579 }
4580 } elseif (strtoupper($countrycode) == "PF") {//Polynésie française
4581 if (dol_strlen($phone) == 12) {//ex: +689_AB_CD_EF_GH
4582 $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);
4583 }
4584 } elseif (strtoupper($countrycode) == "CO") {//Colombie
4585 if (dol_strlen($phone) == 13) {//ex: +57_ABC_DEF_GH_IJ
4586 $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);
4587 }
4588 } elseif (strtoupper($countrycode) == "JO") {//Jordanie
4589 if (dol_strlen($phone) == 12) {//ex: +962_A_BCD_EF_GH
4590 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 1).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
4591 }
4592 } elseif (strtoupper($countrycode) == "JM") {//Jamaïque
4593 if (dol_strlen($newphone) == 12) {//ex: +1867_ABC_DEFG
4594 $newphone = substr($newphone, 0, 5).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
4595 }
4596 } elseif (strtoupper($countrycode) == "MG") {//Madagascar
4597 if (dol_strlen($phone) == 13) {//ex: +261_AB_CD_EFG_HI
4598 $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);
4599 }
4600 } elseif (strtoupper($countrycode) == "GB") {//Royaume uni
4601 if (dol_strlen($phone) == 13) {//ex: +44_ABCD_EFG_HIJ
4602 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
4603 }
4604 } elseif (strtoupper($countrycode) == "CH") {//Suisse
4605 if (dol_strlen($phone) == 12) {//ex: +41_AB_CDE_FG_HI
4606 $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);
4607 } elseif (dol_strlen($phone) == 15) {// +41_AB_CDE_FGH_IJKL
4608 $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);
4609 }
4610 } elseif (strtoupper($countrycode) == "TN") {//Tunisie
4611 if (dol_strlen($phone) == 12) {//ex: +216_AB_CDE_FGH
4612 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
4613 }
4614 } elseif (strtoupper($countrycode) == "GF") {//Guyane francaise
4615 if (dol_strlen($phone) == 13) {//ex: +594_ABC_DE_FG_HI (ABC=594 de nouveau)
4616 $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);
4617 }
4618 } elseif (strtoupper($countrycode) == "GP") {//Guadeloupe
4619 if (dol_strlen($phone) == 13) {//ex: +590_ABC_DE_FG_HI (ABC=590 de nouveau)
4620 $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);
4621 }
4622 } elseif (strtoupper($countrycode) == "MQ") {//Martinique
4623 if (dol_strlen($phone) == 13) {//ex: +596_ABC_DE_FG_HI (ABC=596 de nouveau)
4624 $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);
4625 }
4626 } elseif (strtoupper($countrycode) == "IT") {//Italie
4627 if (dol_strlen($phone) == 12) {//ex: +39_ABC_DEF_GHI
4628 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
4629 } elseif (dol_strlen($phone) == 13) {//ex: +39_ABC_DEF_GH_IJ
4630 $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);
4631 }
4632 } elseif (strtoupper($countrycode) == "AU") {
4633 //Australie
4634 if (dol_strlen($phone) == 12) {
4635 //ex: +61_A_BCDE_FGHI
4636 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 4);
4637 }
4638 } elseif (strtoupper($countrycode) == "LU") {
4639 // Luxembourg
4640 if (dol_strlen($phone) == 10) {// fix 6 digits +352_AA_BB_CC
4641 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2);
4642 } elseif (dol_strlen($phone) == 11) {// fix 7 digits +352_AA_BB_CC_D
4643 $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);
4644 } elseif (dol_strlen($phone) == 12) {// fix 8 digits +352_AA_BB_CC_DD
4645 $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);
4646 } elseif (dol_strlen($phone) == 13) {// mobile +352_AAA_BB_CC_DD
4647 $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);
4648 }
4649 } elseif (strtoupper($countrycode) == "PE") {
4650 // Peru
4651 if (dol_strlen($phone) == 7) {// fix 7 chiffres without code AAA_BBBB
4652 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4);
4653 } elseif (dol_strlen($phone) == 9) {// mobile add code and fix 9 chiffres +51_AAA_BBB_CCC
4654 $newphonewa = '+51'.$newphone;
4655 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3);
4656 } elseif (dol_strlen($phone) == 11) {// fix 11 chiffres +511_AAA_BBBB
4657 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 4);
4658 } elseif (dol_strlen($phone) == 12) {// mobile +51_AAA_BBB_CCC
4659 $newphonewa = $newphone;
4660 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
4661 }
4662 } elseif (strtoupper($countrycode) == "IN") {//India
4663 if (dol_strlen($phone) == 13) {
4664 if ($withpicto == 'phone') {//ex: +91_AB_CDEF_GHIJ
4665 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 4).$separ.substr($newphone, 9, 4);
4666 } else {//ex: +91_ABCDE_FGHIJ
4667 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 5).$separ.substr($newphone, 8, 5);
4668 }
4669 }
4670 }
4671
4672 $newphoneastart = $newphoneaend = '';
4673 if (!empty($addlink)) { // Link on phone number (+ link to add action if conf->global->AGENDA_ADDACTIONFORPHONE set)
4674 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
4675 $newphoneastart = '<a href="tel:'.urlencode($phone).'">';
4676 $newphoneaend .= '</a>';
4677 } elseif (isModEnabled('clicktodial') && $addlink == 'AC_TEL') { // If click to dial, we use click to dial url
4678 if (empty($user->clicktodial_loaded)) {
4679 $user->fetch_clicktodial();
4680 }
4681
4682 // Define urlmask
4683 $urlmask = getDolGlobalString('CLICKTODIAL_URL', 'ErrorClickToDialModuleNotConfigured');
4684 if (!empty($user->clicktodial_url)) {
4685 $urlmask = $user->clicktodial_url;
4686 }
4687
4688 $clicktodial_poste = (!empty($user->clicktodial_poste) ? urlencode($user->clicktodial_poste) : '');
4689 $clicktodial_login = (!empty($user->clicktodial_login) ? urlencode($user->clicktodial_login) : '');
4690 $clicktodial_password = (!empty($user->clicktodial_password) ? urlencode($user->clicktodial_password) : '');
4691 // This line is for backward compatibility @phan-suppress-next-line PhanPluginPrintfVariableFormatString
4692 $url = sprintf($urlmask, urlencode($phone), $clicktodial_poste, $clicktodial_login, $clicktodial_password);
4693 // Those lines are for substitution
4694 $substitarray = array('__PHONEFROM__' => $clicktodial_poste,
4695 '__PHONETO__' => urlencode($phone),
4696 '__LOGIN__' => $clicktodial_login,
4697 '__PASS__' => $clicktodial_password);
4698 $url = make_substitutions($url, $substitarray);
4699 if (!getDolGlobalString('CLICKTODIAL_DO_NOT_USE_AJAX_CALL')) {
4700 // Default and recommended: New method using ajax without submitting a page making a javascript history.go(-1) back
4701 $newphoneastart = '<a href="'.$url.'" class="cssforclicktodial">'; // Call of ajax is handled by the lib_foot.js.php on class 'cssforclicktodial'
4702 $newphoneaend = '</a>';
4703 } else {
4704 // Old method
4705 $newphoneastart = '<a href="'.$url.'"';
4706 if (getDolGlobalString('CLICKTODIAL_FORCENEWTARGET')) {
4707 $newphoneastart .= ' target="_blank" rel="noopener noreferrer"';
4708 }
4709 $newphoneastart .= '>';
4710 $newphoneaend .= '</a>';
4711 }
4712 }
4713
4714 //if (($cid || $socid) && isModEnabled('agenda') && $user->hasRight('agenda', 'myactions', 'create'))
4715 if (isModEnabled('agenda') && $user->hasRight("agenda", "myactions", "create")) {
4716 $type = 'AC_TEL';
4717 $addlinktoagenda = '';
4718 if ($addlink == 'AC_FAX') {
4719 $type = 'AC_FAX';
4720 }
4721 if (getDolGlobalString('AGENDA_ADDACTIONFORPHONE')) {
4722 $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>';
4723 }
4724 if ($addlinktoagenda) {
4725 $newphone = '<span>'.$newphone.' '.$addlinktoagenda.'</span>';
4726 }
4727 }
4728 }
4729
4730 if (getDolGlobalString('CONTACT_PHONEMOBILE_SHOW_LINK_TO_WHATSAPP') && $withpicto == 'mobile') {
4731 // Link to Whatsapp
4732 $newphone .= ' <a href="https://wa.me/'.$newphonewa.'" target="_blank"';// Use api to whatasapp contacts
4733 $newphone .= '><span class="paddingright fab fa-whatsapp" style="color:#25D366;" title="WhatsApp"></span></a>';
4734 }
4735
4736 if (empty($titlealt)) {
4737 $titlealt = ($withpicto == 'fax' ? $langs->trans("Fax") : $langs->trans("Phone"));
4738 }
4739 $rep = '';
4740
4741 if ($hookmanager) {
4742 $parameters = array('countrycode' => $countrycode, 'cid' => $cid, 'socid' => $socid, 'titlealt' => $titlealt, 'picto' => $withpicto);
4743 $reshook = $hookmanager->executeHooks('printPhone', $parameters, $phone);
4744 $rep .= $hookmanager->resPrint;
4745 }
4746 if (empty($reshook)) {
4747 $picto = '';
4748 if ($withpicto) {
4749 if ($withpicto == 'fax') {
4750 $picto = 'phoning_fax';
4751 } elseif ($withpicto == 'phone') {
4752 $picto = 'phoning';
4753 } elseif ($withpicto == 'mobile') {
4754 $picto = 'phoning_mobile';
4755 } else {
4756 $picto = '';
4757 }
4758 }
4759 if ($adddivfloat == 1) {
4760 $rep .= '<div class="nospan float'.($morecss ? ' '.$morecss : '').'">';
4761 } elseif (empty($adddivfloat)) {
4762 $rep .= '<span'.($morecss ? ' class="'.$morecss.'"' : '').'>';
4763 }
4764
4765 $rep .= $newphoneastart;
4766 $rep .= ($withpicto ? img_picto($titlealt, 'object_'.$picto.'.png') : '');
4767 if ($separ != 'hidenum') {
4768 $rep .= ($withpicto ? ' ' : '').$newphone;
4769 }
4770 $rep .= $newphoneaend;
4771
4772 if ($adddivfloat == 1) {
4773 $rep .= '</div>';
4774 } elseif (empty($adddivfloat)) {
4775 $rep .= '</span>';
4776 }
4777 }
4778
4779 return $rep;
4780}
4781
4790function dol_print_ip($ip, $mode = 0, $showname = 0)
4791{
4792 global $conf;
4793
4794 $ret = '';
4795 if (!isset($conf->cache['resolveips'])) {
4796 $conf->cache['resolveips'] = array();
4797 }
4798
4799 if ($mode != 2) {
4800 $countrycode = dolGetCountryCodeFromIp($ip);
4801 if ($countrycode) { // If success, countrycode is us, fr, ...
4802 if (file_exists(DOL_DOCUMENT_ROOT.'/theme/common/flags/'.$countrycode.'.png')) {
4803 $ret .= picto_from_langcode($countrycode);
4804 // $ret .= img_picto($countrycode.' '.$langs->trans("AccordingToGeoIPDatabase"), DOL_URL_ROOT.'/theme/common/flags/'.$countrycode.'.png', '', 1);
4805 } else {
4806 $ret .= '('.$countrycode.')';
4807 }
4808 $ret .= '&nbsp;';
4809 } else {
4810 // Nothing
4811 }
4812 }
4813
4814 if (in_array($mode, [0, 2])) {
4815 $domain = '';
4816 if ($showname) {
4817 if (!array_key_exists($ip, $conf->cache['resolveips'])) {
4818 $domain = gethostbyaddr($ip);
4819 $conf->cache['resolveips'][$ip] = $domain; // false or domain
4820 } else {
4821 $domain = $conf->cache['resolveips'][$ip];
4822 }
4823 }
4824 if ($domain) {
4825 $ret .= $domain;
4826 } else {
4827 $ret .= $ip;
4828 }
4829 }
4830
4831 return $ret;
4832}
4833
4846function getUserRemoteIP($trusted = 0)
4847{
4848 if ($trusted) { // Return only IP we can rely on (not spoofable by the client)
4849 $ip = (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']); // value may be the IP of a proxy
4850 // Note that if apache module remoteip has been enabled, REMOTE_ADDR can contain the real client (the value from cloudFlare HTTP_CF_CONNECTING_IP for example)
4851 // This can happen if the proxy were added in the list of trusted proxy.
4852 return $ip;
4853 }
4854
4855 // Try to guess the real IP of client (but this may not be reliable)
4856 if (empty($_SERVER['HTTP_X_FORWARDED_FOR']) || preg_match('/[^0-9\.\:,\[\]\s]/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {
4857 if (empty($_SERVER['HTTP_CLIENT_IP']) || preg_match('/[^0-9\.\:,\[\]\s]/', $_SERVER['HTTP_CLIENT_IP'])) {
4858 if (empty($_SERVER["HTTP_CF_CONNECTING_IP"])) {
4859 $ip = (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']); // value may be the IP of the proxy and not the client
4860 } else {
4861 $ip = $_SERVER["HTTP_CF_CONNECTING_IP"]; // value here may have been forged by client
4862 }
4863 } else {
4864 $ip = preg_replace('/,.*$/', '', $_SERVER['HTTP_CLIENT_IP']); // value is clean here but may have been forged by proxy
4865 }
4866 } else {
4867 $ip = preg_replace('/,.*$/', '', $_SERVER['HTTP_X_FORWARDED_FOR']); // value is clean here but may have been forged by proxy
4868 }
4869 return $ip;
4870}
4871
4880function isHTTPS()
4881{
4882 $isSecure = false;
4883 if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
4884 $isSecure = true;
4885 } 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') {
4886 $isSecure = true;
4887 }
4888 return $isSecure;
4889}
4890
4897function dolGetCountryCodeFromIp($ip)
4898{
4899 $countrycode = '';
4900
4901 if (isModEnabled('geoipmaxmind')) {
4902 $datafile = getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE');
4903 //$ip='24.24.24.24';
4904 //$datafile='/usr/share/GeoIP/GeoIP.dat'; Note that this must be downloaded datafile (not same than datafile provided with ubuntu packages)
4905 if ($datafile) {
4906 try {
4907 include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
4908 $geoip = new DolGeoIP('country', $datafile);
4909 //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
4910 $countrycode = $geoip->getCountryCodeFromIP($ip);
4911 } catch (Exception $e) {
4912 //print 'Error with GeoIP database: '.$e->getMessage();
4913 }
4914 }
4915 }
4916
4917 return $countrycode;
4918}
4919
4920
4927function dol_user_country()
4928{
4929 global $conf, $langs, $user;
4930
4931 //$ret=$user->xxx;
4932 $ret = '';
4933 if (isModEnabled('geoipmaxmind')) {
4934 $ip = getUserRemoteIP();
4935 $datafile = getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE');
4936 //$ip='24.24.24.24';
4937 //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';
4938 include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
4939 $geoip = new DolGeoIP('country', $datafile);
4940 $countrycode = $geoip->getCountryCodeFromIP($ip);
4941 $ret = $countrycode;
4942 }
4943 return $ret;
4944}
4945
4958function dol_print_address($address, $htmlid, $element, $id, $noprint = 0, $charfornl = '')
4959{
4960 global $hookmanager;
4961
4962 $out = '';
4963
4964 if ($address) {
4965 if ($hookmanager) {
4966 $parameters = array('element' => $element, 'id' => $id);
4967 $reshook = $hookmanager->executeHooks('printAddress', $parameters, $address);
4968 $out .= $hookmanager->resPrint;
4969 }
4970 if (empty($reshook)) {
4971 if (empty($charfornl)) {
4972 $out .= nl2br((string) $address);
4973 } else {
4974 $out .= preg_replace('/[\r\n]+/', $charfornl, (string) $address);
4975 }
4976
4977 // TODO Remove this block, we can add this using the hook now
4978 $showgmap = $showomap = 0;
4979 if (($element == 'thirdparty' || $element == 'societe') && isModEnabled('google') && getDolGlobalString('GOOGLE_ENABLE_GMAPS')) {
4980 $showgmap = 1;
4981 }
4982 if ($element == 'contact' && isModEnabled('google') && getDolGlobalString('GOOGLE_ENABLE_GMAPS_CONTACTS')) {
4983 $showgmap = 1;
4984 }
4985 if ($element == 'member' && isModEnabled('google') && getDolGlobalString('GOOGLE_ENABLE_GMAPS_MEMBERS')) {
4986 $showgmap = 1;
4987 }
4988 if ($element == 'user' && isModEnabled('google') && getDolGlobalString('GOOGLE_ENABLE_GMAPS_USERS')) {
4989 $showgmap = 1;
4990 }
4991 if (($element == 'thirdparty' || $element == 'societe') && isModEnabled('openstreetmap') && getDolGlobalString('OPENSTREETMAP_ENABLE_MAPS')) {
4992 $showomap = 1;
4993 }
4994 if ($element == 'contact' && isModEnabled('openstreetmap') && getDolGlobalString('OPENSTREETMAP_ENABLE_MAPS_CONTACTS')) {
4995 $showomap = 1;
4996 }
4997 if ($element == 'member' && isModEnabled('openstreetmap') && getDolGlobalString('OPENSTREETMAP_ENABLE_MAPS_MEMBERS')) {
4998 $showomap = 1;
4999 }
5000 if ($element == 'user' && isModEnabled('openstreetmap') && getDolGlobalString('OPENSTREETMAP_ENABLE_MAPS_USERS')) {
5001 $showomap = 1;
5002 }
5003 if ($showgmap) {
5004 $url = dol_buildpath('/google/gmaps.php?mode='.$element.'&id='.$id, 1);
5005 $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
5006 }
5007 if ($showomap) {
5008 $url = dol_buildpath('/openstreetmap/maps.php?mode='.$element.'&id='.$id, 1);
5009 $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'_openstreetmap" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
5010 }
5011 }
5012 }
5013 if ($noprint) {
5014 return $out;
5015 } else {
5016 print $out;
5017 return null;
5018 }
5019}
5020
5021
5031function isValidEmail($address, $acceptsupervisorkey = 0, $acceptuserkey = 0)
5032{
5033 if ($acceptsupervisorkey && $address == '__SUPERVISOREMAIL__') {
5034 return true;
5035 }
5036 if ($acceptuserkey && $address == '__USER_EMAIL__') {
5037 return true;
5038 }
5039 if (filter_var($address, FILTER_VALIDATE_EMAIL)) {
5040 return true;
5041 }
5042
5043 return false;
5044}
5045
5055function isValidMXRecord($domain)
5056{
5057 if (function_exists('idn_to_ascii') && function_exists('checkdnsrr')) {
5058 if (!checkdnsrr(idn_to_ascii($domain), 'MX')) {
5059 return 0;
5060 }
5061 if (function_exists('getmxrr')) {
5062 $mxhosts = array();
5063 $weight = array();
5064 getmxrr(idn_to_ascii($domain), $mxhosts, $weight);
5065 if (count($mxhosts) > 1) {
5066 return 1;
5067 }
5068 if (count($mxhosts) == 1 && !in_array((string) $mxhosts[0], array('', '.'))) {
5069 return 1;
5070 }
5071
5072 return 0;
5073 }
5074 }
5075
5076 // function idn_to_ascii or checkdnsrr or getmxrr does not exists
5077 return -1;
5078}
5079
5087function isValidPhone($phone)
5088{
5089 return true;
5090}
5091
5092
5102function dolGetFirstLetters($s, $nbofchar = 1)
5103{
5104 $ret = '';
5105 $tmparray = explode(' ', $s);
5106 foreach ($tmparray as $tmps) {
5107 $ret .= dol_substr($tmps, 0, $nbofchar);
5108 }
5109
5110 return $ret;
5111}
5112
5113
5121function dol_strlen($string, $stringencoding = 'UTF-8')
5122{
5123 if (is_null($string)) {
5124 return 0;
5125 }
5126
5127 if (function_exists('mb_strlen')) {
5128 return mb_strlen($string, $stringencoding);
5129 } else {
5130 return strlen($string);
5131 }
5132}
5133
5144function dol_substr($string, $start, $length = null, $stringencoding = '', $trunconbytes = 0)
5145{
5146 global $langs;
5147
5148 if (empty($stringencoding)) {
5149 $stringencoding = (empty($langs) ? 'UTF-8' : $langs->charset_output);
5150 }
5151
5152 $ret = '';
5153 if (empty($trunconbytes)) {
5154 if (function_exists('mb_substr')) {
5155 $ret = mb_substr($string, $start, $length, $stringencoding);
5156 } else {
5157 $ret = substr($string, $start, $length);
5158 }
5159 } else {
5160 if (function_exists('mb_strcut')) {
5161 $ret = mb_strcut($string, $start, $length, $stringencoding);
5162 } else {
5163 $ret = substr($string, $start, $length);
5164 }
5165 }
5166 return $ret;
5167}
5168
5169
5183function dol_trunc($string, $size = 40, $trunc = 'right', $stringencoding = 'UTF-8', $nodot = 0, $display = 0)
5184{
5185 global $conf;
5186
5187 if (empty($size) || getDolGlobalString('MAIN_DISABLE_TRUNC')) {
5188 return $string;
5189 }
5190
5191 if (empty($stringencoding)) {
5192 $stringencoding = 'UTF-8';
5193 }
5194 // reduce for small screen
5195 if (!empty($conf->dol_optimize_smallscreen) && $conf->dol_optimize_smallscreen == 1 && $display == 1) {
5196 $size = round($size / 3);
5197 }
5198
5199 // We go always here
5200 if ($trunc == 'right') {
5201 $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
5202 if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
5203 // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
5204 return dol_substr($newstring, 0, $size, $stringencoding).($nodot ? '' : '…');
5205 } else {
5206 //return 'u'.$size.'-'.$newstring.'-'.dol_strlen($newstring,$stringencoding).'-'.$string;
5207 return $string;
5208 }
5209 } elseif ($trunc == 'middle') {
5210 $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
5211 if (dol_strlen($newstring, $stringencoding) > 2 && dol_strlen($newstring, $stringencoding) > ($size + 1)) {
5212 $size1 = (int) round($size / 2);
5213 $size2 = (int) round($size / 2);
5214 return dol_substr($newstring, 0, $size1, $stringencoding).'…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size2, $size2, $stringencoding);
5215 } else {
5216 return $string;
5217 }
5218 } elseif ($trunc == 'left') {
5219 $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
5220 if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
5221 // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
5222 return '…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size, $size, $stringencoding);
5223 } else {
5224 return $string;
5225 }
5226 } elseif ($trunc == 'wrap') {
5227 $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
5228 if (dol_strlen($newstring, $stringencoding) > ($size + 1)) {
5229 return dol_substr($newstring, 0, $size, $stringencoding)."\n".dol_trunc(dol_substr($newstring, $size, dol_strlen($newstring, $stringencoding) - $size, $stringencoding), $size, $trunc);
5230 } else {
5231 return $string;
5232 }
5233 } else {
5234 return 'BadParam3CallingDolTrunc';
5235 }
5236}
5237
5245function getPictoForType($key, $morecss = '')
5246{
5247 // Set array with type -> picto
5248 $type2picto = array(
5249 'varchar' => 'font',
5250 'text' => 'font',
5251 'html' => 'code',
5252 'int' => 'sort-numeric-down',
5253 'double' => 'sort-numeric-down',
5254 'price' => 'currency',
5255 'pricecy' => 'multicurrency',
5256 'password' => 'key',
5257 'boolean' => 'check-square',
5258 'date' => 'calendar',
5259 'datetime' => 'calendar',
5260 'duration' => 'hourglass',
5261 'phone' => 'phone',
5262 'mail' => 'email',
5263 'url' => 'url',
5264 'ip' => 'country',
5265 'select' => 'list',
5266 'sellist' => 'list',
5267 'stars' => 'fontawesome_star_fas',
5268 'radio' => 'check-circle',
5269 'checkbox' => 'list',
5270 'chkbxlst' => 'list',
5271 'link' => 'link',
5272 'icon' => "question",
5273 'point' => "country",
5274 'multipts' => 'country',
5275 'linestrg' => "country",
5276 'polygon' => "country",
5277 'separate' => 'minus'
5278 );
5279
5280 if (!empty($type2picto[$key])) {
5281 return img_picto('', $type2picto[$key], 'class="pictofixedwidth'.($morecss ? ' '.$morecss : '').'"');
5282 }
5283
5284 return img_picto('', 'generic', 'class="pictofixedwidth'.($morecss ? ' '.$morecss : '').'"');
5285}
5286
5287
5310function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $srconly = 0, $notitle = 0, $alt = '', $morecss = '', $marginleftonlyshort = 2, $allowothertags = array())
5311{
5312 global $conf;
5313
5314 // We forge fullpathpicto for image to $path/img/$picto. By default, we take DOL_URL_ROOT/theme/$conf->theme/img/$picto
5315 $url = DOL_URL_ROOT;
5316 $theme = isset($conf->theme) ? $conf->theme : null;
5317 $path = 'theme/'.$theme;
5318 if (empty($picto)) {
5319 $picto = 'generic';
5320 }
5321
5322 // Define fullpathpicto to use into src
5323 if ($pictoisfullpath) {
5324 // Clean parameters
5325 if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
5326 $picto .= '.png';
5327 }
5328 $fullpathpicto = $picto;
5329 $reg = array();
5330 if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
5331 $morecss .= ($morecss ? ' ' : '').$reg[1];
5332 $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
5333 }
5334 } else {
5335 // $picto can not be null since replaced with 'generic' in that case
5336 //$pictowithouttext = preg_replace('/(\.png|\.gif|\.svg)$/', '', (is_null($picto) ? '' : $picto));
5337 $pictowithouttext = preg_replace('/(\.png|\.gif|\.svg)$/', '', $picto);
5338 $pictowithouttext = str_replace('object_', '', $pictowithouttext);
5339 $pictowithouttext = str_replace('_nocolor', '', $pictowithouttext);
5340
5341 // Fix some values of $pictowithouttext
5342 $pictoconvertkey = array('facture' => 'bill', 'shipping' => 'shipment', 'fichinter' => 'intervention', 'agenda' => 'calendar', 'invoice_supplier' => 'supplier_invoice', 'order_supplier' => 'supplier_order');
5343 if (in_array($pictowithouttext, array_keys($pictoconvertkey))) {
5344 $pictowithouttext = $pictoconvertkey[$pictowithouttext];
5345 }
5346
5347 if (strpos($pictowithouttext, 'fontawesome_') === 0 || strpos($pictowithouttext, 'fa-') === 0) {
5348 // This is a font awesome image 'fontawesome_xxx' or 'fa-xxx'
5349 $pictowithouttext = str_replace('fontawesome_', '', $pictowithouttext);
5350 $pictowithouttext = str_replace('fa-', '', $pictowithouttext);
5351
5352 // Compatibility with old fontawesome versions
5353 if ($pictowithouttext == 'file-o') {
5354 $pictowithouttext = 'file';
5355 }
5356
5357 $pictowithouttextarray = explode('_', $pictowithouttext);
5358 $marginleftonlyshort = 0;
5359
5360 if (!empty($pictowithouttextarray[1])) {
5361 // Syntax is 'fontawesome_fakey_faprefix_facolor_fasize' or 'fa-fakey_faprefix_facolor_fasize'
5362 $fakey = 'fa-'.$pictowithouttextarray[0];
5363 $faprefix = empty($pictowithouttextarray[1]) ? 'fas' : $pictowithouttextarray[1];
5364 $facolor = empty($pictowithouttextarray[2]) ? '' : $pictowithouttextarray[2];
5365 $fasize = empty($pictowithouttextarray[3]) ? '' : $pictowithouttextarray[3];
5366 } else {
5367 $fakey = 'fa-'.$pictowithouttext;
5368 $faprefix = 'fas';
5369 $facolor = '';
5370 $fasize = '';
5371 }
5372
5373 // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
5374 // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
5375 $morestyle = '';
5376 $reg = array();
5377 if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
5378 $morecss .= ($morecss ? ' ' : '').$reg[1];
5379 $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
5380 }
5381 if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
5382 $morestyle = $reg[1];
5383 $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt);
5384 }
5385 $moreatt = trim($moreatt);
5386
5387 $enabledisablehtml = '<span class="'.$faprefix.' '.$fakey.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
5388 $enabledisablehtml .= ($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').($morestyle ? ' '.$morestyle : '').'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : '').'>';
5389 $enabledisablehtml .= '</span>';
5390
5391 return $enabledisablehtml;
5392 }
5393
5394 if (empty($srconly) && in_array($pictowithouttext, getImgPictoNameList())) {
5395 $fakey = $pictowithouttext;
5396 $facolor = '';
5397 $fasize = '';
5398 $fa = getDolGlobalString('MAIN_FONTAWESOME_ICON_STYLE', 'fas');
5399 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'))) {
5400 $fa = 'far';
5401 }
5402 if (in_array($pictowithouttext, array('black-tie', 'discord', 'facebook', 'flickr', 'github', 'google', 'google-plus-g', 'instagram', 'linkedin', 'meetup', 'microsoft', 'pinterest', 'skype', 'slack', 'twitter', 'reddit', 'snapchat', 'stripe', 'stripe-s', 'tumblr', 'viadeo', 'whatsapp', 'youtube'))) {
5403 $fa = 'fab';
5404 }
5405
5406 $arrayconvpictotofa = getImgPictoConv('fa');
5407
5408 if ($pictowithouttext == 'off') {
5409 $fakey = 'fa-square';
5410 $fasize = '1.3em';
5411 } elseif ($pictowithouttext == 'on') {
5412 $fakey = 'fa-check-square';
5413 $fasize = '1.3em';
5414 } elseif ($pictowithouttext == 'listlight') {
5415 $fakey = 'fa-download';
5416 $marginleftonlyshort = 1;
5417 } elseif ($pictowithouttext == 'printer') {
5418 $fakey = 'fa-print';
5419 $fasize = '1.2em';
5420 } elseif ($pictowithouttext == 'note') {
5421 $fakey = 'fa-sticky-note';
5422 $marginleftonlyshort = 1;
5423 } elseif (in_array($pictowithouttext, array('1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'))) {
5424 $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');
5425 $fakey = 'fa-'.$convertarray[$pictowithouttext];
5426 if (preg_match('/selected/', $pictowithouttext)) {
5427 $facolor = '#888';
5428 }
5429 $marginleftonlyshort = 1;
5430 } elseif (!empty($arrayconvpictotofa[$pictowithouttext])) {
5431 $fakey = 'fa-'.$arrayconvpictotofa[$pictowithouttext];
5432 } else {
5433 $fakey = 'fa-'.$pictowithouttext;
5434 }
5435
5436 if (in_array($pictowithouttext, array('dollyrevert', 'member', 'members', 'contract', 'group', 'resource', 'shipment', 'reception'))) {
5437 $morecss .= ' em092';
5438 }
5439 if (in_array($pictowithouttext, array('conferenceorbooth', 'collab', 'eventorganization', 'holiday', 'info', 'info_black', 'project', 'workstation'))) {
5440 $morecss .= ' em088';
5441 }
5442 if (in_array($pictowithouttext, array('asset', 'intervention', 'payment', 'loan', 'partnership', 'stock', 'technic'))) {
5443 $morecss .= ' em080';
5444 }
5445
5446 // Define $marginleftonlyshort
5447 $arrayconvpictotomarginleftonly = array(
5448 'bank', 'check', 'delete', 'generic', 'grip', 'grip_title', 'jabber',
5449 'grip_title', 'grip', 'listlight', 'note', 'on', 'off', 'playdisabled', 'printer', 'resize', 'sign-out', 'stats', 'switch_on', 'switch_on_grey', 'switch_on_red', 'switch_off',
5450 'uparrow', '1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'
5451 );
5452 if (!array_key_exists($pictowithouttext, $arrayconvpictotomarginleftonly)) {
5453 $marginleftonlyshort = 0;
5454 }
5455
5456 // Add CSS
5457 $arrayconvpictotomorcess = array(
5458 'action' => 'infobox-action', 'account' => 'infobox-bank_account', 'accounting_account' => 'infobox-bank_account', 'accountline' => 'infobox-bank_account', 'accountancy' => 'infobox-bank_account', 'asset' => 'infobox-bank_account',
5459 'bank_account' => 'infobox-bank_account',
5460 'bill' => 'infobox-commande', 'billa' => 'infobox-commande', 'billr' => 'infobox-commande', 'billd' => 'infobox-commande',
5461 'bookcal' => 'infobox-action',
5462 'margin' => 'infobox-bank_account', 'conferenceorbooth' => 'infobox-project',
5463 'cash-register' => 'infobox-bank_account', 'contract' => 'infobox-contrat', 'check' => 'font-status4', 'collab' => 'infobox-action', 'conversation' => 'infobox-contrat',
5464 'donation' => 'infobox-commande', 'dolly' => 'infobox-commande', 'dollyrevert' => 'flip infobox-order_supplier',
5465 'ecm' => 'infobox-action', 'eventorganization' => 'infobox-project',
5466 'hrm' => 'infobox-adherent', 'group' => 'infobox-adherent', 'intervention' => 'infobox-contrat',
5467 'incoterm' => 'infobox-supplier_proposal',
5468 'currency' => 'infobox-bank_account', 'multicurrency' => 'infobox-bank_account',
5469 'members' => 'infobox-adherent', 'member' => 'infobox-adherent', 'money-bill-alt' => 'infobox-bank_account',
5470 'order' => 'infobox-commande',
5471 'user' => 'infobox-adherent', 'users' => 'infobox-adherent',
5472 'error' => 'pictoerror', 'warning' => 'pictowarning', 'switch_on' => 'font-status4', 'switch_on_warning' => 'font-status4 warning', 'switch_on_red' => 'font-status8',
5473 'holiday' => 'infobox-holiday', 'info' => 'opacityhigh', 'info_black' => 'font-status1', 'invoice' => 'infobox-commande',
5474 'knowledgemanagement' => 'infobox-contrat rotate90', 'loan' => 'infobox-bank_account',
5475 'payment' => 'infobox-bank_account', 'payment_vat' => 'infobox-bank_account', 'poll' => 'infobox-adherent', 'pos' => 'infobox-bank_account', 'project' => 'infobox-project', 'projecttask' => 'infobox-project',
5476 'propal' => 'infobox-propal', 'proposal' => 'infobox-propal','private' => 'infobox-project',
5477 'reception' => 'flip infobox-order_supplier', 'recruitmentjobposition' => 'infobox-adherent', 'recruitmentcandidature' => 'infobox-adherent',
5478 'resource' => 'infobox-action',
5479 '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',
5480 'supplier' => 'infobox-order_supplier', 'supplier_order' => 'infobox-order_supplier', 'supplier_proposal' => 'infobox-supplier_proposal',
5481 'ticket' => 'infobox-contrat', 'title_accountancy' => 'infobox-bank_account', 'title_hrm' => 'infobox-holiday', 'expensereport' => 'infobox-expensereport', 'trip' => 'infobox-expensereport', 'title_agenda' => 'infobox-action',
5482 'vat' => 'infobox-bank_account',
5483 //'title_setup'=>'infobox-action', 'tools'=>'infobox-action',
5484 'list-alt' => 'imgforviewmode', 'calendar' => 'imgforviewmode', 'calendarweek' => 'imgforviewmode', 'calendarmonth' => 'imgforviewmode', 'calendarday' => 'imgforviewmode', 'calendarperuser' => 'imgforviewmode', 'calendarpertype' => 'imgforviewmode'
5485 );
5486 if (!empty($arrayconvpictotomorcess[$pictowithouttext]) && strpos($picto, '_nocolor') === false) {
5487 $morecss .= ($morecss ? ' ' : '').$arrayconvpictotomorcess[$pictowithouttext];
5488 }
5489
5490 // Define $color
5491 $arrayconvpictotocolor = array(
5492 'address' => '#6c6aa8', 'building' => '#6c6aa8', 'bom' => '#a69944',
5493 'clone' => '#999', 'cog' => '#999', 'companies' => '#6c6aa8', 'company' => '#6c6aa8', 'contact' => '#6c6aa8', 'cron' => '#555',
5494 'dynamicprice' => '#a69944',
5495 'edit' => '#444', 'note' => '#999', 'error' => '', 'help' => '#bbb', 'listlight' => '#999', 'language' => '#555',
5496 //'dolly'=>'#a69944', 'dollyrevert'=>'#a69944',
5497 'lock' => '#ddd', 'lot' => '#a69944',
5498 'map-marker-alt' => '#aaa', 'mrp' => '#a69944', 'product' => '#a69944', 'service' => '#a69944', 'inventory' => '#a69944', 'stock' => '#a69944', 'movement' => '#a69944',
5499 'other' => '#ddd', 'world' => '#986c6a',
5500 'partnership' => '#6c6aa8', 'playdisabled' => '#ccc', 'printer' => '#444', 'projectpub' => '#986c6a', 'resize' => '#444', 'rss' => '#cba',
5501 //'shipment'=>'#a69944',
5502 'search-plus' => '#808080', 'security' => '#999', 'square' => '#888', 'stop-circle' => '#888', 'stats' => '#444', 'switch_off' => '#999',
5503 'technic' => '#999', 'tick' => '#282', 'timespent' => '#555',
5504 'uncheck' => '#800', 'uparrow' => '#555', 'user-cog' => '#999', 'country' => '#aaa', 'globe-americas' => '#aaa', 'region' => '#aaa', 'state' => '#aaa',
5505 'website' => '#304', 'workstation' => '#a69944'
5506 );
5507 if (isset($arrayconvpictotocolor[$pictowithouttext]) && strpos($picto, '_nocolor') === false) {
5508 $facolor = $arrayconvpictotocolor[$pictowithouttext];
5509 }
5510
5511 // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
5512 // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
5513 $morestyle = '';
5514 $reg = array();
5515 if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
5516 $morecss .= ($morecss ? ' ' : '').$reg[1];
5517 $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
5518 }
5519 if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
5520 $morestyle = $reg[1];
5521 $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt);
5522 }
5523 $moreatt = trim($moreatt);
5524
5525 $enabledisablehtml = '<span class="'.$fa.' '.$fakey.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
5526 $enabledisablehtml .= ($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').($morestyle ? ' '.$morestyle : '').'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : '').'>';
5527 $enabledisablehtml .= '</span>';
5528
5529 return $enabledisablehtml;
5530 }
5531
5532 if (getDolGlobalString('MAIN_OVERWRITE_THEME_PATH')) {
5533 $path = getDolGlobalString('MAIN_OVERWRITE_THEME_PATH') . '/theme/'.$theme; // If the theme does not have the same name as the module
5534 } elseif (getDolGlobalString('MAIN_OVERWRITE_THEME_RES')) {
5535 $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
5536 } elseif (!empty($conf->modules_parts['theme']) && array_key_exists($theme, $conf->modules_parts['theme'])) {
5537 $path = $theme.'/theme/'.$theme; // If the theme have the same name as the module
5538 }
5539
5540 // If we ask an image into $url/$mymodule/img (instead of default path)
5541 $regs = array();
5542 if (preg_match('/^([^@]+)@([^@]+)$/i', $picto, $regs)) {
5543 $picto = $regs[1];
5544 $path = $regs[2]; // $path is $mymodule
5545 }
5546
5547 // Clean parameters
5548 if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
5549 $picto .= '.png';
5550 }
5551 // If alt path are defined, define url where img file is, according to physical path
5552 // ex: array(["main"]=>"/home/maindir/htdocs", ["alt0"]=>"/home/moddir0/htdocs", ...)
5553 foreach ($conf->file->dol_document_root as $type => $dirroot) {
5554 if ($type == 'main') {
5555 continue;
5556 }
5557 // This need a lot of time, that's why enabling alternative dir like "custom" dir is not recommended
5558 if (file_exists($dirroot.'/'.$path.'/img/'.$picto)) {
5559 $url = DOL_URL_ROOT.$conf->file->dol_url_root[$type];
5560 break;
5561 }
5562 }
5563
5564 // $url is '' or '/custom', $path is current theme or
5565 $fullpathpicto = $url.'/'.$path.'/img/'.$picto;
5566 }
5567
5568 if ($srconly) {
5569 return $fullpathpicto;
5570 }
5571
5572 // tag title is used for tooltip on <a>, tag alt can be used with very simple text on image for blind people
5573 return '<img src="'.$fullpathpicto.'"'.($notitle ? '' : ' alt="'.dolPrintHTMLForAttribute($alt, 0, $allowothertags).'"').(($notitle || empty($titlealt)) ? '' : ' title="'.dolPrintHTMLForAttribute($titlealt, 0, $allowothertags).'"').($moreatt ? ' '.$moreatt.($morecss ? ' class="'.$morecss.'"' : '') : ' class="inline-block'.($morecss ? ' '.$morecss : '').'"').'>'; // Alt is used for accessibility, title for popup
5574}
5575
5581function getImgPictoNameList()
5582{
5583 return array(
5584 '1downarrow', '1uparrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected',
5585 'accountancy', 'accounting_account', 'account', 'accountline', 'action', 'add', 'address', 'ai', 'angle-double-down', 'angle-double-up', 'asset',
5586 'back', 'bank_account', 'barcode', 'bank', 'bell', 'bill', 'billa', 'billr', 'billd', 'birthday-cake', 'bom', 'bookcal', 'bookmark', 'briefcase-medical', 'bug', 'building',
5587 'card', 'calendarlist', 'calendar', 'calendarmonth', 'calendarweek', 'calendarday', 'calendarperuser', 'calendarpertype', 'hourglass',
5588 'cash-register', 'category', 'chart', 'check', 'clock', 'clone', 'close_title', 'code', 'cog', 'collab', 'company', 'contact', 'country', 'contract', 'conversation', 'cron', 'cross', 'cubes',
5589 'check-circle', 'check-square', 'circle', 'stop-circle', 'currency', 'multicurrency',
5590 'chevron-left', 'chevron-right', 'chevron-down', 'chevron-up',
5591 'chevron-double-left', 'chevron-double-right', 'chevron-double-down', 'chevron-double-top',
5592 'commercial', 'companies',
5593 'delete', 'dolly', 'dollyrevert', 'donation', 'download', 'dynamicprice',
5594 'edit', 'ellipsis-h', 'email', 'entity', 'envelope', 'eraser', 'establishment', 'expensereport', 'external-link-alt', 'external-link-square-alt', 'eye',
5595 'filter', 'file', 'file-o', 'file-code', 'file-export', 'file-import', 'file-upload', 'autofill', 'folder', 'folder-open', 'folder-plus', 'font',
5596 'generate', 'generic', 'globe', 'globe-americas', 'graph', 'grip', 'grip_title', 'group',
5597 'hands-helping', 'help', 'holiday',
5598 'id-card', 'images', 'incoterm', 'info', 'info_black', 'intervention', 'inventory', 'intracommreport', 'jobprofile',
5599 'key', 'knowledgemanagement',
5600 'label', 'language', 'layout', 'line', 'link', 'list', 'list-alt', 'listlight', 'loan', 'lock', 'lot', 'long-arrow-alt-right',
5601 'margin', 'map-marker-alt', 'member', 'meeting', 'minus', 'money-bill-alt', 'movement', 'mrp', 'note', 'next',
5602 'off', 'on', 'order',
5603 'paragraph', 'play', 'pdf', 'phone', 'phoning', 'phoning_mobile', 'phoning_fax', 'playdisabled', 'previous', 'poll', 'pos', 'printer', 'product', 'propal', 'proposal', 'puce',
5604 'resize', 'search', 'service', 'stats', 'stock',
5605 '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',
5606 'discord', 'facebook', 'flickr', 'instagram','linkedin', 'github', 'google', 'jabber', 'meetup', 'microsoft', 'skype', 'slack', 'twitter', 'pinterest', 'reddit', 'snapchat', 'tumblr', 'youtube', 'viadeo', 'google-plus-g', 'whatsapp',
5607 'generic', 'home', 'hrm', 'members', 'products', 'invoicing',
5608 'partnership', 'payment', 'payment_vat', 'pencil-ruler', 'pictoconfirm', 'preview', 'project', 'projectpub', 'projecttask', 'question', 'refresh', 'region',
5609 'salary', 'shipment', 'state', 'supplier_invoice', 'supplier_invoicea', 'supplier_invoicer', 'supplier_invoiced',
5610 'technic', 'ticket',
5611 'error', 'warning',
5612 'recent', 'reception', 'recruitmentcandidature', 'recruitmentjobposition', 'replacement', 'resource', 'recurring', 'rss',
5613 'search-plus', 'shapes', 'skill', 'square', 'sort-numeric-down', 'status', 'stop-circle', 'store', 'supplier', 'supplier_proposal', 'supplier_order', 'supplier_invoice',
5614 'terminal', 'tick', 'timespent', 'title_setup', 'title_accountancy', 'title_bank', 'title_hrm', 'title_agenda', 'trip',
5615 'uncheck', 'undo', 'url', 'user-cog', 'user-injured', 'user-md', 'upload', 'vat', 'website', 'workstation', 'webhook', 'world', 'private',
5616 'conferenceorbooth', 'eventorganization',
5617 'stamp', 'signature',
5618 'webportal'
5619 );
5620}
5621
5629function getImgPictoConv($mode = 'fa')
5630{
5631 global $conf;
5632
5633 // Array when the fa picto key is different than the Dolibarr picto key.
5634 $arrayconvpictotofa = array(
5635 'account' => 'university', 'accounting_account' => 'clipboard-list', 'accountline' => 'receipt', 'accountancy' => 'search-dollar', 'action' => 'calendar-alt', 'add' => 'plus-circle', 'address' => 'address-book', 'ai' => 'magic',
5636 'asset' => 'money-check-alt', 'autofill' => 'fill',
5637 'back' => 'arrow-left', 'bank_account' => 'university',
5638 'bill' => 'file-invoice-dollar', 'billa' => 'file-excel', 'billr' => 'file-invoice-dollar', 'billd' => 'file-medical',
5639 'bookcal' => 'calendar-check',
5640 'supplier_invoice' => 'file-invoice-dollar', 'supplier_invoicea' => 'file-excel', 'supplier_invoicer' => 'file-invoice-dollar', 'supplier_invoiced' => 'file-medical',
5641 'bom' => 'shapes',
5642 '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',
5643 'chevron-double-left' => 'angle-double-left', 'chevron-double-right' => 'angle-double-right', 'chevron-double-down' => 'angle-double-down', 'chevron-double-top' => 'angle-double-up',
5644 'donation' => 'file-alt', 'dynamicprice' => 'hand-holding-usd',
5645 'setup' => 'cog', 'companies' => 'building', 'products' => 'cube', 'commercial' => 'suitcase', 'invoicing' => 'coins',
5646 'accounting' => 'search-dollar', 'category' => 'tag', 'dollyrevert' => 'dolly',
5647 'file-o' => 'file', 'generate' => 'plus-square', 'hrm' => 'user-tie', 'incoterm' => 'truck-loading',
5648 'margin' => 'calculator', 'members' => 'user-friends', 'ticket' => 'ticket-alt', 'globe' => 'external-link-alt', 'lot' => 'barcode',
5649 'email' => 'at', 'establishment' => 'building', 'edit' => 'pencil-alt', 'entity' => 'globe',
5650 'graph' => 'chart-line', 'grip_title' => 'arrows-alt', 'grip' => 'arrows-alt', 'help' => 'question-circle',
5651 'generic' => 'file', 'holiday' => 'umbrella-beach',
5652 'info' => 'info-circle', 'info_black' => 'info-circle', 'inventory' => 'boxes', 'intracommreport' => 'globe-europe', 'jobprofile' => 'cogs',
5653 'knowledgemanagement' => 'ticket-alt', 'label' => 'layer-group', 'layout' => 'columns', 'line' => 'bars', 'loan' => 'money-bill-alt',
5654 'member' => 'user-alt', 'meeting' => 'chalkboard-teacher', 'mrp' => 'cubes', 'next' => 'arrow-alt-circle-right',
5655 'trip' => 'wallet', 'expensereport' => 'wallet', 'group' => 'users', 'movement' => 'people-carry',
5656 'sign-out' => 'sign-out-alt',
5657 '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',
5658 'bank' => 'university', 'close_title' => 'times', 'delete' => 'trash', 'filter' => 'filter',
5659 'list-alt' => 'list-alt', 'calendarlist' => 'bars', 'calendar' => 'calendar-alt', 'calendarmonth' => 'calendar-alt', 'calendarweek' => 'calendar-week', 'calendarday' => 'calendar-day', 'calendarperuser' => 'table', 'calendarpertype' => 'table',
5660 'intervention' => 'ambulance', 'invoice' => 'file-invoice-dollar', 'order' => 'file-invoice',
5661 'error' => 'exclamation-triangle', 'warning' => 'exclamation-triangle',
5662 'other' => 'square',
5663 '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',
5664 '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',
5665 'recent' => 'check-square', 'reception' => 'dolly', 'recruitmentjobposition' => 'id-card-alt', 'recruitmentcandidature' => 'id-badge',
5666 'resize' => 'crop', 'supplier_order' => 'dol-order_supplier', 'supplier_proposal' => 'file-signature',
5667 'refresh' => 'redo', 'region' => 'map-marked', 'replacement' => 'exchange-alt', 'resource' => 'laptop-house', 'recurring' => 'history',
5668 'service' => 'concierge-bell',
5669 'skill' => 'shapes', 'state' => 'map-marked-alt', 'security' => 'key', 'salary' => 'wallet', 'shipment' => 'dolly', 'stock' => 'box-open', 'stats' => 'chart-bar', 'split' => 'code-branch',
5670 'status' => 'stop-circle',
5671 'stripe' => 'stripe-s', 'supplier' => 'building',
5672 'technic' => 'cogs', 'tick' => 'check', 'timespent' => 'clock', 'title_setup' => 'tools', 'title_accountancy' => 'money-check-alt', 'title_bank' => 'university', 'title_hrm' => 'umbrella-beach',
5673 'title_agenda' => 'calendar-alt',
5674 'uncheck' => 'times', 'uparrow' => 'share', 'url' => 'external-link-alt', 'vat' => 'money-check-alt', 'vcard' => 'arrow-alt-circle-down',
5675 'jabber' => 'comment',
5676 'website' => 'globe-americas', 'workstation' => 'pallet', 'webhook' => 'bullseye', 'world' => 'globe', 'private' => 'user-lock',
5677 'conferenceorbooth' => 'chalkboard-teacher', 'eventorganization' => 'project-diagram',
5678 'webportal' => 'door-open'
5679 );
5680
5681 if ($conf->currency == 'EUR') {
5682 $arrayconvpictotofa['currency'] = 'euro-sign';
5683 $arrayconvpictotofa['multicurrency'] = 'dollar-sign';
5684 } else {
5685 $arrayconvpictotofa['currency'] = 'dollar-sign';
5686 $arrayconvpictotofa['multicurrency'] = 'euro-sign';
5687 }
5688
5689 return $arrayconvpictotofa;
5690}
5691
5692
5707function img_object($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $srconly = 0, $notitle = 0, $allowothertags = array())
5708{
5709 if (strpos($picto, '^') === 0) {
5710 return img_picto($titlealt, str_replace('^', '', $picto), $moreatt, $pictoisfullpath, $srconly, $notitle, '', '', 2, $allowothertags);
5711 } else {
5712 return img_picto($titlealt, 'object_'.$picto, $moreatt, $pictoisfullpath, $srconly, $notitle, '', '', 2, $allowothertags);
5713 }
5714}
5715
5727function img_weather($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $morecss = '')
5728{
5729 global $conf;
5730
5731 if (is_numeric($picto)) {
5732 //$leveltopicto = array(0=>'weather-clear.png', 1=>'weather-few-clouds.png', 2=>'weather-clouds.png', 3=>'weather-many-clouds.png', 4=>'weather-storm.png');
5733 //$picto = $leveltopicto[$picto];
5734 return '<i class="fa fa-weather-level'.$picto.'"></i>';
5735 } elseif (!preg_match('/(\.png|\.gif)$/i', $picto)) {
5736 $picto .= '.png';
5737 }
5738
5739 $path = DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/weather/'.$picto;
5740
5741 return img_picto($titlealt, $path, $moreatt, 1, 0, 0, '', $morecss);
5742}
5743
5755function img_picto_common($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $notitle = 0)
5756{
5757 global $conf;
5758
5759 if (!preg_match('/(\.png|\.gif)$/i', $picto)) {
5760 $picto .= '.png';
5761 }
5762
5763 if ($pictoisfullpath) {
5764 $path = $picto;
5765 } else {
5766 $path = DOL_URL_ROOT.'/theme/common/'.$picto;
5767
5768 if (getDolGlobalInt('MAIN_MODULE_CAN_OVERWRITE_COMMONICONS')) {
5769 $themepath = DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/'.$picto;
5770
5771 if (file_exists($themepath)) {
5772 $path = $themepath;
5773 }
5774 }
5775 }
5776
5777 return img_picto($titlealt, $path, $moreatt, 1, 0, $notitle);
5778}
5779
5793function img_action($titlealt, $numaction, $picto = '', $moreatt = '')
5794{
5795 global $langs;
5796
5797 if (empty($titlealt) || $titlealt == 'default') {
5798 if ($numaction == '-1' || $numaction == 'ST_NO') {
5799 $numaction = -1;
5800 $titlealt = $langs->transnoentitiesnoconv('ChangeDoNotContact');
5801 } elseif ($numaction == '0' || $numaction == 'ST_NEVER') {
5802 $numaction = 0;
5803 $titlealt = $langs->transnoentitiesnoconv('ChangeNeverContacted');
5804 } elseif ($numaction == '1' || $numaction == 'ST_TODO') {
5805 $numaction = 1;
5806 $titlealt = $langs->transnoentitiesnoconv('ChangeToContact');
5807 } elseif ($numaction == '2' || $numaction == 'ST_PEND') {
5808 $numaction = 2;
5809 $titlealt = $langs->transnoentitiesnoconv('ChangeContactInProcess');
5810 } elseif ($numaction == '3' || $numaction == 'ST_DONE') {
5811 $numaction = 3;
5812 $titlealt = $langs->transnoentitiesnoconv('ChangeContactDone');
5813 } else {
5814 $titlealt = $langs->transnoentitiesnoconv('ChangeStatus '.$numaction);
5815 $numaction = 0;
5816 }
5817 }
5818 if (!is_numeric($numaction)) {
5819 $numaction = 0;
5820 }
5821
5822 return img_picto($titlealt, (empty($picto) ? 'stcomm'.$numaction.'.png' : $picto), $moreatt);
5823}
5824
5832function img_pdf($titlealt = 'default', $size = 3)
5833{
5834 global $langs;
5835
5836 if ($titlealt == 'default') {
5837 $titlealt = $langs->trans('Show');
5838 }
5839
5840 return img_picto($titlealt, 'pdf'.$size.'.png');
5841}
5842
5850function img_edit_add($titlealt = 'default', $other = '')
5851{
5852 global $langs;
5853
5854 if ($titlealt == 'default') {
5855 $titlealt = $langs->trans('Add');
5856 }
5857
5858 return img_picto($titlealt, 'edit_add.png', $other);
5859}
5867function img_edit_remove($titlealt = 'default', $other = '')
5868{
5869 global $langs;
5870
5871 if ($titlealt == 'default') {
5872 $titlealt = $langs->trans('Remove');
5873 }
5874
5875 return img_picto($titlealt, 'edit_remove.png', $other);
5876}
5877
5886function img_edit($titlealt = 'default', $float = 0, $other = '')
5887{
5888 global $langs;
5889
5890 if ($titlealt == 'default') {
5891 $titlealt = $langs->trans('Modify');
5892 }
5893
5894 return img_picto($titlealt, 'edit.png', ($float ? 'style="float: '.($langs->tab_translate["DIRECTION"] == 'rtl' ? 'left' : 'right').'"' : "").($other ? ' '.$other : ''));
5895}
5896
5905function img_view($titlealt = 'default', $float = 0, $other = 'class="valignmiddle"')
5906{
5907 global $langs;
5908
5909 if ($titlealt == 'default') {
5910 $titlealt = $langs->trans('View');
5911 }
5912
5913 $moreatt = ($float ? 'style="float: right" ' : '').$other;
5914
5915 return img_picto($titlealt, 'eye', $moreatt);
5916}
5917
5926function img_delete($titlealt = 'default', $other = 'class="pictodelete"', $morecss = '')
5927{
5928 global $langs;
5929
5930 if ($titlealt == 'default') {
5931 $titlealt = $langs->trans('Delete');
5932 }
5933
5934 return img_picto($titlealt, 'delete.png', $other, 0, 0, 0, '', $morecss);
5935}
5936
5944function img_printer($titlealt = "default", $other = '')
5945{
5946 global $langs;
5947 if ($titlealt == "default") {
5948 $titlealt = $langs->trans("Print");
5949 }
5950 return img_picto($titlealt, 'printer.png', $other);
5951}
5952
5960function img_split($titlealt = 'default', $other = 'class="pictosplit"')
5961{
5962 global $langs;
5963
5964 if ($titlealt == 'default') {
5965 $titlealt = $langs->trans('Split');
5966 }
5967
5968 return img_picto($titlealt, 'split.png', $other);
5969}
5970
5978function img_help($usehelpcursor = 1, $usealttitle = 1)
5979{
5980 global $langs;
5981
5982 if ($usealttitle) {
5983 if (is_string($usealttitle)) {
5984 $usealttitle = dol_escape_htmltag($usealttitle);
5985 } else {
5986 $usealttitle = $langs->trans('Info');
5987 }
5988 }
5989
5990 return img_picto($usealttitle, 'info.png', 'style="vertical-align: middle;'.($usehelpcursor == 1 ? ' cursor: help' : ($usehelpcursor == 2 ? ' cursor: pointer' : '')).'"');
5991}
5992
5999function img_info($titlealt = 'default')
6000{
6001 global $langs;
6002
6003 if ($titlealt == 'default') {
6004 $titlealt = $langs->trans('Informations');
6005 }
6006
6007 return img_picto($titlealt, 'info.png', 'style="vertical-align: middle;"');
6008}
6009
6018function img_warning($titlealt = 'default', $moreatt = '', $morecss = 'pictowarning')
6019{
6020 global $langs;
6021
6022 if ($titlealt == 'default') {
6023 $titlealt = $langs->trans('Warning');
6024 }
6025
6026 //return '<div class="imglatecoin">'.img_picto($titlealt, 'warning_white.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): '')).'</div>';
6027 return img_picto($titlealt, 'warning.png', 'class="'.$morecss.'"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt) : ''));
6028}
6029
6036function img_error($titlealt = 'default')
6037{
6038 global $langs;
6039
6040 if ($titlealt == 'default') {
6041 $titlealt = $langs->trans('Error');
6042 }
6043
6044 return img_picto($titlealt, 'error.png');
6045}
6046
6054function img_next($titlealt = 'default', $moreatt = '')
6055{
6056 global $langs;
6057
6058 if ($titlealt == 'default') {
6059 $titlealt = $langs->trans('Next');
6060 }
6061
6062 //return img_picto($titlealt, 'next.png', $moreatt);
6063 return '<span class="fa fa-chevron-right paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
6064}
6065
6073function img_previous($titlealt = 'default', $moreatt = '')
6074{
6075 global $langs;
6076
6077 if ($titlealt == 'default') {
6078 $titlealt = $langs->trans('Previous');
6079 }
6080
6081 //return img_picto($titlealt, 'previous.png', $moreatt);
6082 return '<span class="fa fa-chevron-left paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
6083}
6084
6093function img_down($titlealt = 'default', $selected = 0, $moreclass = '')
6094{
6095 global $langs;
6096
6097 if ($titlealt == 'default') {
6098 $titlealt = $langs->trans('Down');
6099 }
6100
6101 return img_picto($titlealt, ($selected ? '1downarrow_selected.png' : '1downarrow.png'), 'class="imgdown'.($moreclass ? " ".$moreclass : "").'"');
6102}
6103
6112function img_up($titlealt = 'default', $selected = 0, $moreclass = '')
6113{
6114 global $langs;
6115
6116 if ($titlealt == 'default') {
6117 $titlealt = $langs->trans('Up');
6118 }
6119
6120 return img_picto($titlealt, ($selected ? '1uparrow_selected.png' : '1uparrow.png'), 'class="imgup'.($moreclass ? " ".$moreclass : "").'"');
6121}
6122
6131function img_left($titlealt = 'default', $selected = 0, $moreatt = '')
6132{
6133 global $langs;
6134
6135 if ($titlealt == 'default') {
6136 $titlealt = $langs->trans('Left');
6137 }
6138
6139 return img_picto($titlealt, ($selected ? '1leftarrow_selected.png' : '1leftarrow.png'), $moreatt);
6140}
6141
6150function img_right($titlealt = 'default', $selected = 0, $moreatt = '')
6151{
6152 global $langs;
6153
6154 if ($titlealt == 'default') {
6155 $titlealt = $langs->trans('Right');
6156 }
6157
6158 return img_picto($titlealt, ($selected ? '1rightarrow_selected.png' : '1rightarrow.png'), $moreatt);
6159}
6160
6168function img_allow($allow, $titlealt = 'default')
6169{
6170 global $langs;
6171
6172 if ($titlealt == 'default') {
6173 $titlealt = $langs->trans('Active');
6174 }
6175
6176 if ($allow == 1) {
6177 return img_picto($titlealt, 'tick.png');
6178 }
6179
6180 return '-';
6181}
6182
6190function img_credit_card($brand, $morecss = null)
6191{
6192 if (is_null($morecss)) {
6193 $morecss = 'fa-2x';
6194 }
6195
6196 if ($brand == 'visa' || $brand == 'Visa') {
6197 $brand = 'cc-visa';
6198 } elseif ($brand == 'mastercard' || $brand == 'MasterCard') {
6199 $brand = 'cc-mastercard';
6200 } elseif ($brand == 'amex' || $brand == 'American Express') {
6201 $brand = 'cc-amex';
6202 } elseif ($brand == 'discover' || $brand == 'Discover') {
6203 $brand = 'cc-discover';
6204 } elseif ($brand == 'jcb' || $brand == 'JCB') {
6205 $brand = 'cc-jcb';
6206 } elseif ($brand == 'diners' || $brand == 'Diners club') {
6207 $brand = 'cc-diners-club';
6208 } elseif (!in_array($brand, array('cc-visa', 'cc-mastercard', 'cc-amex', 'cc-discover', 'cc-jcb', 'cc-diners-club'))) {
6209 $brand = 'credit-card';
6210 }
6211
6212 return '<span class="fa fa-'.$brand.' fa-fw'.($morecss ? ' '.$morecss : '').'"></span>';
6213}
6214
6223function img_mime($file, $titlealt = '', $morecss = '')
6224{
6225 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
6226
6227 $mimetype = dol_mimetype($file, '', 1);
6228 //$mimeimg = dol_mimetype($file, '', 2);
6229 $mimefa = dol_mimetype($file, '', 4);
6230
6231 if (empty($titlealt)) {
6232 $titlealt = 'Mime type: '.$mimetype;
6233 }
6234
6235 //return img_picto_common($titlealt, 'mime/'.$mimeimg, 'class="'.$morecss.'"');
6236 return '<i class="fa fa-'.$mimefa.' '.(preg_match('/pictofixedwidth/', $morecss) ? '' : 'paddingright ').($morecss ? ' '.$morecss : '').'"'.($titlealt ? ' title="'.dolPrintHTMLForAttribute($titlealt).'"' : '').'></i>';
6237}
6238
6239
6247function img_search($titlealt = 'default', $other = '')
6248{
6249 global $langs;
6250
6251 if ($titlealt == 'default') {
6252 $titlealt = $langs->trans('Search');
6253 }
6254
6255 $img = img_picto($titlealt, 'search.png', $other, 0, 1);
6256
6257 $input = '<input type="image" class="liste_titre" name="button_search" src="'.$img.'" ';
6258 $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
6259
6260 return $input;
6261}
6262
6270function img_searchclear($titlealt = 'default', $other = '')
6271{
6272 global $langs;
6273
6274 if ($titlealt == 'default') {
6275 $titlealt = $langs->trans('Search');
6276 }
6277
6278 $img = img_picto($titlealt, 'searchclear.png', $other, 0, 1);
6279
6280 $input = '<input type="image" class="liste_titre" name="button_removefilter" src="'.$img.'" ';
6281 $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
6282
6283 return $input;
6284}
6285
6298function info_admin($text, $infoonimgalt = 0, $nodiv = 0, $admin = '1', $morecss = 'hideonsmartphone', $textfordropdown = '', $picto = '')
6299{
6300 global $conf, $langs;
6301
6302 if ($infoonimgalt) {
6303 $result = img_picto($text, 'info', 'class="'.($morecss ? ' '.$morecss : '').'"');
6304 } else {
6305 if (empty($conf->use_javascript_ajax)) {
6306 $textfordropdown = '';
6307 }
6308
6309 $class = (empty($admin) ? 'undefined' : ($admin == '1' ? 'info' : $admin));
6310 $fa = 'info-circle';
6311 if ($picto == 'warning') {
6312 $fa = 'exclamation-triangle';
6313 }
6314 $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> ';
6315 $result .= dol_escape_htmltag($text, 1, 0, 'div,span,b,br,a');
6316 $result .= ($nodiv ? '' : '</div>');
6317
6318 if ($textfordropdown) {
6319 $tmpresult = '<span class="'.$class.'text opacitymedium cursorpointer">'.$langs->trans($textfordropdown).' '.img_picto($langs->trans($textfordropdown), '1downarrow').'</span>';
6320 $tmpresult .= '<script nonce="'.getNonce().'" type="text/javascript">
6321 jQuery(document).ready(function() {
6322 jQuery(".'.$class.'text").click(function() {
6323 console.log("toggle text");
6324 jQuery(".'.$class.'").toggle();
6325 });
6326 });
6327 </script>';
6328
6329 $result = $tmpresult.$result;
6330 }
6331 }
6332
6333 return $result;
6334}
6335
6336
6348function dol_print_error($db = null, $error = '', $errors = null)
6349{
6350 global $conf, $langs, $user, $argv;
6351 global $dolibarr_main_prod;
6352
6353 $out = '';
6354 $syslog = '';
6355
6356 // If error occurs before the $lang object was loaded
6357 if (!$langs) {
6358 require_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
6359 $langs = new Translate('', $conf);
6360 $langs->load("main");
6361 }
6362
6363 // Load translation files required by the error messages
6364 $langs->loadLangs(array('main', 'errors'));
6365
6366 if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
6367 $out .= $langs->trans("DolibarrHasDetectedError").".<br>\n";
6368 if (getDolGlobalInt('MAIN_FEATURES_LEVEL') > 0) {
6369 $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";
6370 }
6371 $out .= $langs->trans("InformationToHelpDiagnose").":<br>\n";
6372
6373 $out .= "<b>".$langs->trans("Date").":</b> ".dol_print_date(time(), 'dayhourlog')."<br>\n";
6374 $out .= "<b>".$langs->trans("Dolibarr").":</b> ".DOL_VERSION." - https://www.dolibarr.org<br>\n";
6375 if (isset($conf->global->MAIN_FEATURES_LEVEL)) {
6376 $out .= "<b>".$langs->trans("LevelOfFeature").":</b> ".getDolGlobalInt('MAIN_FEATURES_LEVEL')."<br>\n";
6377 }
6378 if ($user instanceof User) {
6379 $out .= "<b>".$langs->trans("Login").":</b> ".$user->login."<br>\n";
6380 }
6381 if (function_exists("phpversion")) {
6382 $out .= "<b>".$langs->trans("PHP").":</b> ".phpversion()."<br>\n";
6383 }
6384 $out .= "<b>".$langs->trans("Server").":</b> ".(isset($_SERVER["SERVER_SOFTWARE"]) ? dol_htmlentities($_SERVER["SERVER_SOFTWARE"], ENT_COMPAT) : '')."<br>\n";
6385 if (function_exists("php_uname")) {
6386 $out .= "<b>".$langs->trans("OS").":</b> ".php_uname()."<br>\n";
6387 }
6388 $out .= "<b>".$langs->trans("UserAgent").":</b> ".(isset($_SERVER["HTTP_USER_AGENT"]) ? dol_htmlentities($_SERVER["HTTP_USER_AGENT"], ENT_COMPAT) : '')."<br>\n";
6389 $out .= "<br>\n";
6390 $out .= "<b>" . $langs->trans("RequestedUrl") . ":</b> " . (isset($_SERVER["REQUEST_URI"]) ? dol_htmlentities($_SERVER["REQUEST_URI"], ENT_COMPAT) : '') . "<br>\n";
6391 $out .= "<b>" . $langs->trans("Referer") . ":</b> " . (isset($_SERVER["HTTP_REFERER"]) ? dol_htmlentities($_SERVER["HTTP_REFERER"], ENT_COMPAT) : '') . "<br>\n";
6392 $out .= "<b>" . $langs->trans("MenuManager") . ":</b> " . (isset($conf->standard_menu) ? dol_htmlentities($conf->standard_menu, ENT_COMPAT) : '') . "<br>\n";
6393 $out .= "<br>\n";
6394 $syslog .= "url=" . (isset($_SERVER["REQUEST_URI"]) ? dol_escape_htmltag($_SERVER["REQUEST_URI"]) : '');
6395 $syslog .= ", query_string=" . (isset($_SERVER["QUERY_STRING"]) ? dol_escape_htmltag($_SERVER["QUERY_STRING"]) : '');
6396 } else { // Mode CLI
6397 $out .= '> '.$langs->transnoentities("ErrorInternalErrorDetected").":\n".$argv[0]."\n";
6398 $syslog .= "pid=".dol_getmypid();
6399 }
6400
6401 if (!empty($conf->modules)) {
6402 $out .= "<b>".$langs->trans("Modules").":</b> ".implode(', ', $conf->modules)."<br>\n";
6403 }
6404
6405 if (is_object($db)) {
6406 if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
6407 $out .= "<b>".$langs->trans("DatabaseTypeManager").":</b> ".$db->type."<br>\n";
6408 $lastqueryerror = $db->lastqueryerror();
6409 if (!utf8_check($lastqueryerror)) {
6410 $lastqueryerror = "SQL error string is not a valid UTF8 string. We can't show it.";
6411 }
6412 $out .= "<b>".$langs->trans("RequestLastAccessInError").":</b> ".($lastqueryerror ? dol_escape_htmltag($lastqueryerror) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
6413 $out .= "<b>".$langs->trans("ReturnCodeLastAccessInError").":</b> ".($db->lasterrno() ? dol_escape_htmltag($db->lasterrno()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
6414 $out .= "<b>".$langs->trans("InformationLastAccessInError").":</b> ".($db->lasterror() ? dol_escape_htmltag($db->lasterror()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
6415 $out .= "<br>\n";
6416 } else { // Mode CLI
6417 // No dol_escape_htmltag for output, we are in CLI mode
6418 $out .= '> '.$langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n";
6419 $out .= '> '.$langs->transnoentities("RequestLastAccessInError").":\n".($db->lastqueryerror() ? $db->lastqueryerror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
6420 $out .= '> '.$langs->transnoentities("ReturnCodeLastAccessInError").":\n".($db->lasterrno() ? $db->lasterrno() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
6421 $out .= '> '.$langs->transnoentities("InformationLastAccessInError").":\n".($db->lasterror() ? $db->lasterror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
6422 }
6423 $syslog .= ", sql=".$db->lastquery();
6424 $syslog .= ", db_error=".$db->lasterror();
6425 }
6426
6427 if ($error || $errors) {
6428 // Merge all into $errors array
6429 if (is_array($error) && is_array($errors)) {
6430 $errors = array_merge($error, $errors);
6431 } elseif (is_array($error)) { // deprecated, use second parameters
6432 $errors = $error;
6433 } elseif (is_array($errors) && !empty($error)) {
6434 $errors = array_merge(array($error), $errors);
6435 } elseif (!empty($error)) {
6436 $errors = array_merge(array($error), array($errors));
6437 }
6438
6439 $langs->load("errors");
6440
6441 foreach ($errors as $msg) {
6442 if (empty($msg)) {
6443 continue;
6444 }
6445 if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
6446 $out .= "<b>".$langs->trans("Message").":</b> ".dol_escape_htmltag($msg)."<br>\n";
6447 } else { // Mode CLI
6448 $out .= '> '.$langs->transnoentities("Message").":\n".$msg."\n";
6449 }
6450 $syslog .= ", msg=".$msg;
6451 }
6452 }
6453 if (empty($dolibarr_main_prod) && $_SERVER['DOCUMENT_ROOT'] && function_exists('xdebug_print_function_stack') && function_exists('xdebug_call_file')) {
6454 xdebug_print_function_stack();
6455 $out .= '<b>XDebug information:</b>'."<br>\n";
6456 $out .= 'File: '.xdebug_call_file()."<br>\n";
6457 $out .= 'Line: '.xdebug_call_line()."<br>\n";
6458 $out .= 'Function: '.xdebug_call_function()."<br>\n";
6459 $out .= "<br>\n";
6460 }
6461
6462 // Return a http header with error code if possible
6463 if (!headers_sent()) {
6464 if (function_exists('top_httphead')) { // In CLI context, the method does not exists
6465 top_httphead();
6466 }
6467 //http_response_code(500); // If we use 500, message is not output with some command line tools
6468 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
6469 }
6470
6471 if (empty($dolibarr_main_prod)) {
6472 print $out;
6473 } else {
6474 if (empty($langs->defaultlang)) {
6475 $langs->setDefaultLang();
6476 }
6477 $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.
6478 // This should not happen, except if there is a bug somewhere. Enabled and check log in such case.
6479 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";
6480 print $langs->trans("DolibarrHasDetectedError").'. ';
6481 print $langs->trans("YouCanSetOptionDolibarrMainProdToZero");
6482 if (!defined("MAIN_CORE_ERROR")) {
6483 define("MAIN_CORE_ERROR", 1);
6484 }
6485 }
6486
6487 dol_syslog("Error ".$syslog, LOG_ERR);
6488}
6489
6500function dol_print_error_email($prefixcode, $errormessage = '', $errormessages = array(), $morecss = 'error', $email = '')
6501{
6502 global $langs;
6503
6504 if (empty($email)) {
6505 $email = getDolGlobalString('MAIN_INFO_SOCIETE_MAIL');
6506 }
6507
6508 $langs->load("errors");
6509 $now = dol_now();
6510
6511 print '<br><div class="center login_main_message"><div class="'.$morecss.'">';
6512 print $langs->trans("ErrorContactEMail", $email, $prefixcode.'-'.dol_print_date($now, '%Y%m%d%H%M%S'));
6513 if ($errormessage) {
6514 print '<br><br>'.$errormessage;
6515 }
6516 if (is_array($errormessages) && count($errormessages)) {
6517 foreach ($errormessages as $mesgtoshow) {
6518 print '<br><br>'.$mesgtoshow;
6519 }
6520 }
6521 print '</div></div>';
6522}
6523
6540function print_liste_field_titre($name, $file = "", $field = "", $begin = "", $param = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $tooltip = "", $forcenowrapcolumntitle = 0)
6541{
6542 print getTitleFieldOfList($name, 0, $file, $field, $begin, $param, $moreattrib, $sortfield, $sortorder, $prefix, 0, $tooltip, $forcenowrapcolumntitle);
6543}
6544
6563function getTitleFieldOfList($name, $thead = 0, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $disablesortlink = 0, $tooltip = '', $forcenowrapcolumntitle = 0)
6564{
6565 global $langs, $form;
6566 //print "$name, $file, $field, $begin, $options, $moreattrib, $sortfield, $sortorder<br>\n";
6567
6568 if ($moreattrib == 'class="right"') {
6569 $prefix .= 'right '; // For backward compatibility
6570 }
6571
6572 $sortorder = strtoupper((string) $sortorder);
6573 $out = '';
6574 $sortimg = '';
6575
6576 $tag = 'th';
6577 if ($thead == 2) {
6578 $tag = 'div';
6579 }
6580
6581 $tmpsortfield = explode(',', (string) $sortfield);
6582 $sortfield1 = trim($tmpsortfield[0]); // If $sortfield is 'd.datep,d.id', it becomes 'd.datep'
6583 $tmpfield = explode(',', $field);
6584 $field1 = trim($tmpfield[0]); // If $field is 'd.datep,d.id', it becomes 'd.datep'
6585
6586 if (!getDolGlobalString('MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE') && empty($forcenowrapcolumntitle)) {
6587 $prefix = 'wrapcolumntitle '.$prefix;
6588 }
6589
6590 //var_dump('field='.$field.' field1='.$field1.' sortfield='.$sortfield.' sortfield1='.$sortfield1);
6591 // If field is used as sort criteria we use a specific css class liste_titre_sel
6592 // Example if (sortfield,field)=("nom","xxx.nom") or (sortfield,field)=("nom","nom")
6593 $liste_titre = 'liste_titre';
6594 if ($field1 && ($sortfield1 == $field1 || $sortfield1 == preg_replace("/^[^\.]+\./", "", $field1))) {
6595 $liste_titre = 'liste_titre_sel';
6596 }
6597
6598 $tagstart = '<'.$tag.' class="'.$prefix.$liste_titre.'" '.$moreattrib;
6599 //$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)).'"' : '');
6600 $tagstart .= ($name && !getDolGlobalString('MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE') && empty($forcenowrapcolumntitle) && !dol_textishtml($name)) ? ' title="'.dolPrintHTMLForAttribute($langs->trans($name)).'"' : '';
6601 $tagstart .= '>';
6602
6603 if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
6604 $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
6605 $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
6606 $options = preg_replace('/&+/i', '&', $options);
6607 if (!preg_match('/^&/', $options)) {
6608 $options = '&'.$options;
6609 }
6610
6611 $sortordertouseinlink = '';
6612 if ($field1 != $sortfield1) { // We are on another field than current sorted field
6613 if (preg_match('/^DESC/i', $sortorder)) {
6614 $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
6615 } else { // We reverse the var $sortordertouseinlink
6616 $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
6617 }
6618 } else { // We are on field that is the first current sorting criteria
6619 if (preg_match('/^ASC/i', $sortorder)) { // We reverse the var $sortordertouseinlink
6620 $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
6621 } else {
6622 $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
6623 }
6624 }
6625 $sortordertouseinlink = preg_replace('/,$/', '', $sortordertouseinlink);
6626 $out .= '<a class="reposition" href="'.$file.'?sortfield='.urlencode($field).'&sortorder='.urlencode($sortordertouseinlink).'&begin='.urlencode($begin).$options.'"';
6627 //$out .= (getDolGlobalString('MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE') ? '' : ' title="'.dol_escape_htmltag($langs->trans($name)).'"');
6628 $out .= '>';
6629 }
6630 if ($tooltip) {
6631 // You can also use 'TranslationString:keyfortooltiponclick:tooltipdirection' for a tooltip on click or to change tooltip position.
6632 if (strpos($tooltip, ':') !== false) {
6633 $tmptooltip = explode(':', $tooltip);
6634 } else {
6635 $tmptooltip = array($tooltip);
6636 }
6637 $out .= $form->textwithpicto($langs->trans((string) $name), $langs->trans($tmptooltip[0]), (empty($tmptooltip[2]) ? '1' : $tmptooltip[2]), 'help', '', 0, 3, (empty($tmptooltip[1]) ? '' : 'extra_'.str_replace('.', '_', $field).'_'.$tmptooltip[1]));
6638 } else {
6639 $out .= $langs->trans((string) $name);
6640 }
6641
6642 if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
6643 $out .= '</a>';
6644 }
6645
6646 if (empty($thead) && $field) { // If this is a sort field
6647 $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
6648 $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
6649 $options = preg_replace('/&+/i', '&', $options);
6650 if (!preg_match('/^&/', $options)) {
6651 $options = '&'.$options;
6652 }
6653
6654 if (!$sortorder || ($field1 != $sortfield1)) {
6655 // Nothing
6656 } else {
6657 if (preg_match('/^DESC/', $sortorder)) {
6658 $sortimg .= '<span class="nowrap">'.img_up("Z-A", 0, 'paddingright').'</span>';
6659 }
6660 if (preg_match('/^ASC/', $sortorder)) {
6661 $sortimg .= '<span class="nowrap">'.img_down("A-Z", 0, 'paddingright').'</span>';
6662 }
6663 }
6664 }
6665
6666 $tagend = '</'.$tag.'>';
6667
6668 $out = $tagstart.$sortimg.$out.$tagend;
6669
6670 return $out;
6671}
6672
6681function print_titre($title)
6682{
6683 dol_syslog(__FUNCTION__." is deprecated", LOG_WARNING);
6684
6685 print '<div class="titre">'.$title.'</div>';
6686}
6687
6699function print_fiche_titre($title, $mesg = '', $picto = 'generic', $pictoisfullpath = 0, $id = '')
6700{
6701 print load_fiche_titre($title, $mesg, $picto, $pictoisfullpath, $id);
6702}
6703
6717function load_fiche_titre($title, $morehtmlright = '', $picto = 'generic', $pictoisfullpath = 0, $id = '', $morecssontable = '', $morehtmlcenter = '')
6718{
6719 $return = '';
6720
6721 if ($picto == 'setup') {
6722 $picto = 'generic';
6723 }
6724
6725 $return .= "\n";
6726 $return .= '<table '.($id ? 'id="'.$id.'" ' : '').'class="centpercent notopnoleftnoright table-fiche-title'.($morecssontable ? ' '.$morecssontable : '').'">'; // margin bottom must be same than into print_barre_list
6727 $return .= '<tr class="toptitle">';
6728 if ($picto) {
6729 $return .= '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle widthpictotitle pictotitle"', $pictoisfullpath).'</td>';
6730 }
6731 $return .= '<td class="nobordernopadding valignmiddle col-title">';
6732 $return .= '<div class="titre inline-block">';
6733 $return .= '<span class="inline-block valignmiddle">'.$title.'</span>'; // $title is already HTML sanitized content
6734 $return .= '</div>';
6735 $return .= '</td>';
6736 if (dol_strlen($morehtmlcenter)) {
6737 $return .= '<td class="nobordernopadding center valignmiddle col-center">'.$morehtmlcenter.'</td>';
6738 }
6739 if (dol_strlen($morehtmlright)) {
6740 $return .= '<td class="nobordernopadding titre_right wordbreakimp right valignmiddle col-right">'.$morehtmlright.'</td>';
6741 }
6742 $return .= '</tr></table>'."\n";
6743
6744 return $return;
6745}
6746
6770function print_barre_liste($title, $page, $file, $options = '', $sortfield = '', $sortorder = '', $morehtmlcenter = '', $num = -1, $totalnboflines = '', $picto = 'generic', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limit = -1, $selectlimitsuffix = 0, $hidenavigation = 0, $pagenavastextinput = 0, $morehtmlrightbeforearrow = '')
6771{
6772 global $conf, $langs;
6773
6774 $savlimit = $limit;
6775 $savtotalnboflines = $totalnboflines;
6776 if (is_numeric($totalnboflines)) {
6777 $totalnboflines = abs($totalnboflines);
6778 }
6779
6780 // Detect if there is a subtitle
6781 $subtitle = '';
6782 $tmparray = preg_split('/<br>/i', $title, 2);
6783 if (!empty($tmparray[1])) {
6784 $title = $tmparray[0];
6785 $subtitle = $tmparray[1];
6786 }
6787
6788 $page = (int) $page;
6789
6790 if ($picto == 'setup') {
6791 $picto = 'title_setup.png';
6792 }
6793 if (($conf->browser->name == 'ie') && $picto == 'generic') {
6794 $picto = 'title.gif';
6795 }
6796 if ($limit < 0) {
6797 $limit = $conf->liste_limit;
6798 }
6799
6800 if ($savlimit != 0 && (($num > $limit) || ($num == -1) || ($limit == 0))) {
6801 $nextpage = 1;
6802 } else {
6803 $nextpage = 0;
6804 }
6805 //print 'totalnboflines='.$totalnboflines.'-savlimit='.$savlimit.'-limit='.$limit.'-num='.$num.'-nextpage='.$nextpage.'-selectlimitsuffix='.$selectlimitsuffix.'-hidenavigation='.$hidenavigation;
6806
6807 print "\n";
6808 print "<!-- Begin print_barre_liste -->\n";
6809 print '<table class="centpercent notopnoleftnoright table-fiche-title'.($morecss ? ' '.$morecss : '').'">';
6810 print '<tr class="toptitle">'; // margin bottom must be same than into load_fiche_tire
6811
6812 // Left
6813
6814 if ($picto && $title) {
6815 print '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">';
6816 print img_picto('', $picto, 'class="valignmiddle pictotitle widthpictotitle"', $pictoisfullpath);
6817 print '</td>';
6818 }
6819
6820 print '<td class="nobordernopadding valignmiddle col-title">';
6821 print '<div class="titre inline-block">';
6822 print '<span class="inline-block valignmiddle print-barre-liste">'.$title.'</span>'; // $title may contains HTML like a combo list from page consumption.php, so we do not use dolPrintLabel here()
6823 if (!empty($title) && $savtotalnboflines >= 0 && (string) $savtotalnboflines != '' && $totalnboflines > 0) {
6824 print '<span class="opacitymedium colorblack marginleftonly totalnboflines valignmiddle" title="'.$langs->trans("NbRecordQualified").'">('.$totalnboflines.')</span>';
6825 }
6826 print '</div>';
6827 if (!empty($subtitle)) {
6828 print '<br><div class="subtitle inline-block hideonsmartphone">'.$subtitle.'</div>';
6829 }
6830 print '</td>';
6831
6832 // Center
6833 if ($morehtmlcenter && empty($conf->dol_optimize_smallscreen)) {
6834 print '<td class="nobordernopadding center valignmiddle col-center">'.$morehtmlcenter.'</td>';
6835 }
6836
6837 // Right
6838 print '<td class="nobordernopadding valignmiddle right col-right">';
6839 print '<input type="hidden" name="pageplusoneold" value="'.((int) $page + 1).'">';
6840 if ($sortfield) {
6841 $options .= "&sortfield=".urlencode($sortfield);
6842 }
6843 if ($sortorder) {
6844 $options .= "&sortorder=".urlencode($sortorder);
6845 }
6846 // Show navigation bar
6847 $pagelist = '';
6848 if ($savlimit != 0 && ($page > 0 || $num > $limit)) {
6849 if ($totalnboflines) { // If we know total nb of lines
6850 // Define nb of extra page links before and after selected page + ... + first or last
6851 $maxnbofpage = (empty($conf->dol_optimize_smallscreen) ? 4 : 0);
6852
6853 if ($limit > 0) {
6854 $nbpages = ceil($totalnboflines / $limit);
6855 } else {
6856 $nbpages = 1;
6857 }
6858 $cpt = ($page - $maxnbofpage);
6859 if ($cpt < 0) {
6860 $cpt = 0;
6861 }
6862
6863 if ($cpt >= 1) {
6864 if (empty($pagenavastextinput)) {
6865 $pagelist .= '<li class="pagination"><a class="reposition" href="'.$file.'?page=0'.$options.'">1</a></li>';
6866 if ($cpt > 2) {
6867 $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
6868 } elseif ($cpt == 2) {
6869 $pagelist .= '<li class="pagination"><a class="reposition" href="'.$file.'?page=1'.$options.'">2</a></li>';
6870 }
6871 }
6872 }
6873
6874 do {
6875 if ($pagenavastextinput) {
6876 if ($cpt == $page) {
6877 $pagelist .= '<li class="pagination pageplusone valignmiddle"><input type="text" class="'.($totalnboflines > 100 ? 'width40' : 'width25').' center pageplusone heightofcombo" name="pageplusone" value="'.($page + 1).'"></li>';
6878 $pagelist .= '/';
6879 }
6880 } else {
6881 if ($cpt == $page) {
6882 $pagelist .= '<li class="pagination"><span class="active">'.($page + 1).'</span></li>';
6883 } else {
6884 $pagelist .= '<li class="pagination"><a class="reposition" href="'.$file.'?page='.$cpt.$options.'">'.($cpt + 1).'</a></li>';
6885 }
6886 }
6887 $cpt++;
6888 } while ($cpt < $nbpages && $cpt <= ($page + $maxnbofpage));
6889
6890 if (empty($pagenavastextinput)) {
6891 if ($cpt < $nbpages) {
6892 if ($cpt < $nbpages - 2) {
6893 $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
6894 } elseif ($cpt == $nbpages - 2) {
6895 $pagelist .= '<li class="pagination"><a class="reposition" href="'.$file.'?page='.($nbpages - 2).$options.'">'.($nbpages - 1).'</a></li>';
6896 }
6897 $pagelist .= '<li class="pagination"><a class="reposition" href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
6898 }
6899 } else {
6900 //var_dump($page.' '.$cpt.' '.$nbpages);
6901 $pagelist .= '<li class="pagination paginationlastpage"><a class="reposition" href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
6902 }
6903 } else {
6904 $pagelist .= '<li class="pagination"><span class="active">'.($page + 1)."</li>";
6905 }
6906 }
6907
6908 if ($savlimit || $morehtmlright || $morehtmlrightbeforearrow) {
6909 print_fleche_navigation($page, $file, $options, $nextpage, $pagelist, $morehtmlright, $savlimit, $totalnboflines, $selectlimitsuffix, $morehtmlrightbeforearrow, $hidenavigation); // output the div and ul for previous/last completed with page numbers into $pagelist
6910 }
6911
6912 // js to autoselect page field on focus
6913 if ($pagenavastextinput) {
6914 print ajax_autoselect('.pageplusone');
6915 }
6916
6917 print '</td>';
6918 print '</tr>';
6919
6920 print '</table>'."\n";
6921
6922 // Center
6923 if ($morehtmlcenter && !empty($conf->dol_optimize_smallscreen)) {
6924 print '<div class="nobordernopadding marginbottomonly center valignmiddle col-center centpercent">'.$morehtmlcenter.'</div>';
6925 }
6926
6927 print "<!-- End title -->\n\n";
6928}
6929
6946function print_fleche_navigation($page, $file, $options = '', $nextpage = 0, $betweenarrows = '', $afterarrows = '', $limit = -1, $totalnboflines = 0, $selectlimitsuffix = '', $beforearrows = '', $hidenavigation = 0)
6947{
6948 global $conf, $langs;
6949
6950 print '<div class="pagination"><ul>';
6951 if ($beforearrows) {
6952 print '<li class="paginationbeforearrows">';
6953 print $beforearrows;
6954 print '</li>';
6955 }
6956
6957 if (empty($hidenavigation)) {
6958 if ((int) $limit > 0 && (empty($selectlimitsuffix) || !is_numeric($selectlimitsuffix))) {
6959 $pagesizechoices = '10:10,15:15,20:20,25:25,50:50,100:100,250:250,500:500,1000:1000';
6960 $pagesizechoices .= ',5000:5000';
6961 //$pagesizechoices .= ',10000:10000'; // Memory trouble on most browsers
6962 //$pagesizechoices .= ',20000:20000'; // Memory trouble on most browsers
6963 //$pagesizechoices .= ',0:'.$langs->trans("All"); // Not yet supported
6964 //$pagesizechoices .= ',2:2';
6965 if (getDolGlobalString('MAIN_PAGESIZE_CHOICES')) {
6966 $pagesizechoices = getDolGlobalString('MAIN_PAGESIZE_CHOICES');
6967 }
6968
6969 if (getDolGlobalString('MAIN_USE_HTML5_LIMIT_SELECTOR')) {
6970 print '<li class="pagination">';
6971 print '<input onfocus="this.value=null;" onchange="this.blur();" class="flat selectlimit nopadding maxwidth75 right pageplusone" id="limit" name="limit" list="limitlist" title="'.dol_escape_htmltag($langs->trans("MaxNbOfRecordPerPage")).'" value="'.$limit.'">';
6972 print '<datalist id="limitlist">';
6973 } else {
6974 print '<li class="paginationcombolimit valignmiddle">';
6975 print '<select id="limit'.(is_numeric($selectlimitsuffix) ? '' : $selectlimitsuffix).'" name="limit" class="flat selectlimit nopadding maxwidth75 center'.(is_numeric($selectlimitsuffix) ? '' : ' '.$selectlimitsuffix).'" title="'.dol_escape_htmltag($langs->trans("MaxNbOfRecordPerPage")).'">';
6976 }
6977 $tmpchoice = explode(',', $pagesizechoices);
6978 $tmpkey = $limit.':'.$limit;
6979 if (!in_array($tmpkey, $tmpchoice)) {
6980 $tmpchoice[$tmpkey] = $tmpkey;
6981 }
6982 $tmpkey = $conf->liste_limit.':'.$conf->liste_limit;
6983 if (!in_array($tmpkey, $tmpchoice)) {
6984 $tmpchoice[$tmpkey] = $tmpkey;
6985 }
6986 asort($tmpchoice, SORT_NUMERIC);
6987 foreach ($tmpchoice as $val) {
6988 $selected = '';
6989 $tmp = explode(':', $val);
6990 $key = $tmp[0];
6991 $val = $tmp[1];
6992 if ($key != '' && $val != '') {
6993 if ((int) $key == (int) $limit) {
6994 $selected = ' selected="selected"';
6995 }
6996 print '<option name="'.$key.'"'.$selected.'>'.dol_escape_htmltag($val).'</option>'."\n";
6997 }
6998 }
6999 if (getDolGlobalString('MAIN_USE_HTML5_LIMIT_SELECTOR')) {
7000 print '</datalist>';
7001 } else {
7002 print '</select>';
7003 print ajax_combobox("limit".(is_numeric($selectlimitsuffix) ? '' : $selectlimitsuffix), array(), 0, 0, 'resolve', '-1', 'limit');
7004 //print ajax_combobox("limit");
7005 }
7006
7007 if ($conf->use_javascript_ajax) {
7008 print '<!-- JS CODE TO ENABLE select limit to launch submit of page -->
7009 <script>
7010 jQuery(document).ready(function () {
7011 jQuery(".selectlimit").change(function() {
7012 console.log("We change limit so we submit the form");
7013 $(this).parents(\'form:first\').submit();
7014 });
7015 });
7016 </script>
7017 ';
7018 }
7019 print '</li>';
7020 }
7021 if ($page > 0) {
7022 print '<li class="pagination paginationpage paginationpageleft"><a class="paginationprevious reposition" href="'.$file.'?page='.($page - 1).$options.'"><i class="fa fa-chevron-left" title="'.dol_escape_htmltag($langs->trans("Previous")).'"></i></a></li>';
7023 }
7024 if ($betweenarrows) {
7025 print '<!--<div class="betweenarrows nowraponall inline-block">-->';
7026 print $betweenarrows;
7027 print '<!--</div>-->';
7028 }
7029 if ($nextpage > 0) {
7030 print '<li class="pagination paginationpage paginationpageright"><a class="paginationnext reposition" href="'.$file.'?page='.($page + 1).$options.'"><i class="fa fa-chevron-right" title="'.dol_escape_htmltag($langs->trans("Next")).'"></i></a></li>';
7031 }
7032 if ($afterarrows) {
7033 print '<li class="paginationafterarrows">';
7034 print $afterarrows;
7035 print '</li>';
7036 }
7037 }
7038 print '</ul></div>'."\n";
7039}
7040
7041
7053function vatrate($rate, $addpercent = false, $info_bits = 0, $usestarfornpr = 0, $html = 0)
7054{
7055 $morelabel = '';
7056
7057 if (preg_match('/%/', $rate)) {
7058 $rate = str_replace('%', '', $rate);
7059 $addpercent = true;
7060 }
7061 $reg = array();
7062 if (preg_match('/\‍((.*)\‍)/', $rate, $reg)) {
7063 $morelabel = ' ('.$reg[1].')';
7064 $rate = preg_replace('/\s*'.preg_quote($morelabel, '/').'/', '', $rate);
7065 $morelabel = ' '.($html ? '<span class="opacitymedium">' : '').'('.$reg[1].')'.($html ? '</span>' : '');
7066 }
7067 if (preg_match('/\*/', $rate)) {
7068 $rate = str_replace('*', '', $rate);
7069 $info_bits |= 1;
7070 }
7071
7072 // If rate is '9/9/9' we don't change it. If rate is '9.000' we apply price()
7073 if (!preg_match('/\//', $rate)) {
7074 $ret = price($rate, 0, '', 0, 0).($addpercent ? '%' : '');
7075 } else {
7076 // TODO Split on / and output with a price2num to have clean numbers without ton of 000.
7077 $ret = $rate.($addpercent ? '%' : '');
7078 }
7079 if (($info_bits & 1) && $usestarfornpr >= 0) {
7080 $ret .= ' *';
7081 }
7082 $ret .= $morelabel;
7083 return $ret;
7084}
7085
7086
7102function price($amount, $form = 0, $outlangs = '', $trunc = 1, $rounding = -1, $forcerounding = -1, $currency_code = '')
7103{
7104 global $langs, $conf;
7105
7106 // Clean parameters
7107 if (empty($amount)) {
7108 $amount = 0; // To have a numeric value if amount not defined or = ''
7109 }
7110 $amount = (is_numeric($amount) ? $amount : 0); // Check if amount is numeric, for example, an error occurred when amount value = o (letter) instead 0 (number)
7111 if ($rounding == -1) {
7112 $rounding = min(getDolGlobalString('MAIN_MAX_DECIMALS_UNIT'), getDolGlobalString('MAIN_MAX_DECIMALS_TOT'));
7113 }
7114 $nbdecimal = $rounding;
7115
7116 if ($outlangs === 'none') {
7117 // Use international separators
7118 $dec = '.';
7119 $thousand = '';
7120 } else {
7121 // Output separators by default (french)
7122 $dec = ',';
7123 $thousand = ' ';
7124
7125 // If $outlangs not forced, we use use language
7126 if (!($outlangs instanceof Translate)) {
7127 $outlangs = $langs;
7128 }
7129
7130 if ($outlangs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
7131 $dec = $outlangs->transnoentitiesnoconv("SeparatorDecimal");
7132 }
7133 if ($outlangs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
7134 $thousand = $outlangs->transnoentitiesnoconv("SeparatorThousand");
7135 }
7136 if ($thousand == 'None') {
7137 $thousand = '';
7138 } elseif ($thousand == 'Space') {
7139 $thousand = ' ';
7140 }
7141 }
7142 //print "outlangs=".$outlangs->defaultlang." amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
7143
7144 //print "amount=".$amount."-";
7145 $amount = str_replace(',', '.', $amount); // should be useless
7146 //print $amount."-";
7147 $data = explode('.', $amount);
7148 $decpart = isset($data[1]) ? $data[1] : '';
7149 $decpart = preg_replace('/0+$/i', '', $decpart); // Supprime les 0 de fin de partie decimale
7150 //print "decpart=".$decpart."<br>";
7151 $end = '';
7152
7153 // We increase nbdecimal if there is more decimal than asked (to not loose information)
7154 if (dol_strlen($decpart) > $nbdecimal) {
7155 $nbdecimal = dol_strlen($decpart);
7156 }
7157
7158 // If nbdecimal is higher than max to show
7159 $nbdecimalmaxshown = (int) str_replace('...', '', getDolGlobalString('MAIN_MAX_DECIMALS_SHOWN'));
7160 if ($trunc && $nbdecimal > $nbdecimalmaxshown) {
7161 $nbdecimal = $nbdecimalmaxshown;
7162 if (preg_match('/\.\.\./i', getDolGlobalString('MAIN_MAX_DECIMALS_SHOWN'))) {
7163 // If output is truncated, we show ...
7164 $end = '...';
7165 }
7166 }
7167
7168 // If force rounding
7169 if ((string) $forcerounding != '-1' && (string) $forcerounding != '') {
7170 if ($forcerounding === 'MU') {
7171 $nbdecimal = getDolGlobalInt('MAIN_MAX_DECIMALS_UNIT');
7172 } elseif ($forcerounding === 'MT') {
7173 $nbdecimal = getDolGlobalInt('MAIN_MAX_DECIMALS_TOT');
7174 } elseif ($forcerounding >= 0) {
7175 $nbdecimal = (int) $forcerounding;
7176 }
7177 }
7178
7179 // Format number
7180 $output = number_format((float) $amount, $nbdecimal, $dec, $thousand);
7181 // Add symbol of currency if requested
7182 $cursymbolbefore = $cursymbolafter = '';
7183 if ($currency_code && is_object($outlangs)) {
7184 if ($currency_code == 'auto') {
7185 $currency_code = $conf->currency;
7186 }
7187
7188 $listofcurrenciesbefore = array('AUD', 'CAD', 'CNY', 'COP', 'CLP', 'GBP', 'HKD', 'MXN', 'PEN', 'USD', 'CRC', 'ZAR');
7189 $listoflanguagesbefore = array('nl_NL');
7190 if (in_array($currency_code, $listofcurrenciesbefore) || in_array($outlangs->defaultlang, $listoflanguagesbefore)) {
7191 $cursymbolbefore .= $outlangs->getCurrencySymbol($currency_code);
7192 } else {
7193 $tmpcur = $outlangs->getCurrencySymbol($currency_code);
7194 $cursymbolafter .= ($tmpcur == $currency_code ? ' '.$tmpcur : $tmpcur);
7195 }
7196 }
7197 $output = $cursymbolbefore.$output.$end.($cursymbolafter ? ' ' : '').$cursymbolafter;
7198 if ($form) {
7199 $output = preg_replace('/\s/', '&nbsp;', $output);
7200 $output = preg_replace('/\'/', '&#039;', $output);
7201 }
7202
7203 return $output;
7204}
7205
7230function price2num($amount, $rounding = '', $option = 0)
7231{
7232 global $langs, $conf;
7233
7234 // Clean parameters
7235 if (is_null($amount)) {
7236 $amount = '';
7237 }
7238
7239 // Round PHP function does not allow number like '1,234.56' nor '1.234,56' nor '1 234,56'
7240 // Numbers must be '1234.56'
7241 // Decimal delimiter for PHP and database SQL requests must be '.'
7242 $dec = ',';
7243 $thousand = ' ';
7244 if (is_null($langs)) { // $langs is not defined, we use english values.
7245 $dec = '.';
7246 $thousand = ',';
7247 } else {
7248 if ($langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
7249 $dec = $langs->transnoentitiesnoconv("SeparatorDecimal");
7250 }
7251 if ($langs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
7252 $thousand = $langs->transnoentitiesnoconv("SeparatorThousand");
7253 }
7254 }
7255 if ($thousand == 'None') {
7256 $thousand = '';
7257 } elseif ($thousand == 'Space') {
7258 $thousand = ' ';
7259 }
7260 //print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
7261
7262 // Convert value to universal number format (no thousand separator, '.' as decimal separator)
7263 if ($option != 1) { // If not a PHP number or unknown, we change or clean format
7264 //print "\n".'PP'.$amount.' - '.$dec.' - '.$thousand.' - '.intval($amount).'<br>';
7265 if (!is_numeric($amount)) {
7266 $amount = preg_replace('/[a-zA-Z\/\\\*\‍(\‍)<>\_]/', '', $amount);
7267 }
7268
7269 if ($option == 2 && $thousand == '.' && preg_match('/\.(\d\d\d)$/', (string) $amount)) { // It means the . is used as a thousand separator and string come from input data, so 1.123 is 1123
7270 $amount = str_replace($thousand, '', $amount);
7271 }
7272
7273 // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
7274 // to format defined by LC_NUMERIC after a calculation and we want source format to be like defined by Dolibarr setup.
7275 // So if number was already a good number, it is converted into local Dolibarr setup.
7276 if (is_numeric($amount)) {
7277 // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
7278 $temps = sprintf("%10.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
7279 $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
7280 $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
7281 $amount = number_format($amount, $nbofdec, $dec, $thousand);
7282 }
7283 //print "QQ".$amount."<br>\n";
7284
7285 // Now make replaceents (the main goal of function)
7286
7287 if ($thousand != ',' && $thousand != '.') {
7288 // Accept the two types of decimal points french users (i.e., using ' ' for thousands)
7289
7290 // REGEX: Find the integral and decimal parts.
7291 //
7292 // We require that the decimal point only appears once in $amount.
7293 // The regex `/^(?<int>[^,]*,|[^.]*\.)(?<dec>[^.,]*)$/u` can be broken down as follows:
7294 // - `(?<int>[^,]*,|[^.]*\.)` is any accepted sequence up to the last potential decimal point '.' or ',' and named `int`.
7295 // It covers two cases:
7296 // - `[^,]*,`: Any sequence of characters that is not ',' with ',' accepted as the decimal point (from start of string because of earlier `^`);
7297 // - `[^.]*\.`: Any sequence of characters that is not a '.' with '.' accepted as the decimal point (from start of string.
7298 // - `(?<dec>[^.,]*)`: The sequence after the character accepted as the decimal point, not including it.
7299 $matches = array();
7300 if (preg_match('/^(?<int>[^,]*,|[^.]*\.)(?<dec>[^.,]*)$/u', $amount, $matches)) {
7301 $intPart = $matches['int'];
7302 $decPart = $matches['dec'];
7303
7304 // Remove all commas and dots from intPart
7305 $intPart = str_replace(['.', ','], '', $intPart);
7306
7307 // Combine intPart and decPart with a dot
7308 $amount = $intPart . $dec . $decPart;
7309 }
7310 }
7311
7312 $amount = str_replace(' ', '', $amount); // To avoid spaces
7313 $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
7314 $amount = str_replace($dec, '.', $amount);
7315
7316 $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
7317 }
7318 //print ' XX'.$amount.' '.$rounding;
7319
7320 // Now, $amount is a real PHP float number. We make a rounding if required.
7321 if ($rounding) {
7322 $nbofdectoround = '';
7323 if ($rounding == 'MU') {
7324 $nbofdectoround = getDolGlobalInt('MAIN_MAX_DECIMALS_UNIT'); // usually 5
7325 } elseif ($rounding == 'MT') {
7326 $nbofdectoround = getDolGlobalInt('MAIN_MAX_DECIMALS_TOT'); // usually 2 or 3
7327 } elseif ($rounding == 'MS') {
7328 $nbofdectoround = isset($conf->global->MAIN_MAX_DECIMALS_STOCK) ? getDolGlobalInt('MAIN_MAX_DECIMALS_STOCK') : 5;
7329 } elseif ($rounding == 'CU') {
7330 $nbofdectoround = getDolGlobalInt('MAIN_MAX_DECIMALS_CURRENCY_UNIT', getDolGlobalInt('MAIN_MAX_DECIMALS_UNIT')); // TODO Use param of currency
7331 } elseif ($rounding == 'CT') {
7332 $nbofdectoround = getDolGlobalInt('MAIN_MAX_DECIMALS_CURRENCY_TOT', getDolGlobalInt('MAIN_MAX_DECIMALS_TOT')); // TODO Use param of currency
7333 } elseif (is_numeric($rounding)) {
7334 $nbofdectoround = (int) $rounding;
7335 }
7336
7337 //print " RR".$amount.' - '.$nbofdectoround.'<br>';
7338 if (dol_strlen($nbofdectoround)) {
7339 $amount = round(is_string($amount) ? (float) $amount : $amount, $nbofdectoround); // $nbofdectoround can be 0.
7340 } else {
7341 return 'ErrorBadParameterProvidedToFunction';
7342 }
7343 //print ' SS'.$amount.' - '.$nbofdec.' - '.$dec.' - '.$thousand.' - '.$nbofdectoround.'<br>';
7344
7345 // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
7346 // to format defined by LC_NUMERIC after a calculation and we want source format to be defined by Dolibarr setup.
7347 if (is_numeric($amount)) {
7348 // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
7349 $temps = sprintf("%10.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
7350 $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
7351 $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
7352 $amount = number_format($amount, min($nbofdec, $nbofdectoround), $dec, $thousand); // Convert amount to format with dolibarr dec and thousand
7353 }
7354 //print "TT".$amount.'<br>';
7355
7356 // Always make replace because each math function (like round) replace
7357 // with local values and we want a number that has a SQL string format x.y
7358 if ($thousand != ',' && $thousand != '.') {
7359 $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
7360 }
7361
7362 $amount = str_replace(' ', '', $amount); // To avoid spaces
7363 $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
7364 $amount = str_replace($dec, '.', $amount);
7365
7366 $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
7367 }
7368
7369 return $amount;
7370}
7371
7384function showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round = -1, $forceunitoutput = 'no', $use_short_label = 0)
7385{
7386 require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
7387
7388 if (($forceunitoutput == 'no' && $dimension < 1 / 10000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -6)) {
7389 $dimension *= 1000000;
7390 $unit -= 6;
7391 } elseif (($forceunitoutput == 'no' && $dimension < 1 / 10 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -3)) {
7392 $dimension *= 1000;
7393 $unit -= 3;
7394 } elseif (($forceunitoutput == 'no' && $dimension > 100000000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 6)) {
7395 $dimension /= 1000000;
7396 $unit += 6;
7397 } elseif (($forceunitoutput == 'no' && $dimension > 100000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 3)) {
7398 $dimension /= 1000;
7399 $unit += 3;
7400 }
7401 // Special case when we want output unit into pound or ounce
7402 /* TODO
7403 if ($unit < 90 && $type == 'weight' && is_numeric($forceunitoutput) && (($forceunitoutput == 98) || ($forceunitoutput == 99))
7404 {
7405 $dimension = // convert dimension from standard unit into ounce or pound
7406 $unit = $forceunitoutput;
7407 }
7408 if ($unit > 90 && $type == 'weight' && is_numeric($forceunitoutput) && $forceunitoutput < 90)
7409 {
7410 $dimension = // convert dimension from standard unit into ounce or pound
7411 $unit = $forceunitoutput;
7412 }*/
7413
7414 $ret = price($dimension, 0, $outputlangs, 0, 0, $round);
7415 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
7416 $ret .= ' '.measuringUnitString(0, $type, $unit, $use_short_label, $outputlangs);
7417
7418 return $ret;
7419}
7420
7421
7434function get_localtax($vatrate, $local, $thirdparty_buyer = null, $thirdparty_seller = null, $vatnpr = 0)
7435{
7436 global $db, $conf, $mysoc;
7437
7438 if (empty($thirdparty_seller) || !is_object($thirdparty_seller)) {
7439 $thirdparty_seller = $mysoc;
7440 }
7441
7442 dol_syslog("get_localtax tva=".$vatrate." local=".$local." thirdparty_buyer id=".(is_object($thirdparty_buyer) ? $thirdparty_buyer->id : '')."/country_code=".(is_object($thirdparty_buyer) ? $thirdparty_buyer->country_code : '')." thirdparty_seller id=".$thirdparty_seller->id."/country_code=".$thirdparty_seller->country_code." thirdparty_seller localtax1_assuj=".$thirdparty_seller->localtax1_assuj." thirdparty_seller localtax2_assuj=".$thirdparty_seller->localtax2_assuj);
7443
7444 $vatratecleaned = $vatrate;
7445 $reg = array();
7446 if (preg_match('/^(.*)\s*\‍((.*)\‍)$/', (string) $vatrate, $reg)) { // If vat is "xx (yy)"
7447 $vatratecleaned = trim($reg[1]);
7448 $vatratecode = $reg[2];
7449 }
7450
7451 /*if ($thirdparty_buyer->country_code != $thirdparty_seller->country_code)
7452 {
7453 return 0;
7454 }*/
7455
7456 // Some test to guess with no need to make database access
7457 if ($mysoc->country_code == 'ES') { // For spain localtaxes 1 and 2, tax is qualified if buyer use local tax
7458 if ($local == 1) {
7459 if (!$mysoc->localtax1_assuj || (string) $vatratecleaned == "0") {
7460 return 0;
7461 }
7462 if ($thirdparty_seller->id == $mysoc->id) {
7463 if (!$thirdparty_buyer->localtax1_assuj) {
7464 return 0;
7465 }
7466 } else {
7467 if (!$thirdparty_seller->localtax1_assuj) {
7468 return 0;
7469 }
7470 }
7471 }
7472
7473 if ($local == 2) {
7474 //if (! $mysoc->localtax2_assuj || (string) $vatratecleaned == "0") return 0;
7475 if (!$mysoc->localtax2_assuj) {
7476 return 0; // If main vat is 0, IRPF may be different than 0.
7477 }
7478 if ($thirdparty_seller->id == $mysoc->id) {
7479 if (!$thirdparty_buyer->localtax2_assuj) {
7480 return 0;
7481 }
7482 } else {
7483 if (!$thirdparty_seller->localtax2_assuj) {
7484 return 0;
7485 }
7486 }
7487 }
7488 } else {
7489 if ($local == 1 && !$thirdparty_seller->localtax1_assuj) {
7490 return 0;
7491 }
7492 if ($local == 2 && !$thirdparty_seller->localtax2_assuj) {
7493 return 0;
7494 }
7495 }
7496
7497 // For some country MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY is forced to on.
7498 if (in_array($mysoc->country_code, array('ES'))) {
7499 $conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY = 1;
7500 }
7501
7502 // Search local taxes
7503 if (getDolGlobalString('MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY')) {
7504 if ($local == 1) {
7505 if ($thirdparty_seller != $mysoc) {
7506 if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
7507 return $thirdparty_seller->localtax1_value;
7508 }
7509 } else { // i am the seller
7510 if (!isOnlyOneLocalTax($local)) { // TODO If seller is me, why not always returning this, even if there is only one locatax vat.
7511 return getDolGlobalString('MAIN_INFO_VALUE_LOCALTAX1');
7512 }
7513 }
7514 }
7515 if ($local == 2) {
7516 if ($thirdparty_seller != $mysoc) {
7517 if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
7518 // TODO We should also return value defined on thirdparty only if defined
7519 return $thirdparty_seller->localtax2_value;
7520 }
7521 } else { // i am the seller
7522 if (in_array($mysoc->country_code, array('ES'))) {
7523 return $thirdparty_buyer->localtax2_value;
7524 } else {
7525 return getDolGlobalString('MAIN_INFO_VALUE_LOCALTAX2');
7526 }
7527 }
7528 }
7529 }
7530
7531 // By default, search value of local tax on line of common tax
7532 $sql = "SELECT t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
7533 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
7534 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($thirdparty_seller->country_code)."'";
7535 $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
7536 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
7537 if (!empty($vatratecode)) {
7538 $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; // If we have the code, we use it in priority
7539 } else {
7540 $sql .= " AND t.recuperableonly = '".$db->escape((string) $vatnpr)."'";
7541 }
7542
7543 $resql = $db->query($sql);
7544
7545 if ($resql) {
7546 $obj = $db->fetch_object($resql);
7547 if ($obj) {
7548 if ($local == 1) {
7549 return $obj->localtax1;
7550 } elseif ($local == 2) {
7551 return $obj->localtax2;
7552 }
7553 }
7554 }
7555
7556 return 0;
7557}
7558
7559
7568function isOnlyOneLocalTax($local)
7569{
7570 $tax = get_localtax_by_third($local);
7571
7572 $valors = explode(":", $tax);
7573
7574 if (count($valors) > 1) {
7575 return false;
7576 } else {
7577 return true;
7578 }
7579}
7580
7587function get_localtax_by_third($local)
7588{
7589 global $db, $mysoc;
7590
7591 $sql = " SELECT t.localtax".$local." as localtax";
7592 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t INNER JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = t.fk_pays";
7593 $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND t.active = 1 AND t.entity IN (".getEntity('c_tva').") AND t.taux = (";
7594 $sql .= "SELECT MAX(tt.taux) FROM ".MAIN_DB_PREFIX."c_tva as tt INNER JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = tt.fk_pays";
7595 $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND t.entity IN (".getEntity('c_tva').") AND tt.active = 1)";
7596 $sql .= " AND t.localtax".$local."_type <> '0'";
7597 $sql .= " ORDER BY t.rowid DESC";
7598
7599 $resql = $db->query($sql);
7600 if ($resql) {
7601 $obj = $db->fetch_object($resql);
7602 if ($obj) {
7603 return $obj->localtax;
7604 } else {
7605 return '0';
7606 }
7607 }
7608
7609 return 'Error';
7610}
7611
7612
7624function getTaxesFromId($vatrate, $buyer = null, $seller = null, $firstparamisid = 1)
7625{
7626 global $db;
7627
7628 dol_syslog("getTaxesFromId vat id or rate = ".$vatrate);
7629
7630 // Search local taxes
7631 $sql = "SELECT t.rowid, t.code, t.taux as rate, t.recuperableonly as npr, t.accountancy_code_sell, t.accountancy_code_buy,";
7632 $sql .= " t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type";
7633 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
7634 if ($firstparamisid) {
7635 $sql .= " WHERE t.rowid = ".(int) $vatrate;
7636 } else {
7637 $vatratecleaned = $vatrate;
7638 $vatratecode = '';
7639 $reg = array();
7640 if (preg_match('/^(.*)\s*\‍((.*)\‍)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
7641 $vatratecleaned = $reg[1];
7642 $vatratecode = $reg[2];
7643 }
7644
7645 $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
7646 /*if ($mysoc->country_code == 'ES') $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($buyer->country_code)."'"; // vat in spain use the buyer country ??
7647 else $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";*/
7648 $sql .= " WHERE t.fk_pays = c.rowid";
7649 if (getDolGlobalString('SERVICE_ARE_ECOMMERCE_200238EC')) {
7650 $sql .= " AND c.code = '".$db->escape($buyer->country_code)."'";
7651 } else {
7652 $sql .= " AND c.code = '".$db->escape($seller->country_code)."'";
7653 }
7654 $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
7655 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
7656 if ($vatratecode) {
7657 $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
7658 }
7659 }
7660
7661 $resql = $db->query($sql);
7662 if ($resql) {
7663 $obj = $db->fetch_object($resql);
7664 if ($obj) {
7665 return array(
7666 'rowid' => $obj->rowid,
7667 'code' => $obj->code,
7668 'rate' => $obj->rate,
7669 'localtax1' => $obj->localtax1,
7670 'localtax1_type' => $obj->localtax1_type,
7671 'localtax2' => $obj->localtax2,
7672 'localtax2_type' => $obj->localtax2_type,
7673 'npr' => $obj->npr,
7674 'accountancy_code_sell' => $obj->accountancy_code_sell,
7675 'accountancy_code_buy' => $obj->accountancy_code_buy
7676 );
7677 } else {
7678 return array();
7679 }
7680 } else {
7681 dol_print_error($db);
7682 }
7683
7684 return array();
7685}
7686
7703function getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid = 0)
7704{
7705 global $db, $mysoc;
7706
7707 dol_syslog("getLocalTaxesFromRate vatrate=".$vatrate." local=".$local);
7708
7709 // Search local taxes
7710 $sql = "SELECT t.taux as rate, t.code, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.accountancy_code_sell, t.accountancy_code_buy";
7711 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
7712 if ($firstparamisid) {
7713 $sql .= " WHERE t.rowid = ".(int) $vatrate;
7714 } else {
7715 $vatratecleaned = $vatrate;
7716 $vatratecode = '';
7717 $reg = array();
7718 if (preg_match('/^(.*)\s*\‍((.*)\‍)$/', $vatrate, $reg)) { // If vat is "x.x (yy)"
7719 $vatratecleaned = $reg[1];
7720 $vatratecode = $reg[2];
7721 }
7722
7723 $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
7724 if (!empty($mysoc) && $mysoc->country_code == 'ES') {
7725 $countrycodetouse = ((empty($buyer) || empty($buyer->country_code)) ? $mysoc->country_code : $buyer->country_code);
7726 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($countrycodetouse)."'"; // local tax in spain use the buyer country ??
7727 } else {
7728 $countrycodetouse = ((empty($seller) || empty($seller->country_code)) ? $mysoc->country_code : $seller->country_code);
7729 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($countrycodetouse)."'";
7730 }
7731 $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
7732 if ($vatratecode) {
7733 $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
7734 }
7735 }
7736
7737 $resql = $db->query($sql);
7738 if ($resql) {
7739 $obj = $db->fetch_object($resql);
7740
7741 if ($obj) {
7742 $vateratestring = $obj->rate.($obj->code ? ' ('.$obj->code.')' : '');
7743
7744 if ($local == 1) {
7745 return array($obj->localtax1_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
7746 } elseif ($local == 2) {
7747 return array($obj->localtax2_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
7748 } else {
7749 return array($obj->localtax1_type, get_localtax($vateratestring, 1, $buyer, $seller), $obj->localtax2_type, get_localtax($vateratestring, 2, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
7750 }
7751 }
7752 }
7753
7754 return array();
7755}
7756
7767function get_product_vat_for_country($idprod, $thirdpartytouse, $idprodfournprice = 0)
7768{
7769 global $db, $mysoc;
7770
7771 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
7772
7773 $ret = 0;
7774 $found = 0;
7775
7776 if ($idprod > 0) {
7777 // Load product
7778 $product = new Product($db);
7779 $product->fetch($idprod);
7780
7781 if (($mysoc->country_code == $thirdpartytouse->country_code)
7782 || (in_array($mysoc->country_code, array('FR', 'MC')) && in_array($thirdpartytouse->country_code, array('FR', 'MC')))
7783 || (in_array($mysoc->country_code, array('MQ', 'GP')) && in_array($thirdpartytouse->country_code, array('MQ', 'GP')))
7784 ) {
7785 // If country of thirdparty to consider is ours
7786 if ($idprodfournprice > 0) { // We want vat for product for a "supplier" object
7787 $result = $product->get_buyprice($idprodfournprice, 0, 0, '');
7788 if ($result > 0) {
7789 $ret = $product->vatrate_supplier;
7790 if ($product->default_vat_code_supplier) {
7791 $ret .= ' ('.$product->default_vat_code_supplier.')';
7792 }
7793 $found = 1;
7794 }
7795 }
7796 if (!$found) {
7797 $ret = $product->tva_tx; // Default sales vat of product
7798 if ($product->default_vat_code) {
7799 $ret .= ' ('.$product->default_vat_code.')';
7800 }
7801 $found = 1;
7802 }
7803 } else {
7804 // TODO Read default product vat according to product and an other countrycode.
7805 // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
7806 }
7807 }
7808
7809 if (!$found) {
7810 if (!getDolGlobalString('MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS')) {
7811 // If vat of product for the country not found or not defined, we return the first rate found (sorting on use_default, then on higher vat of country).
7812 $sql = "SELECT t.taux as vat_rate, t.code as default_vat_code";
7813 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
7814 $sql .= " WHERE t.active = 1 AND t.fk_pays = c.rowid AND c.code = '".$db->escape($thirdpartytouse->country_code)."'";
7815 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
7816 $sql .= " ORDER BY t.use_default DESC, t.taux DESC, t.code ASC, t.recuperableonly ASC";
7817 $sql .= $db->plimit(1);
7818
7819 $resql = $db->query($sql);
7820 if ($resql) {
7821 $obj = $db->fetch_object($resql);
7822 if ($obj) {
7823 $ret = $obj->vat_rate;
7824 if ($obj->default_vat_code) {
7825 $ret .= ' ('.$obj->default_vat_code.')';
7826 }
7827 }
7828 $db->free($resql);
7829 } else {
7830 dol_print_error($db);
7831 }
7832 } else {
7833 // Forced value if autodetect fails. MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS can be
7834 // '1.23'
7835 // or '1.23 (CODE)'
7836 $defaulttx = '';
7837 if (getDolGlobalString('MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS') != 'none') {
7838 $defaulttx = getDolGlobalString('MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS');
7839 }
7840 /*if (preg_match('/\‍((.*)\‍)/', $defaulttx, $reg)) {
7841 $defaultcode = $reg[1];
7842 $defaulttx = preg_replace('/\s*\‍(.*\‍)/', '', $defaulttx);
7843 }*/
7844
7845 $ret = $defaulttx;
7846 }
7847 }
7848
7849 dol_syslog("get_product_vat_for_country: ret=".$ret);
7850 return $ret;
7851}
7852
7862function get_product_localtax_for_country($idprod, $local, $thirdpartytouse)
7863{
7864 global $db, $mysoc;
7865
7866 if (!class_exists('Product')) {
7867 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
7868 }
7869
7870 $ret = 0;
7871 $found = 0;
7872
7873 if ($idprod > 0) {
7874 // Load product
7875 $product = new Product($db);
7876 $result = $product->fetch($idprod);
7877
7878 if ($mysoc->country_code == $thirdpartytouse->country_code) { // If selling country is ours
7879 /* Not defined yet, so we don't use this
7880 if ($local==1) $ret=$product->localtax1_tx;
7881 elseif ($local==2) $ret=$product->localtax2_tx;
7882 $found=1;
7883 */
7884 } else {
7885 // TODO Read default product vat according to product and another countrycode.
7886 // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
7887 }
7888 }
7889
7890 if (!$found) {
7891 // If vat of product for the country not found or not defined, we return higher vat of country.
7892 $sql = "SELECT taux as vat_rate, localtax1, localtax2";
7893 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
7894 $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$db->escape($thirdpartytouse->country_code)."'";
7895 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
7896 $sql .= " ORDER BY t.taux DESC, t.recuperableonly ASC";
7897 $sql .= $db->plimit(1);
7898
7899 $resql = $db->query($sql);
7900 if ($resql) {
7901 $obj = $db->fetch_object($resql);
7902 if ($obj) {
7903 if ($local == 1) {
7904 $ret = $obj->localtax1;
7905 } elseif ($local == 2) {
7906 $ret = $obj->localtax2;
7907 }
7908 }
7909 } else {
7910 dol_print_error($db);
7911 }
7912 }
7913
7914 dol_syslog("get_product_localtax_for_country: ret=".$ret);
7915 return $ret;
7916}
7917
7935function get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
7936{
7937 global $mysoc, $db;
7938
7939 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
7940
7941 // Note: possible values for tva_assuj are 0/1 or franchise/reel
7942 $seller_use_vat = ((is_numeric($thirdparty_seller->tva_assuj) && !$thirdparty_seller->tva_assuj) || (!is_numeric($thirdparty_seller->tva_assuj) && $thirdparty_seller->tva_assuj == 'franchise')) ? 0 : 1;
7943
7944 if (empty($thirdparty_seller->country_code)) {
7945 $thirdparty_seller->country_code = $mysoc->country_code;
7946 }
7947 $seller_country_code = $thirdparty_seller->country_code;
7948 $seller_in_cee = isInEEC($thirdparty_seller);
7949
7950 if (empty($thirdparty_buyer->country_code)) {
7951 $thirdparty_buyer->country_code = $mysoc->country_code;
7952 }
7953 $buyer_country_code = $thirdparty_buyer->country_code;
7954 $buyer_in_cee = isInEEC($thirdparty_buyer);
7955
7956 dol_syslog("get_default_tva: seller use vat=".$seller_use_vat.", seller country=".$seller_country_code.", seller in cee=".((string) (int) $seller_in_cee).", buyer vat number=".$thirdparty_buyer->tva_intra." buyer country=".$buyer_country_code.", buyer state=".$thirdparty_buyer->state_id." buyer in cee=".((string) (int) $buyer_in_cee).", idprod=".$idprod.", idprodfournprice=".$idprodfournprice.", SERVICE_ARE_ECOMMERCE_200238EC=".getDolGlobalString('SERVICE_ARE_ECOMMERCE_200238EC'));
7957
7958 // If services are eServices according to EU Council Directive 2002/38/EC (http://ec.europa.eu/taxation_customs/taxation/vat/traders/e-commerce/article_1610_en.htm)
7959 // we use the buyer VAT.
7960 if (getDolGlobalString('SERVICE_ARE_ECOMMERCE_200238EC')) {
7961 if ($seller_in_cee && $buyer_in_cee) {
7962 $isacompany = $thirdparty_buyer->isACompany();
7963 if ($isacompany && getDolGlobalString('MAIN_USE_VAT_COMPANIES_IN_EEC_WITH_INVALID_VAT_ID_ARE_INDIVIDUAL')) {
7964 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
7965 if (!isValidVATID($thirdparty_buyer)) {
7966 $isacompany = 0;
7967 }
7968 }
7969
7970 if (!$isacompany) {
7971 //print 'VATRULE 0';
7972 return get_product_vat_for_country($idprod, $thirdparty_buyer, $idprodfournprice);
7973 }
7974 }
7975 }
7976
7977 // If seller does not use VAT, default VAT is 0. End of rule.
7978 if (!$seller_use_vat) {
7979 //print 'VATRULE 1';
7980 return 0;
7981 }
7982
7983 // 'VATRULE 2' - Force VAT if a buyer department is defined on vat rates dictionary
7984 if (!empty($thirdparty_buyer->state_id)) {
7985 $sql = "SELECT d.rowid, t.taux as vat_default_rate, t.code as vat_default_code ";
7986 $sql .= " FROM ".$db->prefix()."c_tva as t";
7987 $sql .= " INNER JOIN ".$db->prefix()."c_departements as d ON t.fk_department_buyer = d.rowid";
7988 $sql .= " WHERE d.rowid = ".((int) $thirdparty_buyer->state_id);
7989 $sql .= " AND t.active > 0";
7990 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
7991 $sql .= " ORDER BY t.use_default DESC, t.taux DESC, t.code ASC, t.recuperableonly ASC";
7992
7993 $res = $db->query($sql);
7994 if ($res) {
7995 if ($db->num_rows($res)) {
7996 $obj = $db->fetch_object($res);
7997 return $obj->vat_default_rate.' ('.$obj->vat_default_code.')';
7998 }
7999 $db->free($res);
8000 }
8001 }
8002
8003 // If the (seller country = buyer country) then the default VAT = VAT of the product sold. End of rule.
8004 if (($seller_country_code == $buyer_country_code)
8005 || (in_array($seller_country_code, array('FR', 'MC')) && in_array($buyer_country_code, array('FR', 'MC')))
8006 || (in_array($seller_country_code, array('MQ', 'GP')) && in_array($buyer_country_code, array('MQ', 'GP')))
8007 ) { // Warning ->country_code not always defined
8008 //print 'VATRULE 3';
8009 $tmpvat = get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
8010
8011 if ($seller_country_code == 'IN' && getDolGlobalString('MAIN_SALETAX_AUTOSWITCH_I_CS_FOR_INDIA')) {
8012 // Special case for india.
8013 //print 'VATRULE 3b';
8014 $reg = array();
8015 if (preg_match('/C+S-(\d+)/', $tmpvat, $reg) && $thirdparty_seller->state_id != $thirdparty_buyer->state_id) {
8016 // we must revert the C+S into I
8017 $tmpvat = str_replace("C+S", "I", $tmpvat);
8018 } elseif (preg_match('/I-(\d+)/', $tmpvat, $reg) && $thirdparty_seller->state_id == $thirdparty_buyer->state_id) {
8019 // we must revert the I into C+S
8020 $tmpvat = str_replace("I", "C+S", $tmpvat);
8021 }
8022 }
8023
8024 return $tmpvat;
8025 }
8026
8027 // If (seller and buyer in the European Community) and (property sold = new means of transport such as car, boat, plane) then VAT by default = 0 (VAT must be paid by the buyer to the tax center of his country and not to the seller). End of rule.
8028 // 'VATRULE 4' - Not supported
8029
8030 // If (seller and buyer in the European Community) and (buyer = individual) then VAT by default = VAT of the product sold. End of rule
8031 // If (seller and buyer in European Community) and (buyer = company) then VAT by default=0. End of rule
8032 if (($seller_in_cee && $buyer_in_cee)) {
8033 $isacompany = $thirdparty_buyer->isACompany();
8034 if ($isacompany && getDolGlobalString('MAIN_USE_VAT_COMPANIES_IN_EEC_WITH_INVALID_VAT_ID_ARE_INDIVIDUAL')) {
8035 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
8036 if (!isValidVATID($thirdparty_buyer)) {
8037 $isacompany = 0;
8038 }
8039 }
8040
8041 if (!$isacompany) {
8042 //print 'VATRULE 5';
8043 return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
8044 } else {
8045 //print 'VATRULE 6';
8046 return 0;
8047 }
8048 }
8049
8050 // If (seller in the European Community and buyer outside the European Community and private buyer) then VAT by default = VAT of the product sold. End of rule
8051 // I don't see any use case that need this rule.
8052 if (getDolGlobalString('MAIN_USE_VAT_OF_PRODUCT_FOR_INDIVIDUAL_CUSTOMER_OUT_OF_EEC') && empty($buyer_in_cee)) {
8053 $isacompany = $thirdparty_buyer->isACompany();
8054 if (!$isacompany) {
8055 return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
8056 //print 'VATRULE extra';
8057 }
8058 }
8059
8060 // Otherwise the VAT proposed by default=0. End of rule.
8061 // Rem: This means that at least one of the 2 is outside the European Community and the country differs
8062 //print 'VATRULE 7';
8063 return 0;
8064}
8065
8066
8077function get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
8078{
8079 global $db;
8080
8081 if ($idprodfournprice > 0) {
8082 if (!class_exists('ProductFournisseur')) {
8083 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
8084 }
8085 $prodprice = new ProductFournisseur($db);
8086 $prodprice->fetch_product_fournisseur_price($idprodfournprice);
8087 return $prodprice->fourn_tva_npr;
8088 } elseif ($idprod > 0) {
8089 if (!class_exists('Product')) {
8090 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
8091 }
8092 $prod = new Product($db);
8093 $prod->fetch($idprod);
8094 return $prod->tva_npr;
8095 }
8096
8097 return 0;
8098}
8099
8113function get_default_localtax($thirdparty_seller, $thirdparty_buyer, $local, $idprod = 0)
8114{
8115 global $mysoc;
8116
8117 if (!is_object($thirdparty_seller)) {
8118 return -1;
8119 }
8120 if (!is_object($thirdparty_buyer)) {
8121 return -1;
8122 }
8123
8124 if (empty($thirdparty_seller->country_code)) {
8125 $thirdparty_seller->country_code = $mysoc->country_code;
8126 }
8127 $seller_country_code = $thirdparty_seller->country_code;
8128 //$seller_in_cee = isInEEC($thirdparty_seller);
8129
8130 if (empty($thirdparty_buyer->country_code)) {
8131 $thirdparty_buyer->country_code = $mysoc->country_code;
8132 }
8133 $buyer_country_code = $thirdparty_buyer->country_code;
8134 //$buyer_in_cee = isInEEC($thirdparty_buyer);
8135
8136 if ($local == 1) { // Localtax 1
8137 if ($mysoc->country_code == 'ES') {
8138 if (is_numeric($thirdparty_buyer->localtax1_assuj) && !$thirdparty_buyer->localtax1_assuj) {
8139 return 0;
8140 }
8141 } else {
8142 // Si vendeur non assujeti a Localtax1, localtax1 par default=0
8143 if (is_numeric($thirdparty_seller->localtax1_assuj) && !$thirdparty_seller->localtax1_assuj) {
8144 return 0;
8145 }
8146 if (!is_numeric($thirdparty_seller->localtax1_assuj) && $thirdparty_seller->localtax1_assuj == 'localtax1off') {
8147 return 0;
8148 }
8149 }
8150 } elseif ($local == 2) { //I Localtax 2
8151 // Si vendeur non assujeti a Localtax2, localtax2 par default=0
8152 if (is_numeric($thirdparty_seller->localtax2_assuj) && !$thirdparty_seller->localtax2_assuj) {
8153 return 0;
8154 }
8155 if (!is_numeric($thirdparty_seller->localtax2_assuj) && $thirdparty_seller->localtax2_assuj == 'localtax2off') {
8156 return 0;
8157 }
8158 }
8159
8160 if ($seller_country_code == $buyer_country_code) {
8161 return get_product_localtax_for_country($idprod, $local, $thirdparty_seller);
8162 }
8163
8164 return 0;
8165}
8166
8175function yn($yesno, $format = 1, $color = 0)
8176{
8177 global $langs;
8178
8179 $result = 'unknown';
8180 $classname = '';
8181 if ($yesno == 1 || (isset($yesno) && (strtolower($yesno) == 'yes' || strtolower($yesno) == 'true'))) { // To set to 'no' before the test because of the '== 0'
8182 $result = $langs->trans('yes');
8183 if ($format == 1 || $format == 3) {
8184 $result = $langs->trans("Yes");
8185 }
8186 if ($format == 2) {
8187 $result = '<input type="checkbox" value="1" checked disabled>';
8188 }
8189 if ($format == 3) {
8190 $result = '<input type="checkbox" value="1" checked disabled> '.$result;
8191 }
8192 if ($format == 4 || !is_numeric($format)) {
8193 $result = img_picto(is_numeric($format) ? '' : $format, 'check');
8194 }
8195
8196 $classname = 'ok';
8197 } elseif ($yesno == 0 || strtolower($yesno) == 'no' || strtolower($yesno) == 'false') {
8198 $result = $langs->trans("no");
8199 if ($format == 1 || $format == 3) {
8200 $result = $langs->trans("No");
8201 }
8202 if ($format == 2) {
8203 $result = '<input type="checkbox" value="0" disabled>';
8204 }
8205 if ($format == 3) {
8206 $result = '<input type="checkbox" value="0" disabled> '.$result;
8207 }
8208 if ($format == 4 || !is_numeric($format)) {
8209 $result = img_picto(is_numeric($format) ? '' : $format, 'uncheck');
8210 }
8211
8212 if ($color == 2) {
8213 $classname = 'ok';
8214 } else {
8215 $classname = 'error';
8216 }
8217 }
8218 if ($color) {
8219 return '<span class="'.$classname.'">'.$result.'</span>';
8220 }
8221 return $result;
8222}
8223
8242function get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart = '')
8243{
8244 if (empty($modulepart) && is_object($object)) {
8245 if (!empty($object->module)) {
8246 $modulepart = $object->module;
8247 } elseif (!empty($object->element)) {
8248 $modulepart = $object->element;
8249 }
8250 }
8251
8252 $path = '';
8253
8254 // Define $arrayforoldpath that is module path using a hierarchy on more than 1 level.
8255 $arrayforoldpath = array('cheque' => 2, 'category' => 2, 'holiday' => 2, 'supplier_invoice' => 2, 'invoice_supplier' => 2, 'mailing' => 2, 'supplier_payment' => 2);
8256 if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
8257 $arrayforoldpath['product'] = 2;
8258 }
8259
8260 if (empty($level) && array_key_exists($modulepart, $arrayforoldpath)) {
8261 $level = $arrayforoldpath[$modulepart];
8262 }
8263 if (!empty($level) && array_key_exists($modulepart, $arrayforoldpath)) {
8264 // This part should be removed once all code is using "get_exdir" to forge path, with parameter $object and $modulepart provided.
8265 if (empty($num) && is_object($object)) {
8266 $num = $object->id;
8267 }
8268 if (empty($alpha)) {
8269 $num = preg_replace('/([^0-9])/i', '', $num);
8270 } else {
8271 $num = preg_replace('/^.*\-/i', '', $num);
8272 }
8273 $num = substr("000".$num, -$level);
8274 if ($level == 1) {
8275 $path = substr($num, 0, 1);
8276 }
8277 if ($level == 2) {
8278 $path = substr($num, 1, 1).'/'.substr($num, 0, 1);
8279 }
8280 if ($level == 3) {
8281 $path = substr($num, 2, 1).'/'.substr($num, 1, 1).'/'.substr($num, 0, 1);
8282 }
8283 } else {
8284 // We will enhance here a common way of forging path for document storage.
8285 // In a future, we may distribute directories on several levels depending on setup and object.
8286 // Here, $object->id, $object->ref and $modulepart are required.
8287 if (in_array($modulepart, array('societe', 'thirdparty')) && $object instanceOf Societe) {
8288 // Special case for thirdparty, where the ref is a company name that is not unique so path on disk is using the ID instead of the ref
8289 $path = dol_sanitizeFileName((string) $object->id);
8290 } else {
8291 $path = dol_sanitizeFileName(empty($object->ref) ? (string) ((is_object($object) && property_exists($object, 'id')) ? $object->id : '') : $object->ref);
8292 }
8293 }
8294
8295 if (empty($withoutslash) && !empty($path)) {
8296 $path .= '/';
8297 }
8298
8299 return $path;
8300}
8301
8310function dol_mkdir($dir, $dataroot = '', $newmask = '')
8311{
8312 dol_syslog("functions.lib::dol_mkdir: dir=".$dir, LOG_INFO);
8313
8314 $dir = dol_sanitizePathName($dir, '_', 0);
8315
8316 $dir_osencoded = dol_osencode($dir);
8317 if (@is_dir($dir_osencoded)) {
8318 return 0;
8319 }
8320
8321 $nberr = 0;
8322 $nbcreated = 0;
8323
8324 $ccdir = '';
8325 if (!empty($dataroot)) {
8326 // Remove data root from loop
8327 $dir = str_replace($dataroot.'/', '', $dir);
8328 $ccdir = $dataroot.'/';
8329 }
8330
8331 $cdir = explode("/", $dir);
8332 $num = count($cdir);
8333 for ($i = 0; $i < $num; $i++) {
8334 if ($i > 0) {
8335 $ccdir .= '/'.$cdir[$i];
8336 } else {
8337 $ccdir .= $cdir[$i];
8338 }
8339 $regs = array();
8340 if (preg_match("/^.:$/", $ccdir, $regs)) {
8341 continue; // If the Windows path is incomplete, continue with next directory
8342 }
8343
8344 // Attention, is_dir() can fail event if the directory exists
8345 // (i.e. according the open_basedir configuration)
8346 if ($ccdir) {
8347 $ccdir_osencoded = dol_osencode($ccdir);
8348 if (!@is_dir($ccdir_osencoded)) {
8349 dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' is not found (does not exists or is outside open_basedir PHP setting).", LOG_DEBUG);
8350
8351 umask(0);
8352 $dirmaskdec = octdec((string) $newmask);
8353 if (empty($newmask)) {
8354 $dirmaskdec = octdec(getDolGlobalString('MAIN_UMASK', '0755'));
8355 }
8356 $dirmaskdec |= octdec('0111'); // Set x bit required for directories
8357 if (!@mkdir($ccdir_osencoded, $dirmaskdec)) {
8358 // If the is_dir has returned a false information, we arrive here
8359 dol_syslog("functions.lib::dol_mkdir: Fails to create directory '".$ccdir."' (no permission to write into parent or directory already exists).", LOG_WARNING);
8360 $nberr++;
8361 } else {
8362 dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' created", LOG_DEBUG);
8363 $nberr = 0; // At this point in the code, the previous failures can be ignored -> set $nberr to 0
8364 $nbcreated++;
8365 }
8366 } else {
8367 $nberr = 0; // At this point in the code, the previous failures can be ignored -> set $nberr to 0
8368 }
8369 }
8370 }
8371 return ($nberr ? -$nberr : $nbcreated);
8372}
8373
8374
8382function dolChmod($filepath, $newmask = '')
8383{
8384 if (!empty($newmask)) {
8385 @chmod($filepath, octdec($newmask));
8386 } elseif (getDolGlobalString('MAIN_UMASK')) {
8387 @chmod($filepath, octdec(getDolGlobalString('MAIN_UMASK')));
8388 }
8389}
8390
8391
8397function picto_required()
8398{
8399 return '<span class="fieldrequired">*</span>';
8400}
8401
8402
8419function dol_string_nohtmltag($stringtoclean, $removelinefeed = 1, $pagecodeto = 'UTF-8', $strip_tags = 0, $removedoublespaces = 1)
8420{
8421 if (is_null($stringtoclean)) {
8422 return '';
8423 }
8424
8425 if ($removelinefeed == 2) {
8426 $stringtoclean = preg_replace('/<br[^>]*>(\n|\r)+/ims', '<br>', $stringtoclean);
8427 }
8428 $temp = preg_replace('/<br[^>]*>/i', "\n", $stringtoclean);
8429
8430 // We remove entities BEFORE stripping (in case of an open separator char that is entity encoded and not the closing other, the strip will fails)
8431 $temp = dol_html_entity_decode($temp, ENT_COMPAT | ENT_HTML5, $pagecodeto);
8432
8433 $temp = str_replace('< ', '__ltspace__', $temp);
8434 $temp = str_replace('<:', '__lttwopoints__', $temp);
8435
8436 if ($strip_tags) {
8437 $temp = strip_tags($temp);
8438 } else {
8439 // Remove '<' into remaining, so remove non closing html tags like '<abc' or '<<abc'. Note: '<123abc' is not a html tag (can be kept), but '<abc123' is (must be removed).
8440 $pattern = "/<[^<>]+>/";
8441 // Example of $temp: <a href="/myurl" title="<u>A title</u>">0000-021</a>
8442 // pass 1 - $temp after pass 1: <a href="/myurl" title="A title">0000-021
8443 // pass 2 - $temp after pass 2: 0000-021
8444 $tempbis = $temp;
8445 do {
8446 $temp = $tempbis;
8447 $tempbis = str_replace('<>', '', $temp); // No reason to have this into a text, except if value is to try bypass the next html cleaning
8448 $tempbis = preg_replace($pattern, '', $tempbis);
8449 //$idowhile++; print $temp.'-'.$tempbis."\n"; if ($idowhile > 100) break;
8450 } while ($tempbis != $temp);
8451
8452 $temp = $tempbis;
8453
8454 // Remove '<' into remaining, so remove non closing html tags like '<abc' or '<<abc'. Note: '<123abc' is not a html tag (can be kept), but '<abc123' is (must be removed).
8455 $temp = preg_replace('/<+([a-z]+)/i', '\1', $temp);
8456 }
8457
8458 $temp = dol_html_entity_decode($temp, ENT_COMPAT, $pagecodeto);
8459
8460 // Remove also carriage returns
8461 if ($removelinefeed == 1) {
8462 $temp = str_replace(array("\r\n", "\r", "\n"), " ", $temp);
8463 }
8464
8465 // And double spaces
8466 if ($removedoublespaces) {
8467 while (strpos($temp, " ") !== false) {
8468 $temp = str_replace(" ", " ", $temp);
8469 }
8470 }
8471
8472 $temp = str_replace('__ltspace__', '< ', $temp);
8473 $temp = str_replace('__lttwopoints__', '<:', $temp);
8474
8475 return trim($temp);
8476}
8477
8497function dol_string_onlythesehtmltags($stringtoclean, $cleanalsosomestyles = 1, $removeclassattribute = 1, $cleanalsojavascript = 0, $allowiframe = 0, $allowed_tags = array(), $allowlink = 0, $allowscript = 0, $allowstyle = 0, $allowphp = 0)
8498{
8499 if (empty($allowed_tags)) {
8500 $allowed_tags = array(
8501 "html", "head", "meta", "body", "article", "a", "abbr", "b", "blockquote", "br", "cite", "div", "dl", "dd", "dt", "em", "font", "img", "ins", "hr", "i", "li",
8502 "ol", "p", "q", "s", "span", "strike", "strong", "title", "table", "tr", "th", "td", "u", "ul", "sup", "sub", "blockquote", "pre", "h1", "h2", "h3", "h4", "h5", "h6",
8503 "header", "footer", "nav", "section", "menu", "menuitem" // html5 tags
8504 );
8505 }
8506 $allowed_tags[] = "comment"; // this tags is added to manage comment <!--...--> that are replaced into <comment>...</comment>
8507 if ($allowiframe) {
8508 if (!in_array('iframe', $allowed_tags)) {
8509 $allowed_tags[] = "iframe";
8510 }
8511 }
8512 if ($allowlink) {
8513 if (!in_array('link', $allowed_tags)) {
8514 $allowed_tags[] = "link";
8515 }
8516 }
8517 if ($allowscript) {
8518 if (!in_array('script', $allowed_tags)) {
8519 $allowed_tags[] = "script";
8520 }
8521 }
8522 if ($allowstyle) {
8523 if (!in_array('style', $allowed_tags)) {
8524 $allowed_tags[] = "style";
8525 }
8526 }
8527
8528 $allowed_tags_string = implode("><", $allowed_tags);
8529 $allowed_tags_string = '<'.$allowed_tags_string.'>';
8530
8531 $stringtoclean = str_replace('<!DOCTYPE html>', '__!DOCTYPE_HTML__', $stringtoclean); // Replace DOCTYPE to avoid to have it removed by the strip_tags
8532
8533 $stringtoclean = dol_string_nounprintableascii($stringtoclean, 0);
8534
8535 //$stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
8536 $stringtoclean = preg_replace('/<!--([^>]*)-->/', '<comment>\1</comment>', $stringtoclean);
8537
8538 if ($allowphp) {
8539 $allowed_tags[] = "commentphp";
8540 $stringtoclean = preg_replace('/^<\?php([^"]+)\?>$/i', '<commentphp>\1__</commentphp>', $stringtoclean); // Note: <?php ... > is allowed only if on the same line
8541 $stringtoclean = preg_replace('/"<\?php([^"]+)\?>"/i', '"<commentphp>\1</commentphp>"', $stringtoclean); // Note: "<?php ... >" is allowed only if on the same line
8542 }
8543
8544 $stringtoclean = preg_replace('/&colon;/i', ':', $stringtoclean);
8545 $stringtoclean = preg_replace('/&#58;|&#0+58|&#x3A/i', '', $stringtoclean); // refused string ':' encoded (no reason to have a : encoded like this) to disable 'javascript:...'
8546
8547 // Remove all HTML tags
8548 $temp = strip_tags($stringtoclean, $allowed_tags_string); // Warning: This remove also undesired </>, so may changes string obfuscated with </> that pass the injection detection into a harmfull string
8549
8550 if ($cleanalsosomestyles) { // Clean for remaining html tags
8551 $temp = preg_replace('/position\s*:\s*(absolute|fixed)\s*!\s*important/i', '', $temp); // Note: If hacker try to introduce css comment into string to bypass this regex, the string must also be encoded by the dol_htmlentitiesbr during output so it become harmless
8552 }
8553 if ($removeclassattribute) { // Clean for remaining html tags
8554 $temp = preg_replace('/(<[^>]+)\s+class=((["\']).*?\\3|\\w*)/i', '\\1', $temp);
8555 }
8556
8557 // Remove 'javascript:' that we should not find into a text
8558 // Warning: This is not reliable to fight against obfuscated javascript, there is a lot of other solution to include js into a common html tag (only filtered by a GETPOST(.., powerfullfilter)).
8559 if ($cleanalsojavascript) {
8560 $temp = preg_replace('/j\s*a\s*v\s*a\s*s\s*c\s*r\s*i\s*p\s*t\s*:/i', '', $temp);
8561 }
8562
8563 $temp = str_replace('__!DOCTYPE_HTML__', '<!DOCTYPE html>', $temp); // Restore the DOCTYPE
8564
8565 if ($allowphp) {
8566 $temp = preg_replace('/<commentphp>(.*)<\/commentphp>/', '<?php\1?>', $temp); // Restore php code
8567 }
8568
8569 $temp = preg_replace('/<comment>([^>]*)<\/comment>/', '<!--\1-->', $temp); // Restore html comments
8570
8571
8572 return $temp;
8573}
8574
8575
8588function dol_string_onlythesehtmlattributes($stringtoclean, $allowed_attributes = null)
8589{
8590 if (is_null($allowed_attributes)) {
8591 $allowed_attributes = array(
8592 "allow", "allowfullscreen", "alt", "async", "class", "contenteditable", "crossorigin", "data-html", "frameborder", "height", "href", "id", "name", "property", "rel", "src", "style", "target", "title", "type", "width",
8593 // HTML5
8594 "header", "footer", "nav", "section", "menu", "menuitem"
8595 );
8596 }
8597 // Always add content and http-equiv for meta tags, required to force encoding and keep html content in utf8 by load/saveHTML functions.
8598 if (!in_array("content", $allowed_attributes)) {
8599 $allowed_attributes[] = "content";
8600 }
8601 if (!in_array("http-equiv", $allowed_attributes)) {
8602 $allowed_attributes[] = "http-equiv";
8603 }
8604
8605 if (class_exists('DOMDocument') && !empty($stringtoclean)) {
8606 //$stringtoclean = '<?xml encoding="UTF-8"><html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"></head><body>'.$stringtoclean.'</body></html>';
8607 $stringtoclean = '<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"></head><body>'.$stringtoclean.'</body></html>';
8608
8609 // Warning: loadHTML does not support HTML5 on old libxml versions.
8610 $dom = new DOMDocument('', 'UTF-8');
8611 // If $stringtoclean is wrong, it will generates warnings. So we disable warnings and restore them later.
8612 $savwarning = error_reporting();
8613 error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE);
8614 $dom->loadHTML($stringtoclean, LIBXML_ERR_NONE | LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD | LIBXML_NONET | LIBXML_NOWARNING | LIBXML_NOXMLDECL);
8615 error_reporting($savwarning);
8616
8617 if ($dom instanceof DOMDocument) {
8618 for ($els = $dom->getElementsByTagname('*'), $i = $els->length - 1; $i >= 0; $i--) {
8619 $el = $els->item($i);
8620 if (!$el instanceof DOMElement) {
8621 continue;
8622 }
8623 $attrs = $el->attributes;
8624 for ($ii = $attrs->length - 1; $ii >= 0; $ii--) {
8625 //var_dump($attrs->item($ii));
8626 if (!empty($attrs->item($ii)->name)) {
8627 if (! in_array($attrs->item($ii)->name, $allowed_attributes)) {
8628 // Delete attribute if not into allowed_attributes @phan-suppress-next-line PhanUndeclaredMethod
8629 $els->item($i)->removeAttribute($attrs->item($ii)->name);
8630 } elseif (in_array($attrs->item($ii)->name, array('style'))) {
8631 // If attribute is 'style'
8632 $valuetoclean = $attrs->item($ii)->value;
8633
8634 if (isset($valuetoclean)) {
8635 do {
8636 $oldvaluetoclean = $valuetoclean;
8637 $valuetoclean = preg_replace('/\/\*.*\*\//m', '', $valuetoclean); // clean css comments
8638 $valuetoclean = preg_replace('/position\s*:\s*[a-z]+/mi', '', $valuetoclean);
8639 if ($els->item($i)->tagName == 'a') { // more paranoiac cleaning for clickable tags.
8640 $valuetoclean = preg_replace('/display\s*:/mi', '', $valuetoclean);
8641 $valuetoclean = preg_replace('/z-index\s*:/mi', '', $valuetoclean);
8642 $valuetoclean = preg_replace('/\s+(top|left|right|bottom)\s*:/mi', '', $valuetoclean);
8643 }
8644
8645 // We do not allow logout|passwordforgotten.php and action= into the content of a "style" tag
8646 $valuetoclean = preg_replace('/(logout|passwordforgotten)\.php/mi', '', $valuetoclean);
8647 $valuetoclean = preg_replace('/action=/mi', '', $valuetoclean);
8648 } while ($oldvaluetoclean != $valuetoclean);
8649 }
8650
8651 $attrs->item($ii)->value = $valuetoclean;
8652 }
8653 }
8654 }
8655 }
8656 }
8657
8658 $dom->encoding = 'UTF-8';
8659
8660 $return = $dom->saveHTML(); // This may add a LF at end of lines, so we will trim later
8661 //$return = '<html><body>aaaa</p>bb<p>ssdd</p>'."\n<p>aaa</p>aa<p>bb</p>";
8662
8663 //$return = preg_replace('/^'.preg_quote('<?xml encoding="UTF-8">', '/').'/', '', $return);
8664 $return = preg_replace('/^'.preg_quote('<html><head><', '/').'[^<>]*'.preg_quote('></head><body>', '/').'/', '', $return);
8665 $return = preg_replace('/'.preg_quote('</body></html>', '/').'$/', '', trim($return));
8666
8667 return trim($return);
8668 } else {
8669 return $stringtoclean;
8670 }
8671}
8672
8684function dol_string_neverthesehtmltags($stringtoclean, $disallowed_tags = array('textarea'), $cleanalsosomestyles = 0)
8685{
8686 $temp = $stringtoclean;
8687 foreach ($disallowed_tags as $tagtoremove) {
8688 $temp = preg_replace('/<\/?'.$tagtoremove.'>/', '', $temp);
8689 $temp = preg_replace('/<\/?'.$tagtoremove.'\s+[^>]*>/', '', $temp);
8690 }
8691
8692 if ($cleanalsosomestyles) {
8693 $temp = preg_replace('/position\s*:\s*(absolute|fixed)\s*!\s*important/', '', $temp); // Note: If hacker try to introduce css comment into string to avoid this, string should be encoded by the dol_htmlentitiesbr so be harmless
8694 }
8695
8696 return $temp;
8697}
8698
8699
8709function dolGetFirstLineOfText($text, $nboflines = 1, $charset = 'UTF-8')
8710{
8711 if ($nboflines == 1) {
8712 if (dol_textishtml($text)) {
8713 $firstline = preg_replace('/<br[^>]*>.*$/s', '', $text); // The s pattern modifier means the . can match newline characters
8714 $firstline = preg_replace('/<div[^>]*>.*$/s', '', $firstline); // The s pattern modifier means the . can match newline characters
8715 } else {
8716 if (isset($text)) {
8717 $firstline = preg_replace('/[\n\r].*/', '', $text);
8718 } else {
8719 $firstline = '';
8720 }
8721 }
8722 return $firstline.(isset($firstline) && isset($text) && (strlen($firstline) != strlen($text)) ? '...' : '');
8723 } else {
8724 $ishtml = 0;
8725 if (dol_textishtml($text)) {
8726 $text = preg_replace('/\n/', '', $text);
8727 $ishtml = 1;
8728 $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
8729 } else {
8730 $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
8731 }
8732
8733 $text = strtr($text, $repTable);
8734 if ($charset == 'UTF-8') {
8735 $pattern = '/(<br[^>]*>)/Uu';
8736 } else {
8737 // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
8738 $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
8739 }
8740 $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
8741
8742 $firstline = '';
8743 $i = 0;
8744 $countline = 0;
8745 $lastaddediscontent = 1;
8746 while ($countline < $nboflines && isset($a[$i])) {
8747 if (preg_match('/<br[^>]*>/', $a[$i])) {
8748 if (array_key_exists($i + 1, $a) && !empty($a[$i + 1])) {
8749 $firstline .= ($ishtml ? "<br>\n" : "\n");
8750 // Is it a br for a new line of after a printed line ?
8751 if (!$lastaddediscontent) {
8752 $countline++;
8753 }
8754 $lastaddediscontent = 0;
8755 }
8756 } else {
8757 $firstline .= $a[$i];
8758 $lastaddediscontent = 1;
8759 $countline++;
8760 }
8761 $i++;
8762 }
8763
8764 $adddots = (isset($a[$i]) && (!preg_match('/<br[^>]*>/', $a[$i]) || (array_key_exists($i + 1, $a) && !empty($a[$i + 1]))));
8765 //unset($a);
8766 $ret = $firstline.($adddots ? '...' : '');
8767 //exit;
8768 return $ret;
8769 }
8770}
8771
8772
8784function dol_nl2br($stringtoencode, $nl2brmode = 0, $forxml = false)
8785{
8786 if (is_null($stringtoencode)) {
8787 return '';
8788 }
8789
8790 if (!$nl2brmode) {
8791 return nl2br($stringtoencode, $forxml);
8792 } else {
8793 $ret = preg_replace('/(\r\n|\r|\n)/i', ($forxml ? '<br />' : '<br>'), $stringtoencode);
8794 return $ret;
8795 }
8796}
8797
8807function dol_htmlwithnojs($stringtoencode, $nouseofiframesandbox = 0, $check = 'restricthtml')
8808{
8809 if (empty($nouseofiframesandbox) && getDolGlobalString('MAIN_SECURITY_USE_SANDBOX_FOR_HTMLWITHNOJS')) {
8810 // TODO using sandbox on inline html content is not possible yet with current browsers
8811 //$s = '<iframe class="iframewithsandbox" sandbox><html><body>';
8812 //$s .= $stringtoencode;
8813 //$s .= '</body></html></iframe>';
8814 return $stringtoencode;
8815 } else {
8816 $out = $stringtoencode;
8817
8818 // First clean HTML content
8819 do {
8820 $oldstringtoclean = $out;
8821
8822 $outishtml = 0;
8823 if (dol_textishtml($out)) {
8824 $outishtml = 1;
8825 }
8826
8827 // HTML sanitizer by DOMDocument
8828 if (!empty($out) && getDolGlobalString('MAIN_RESTRICTHTML_ONLY_VALID_HTML') && $check != 'restricthtmlallowunvalid') {
8829 try {
8830 libxml_use_internal_errors(false); // Avoid to fill memory with xml errors
8831 if (LIBXML_VERSION < 20900) {
8832 // Avoid load of external entities (security problem).
8833 // Required only if LIBXML_VERSION < 20900
8834 // @phan-suppress-next-line PhanDeprecatedFunctionInternal
8835 libxml_disable_entity_loader(true);
8836 }
8837
8838 $dom = new DOMDocument();
8839 // Add a trick '<div class="tricktoremove">' to solve pb with text without parent tag
8840 // like '<h1>Foo</h1><p>bar</p>' that wrongly ends up, without the trick, with '<h1>Foo<p>bar</p></h1>'
8841 // like 'abc' that wrongly ends up, without the trick, with '<p>abc</p>'
8842 // Add also a trick <html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"> to solve utf8 lost.
8843 // I don't know what the xml encoding is the trick for
8844 if ($outishtml) {
8845 //$out = '<?xml encoding="UTF-8"><html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"></head><body><div class="tricktoremove">'.$out.'</div></body></html>';
8846 $out = '<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"></head><body><div class="tricktoremove">'.$out.'</div></body></html>';
8847 //$out = '<html><head><meta charset="utf-8"></head><body><div class="tricktoremove">'.$out.'</div></body></html>';
8848 } else {
8849 //$out = '<?xml encoding="UTF-8"><html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"></head><body><div class="tricktoremove">'.dol_nl2br($out).'</div></body></html>';
8850 $out = '<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"></head><body><div class="tricktoremove">'.dol_nl2br($out).'</div></body></html>';
8851 //$out = '<html><head><meta charset="utf-8"></head><body><div class="tricktoremove">'.dol_nl2br($out).'</div></body></html>';
8852 }
8853
8854 $dom->loadHTML($out, LIBXML_HTML_NODEFDTD | LIBXML_ERR_NONE | LIBXML_HTML_NOIMPLIED | LIBXML_NONET | LIBXML_NOWARNING | LIBXML_NOERROR | LIBXML_NOXMLDECL);
8855
8856 $dom->encoding = 'UTF-8';
8857
8858 $out = trim($dom->saveHTML());
8859
8860 // Remove the trick added to solve pb with text in utf8 and text without parent tag
8861 //$out = preg_replace('/^'.preg_quote('<?xml encoding="UTF-8">', '/').'/', '', $out);
8862 $out = preg_replace('/^'.preg_quote('<html><head><', '/').'[^<>]+'.preg_quote('></head><body><div class="tricktoremove">', '/').'/', '', $out);
8863 $out = preg_replace('/'.preg_quote('</div></body></html>', '/').'$/', '', trim($out));
8864 // $out = preg_replace('/^<\?xml encoding="UTF-8"><div class="tricktoremove">/', '', $out);
8865 // $out = preg_replace('/<\/div>$/', '', $out);
8866 // var_dump('rrrrrrrrrrrrrrrrrrrrrrrrrrrrr'.$out);
8867
8868 if (!$outishtml) { // If $out was not HTML content we made before a dol_nl2br so we must do the opposite operation now
8869 $out = str_replace('<br>', '', $out);
8870 }
8871 } catch (Exception $e) {
8872 // If error, invalid HTML string with no way to clean it
8873 //print $e->getMessage();
8874 $out = 'InvalidHTMLStringCantBeCleaned '.$e->getMessage();
8875 }
8876 }
8877
8878 // HTML sanitizer by Tidy
8879 // Tidy can't be used for restricthtmlallowunvalid and restricthtmlallowlinkscript
8880 // Tidy can't be used for non html text content as it is corrupting the new lines fields.
8881 if (!empty($out) && getDolGlobalString('MAIN_RESTRICTHTML_ONLY_VALID_HTML_TIDY') && !in_array($check, array('restricthtmlallowunvalid', 'restricthtmlallowlinkscript')) && $outishtml) {
8882 // TODO Try to implement a hack for restricthtmlallowlinkscript by renaming tag <link> and <script> ?
8883 try {
8884 //var_dump($out);
8885
8886 // Try cleaning using tidy
8887 if (extension_loaded('tidy') && class_exists("tidy")) {
8888 //print "aaa".$out."\n";
8889
8890 // See options at https://tidy.sourceforge.net/docs/quickref.html
8891 $config = array(
8892 'clean' => false,
8893 // Best will be to set 'quote-marks' to false to not replace " that are used for real text content (not a string symbol for html attribute) into &quot;
8894 'quote-marks' => false,
8895 'doctype' => 'strict',
8896 'show-body-only' => true,
8897 "indent-attributes" => false,
8898 "vertical-space" => false,
8899 //'ident' => false, // Not always supported
8900 "wrap" => 0,
8901 'preserve-entities' => true
8902 // HTML5 tags
8903 //'new-blocklevel-tags' => 'article aside audio bdi canvas details dialog figcaption figure footer header hgroup main menu menuitem nav section source summary template track video',
8904 //'new-blocklevel-tags' => 'footer header section menu menuitem'
8905 //'new-empty-tags' => 'command embed keygen source track wbr',
8906 //'new-inline-tags' => 'audio command datalist embed keygen mark menuitem meter output progress source time video wbr',
8907 );
8908
8909 // Tidy
8910 $tidy = new tidy();
8911 $out = $tidy->repairString($out, $config, 'utf8');
8912
8913 //print "xxx".$out;exit;
8914 }
8915
8916 //var_dump($out);
8917 } catch (Exception $e) {
8918 // If error, invalid HTML string with no way to clean it
8919 //print $e->getMessage();
8920 $out = 'InvalidHTMLStringCantBeCleaned '.$e->getMessage();
8921 }
8922 }
8923
8924 // Clear ZERO WIDTH NO-BREAK SPACE, ZERO WIDTH SPACE, ZERO WIDTH JOINER
8925 $out = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', ' ', $out);
8926
8927 // Clean some html entities that are useless so text is cleaner
8928 $out = preg_replace('/&(tab|newline);/i', ' ', $out);
8929
8930 // Ckeditor uses the numeric entity for apostrophe, so we force it to
8931 // the text entity (all other special chars are encoded using text entities) so we can then exclude all numeric entities.
8932 $out = preg_replace('/&#39;/i', '&apos;', $out);
8933
8934 // We replace chars from a/A to z/Z encoded with numeric HTML entities with the real char so we won't loose the chars at the next step (preg_replace).
8935 // No need to use a loop here, this step is not to sanitize (this is done at next step, this is to try to save chars, even if they are
8936 // using a non conventionnal way to be encoded, to not have them sanitized just after)
8937 if (function_exists('realCharForNumericEntities')) { // May not exist when main.inc.php not loaded, for example in a CLI context
8938 $out = preg_replace_callback(
8939 '/&#(x?[0-9][0-9a-f]+;?)/i',
8944 static function ($m) {
8945 return realCharForNumericEntities($m);
8946 },
8947 $out
8948 );
8949 }
8950
8951 // Now we remove all remaining HTML entities starting with a number. We don't want such entities.
8952 $out = preg_replace('/&#x?[0-9]+/i', '', $out); // For example if we have j&#x61vascript with an entities without the ; to hide the 'a' of 'javascript'.
8953
8954 // Keep only some html tags and remove also some 'javascript:' strings
8955 if ($check == 'restricthtmlallowlinkscript') {
8956 $out = dol_string_onlythesehtmltags($out, 0, 1, 0, 0, array(), 1, 1, 1, getDolGlobalInt("UNSECURED_restricthtmlallowlinkscript_ALLOW_PHP"));
8957 } elseif ($check == 'restricthtmlallowclass' || $check == 'restricthtmlallowunvalid') {
8958 $out = dol_string_onlythesehtmltags($out, 0, 0, 1);
8959 } elseif ($check == 'restricthtmlallowiframe') {
8960 $out = dol_string_onlythesehtmltags($out, 0, 0, 1, 1);
8961 } else {
8962 $out = dol_string_onlythesehtmltags($out, 0, 1, 1);
8963 }
8964
8965 // Keep only some html attributes and exclude non expected HTML attributes and clean content of some attributes (keep only alt=, title=...).
8966 if (getDolGlobalString('MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES')) {
8968 }
8969
8970 // Restore entity &apos; into &#39; (restricthtml is for html content so we can use html entity) because it is
8971 // compatible with HTML 4 used y CKEditor, and HTML 5 (when &apos; works only with HTML5).
8972 $out = preg_replace('/&apos;/i', "&#39;", $out);
8973
8974 // Now remove js
8975 // List of dom events is on https://www.w3schools.com/jsref/dom_obj_event.asp and https://developer.mozilla.org/en-US/docs/Web/Events
8976 $out = preg_replace('/on(mouse|drag|key|load|touch|pointer|select|transition)[a-z]*\s*=/i', '', $out); // onmousexxx can be set on img or any html tag like <img title='...' onmouseover=alert(1)>
8977 $out = preg_replace('/on(abort|after|animation|auxclick|before|blur|cancel|canplay|canplaythrough|change|click|close|contextmenu|cuechange|copy|cut)[a-z]*\s*=/i', '', $out);
8978 $out = preg_replace('/on(dblclick|drop|durationchange|emptied|end|ended|error|focus(in|out)?|formdata|gotpointercapture|hashchange|input|invalid)[a-z]*\s*=/i', '', $out);
8979 $out = preg_replace('/on(lostpointercapture|offline|online|pagehide|pageshow)[a-z]*\s*=/i', '', $out);
8980 $out = preg_replace('/on(paste|pause|play|playing|progress|ratechange|reset|resize|scroll|search|seeked|seeking|show|stalled|start|submit|suspend)[a-z]*\s*=/i', '', $out);
8981 $out = preg_replace('/on(timeupdate|toggle|unload|volumechange|waiting|wheel)[a-z]*\s*=/i', '', $out);
8982 // More not into the previous list
8983 $out = preg_replace('/on(repeat|begin|finish|beforeinput)[a-z]*\s*=/i', '', $out);
8984 } while ($oldstringtoclean != $out);
8985
8986 // Check the limit of external links that are automatically executed in a Rich text content. We count:
8987 // '<img' to avoid <img src="http...">, we can only accept "<img src="data:..."
8988 // 'url(' to avoid inline style like background: url(http...
8989 // '<link' to avoid <link href="http...">
8990 $reg = array();
8991 $tmpout = preg_replace('/<img src="data:/mi', '<__IMG_SRC_DATA__ src="data:', $out);
8992 preg_match_all('/(<img|url\‍(|<link)/i', $tmpout, $reg);
8993 $nblinks = count($reg[0]);
8994 if ($nblinks > getDolGlobalInt("MAIN_SECURITY_MAX_IMG_IN_HTML_CONTENT", 1000)) {
8995 $out = 'ErrorTooManyLinksIntoHTMLString';
8996 }
8997
8998 if (getDolGlobalInt('MAIN_DISALLOW_URL_INTO_DESCRIPTIONS') == 2 || $check == 'restricthtmlnolink') {
8999 if ($nblinks > 0) {
9000 $out = 'ErrorHTMLLinksNotAllowed';
9001 }
9002 } elseif (getDolGlobalInt('MAIN_DISALLOW_URL_INTO_DESCRIPTIONS') == 1) {
9003 $nblinks = 0;
9004 // Loop on each url in src= and url(
9005 $pattern = '/src=["\']?(http[^"\']+)|url\‍(["\']?(http[^\‍)]+)/';
9006
9007 $matches = array();
9008 if (preg_match_all($pattern, $out, $matches)) {
9009 // URLs are into $matches[1]
9010 $urls = $matches[1];
9011
9012 // Affiche les URLs
9013 foreach ($urls as $url) {
9014 $nblinks++;
9015 echo "Found url = ".$url . "\n";
9016 }
9017 if ($nblinks > 0) {
9018 $out = 'ErrorHTMLExternalLinksNotAllowed';
9019 }
9020 }
9021 }
9022
9023 return $out;
9024 }
9025}
9026
9047function dol_htmlentitiesbr($stringtoencode, $nl2brmode = 0, $pagecodefrom = 'UTF-8', $removelasteolbr = 1)
9048{
9049 if (is_null($stringtoencode)) {
9050 return '';
9051 }
9052
9053 $newstring = $stringtoencode;
9054 if (dol_textishtml($stringtoencode)) { // Check if text is already HTML or not
9055 $newstring = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i', '<br>', $newstring); // Replace "<br type="_moz" />" by "<br>". It's same and avoid pb with FPDF.
9056 if ($removelasteolbr) {
9057 $newstring = preg_replace('/<br>$/i', '', $newstring); // Remove last <br> (remove only last one)
9058 }
9059 $newstring = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', ' ', $newstring);
9060 $newstring = strtr($newstring, array('&' => '__PROTECTand__', '<' => '__PROTECTlt__', '>' => '__PROTECTgt__', '"' => '__PROTECTdquot__'));
9061 $newstring = dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom); // Make entity encoding
9062 $newstring = strtr($newstring, array('__PROTECTand__' => '&', '__PROTECTlt__' => '<', '__PROTECTgt__' => '>', '__PROTECTdquot__' => '"'));
9063 } else {
9064 if ($removelasteolbr) {
9065 $newstring = preg_replace('/(\r\n|\r|\n)$/i', '', $newstring); // Remove last \n (may remove several)
9066 }
9067 $newstring = dol_nl2br(dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom), $nl2brmode);
9068 }
9069 // Other substitutions that htmlentities does not do
9070 //$newstring=str_replace(chr(128),'&euro;',$newstring); // 128 = 0x80. Not in html entity table. // Seems useles with TCPDF. Make bug with UTF8 languages
9071 return $newstring;
9072}
9073
9081function dol_htmlentitiesbr_decode($stringtodecode, $pagecodeto = 'UTF-8')
9082{
9083 $ret = dol_html_entity_decode($stringtodecode, ENT_COMPAT | ENT_HTML5, $pagecodeto);
9084 $ret = preg_replace('/'."\r\n".'<br(\s[\sa-zA-Z_="]*)?\/?>/i', "<br>", $ret);
9085 $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\r\n".'/i', "\r\n", $ret);
9086 $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\n".'/i', "\n", $ret);
9087 $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i', "\n", $ret);
9088 return $ret;
9089}
9090
9097function dol_htmlcleanlastbr($stringtodecode)
9098{
9099 $ret = preg_replace('/&nbsp;$/i', "", $stringtodecode); // Because wysiwyg editor may add a &nbsp; at end of last line
9100 $ret = preg_replace('/(<br>|<br(\s[\sa-zA-Z_="]*)?\/?>|'."\n".'|'."\r".')+$/i', "", $ret);
9101 return $ret;
9102}
9103
9113function dol_html_entity_decode($a, $b, $c = 'UTF-8', $keepsomeentities = 0)
9114{
9115 $newstring = $a;
9116 if ($keepsomeentities) {
9117 $newstring = strtr($newstring, array('&amp;' => '__andamp__', '&lt;' => '__andlt__', '&gt;' => '__andgt__', '"' => '__dquot__'));
9118 }
9119 $newstring = html_entity_decode((string) $newstring, (int) $b, (string) $c);
9120 if ($keepsomeentities) {
9121 $newstring = strtr($newstring, array('__andamp__' => '&amp;', '__andlt__' => '&lt;', '__andgt__' => '&gt;', '__dquot__' => '"'));
9122 }
9123 return $newstring;
9124}
9125
9137function dol_htmlentities($string, $flags = ENT_QUOTES | ENT_SUBSTITUTE, $encoding = 'UTF-8', $double_encode = false)
9138{
9139 return htmlentities($string, $flags, $encoding, $double_encode);
9140}
9141
9153function dol_string_is_good_iso($s, $clean = 0)
9154{
9155 $len = dol_strlen($s);
9156 $out = '';
9157 $ok = 1;
9158 for ($scursor = 0; $scursor < $len; $scursor++) {
9159 $ordchar = ord($s[$scursor]);
9160 //print $scursor.'-'.$ordchar.'<br>';
9161 if ($ordchar < 32 && $ordchar != 13 && $ordchar != 10) {
9162 $ok = 0;
9163 break;
9164 } elseif ($ordchar > 126 && $ordchar < 160) {
9165 $ok = 0;
9166 break;
9167 } elseif ($clean) {
9168 $out .= $s[$scursor];
9169 }
9170 }
9171 if ($clean) {
9172 return $out;
9173 }
9174 return $ok;
9175}
9176
9185function dol_nboflines($s, $maxchar = 0)
9186{
9187 if ($s == '') {
9188 return 0;
9189 }
9190 $arraystring = explode("\n", $s);
9191 $nb = count($arraystring);
9192
9193 return $nb;
9194}
9195
9196
9206function dol_nboflines_bis($text, $maxlinesize = 0, $charset = 'UTF-8')
9207{
9208 $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
9209 if (dol_textishtml($text)) {
9210 $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
9211 }
9212
9213 $text = strtr($text, $repTable);
9214 if ($charset == 'UTF-8') {
9215 $pattern = '/(<br[^>]*>)/Uu';
9216 } else {
9217 // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
9218 $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
9219 }
9220 $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
9221
9222 $nblines = (int) floor((count($a) + 1) / 2);
9223 // count possible auto line breaks
9224 if ($maxlinesize) {
9225 foreach ($a as $line) {
9226 if (dol_strlen($line) > $maxlinesize) {
9227 //$line_dec = html_entity_decode(strip_tags($line));
9228 $line_dec = html_entity_decode($line);
9229 if (dol_strlen($line_dec) > $maxlinesize) {
9230 $line_dec = wordwrap($line_dec, $maxlinesize, '\n', true);
9231 $nblines += substr_count($line_dec, '\n');
9232 }
9233 }
9234 }
9235 }
9236
9237 unset($a);
9238 return $nblines;
9239}
9240
9249function dol_textishtml($msg, $option = 0)
9250{
9251 if (is_null($msg)) {
9252 return false;
9253 }
9254
9255 if ($option == 1) {
9256 if (preg_match('/<(html|link|script)/i', $msg)) {
9257 return true;
9258 } elseif (preg_match('/<body/i', $msg)) {
9259 return true;
9260 } elseif (preg_match('/<\/textarea/i', $msg)) {
9261 return true;
9262 } elseif (preg_match('/<(b|em|i|u)(\s+[^>]+)?>/i', $msg)) {
9263 return true;
9264 } elseif (preg_match('/<br/i', $msg)) {
9265 return true;
9266 }
9267 return false;
9268 } else {
9269 // Remove all urls because 'http://aa?param1=abc&amp;param2=def' must not be used inside detection
9270 $msg = preg_replace('/https?:\/\/[^"\'\s]+/i', '', $msg);
9271 if (preg_match('/<(html|link|script|body)/i', $msg)) {
9272 return true;
9273 } elseif (preg_match('/<\/textarea/i', $msg)) {
9274 return true;
9275 } elseif (preg_match('/<(b|em|i|u)(\s+[^>]+)?>/i', $msg)) {
9276 return true;
9277 } elseif (preg_match('/<(br|hr)\/>/i', $msg)) {
9278 return true;
9279 } elseif (preg_match('/<(br|hr|div|font|li|p|span|strong|table)>/i', $msg)) {
9280 return true;
9281 } elseif (preg_match('/<(br|hr|div|font|li|p|span|strong|table)\s+[^<>\/]*\/?>/i', $msg)) {
9282 return true;
9283 } elseif (preg_match('/<img\s+[^<>]*src[^<>]*>/i', $msg)) {
9284 return true; // must accept <img src="http://example.com/aaa.png" />
9285 } elseif (preg_match('/<a\s+[^<>]*href[^<>]*>/i', $msg)) {
9286 return true; // must accept <a href="http://example.com/aaa.png" />
9287 } elseif (preg_match('/<h[0-9]>/i', $msg)) {
9288 return true;
9289 } elseif (preg_match('/&[A-Z0-9]{1,6};/i', $msg)) {
9290 // TODO If content is 'A link https://aaa?param=abc&amp;param2=def', it return true but must be false
9291 return true; // Html entities names (http://www.w3schools.com/tags/ref_entities.asp)
9292 } elseif (preg_match('/&#[0-9]{2,3};/i', $msg)) {
9293 return true; // Html entities numbers (http://www.w3schools.com/tags/ref_entities.asp)
9294 } elseif (preg_match('/&#x[a-f0-9][a-f0-9];/i', $msg)) {
9295 return true; // Html entities numbers in hexa
9296 }
9297
9298 return false;
9299 }
9300}
9301
9316function dol_concatdesc($text1, $text2, $forxml = false, $invert = false)
9317{
9318 if (!empty($invert)) {
9319 $tmp = $text1;
9320 $text1 = $text2;
9321 $text2 = $tmp;
9322 }
9323
9324 $ret = '';
9325 $ret .= (!dol_textishtml($text1) && dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text1, 0, 1, '', 1), 0, $forxml) : $text1;
9326 $ret .= (!empty($text1) && !empty($text2)) ? ((dol_textishtml($text1) || dol_textishtml($text2)) ? ($forxml ? "<br >\n" : "<br>\n") : "\n") : "";
9327 $ret .= (dol_textishtml($text1) && !dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text2, 0, 1, '', 1), 0, $forxml) : $text2;
9328 return $ret;
9329}
9330
9331
9332
9346function getCommonSubstitutionArray($outputlangs, $onlykey = 0, $exclude = null, $object = null, $include = null)
9347{
9348 global $db, $conf, $mysoc, $user, $extrafields;
9349
9350 $substitutionarray = array();
9351
9352 if ((empty($exclude) || !in_array('user', $exclude)) && (empty($include) || in_array('user', $include)) && $user instanceof User) {
9353 // Add SIGNATURE into substitutionarray first, so, when we will make the substitution,
9354 // this will include signature content first and then replace var found into content of signature
9355 //var_dump($onlykey);
9356 $emailsendersignature = $user->signature; // By default, we use the signature of current user. We must complete substitution with signature in c_email_senderprofile of array after calling getCommonSubstitutionArray()
9357 $usersignature = $user->signature;
9358 $substitutionarray = array_merge($substitutionarray, array(
9359 '__SENDEREMAIL_SIGNATURE__' => (string) ((!getDolGlobalString('MAIN_MAIL_DO_NOT_USE_SIGN')) ? ($onlykey == 2 ? dol_trunc('SignatureFromTheSelectedSenderProfile', 30) : $emailsendersignature) : ''),
9360 '__USER_SIGNATURE__' => (string) (($usersignature && !getDolGlobalString('MAIN_MAIL_DO_NOT_USE_SIGN')) ? ($onlykey == 2 ? dol_trunc(dol_string_nohtmltag($usersignature), 30) : $usersignature) : '')
9361 ));
9362
9363 if (is_object($user) && ($user instanceof User)) {
9364 $substitutionarray = array_merge($substitutionarray, array(
9365 '__USER_ID__' => (string) $user->id,
9366 '__USER_LOGIN__' => (string) $user->login,
9367 '__USER_EMAIL__' => (string) $user->email,
9368 '__USER_PHONE__' => (string) dol_print_phone($user->office_phone, '', 0, 0, '', " ", '', '', -1),
9369 '__USER_PHONEPRO__' => (string) dol_print_phone($user->user_mobile, '', 0, 0, '', " ", '', '', -1),
9370 '__USER_PHONEMOBILE__' => (string) dol_print_phone($user->personal_mobile, '', 0, 0, '', " ", '', '', -1),
9371 '__USER_FAX__' => (string) $user->office_fax,
9372 '__USER_LASTNAME__' => (string) $user->lastname,
9373 '__USER_FIRSTNAME__' => (string) $user->firstname,
9374 '__USER_FULLNAME__' => (string) $user->getFullName($outputlangs),
9375 '__USER_SUPERVISOR_ID__' => (string) ($user->fk_user ? $user->fk_user : '0'),
9376 '__USER_JOB__' => (string) $user->job,
9377 '__USER_REMOTE_IP__' => (string) getUserRemoteIP(),
9378 '__USER_VCARD_URL__' => (string) $user->getOnlineVirtualCardUrl('', 'external')
9379 ));
9380 }
9381 }
9382 if ((empty($exclude) || !in_array('mycompany', $exclude)) && is_object($mysoc) && (empty($include) || in_array('mycompany', $include))) {
9383 $substitutionarray = array_merge($substitutionarray, array(
9384 '__MYCOMPANY_NAME__' => $mysoc->name,
9385 '__MYCOMPANY_EMAIL__' => $mysoc->email,
9386 '__MYCOMPANY_URL__' => $mysoc->url,
9387 '__MYCOMPANY_PHONE__' => dol_print_phone($mysoc->phone, '', 0, 0, '', " ", '', '', -1),
9388 '__MYCOMPANY_PHONEMOBILE__' => dol_print_phone($mysoc->phone_mobile, '', 0, 0, '', " ", '', '', -1),
9389 '__MYCOMPANY_FAX__' => dol_print_phone($mysoc->fax, '', 0, 0, '', " ", '', '', -1),
9390 '__MYCOMPANY_PROFID1__' => $mysoc->idprof1,
9391 '__MYCOMPANY_PROFID2__' => $mysoc->idprof2,
9392 '__MYCOMPANY_PROFID3__' => $mysoc->idprof3,
9393 '__MYCOMPANY_PROFID4__' => $mysoc->idprof4,
9394 '__MYCOMPANY_PROFID5__' => $mysoc->idprof5,
9395 '__MYCOMPANY_PROFID6__' => $mysoc->idprof6,
9396 '__MYCOMPANY_PROFID7__' => $mysoc->idprof7,
9397 '__MYCOMPANY_PROFID8__' => $mysoc->idprof8,
9398 '__MYCOMPANY_PROFID9__' => $mysoc->idprof9,
9399 '__MYCOMPANY_PROFID10__' => $mysoc->idprof10,
9400 '__MYCOMPANY_CAPITAL__' => $mysoc->capital,
9401 '__MYCOMPANY_FULLADDRESS__' => (method_exists($mysoc, 'getFullAddress') ? $mysoc->getFullAddress(1, ', ') : ''), // $mysoc may be stdClass
9402 '__MYCOMPANY_ADDRESS__' => $mysoc->address,
9403 '__MYCOMPANY_ZIP__' => $mysoc->zip,
9404 '__MYCOMPANY_TOWN__' => $mysoc->town,
9405 '__MYCOMPANY_STATE__' => $mysoc->state,
9406 '__MYCOMPANY_COUNTRY__' => $mysoc->country,
9407 '__MYCOMPANY_COUNTRY_ID__' => $mysoc->country_id,
9408 '__MYCOMPANY_COUNTRY_CODE__' => $mysoc->country_code,
9409 '__MYCOMPANY_CURRENCY_CODE__' => $conf->currency
9410 ));
9411 }
9412
9413 if (($onlykey || is_object($object)) && (empty($exclude) || !in_array('object', $exclude)) && (empty($include) || in_array('object', $include))) {
9414 if ($onlykey) {
9415 $substitutionarray['__ID__'] = '__ID__';
9416 $substitutionarray['__REF__'] = '__REF__';
9417 $substitutionarray['__NEWREF__'] = '__NEWREF__';
9418 $substitutionarray['__LABEL__'] = '__LABEL__';
9419 $substitutionarray['__REF_CLIENT__'] = '__REF_CLIENT__';
9420 $substitutionarray['__REF_SUPPLIER__'] = '__REF_SUPPLIER__';
9421 $substitutionarray['__NOTE_PUBLIC__'] = '__NOTE_PUBLIC__';
9422 $substitutionarray['__NOTE_PRIVATE__'] = '__NOTE_PRIVATE__';
9423 $substitutionarray['__EXTRAFIELD_XXX__'] = '__EXTRAFIELD_XXX__';
9424
9425 if (isModEnabled("societe")) { // Most objects are concerned
9426 $substitutionarray['__THIRDPARTY_ID__'] = '__THIRDPARTY_ID__';
9427 $substitutionarray['__THIRDPARTY_NAME__'] = '__THIRDPARTY_NAME__';
9428 $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = '__THIRDPARTY_NAME_ALIAS__';
9429 $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = '__THIRDPARTY_CODE_CLIENT__';
9430 $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = '__THIRDPARTY_CODE_FOURNISSEUR__';
9431 $substitutionarray['__THIRDPARTY_EMAIL__'] = '__THIRDPARTY_EMAIL__';
9432 //$substitutionarray['__THIRDPARTY_EMAIL_URLENCODED__'] = '__THIRDPARTY_EMAIL_URLENCODED__'; // We hide this one
9433 $substitutionarray['__THIRDPARTY_URL__'] = '__THIRDPARTY_URL__';
9434 //$substitutionarray['__THIRDPARTY_URL_URLENCODED__'] = '__THIRDPARTY_URL_URLENCODED__'; // We hide this one
9435 $substitutionarray['__THIRDPARTY_PHONE__'] = '__THIRDPARTY_PHONE__';
9436 $substitutionarray['__THIRDPARTY_FAX__'] = '__THIRDPARTY_FAX__';
9437 $substitutionarray['__THIRDPARTY_ADDRESS__'] = '__THIRDPARTY_ADDRESS__';
9438 $substitutionarray['__THIRDPARTY_ZIP__'] = '__THIRDPARTY_ZIP__';
9439 $substitutionarray['__THIRDPARTY_TOWN__'] = '__THIRDPARTY_TOWN__';
9440 $substitutionarray['__THIRDPARTY_STATE__'] = '__THIRDPARTY_STATE__';
9441 $substitutionarray['__THIRDPARTY_IDPROF1__'] = '__THIRDPARTY_IDPROF1__';
9442 $substitutionarray['__THIRDPARTY_IDPROF2__'] = '__THIRDPARTY_IDPROF2__';
9443 $substitutionarray['__THIRDPARTY_IDPROF3__'] = '__THIRDPARTY_IDPROF3__';
9444 $substitutionarray['__THIRDPARTY_IDPROF4__'] = '__THIRDPARTY_IDPROF4__';
9445 $substitutionarray['__THIRDPARTY_IDPROF5__'] = '__THIRDPARTY_IDPROF5__';
9446 $substitutionarray['__THIRDPARTY_IDPROF6__'] = '__THIRDPARTY_IDPROF6__';
9447 $substitutionarray['__THIRDPARTY_IDPROF7__'] = '__THIRDPARTY_IDPROF7__';
9448 $substitutionarray['__THIRDPARTY_IDPROF8__'] = '__THIRDPARTY_IDPROF8__';
9449 $substitutionarray['__THIRDPARTY_IDPROF9__'] = '__THIRDPARTY_IDPROF9__';
9450 $substitutionarray['__THIRDPARTY_IDPROF10__'] = '__THIRDPARTY_IDPROF10__';
9451 $substitutionarray['__THIRDPARTY_TVAINTRA__'] = '__THIRDPARTY_TVAINTRA__';
9452 $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = '__THIRDPARTY_NOTE_PUBLIC__';
9453 $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = '__THIRDPARTY_NOTE_PRIVATE__';
9454 }
9455 if (isModEnabled('member') && (!is_object($object) || $object->element == 'adherent') && (empty($exclude) || !in_array('member', $exclude)) && (empty($include) || in_array('member', $include))) {
9456 $substitutionarray['__MEMBER_ID__'] = '__MEMBER_ID__';
9457 $substitutionarray['__MEMBER_TITLE__'] = '__MEMBER_TITLE__';
9458 $substitutionarray['__MEMBER_FIRSTNAME__'] = '__MEMBER_FIRSTNAME__';
9459 $substitutionarray['__MEMBER_LASTNAME__'] = '__MEMBER_LASTNAME__';
9460 $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = 'Login and pass of the external user account';
9461 /*$substitutionarray['__MEMBER_NOTE_PUBLIC__'] = '__MEMBER_NOTE_PUBLIC__';
9462 $substitutionarray['__MEMBER_NOTE_PRIVATE__'] = '__MEMBER_NOTE_PRIVATE__';*/
9463 }
9464 // add substitution variables for ticket
9465 if (isModEnabled('ticket') && (!is_object($object) || $object->element == 'ticket') && (empty($exclude) || !in_array('ticket', $exclude)) && (empty($include) || in_array('ticket', $include))) {
9466 $substitutionarray['__TICKET_TRACKID__'] = '__TICKET_TRACKID__';
9467 $substitutionarray['__TICKET_SUBJECT__'] = '__TICKET_SUBJECT__';
9468 $substitutionarray['__TICKET_TYPE__'] = '__TICKET_TYPE__';
9469 $substitutionarray['__TICKET_SEVERITY__'] = '__TICKET_SEVERITY__';
9470 $substitutionarray['__TICKET_CATEGORY__'] = '__TICKET_CATEGORY__';
9471 $substitutionarray['__TICKET_ANALYTIC_CODE__'] = '__TICKET_ANALYTIC_CODE__';
9472 $substitutionarray['__TICKET_MESSAGE__'] = '__TICKET_MESSAGE__';
9473 $substitutionarray['__TICKET_PROGRESSION__'] = '__TICKET_PROGRESSION__';
9474 $substitutionarray['__TICKET_USER_ASSIGN__'] = '__TICKET_USER_ASSIGN__';
9475 }
9476
9477 if (isModEnabled('recruitment') && (!is_object($object) || $object->element == 'recruitmentcandidature') && (empty($exclude) || !in_array('recruitment', $exclude)) && (empty($include) || in_array('recruitment', $include))) {
9478 $substitutionarray['__CANDIDATE_FULLNAME__'] = '__CANDIDATE_FULLNAME__';
9479 $substitutionarray['__CANDIDATE_FIRSTNAME__'] = '__CANDIDATE_FIRSTNAME__';
9480 $substitutionarray['__CANDIDATE_LASTNAME__'] = '__CANDIDATE_LASTNAME__';
9481 }
9482 if (isModEnabled('project') && (empty($exclude) || !in_array('project', $exclude)) && (empty($include) || in_array('project', $include))) { // Most objects
9483 $substitutionarray['__PROJECT_ID__'] = '__PROJECT_ID__';
9484 $substitutionarray['__PROJECT_REF__'] = '__PROJECT_REF__';
9485 $substitutionarray['__PROJECT_NAME__'] = '__PROJECT_NAME__';
9486 /*$substitutionarray['__PROJECT_NOTE_PUBLIC__'] = '__PROJECT_NOTE_PUBLIC__';
9487 $substitutionarray['__PROJECT_NOTE_PRIVATE__'] = '__PROJECT_NOTE_PRIVATE__';*/
9488 }
9489 if (isModEnabled('contract') && (!is_object($object) || $object->element == 'contract') && (empty($exclude) || !in_array('contract', $exclude)) && (empty($include) || in_array('contract', $include))) {
9490 $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = 'Highest date planned for a service start';
9491 $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = 'Highest date and hour planned for service start';
9492 $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = 'Lowest data for planned expiration of service';
9493 $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = 'Lowest date and hour for planned expiration of service';
9494 }
9495 if (isModEnabled("propal") && (!is_object($object) || $object->element == 'propal') && (empty($exclude) || !in_array('propal', $exclude)) && (empty($include) || in_array('propal', $include))) {
9496 $substitutionarray['__ONLINE_SIGN_URL__'] = 'ToOfferALinkForOnlineSignature';
9497 }
9498 if (isModEnabled("intervention") && (!is_object($object) || $object->element == 'fichinter') && (empty($exclude) || !in_array('intervention', $exclude)) && (empty($include) || in_array('intervention', $include))) {
9499 $substitutionarray['__ONLINE_SIGN_FICHINTER_URL__'] = 'ToOfferALinkForOnlineSignature';
9500 }
9501 $substitutionarray['__ONLINE_PAYMENT_URL__'] = 'UrlToPayOnlineIfApplicable';
9502 $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = 'TextAndUrlToPayOnlineIfApplicable';
9503 $substitutionarray['__SECUREKEYPAYMENT__'] = 'Security key (if key is not unique per record)';
9504 $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = 'Security key for payment on a member subscription (one key per member)';
9505 $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = 'Security key for payment on an order';
9506 $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = 'Security key for payment on an invoice';
9507 $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = 'Security key for payment on a service of a contract';
9508
9509 $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = 'Direct download url of a proposal';
9510 $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = 'Direct download url of an order';
9511 $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = 'Direct download url of an invoice';
9512 $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = 'Direct download url of a contract';
9513 $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = 'Direct download url of a supplier proposal';
9514
9515 if (isModEnabled("shipping") && (!is_object($object) || $object->element == 'shipping')) {
9516 $substitutionarray['__SHIPPINGTRACKNUM__'] = 'Shipping tracking number';
9517 $substitutionarray['__SHIPPINGTRACKNUMURL__'] = 'Shipping tracking url';
9518 $substitutionarray['__SHIPPINGMETHOD__'] = 'Shipping method';
9519 }
9520 if (isModEnabled("reception") && (!is_object($object) || $object->element == 'reception')) {
9521 $substitutionarray['__RECEPTIONTRACKNUM__'] = 'Shipping tracking number of shipment';
9522 $substitutionarray['__RECEPTIONTRACKNUMURL__'] = 'Shipping tracking url';
9523 }
9524 } else {
9525 '@phan-var-force Adherent|Delivery $object';
9527 $substitutionarray['__ID__'] = $object->id;
9528 $substitutionarray['__REF__'] = $object->ref;
9529 $substitutionarray['__NEWREF__'] = $object->newref;
9530 $substitutionarray['__LABEL__'] = (isset($object->label) ? $object->label : (isset($object->title) ? $object->title : null));
9531 $substitutionarray['__REF_CLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
9532 $substitutionarray['__REF_SUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
9533 $substitutionarray['__NOTE_PUBLIC__'] = (isset($object->note_public) ? $object->note_public : null);
9534 $substitutionarray['__NOTE_PRIVATE__'] = (isset($object->note_private) ? $object->note_private : null);
9535
9536 $substitutionarray['__DATE_CREATION__'] = (isset($object->date_creation) ? dol_print_date($object->date_creation, 'day', false, $outputlangs) : '');
9537 $substitutionarray['__DATE_MODIFICATION__'] = (isset($object->date_modification) ? dol_print_date($object->date_modification, 'day', false, $outputlangs) : '');
9538 $substitutionarray['__DATE_VALIDATION__'] = (isset($object->date_validation) ? dol_print_date($object->date_validation, 'day', false, $outputlangs) : '');
9539
9540 // handle date_delivery: in customer order/supplier order, the property name is delivery_date, in shipment/reception it is date_delivery
9541 $date_delivery = null;
9542 if (property_exists($object, 'date_delivery')) {
9543 $date_delivery = $object->date_delivery;
9544 } elseif (property_exists($object, 'delivery_date')) {
9545 $date_delivery = $object->delivery_date;
9546 }
9547 $substitutionarray['__DATE_DELIVERY__'] = (isset($date_delivery) ? dol_print_date($date_delivery, 'day', false, $outputlangs) : '');
9548 $substitutionarray['__DATE_DELIVERY_DAY__'] = (isset($date_delivery) ? dol_print_date($date_delivery, "%d") : '');
9549 $substitutionarray['__DATE_DELIVERY_DAY_TEXT__'] = (isset($date_delivery) ? dol_print_date($date_delivery, "%A") : '');
9550 $substitutionarray['__DATE_DELIVERY_MON__'] = (isset($date_delivery) ? dol_print_date($date_delivery, "%m") : '');
9551 $substitutionarray['__DATE_DELIVERY_MON_TEXT__'] = (isset($date_delivery) ? dol_print_date($date_delivery, "%b") : '');
9552 $substitutionarray['__DATE_DELIVERY_YEAR__'] = (isset($date_delivery) ? dol_print_date($date_delivery, "%Y") : '');
9553 $substitutionarray['__DATE_DELIVERY_HH__'] = (isset($date_delivery) ? dol_print_date($date_delivery, "%H") : '');
9554 $substitutionarray['__DATE_DELIVERY_MM__'] = (isset($date_delivery) ? dol_print_date($date_delivery, "%M") : '');
9555 $substitutionarray['__DATE_DELIVERY_SS__'] = (isset($date_delivery) ? dol_print_date($date_delivery, "%S") : '');
9556
9557 // For backward compatibility (deprecated)
9558 $substitutionarray['__REFCLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
9559 $substitutionarray['__REFSUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
9560
9561 $substitutionarray['__SUPPLIER_ORDER_DATE_DELIVERY__'] = (isset($date_delivery) ? dol_print_date($date_delivery, 'day', false, $outputlangs) : '');
9562 $substitutionarray['__SUPPLIER_ORDER_DELAY_DELIVERY__'] = (isset($object->availability_code) ? ($outputlangs->transnoentities("AvailabilityType".$object->availability_code) != 'AvailabilityType'.$object->availability_code ? $outputlangs->transnoentities("AvailabilityType".$object->availability_code) : $outputlangs->convToOutputCharset(isset($object->availability) ? $object->availability : '')) : '');
9563 $substitutionarray['__EXPIRATION_DATE__'] = (isset($object->fin_validite) ? dol_print_date($object->fin_validite, 'daytext') : '');
9564
9565 if (is_object($object) && ($object->element == 'adherent' || $object->element == 'member') && $object->id > 0) {
9566 '@phan-var-force Adherent $object';
9568 $birthday = (empty($object->birth) ? '' : dol_print_date($object->birth, 'day'));
9569
9570 $substitutionarray['__MEMBER_ID__'] = (isset($object->id) ? $object->id : '');
9571 if (method_exists($object, 'getCivilityLabel')) {
9572 $substitutionarray['__MEMBER_TITLE__'] = $object->getCivilityLabel();
9573 }
9574 $substitutionarray['__MEMBER_FIRSTNAME__'] = (isset($object->firstname) ? $object->firstname : '');
9575 $substitutionarray['__MEMBER_LASTNAME__'] = (isset($object->lastname) ? $object->lastname : '');
9576 $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = '';
9577 if (method_exists($object, 'getFullName')) {
9578 $substitutionarray['__MEMBER_FULLNAME__'] = $object->getFullName($outputlangs);
9579 }
9580 $substitutionarray['__MEMBER_COMPANY__'] = (isset($object->societe) ? $object->societe : '');
9581 $substitutionarray['__MEMBER_ADDRESS__'] = (isset($object->address) ? $object->address : '');
9582 $substitutionarray['__MEMBER_ZIP__'] = (isset($object->zip) ? $object->zip : '');
9583 $substitutionarray['__MEMBER_TOWN__'] = (isset($object->town) ? $object->town : '');
9584 $substitutionarray['__MEMBER_STATE__'] = (isset($object->state) ? $object->state : '');
9585 $substitutionarray['__MEMBER_COUNTRY__'] = (isset($object->country) ? $object->country : '');
9586 $substitutionarray['__MEMBER_EMAIL__'] = (isset($object->email) ? $object->email : '');
9587 $substitutionarray['__MEMBER_BIRTH__'] = (isset($birthday) ? $birthday : '');
9588 $substitutionarray['__MEMBER_PHOTO__'] = (isset($object->photo) ? $object->photo : '');
9589 $substitutionarray['__MEMBER_LOGIN__'] = (isset($object->login) ? $object->login : '');
9590 $substitutionarray['__MEMBER_PASSWORD__'] = (isset($object->pass) ? $object->pass : '');
9591 $substitutionarray['__MEMBER_PHONE__'] = (isset($object->phone) ? dol_print_phone($object->phone) : '');
9592 $substitutionarray['__MEMBER_PHONEPRO__'] = (isset($object->phone_perso) ? dol_print_phone($object->phone_perso) : '');
9593 $substitutionarray['__MEMBER_PHONEMOBILE__'] = (isset($object->phone_mobile) ? dol_print_phone($object->phone_mobile) : '');
9594 $substitutionarray['__MEMBER_TYPE__'] = (isset($object->type) ? $object->type : '');
9595 $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE__'] = dol_print_date($object->first_subscription_date, 'day');
9596
9597 $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_RFC__'] = dol_print_date($object->first_subscription_date, 'dayrfc');
9598 $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_START__'] = (isset($object->first_subscription_date_start) ? dol_print_date($object->first_subscription_date_start, 'day') : '');
9599 $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_START_RFC__'] = (isset($object->first_subscription_date_start) ? dol_print_date($object->first_subscription_date_start, 'dayrfc') : '');
9600 $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_END__'] = (isset($object->first_subscription_date_end) ? dol_print_date($object->first_subscription_date_end, 'day') : '');
9601 $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_END_RFC__'] = (isset($object->first_subscription_date_end) ? dol_print_date($object->first_subscription_date_end, 'dayrfc') : '');
9602 $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE__'] = dol_print_date($object->last_subscription_date, 'day');
9603 $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_RFC__'] = dol_print_date($object->last_subscription_date, 'dayrfc');
9604 $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->last_subscription_date_start, 'day');
9605 $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_START_RFC__'] = dol_print_date($object->last_subscription_date_start, 'dayrfc');
9606 $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->last_subscription_date_end, 'day');
9607 $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_END_RFC__'] = dol_print_date($object->last_subscription_date_end, 'dayrfc');
9608 }
9609
9610 if (is_object($object) && $object->element == 'societe') {
9612 '@phan-var-force Societe $object';
9613 $substitutionarray['__THIRDPARTY_ID__'] = $object->id ?? '';
9614 $substitutionarray['__THIRDPARTY_NAME__'] = $object->name ?? '';
9615 $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = $object->name_alias ?? '';
9616 $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = $object->code_client ?? '';
9617 $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = $object->code_fournisseur ?? '';
9618 $substitutionarray['__THIRDPARTY_EMAIL__'] = $object->email ?? '';
9619 $substitutionarray['__THIRDPARTY_EMAIL_URLENCODED__'] = urlencode($object->email ?? '');
9620 $substitutionarray['__THIRDPARTY_URL__'] = $object->url ?? '';
9621 $substitutionarray['__THIRDPARTY_URL_URLENCODED__'] = urlencode($object->url ?? '');
9622 $substitutionarray['__THIRDPARTY_PHONE__'] = dol_print_phone($object->phone ?? '');
9623 $substitutionarray['__THIRDPARTY_FAX__'] = dol_print_phone($object->fax ?? '');
9624 $substitutionarray['__THIRDPARTY_ADDRESS__'] = $object->address ?? '';
9625 $substitutionarray['__THIRDPARTY_ZIP__'] = $object->zip ?? '';
9626 $substitutionarray['__THIRDPARTY_TOWN__'] = $object->town ?? '';
9627 $substitutionarray['__THIRDPARTY_STATE__'] = $object->state ?? '';
9628 $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = ($object->country_id > 0 ? $object->country_id : '');
9629 $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = $object->country_code ?? '';
9630 $substitutionarray['__THIRDPARTY_IDPROF1__'] = $object->idprof1 ?? '';
9631 $substitutionarray['__THIRDPARTY_IDPROF2__'] = $object->idprof2 ?? '';
9632 $substitutionarray['__THIRDPARTY_IDPROF3__'] = $object->idprof3 ?? '';
9633 $substitutionarray['__THIRDPARTY_IDPROF4__'] = $object->idprof4 ?? '';
9634 $substitutionarray['__THIRDPARTY_IDPROF5__'] = $object->idprof5 ?? '';
9635 $substitutionarray['__THIRDPARTY_IDPROF6__'] = $object->idprof6 ?? '';
9636 $substitutionarray['__THIRDPARTY_TVAINTRA__'] = $object->tva_intra ?? '';
9637 $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = dol_htmlentitiesbr($object->note_public ?? '');
9638 $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = dol_htmlentitiesbr($object->note_private ?? '');
9639 } elseif (is_object($object) && is_object($object->thirdparty)) {
9640 $substitutionarray['__THIRDPARTY_ID__'] = $object->thirdparty->id ?? '';
9641 $substitutionarray['__THIRDPARTY_NAME__'] = $object->thirdparty->name ?? '';
9642 $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = $object->thirdparty->name_alias ?? '';
9643 $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = $object->thirdparty->code_client ?? '';
9644 $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = $object->thirdparty->code_fournisseur ?? '';
9645 $substitutionarray['__THIRDPARTY_EMAIL__'] = $object->thirdparty->email ?? '';
9646 $substitutionarray['__THIRDPARTY_EMAIL_URLENCODED__'] = urlencode($object->thirdparty->email ?? '');
9647 $substitutionarray['__THIRDPARTY_PHONE__'] = dol_print_phone($object->thirdparty->phone ?? '');
9648 $substitutionarray['__THIRDPARTY_FAX__'] = dol_print_phone($object->thirdparty->fax ?? '');
9649 $substitutionarray['__THIRDPARTY_ADDRESS__'] = $object->thirdparty->address ?? '';
9650 $substitutionarray['__THIRDPARTY_ZIP__'] = $object->thirdparty->zip ?? '';
9651 $substitutionarray['__THIRDPARTY_TOWN__'] = $object->thirdparty->town ?? '';
9652 $substitutionarray['__THIRDPARTY_STATE__'] = $object->thirdparty->state ?? '';
9653 $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = ($object->thirdparty->country_id > 0 ? $object->thirdparty->country_id : '');
9654 $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = $object->thirdparty->country_code ?? '';
9655 $substitutionarray['__THIRDPARTY_IDPROF1__'] = $object->thirdparty->idprof1 ?? '';
9656 $substitutionarray['__THIRDPARTY_IDPROF2__'] = $object->thirdparty->idprof2 ?? '';
9657 $substitutionarray['__THIRDPARTY_IDPROF3__'] = $object->thirdparty->idprof3 ?? '';
9658 $substitutionarray['__THIRDPARTY_IDPROF4__'] = $object->thirdparty->idprof4 ?? '';
9659 $substitutionarray['__THIRDPARTY_IDPROF5__'] = $object->thirdparty->idprof5 ?? '';
9660 $substitutionarray['__THIRDPARTY_IDPROF6__'] = $object->thirdparty->idprof6 ?? '';
9661 $substitutionarray['__THIRDPARTY_TVAINTRA__'] = $object->thirdparty->tva_intra ?? '';
9662 $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = dol_htmlentitiesbr($object->thirdparty->note_public ?? '');
9663 $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = dol_htmlentitiesbr($object->thirdparty->note_private ?? '');
9664 }
9665
9666 if (is_object($object) && $object->element == 'recruitmentcandidature') {
9667 '@phan-var-force RecruitmentCandidature $object';
9669 $substitutionarray['__CANDIDATE_FULLNAME__'] = $object->getFullName($outputlangs);
9670 $substitutionarray['__CANDIDATE_FIRSTNAME__'] = isset($object->firstname) ? $object->firstname : '';
9671 $substitutionarray['__CANDIDATE_LASTNAME__'] = isset($object->lastname) ? $object->lastname : '';
9672 }
9673 if (is_object($object) && $object->element == 'conferenceorboothattendee') {
9674 '@phan-var-force ConferenceOrBoothAttendee $object';
9676 $substitutionarray['__ATTENDEE_FULLNAME__'] = $object->getFullName($outputlangs);
9677 $substitutionarray['__ATTENDEE_FIRSTNAME__'] = isset($object->firstname) ? $object->firstname : '';
9678 $substitutionarray['__ATTENDEE_LASTNAME__'] = isset($object->lastname) ? $object->lastname : '';
9679 }
9680
9681 if (is_object($object) && $object->element == 'project') {
9682 '@phan-var-force Project $object';
9684 $substitutionarray['__PROJECT_ID__'] = $object->id;
9685 $substitutionarray['__PROJECT_REF__'] = $object->ref;
9686 $substitutionarray['__PROJECT_NAME__'] = $object->title;
9687 } elseif (is_object($object)) {
9688 $project = null;
9689 if (!empty($object->project)) {
9690 $project = $object->project;
9691 } elseif (!empty($object->projet)) { // Deprecated, for backward compatibility
9692 $project = $object->projet;
9693 }
9694 if (!is_null($project) && is_object($project)) {
9695 $substitutionarray['__PROJECT_ID__'] = $project->id;
9696 $substitutionarray['__PROJECT_REF__'] = $project->ref;
9697 $substitutionarray['__PROJECT_NAME__'] = $project->title;
9698 } else {
9699 // can substitute variables for project : uses lazy load in "make_substitutions" method
9700 $project_id = 0;
9701 if (!empty($object->fk_project) && $object->fk_project > 0) {
9702 $project_id = $object->fk_project;
9703 } elseif (!empty($object->fk_projet) && $object->fk_projet > 0) {
9704 $project_id = $object->fk_project;
9705 }
9706 if ($project_id > 0) {
9707 // path:class:method:id
9708 $substitutionarray['__PROJECT_ID__@lazyload'] = '/projet/class/project.class.php:Project:fetchAndSetSubstitution:' . $project_id;
9709 $substitutionarray['__PROJECT_REF__@lazyload'] = '/projet/class/project.class.php:Project:fetchAndSetSubstitution:' . $project_id;
9710 $substitutionarray['__PROJECT_NAME__@lazyload'] = '/projet/class/project.class.php:Project:fetchAndSetSubstitution:' . $project_id;
9711 }
9712 }
9713 }
9714
9715 if (is_object($object) && $object->element == 'facture') {
9716 '@phan-var-force Facture $object';
9718 $substitutionarray['__INVOICE_SITUATION_NUMBER__'] = isset($object->situation_counter) ? $object->situation_counter : '';
9719 }
9720 if (is_object($object) && $object->element == 'shipping') {
9721 '@phan-var-force Expedition $object';
9723 $substitutionarray['__SHIPPINGTRACKNUM__'] = $object->tracking_number;
9724 $substitutionarray['__SHIPPINGTRACKNUMURL__'] = $object->tracking_url;
9725 $substitutionarray['__SHIPPINGMETHOD__'] = $object->shipping_method;
9726 }
9727 if (is_object($object) && $object->element == 'reception') {
9728 '@phan-var-force Reception $object';
9730 $substitutionarray['__RECEPTIONTRACKNUM__'] = $object->tracking_number;
9731 $substitutionarray['__RECEPTIONTRACKNUMURL__'] = $object->tracking_url;
9732 }
9733
9734 if (is_object($object) && $object->element == 'contrat' && $object->id > 0 && is_array($object->lines)) {
9735 '@phan-var-force Contrat $object';
9737 $dateplannedstart = '';
9738 $datenextexpiration = '';
9739 foreach ($object->lines as $line) {
9740 if ($line->date_start > $dateplannedstart) {
9741 $dateplannedstart = $line->date_start;
9742 }
9743 if ($line->statut == 4 && $line->date_end && (!$datenextexpiration || $line->date_end < $datenextexpiration)) {
9744 $datenextexpiration = $line->date_end;
9745 }
9746 }
9747 $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = dol_print_date($dateplannedstart, 'day');
9748 $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE_RFC__'] = dol_print_date($dateplannedstart, 'dayrfc');
9749 $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = dol_print_date($dateplannedstart, 'standard');
9750
9751 $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = dol_print_date($datenextexpiration, 'day');
9752 $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE_RFC__'] = dol_print_date($datenextexpiration, 'dayrfc');
9753 $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = dol_print_date($datenextexpiration, 'standard');
9754 }
9755 // add substitution variables for ticket
9756 if (is_object($object) && $object->element == 'ticket') {
9757 '@phan-var-force Ticket $object';
9759 $substitutionarray['__TICKET_TRACKID__'] = $object->track_id;
9760 $substitutionarray['__TICKET_SUBJECT__'] = $object->subject;
9761 $substitutionarray['__TICKET_TYPE__'] = $object->type_code;
9762 $substitutionarray['__TICKET_SEVERITY__'] = $object->severity_code;
9763 $substitutionarray['__TICKET_CATEGORY__'] = $object->category_code; // For backward compatibility
9764 $substitutionarray['__TICKET_ANALYTIC_CODE__'] = $object->category_code;
9765 $substitutionarray['__TICKET_MESSAGE__'] = $object->message;
9766 $substitutionarray['__TICKET_PROGRESSION__'] = $object->progress;
9767 $userstat = new User($db);
9768 if ($object->fk_user_assign > 0) {
9769 $userstat->fetch($object->fk_user_assign);
9770 $substitutionarray['__TICKET_USER_ASSIGN__'] = dolGetFirstLastname($userstat->firstname, $userstat->lastname);
9771 }
9772
9773 if ($object->fk_user_create > 0) {
9774 $userstat->fetch($object->fk_user_create);
9775 $substitutionarray['__USER_CREATE__'] = dolGetFirstLastname($userstat->firstname, $userstat->lastname);
9776 }
9777 }
9778
9779 // Create dynamic tags for __EXTRAFIELD_FIELD__
9780 if ($object->table_element && $object->id > 0) {
9781 if (!is_object($extrafields)) {
9782 $extrafields = new ExtraFields($db);
9783 }
9784 $extrafields->fetch_name_optionals_label($object->table_element, true);
9785
9786 if ($object->fetch_optionals() > 0) {
9787 if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) {
9788 foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) {
9789 if ($extrafields->attributes[$object->table_element]['type'][$key] == 'date') {
9790 $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = dol_print_date($object->array_options['options_'.$key], 'day');
9791 $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = dol_print_date($object->array_options['options_'.$key], 'day', 'tzserver', $outputlangs);
9792 $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = dol_print_date($object->array_options['options_'.$key], 'dayrfc');
9793 } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'datetime') {
9794 $datetime = $object->array_options['options_'.$key];
9795 $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour') : '');
9796 $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour', 'tzserver', $outputlangs) : '');
9797 $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_DAY_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'day', 'tzserver', $outputlangs) : '');
9798 $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhourrfc') : '');
9799 } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'phone') {
9800 $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = dol_print_phone($object->array_options['options_'.$key]);
9801 } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'price') {
9802 $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = $object->array_options['options_'.$key];
9803 $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_FORMATED__'] = price($object->array_options['options_'.$key]); // For compatibility
9804 $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_FORMATTED__'] = price($object->array_options['options_'.$key]);
9805 } elseif ($extrafields->attributes[$object->table_element]['type'][$key] != 'separator') {
9806 $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = !empty($object->array_options['options_'.$key]) ? $object->array_options['options_'.$key] : '';
9807 }
9808 }
9809 }
9810 }
9811 }
9812
9813 // Complete substitution array with the url to make online payment
9814 if (empty($substitutionarray['__REF__'])) {
9815 $paymenturl = '';
9816 } else {
9817 // Set the online payment url link into __ONLINE_PAYMENT_URL__ key
9818 require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
9819 $outputlangs->loadLangs(array('paypal', 'other'));
9820
9821 $amounttouse = 0;
9822 $typeforonlinepayment = 'free';
9823 if (is_object($object) && $object->element == 'commande') {
9824 $typeforonlinepayment = 'order';
9825 }
9826 if (is_object($object) && $object->element == 'facture') {
9827 $typeforonlinepayment = 'invoice';
9828 }
9829 if (is_object($object) && $object->element == 'member') {
9830 $typeforonlinepayment = 'member';
9831 if (!empty($object->last_subscription_amount)) {
9832 $amounttouse = $object->last_subscription_amount;
9833 }
9834 }
9835 if (is_object($object) && $object->element == 'contrat') {
9836 $typeforonlinepayment = 'contract';
9837 }
9838 if (is_object($object) && $object->element == 'fichinter') {
9839 $typeforonlinepayment = 'ficheinter';
9840 }
9841
9842 $url = getOnlinePaymentUrl(0, $typeforonlinepayment, $substitutionarray['__REF__'], $amounttouse);
9843 $paymenturl = $url;
9844 }
9845
9846 if ($object->id > 0) {
9847 $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = ($paymenturl ? str_replace('\n', "\n", $outputlangs->trans("PredefinedMailContentLink", $paymenturl)) : '');
9848 $substitutionarray['__ONLINE_PAYMENT_URL__'] = $paymenturl;
9849
9850 // Show structured communication
9851 if (getDolGlobalString('INVOICE_PAYMENT_ENABLE_STRUCTURED_COMMUNICATION') && $object->element == 'facture') {
9852 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions_be.lib.php';
9853 $substitutionarray['__PAYMENT_STRUCTURED_COMMUNICATION__'] = dolBECalculateStructuredCommunication($object->ref, $object->type);
9854 }
9855
9856 if (getDolGlobalString('PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD') && is_object($object) && $object->element == 'propal') {
9857 $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
9858 } else {
9859 $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = '';
9860 }
9861 if (getDolGlobalString('ORDER_ALLOW_EXTERNAL_DOWNLOAD') && is_object($object) && $object->element == 'commande') {
9862 $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = $object->getLastMainDocLink($object->element);
9863 } else {
9864 $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = '';
9865 }
9866 if (getDolGlobalString('INVOICE_ALLOW_EXTERNAL_DOWNLOAD') && is_object($object) && $object->element == 'facture') {
9867 $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = $object->getLastMainDocLink($object->element);
9868 } else {
9869 $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = '';
9870 }
9871 if (getDolGlobalString('CONTRACT_ALLOW_EXTERNAL_DOWNLOAD') && is_object($object) && $object->element == 'contrat') {
9872 $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = $object->getLastMainDocLink($object->element);
9873 } else {
9874 $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = '';
9875 }
9876 if (getDolGlobalString('FICHINTER_ALLOW_EXTERNAL_DOWNLOAD') && is_object($object) && $object->element == 'fichinter') {
9877 $substitutionarray['__DIRECTDOWNLOAD_URL_FICHINTER__'] = $object->getLastMainDocLink($object->element);
9878 } else {
9879 $substitutionarray['__DIRECTDOWNLOAD_URL_FICHINTER__'] = '';
9880 }
9881 if (getDolGlobalString('SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD') && is_object($object) && $object->element == 'supplier_proposal') {
9882 $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
9883 } else {
9884 $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = '';
9885 }
9886
9887 if (is_object($object) && $object->element == 'propal') {
9888 '@phan-var-force Propal $object';
9890 $substitutionarray['__URL_PROPOSAL__'] = DOL_MAIN_URL_ROOT."/comm/propal/card.php?id=".$object->id;
9891 require_once DOL_DOCUMENT_ROOT.'/core/lib/signature.lib.php';
9892 $substitutionarray['__ONLINE_SIGN_URL__'] = getOnlineSignatureUrl(0, 'proposal', $object->ref, 1, $object);
9893 }
9894 if (is_object($object) && $object->element == 'commande') {
9895 '@phan-var-force Commande $object';
9897 $substitutionarray['__URL_ORDER__'] = DOL_MAIN_URL_ROOT."/commande/card.php?id=".$object->id;
9898 }
9899 if (is_object($object) && $object->element == 'facture') {
9900 '@phan-var-force Facture $object';
9902 $substitutionarray['__URL_INVOICE__'] = DOL_MAIN_URL_ROOT."/compta/facture/card.php?id=".$object->id;
9903 }
9904 if (is_object($object) && $object->element == 'contrat') {
9905 '@phan-var-force Contrat $object';
9907 $substitutionarray['__URL_CONTRACT__'] = DOL_MAIN_URL_ROOT."/contrat/card.php?id=".$object->id;
9908 require_once DOL_DOCUMENT_ROOT.'/core/lib/signature.lib.php';
9909 $substitutionarray['__ONLINE_SIGN_URL__'] = getOnlineSignatureUrl(0, 'contract', $object->ref, 1, $object);
9910 }
9911 if (is_object($object) && $object->element == 'fichinter') {
9912 '@phan-var-force Fichinter $object';
9914 $substitutionarray['__URL_FICHINTER__'] = DOL_MAIN_URL_ROOT."/fichinter/card.php?id=".$object->id;
9915 require_once DOL_DOCUMENT_ROOT.'/core/lib/signature.lib.php';
9916 $substitutionarray['__ONLINE_SIGN_FICHINTER_URL__'] = getOnlineSignatureUrl(0, 'fichinter', $object->ref, 1, $object);
9917 }
9918 if (is_object($object) && $object->element == 'supplier_proposal') {
9919 '@phan-var-force SupplierProposal $object';
9921 $substitutionarray['__URL_SUPPLIER_PROPOSAL__'] = DOL_MAIN_URL_ROOT."/supplier_proposal/card.php?id=".$object->id;
9922 }
9923 if (is_object($object) && $object->element == 'invoice_supplier') {
9924 '@phan-var-force FactureFournisseur $object';
9926 $substitutionarray['__URL_SUPPLIER_INVOICE__'] = DOL_MAIN_URL_ROOT."/fourn/facture/card.php?id=".$object->id;
9927 }
9928 if (is_object($object) && $object->element == 'shipping') {
9929 '@phan-var-force Expedition $object';
9931 $substitutionarray['__URL_SHIPMENT__'] = DOL_MAIN_URL_ROOT."/expedition/card.php?id=".$object->id;
9932 }
9933 }
9934
9935 if (is_object($object) && $object->element == 'action') {
9936 '@phan-var-force ActionComm $object';
9938 $substitutionarray['__EVENT_LABEL__'] = $object->label;
9939 $substitutionarray['__EVENT_TYPE__'] = $outputlangs->trans("Action".$object->type_code);
9940 $substitutionarray['__EVENT_DATE__'] = dol_print_date($object->datep, 'day', 'auto', $outputlangs);
9941 $substitutionarray['__EVENT_TIME__'] = dol_print_date($object->datep, 'hour', 'auto', $outputlangs);
9942 }
9943 }
9944 }
9945 if ((empty($exclude) || !in_array('objectamount', $exclude)) && (empty($include) || in_array('objectamount', $include))) {
9946 '@phan-var-force Facture|FactureRec $object';
9948 include_once DOL_DOCUMENT_ROOT.'/core/lib/functionsnumtoword.lib.php';
9949
9950 $substitutionarray['__DATE_YMD__'] = is_object($object) ? (isset($object->date) ? dol_print_date($object->date, 'day', false, $outputlangs) : null) : '';
9951 $substitutionarray['__DATE_DUE_YMD__'] = is_object($object) ? (isset($object->date_lim_reglement) ? dol_print_date($object->date_lim_reglement, 'day', false, $outputlangs) : null) : '';
9952 $substitutionarray['__DATE_YMD_TEXT__'] = is_object($object) ? (isset($object->date) ? dol_print_date($object->date, 'daytext', false, $outputlangs) : null) : '';
9953 $substitutionarray['__DATE_DUE_YMD_TEXT__'] = is_object($object) ? (isset($object->date_lim_reglement) ? dol_print_date($object->date_lim_reglement, 'daytext', false, $outputlangs) : null) : '';
9954
9955 $already_payed_all = 0;
9956 if (is_object($object) && ($object instanceof Facture)) {
9957 $already_payed_all = $object->sumpayed + $object->sumdeposit + $object->sumcreditnote;
9958 }
9959
9960 $substitutionarray['__AMOUNT_EXCL_TAX__'] = is_object($object) ? $object->total_ht : '';
9961 $substitutionarray['__AMOUNT_EXCL_TAX_TEXT__'] = is_object($object) ? dol_convertToWord($object->total_ht, $outputlangs, '', true) : '';
9962 $substitutionarray['__AMOUNT_EXCL_TAX_TEXTCURRENCY__'] = is_object($object) ? dol_convertToWord($object->total_ht, $outputlangs, $conf->currency, true) : '';
9963
9964 $substitutionarray['__AMOUNT__'] = is_object($object) ? $object->total_ttc : '';
9965 $substitutionarray['__AMOUNT_TEXT__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, '', true) : '';
9966 $substitutionarray['__AMOUNT_TEXTCURRENCY__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, $conf->currency, true) : '';
9967
9968 $substitutionarray['__AMOUNT_REMAIN__'] = is_object($object) ? price2num($object->total_ttc - $already_payed_all, 'MT') : '';
9969
9970 $substitutionarray['__AMOUNT_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
9971 $substitutionarray['__AMOUNT_VAT_TEXT__'] = is_object($object) ? (isset($object->total_vat) ? dol_convertToWord($object->total_vat, $outputlangs, '', true) : dol_convertToWord($object->total_tva, $outputlangs, '', true)) : '';
9972 $substitutionarray['__AMOUNT_VAT_TEXTCURRENCY__'] = is_object($object) ? (isset($object->total_vat) ? dol_convertToWord($object->total_vat, $outputlangs, $conf->currency, true) : dol_convertToWord($object->total_tva, $outputlangs, $conf->currency, true)) : '';
9973
9974 if ($onlykey != 2 || $mysoc->useLocalTax(1)) {
9975 $substitutionarray['__AMOUNT_TAX2__'] = is_object($object) ? $object->total_localtax1 : '';
9976 }
9977 if ($onlykey != 2 || $mysoc->useLocalTax(2)) {
9978 $substitutionarray['__AMOUNT_TAX3__'] = is_object($object) ? $object->total_localtax2 : '';
9979 }
9980
9981 // Amount keys formatted in a currency
9982 $substitutionarray['__AMOUNT_EXCL_TAX_FORMATTED__'] = is_object($object) ? ($object->total_ht ? price($object->total_ht, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
9983 $substitutionarray['__AMOUNT_FORMATTED__'] = is_object($object) ? ($object->total_ttc ? price($object->total_ttc, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
9984 $substitutionarray['__AMOUNT_REMAIN_FORMATTED__'] = is_object($object) ? ($object->total_ttc ? price($object->total_ttc - $already_payed_all, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
9985 $substitutionarray['__AMOUNT_VAT_FORMATTED__'] = is_object($object) ? (isset($object->total_vat) ? price($object->total_vat, 0, $outputlangs, 0, -1, -1, $conf->currency) : ($object->total_tva ? price($object->total_tva, 0, $outputlangs, 0, -1, -1, $conf->currency) : null)) : '';
9986 if ($onlykey != 2 || $mysoc->useLocalTax(1)) {
9987 $substitutionarray['__AMOUNT_TAX2_FORMATTED__'] = is_object($object) ? ($object->total_localtax1 ? price($object->total_localtax1, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
9988 }
9989 if ($onlykey != 2 || $mysoc->useLocalTax(2)) {
9990 $substitutionarray['__AMOUNT_TAX3_FORMATTED__'] = is_object($object) ? ($object->total_localtax2 ? price($object->total_localtax2, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
9991 }
9992 // Amount keys formatted in a currency (with the typo error for backward compatibility)
9993 if ($onlykey != 2) {
9994 $substitutionarray['__AMOUNT_EXCL_TAX_FORMATED__'] = $substitutionarray['__AMOUNT_EXCL_TAX_FORMATTED__'];
9995 $substitutionarray['__AMOUNT_FORMATED__'] = $substitutionarray['__AMOUNT_FORMATTED__'];
9996 $substitutionarray['__AMOUNT_REMAIN_FORMATED__'] = $substitutionarray['__AMOUNT_REMAIN_FORMATTED__'];
9997 $substitutionarray['__AMOUNT_VAT_FORMATED__'] = $substitutionarray['__AMOUNT_VAT_FORMATTED__'];
9998 if ($mysoc instanceof Societe && $mysoc->useLocalTax(1)) {
9999 $substitutionarray['__AMOUNT_TAX2_FORMATED__'] = $substitutionarray['__AMOUNT_TAX2_FORMATTED__'];
10000 }
10001 if ($mysoc instanceof Societe && $mysoc->useLocalTax(2)) {
10002 $substitutionarray['__AMOUNT_TAX3_FORMATED__'] = $substitutionarray['__AMOUNT_TAX3_FORMATTED__'];
10003 }
10004 }
10005
10006 $substitutionarray['__AMOUNT_MULTICURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? $object->multicurrency_total_ttc : '';
10007 $substitutionarray['__AMOUNT_MULTICURRENCY_TEXT__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, '', true) : '';
10008 $substitutionarray['__AMOUNT_MULTICURRENCY_TEXTCURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, $object->multicurrency_code, true) : '';
10009 $substitutionarray['__MULTICURRENCY_CODE__'] = (is_object($object) && isset($object->multicurrency_code)) ? $object->multicurrency_code : '';
10010 // TODO Add other keys for foreign multicurrency
10011
10012 // For backward compatibility
10013 if ($onlykey != 2) {
10014 $substitutionarray['__TOTAL_TTC__'] = is_object($object) ? $object->total_ttc : '';
10015 $substitutionarray['__TOTAL_HT__'] = is_object($object) ? $object->total_ht : '';
10016 $substitutionarray['__TOTAL_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
10017 }
10018 }
10019
10020
10021 if ((empty($exclude) || !in_array('date', $exclude)) && (empty($include) || in_array('date', $include))) {
10022 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
10023
10024 $now = dol_now();
10025
10026 $tmp = dol_getdate($now, true);
10027 $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
10028 $tmp3 = dol_get_prev_month($tmp['mon'], $tmp['year']);
10029 $tmp4 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
10030 $tmp5 = dol_get_next_month($tmp['mon'], $tmp['year']);
10031
10032 $daytext = $outputlangs->trans('Day'.$tmp['wday']);
10033
10034 $substitutionarray = array_merge($substitutionarray, array(
10035 '__NOW_TMS__' => (string) $now, // Must be the string that represent the int
10036 '__NOW_TMS_YMD__' => dol_print_date($now, 'day', 'auto', $outputlangs),
10037 '__DAY__' => (string) $tmp['mday'],
10038 '__DAY_TEXT__' => $daytext, // Monday
10039 '__DAY_TEXT_SHORT__' => dol_trunc($daytext, 3, 'right', 'UTF-8', 1), // Mon
10040 '__DAY_TEXT_MIN__' => dol_trunc($daytext, 1, 'right', 'UTF-8', 1), // M
10041 '__MONTH__' => (string) $tmp['mon'],
10042 '__MONTH_TEXT__' => $outputlangs->trans('Month'.sprintf("%02d", $tmp['mon'])),
10043 '__MONTH_TEXT_SHORT__' => $outputlangs->trans('MonthShort'.sprintf("%02d", $tmp['mon'])),
10044 '__MONTH_TEXT_MIN__' => $outputlangs->trans('MonthVeryShort'.sprintf("%02d", $tmp['mon'])),
10045 '__YEAR__' => (string) $tmp['year'],
10046 '__YEAR_PREVIOUS_MONTH__' => (string) $tmp3['year'],
10047 '__YEAR_NEXT_MONTH__' => (string) $tmp5['year'],
10048 '__PREVIOUS_DAY__' => (string) $tmp2['day'],
10049 '__PREVIOUS_MONTH__' => (string) $tmp3['month'],
10050 '__PREVIOUS_MONTH_TEXT__' => $outputlangs->trans('Month'.sprintf("%02d", $tmp3['month'])),
10051 '__PREVIOUS_MONTH_TEXT_SHORT__' => $outputlangs->trans('MonthShort'.sprintf("%02d", $tmp3['month'])),
10052 '__PREVIOUS_MONTH_TEXT_MIN__' => $outputlangs->trans('MonthVeryShort'.sprintf("%02d", $tmp3['month'])),
10053 '__PREVIOUS_YEAR__' => (string) ($tmp['year'] - 1),
10054 '__NEXT_DAY__' => (string) $tmp4['day'],
10055 '__NEXT_MONTH__' => (string) $tmp5['month'],
10056 '__NEXT_MONTH_TEXT__' => $outputlangs->trans('Month'.sprintf("%02d", $tmp5['month'])),
10057 '__NEXT_MONTH_TEXT_SHORT__' => $outputlangs->trans('MonthShort'.sprintf("%02d", $tmp5['month'])),
10058 '__NEXT_MONTH_TEXT_MIN__' => $outputlangs->trans('MonthVeryShort'.sprintf("%02d", $tmp5['month'])),
10059 '__NEXT_YEAR__' => (string) ($tmp['year'] + 1),
10060 ));
10061 }
10062
10063 if (isModEnabled('multicompany')) {
10064 $substitutionarray = array_merge($substitutionarray, array('__ENTITY_ID__' => $conf->entity));
10065 }
10066 if ((empty($exclude) || !in_array('system', $exclude)) && (empty($include) || in_array('user', $include))) {
10067 $substitutionarray['__DOL_MAIN_URL_ROOT__'] = DOL_MAIN_URL_ROOT;
10068 $substitutionarray['__(AnyTranslationKey)__'] = $outputlangs->trans('TranslationOfKey');
10069 $substitutionarray['__(AnyTranslationKey|langfile)__'] = $outputlangs->trans('TranslationOfKey').' (load also language file before)';
10070 $substitutionarray['__[AnyConstantKey]__'] = $outputlangs->trans('ValueOfConstantKey');
10071 }
10072
10073 // Note: The lazyload variables are replaced only during the call by make_substitutions, and only if necessary
10074
10075 return $substitutionarray;
10076}
10077
10094function make_substitutions($text, $substitutionarray, $outputlangs = null, $converttextinhtmlifnecessary = 0)
10095{
10096 global $conf, $db, $langs;
10097
10098 if (!is_array($substitutionarray)) {
10099 return 'ErrorBadParameterSubstitutionArrayWhenCalling_make_substitutions';
10100 }
10101
10102 if (empty($outputlangs)) {
10103 $outputlangs = $langs;
10104 }
10105
10106 // Is initial text HTML or simple text ?
10107 $msgishtml = 0;
10108 if (dol_textishtml($text, 1)) {
10109 $msgishtml = 1;
10110 }
10111
10112 // Make substitution for language keys: __(AnyTranslationKey)__ or __(AnyTranslationKey|langfile)__
10113 if (is_object($outputlangs)) {
10114 $reg = array();
10115 while (preg_match('/__\‍(([^\‍)]+)\‍)__/', $text, $reg)) {
10116 // If key is __(TranslationKey|langfile)__, then force load of langfile.lang
10117 $tmp = explode('|', $reg[1]);
10118 if (!empty($tmp[1])) {
10119 $outputlangs->load($tmp[1]);
10120 }
10121
10122 $value = $outputlangs->transnoentitiesnoconv($reg[1]);
10123
10124 if (empty($converttextinhtmlifnecessary)) {
10125 // convert $newval into HTML is necessary
10126 $text = preg_replace('/__\‍('.preg_quote($reg[1], '/').'\‍)__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
10127 } else {
10128 if (! $msgishtml) {
10129 $valueishtml = dol_textishtml($value, 1);
10130 //var_dump("valueishtml=".$valueishtml);
10131
10132 if ($valueishtml) {
10133 $text = dol_htmlentitiesbr($text);
10134 $msgishtml = 1;
10135 }
10136 } else {
10137 $value = dol_nl2br((string) $value);
10138 }
10139
10140 $text = preg_replace('/__\‍('.preg_quote($reg[1], '/').'\‍)__/', $value, $text);
10141 }
10142 }
10143 }
10144
10145 // Make substitution for constant keys.
10146 // Must be after the substitution of translation, so if the text of translation contains a string __[xxx]__, it is also converted.
10147 $reg = array();
10148 while (preg_match('/__\[([^\]]+)\]__/', $text, $reg)) {
10149 $keyfound = $reg[1];
10150 if (isASecretKey($keyfound)) {
10151 $value = '*****forbidden*****';
10152 } else {
10153 $value = empty($conf->global->$keyfound) ? '' : $conf->global->$keyfound;
10154 }
10155
10156 if (empty($converttextinhtmlifnecessary)) {
10157 // convert $newval into HTML is necessary
10158 $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
10159 } else {
10160 if (! $msgishtml) {
10161 $valueishtml = dol_textishtml($value, 1);
10162
10163 if ($valueishtml) {
10164 $text = dol_htmlentitiesbr($text);
10165 $msgishtml = 1;
10166 }
10167 } else {
10168 $value = dol_nl2br((string) $value);
10169 }
10170
10171 $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $value, $text);
10172 }
10173 }
10174
10175 // Make substitution for array $substitutionarray
10176 foreach ($substitutionarray as $key => $value) {
10177 if (!isset($value)) {
10178 continue; // If value is null, it same than not having substitution key at all into array, we do not replace.
10179 }
10180
10181 if (($key == '__USER_SIGNATURE__' || $key == '__SENDEREMAIL_SIGNATURE__') && (getDolGlobalString('MAIN_MAIL_DO_NOT_USE_SIGN'))) {
10182 $value = ''; // Protection
10183 }
10184
10185 if (empty($converttextinhtmlifnecessary)) {
10186 $text = str_replace((string) $key, (string) $value, $text); // Cast to string is needed when value is 123.5 for example
10187 } else {
10188 if (! $msgishtml) {
10189 $valueishtml = dol_textishtml($value, 1);
10190
10191 if ($valueishtml) {
10192 $text = dol_htmlentitiesbr($text);
10193 $msgishtml = 1;
10194 }
10195 } else {
10196 $value = dol_nl2br((string) $value);
10197 }
10198 $text = str_replace((string) $key, (string) $value, $text); // Cast to string is needed 123.5 for example
10199 }
10200 }
10201
10202 // TODO Implement the lazyload substitution
10203 /*
10204 add a loop to scan $substitutionarray:
10205 For each key ending with '@lazyload', we extract the substitution key 'XXX' and we check inside the $text (the 1st parameter of make_substitutions), if the string XXX exists.
10206 If no, we don't need to make replacement, so we do nothing.
10207 If yes, we can make the substitution:
10208
10209 include_once $path;
10210 $tmpobj = new $class($db);
10211 $valuetouseforsubstitution = $tmpobj->$method($id, '__XXX__');
10212 And make the replacement of "__XXX__@lazyload" with $valuetouseforsubstitution
10213 */
10214 $memory_object_list = array();
10215 foreach ($substitutionarray as $key => $value) {
10216 $lazy_load_arr = array();
10217 if (preg_match('/(__[A-Z\_]+__)@lazyload$/', $key, $lazy_load_arr)) {
10218 if (isset($lazy_load_arr[1]) && !empty($lazy_load_arr[1])) {
10219 $key_to_substitute = $lazy_load_arr[1];
10220 if (preg_match('/' . preg_quote($key_to_substitute, '/') . '/', $text)) {
10221 $param_arr = explode(':', (string) $value);
10222 // path:class:method:id
10223 if (count($param_arr) == 4) {
10224 $path = $param_arr[0];
10225 $class = $param_arr[1];
10226 $method = $param_arr[2];
10227 $id = (int) $param_arr[3];
10228
10229 // load class file and init object list in memory
10230 if (!isset($memory_object_list[$class])) {
10231 if (dol_is_file(DOL_DOCUMENT_ROOT . $path)) {
10232 require_once DOL_DOCUMENT_ROOT . $path;
10233 if (class_exists($class)) {
10234 $memory_object_list[$class] = array(
10235 'list' => array(),
10236 );
10237 }
10238 }
10239 }
10240
10241 // fetch object and set substitution
10242 if (isset($memory_object_list[$class]) && isset($memory_object_list[$class]['list'])) {
10243 if (method_exists($class, $method)) {
10244 if (!isset($memory_object_list[$class]['list'][$id])) {
10245 $tmpobj = new $class($db);
10246 // @phan-suppress-next-line PhanPluginUnknownObjectMethodCall
10247 $valuetouseforsubstitution = $tmpobj->$method($id, $key_to_substitute);
10248 $memory_object_list[$class]['list'][$id] = $tmpobj;
10249 } else {
10250 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
10251 $tmpobj = $memory_object_list[$class]['list'][$id];
10252 // @phan-suppress-next-line PhanPluginUnknownObjectMethodCall
10253 $valuetouseforsubstitution = $tmpobj->$method($id, $key_to_substitute, true);
10254 }
10255
10256 $text = str_replace((string) $key_to_substitute, (string) $valuetouseforsubstitution, $text); // Cast to string in case value is 123.5 for example
10257 }
10258 }
10259 }
10260 }
10261 }
10262 }
10263 }
10264
10265 return $text;
10266}
10267
10280function complete_substitutions_array(&$substitutionarray, $outputlangs, $object = null, $parameters = null, $callfunc = "completesubstitutionarray")
10281{
10282 global $conf, $user;
10283
10284 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
10285
10286 // Note: substitution key for each extrafields, using key __EXTRA_XXX__ is already available into the getCommonSubstitutionArray used to build the substitution array.
10287
10288 // Check if there is external substitution to do, requested by plugins
10289 $dirsubstitutions = array_merge(array(), (array) $conf->modules_parts['substitutions']);
10290
10291 foreach ($dirsubstitutions as $reldir) {
10292 $dir = dol_buildpath($reldir, 0);
10293
10294 // Check if directory exists
10295 if (!dol_is_dir($dir)) {
10296 continue;
10297 }
10298
10299 $substitfiles = dol_dir_list($dir, 'files', 0, 'functions_');
10300 foreach ($substitfiles as $substitfile) {
10301 $reg = array();
10302 if (preg_match('/functions_(.*)\.lib\.php/i', $substitfile['name'], $reg)) {
10303 $module = $reg[1];
10304
10305 dol_syslog("Library ".$substitfile['name']." found into ".$dir);
10306 // Include the user's functions file
10307 require_once $dir.$substitfile['name'];
10308 // Call the user's function, and only if it is defined
10309 $function_name = $module."_".$callfunc;
10310 if (function_exists($function_name)) {
10311 $function_name($substitutionarray, $outputlangs, $object, $parameters);
10312 }
10313 }
10314 }
10315 }
10316 if (getDolGlobalString('ODT_ENABLE_ALL_TAGS_IN_SUBSTITUTIONS')) {
10317 // to list all tags in odt template
10318 $tags = '';
10319 foreach ($substitutionarray as $key => $value) {
10320 $tags .= '{'.$key.'} => '.$value."\n";
10321 }
10322 $substitutionarray = array_merge($substitutionarray, array('__ALL_TAGS__' => $tags));
10323 }
10324}
10325
10335function print_date_range($date_start, $date_end, $format = '', $outputlangs = null)
10336{
10337 print get_date_range($date_start, $date_end, $format, $outputlangs);
10338}
10339
10350function get_date_range($date_start, $date_end, $format = '', $outputlangs = null, $withparenthesis = 1)
10351{
10352 global $langs;
10353
10354 $out = '';
10355
10356 if (!is_object($outputlangs)) {
10357 $outputlangs = $langs;
10358 }
10359
10360 if ($date_start && $date_end) {
10361 $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFromTo', dol_print_date($date_start, $format, false, $outputlangs), dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
10362 }
10363 if ($date_start && !$date_end) {
10364 $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFrom', dol_print_date($date_start, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
10365 }
10366 if (!$date_start && $date_end) {
10367 $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateUntil', dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
10368 }
10369
10370 return $out;
10371}
10372
10381function dolGetFirstLastname($firstname, $lastname, $nameorder = -1)
10382{
10383 global $conf;
10384
10385 $ret = '';
10386 // If order not defined, we use the setup
10387 if ($nameorder < 0) {
10388 $nameorder = (!getDolGlobalString('MAIN_FIRSTNAME_NAME_POSITION') ? 1 : 0);
10389 }
10390 if ($nameorder == 1) {
10391 $ret .= $firstname;
10392 if ($firstname && $lastname) {
10393 $ret .= ' ';
10394 }
10395 $ret .= $lastname;
10396 } elseif ($nameorder == 2 || $nameorder == 3) {
10397 $ret .= $firstname;
10398 if (empty($ret) && $nameorder == 3) {
10399 $ret .= $lastname;
10400 }
10401 } else { // 0, 4 or 5
10402 $ret .= $lastname;
10403 if (empty($ret) && $nameorder == 5) {
10404 $ret .= $firstname;
10405 }
10406 if ($nameorder == 0) {
10407 if ($firstname && $lastname) {
10408 $ret .= ' ';
10409 }
10410 $ret .= $firstname;
10411 }
10412 }
10413 return $ret;
10414}
10415
10416
10429function setEventMessage($mesgs, $style = 'mesgs', $noduplicate = 0, $attop = 0)
10430{
10431 //dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING); This is not deprecated, it is used by setEventMessages function
10432 if (!is_array($mesgs)) {
10433 $mesgs = trim((string) $mesgs);
10434 // If mesgs is a not an empty string
10435 if ($mesgs) {
10436 if (!empty($noduplicate) && isset($_SESSION['dol_events'][$style]) && in_array($mesgs, $_SESSION['dol_events'][$style])) {
10437 return;
10438 }
10439 if ($attop) {
10440 array_unshift($_SESSION['dol_events'][$style], $mesgs);
10441 } else {
10442 $_SESSION['dol_events'][$style][] = $mesgs;
10443 }
10444 }
10445 } else {
10446 // If mesgs is an array
10447 foreach ($mesgs as $mesg) {
10448 $mesg = trim((string) $mesg);
10449 if ($mesg) {
10450 if (!empty($noduplicate) && isset($_SESSION['dol_events'][$style]) && in_array($mesg, $_SESSION['dol_events'][$style])) {
10451 return;
10452 }
10453 if ($attop) {
10454 array_unshift($_SESSION['dol_events'][$style], $mesgs);
10455 } else {
10456 $_SESSION['dol_events'][$style][] = $mesg;
10457 }
10458 }
10459 }
10460 }
10461}
10462
10476function setEventMessages($mesg, $mesgs, $style = 'mesgs', $messagekey = '', $noduplicate = 0, $attop = 0)
10477{
10478 if (empty($mesg) && empty($mesgs)) {
10479 dol_syslog("Try to add a message in stack, but value to add is empty message" . getCallerInfoString(), LOG_WARNING);
10480 } else {
10481 if ($messagekey) {
10482 // Complete message with a js link to set a cookie "DOLHIDEMESSAGE".$messagekey;
10483 // TODO
10484 $mesg .= '';
10485 }
10486 if (empty($messagekey) || empty($_COOKIE["DOLUSER_HIDEMESSAGE".$messagekey])) {
10487 if (!in_array((string) $style, array('mesgs', 'warnings', 'errors'))) {
10488 dol_print_error(null, 'Bad parameter style='.$style.' for setEventMessages');
10489 }
10490 if (empty($mesgs)) {
10491 setEventMessage((string) $mesg, $style, $noduplicate, $attop);
10492 } else {
10493 if (!empty($mesg) && !in_array($mesg, $mesgs)) {
10494 setEventMessage($mesg, $style, $noduplicate, $attop); // Add message string if not already into array
10495 }
10496 setEventMessage($mesgs, $style, $noduplicate, $attop);
10497 }
10498 }
10499 }
10500}
10501
10511function dol_htmloutput_events($disabledoutputofmessages = 0)
10512{
10513 // Show mesgs
10514 if (isset($_SESSION['dol_events']['mesgs'])) {
10515 if (empty($disabledoutputofmessages)) {
10516 dol_htmloutput_mesg('', $_SESSION['dol_events']['mesgs']);
10517 }
10518 unset($_SESSION['dol_events']['mesgs']);
10519 }
10520 // Show errors
10521 if (isset($_SESSION['dol_events']['errors'])) {
10522 if (empty($disabledoutputofmessages)) {
10523 dol_htmloutput_mesg('', $_SESSION['dol_events']['errors'], 'error');
10524 }
10525 unset($_SESSION['dol_events']['errors']);
10526 }
10527
10528 // Show warnings
10529 if (isset($_SESSION['dol_events']['warnings'])) {
10530 if (empty($disabledoutputofmessages)) {
10531 dol_htmloutput_mesg('', $_SESSION['dol_events']['warnings'], 'warning');
10532 }
10533 unset($_SESSION['dol_events']['warnings']);
10534 }
10535}
10536
10551function get_htmloutput_mesg($mesgstring = '', $mesgarray = [], $style = 'ok', $keepembedded = 0)
10552{
10553 global $conf, $langs;
10554
10555 $ret = 0;
10556 $return = '';
10557 $out = '';
10558 $divstart = $divend = '';
10559
10560 // If inline message with no format, we add it.
10561 if ((empty($conf->use_javascript_ajax) || getDolGlobalString('MAIN_DISABLE_JQUERY_JNOTIFY') || defined('DISABLE_JQUERY_JNOTIFY') || $keepembedded) && !preg_match('/<div class=".*">/i', $out)) {
10562 $divstart = '<div class="'.$style.' clearboth">';
10563 $divend = '</div>';
10564 }
10565
10566 if ((is_array($mesgarray) && count($mesgarray)) || $mesgstring) {
10567 $langs->load("errors");
10568 $out .= $divstart;
10569 if (is_array($mesgarray) && count($mesgarray)) {
10570 foreach ($mesgarray as $message) {
10571 $ret++;
10572 $out .= $langs->trans($message);
10573 if ($ret < count($mesgarray)) {
10574 $out .= "<br>\n";
10575 }
10576 }
10577 }
10578 if ($mesgstring) {
10579 $ret++;
10580 $out .= $langs->trans($mesgstring);
10581 }
10582 $out .= $divend;
10583 }
10584
10585 if ($out) {
10586 if (!empty($conf->use_javascript_ajax) && !getDolGlobalString('MAIN_DISABLE_JQUERY_JNOTIFY') && !defined('DISABLE_JQUERY_JNOTIFY') && empty($keepembedded)) {
10587 $return = '<script nonce="'.getNonce().'">
10588 $(document).ready(function() {
10589 /* jnotify(message, preset of message type, keepmessage) */
10590 $.jnotify("'.dol_escape_js($out).'", "'.($style == "ok" ? 3000 : $style).'", '.($style == "ok" ? "false" : "true").',{ remove: function (){} } );
10591 });
10592 </script>';
10593 } else {
10594 $return = $out;
10595 }
10596 }
10597
10598 return $return;
10599}
10600
10612function get_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
10613{
10614 return get_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
10615}
10616
10630function dol_htmloutput_mesg($mesgstring = '', $mesgarray = array(), $style = 'ok', $keepembedded = 0)
10631{
10632 if (empty($mesgstring) && (!is_array($mesgarray) || count($mesgarray) == 0)) {
10633 return;
10634 }
10635
10636 $iserror = 0;
10637 $iswarning = 0;
10638 if (is_array($mesgarray)) {
10639 foreach ($mesgarray as $val) {
10640 if ($val && preg_match('/class="error"/i', $val)) {
10641 $iserror++;
10642 break;
10643 }
10644 if ($val && preg_match('/class="warning"/i', $val)) {
10645 $iswarning++;
10646 break;
10647 }
10648 }
10649 } elseif ($mesgstring && preg_match('/class="error"/i', $mesgstring)) {
10650 $iserror++;
10651 } elseif ($mesgstring && preg_match('/class="warning"/i', $mesgstring)) {
10652 $iswarning++;
10653 }
10654 if ($style == 'error') {
10655 $iserror++;
10656 }
10657 if ($style == 'warning') {
10658 $iswarning++;
10659 }
10660
10661 if ($iserror || $iswarning) {
10662 // Remove div from texts
10663 $mesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $mesgstring);
10664 $mesgstring = preg_replace('/<div class="(error|warning)">/', '', $mesgstring);
10665 $mesgstring = preg_replace('/<\/div>/', '', $mesgstring);
10666 // Remove div from texts array
10667 if (is_array($mesgarray)) {
10668 $newmesgarray = array();
10669 foreach ($mesgarray as $val) {
10670 if (is_string($val)) {
10671 $tmpmesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $val);
10672 $tmpmesgstring = preg_replace('/<div class="(error|warning)">/', '', $tmpmesgstring);
10673 $tmpmesgstring = preg_replace('/<\/div>/', '', $tmpmesgstring);
10674 $newmesgarray[] = $tmpmesgstring;
10675 } else {
10676 dol_syslog("Error call of dol_htmloutput_mesg with an array with a value that is not a string", LOG_WARNING);
10677 }
10678 }
10679 $mesgarray = $newmesgarray;
10680 }
10681 print get_htmloutput_mesg($mesgstring, $mesgarray, ($iserror ? 'error' : 'warning'), $keepembedded);
10682 } else {
10683 print get_htmloutput_mesg($mesgstring, $mesgarray, 'ok', $keepembedded);
10684 }
10685}
10686
10698function dol_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
10699{
10700 dol_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
10701}
10702
10723function dol_sort_array(&$array, $index, $order = 'asc', $natsort = 0, $case_sensitive = 0, $keepindex = 0)
10724{
10725 // Clean parameters
10726 $order = strtolower($order);
10727
10728 if (is_array($array)) {
10729 $sizearray = count($array);
10730 if ($sizearray > 0) {
10731 $temp = array();
10732 foreach (array_keys($array) as $key) {
10733 if (is_object($array[$key])) {
10734 $temp[$key] = empty($array[$key]->$index) ? 0 : $array[$key]->$index;
10735 } else {
10736 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable,PhanTypeArraySuspicious,PhanTypeMismatchDimFetch
10737 $temp[$key] = empty($array[$key][$index]) ? 0 : $array[$key][$index];
10738 }
10739 if ($natsort == -1) {
10740 $temp[$key] = '___'.$temp[$key]; // We add a string at begin of value to force an alpha order when using asort.
10741 }
10742 }
10743
10744 if (empty($natsort) || $natsort == -1) {
10745 if ($order == 'asc') {
10746 asort($temp);
10747 } else {
10748 arsort($temp);
10749 }
10750 } else {
10751 if ($case_sensitive) {
10752 natsort($temp);
10753 } else {
10754 natcasesort($temp); // natecasesort is not sensible to case
10755 }
10756 if ($order != 'asc') {
10757 $temp = array_reverse($temp, true);
10758 }
10759 }
10760
10761 $sorted = array();
10762
10763 foreach (array_keys($temp) as $key) {
10764 (is_numeric($key) && empty($keepindex)) ? $sorted[] = $array[$key] : $sorted[$key] = $array[$key];
10765 }
10766
10767 return $sorted;
10768 }
10769 }
10770 return $array;
10771}
10772
10773
10781function utf8_check($str)
10782{
10783 $str = (string) $str; // Sometimes string is an int.
10784
10785 // We must use here a binary strlen function (so not dol_strlen)
10786 $strLength = strlen($str);
10787 for ($i = 0; $i < $strLength; $i++) {
10788 if (ord($str[$i]) < 0x80) {
10789 continue; // 0bbbbbbb
10790 } elseif ((ord($str[$i]) & 0xE0) == 0xC0) {
10791 $n = 1; // 110bbbbb
10792 } elseif ((ord($str[$i]) & 0xF0) == 0xE0) {
10793 $n = 2; // 1110bbbb
10794 } elseif ((ord($str[$i]) & 0xF8) == 0xF0) {
10795 $n = 3; // 11110bbb
10796 } elseif ((ord($str[$i]) & 0xFC) == 0xF8) {
10797 $n = 4; // 111110bb
10798 } elseif ((ord($str[$i]) & 0xFE) == 0xFC) {
10799 $n = 5; // 1111110b
10800 } else {
10801 return false; // Does not match any model
10802 }
10803 for ($j = 0; $j < $n; $j++) { // n bytes matching 10bbbbbb follow ?
10804 if ((++$i == strlen($str)) || ((ord($str[$i]) & 0xC0) != 0x80)) {
10805 return false;
10806 }
10807 }
10808 }
10809 return true;
10810}
10811
10819function utf8_valid($str)
10820{
10821 /* 2 other methods to test if string is utf8
10822 $validUTF8 = mb_check_encoding($messagetext, 'UTF-8');
10823 $validUTF8b = ! (false === mb_detect_encoding($messagetext, 'UTF-8', true));
10824 */
10825 return preg_match('//u', $str) ? true : false;
10826}
10827
10828
10835function ascii_check($str)
10836{
10837 if (function_exists('mb_check_encoding')) {
10838 //if (mb_detect_encoding($str, 'ASCII', true) return false;
10839 if (!mb_check_encoding($str, 'ASCII')) {
10840 return false;
10841 }
10842 } else {
10843 if (preg_match('/[^\x00-\x7f]/', $str)) {
10844 return false; // Contains a byte > 7f
10845 }
10846 }
10847
10848 return true;
10849}
10850
10851
10859function dol_osencode($str)
10860{
10861 $tmp = ini_get("unicode.filesystem_encoding");
10862 if (empty($tmp) && !empty($_SERVER["WINDIR"])) {
10863 $tmp = 'iso-8859-1'; // By default for windows
10864 }
10865 if (empty($tmp)) {
10866 $tmp = 'utf-8'; // By default for other
10867 }
10868 if (getDolGlobalString('MAIN_FILESYSTEM_ENCODING')) {
10869 $tmp = getDolGlobalString('MAIN_FILESYSTEM_ENCODING');
10870 }
10871
10872 if ($tmp == 'iso-8859-1') {
10873 return mb_convert_encoding($str, 'ISO-8859-1', 'UTF-8');
10874 }
10875 return $str;
10876}
10877
10878
10894function dol_getIdFromCode($db, $key, $tablename, $fieldkey = 'code', $fieldid = 'id', $entityfilter = 0, $filters = '', $useCache = true)
10895{
10896 global $conf;
10897
10898 // If key empty
10899 if ($key == '') {
10900 return 0;
10901 }
10902
10903 // Check in cache
10904 if ($useCache && isset($conf->cache['codeid'][$tablename][$key][$fieldid])) { // Can be defined to 0 or ''
10905 return $conf->cache['codeid'][$tablename][$key][$fieldid]; // Found in cache
10906 }
10907
10908 dol_syslog('dol_getIdFromCode (value for field '.$fieldid.' from key '.$key.' not found into cache)', LOG_DEBUG);
10909
10910 $sql = "SELECT ".$fieldid." as valuetoget";
10911 $sql .= " FROM ".MAIN_DB_PREFIX.$tablename;
10912 if ($fieldkey == 'id' || $fieldkey == 'rowid') {
10913 $sql .= " WHERE ".$fieldkey." = ".((int) $key);
10914 } else {
10915 $sql .= " WHERE ".$fieldkey." = '".$db->escape($key)."'";
10916 }
10917 if (!empty($entityfilter)) {
10918 $sql .= " AND entity IN (".getEntity($tablename).")";
10919 }
10920 if ($filters) {
10921 $sql .= $filters;
10922 }
10923
10924 $resql = $db->query($sql);
10925 if ($resql) {
10926 $obj = $db->fetch_object($resql);
10927 $valuetoget = '';
10928 if ($obj) {
10929 $valuetoget = $obj->valuetoget;
10930 $conf->cache['codeid'][$tablename][$key][$fieldid] = $valuetoget;
10931 } else {
10932 $conf->cache['codeid'][$tablename][$key][$fieldid] = '';
10933 }
10934 $db->free($resql);
10935
10936 return $valuetoget;
10937 } else {
10938 return -1;
10939 }
10940}
10941
10951function isStringVarMatching($var, $regextext, $matchrule = 1)
10952{
10953 if ($matchrule == 1) {
10954 if ($var == 'mainmenu') {
10955 global $mainmenu;
10956 return (preg_match('/^'.$regextext.'/', $mainmenu));
10957 } elseif ($var == 'leftmenu') {
10958 global $leftmenu;
10959 return (preg_match('/^'.$regextext.'/', $leftmenu));
10960 } else {
10961 return 'This variable is not accessible with dol_eval';
10962 }
10963 } else {
10964 return 'This value for matchrule is not implemented';
10965 }
10966}
10967
10968
10978function verifCond($strToEvaluate, $onlysimplestring = '1')
10979{
10980 //print $strToEvaluate."<br>\n";
10981 $rights = true;
10982 if (isset($strToEvaluate) && $strToEvaluate !== '') {
10983 //var_dump($strToEvaluate);
10984 //$rep = dol_eval($strToEvaluate, 1, 0, '1'); // to show the error
10985 $rep = dol_eval($strToEvaluate, 1, 1, $onlysimplestring); // The dol_eval() must contains all the "global $xxx;" for all variables $xxx found into the string condition
10986 $rights = (bool) $rep && (!is_string($rep) || strpos($rep, 'Bad string syntax to evaluate') === false);
10987 //var_dump($rights);
10988 }
10989 return $rights;
10990}
10991
11006function dol_eval($s, $returnvalue = 1, $hideerrors = 1, $onlysimplestring = '1')
11007{
11008 if ($returnvalue != 1) {
11009 dol_syslog("Use of dol_eval with parameter returnvalue = 0 is now forbidden. Please fix this", LOG_ERR);
11010 }
11011
11012 if (getDolGlobalString("MAIN_USE_DOL_EVAL_NEW")) {
11013 return dol_eval_new($s);
11014 } else {
11015 return dol_eval_standard($s, $returnvalue, $hideerrors, $onlysimplestring);
11016 }
11017}
11018
11028function dol_eval_new($s)
11029{
11030 // Only this global variables can be read by eval function and returned to caller
11031 global $conf, // Read of const is done with getDolGlobalString() but we need $conf->currency for example
11032 $db, $langs, $user, $website, $websitepage,
11033 $action, $mainmenu, $leftmenu,
11034 $mysoc,
11035 $objectoffield, // To allow the use of $objectoffield in computed fields
11036
11037 // Old variables used
11038 $object,
11039 $obj; // To get $obj used into list when dol_eval() is used for computed fields and $obj is not yet $object
11040
11041 // PHP < 7.4.0
11042 defined('T_COALESCE_EQUAL') || define('T_COALESCE_EQUAL', PHP_INT_MAX);
11043 defined('T_FN') || define('T_FN', PHP_INT_MAX);
11044
11045 // PHP < 8.0.0
11046 defined('T_ATTRIBUTE') || define('T_ATTRIBUTE', PHP_INT_MAX);
11047 defined('T_MATCH') || define('T_MATCH', PHP_INT_MAX);
11048 defined('T_NAME_FULLY_QUALIFIED') || define('T_NAME_FULLY_QUALIFIED', PHP_INT_MAX);
11049 defined('T_NAME_QUALIFIED') || define('T_NAME_QUALIFIED', PHP_INT_MAX);
11050 defined('T_NAME_RELATIVE') || define('T_NAME_RELATIVE', PHP_INT_MAX);
11051
11052 // PHP < 8.1.0
11053 defined('T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG') || define('T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG', PHP_INT_MAX);
11054 defined('T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG') || define('T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG', PHP_INT_MAX);
11055 defined('T_ENUM') || define('T_ENUM', PHP_INT_MAX);
11056 defined('T_READONLY') || define('T_READONLY', PHP_INT_MAX);
11057
11058 // PHP < 8.4.0
11059 defined('T_PRIVATE_SET') || define('T_PRIVATE_SET', PHP_INT_MAX);
11060 defined('T_PROTECTED_SET') || define('T_PROTECTED_SET', PHP_INT_MAX);
11061 defined('T_PUBLIC_SET') || define('T_PUBLIC_SET', PHP_INT_MAX);
11062
11063 $prohibited_token_ids = [
11064 /*
11065 * Prohibited int tokens
11066 */
11067
11068 // T_AND_EQUAL', 'T_ARRAY', 'T_ARRAY_CAST', 'T_AS',
11069 'T_ABSTRACT', 'T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG', 'T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG', 'T_ATTRIBUTE',
11070 // 'T_BOOLEAN_AND', 'T_BOOLEAN_OR', 'T_BOOL_CAST', 'T_BREAK',
11071 'T_BAD_CHARACTER',
11072 // 'T_CASE', 'T_CLASS_C', 'T_CLONE', 'T_COALESCE', 'T_COALESCE_EQUAL', 'T_COMMENT', 'T_CONCAT_EQUAL',
11073 // 'T_CONSTANT_ENCAPSED_STRING', 'T_CONTINUE', 'T_CURLY_OPEN',
11074 'T_CALLABLE', 'T_CATCH', 'T_CLASS', 'T_CLOSE_TAG', 'T_CONST',
11075 // 'T_DEC', 'T_DEFAULT', 'T_DIV_EQUAL', 'T_DNUMBER', 'T_DO', 'T_DOC_COMMENT',
11076 // 'T_DOLLAR_OPEN_CURLY_BRACES', 'T_DOUBLE_ARROW', 'T_DOUBLE_CAST', 'T_DOUBLE_COLON',
11077 'T_DECLARE', 'T_DIR',
11078 // 'T_ELLIPSIS', 'T_ELSE', 'T_ELSEIF', 'T_EMPTY', 'T_ENCAPSED_AND_WHITESPACE', 'T_ENDFOR',
11079 // 'T_ENDFOREACH', 'T_ENDIF', 'T_ENDSWITCH', 'T_ENDWHILE', 'T_END_HEREDOC',
11080 'T_ECHO', 'T_ENDDECLARE', 'T_ENUM', 'T_EVAL', 'T_EXIT', 'T_EXTENDS',
11081 // 'T_FOR', 'T_FOREACH',
11082 'T_FILE', 'T_FINAL', 'T_FINALLY', 'T_FN', 'T_FUNCTION', 'T_FUNC_C',
11083 'T_GLOBAL', 'T_GOTO',
11084 'T_HALT_COMPILER',
11085 // 'T_IF', 'T_INC', 'T_INLINE_HTML', 'T_INSTANCEOF', 'T_INT_CAST', 'T_ISSET', 'T_IS_EQUAL', 'T_IS_GREATER_OR_EQUAL',
11086 // 'T_IS_IDENTICAL', 'T_IS_NOT_EQUAL', 'T_IS_NOT_IDENTICAL', 'T_IS_SMALLER_OR_EQUAL',
11087 'T_IMPLEMENTS', 'T_INCLUDE', 'T_INCLUDE_ONCE', 'T_INSTEADOF', 'T_INTERFACE',
11088 // 'T_LIST', 'T_LNUMBER', 'T_LOGICAL_AND', 'T_LOGICAL_OR', 'T_LOGICAL_XOR',
11089 'T_LINE',
11090 // 'T_MINUS_EQUAL', 'T_MOD_EQUAL', 'T_MUL_EQUAL',
11091 'T_METHOD_C',
11092 // 'T_NEW',
11093 // 'T_NS_SEPARATOR', 'T_NUM_STRING',
11094 'T_NAMESPACE',
11095 // 'T_NAME_FULLY_QUALIFIED', 'T_NAME_QUALIFIED', 'T_NAME_RELATIVE', 'T_NS_C',
11096 // 'T_OBJECT_CAST', 'T_OBJECT_OPERATOR', 'T_OR_EQUAL',
11097 'T_OPEN_TAG', 'T_OPEN_TAG_WITH_ECHO',
11098 // 'T_PAAMAYIM_NEKUDOTAYIM', 'T_PLUS_EQUAL', 'T_POW', 'T_POW_EQUAL',
11099 'T_PRINT', 'T_PRIVATE', 'T_PROTECTED', 'T_PUBLIC',
11100 // 'T_PROPERTY_C',
11101 'T_READONLY', 'T_REQUIRE', 'T_REQUIRE_ONCE', 'T_RETURN',
11102 // 'T_SL', 'T_SL_EQUAL', 'T_SPACESHIP', 'T_SR', 'T_SR_EQUAL', 'T_START_HEREDOC', 'T_STATIC',
11103 // 'T_STRING', 'T_STRING_CAST', 'T_STRING_VARNAME', 'T_SWITCH',
11104 'T_STATIC',
11105 'T_THROW', 'T_TRAIT', 'T_TRAIT_C', 'T_TRY',
11106 'T_UNSET', 'T_UNSET_CAST', 'T_USE',
11107 // 'T_VARIABLE',
11108 'T_VAR',
11109 // 'T_WHILE', 'T_WHITESPACE',
11110 // 'T_XOR_EQUAL',
11111 // 'T_YIELD', 'T_YIELD_FROM',
11112
11113 /*
11114 * Prohibited string tokens
11115 */
11116 ';', '`',
11117 ];
11118
11119 $prohibited_variables = [
11120 '$_COOKIE', '$_ENV', '$_FILES', '$GLOBALS', '$_GET', '$_POST', '$_REQUEST', '$_SERVER', '$_SESSION',
11121 ];
11122
11123 $prohibited_functions = [
11124 // 'base64_decode', 'rawurldecode', 'urldecode', 'str_rot13', 'hex2bin', // I haven't managed to inject anything with these functions yet, can someone confirm?
11125 // 'get_defined_functions', 'get_defined_vars', 'get_defined_constants', 'get_declared_classes', // Should we really block the admin from viewing these lists?
11126 'override_function', 'session_id', 'session_create_id', 'session_regenerate_id',
11127 'call_user_func', 'call_user_func_array', // PREVENT calling forbidden functions
11128 'exec', 'passthru', 'shell_exec', 'system', 'proc_open', 'popen',
11129 'dol_eval', 'dol_eval_new', 'dol_eval_standard', 'dol_contctdesc', 'executeCLI', 'verifCond', 'GETPOST', // Native Dolibarr functions
11130 'create_function', 'assert', 'mb_ereg_replace', 'mb_eregi_replace', // function with eval capabilities
11131 'dol_compress_dir', 'dol_decode', 'dol_delete_file', 'dol_delete_dir', 'dol_delete_dir_recursive', 'dol_copy', 'archiveOrBackupFile', // more dolibarr functions
11132 'fopen', 'file_put_contents', 'fputs', 'fputscsv', 'fwrite', 'fpassthru', 'mkdir', 'rmdir', 'symlink', 'touch', 'unlink', 'umask', // PHP functions related to file operations
11133 'invoke', 'invokeArgs', // Method of ReflectionFunction to execute a function
11134 'filter_input', 'filter_input_array', 'GETPOST', // PREVENT CODE INJECTION
11135 ];
11136
11137 $prohibited_token_arrangements = [
11138 // Variable functions « $a( », « "$a"( », « 'FN_NAME'( », ('FN_NAME')()
11139 ' T_VARIABLE ( ', ' " ( ', ' \' ( ', ' T_CONSTANT_ENCAPSED_STRING ( ', ' ) ( ',
11140 ];
11141
11142 $tokens = token_get_all("<?php return {$s};", TOKEN_PARSE);
11143
11144 $tokens_arrangement = ' ';
11145
11146 for ($i = 2, $c = count($tokens) - 1; $i < $c; ++$i) { // ignore <?php return and ;
11147 if (is_array($tokens[$i])) {
11148 $token_id = $tokens[$i][0];
11149 $token_value = $tokens[$i][1];
11150 $token_name = token_name($tokens[$i][0]);
11151 } else {
11152 $token_id = $tokens[$i];
11153 $token_value = $tokens[$i];
11154 $token_name = $tokens[$i];
11155 }
11156
11157 // Ignore whitespaces
11158 if (T_WHITESPACE === $token_id) {
11159 continue;
11160 }
11161
11162 // Keep history to check arrangements
11163 $tokens_arrangement .= "{$token_name} ";
11164
11165 // Prohibited Variables
11166 if (T_VARIABLE === $token_id
11167 && in_array($token_value, $prohibited_variables, true)
11168 ) {
11169 return "« {$token_value} » is prohibited in « {$s} »";
11170 }
11171
11172 // Prohibited Functions
11173 if (T_STRING === $token_id
11174 && in_array($token_value, $prohibited_functions, true)
11175 ) {
11176 return "« {$token_value} » is prohibited in « {$s} »";
11177 }
11178 }
11179
11180 // Prohibited Token IDs
11181 $maxi = count($prohibited_token_ids);
11182 for ($i = 0; $i < $maxi; ++$i) {
11183 if (false !== strpos($tokens_arrangement, " {$prohibited_token_ids[$i]} ")) {
11184 return "« {$prohibited_token_ids[$i]} » is prohibited in « {$s} »";
11185 }
11186 }
11187
11188 // Prohibited token arrangements
11189 $maxi = count($prohibited_token_arrangements);
11190 for ($i = 0; $i < $maxi; ++$i) {
11191 if (false !== strpos($tokens_arrangement, $prohibited_token_arrangements[$i])) {
11192 return "« {$prohibited_token_arrangements[$i]} » is prohibited in « {$s} »";
11193 }
11194 }
11195
11196 // Return result
11197 try {
11198 return @eval("return {$s};") ?? '';
11199 } catch (Throwable $ex) {
11200 return "Exception during evaluation: ".$s." - ".$ex->getMessage();
11201 }
11202}
11203
11218function dol_eval_standard($s, $returnvalue = 1, $hideerrors = 1, $onlysimplestring = '1')
11219{
11220 // Only this global variables can be read by eval function and returned to caller
11221 global $conf; // Read of const is done with getDolGlobalString() but we need $conf->currency for example
11222 global $db, $langs, $user, $website, $websitepage;
11223 global $action, $mainmenu, $leftmenu;
11224 global $mysoc;
11225 global $objectoffield; // To allow the use of $objectoffield in computed fields
11226
11227 // Old variables used (deprecated)
11228 global $object;
11229 global $obj; // To get $obj used into list when dol_eval() is used for computed fields and $obj is not yet $object
11230
11231 $isObBufferActive = false; // When true, the ObBuffer must be cleaned in the exception handler
11232 if (!in_array($onlysimplestring, array('0', '1', '2'))) {
11233 return "Bad call of dol_eval. Parameter onlysimplestring must be '0' (deprecated), '1' or '2'";
11234 }
11235 if (!is_scalar($s)) {
11236 return "Bad call of dol_eval. First parameter must be a string, found ".var_export($s, true);
11237 }
11238
11239 try {
11240 // Test on dangerous char (used for RCE), we allow only characters to make PHP variable testing
11241 if ($onlysimplestring == '1' || $onlysimplestring == '2') {
11242 // We must accept with 1: '1 && getDolGlobalInt("doesnotexist1") && getDolGlobalString("MAIN_FEATURES_LEVEL")'
11243 // We must accept with 1: '$user->hasRight("cabinetmed", "read") && !$object->canvas=="patient@cabinetmed"'
11244 // We must accept with 2: (($reloadedobj = new Task($db)) && ($reloadedobj->fetchNoCompute($object->id) <= 99) && ($secondloadedobj = new Project($db)) && ($secondloadedobj->fetchNoCompute($reloadedobj->fk_project) > 0)) ? $secondloadedobj->ref : "Parent project not found"
11245
11246 // Check if there is dynamic call (first we check chars are all into a whitelist chars)
11247 $specialcharsallowed = '^$_+-.*>&|=!?():"\',/@';
11248 if ($onlysimplestring == '2') {
11249 $specialcharsallowed .= '<[]';
11250 }
11251 if (getDolGlobalString('MAIN_ALLOW_UNSECURED_SPECIAL_CHARS_IN_DOL_EVAL')) {
11252 $specialcharsallowed .= getDolGlobalString('MAIN_ALLOW_UNSECURED_SPECIAL_CHARS_IN_DOL_EVAL');
11253 }
11254 if (preg_match('/[^a-z0-9\s'.preg_quote($specialcharsallowed, '/').']/i', $s)) {
11255 if ($returnvalue) {
11256 return 'Bad string syntax to evaluate (found chars that are not chars for a simple one line clean eval string): '.$s;
11257 } else {
11258 dol_syslog('Bad string syntax to evaluate (found chars that are not chars for a simple one line clean eval string): '.$s, LOG_WARNING);
11259 return '';
11260 }
11261 }
11262
11263 // Check if we found a ? without a space before and after
11264 $tmps = str_replace(' ? ', '__XXX__', $s);
11265 if (strpos($tmps, '?') !== false) {
11266 if ($returnvalue) {
11267 return 'Bad string syntax to evaluate (The char ? can be used only with a space before and after): '.$s;
11268 } else {
11269 dol_syslog('Bad string syntax to evaluate (The char ? can be used only with a space before and after): '.$s, LOG_WARNING);
11270 return '';
11271 }
11272 }
11273
11274 // Check if there is a < or <= without spaces before/after
11275 if (preg_match('/<=?[^\s]/', $s)) {
11276 if ($returnvalue) {
11277 return 'Bad string syntax to evaluate (mode '.$onlysimplestring.', found a < or <= without space before and after): '.$s;
11278 } else {
11279 dol_syslog('Bad string syntax to evaluate (mode '.$onlysimplestring.', found a < or <= without space before and after): '.$s, LOG_WARNING);
11280 return '';
11281 }
11282 }
11283
11284 // Check if there is dynamic call (first we use black list patterns)
11285 if (preg_match('/\$[\w]*\s*\‍(/', $s)) {
11286 if ($returnvalue) {
11287 return 'Bad string syntax to evaluate (mode '.$onlysimplestring.', found a call using "$abc(" or "$abc (" instead of using the direct name of the function): '.$s;
11288 } else {
11289 dol_syslog('Bad string syntax to evaluate (mode '.$onlysimplestring.', found a call using "$abc(" or "$abc (" instead of using the direct name of the function): '.$s, LOG_WARNING);
11290 return '';
11291 }
11292 }
11293
11294 // Now we check if we try dynamic call
11295 // First we remove white list pattern of using parenthesis then testing if one open parenthesis exists
11296 $savescheck = '';
11297 $scheck = $s;
11298 while ($scheck && $savescheck != $scheck) {
11299 $savescheck = $scheck;
11300 $scheck = preg_replace('/->[a-zA-Z0-9_]+\‍(/', '->__METHOD__', $scheck); // accept parenthesis in '...->method(...'
11301 $scheck = preg_replace('/::[a-zA-Z0-9_]+\‍(/', '->__METHOD__', $scheck); // accept parenthesis in '...::method(...'
11302 $scheck = preg_replace('/^\‍(+/', '__PARENTHESIS__ ', $scheck); // accept parenthesis in '(...'. Must replace with "__PARENTHESIS__ with a space after "to allow following substitutions
11303 $scheck = preg_replace('/\&\&\s+\‍(/', '__ANDPARENTHESIS__ ', $scheck); // accept parenthesis in '&& ('. Must replace with "__PARENTHESIS__ with a space after" to allow following substitutions
11304 $scheck = preg_replace('/\|\|\s+\‍(/', '__ORPARENTHESIS__ ', $scheck); // accept parenthesis in '|| ('. Must replace with "__PARENTHESIS__ with a space after" to allow following substitutions
11305 $scheck = preg_replace('/^!?[a-zA-Z0-9_]+\‍(/', '__FUNCTION__', $scheck); // accept parenthesis in 'function(' and '!function('
11306 $scheck = preg_replace('/\s!?[a-zA-Z0-9_]+\‍(/', '__FUNCTION__', $scheck); // accept parenthesis in '... function(' and '... !function('
11307 $scheck = preg_replace('/^!\‍(/', '__NOTANDPARENTHESIS__', $scheck); // accept parenthesis in '!('
11308 $scheck = preg_replace('/\s!\‍(/', ' __NOTANDPARENTHESIS__', $scheck); // accept parenthesis in '... !('
11309 $scheck = preg_replace('/(\^|\')\‍(/', '__REGEXSTART__', $scheck); // To allow preg_match('/^(aaa|bbb)/'... or isStringVarMatching('leftmenu', '(aaa|bbb)')
11310 }
11311 //print 'scheck='.$scheck." : ".strpos($scheck, '(')."<br>\n";
11312
11313 // Now test if it remains 1 open parenthesis.
11314 if (strpos($scheck, '(') !== false) {
11315 if ($returnvalue) {
11316 return 'Bad string syntax to evaluate (mode '.$onlysimplestring.', found call of a function or method without using the direct name of the function): '.$s;
11317 } else {
11318 dol_syslog('Bad string syntax to evaluate (mode '.$onlysimplestring.', found call of a function or method without using the direct name of the function): '.$s, LOG_WARNING);
11319 return '';
11320 }
11321 }
11322
11323 // TODO
11324 // We can exclude $ char that are not in dol_eval global, so that are not:
11325 // $db, $langs, $leftmenu, $topmenu, $user, $langs, $objectoffield, $object, $obj, ...,
11326 }
11327 if ($s === 'Array') {
11328 if ($returnvalue) {
11329 return 'Bad string syntax to evaluate (value is Array): '.var_export($s, true);
11330 } else {
11331 dol_syslog('Bad string syntax to evaluate (value is Array): '.var_export($s, true), LOG_WARNING);
11332 return '';
11333 }
11334 }
11335
11336 if (!getDolGlobalString('MAIN_ALLOW_DOUBLE_COLON_IN_DOL_EVAL') && strpos($s, '::') !== false) {
11337 if ($returnvalue) {
11338 return 'Bad string syntax to evaluate (double : char is forbidden without setting MAIN_ALLOW_DOUBLE_COLON_IN_DOL_EVAL): '.$s;
11339 } else {
11340 dol_syslog('Bad string syntax to evaluate (double : char is forbidden without setting MAIN_ALLOW_DOUBLE_COLON_IN_DOL_EVAL): '.$s, LOG_WARNING);
11341 return '';
11342 }
11343 }
11344
11345 if (strpos($s, '`') !== false) {
11346 if ($returnvalue) {
11347 return 'Bad string syntax to evaluate (backtick char is forbidden): '.$s;
11348 } else {
11349 dol_syslog('Bad string syntax to evaluate (backtick char is forbidden): '.$s, LOG_WARNING);
11350 return '';
11351 }
11352 }
11353
11354 // Disallow also concat
11355 if (getDolGlobalString('MAIN_DISALLOW_STRING_OBFUSCATION_IN_DOL_EVAL')) {
11356 if (preg_match('/[^0-9]+\.[^0-9]+/', $s)) { // We refuse . if not between 2 numbers
11357 if ($returnvalue) {
11358 return 'Bad string syntax to evaluate (dot char is forbidden): '.$s;
11359 } else {
11360 dol_syslog('Bad string syntax to evaluate (dot char is forbidden): '.$s, LOG_WARNING);
11361 return '';
11362 }
11363 }
11364 }
11365
11366 // We block use of php exec or php file functions
11367 $forbiddenphpstrings = array('$$', '$_', '}[', ')(');
11368 $forbiddenphpstrings = array_merge($forbiddenphpstrings, array('_ENV', '_SESSION', '_COOKIE', '_GET', '_GLOBAL', '_POST', '_REQUEST', 'ReflectionFunction'));
11369
11370 // We list all forbidden function as keywords we don't want to see (we don't mind it if is "kewyord(" or just "keyword", we don't want "keyword" at all)
11371 // We must exclude all functions that allow to execute another function. This includes all function that has a parameter with type "callable" to avoid things
11372 // like we can do with array_map and its callable parameter: dol_eval('json_encode(array_map(implode("",["ex","ec"]), ["id"]))', 1, 1, '0')
11373 $forbiddenphpfunctions = array();
11374 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("override_function", "session_id", "session_create_id", "session_regenerate_id"));
11375 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("get_defined_functions", "get_defined_vars", "get_defined_constants", "get_declared_classes"));
11376 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("function", "call_user_func", "call_user_func_array"));
11377
11378 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("array_all", "array_any", "array_diff_ukey", "array_filter", "array_find", "array_find_key", "array_map", "array_reduce", "array_intersect_uassoc", "array_intersect_ukey", "array_walk", "array_walk_recursive"));
11379 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("usort", "uasort", "uksort", "preg_replace_callback", "preg_replace_callback_array", "header_register_callback"));
11380 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("error_log", "set_error_handler", "set_exception_handler", "libxml_set_external_entity_loader", "register_shutdown_function", "register_tick_function", "unregister_tick_function"));
11381 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("spl_autoload_register", "spl_autoload_unregister", "iterator_apply", "session_set_save_handler"));
11382 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("forward_static_call", "forward_static_call_array", "register_postsend_function"));
11383
11384 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("ob_start"));
11385
11386 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("require", "include", "require_once", "include_once"));
11387 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("exec", "passthru", "shell_exec", "system", "proc_open", "popen"));
11388 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("dol_eval", "dol_eval_new", "dol_eval_standard", "dol_concatdesc", "executeCLI", "verifCond", "GETPOST", "dolEncrypt", "dolDecrypt")); // native dolibarr functions
11389 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("eval", "create_function", "assert", "mb_ereg_replace")); // function with eval capabilities
11390 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("readline_completion_function", "readline_callback_handler_install"));
11391 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("dol_compress_dir", "dol_decode", "dol_dir_list", "dol_dir_list_in_database", "dol_delete_file", "dol_delete_dir", "dol_delete_dir_recursive", "dol_copy", "archiveOrBackupFile")); // more dolibarr functions
11392 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("chdir", "dir", "fopen", "file", "file_exists", "file_get_contents", "file_put_contents", "fget", "fgetc", "fgetcsv", "fputs", "fputscsv", "fpassthru", "fscanf", "fseek", "fwrite", "is_file", "is_dir", "is_link", "mkdir", "opendir", "rmdir", "scandir", "symlink", "touch", "unlink", "umask"));
11393 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("require", "include"));
11394 if (getDolGlobalString('MAIN_DISALLOW_STRING_OBFUSCATION_IN_DOL_EVAL')) { // We disabllow all function that allow to obfuscate the real name of a function
11395 // @phpcs:ignore
11396 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("base64"."_"."decode", "rawurl"."decode", "url"."decode", "str"."_rot13", "hex"."2bin")); // name of forbidden functions are split to avoid false positive
11397 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("dol_concatdesc")); // native dolibarr functions
11398 }
11399
11400 $forbiddenphpmethods = array('invoke', 'invokeArgs'); // Method of ReflectionFunction to execute a function
11401
11402 $forbiddenphpregex = 'global\s*\$';
11403 $forbiddenphpregex .= '|';
11404 $forbiddenphpregex .= '\b('.implode('|', $forbiddenphpfunctions).')\b';
11405
11406 $forbiddenphpmethodsregex = '->('.implode('|', $forbiddenphpmethods).')';
11407
11408 do {
11409 $oldstringtoclean = $s;
11410 $s = str_ireplace($forbiddenphpstrings, '__forbiddenstring__', $s);
11411 $s = preg_replace('/'.$forbiddenphpregex.'/i', '__forbiddenstring__', $s);
11412 $s = preg_replace('/'.$forbiddenphpmethodsregex.'/i', '__forbiddenstring__', $s);
11413 //$s = preg_replace('/\$[a-zA-Z0-9_\->\$]+\‍(/i', '', $s); // Remove $function( call and $mycall->mymethod(
11414 } while ($oldstringtoclean != $s);
11415
11416
11417 if (strpos($s, '__forbiddenstring__') !== false) {
11418 dol_syslog('Bad string syntax to evaluate: '.$s, LOG_WARNING);
11419 if ($returnvalue) {
11420 return 'Bad string syntax to evaluate: '.$s;
11421 } else {
11422 dol_syslog('Bad string syntax to evaluate: '.$s);
11423 return '';
11424 }
11425 }
11426
11427 //print $s."<br>\n";
11428 if ($returnvalue) {
11429 ob_start(); // An evaluation has no reason to output data
11430 $isObBufferActive = true;
11431 $tmps = $hideerrors ? @eval('return ' . $s . ';') : eval('return ' . $s . ';');
11432 $tmpo = ob_get_clean();
11433 $isObBufferActive = false;
11434 if ($tmpo) {
11435 print 'Bad string syntax to evaluate. Some data were output when it should not when evaluating: ' . $s;
11436 }
11437 return $tmps;
11438 } else {
11439 dol_syslog('Do not use anymore dol_eval with param returnvalue=0', LOG_WARNING);
11440 if ($hideerrors) {
11441 @eval($s);
11442 } else {
11443 eval($s);
11444 }
11445 return '';
11446 }
11447 } catch (Error $e) {
11448 if ($isObBufferActive) {
11449 // Clean up buffer which was left behind due to exception.
11450 $tmpo = ob_get_clean();
11451 $isObBufferActive = false;
11452 }
11453 $error = 'dol_eval try/catch error : ';
11454 $error .= $e->getMessage();
11455 dol_syslog($error, LOG_WARNING);
11456 if ($returnvalue) {
11457 return 'Exception during evaluation: '.$s;
11458 } else {
11459 return '';
11460 }
11461 }
11462}
11463
11471function dol_validElement($element)
11472{
11473 return (trim($element) != '');
11474}
11475
11484function picto_from_langcode($codelang, $moreatt = '', $notitlealt = 0)
11485{
11486 if (empty($codelang)) {
11487 return '';
11488 }
11489
11490 if ($codelang == 'auto') {
11491 return '<span class="fa fa-language"></span>';
11492 }
11493
11494 $langtocountryflag = array(
11495 'ar_AR' => '',
11496 'ca_ES' => 'catalonia',
11497 'da_DA' => 'dk',
11498 'fr_CA' => 'mq',
11499 'sv_SV' => 'se',
11500 'sw_SW' => 'unknown',
11501 'AQ' => 'unknown',
11502 'CW' => 'unknown',
11503 'IM' => 'unknown',
11504 'JE' => 'unknown',
11505 'MF' => 'unknown',
11506 'BL' => 'unknown',
11507 'SX' => 'unknown'
11508 );
11509
11510 if (isset($langtocountryflag[$codelang])) {
11511 $flagImage = $langtocountryflag[$codelang];
11512 } else {
11513 $tmparray = explode('_', $codelang);
11514 $flagImage = empty($tmparray[1]) ? $tmparray[0] : $tmparray[1];
11515 }
11516
11517 $morecss = '';
11518 $reg = array();
11519 if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
11520 $morecss = $reg[1];
11521 $moreatt = "";
11522 }
11523
11524 // return img_picto_common($codelang, 'flags/'.strtolower($flagImage).'.png', $moreatt, 0, $notitlealt);
11525 return '<span class="flag-sprite '.strtolower($flagImage).($morecss ? ' '.$morecss : '').'"'.($moreatt ? ' '.$moreatt : '').(!$notitlealt ? ' title="'.$codelang.'"' : '').'></span>';
11526}
11527
11535function getLanguageCodeFromCountryCode($countrycode)
11536{
11537 global $mysoc;
11538
11539 if (empty($countrycode)) {
11540 return null;
11541 }
11542
11543 if (strtoupper($countrycode) == 'MQ') {
11544 return 'fr_CA';
11545 }
11546 if (strtoupper($countrycode) == 'SE') {
11547 return 'sv_SE'; // se_SE is Sami/Sweden, and we want in priority sv_SE for SE country
11548 }
11549 if (strtoupper($countrycode) == 'CH') {
11550 if ($mysoc->country_code == 'FR') {
11551 return 'fr_CH';
11552 }
11553 if ($mysoc->country_code == 'DE') {
11554 return 'de_CH';
11555 }
11556 if ($mysoc->country_code == 'IT') {
11557 return 'it_CH';
11558 }
11559 }
11560
11561 // Locale list taken from:
11562 // http://stackoverflow.com/questions/3191664/
11563 // list-of-all-locales-and-their-short-codes
11564 $locales = array(
11565 'af-ZA',
11566 'am-ET',
11567 'ar-AE',
11568 'ar-BH',
11569 'ar-DZ',
11570 'ar-EG',
11571 'ar-IQ',
11572 'ar-JO',
11573 'ar-KW',
11574 'ar-LB',
11575 'ar-LY',
11576 'ar-MA',
11577 'ar-OM',
11578 'ar-QA',
11579 'ar-SA',
11580 'ar-SY',
11581 'ar-TN',
11582 'ar-YE',
11583 //'as-IN', // Moved after en-IN
11584 'ba-RU',
11585 'be-BY',
11586 'bg-BG',
11587 'bn-BD',
11588 //'bn-IN', // Moved after en-IN
11589 'bo-CN',
11590 'br-FR',
11591 'ca-ES',
11592 'co-FR',
11593 'cs-CZ',
11594 'cy-GB',
11595 'da-DK',
11596 'de-AT',
11597 'de-CH',
11598 'de-DE',
11599 'de-LI',
11600 'de-LU',
11601 'dv-MV',
11602 'el-GR',
11603 'en-AU',
11604 'en-BZ',
11605 'en-CA',
11606 'en-GB',
11607 'en-IE',
11608 'en-IN',
11609 'as-IN', // as-IN must be after en-IN (en in priority if country is IN)
11610 'bn-IN', // bn-IN must be after en-IN (en in priority if country is IN)
11611 'en-JM',
11612 'en-MY',
11613 'en-NZ',
11614 'en-PH',
11615 'en-SG',
11616 'en-TT',
11617 'en-US',
11618 'en-ZA',
11619 'en-ZW',
11620 'es-AR',
11621 'es-BO',
11622 'es-CL',
11623 'es-CO',
11624 'es-CR',
11625 'es-DO',
11626 'es-EC',
11627 'es-ES',
11628 'es-GT',
11629 'es-HN',
11630 'es-MX',
11631 'es-NI',
11632 'es-PA',
11633 'es-PE',
11634 'es-PR',
11635 'es-PY',
11636 'es-SV',
11637 'es-US',
11638 'es-UY',
11639 'es-VE',
11640 'et-EE',
11641 'eu-ES',
11642 'fa-IR',
11643 'fi-FI',
11644 'fo-FO',
11645 'fr-BE',
11646 'fr-CA',
11647 'fr-CH',
11648 'fr-FR',
11649 'fr-LU',
11650 'fr-MC',
11651 'fy-NL',
11652 'ga-IE',
11653 'gd-GB',
11654 'gl-ES',
11655 'gu-IN',
11656 'he-IL',
11657 'hi-IN',
11658 'hr-BA',
11659 'hr-HR',
11660 'hu-HU',
11661 'hy-AM',
11662 'id-ID',
11663 'ig-NG',
11664 'ii-CN',
11665 'is-IS',
11666 'it-CH',
11667 'it-IT',
11668 'ja-JP',
11669 'ka-GE',
11670 'kk-KZ',
11671 'kl-GL',
11672 'km-KH',
11673 'kn-IN',
11674 'ko-KR',
11675 'ky-KG',
11676 'lb-LU',
11677 'lo-LA',
11678 'lt-LT',
11679 'lv-LV',
11680 'mi-NZ',
11681 'mk-MK',
11682 'ml-IN',
11683 'mn-MN',
11684 'mr-IN',
11685 'ms-BN',
11686 'ms-MY',
11687 'mt-MT',
11688 'nb-NO',
11689 'ne-NP',
11690 'nl-BE',
11691 'nl-NL',
11692 'nn-NO',
11693 'oc-FR',
11694 'or-IN',
11695 'pa-IN',
11696 'pl-PL',
11697 'ps-AF',
11698 'pt-BR',
11699 'pt-PT',
11700 'rm-CH',
11701 'ro-MD',
11702 'ro-RO',
11703 'ru-RU',
11704 'rw-RW',
11705 'sa-IN',
11706 'se-FI',
11707 'se-NO',
11708 'se-SE',
11709 'si-LK',
11710 'sk-SK',
11711 'sl-SI',
11712 'sq-AL',
11713 'sv-FI',
11714 'sv-SE',
11715 'sw-KE',
11716 'ta-IN',
11717 'te-IN',
11718 'th-TH',
11719 'tk-TM',
11720 'tn-ZA',
11721 'tr-TR',
11722 'tt-RU',
11723 'ug-CN',
11724 'uk-UA',
11725 'ur-PK',
11726 'vi-VN',
11727 'wo-SN',
11728 'xh-ZA',
11729 'yo-NG',
11730 'zh-CN',
11731 'zh-HK',
11732 'zh-MO',
11733 'zh-SG',
11734 'zh-TW',
11735 'zu-ZA',
11736 );
11737
11738 $buildprimarykeytotest = strtolower($countrycode).'-'.strtoupper($countrycode);
11739 if (in_array($buildprimarykeytotest, $locales)) {
11740 return strtolower($countrycode).'_'.strtoupper($countrycode);
11741 }
11742
11743 if (function_exists('locale_get_primary_language') && function_exists('locale_get_region')) { // Need extension php-intl
11744 foreach ($locales as $locale) {
11745 $locale_language = locale_get_primary_language($locale);
11746 $locale_region = locale_get_region($locale);
11747 if (strtoupper($countrycode) == $locale_region) {
11748 //var_dump($locale.' - '.$locale_language.' - '.$locale_region);
11749 return strtolower($locale_language).'_'.strtoupper($locale_region);
11750 }
11751 }
11752 } else {
11753 dol_syslog("Warning Extension php-intl is not available", LOG_WARNING);
11754 }
11755
11756 return null;
11757}
11758
11789function complete_head_from_modules($conf, $langs, $object, &$head, &$h, $type, $mode = 'add', $filterorigmodule = '')
11790{
11791 global $hookmanager, $db;
11792
11793 if (isset($conf->modules_parts['tabs'][$type]) && is_array($conf->modules_parts['tabs'][$type])) {
11794 foreach ($conf->modules_parts['tabs'][$type] as $value) {
11795 $values = explode(':', $value);
11796
11797 $reg = array();
11798 if ($mode == 'add' && !preg_match('/^\-/', $values[1])) {
11799 $newtab = array();
11800 $postab = $h;
11801 // detect if position set in $values[1] ie : +(2)mytab@mymodule (first tab is 0, second is one, ...)
11802 $str = $values[1];
11803 $posstart = strpos($str, '(');
11804 if ($posstart > 0) {
11805 $posend = strpos($str, ')');
11806 if ($posstart > 0) {
11807 $res1 = substr($str, $posstart + 1, $posend - $posstart - 1);
11808 if (is_numeric($res1)) {
11809 $postab = (int) $res1;
11810 $values[1] = '+' . substr($str, $posend + 1);
11811 }
11812 }
11813 }
11814 if (count($values) == 6) {
11815 // new declaration with permissions:
11816 // $value='objecttype:+tabname1:Title1:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
11817 // $value='objecttype:+tabname1:Title1,class,pathfile,method:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
11818 if ($values[0] != $type) {
11819 continue;
11820 }
11821
11822 if (verifCond($values[4], '2')) {
11823 if ($values[3]) {
11824 if ($filterorigmodule) { // If a filter of module origin has been requested
11825 if (strpos($values[3], '@')) { // This is an external module
11826 if ($filterorigmodule != 'external') {
11827 continue;
11828 }
11829 } else { // This looks a core module
11830 if ($filterorigmodule != 'core') {
11831 continue;
11832 }
11833 }
11834 }
11835 $langs->load($values[3]);
11836 }
11837 if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
11838 // If label is "SUBSTITUION_..."
11839 $substitutionarray = array();
11840 complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey' => $values[2]));
11841 $label = make_substitutions($reg[1], $substitutionarray);
11842 } else {
11843 // If label is "Label,Class,File,Method", we call the method to show content inside the badge
11844 $labeltemp = explode(',', $values[2]);
11845 $label = $langs->trans($labeltemp[0]);
11846
11847 if (!empty($labeltemp[1]) && is_object($object) && !empty($object->id)) {
11848 dol_include_once($labeltemp[2]);
11849 $classtoload = $labeltemp[1];
11850 if (class_exists($classtoload)) {
11851 $obj = new $classtoload($db);
11852 $function = $labeltemp[3];
11853 if ($obj && $function && method_exists($obj, $function)) {
11854 // @phan-suppress-next-line PhanPluginUnknownObjectMethodCall
11855 $nbrec = $obj->$function($object->id, $obj);
11856 if (!empty($nbrec)) {
11857 $label .= '<span class="badge marginleftonlyshort">'.$nbrec.'</span>';
11858 }
11859 }
11860 }
11861 }
11862 }
11863
11864 $newtab[0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[5]), 1);
11865 $newtab[1] = $label;
11866 $newtab[2] = str_replace('+', '', $values[1]);
11867 $h++;
11868 } else {
11869 continue;
11870 }
11871 } elseif (count($values) == 5) { // case deprecated
11872 dol_syslog('Passing 5 values in tabs module_parts is deprecated. Please update to 6 with permissions.', LOG_WARNING);
11873
11874 if ($values[0] != $type) {
11875 continue;
11876 }
11877 if ($values[3]) {
11878 if ($filterorigmodule) { // If a filter of module origin has been requested
11879 if (strpos($values[3], '@')) { // This is an external module
11880 if ($filterorigmodule != 'external') {
11881 continue;
11882 }
11883 } else { // This looks a core module
11884 if ($filterorigmodule != 'core') {
11885 continue;
11886 }
11887 }
11888 }
11889 $langs->load($values[3]);
11890 }
11891 if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
11892 $substitutionarray = array();
11893 complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey' => $values[2]));
11894 $label = make_substitutions($reg[1], $substitutionarray);
11895 } else {
11896 $label = $langs->trans($values[2]);
11897 }
11898
11899 $newtab[0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[4]), 1);
11900 $newtab[1] = $label;
11901 $newtab[2] = str_replace('+', '', $values[1]);
11902 $h++;
11903 }
11904 // set tab at its position
11905 $head = array_merge(array_slice($head, 0, $postab), array($newtab), array_slice($head, $postab));
11906 } elseif ($mode == 'remove' && preg_match('/^\-/', $values[1])) {
11907 if ($values[0] != $type) {
11908 continue;
11909 }
11910 $tabname = str_replace('-', '', $values[1]);
11911 foreach ($head as $key => $val) {
11912 $condition = (!empty($values[3]) ? verifCond($values[3], '2') : 1);
11913 //var_dump($key.' - '.$tabname.' - '.$head[$key][2].' - '.$values[3].' - '.$condition);
11914 if ($head[$key][2] == $tabname && $condition) {
11915 unset($head[$key]);
11916 break;
11917 }
11918 }
11919 }
11920 }
11921 }
11922
11923 // No need to make a return $head. Var is modified as a reference
11924 if (!empty($hookmanager)) {
11925 $parameters = array('object' => $object, 'mode' => $mode, 'head' => &$head, 'filterorigmodule' => $filterorigmodule);
11926 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable
11927 $reshook = $hookmanager->executeHooks('completeTabsHead', $parameters, $object);
11928 if ($reshook > 0) { // Hook ask to replace completely the array
11929 $head = $hookmanager->resArray;
11930 } else { // Hook
11931 $head = array_merge($head, $hookmanager->resArray);
11932 }
11933 $h = count($head);
11934 }
11935}
11936
11948function printCommonFooter($zone = 'private')
11949{
11950 global $conf, $hookmanager, $user, $langs;
11951 global $debugbar;
11952 global $action;
11953 global $micro_start_time;
11954
11955 if ($zone == 'private') {
11956 print "\n".'<!-- Common footer for private page -->'."\n";
11957 } else {
11958 print "\n".'<!-- Common footer for public page -->'."\n";
11959 }
11960
11961 // A div to store page_y POST parameter so we can read it using javascript
11962 print "\n<!-- A div to store page_y POST parameter -->\n";
11963 print '<div id="page_y" style="display: none;">'.(GETPOST('page_y') ? GETPOST('page_y') : '').'</div>'."\n";
11964
11965 $parameters = array();
11966 $reshook = $hookmanager->executeHooks('printCommonFooter', $parameters); // Note that $action and $object may have been modified by some hooks
11967 if (empty($reshook)) {
11968 if (getDolGlobalString('MAIN_HTML_FOOTER')) {
11969 print getDolGlobalString('MAIN_HTML_FOOTER') . "\n";
11970 }
11971
11972 print "\n";
11973 if (!empty($conf->use_javascript_ajax)) {
11974 print "\n<!-- A script section to add menuhider handler on backoffice, manage focus and mandatory fields, tuning info, ... -->\n";
11975 print '<script>'."\n";
11976 print 'jQuery(document).ready(function() {'."\n";
11977
11978 if ($zone == 'private' && empty($conf->dol_use_jmobile)) {
11979 print "\n";
11980 print '/* JS CODE TO ENABLE to manage handler to switch left menu page (menuhider) */'."\n";
11981 print 'jQuery("li.menuhider").click(function(event) {';
11982 print ' if (!$( "body" ).hasClass( "sidebar-collapse" )){ event.preventDefault(); }'."\n";
11983 print ' console.log("We click on .menuhider");'."\n";
11984 print ' $("body").toggleClass("sidebar-collapse")'."\n";
11985 print '});'."\n";
11986 }
11987
11988 // Management of focus and mandatory for fields
11989 if ($action == 'create' || $action == 'add' || $action == 'edit' || (empty($action) && (preg_match('/new\.php/', $_SERVER["PHP_SELF"]))) || ((empty($action) || $action == 'addline') && (preg_match('/card\.php/', $_SERVER["PHP_SELF"])))) {
11990 print '/* JS CODE TO ENABLE to manage focus and mandatory form fields */'."\n";
11991 $relativepathstring = $_SERVER["PHP_SELF"];
11992 // Clean $relativepathstring
11993 if (constant('DOL_URL_ROOT')) {
11994 $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
11995 }
11996 $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
11997 $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
11998 //$tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
11999
12000 if (!empty($user->default_values[$relativepathstring]['focus'])) {
12001 foreach ($user->default_values[$relativepathstring]['focus'] as $defkey => $defval) {
12002 $qualified = 0;
12003 if ($defkey != '_noquery_') {
12004 $tmpqueryarraytohave = explode('&', $defkey);
12005 $foundintru = 0;
12006 foreach ($tmpqueryarraytohave as $tmpquerytohave) {
12007 $tmpquerytohaveparam = explode('=', $tmpquerytohave);
12008 //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
12009 if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) {
12010 $foundintru = 1;
12011 }
12012 }
12013 if (!$foundintru) {
12014 $qualified = 1;
12015 }
12016 //var_dump($defkey.'-'.$qualified);
12017 } else {
12018 $qualified = 1;
12019 }
12020
12021 if ($qualified) {
12022 print 'console.log("set the focus by executing jQuery(...).focus();")'."\n";
12023 foreach ($defval as $paramkey => $paramval) {
12024 // Set focus on field
12025 print 'jQuery("input[name=\''.$paramkey.'\']").focus();'."\n";
12026 print 'jQuery("textarea[name=\''.$paramkey.'\']").focus();'."\n"; // TODO KO with ckeditor
12027 print 'jQuery("select[name=\''.$paramkey.'\']").focus();'."\n"; // Not really useful, but we keep it in case of.
12028 }
12029 }
12030 }
12031 }
12032 if (!empty($user->default_values[$relativepathstring]['mandatory'])) {
12033 foreach ($user->default_values[$relativepathstring]['mandatory'] as $defkey => $defval) {
12034 $qualified = 0;
12035 if ($defkey != '_noquery_') {
12036 $tmpqueryarraytohave = explode('&', $defkey);
12037 $foundintru = 0;
12038 foreach ($tmpqueryarraytohave as $tmpquerytohave) {
12039 $tmpquerytohaveparam = explode('=', $tmpquerytohave);
12040 //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
12041 if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) {
12042 $foundintru = 1;
12043 }
12044 }
12045 if (!$foundintru) {
12046 $qualified = 1;
12047 }
12048 //var_dump($defkey.'-'.$qualified);
12049 } else {
12050 $qualified = 1;
12051 }
12052
12053 if ($qualified) {
12054 print 'console.log("set the js code to manage fields that are set as mandatory");'."\n";
12055
12056 foreach ($defval as $paramkey => $paramval) {
12057 // Solution 1: Add handler on submit to check if mandatory fields are empty
12058 print 'var form = $(\'[name="'.dol_escape_js($paramkey).'"]\').closest("form");'."\n";
12059 print "form.on('submit', function(event) {
12060 var submitter = \$(this).find(':submit:focus').get(0);
12061 var buttonName = submitter ? \$(submitter).attr('name') : 'save';
12062
12063 if (buttonName == 'cancel') {
12064 console.log('We click on cancel button so we accept submit with no need to check mandatory fields');
12065 return true;
12066 }
12067
12068 console.log('We did not click on cancel button but on something else, we check that field [name=".dol_escape_js($paramkey)."] is not empty');
12069
12070 var tmpvalue = jQuery('[name=\"".dol_escape_js($paramkey)."\"]').val();
12071 let tmptypefield = jQuery('[name=\"".dol_escape_js($paramkey)."\"]').prop('nodeName').toLowerCase(); // Get the tag name (div, section, footer...)
12072
12073 if (tmptypefield == 'textarea') {
12074 // We must instead check the content of ckeditor
12075 var tmpeditor = (typeof CKEDITOR !== 'undefined') ? CKEDITOR.instances['".dol_escape_js($paramkey)."'] : null;
12076 if (tmpeditor) {
12077 tmpvalue = tmpeditor.getData();
12078 console.log('For textarea tmpvalue is '+tmpvalue);
12079 }
12080 }
12081
12082 let tmpvalueisempty = false;
12083 if (tmpvalue === null || tmpvalue === undefined || tmpvalue === '' || tmpvalue === -1 || tmpvalue === '-1') {
12084 tmpvalueisempty = true;
12085 }
12086 if (tmpvalue === '0' && (tmptypefield == 'select' || tmptypefield == 'input')) {
12087 tmpvalueisempty = true;
12088 }
12089 if (tmpvalueisempty && buttonName !== 'cancel') {
12090 console.log('field has type '+tmptypefield+' and is empty, we cancel the submit');
12091 event.preventDefault(); // Stop submission of form to allow custom code to decide.
12092 event.stopPropagation(); // Stop other handlers.
12093
12094 alert('".dol_escape_js($langs->transnoentitiesnoconv("ErrorFieldRequired", $paramkey).' ('.$langs->transnoentitiesnoconv("CustomMandatoryFieldRule").')')."');
12095
12096 return false;
12097 }
12098 console.log('field has type '+tmptypefield+' and is defined to '+tmpvalue);
12099 return true;
12100 });
12101 \n";
12102
12103 // Solution 2: Add property 'required' on input
12104 // so browser will check value and try to focus on it when submitting the form.
12105 //print 'setTimeout(function() {'; // If we want to wait that ckeditor beuatifier has finished its job.
12106 //print 'jQuery("input[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
12107 //print 'jQuery("textarea[id=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
12108 //print 'jQuery("select[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";*/
12109 //print '// required on a select works only if key is "", so we add the required attributes but also we reset the key -1 or 0 to an empty string'."\n";
12110 //print 'jQuery("select[name=\''.$paramkey.'\'] option[value=\'-1\']").prop(\'value\', \'\');'."\n";
12111 //print 'jQuery("select[name=\''.$paramkey.'\'] option[value=\'0\']").prop(\'value\', \'\');'."\n";
12112 // Add 'field required' class on closest td for all input elements : input, textarea and select
12113 //print '}, 500);'; // 500 milliseconds delay
12114
12115 // Now set the class "fieldrequired"
12116 print 'jQuery(\':input[name="' . dol_escape_js($paramkey) . '"]\').closest("tr").find("td:first").addClass("fieldrequired");'."\n";
12117 }
12118
12119 // If we submit using the cancel button, we remove the required attributes
12120 print 'jQuery("input[name=\'cancel\']").click(function() {
12121 console.log("We click on cancel button so removed all required attribute");
12122 jQuery("input, textarea, select").each(function(){this.removeAttribute(\'required\');});
12123 });'."\n";
12124 }
12125 }
12126 }
12127 }
12128
12129 print '});'."\n";
12130
12131 // End of tuning
12132 if (!empty($_SERVER['MAIN_SHOW_TUNING_INFO']) || getDolGlobalString('MAIN_SHOW_TUNING_INFO')) {
12133 print "\n";
12134 print "/* JS CODE TO ENABLE to add memory info */\n";
12135 print 'window.console && console.log("';
12136 if (getDolGlobalString('MEMCACHED_SERVER')) {
12137 print 'MEMCACHED_SERVER=' . getDolGlobalString('MEMCACHED_SERVER').' - ';
12138 }
12139 print 'MAIN_OPTIMIZE_SPEED=' . getDolGlobalString('MAIN_OPTIMIZE_SPEED', 'off');
12140 if (!empty($micro_start_time)) { // Works only if MAIN_SHOW_TUNING_INFO is defined at $_SERVER level. Not in global variable.
12141 $micro_end_time = microtime(true);
12142 print ' - Build time: '.ceil(1000 * ($micro_end_time - $micro_start_time)).' ms';
12143 }
12144
12145 if (function_exists("memory_get_usage")) {
12146 print ' - Mem: '.memory_get_usage(); // Do not use true here, it seems it takes the peak amount
12147 }
12148 if (function_exists("memory_get_peak_usage")) {
12149 print ' - Real mem peak: '.memory_get_peak_usage(true);
12150 }
12151 if (function_exists("zend_loader_file_encoded")) {
12152 print ' - Zend encoded file: '.(zend_loader_file_encoded() ? 'yes' : 'no');
12153 }
12154 print '");'."\n";
12155 }
12156
12157 print "\n".'</script>'."\n";
12158
12159 // Google Analytics
12160 // TODO Add a hook here
12161 if (isModEnabled('google') && getDolGlobalString('MAIN_GOOGLE_AN_ID')) {
12162 $tmptagarray = explode(',', getDolGlobalString('MAIN_GOOGLE_AN_ID'));
12163 foreach ($tmptagarray as $tmptag) {
12164 print "\n";
12165 print "<!-- JS CODE TO ENABLE for google analtics tag -->\n";
12166 print '
12167 <!-- Global site tag (gtag.js) - Google Analytics -->
12168 <script nonce="'.getNonce().'" async src="https://www.googletagmanager.com/gtag/js?id='.trim($tmptag).'"></script>
12169 <script>
12170 window.dataLayer = window.dataLayer || [];
12171 function gtag(){dataLayer.push(arguments);}
12172 gtag(\'js\', new Date());
12173
12174 gtag(\'config\', \''.trim($tmptag).'\');
12175 </script>';
12176 print "\n";
12177 }
12178 }
12179 }
12180
12181 // Add Xdebug coverage of code
12182 if (defined('XDEBUGCOVERAGE')) {
12183 print_r(xdebug_get_code_coverage());
12184 }
12185
12186 // Add DebugBar data
12187 if ($user->hasRight('debugbar', 'read') && $debugbar instanceof DebugBar\DebugBar) {
12188 if (isset($debugbar['time'])) {
12189 // @phan-suppress-next-line PhanPluginUnknownObjectMethodCall
12190 $debugbar['time']->stopMeasure('pageaftermaster');
12191 }
12192 print '<!-- Output debugbar data -->'."\n";
12193 $renderer = $debugbar->getJavascriptRenderer();
12194 print $renderer->render();
12195 } elseif (count($conf->logbuffer)) { // If there is some logs in buffer to show
12196 print "\n";
12197 print "<!-- Start of log output\n";
12198 //print '<div class="hidden">'."\n";
12199 foreach ($conf->logbuffer as $logline) {
12200 print $logline."<br>\n";
12201 }
12202 //print '</div>'."\n";
12203 print "End of log output -->\n";
12204 }
12205 }
12206}
12207
12217function dolExplodeIntoArray($string, $delimiter = ';', $kv = '=')
12218{
12219 if (is_null($string)) {
12220 return array();
12221 }
12222
12223 if (preg_match('/^\[.*\]$/sm', $delimiter) || preg_match('/^\‍(.*\‍)$/sm', $delimiter)) {
12224 // This is a regex string
12225 $newdelimiter = $delimiter;
12226 } else {
12227 // This is a simple string
12228 // @phan-suppress-next-line PhanPluginSuspiciousParamPositionInternal
12229 $newdelimiter = preg_quote($delimiter, '/');
12230 }
12231
12232 if ($a = preg_split('/'.$newdelimiter.'/', $string)) {
12233 $ka = array();
12234 foreach ($a as $s) { // each part
12235 if ($s) {
12236 if ($pos = strpos($s, $kv)) { // key/value delimiter
12237 $ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv)));
12238 } else { // key delimiter not found
12239 $ka[] = trim($s);
12240 }
12241 }
12242 }
12243 return $ka;
12244 }
12245
12246 return array();
12247}
12248
12256function dolExplodeKeepIfQuotes($input)
12257{
12258 // Use regexp to capture words and section in quotes
12259 $matches = array();
12260 preg_match_all('/"([^"]*)"|\'([^\']*)\'|(\S+)/', $input, $matches);
12261
12262 // Merge result and delete empty values
12263
12264 $result = array_map(
12271 static function ($a, $b, $c) {
12272 if ($a !== '') {
12273 return $a;
12274 }
12275 if ($b !== '') {
12276 return $b;
12277 }
12278 if ($c !== '') {
12279 return $c;
12280 }
12281 return '';
12282 },
12283 $matches[1],
12284 $matches[2],
12285 $matches[3]
12286 );
12287 return array_values(array_filter(
12288 $result,
12295 static function ($val) {
12296 return $val !== '';
12297 }
12298 ));
12299}
12300
12301
12308function dol_set_focus($selector)
12309{
12310 print "\n".'<!-- Set focus onto a specific field -->'."\n";
12311 print '<script nonce="'.getNonce().'">jQuery(document).ready(function() { console.log("Force focus by dol_set_focus"); jQuery("'.dol_escape_js($selector).'").focus(); });</script>'."\n";
12312}
12313
12314
12322function dol_getmypid()
12323{
12324 if (!function_exists('getmypid')) {
12325 return mt_rand(99900000, 99965535);
12326 } else {
12327 return getmypid(); // May be a number on 64 bits (depending on OS)
12328 }
12329}
12330
12352function natural_search($fields, $value, $mode = 0, $nofirstand = 0)
12353{
12354 global $db, $langs;
12355
12356 $value = trim($value);
12357
12358 if ($mode == 0) {
12359 $value = preg_replace('/\*/', '%', $value); // Replace * with %
12360 }
12361 if ($mode == 1) {
12362 $value = preg_replace('/([!<>=]+)\s+([0-9'.preg_quote($langs->trans("SeparatorDecimal"), '/').'\-])/', '\1\2', $value); // Clean string '< 10' into '<10' so we can then explode on space to get all tests to do
12363 }
12364
12365 $value = preg_replace('/\s*\|\s*/', '|', $value);
12366
12367 // Split criteria on ' ' but not if we are inside quotes.
12368 // For mode 3, the split is done later on the , only and not on the ' '.
12369 if ($mode != -3 && $mode != 3) {
12370 $crits = dolExplodeKeepIfQuotes($value);
12371 } else {
12372 $crits = array($value);
12373 }
12374
12375 $res = '';
12376 if (!is_array($fields)) {
12377 $fields = array($fields);
12378 }
12379 $i1 = 0; // count the nb of "and" criteria added (all fields / criteria)
12380 foreach ($crits as $crit) { // Loop on each AND criteria
12381 $crit = trim($crit);
12382 $i2 = 0; // count the nb of valid criteria added for this this first criteria
12383 $newres = '';
12384
12385 foreach ($fields as $field) {
12386 if ($mode == 1) {
12387 $tmpcrits = explode('|', $crit);
12388 $i3 = 0; // count the nb of valid criteria added for this current field
12389 foreach ($tmpcrits as $tmpcrit) {
12390 if ($tmpcrit !== '0' && empty($tmpcrit)) {
12391 continue;
12392 }
12393 $tmpcrit = trim($tmpcrit);
12394
12395 $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
12396
12397 $operator = '=';
12398 $newcrit = preg_replace('/([!<>=]+)/', '', $tmpcrit);
12399
12400 $reg = array();
12401 preg_match('/([!<>=]+)/', $tmpcrit, $reg);
12402 if (!empty($reg[1])) {
12403 $operator = $reg[1];
12404 }
12405 if ($newcrit != '') {
12406 $numnewcrit = price2num($newcrit);
12407 if (is_numeric($numnewcrit)) {
12408 $newres .= $db->sanitize($field).' '.$operator.' '.((float) $numnewcrit); // should be a numeric
12409 } else {
12410 $newres .= '1 = 2'; // force false, we received a corrupted data
12411 }
12412 $i3++; // a criteria was added to string
12413 }
12414 }
12415 $i2++; // a criteria for 1 more field was added to string
12416 } elseif ($mode == 2 || $mode == -2) {
12417 $crit = preg_replace('/[^\-0-9,]/', '', $crit); // ID are always integer
12418 $newres .= ($i2 > 0 ? ' OR ' : '').$db->sanitize($field)." ".($mode == -2 ? 'NOT ' : '');
12419 $newres .= $crit ? "IN (".$db->sanitize($db->escape($crit)).")" : "IN (0)";
12420 if ($mode == -2) {
12421 $newres .= ' OR '.$db->sanitize($field).' IS NULL';
12422 }
12423 $i2++; // a criteria for 1 more field was added to string
12424 } elseif ($mode == 3 || $mode == -3) {
12425 $tmparray = explode(',', $crit);
12426 if (count($tmparray)) {
12427 $listofcodes = '';
12428 foreach ($tmparray as $val) {
12429 $val = trim($val);
12430 if ($val) {
12431 $listofcodes .= ($listofcodes ? ',' : '');
12432 $listofcodes .= "'".$db->escape($val)."'";
12433 }
12434 }
12435 $newres .= ($i2 > 0 ? ' OR ' : '').$db->sanitize($field)." ".($mode == -3 ? 'NOT ' : '')."IN (".$db->sanitize($listofcodes, 1, 0, 1).")";
12436 $i2++; // a criteria for 1 more field was added to string
12437 }
12438 if ($mode == -3) {
12439 $newres .= ' OR '.$db->sanitize($field).' IS NULL';
12440 }
12441 } elseif ($mode == 4) {
12442 $tmparray = explode(',', $crit);
12443 if (count($tmparray)) {
12444 $listofcodes = '';
12445 foreach ($tmparray as $val) {
12446 $val = trim($val);
12447 if ($val) {
12448 $newres .= ($i2 > 0 ? " OR (" : "(").$db->sanitize($field)." LIKE '".$db->escape($val).",%'";
12449 $newres .= ' OR '.$db->sanitize($field)." = '".$db->escape($val)."'";
12450 $newres .= ' OR '.$db->sanitize($field)." LIKE '%,".$db->escape($val)."'";
12451 $newres .= ' OR '.$db->sanitize($field)." LIKE '%,".$db->escape($val).",%'";
12452 $newres .= ')';
12453 $i2++; // a criteria for 1 more field was added to string (we can add several criteria for the same field as it is a multiselect search criteria)
12454 }
12455 }
12456 }
12457 } else { // $mode=0
12458 $tmpcrits = explode('|', $crit);
12459 $i3 = 0; // count the nb of valid criteria added for the current couple criteria/field
12460 foreach ($tmpcrits as $tmpcrit) { // loop on each OR criteria
12461 if ($tmpcrit !== '0' && empty($tmpcrit)) {
12462 continue;
12463 }
12464 $tmpcrit = trim($tmpcrit);
12465
12466 if ($tmpcrit == '^$' || strpos($crit, '!') === 0) { // If we search empty, we must combined different OR fields with AND
12467 $newres .= (($i2 > 0 || $i3 > 0) ? ' AND ' : '');
12468 } else {
12469 $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
12470 }
12471
12472 if (preg_match('/\.(id|rowid)$/', $field)) { // Special case for rowid that is sometimes a ref so used as a search field
12473 $newres .= $db->sanitize($field)." = ".(is_numeric($tmpcrit) ? ((float) $tmpcrit) : '0');
12474 } else {
12475 $tmpcrit2 = $tmpcrit;
12476 $tmpbefore = '%';
12477 $tmpafter = '%';
12478 $tmps = '';
12479
12480 if (preg_match('/^!/', $tmpcrit)) {
12481 $tmps .= $db->sanitize($field)." NOT LIKE "; // ! as exclude character
12482 $tmpcrit2 = preg_replace('/^!/', '', $tmpcrit2);
12483 } else {
12484 $tmps .= $db->sanitize($field)." LIKE ";
12485 }
12486 $tmps .= "'";
12487
12488 if (preg_match('/^[\^\$]/', $tmpcrit)) {
12489 $tmpbefore = '';
12490 $tmpcrit2 = preg_replace('/^[\^\$]/', '', $tmpcrit2);
12491 }
12492 if (preg_match('/[\^\$]$/', $tmpcrit)) {
12493 $tmpafter = '';
12494 $tmpcrit2 = preg_replace('/[\^\$]$/', '', $tmpcrit2);
12495 }
12496
12497 if ($tmpcrit2 == '' || preg_match('/^!/', $tmpcrit)) {
12498 $tmps = "(".$tmps;
12499 }
12500 $newres .= $tmps;
12501 $newres .= $tmpbefore;
12502 $newres .= $db->escape($tmpcrit2);
12503 $newres .= $tmpafter;
12504 $newres .= "'";
12505 if ($tmpcrit2 == '' || preg_match('/^!/', $tmpcrit)) {
12506 $newres .= " OR ".$field." IS NULL)";
12507 }
12508 }
12509
12510 $i3++;
12511 }
12512
12513 $i2++; // a criteria for 1 more field was added to string
12514 }
12515 }
12516 if ($newres) {
12517 $res = $res.($res ? ' AND ' : '').($i2 > 1 ? '(' : '').$newres.($i2 > 1 ? ')' : '');
12518 }
12519 $i1++;
12520 }
12521 $res = ($nofirstand ? "" : " AND ")."(".$res.")";
12522
12523 return $res;
12524}
12525
12532function showDirectDownloadLink($object)
12533{
12534 global $langs;
12535
12536 $out = '';
12537 $url = $object->getLastMainDocLink($object->element);
12538
12539 $out .= img_picto($langs->trans("PublicDownloadLinkDesc"), 'globe').' <span class="opacitymedium">'.$langs->trans("DirectDownloadLink").'</span><br>';
12540 if ($url) {
12541 $out .= '<div class="urllink"><input type="text" id="directdownloadlink" class="quatrevingtpercent" value="'.$url.'"></div>';
12542 $out .= ajax_autoselect("directdownloadlink", '');
12543 } else {
12544 $out .= '<div class="urllink">'.$langs->trans("FileNotShared").'</div>';
12545 }
12546
12547 return $out;
12548}
12549
12558function getImageFileNameForSize($file, $extName, $extImgTarget = '')
12559{
12560 $dirName = dirname($file);
12561 if ($dirName == '.') {
12562 $dirName = '';
12563 }
12564
12565 if (!in_array($extName, array('', '_small', '_mini'))) {
12566 return 'Bad parameter extName';
12567 }
12568
12569 $fileName = preg_replace('/(\.gif|\.jpeg|\.jpg|\.png|\.bmp|\.webp)$/i', '', $file); // We remove image extension, whatever is its case
12570 $fileName = basename($fileName);
12571
12572 if (empty($extImgTarget)) {
12573 $extImgTarget = (preg_match('/\.jpg$/i', $file) ? '.jpg' : '');
12574 }
12575 if (empty($extImgTarget)) {
12576 $extImgTarget = (preg_match('/\.jpeg$/i', $file) ? '.jpeg' : '');
12577 }
12578 if (empty($extImgTarget)) {
12579 $extImgTarget = (preg_match('/\.gif$/i', $file) ? '.gif' : '');
12580 }
12581 if (empty($extImgTarget)) {
12582 $extImgTarget = (preg_match('/\.png$/i', $file) ? '.png' : '');
12583 }
12584 if (empty($extImgTarget)) {
12585 $extImgTarget = (preg_match('/\.bmp$/i', $file) ? '.bmp' : '');
12586 }
12587 if (empty($extImgTarget)) {
12588 $extImgTarget = (preg_match('/\.webp$/i', $file) ? '.webp' : '');
12589 }
12590
12591 if (!$extImgTarget) {
12592 return $file;
12593 }
12594
12595 $subdir = '';
12596 if ($extName) {
12597 $subdir = 'thumbs/';
12598 }
12599
12600 return ($dirName ? $dirName.'/' : '').$subdir.$fileName.$extName.$extImgTarget; // New filename for thumb
12601}
12602
12603
12613function getAdvancedPreviewUrl($modulepart, $relativepath, $alldata = 0, $param = '')
12614{
12615 global $conf, $langs;
12616
12617 if (empty($conf->use_javascript_ajax)) {
12618 return '';
12619 }
12620
12621 $isAllowedForPreview = dolIsAllowedForPreview($relativepath);
12622
12623 if ($alldata == 1) {
12624 if ($isAllowedForPreview) {
12625 return array('target' => '_blank', 'css' => 'documentpreview', 'url' => DOL_URL_ROOT.'/document.php?modulepart='.urlencode($modulepart).'&attachment=0&file='.urlencode($relativepath).($param ? '&'.$param : ''), 'mime' => dol_mimetype($relativepath));
12626 } else {
12627 return array();
12628 }
12629 }
12630
12631 // old behavior, return a string
12632 if ($isAllowedForPreview) {
12633 $tmpurl = DOL_URL_ROOT.'/document.php?modulepart='.urlencode($modulepart).'&attachment=0&file='.urlencode($relativepath).($param ? '&'.$param : '');
12634 $title = $langs->transnoentities("Preview");
12635 //$title = '%27-alert(document.domain)-%27'; // An example of js injection into a corrupted title string, that should be blocked by the dol_escape_uri().
12636 //$tmpurl = 'file='.urlencode("'-alert(document.domain)-'_small.jpg"); // An example of tmpurl that should be blocked by the dol_escape_uri()
12637
12638 // We need to do a dol_escape_uri() on the full string after the javascript: because such parts are the URI and when we click on such links, a RFC3986 decode is done,
12639 // by the browser, converting the %27 (like when having param file=abc%27def), or when having a corrupted title), into a ', BEFORE interpreting the content that can be a js code.
12640 // Using the dol_escape_uri guarantee that we encode for URI so decode retrieve original expected value.
12641 return 'javascript:'.dol_escape_uri('document_preview(\''.dol_escape_js($tmpurl).'\', \''.dol_escape_js(dol_mimetype($relativepath)).'\', \''.dol_escape_js($title).'\')');
12642 } else {
12643 return '';
12644 }
12645}
12646
12653function getLabelSpecialCode($idcode)
12654{
12655 global $langs;
12656
12657 $arrayspecialines = array(1 => 'Transport', 2 => 'EcoTax', 3 => 'Option');
12658 if ($idcode > 10) {
12659 return 'Module ID '.$idcode;
12660 }
12661 if (!empty($arrayspecialines[$idcode])) {
12662 return $langs->trans($arrayspecialines[$idcode]);
12663 }
12664 return '';
12665}
12666
12675function ajax_autoselect($htmlname, $addlink = '', $textonlink = 'Link')
12676{
12677 global $langs;
12678 $out = '<script nonce="'.getNonce().'">
12679 jQuery(document).ready(function () {
12680 jQuery("'.((strpos($htmlname, '.') === 0 ? '' : '#').$htmlname).'").click(function() { jQuery(this).select(); } );
12681 });
12682 </script>';
12683 if ($addlink) {
12684 if ($textonlink === 'image') {
12685 $out .= ' <a href="'.$addlink.'" target="_blank" rel="noopener noreferrer">'.img_picto('', 'globe').'</a>';
12686 } else {
12687 $out .= ' <a href="'.$addlink.'" target="_blank" rel="noopener noreferrer">'.$langs->trans("Link").'</a>';
12688 }
12689 }
12690 return $out;
12691}
12692
12700function dolIsAllowedForPreview($file)
12701{
12702 // Check .noexe extension in filename
12703 if (preg_match('/\.noexe$/i', $file)) {
12704 return 0;
12705 }
12706
12707 // Check mime types
12708 $mime_preview = array('bmp', 'jpeg', 'png', 'gif', 'tiff', 'pdf', 'plain', 'css', 'webp');
12709 if (getDolGlobalString('MAIN_ALLOW_SVG_FILES_AS_IMAGES')) {
12710 $mime_preview[] = 'svg+xml';
12711 }
12712 //$mime_preview[]='vnd.oasis.opendocument.presentation';
12713 //$mime_preview[]='archive';
12714 $num_mime = array_search(dol_mimetype($file, '', 1), $mime_preview);
12715 if ($num_mime !== false) {
12716 return 1;
12717 }
12718
12719 // By default, not allowed for preview
12720 return 0;
12721}
12722
12723
12733function dol_mimetype($file, $default = 'application/octet-stream', $mode = 0)
12734{
12735 $mime = $default;
12736 $imgmime = 'other.png';
12737 $famime = 'file-o';
12738 $srclang = '';
12739
12740 $tmpfile = preg_replace('/\.noexe$/', '', $file);
12741
12742 // Plain text files
12743 if (preg_match('/\.txt$/i', $tmpfile)) {
12744 $mime = 'text/plain';
12745 $imgmime = 'text.png';
12746 $famime = 'file-alt';
12747 } elseif (preg_match('/\.rtx$/i', $tmpfile)) {
12748 $mime = 'text/richtext';
12749 $imgmime = 'text.png';
12750 $famime = 'file-alt';
12751 } elseif (preg_match('/\.csv$/i', $tmpfile)) {
12752 $mime = 'text/csv';
12753 $imgmime = 'text.png';
12754 $famime = 'file-csv';
12755 } elseif (preg_match('/\.tsv$/i', $tmpfile)) {
12756 $mime = 'text/tab-separated-values';
12757 $imgmime = 'text.png';
12758 $famime = 'file-alt';
12759 } elseif (preg_match('/\.(cf|conf|log)$/i', $tmpfile)) {
12760 $mime = 'text/plain';
12761 $imgmime = 'text.png';
12762 $famime = 'file-alt';
12763 } elseif (preg_match('/\.ini$/i', $tmpfile)) {
12764 $mime = 'text/plain';
12765 $imgmime = 'text.png';
12766 $srclang = 'ini';
12767 $famime = 'file-alt';
12768 } elseif (preg_match('/\.md$/i', $tmpfile)) {
12769 $mime = 'text/plain';
12770 $imgmime = 'text.png';
12771 $srclang = 'md';
12772 $famime = 'file-alt';
12773 } elseif (preg_match('/\.css$/i', $tmpfile)) {
12774 $mime = 'text/css';
12775 $imgmime = 'css.png';
12776 $srclang = 'css';
12777 $famime = 'file-alt';
12778 } elseif (preg_match('/\.lang$/i', $tmpfile)) {
12779 $mime = 'text/plain';
12780 $imgmime = 'text.png';
12781 $srclang = 'lang';
12782 $famime = 'file-alt';
12783 } elseif (preg_match('/\.(crt|cer|key|pub)$/i', $tmpfile)) { // Certificate files
12784 $mime = 'text/plain';
12785 $imgmime = 'text.png';
12786 $famime = 'file-alt';
12787 } elseif (preg_match('/\.(html|htm|shtml)$/i', $tmpfile)) { // XML based (HTML/XML/XAML)
12788 $mime = 'text/html';
12789 $imgmime = 'html.png';
12790 $srclang = 'html';
12791 $famime = 'file-alt';
12792 } elseif (preg_match('/\.(xml|xhtml)$/i', $tmpfile)) {
12793 $mime = 'text/xml';
12794 $imgmime = 'other.png';
12795 $srclang = 'xml';
12796 $famime = 'file-alt';
12797 } elseif (preg_match('/\.xaml$/i', $tmpfile)) {
12798 $mime = 'text/xml';
12799 $imgmime = 'other.png';
12800 $srclang = 'xaml';
12801 $famime = 'file-alt';
12802 } elseif (preg_match('/\.bas$/i', $tmpfile)) { // Languages
12803 $mime = 'text/plain';
12804 $imgmime = 'text.png';
12805 $srclang = 'bas';
12806 $famime = 'file-code';
12807 } elseif (preg_match('/\.(c)$/i', $tmpfile)) {
12808 $mime = 'text/plain';
12809 $imgmime = 'text.png';
12810 $srclang = 'c';
12811 $famime = 'file-code';
12812 } elseif (preg_match('/\.(cpp)$/i', $tmpfile)) {
12813 $mime = 'text/plain';
12814 $imgmime = 'text.png';
12815 $srclang = 'cpp';
12816 $famime = 'file-code';
12817 } elseif (preg_match('/\.cs$/i', $tmpfile)) {
12818 $mime = 'text/plain';
12819 $imgmime = 'text.png';
12820 $srclang = 'cs';
12821 $famime = 'file-code';
12822 } elseif (preg_match('/\.(h)$/i', $tmpfile)) {
12823 $mime = 'text/plain';
12824 $imgmime = 'text.png';
12825 $srclang = 'h';
12826 $famime = 'file-code';
12827 } elseif (preg_match('/\.(java|jsp)$/i', $tmpfile)) {
12828 $mime = 'text/plain';
12829 $imgmime = 'text.png';
12830 $srclang = 'java';
12831 $famime = 'file-code';
12832 } elseif (preg_match('/\.php([0-9]{1})?$/i', $tmpfile)) {
12833 $mime = 'text/plain';
12834 $imgmime = 'php.png';
12835 $srclang = 'php';
12836 $famime = 'file-code';
12837 } elseif (preg_match('/\.phtml$/i', $tmpfile)) {
12838 $mime = 'text/plain';
12839 $imgmime = 'php.png';
12840 $srclang = 'php';
12841 $famime = 'file-code';
12842 } elseif (preg_match('/\.(pl|pm)$/i', $tmpfile)) {
12843 $mime = 'text/plain';
12844 $imgmime = 'pl.png';
12845 $srclang = 'perl';
12846 $famime = 'file-code';
12847 } elseif (preg_match('/\.sql$/i', $tmpfile)) {
12848 $mime = 'text/plain';
12849 $imgmime = 'text.png';
12850 $srclang = 'sql';
12851 $famime = 'file-code';
12852 } elseif (preg_match('/\.js$/i', $tmpfile)) {
12853 $mime = 'text/x-javascript';
12854 $imgmime = 'jscript.png';
12855 $srclang = 'js';
12856 $famime = 'file-code';
12857 } elseif (preg_match('/\.odp$/i', $tmpfile)) { // Open office
12858 $mime = 'application/vnd.oasis.opendocument.presentation';
12859 $imgmime = 'ooffice.png';
12860 $famime = 'file-powerpoint';
12861 } elseif (preg_match('/\.ods$/i', $tmpfile)) {
12862 $mime = 'application/vnd.oasis.opendocument.spreadsheet';
12863 $imgmime = 'ooffice.png';
12864 $famime = 'file-excel';
12865 } elseif (preg_match('/\.odt$/i', $tmpfile)) {
12866 $mime = 'application/vnd.oasis.opendocument.text';
12867 $imgmime = 'ooffice.png';
12868 $famime = 'file-word';
12869 } elseif (preg_match('/\.mdb$/i', $tmpfile)) { // MS Office
12870 $mime = 'application/msaccess';
12871 $imgmime = 'mdb.png';
12872 $famime = 'file';
12873 } elseif (preg_match('/\.doc[xm]?$/i', $tmpfile)) {
12874 $mime = 'application/msword';
12875 $imgmime = 'doc.png';
12876 $famime = 'file-word';
12877 } elseif (preg_match('/\.dot[xm]?$/i', $tmpfile)) {
12878 $mime = 'application/msword';
12879 $imgmime = 'doc.png';
12880 $famime = 'file-word';
12881 } elseif (preg_match('/\.xlt(x)?$/i', $tmpfile)) {
12882 $mime = 'application/vnd.ms-excel';
12883 $imgmime = 'xls.png';
12884 $famime = 'file-excel';
12885 } elseif (preg_match('/\.xla(m)?$/i', $tmpfile)) {
12886 $mime = 'application/vnd.ms-excel';
12887 $imgmime = 'xls.png';
12888 $famime = 'file-excel';
12889 } elseif (preg_match('/\.xls$/i', $tmpfile)) {
12890 $mime = 'application/vnd.ms-excel';
12891 $imgmime = 'xls.png';
12892 $famime = 'file-excel';
12893 } elseif (preg_match('/\.xls[bmx]$/i', $tmpfile)) {
12894 $mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
12895 $imgmime = 'xls.png';
12896 $famime = 'file-excel';
12897 } elseif (preg_match('/\.pps[mx]?$/i', $tmpfile)) {
12898 $mime = 'application/vnd.ms-powerpoint';
12899 $imgmime = 'ppt.png';
12900 $famime = 'file-powerpoint';
12901 } elseif (preg_match('/\.ppt[mx]?$/i', $tmpfile)) {
12902 $mime = 'application/x-mspowerpoint';
12903 $imgmime = 'ppt.png';
12904 $famime = 'file-powerpoint';
12905 } elseif (preg_match('/\.pdf$/i', $tmpfile)) { // Other
12906 $mime = 'application/pdf';
12907 $imgmime = 'pdf.png';
12908 $famime = 'file-pdf';
12909 } elseif (preg_match('/\.bat$/i', $tmpfile)) { // Scripts
12910 $mime = 'text/x-bat';
12911 $imgmime = 'script.png';
12912 $srclang = 'dos';
12913 $famime = 'file-code';
12914 } elseif (preg_match('/\.sh$/i', $tmpfile)) {
12915 $mime = 'text/x-sh';
12916 $imgmime = 'script.png';
12917 $srclang = 'bash';
12918 $famime = 'file-code';
12919 } elseif (preg_match('/\.ksh$/i', $tmpfile)) {
12920 $mime = 'text/x-ksh';
12921 $imgmime = 'script.png';
12922 $srclang = 'bash';
12923 $famime = 'file-code';
12924 } elseif (preg_match('/\.bash$/i', $tmpfile)) {
12925 $mime = 'text/x-bash';
12926 $imgmime = 'script.png';
12927 $srclang = 'bash';
12928 $famime = 'file-code';
12929 } elseif (preg_match('/\.ico$/i', $tmpfile)) { // Images
12930 $mime = 'image/x-icon';
12931 $imgmime = 'image.png';
12932 $famime = 'file-image';
12933 } elseif (preg_match('/\.(jpg|jpeg)$/i', $tmpfile)) {
12934 $mime = 'image/jpeg';
12935 $imgmime = 'image.png';
12936 $famime = 'file-image';
12937 } elseif (preg_match('/\.png$/i', $tmpfile)) {
12938 $mime = 'image/png';
12939 $imgmime = 'image.png';
12940 $famime = 'file-image';
12941 } elseif (preg_match('/\.gif$/i', $tmpfile)) {
12942 $mime = 'image/gif';
12943 $imgmime = 'image.png';
12944 $famime = 'file-image';
12945 } elseif (preg_match('/\.bmp$/i', $tmpfile)) {
12946 $mime = 'image/bmp';
12947 $imgmime = 'image.png';
12948 $famime = 'file-image';
12949 } elseif (preg_match('/\.(tif|tiff)$/i', $tmpfile)) {
12950 $mime = 'image/tiff';
12951 $imgmime = 'image.png';
12952 $famime = 'file-image';
12953 } elseif (preg_match('/\.svg$/i', $tmpfile)) {
12954 $mime = 'image/svg+xml';
12955 $imgmime = 'image.png';
12956 $famime = 'file-image';
12957 } elseif (preg_match('/\.webp$/i', $tmpfile)) {
12958 $mime = 'image/webp';
12959 $imgmime = 'image.png';
12960 $famime = 'file-image';
12961 } elseif (preg_match('/\.vcs$/i', $tmpfile)) { // Calendar
12962 $mime = 'text/calendar';
12963 $imgmime = 'other.png';
12964 $famime = 'file-alt';
12965 } elseif (preg_match('/\.ics$/i', $tmpfile)) {
12966 $mime = 'text/calendar';
12967 $imgmime = 'other.png';
12968 $famime = 'file-alt';
12969 } elseif (preg_match('/\.torrent$/i', $tmpfile)) { // Other
12970 $mime = 'application/x-bittorrent';
12971 $imgmime = 'other.png';
12972 $famime = 'file-o';
12973 } elseif (preg_match('/\.(mp3|ogg|au|wav|wma|mid)$/i', $tmpfile)) { // Audio
12974 $mime = 'audio';
12975 $imgmime = 'audio.png';
12976 $famime = 'file-audio';
12977 } elseif (preg_match('/\.mp4$/i', $tmpfile)) { // Video
12978 $mime = 'video/mp4';
12979 $imgmime = 'video.png';
12980 $famime = 'file-video';
12981 } elseif (preg_match('/\.ogv$/i', $tmpfile)) {
12982 $mime = 'video/ogg';
12983 $imgmime = 'video.png';
12984 $famime = 'file-video';
12985 } elseif (preg_match('/\.webm$/i', $tmpfile)) {
12986 $mime = 'video/webm';
12987 $imgmime = 'video.png';
12988 $famime = 'file-video';
12989 } elseif (preg_match('/\.avi$/i', $tmpfile)) {
12990 $mime = 'video/x-msvideo';
12991 $imgmime = 'video.png';
12992 $famime = 'file-video';
12993 } elseif (preg_match('/\.divx$/i', $tmpfile)) {
12994 $mime = 'video/divx';
12995 $imgmime = 'video.png';
12996 $famime = 'file-video';
12997 } elseif (preg_match('/\.xvid$/i', $tmpfile)) {
12998 $mime = 'video/xvid';
12999 $imgmime = 'video.png';
13000 $famime = 'file-video';
13001 } elseif (preg_match('/\.(wmv|mpg|mpeg)$/i', $tmpfile)) {
13002 $mime = 'video';
13003 $imgmime = 'video.png';
13004 $famime = 'file-video';
13005 } elseif (preg_match('/\.(zip|rar|gz|tgz|xz|z|cab|bz2|7z|tar|lzh|zst)$/i', $tmpfile)) { // Archive
13006 // application/xxx where zzz is zip, ...
13007 $mime = 'archive';
13008 $imgmime = 'archive.png';
13009 $famime = 'file-archive';
13010 } elseif (preg_match('/\.(exe|com)$/i', $tmpfile)) { // Exe
13011 $mime = 'application/octet-stream';
13012 $imgmime = 'other.png';
13013 $famime = 'file-o';
13014 } elseif (preg_match('/\.(dll|lib|o|so|a)$/i', $tmpfile)) { // Lib
13015 $mime = 'library';
13016 $imgmime = 'library.png';
13017 $famime = 'file-o';
13018 } elseif (preg_match('/\.err$/i', $tmpfile)) { // phpcs:ignore
13019 $mime = 'error';
13020 $imgmime = 'error.png';
13021 $famime = 'file-alt';
13022 }
13023
13024 if ($famime == 'file-o') {
13025 // file-o seems to not work in fontawesome 5
13026 $famime = 'file';
13027 }
13028
13029 // Return mimetype string
13030 switch ((int) $mode) {
13031 case 1:
13032 $tmp = explode('/', $mime);
13033 return (!empty($tmp[1]) ? $tmp[1] : $tmp[0]);
13034 case 2:
13035 return $imgmime;
13036 case 3:
13037 return $srclang;
13038 case 4:
13039 return $famime;
13040 }
13041 return $mime;
13042}
13043
13055function getDictionaryValue($tablename, $field, $id, $checkentity = false, $rowidfield = 'rowid')
13056{
13057 global $conf, $db;
13058
13059 $tablename = preg_replace('/^'.preg_quote(MAIN_DB_PREFIX, '/').'/', '', $tablename); // Clean name of table for backward compatibility.
13060
13061 $dictvalues = (isset($conf->cache['dictvalues_'.$tablename]) ? $conf->cache['dictvalues_'.$tablename] : null);
13062
13063 if (is_null($dictvalues)) {
13064 $dictvalues = array();
13065
13066 $sql = "SELECT * FROM ".MAIN_DB_PREFIX.$tablename." WHERE 1 = 1"; // Here select * is allowed as it is generic code and we don't have list of fields
13067 if ($checkentity) {
13068 $sql .= ' AND entity IN (0,'.getEntity($tablename).')';
13069 }
13070
13071 $resql = $db->query($sql);
13072 if ($resql) {
13073 while ($obj = $db->fetch_object($resql)) {
13074 $dictvalues[$obj->$rowidfield] = $obj; // $obj is stdClass
13075 }
13076 } else {
13077 dol_print_error($db);
13078 }
13079
13080 $conf->cache['dictvalues_'.$tablename] = $dictvalues;
13081 }
13082
13083 if (!empty($dictvalues[$id])) {
13084 // Found
13085 $tmp = $dictvalues[$id];
13086 return (property_exists($tmp, $field) ? $tmp->$field : '');
13087 } else {
13088 // Not found
13089 return '';
13090 }
13091}
13092
13099function colorIsLight($stringcolor)
13100{
13101 $stringcolor = str_replace('#', '', $stringcolor);
13102 $res = -1;
13103 if (!empty($stringcolor)) {
13104 $res = 0;
13105 $tmp = explode(',', $stringcolor);
13106 if (count($tmp) > 1) { // This is a comma RGB ('255','255','255')
13107 $r = $tmp[0];
13108 $g = $tmp[1];
13109 $b = $tmp[2];
13110 } else {
13111 $hexr = $stringcolor[0].$stringcolor[1];
13112 $hexg = $stringcolor[2].$stringcolor[3];
13113 $hexb = $stringcolor[4].$stringcolor[5];
13114 $r = hexdec($hexr);
13115 $g = hexdec($hexg);
13116 $b = hexdec($hexb);
13117 }
13118 $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm
13119 if ($bright > 0.6) {
13120 $res = 1;
13121 }
13122 }
13123 return $res;
13124}
13125
13134function isVisibleToUserType($type_user, &$menuentry, &$listofmodulesforexternal)
13135{
13136 global $conf;
13137
13138 //print 'type_user='.$type_user.' module='.$menuentry['module'].' enabled='.$menuentry['enabled'].' perms='.$menuentry['perms'];
13139 //print 'ok='.in_array($menuentry['module'], $listofmodulesforexternal);
13140 if (empty($menuentry['enabled'])) {
13141 return 0; // Entry disabled by condition
13142 }
13143 if ($type_user && array_key_exists('module', $menuentry) && $menuentry['module']) {
13144 $tmploops = explode('|', $menuentry['module']);
13145 $found = 0;
13146 foreach ($tmploops as $tmploop) {
13147 if (in_array($tmploop, $listofmodulesforexternal)) {
13148 $found++;
13149 break;
13150 }
13151 }
13152 if (!$found) {
13153 return 0; // Entry is for menus all excluded to external users
13154 }
13155 }
13156 if (!$menuentry['perms'] && $type_user) {
13157 return 0; // No permissions and user is external
13158 }
13159 if (!$menuentry['perms'] && getDolGlobalString('MAIN_MENU_HIDE_UNAUTHORIZED')) {
13160 return 0; // No permissions and option to hide when not allowed, even for internal user, is on
13161 }
13162 if (!$menuentry['perms']) {
13163 return 2; // No permissions and user is external
13164 }
13165 return 1;
13166}
13167
13175function roundUpToNextMultiple($n, $x = 5)
13176{
13177 $result = (ceil($n) % $x === 0) ? ceil($n) : (round(($n + $x / 2) / $x) * $x);
13178 return (int) $result;
13179}
13180
13192function dolGetBadge($label, $html = '', $type = 'primary', $mode = '', $url = '', $params = array())
13193{
13194 $csstouse = 'badge';
13195 $csstouse .= (!empty($mode) ? ' badge-'.$mode : '');
13196 $csstouse .= (!empty($type) ? ' badge-'.$type : '');
13197 $csstouse .= (empty($params['css']) ? '' : ' '.$params['css']);
13198
13199 $attr = array(
13200 'class' => $csstouse
13201 );
13202
13203 if (empty($html)) {
13204 $html = $label;
13205 }
13206
13207 if (!empty($url)) {
13208 $attr['href'] = $url;
13209 }
13210
13211 if ($mode === 'dot') {
13212 $attr['class'] .= ' classfortooltip';
13213 $attr['title'] = $html;
13214 $attr['aria-label'] = $label;
13215 $html = '';
13216 }
13217
13218 // Override attr
13219 if (!empty($params['attr']) && is_array($params['attr'])) {
13220 foreach ($params['attr'] as $key => $value) {
13221 if ($key == 'class') {
13222 $attr['class'] .= ' '.$value;
13223 } elseif ($key == 'classOverride') {
13224 $attr['class'] = $value;
13225 } else {
13226 $attr[$key] = $value;
13227 }
13228 }
13229 }
13230
13231 // TODO: add hook
13232
13233 // escape all attribute
13234 $attr = array_map('dolPrintHTMLForAttribute', $attr);
13235
13236 $TCompiledAttr = array();
13237 foreach ($attr as $key => $value) {
13238 $TCompiledAttr[] = $key.'="'.$value.'"';
13239 }
13240
13241 $compiledAttributes = !empty($TCompiledAttr) ? implode(' ', $TCompiledAttr) : '';
13242
13243 $tag = !empty($url) ? 'a' : 'span';
13244
13245 return '<'.$tag.' '.$compiledAttributes.'>'.$html.'</'.$tag.'>';
13246}
13247
13248
13261function dolGetStatus($statusLabel = '', $statusLabelShort = '', $html = '', $statusType = 'status0', $displayMode = 0, $url = '', $params = array())
13262{
13263 global $conf;
13264
13265 $return = '';
13266 $dolGetBadgeParams = array();
13267
13268 if (!empty($params['badgeParams'])) {
13269 $dolGetBadgeParams = $params['badgeParams'];
13270 }
13271
13272 // TODO : add a hook
13273 if ($displayMode == 0) {
13274 $return = !empty($html) ? $html : (empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort));
13275 } elseif ($displayMode == 1) {
13276 $return = !empty($html) ? $html : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
13277 } elseif (getDolGlobalString('MAIN_STATUS_USES_IMAGES')) {
13278 // Use status with images (for backward compatibility)
13279 $return = '';
13280 $htmlLabel = (in_array($displayMode, array(1, 2, 5)) ? '<span class="hideonsmartphone">' : '').(!empty($html) ? $html : $statusLabel).(in_array($displayMode, array(1, 2, 5)) ? '</span>' : '');
13281 $htmlLabelShort = (in_array($displayMode, array(1, 2, 5)) ? '<span class="hideonsmartphone">' : '').(!empty($html) ? $html : (!empty($statusLabelShort) ? $statusLabelShort : $statusLabel)).(in_array($displayMode, array(1, 2, 5)) ? '</span>' : '');
13282
13283 // For small screen, we always use the short label instead of long label.
13284 if (!empty($conf->dol_optimize_smallscreen)) {
13285 if ($displayMode == 0) {
13286 $displayMode = 1;
13287 } elseif ($displayMode == 4) {
13288 $displayMode = 2;
13289 } elseif ($displayMode == 6) {
13290 $displayMode = 5;
13291 }
13292 }
13293
13294 // For backward compatibility. Image's filename are still in French, so we use this array to convert
13295 $statusImg = array(
13296 'status0' => 'statut0',
13297 'status1' => 'statut1',
13298 'status2' => 'statut2',
13299 'status3' => 'statut3',
13300 'status4' => 'statut4',
13301 'status5' => 'statut5',
13302 'status6' => 'statut6',
13303 'status7' => 'statut7',
13304 'status8' => 'statut8',
13305 'status9' => 'statut9'
13306 );
13307
13308 if (!empty($statusImg[$statusType])) {
13309 $htmlImg = img_picto($statusLabel, $statusImg[$statusType]);
13310 } else {
13311 $htmlImg = img_picto($statusLabel, $statusType);
13312 }
13313
13314 if ($displayMode === 2) {
13315 $return = $htmlImg.' '.$htmlLabelShort;
13316 } elseif ($displayMode === 3) {
13317 $return = $htmlImg;
13318 } elseif ($displayMode === 4) {
13319 $return = $htmlImg.' '.$htmlLabel;
13320 } elseif ($displayMode === 5) {
13321 $return = $htmlLabelShort.' '.$htmlImg;
13322 } else { // $displayMode >= 6
13323 $return = $htmlLabel.' '.$htmlImg;
13324 }
13325 } elseif (!getDolGlobalString('MAIN_STATUS_USES_IMAGES') && !empty($displayMode)) {
13326 // Use new badge
13327 $statusLabelShort = (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
13328
13329 $dolGetBadgeParams['attr']['class'] = 'badge-status';
13330 if (empty($dolGetBadgeParams['attr']['title'])) {
13331 $dolGetBadgeParams['attr']['title'] = empty($params['tooltip']) ? $statusLabel : ($params['tooltip'] != 'no' ? $params['tooltip'] : '');
13332 } else { // If a title was forced from $params['badgeParams']['attr']['title'], we set the class to get it as a tooltip.
13333 $dolGetBadgeParams['attr']['class'] .= ' classfortooltip';
13334 // And if we use tooltip, we can output title in HTML @phan-suppress-next-line PhanTypeInvalidDimOffset
13335 $dolGetBadgeParams['attr']['title'] = dol_htmlentitiesbr((string) $dolGetBadgeParams['attr']['title'], 1);
13336 }
13337
13338 if ($displayMode == 3) {
13339 $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), '', $statusType, 'dot', $url, $dolGetBadgeParams);
13340 } elseif ($displayMode === 5) {
13341 $return = dolGetBadge($statusLabelShort, $html, $statusType, '', $url, $dolGetBadgeParams);
13342 } else {
13343 $return = dolGetBadge(((empty($conf->dol_optimize_smallscreen) && $displayMode != 2) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), $html, $statusType, '', $url, $dolGetBadgeParams);
13344 }
13345 }
13346
13347 return $return;
13348}
13349
13350
13386function dolGetButtonAction($label, $text = '', $actionType = 'default', $url = '', $id = '', $userRight = 1, $params = array())
13387{
13388 global $hookmanager, $action, $object, $langs;
13389
13390 // If $url is an array, we must build a dropdown button or recursively iterate over each value
13391 if (is_array($url)) {
13392 // Loop on $url array to remove entries of disabled modules
13393 foreach ($url as $key => $subbutton) {
13394 if (isset($subbutton['enabled']) && empty($subbutton['enabled'])) {
13395 unset($url[$key]);
13396 }
13397 }
13398
13399 $out = '';
13400
13401 if (array_key_exists('areDropdownButtons', $params) && $params["areDropdownButtons"] === false) { // @phan-suppress-current-line PhanTypeInvalidDimOffset
13402 foreach ($url as $button) {
13403 if (!empty($button['lang'])) {
13404 $langs->load($button['lang']);
13405 }
13406 $label = $langs->trans($button['label']);
13407 $text = $button['text'] ?? '';
13408 $actionType = $button['actionType'] ?? '';
13409 $tmpUrl = DOL_URL_ROOT.$button['url'].(empty($params['backtopage']) ? '' : '&amp;backtopage='.urlencode($params['backtopage']));
13410 $id = $button['id'] ?? '';
13411 $userRight = $button['perm'] ?? 1;
13412 $button['params'] = $button['params'] ?? []; // @phan-suppress-current-line PhanPluginDuplicateExpressionAssignmentOperation
13413
13414 $out .= dolGetButtonAction($label, $text, $actionType, $tmpUrl, $id, $userRight, $button['params']);
13415 }
13416 return $out;
13417 }
13418
13419 if (count($url) > 1) {
13420 $out .= '<div class="dropdown inline-block dropdown-holder">';
13421 $out .= '<a style="margin-right: auto;" class="dropdown-toggle classfortooltip butAction'.($userRight ? '' : 'Refused').'" title="'.dol_escape_htmltag($label).'" data-toggle="dropdown">'.($text ? $text : $label).'</a>';
13422 $out .= '<div class="dropdown-content">';
13423 foreach ($url as $subbutton) {
13424 if (!empty($subbutton['lang'])) {
13425 $langs->load($subbutton['lang']);
13426 }
13427
13428 if (!empty($subbutton['urlraw'])) {
13429 $tmpurl = $subbutton['urlraw']; // Use raw url, no url completion, use only what developer send
13430 } else {
13431 $tmpurl = !empty($subbutton['urlroot']) ? $subbutton['urlroot'] : $subbutton['url'];
13432 $tmpurl = dolCompletUrlForDropdownButton($tmpurl, $params, empty($subbutton['urlroot']));
13433 }
13434
13435 $subbuttonparam = array();
13436 if (!empty($subbutton['attr'])) {
13437 $subbuttonparam['attr'] = $subbutton['attr'];
13438 }
13439 $subbuttonparam['isDropDown'] = (empty($params['isDropDown']) ? ($subbutton['isDropDown'] ?? false) : $params['isDropDown']);
13440
13441 $out .= dolGetButtonAction('', $langs->trans($subbutton['label']), 'default', $tmpurl, $subbutton['id'] ?? '', $subbutton['perm'], $subbuttonparam);
13442 }
13443 $out .= "</div>";
13444 $out .= "</div>";
13445 } else {
13446 foreach ($url as $subbutton) { // Should loop on 1 record only
13447 if (!empty($subbutton['lang'])) {
13448 $langs->load($subbutton['lang']);
13449 }
13450
13451 if (!empty($subbutton['urlraw'])) {
13452 $tmpurl = $subbutton['urlraw']; // Use raw url, no url completion, use only what developer send
13453 } else {
13454 $tmpurl = !empty($subbutton['urlroot']) ? $subbutton['urlroot'] : $subbutton['url'];
13455 $tmpurl = dolCompletUrlForDropdownButton($tmpurl, $params, empty($subbutton['urlroot']));
13456 }
13457
13458 $out .= dolGetButtonAction('', $langs->trans($subbutton['label']), 'default', $tmpurl, '', $subbutton['perm'], $params);
13459 }
13460 }
13461
13462 return $out;
13463 }
13464
13465 // Here, $url is a simple link
13466
13467 if (!empty($params['isDropdown']) || !empty($params['isDropDown'])) { // Use the dropdown-item style (not for action button)
13468 $class = "dropdown-item";
13469 } else {
13470 $class = 'butAction';
13471 if ($actionType == 'danger' || $actionType == 'delete') {
13472 $class = 'butActionDelete';
13473 if (!empty($url) && strpos($url, 'token=') === false) {
13474 $url .= '&token='.newToken();
13475 }
13476 }
13477 }
13478 $attr = array(
13479 'class' => $class,
13480 'href' => empty($url) ? '' : $url,
13481 'title' => $label
13482 );
13483
13484 if (empty($text)) {
13485 $text = $label;
13486 $attr['title'] = ''; // if html not set, leave label on title is redundant
13487 } else {
13488 $attr['title'] = $label;
13489 $attr['aria-label'] = $label;
13490 }
13491
13492 if (empty($userRight) || $userRight < 0) {
13493 $attr['class'] = 'butActionRefused';
13494 $attr['href'] = '';
13495 $attr['title'] = (($label && $text && $label != $text) ? $label : '');
13496 $attr['title'] = ($attr['title'] ? $attr['title'] . (empty($userRight) ? '<br>' : '') : '').(empty($userRight) ? $langs->trans('NotEnoughPermissions') : '');
13497 }
13498
13499 if (!empty($id)) {
13500 $attr['id'] = $id;
13501 }
13502
13503 // Override attr
13504 if (!empty($params['attr']) && is_array($params['attr'])) {
13505 foreach ($params['attr'] as $key => $value) {
13506 if ($key == 'class') {
13507 $attr['class'] .= ' '.$value;
13508 } elseif ($key == 'classOverride') {
13509 $attr['class'] = $value;
13510 } else {
13511 $attr[$key] = $value;
13512 }
13513 }
13514 }
13515
13516 // automatic add tooltip when title is detected
13517 if (!empty($attr['title']) && !empty($attr['class']) && strpos($attr['class'], 'classfortooltip') === false) {
13518 $attr['class'] .= ' classfortooltip';
13519 }
13520
13521 // Js Confirm button
13522 if ($userRight && !empty($params['confirm'])) {
13523 if (!is_array($params['confirm'])) {
13524 $params['confirm'] = array();
13525 }
13526
13527 if (empty($params['confirm']['url'])) {
13528 $params['confirm']['url'] = $url . (strpos($url, '?') > 0 ? '&' : '?') . 'confirm=yes';
13529 }
13530
13531 // for js disabled compatibility set $url as call to confirm action and $params['confirm']['url'] to confirmed action
13532 $attr['data-confirm-url'] = $params['confirm']['url'];
13533 $attr['data-confirm-title'] = !empty($params['confirm']['title']) ? $params['confirm']['title'] : $langs->trans('ConfirmBtnCommonTitle', $label);
13534 $attr['data-confirm-content'] = !empty($params['confirm']['content']) ? $params['confirm']['content'] : $langs->trans('ConfirmBtnCommonContent', $label);
13535 $attr['data-confirm-content'] = preg_replace("/\r|\n/", "", $attr['data-confirm-content']);
13536 $attr['data-confirm-action-btn-label'] = !empty($params['confirm']['action-btn-label']) ? $params['confirm']['action-btn-label'] : $langs->trans('Confirm');
13537 $attr['data-confirm-cancel-btn-label'] = !empty($params['confirm']['cancel-btn-label']) ? $params['confirm']['cancel-btn-label'] : $langs->trans('CloseDialog');
13538 $attr['data-confirm-modal'] = !empty($params['confirm']['modal']) ? $params['confirm']['modal'] : true;
13539
13540 $attr['class'] .= ' butActionConfirm';
13541 }
13542
13543 if (isset($attr['href']) && empty($attr['href'])) {
13544 unset($attr['href']);
13545 }
13546
13547 $TCompiledAttr = array();
13548 foreach ($attr as $key => $value) {
13549 if (!empty($params['use_unsecured_unescapedattr']) && is_array($params['use_unsecured_unescapedattr']) && in_array($key, $params['use_unsecured_unescapedattr'])) {
13550 // Not recommended
13551 $value = dol_htmlentities($value, ENT_QUOTES | ENT_SUBSTITUTE);
13552 } elseif ($key == 'href') {
13553 $value = dolPrintHTMLForAttributeUrl($value);
13554 } else {
13555 $value = dolPrintHTMLForAttribute($value);
13556 }
13557
13558 $TCompiledAttr[] = $key.'="'.$value.'"'; // $value has been escaped by the dolPrintHTMLForAttribute... just before
13559 }
13560
13561 $compiledAttributes = empty($TCompiledAttr) ? '' : implode(' ', $TCompiledAttr);
13562
13563 $tag = !empty($attr['href']) ? 'a' : 'span';
13564
13565
13566 $parameters = array(
13567 'TCompiledAttr' => $TCompiledAttr, // array
13568 'compiledAttributes' => $compiledAttributes, // string
13569 'attr' => $attr,
13570 'tag' => $tag,
13571 'label' => $label,
13572 'html' => $text,
13573 'actionType' => $actionType,
13574 'url' => $url,
13575 'id' => $id,
13576 'userRight' => $userRight,
13577 'params' => $params
13578 );
13579
13580 $reshook = $hookmanager->executeHooks('dolGetButtonAction', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
13581 if ($reshook < 0) {
13582 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
13583 }
13584
13585 if (empty($reshook)) {
13586 if (dol_textishtml($text)) { // If content already HTML encoded
13587 return '<' . $tag . ' ' . $compiledAttributes . '><span class="textbutton">' . $text . '</span></' . $tag . '>';
13588 } else {
13589 return '<' . $tag . ' ' . $compiledAttributes . '><span class="textbutton">' . dol_escape_htmltag($text) . '</span></' . $tag . '>';
13590 }
13591 } else {
13592 return $hookmanager->resPrint;
13593 }
13594}
13595
13596
13605function dolCompletUrlForDropdownButton(string $url, array $params, bool $addDolUrlRoot = true)
13606{
13607 if (empty($url)) {
13608 return '';
13609 }
13610
13611 $parsedUrl = parse_url($url);
13612 if ((isset($parsedUrl['scheme']) && in_array($parsedUrl['scheme'], ['javascript', 'mailto', 'tel'])) || strpos($url, '#') === 0) {
13613 return $url;
13614 }
13615
13616 if (!empty($parsedUrl['query'])) {
13617 // Use parse_str() function to parse the string passed via URL
13618 parse_str($parsedUrl['query'], $urlQuery);
13619 if (!isset($urlQuery['backtopage']) && isset($params['backtopage'])) {
13620 $url .= '&amp;backtopage='.urlencode($params['backtopage']);
13621 }
13622 }
13623
13624 if (!isset($parsedUrl['scheme']) && $addDolUrlRoot) {
13625 $url = DOL_URL_ROOT.$url;
13626 }
13627
13628 return $url;
13629}
13630
13631
13638function dolGetButtonTitleSeparator($moreClass = "")
13639{
13640 return '<span class="button-title-separator '.$moreClass.'" ></span>';
13641}
13642
13649function getFieldErrorIcon($fieldValidationErrorMsg)
13650{
13651 $out = '';
13652 if (!empty($fieldValidationErrorMsg)) {
13653 $out .= '<span class="field-error-icon classfortooltip" title="'.dol_escape_htmltag($fieldValidationErrorMsg, 1).'" role="alert" >'; // role alert is used for accessibility
13654 $out .= '<span class="fa fa-exclamation-circle" aria-hidden="true" ></span>'; // For accessibility icon is separated and aria-hidden
13655 $out .= '</span>';
13656 }
13657
13658 return $out;
13659}
13660
13673function dolGetButtonTitle($label, $helpText = '', $iconClass = 'fa fa-file', $url = '', $id = '', $status = 1, $params = array())
13674{
13675 global $langs, $user;
13676
13677 // Actually this conf is used in css too for external module compatibility and smooth transition to this function
13678 if (getDolGlobalString('MAIN_BUTTON_HIDE_UNAUTHORIZED') && (!$user->admin) && $status <= 0) {
13679 return '';
13680 }
13681 // Fix old picto fa-th-list to use fa-grid-vertical instead
13682 if ($iconClass == 'fa fa-th-list imgforviewmode') {
13683 $iconClass = ' fa fa-grip-horizontal imgforviewmode';
13684 }
13685
13686 $class = 'btnTitle';
13687 if (in_array($iconClass, array('fa fa-plus-circle', 'fa fa-plus-circle size15x', 'fa fa-comment-dots', 'fa fa-paper-plane'))) {
13688 $class .= ' btnTitlePlus';
13689 }
13690 $useclassfortooltip = 1;
13691
13692 if (!empty($params['morecss'])) {
13693 $class .= ' '.$params['morecss'];
13694 }
13695
13696 $attr = array(
13697 'class' => $class,
13698 'href' => empty($url) ? '' : $url
13699 );
13700
13701 if (!empty($helpText)) {
13702 $attr['title'] = $helpText;
13703 } elseif ($label) { // empty($attr['title']) &&
13704 $attr['title'] = $label;
13705 $useclassfortooltip = 0;
13706 }
13707
13708 if ($status == 2) {
13709 $attr['class'] .= ' btnTitleSelected';
13710 } elseif ($status <= 0) {
13711 $attr['class'] .= ' refused';
13712
13713 $attr['href'] = '';
13714
13715 if ($status == -1) { // disable
13716 $attr['title'] = $langs->transnoentitiesnoconv("FeatureDisabled");
13717 } elseif ($status == 0) { // Not enough permissions
13718 $attr['title'] = $langs->transnoentitiesnoconv("NotEnoughPermissions");
13719 }
13720 }
13721
13722 if (!empty($attr['title']) && $useclassfortooltip) {
13723 $attr['class'] .= ' classfortooltip';
13724 }
13725
13726 if (!empty($id)) {
13727 $attr['id'] = $id;
13728 }
13729
13730 // Override attr
13731 if (!empty($params['attr']) && is_array($params['attr'])) {
13732 foreach ($params['attr'] as $key => $value) {
13733 if ($key == 'class') {
13734 $attr['class'] .= ' '.$value;
13735 } elseif ($key == 'classOverride') {
13736 $attr['class'] = $value;
13737 } else {
13738 $attr[$key] = $value;
13739 }
13740 }
13741 }
13742
13743 if (isset($attr['href']) && empty($attr['href'])) {
13744 unset($attr['href']);
13745 }
13746
13747 // TODO : add a hook
13748
13749 // Generate attributes with escapement
13750 $TCompiledAttr = array();
13751 foreach ($attr as $key => $value) {
13752 $TCompiledAttr[] = $key.'="'.dol_escape_htmltag($value).'"'; // Do not use dolPrintHTMLForAttribute() here, we must accept "javascript:string"
13753 }
13754
13755 $compiledAttributes = (empty($TCompiledAttr) ? '' : implode(' ', $TCompiledAttr));
13756
13757 $tag = (empty($attr['href']) ? 'span' : 'a');
13758
13759 $button = '<'.$tag.' '.$compiledAttributes.'>';
13760 $button .= '<span class="'.$iconClass.' valignmiddle btnTitle-icon"></span>';
13761 if (!empty($params['forcenohideoftext'])) {
13762 $button .= '<span class="valignmiddle text-plus-circle btnTitle-label'.(empty($params['forcenohideoftext']) ? ' hideonsmartphone' : '').'">'.$label.'</span>';
13763 }
13764 $button .= '</'.$tag.'>';
13765
13766 return $button;
13767}
13768
13778function getElementProperties($elementType)
13779{
13780 global $conf, $db, $hookmanager;
13781
13782 $regs = array();
13783
13784 //$element_type='facture';
13785
13786 $classfile = $classname = $classpath = $subdir = $dir_output = $dir_temp = $parent_element = '';
13787
13788 // Parse element/subelement
13789 $module = $elementType;
13790 $element = $elementType;
13791 $subelement = $elementType;
13792 $table_element = $elementType;
13793
13794 // If we ask a resource form external module (instead of default path)
13795 if (preg_match('/^([^@]+)@([^@]+)$/i', $elementType, $regs)) { // 'myobject@mymodule'
13796 $element = $subelement = $regs[1];
13797 $module = $regs[2];
13798 }
13799
13800 // If we ask a resource for a string with an element and a subelement
13801 // Example 'project_task'
13802 if (preg_match('/^([^_]+)_([^_]+)/i', $element, $regs)) { // 'myobject_mysubobject' with myobject=mymodule
13803 $module = $element = $regs[1];
13804 $subelement = $regs[2];
13805 }
13806
13807 // Object lines will use parent classpath and module ref
13808 if (substr($elementType, -3) == 'det') {
13809 $module = preg_replace('/det$/', '', $element);
13810 $subelement = preg_replace('/det$/', '', $subelement);
13811 $classpath = $module.'/class';
13812 $classfile = $module;
13813 $classname = preg_replace('/det$/', 'Line', $element);
13814 if (in_array($module, array('expedition', 'propale', 'facture', 'contrat', 'fichinter', 'commandefournisseur'))) {
13815 $classname = preg_replace('/det$/', 'Ligne', $element);
13816 }
13817 }
13818 // For compatibility and to work with non standard path
13819 if ($elementType == "action" || $elementType == "actioncomm") {
13820 $classpath = 'comm/action/class';
13821 $subelement = 'Actioncomm';
13822 $module = 'agenda';
13823 $table_element = 'actioncomm';
13824 } elseif ($elementType == 'cronjob') {
13825 $classpath = 'cron/class';
13826 $module = 'cron';
13827 $table_element = 'cron';
13828 } elseif ($elementType == 'adherent_type') {
13829 $classpath = 'adherents/class';
13830 $classfile = 'adherent_type';
13831 $module = 'adherent';
13832 $subelement = 'adherent_type';
13833 $classname = 'AdherentType';
13834 $table_element = 'adherent_type';
13835 } elseif ($elementType == 'bank_account') {
13836 $classpath = 'compta/bank/class';
13837 $module = 'bank'; // We need $conf->bank->dir_output and not $conf->banque->dir_output
13838 $classfile = 'account';
13839 $classname = 'Account';
13840 } elseif ($elementType == 'bank_line') {
13841 $classpath = 'compta/bank/class';
13842 $module = 'bank'; // We need $conf->bank->dir_output and not $conf->banque->dir_output
13843 $classfile = 'account';
13844 $classname = 'AccountLine';
13845 } elseif ($elementType == 'category') {
13846 $classpath = 'categories/class';
13847 $module = 'categorie';
13848 $subelement = 'categorie';
13849 $table_element = 'categorie';
13850 } elseif ($elementType == 'contact') {
13851 $classpath = 'contact/class';
13852 $classfile = 'contact';
13853 $module = 'societe';
13854 $subelement = 'contact';
13855 $table_element = 'socpeople';
13856 } elseif ($elementType == 'inventory') {
13857 $module = 'product';
13858 $classpath = 'product/inventory/class';
13859 } elseif ($elementType == 'inventoryline') {
13860 $module = 'product';
13861 $classpath = 'product/inventory/class';
13862 $table_element = 'inventorydet';
13863 $parent_element = 'inventory';
13864 } elseif ($elementType == 'stock' || $elementType == 'entrepot' || $elementType == 'warehouse') {
13865 $module = 'stock';
13866 $classpath = 'product/stock/class';
13867 $classfile = 'entrepot';
13868 $classname = 'Entrepot';
13869 $table_element = 'entrepot';
13870 } elseif ($elementType == 'project') {
13871 $classpath = 'projet/class';
13872 $module = 'projet';
13873 $table_element = 'projet';
13874 } elseif ($elementType == 'project_task') {
13875 $classpath = 'projet/class';
13876 $module = 'projet';
13877 $subelement = 'task';
13878 $table_element = 'projet_task';
13879 } elseif ($elementType == 'facture' || $elementType == 'invoice') {
13880 $classpath = 'compta/facture/class';
13881 $module = 'facture';
13882 $subelement = 'facture';
13883 $table_element = 'facture';
13884 } elseif ($elementType == 'facturedet') {
13885 $classpath = 'compta/facture/class';
13886 $classfile = 'facture';
13887 $classname = 'FactureLigne';
13888 $module = 'facture';
13889 $table_element = 'facturedet';
13890 $parent_element = 'facture';
13891 } elseif ($elementType == 'facturerec') {
13892 $classpath = 'compta/facture/class';
13893 $classfile = 'facture-rec';
13894 $module = 'facture';
13895 $classname = 'FactureRec';
13896 } elseif ($elementType == 'commande' || $elementType == 'order') {
13897 $classpath = 'commande/class';
13898 $module = 'commande';
13899 $subelement = 'commande';
13900 $table_element = 'commande';
13901 } elseif ($elementType == 'commandedet') {
13902 $classpath = 'commande/class';
13903 $classfile = 'commande';
13904 $classname = 'OrderLine';
13905 $module = 'commande';
13906 $table_element = 'commandedet';
13907 $parent_element = 'commande';
13908 } elseif ($elementType == 'propal') {
13909 $classpath = 'comm/propal/class';
13910 $table_element = 'propal';
13911 } elseif ($elementType == 'propaldet') {
13912 $classpath = 'comm/propal/class';
13913 $classfile = 'propal';
13914 $subelement = 'propaleligne';
13915 $module = 'propal';
13916 $table_element = 'propaldet';
13917 $parent_element = 'propal';
13918 } elseif ($elementType == 'shipping') {
13919 $classpath = 'expedition/class';
13920 $classfile = 'expedition';
13921 $classname = 'Expedition';
13922 $module = 'expedition';
13923 $table_element = 'expedition';
13924 } elseif ($elementType == 'expeditiondet' || $elementType == 'shippingdet') {
13925 $classpath = 'expedition/class';
13926 $classfile = 'expedition';
13927 $classname = 'ExpeditionLigne';
13928 $module = 'expedition';
13929 $table_element = 'expeditiondet';
13930 $parent_element = 'expedition';
13931 } elseif ($elementType == 'delivery_note') {
13932 $classpath = 'delivery/class';
13933 $subelement = 'delivery';
13934 $module = 'expedition';
13935 } elseif ($elementType == 'delivery') {
13936 $classpath = 'delivery/class';
13937 $subelement = 'delivery';
13938 $module = 'expedition';
13939 } elseif ($elementType == 'deliverydet') {
13940 // @todo
13941 } elseif ($elementType == 'supplier_proposal') {
13942 $classpath = 'supplier_proposal/class';
13943 $module = 'supplier_proposal';
13944 $element = 'supplierproposal';
13945 $classfile = 'supplier_proposal';
13946 $subelement = 'supplierproposal';
13947 } elseif ($elementType == 'supplier_proposaldet') {
13948 $classpath = 'supplier_proposal/class';
13949 $module = 'supplier_proposal';
13950 $classfile = 'supplier_proposal';
13951 $classname = 'SupplierProposalLine';
13952 $table_element = 'supplier_proposaldet';
13953 $parent_element = 'supplier_proposal';
13954 } elseif ($elementType == 'contract') {
13955 $classpath = 'contrat/class';
13956 $module = 'contrat';
13957 $subelement = 'contrat';
13958 $table_element = 'contract';
13959 } elseif ($elementType == 'contratdet') {
13960 $classpath = 'contrat/class';
13961 $module = 'contrat';
13962 $table_element = 'contratdet';
13963 $parent_element = 'contrat';
13964 } elseif ($elementType == 'mailing') {
13965 $classpath = 'comm/mailing/class';
13966 $module = 'mailing';
13967 $classfile = 'mailing';
13968 $classname = 'Mailing';
13969 $subelement = '';
13970 } elseif ($elementType == 'member' || $elementType == 'adherent') {
13971 $classpath = 'adherents/class';
13972 $module = 'adherent';
13973 $subelement = 'adherent';
13974 $table_element = 'adherent';
13975 } elseif ($elementType == 'subscription') {
13976 $classpath = 'adherents/class';
13977 $classfile = 'subscription';
13978 $module = 'adherent';
13979 $subelement = 'subscription';
13980 $classname = 'Subscription';
13981 $table_element = 'subscription';
13982 } elseif ($elementType == 'usergroup') {
13983 $classpath = 'user/class';
13984 $module = 'user';
13985 } elseif ($elementType == 'mo') {
13986 $classpath = 'mrp/class';
13987 $classfile = 'mo';
13988 $classname = 'Mo';
13989 $module = 'mrp';
13990 $subelement = '';
13991 $table_element = 'mrp_mo';
13992 } elseif ($elementType == 'mrp_production') {
13993 $classpath = 'mrp/class';
13994 $classfile = 'mo';
13995 $classname = 'MoLine';
13996 $module = 'mrp';
13997 $subelement = '';
13998 $table_element = 'mrp_production';
13999 $parent_element = 'mo';
14000 } elseif ($elementType == 'cabinetmed_cons') {
14001 $classpath = 'cabinetmed/class';
14002 $module = 'cabinetmed';
14003 $subelement = 'cabinetmedcons';
14004 $table_element = 'cabinetmedcons';
14005 } elseif ($elementType == 'fichinter') {
14006 $classpath = 'fichinter/class';
14007 $module = 'ficheinter';
14008 $subelement = 'fichinter';
14009 $table_element = 'fichinter';
14010 } elseif ($elementType == 'dolresource' || $elementType == 'resource') {
14011 $classpath = 'resource/class';
14012 $module = 'resource';
14013 $subelement = 'dolresource';
14014 $table_element = 'resource';
14015 } elseif ($elementType == 'opensurvey_sondage') {
14016 $classpath = 'opensurvey/class';
14017 $module = 'opensurvey';
14018 $subelement = 'opensurveysondage';
14019 } elseif ($elementType == 'order_supplier' || $elementType == 'supplier_order' ||$elementType == 'commande_fournisseur' || $elementType == 'commandefournisseur') {
14020 $classpath = 'fourn/class';
14021 $module = 'fournisseur';
14022 $classfile = 'fournisseur.commande';
14023 $element = 'order_supplier';
14024 $subelement = '';
14025 $classname = 'CommandeFournisseur';
14026 $table_element = 'commande_fournisseur';
14027 } elseif ($elementType == 'commande_fournisseurdet') {
14028 $classpath = 'fourn/class';
14029 $module = 'fournisseur';
14030 $classfile = 'fournisseur.commande';
14031 $element = 'commande_fournisseurdet';
14032 $subelement = '';
14033 $classname = 'CommandeFournisseurLigne';
14034 $table_element = 'commande_fournisseurdet';
14035 $parent_element = 'commande_fournisseur';
14036 } elseif ($elementType == 'invoice_supplier' || $elementType == 'supplier_invoice' || $elementType == 'facture_fourn') {
14037 $classpath = 'fourn/class';
14038 $module = 'fournisseur';
14039 $classfile = 'fournisseur.facture';
14040 $element = 'invoice_supplier';
14041 $subelement = '';
14042 $classname = 'FactureFournisseur';
14043 $table_element = 'facture_fourn';
14044 } elseif ($elementType == 'facture_fourn_det') {
14045 $classpath = 'fourn/class';
14046 $module = 'fournisseur';
14047 $classfile = 'fournisseur.facture';
14048 $element = 'facture_fourn_det';
14049 $subelement = '';
14050 $classname = 'SupplierInvoiceLine';
14051 $table_element = 'facture_fourn_det';
14052 $parent_element = 'invoice_supplier';
14053 } elseif ($elementType == "service") {
14054 $classpath = 'product/class';
14055 $subelement = 'product';
14056 $table_element = 'product';
14057 } elseif ($elementType == 'salary') {
14058 $classpath = 'salaries/class';
14059 $module = 'salaries';
14060 } elseif ($elementType == 'payment_salary') {
14061 $classpath = 'salaries/class';
14062 $classfile = 'paymentsalary';
14063 $classname = 'PaymentSalary';
14064 $module = 'salaries';
14065 } elseif ($elementType == 'productlot') {
14066 $module = 'productbatch';
14067 $classpath = 'product/stock/class';
14068 $classfile = 'productlot';
14069 $classname = 'Productlot';
14070 $element = 'productlot';
14071 $subelement = '';
14072 $table_element = 'product_lot';
14073 } elseif ($elementType == 'societeaccount') {
14074 $classpath = 'societe/class';
14075 $classfile = 'societeaccount';
14076 $classname = 'SocieteAccount';
14077 $module = 'societe';
14078 } elseif ($elementType == 'websitepage' || $elementType == 'website_page') {
14079 $classpath = 'website/class';
14080 $classfile = 'websitepage';
14081 $classname = 'Websitepage';
14082 $module = 'website';
14083 $subelement = 'websitepage';
14084 $table_element = 'website_page';
14085 } elseif ($elementType == 'fiscalyear') {
14086 $classpath = 'core/class';
14087 $module = 'accounting';
14088 $subelement = 'fiscalyear';
14089 } elseif ($elementType == 'chargesociales') {
14090 $classpath = 'compta/sociales/class';
14091 $module = 'tax';
14092 $table_element = 'chargesociales';
14093 } elseif ($elementType == 'tva') {
14094 $classpath = 'compta/tva/class';
14095 $module = 'tax';
14096 $subdir = '/vat';
14097 $table_element = 'tva';
14098 } elseif ($elementType == 'emailsenderprofile') {
14099 $module = '';
14100 $classpath = 'core/class';
14101 $classfile = 'emailsenderprofile';
14102 $classname = 'EmailSenderProfile';
14103 $table_element = 'c_email_senderprofile';
14104 $subelement = '';
14105 } elseif ($elementType == 'conferenceorboothattendee') {
14106 $classpath = 'eventorganization/class';
14107 $classfile = 'conferenceorboothattendee';
14108 $classname = 'ConferenceOrBoothAttendee';
14109 $module = 'eventorganization';
14110 } elseif ($elementType == 'conferenceorbooth') {
14111 $classpath = 'eventorganization/class';
14112 $classfile = 'conferenceorbooth';
14113 $classname = 'ConferenceOrBooth';
14114 $module = 'eventorganization';
14115 } elseif ($elementType == 'ccountry') {
14116 $module = '';
14117 $classpath = 'core/class';
14118 $classfile = 'ccountry';
14119 $classname = 'Ccountry';
14120 $table_element = 'c_country';
14121 $subelement = '';
14122 } elseif ($elementType == 'ecmfiles') {
14123 $module = 'ecm';
14124 $classpath = 'ecm/class';
14125 $classfile = 'ecmfiles';
14126 $classname = 'Ecmfiles';
14127 $table_element = 'ecmfiles';
14128 $subelement = '';
14129 } elseif ($elementType == 'knowledgerecord' || $elementType == 'knowledgemanagement') {
14130 $module = 'knowledgemanagement';
14131 $classpath = 'knowledgemanagement/class';
14132 $classfile = 'knowledgerecord';
14133 $classname = 'KnowledgeRecord';
14134 $table_element = 'knowledgemanagement_knowledgerecord';
14135 $subelement = '';
14136 } elseif ($elementType == 'customer') {
14137 $module = 'societe';
14138 $classpath = 'societe/class';
14139 $classfile = 'client';
14140 $classname = 'Client';
14141 $table_element = 'societe';
14142 $subelement = '';
14143 } elseif ($elementType == 'fournisseur' || $elementType == 'supplier') {
14144 $module = 'societe';
14145 $classpath = 'fourn/class';
14146 $classfile = 'fournisseur';
14147 $classname = 'Fournisseur';
14148 $table_element = 'societe';
14149 $subelement = '';
14150 }
14151
14152
14153 if (empty($classfile)) {
14154 $classfile = strtolower($subelement);
14155 }
14156 if (empty($classname)) {
14157 $classname = ucfirst($subelement);
14158 }
14159 if (empty($classpath)) {
14160 $classpath = $module.'/class';
14161 }
14162
14163 //print 'getElementProperties subdir='.$subdir;
14164
14165 // Set dir_output
14166 if ($module && isset($conf->$module)) { // The generic case
14167 if (!empty($conf->$module->multidir_output[$conf->entity])) {
14168 $dir_output = $conf->$module->multidir_output[$conf->entity];
14169 } elseif (!empty($conf->$module->output[$conf->entity])) {
14170 $dir_output = $conf->$module->output[$conf->entity];
14171 } elseif (!empty($conf->$module->dir_output)) {
14172 $dir_output = $conf->$module->dir_output;
14173 }
14174 if (!empty($conf->$module->multidir_temp[$conf->entity])) {
14175 $dir_temp = $conf->$module->multidir_temp[$conf->entity];
14176 } elseif (!empty($conf->$module->temp[$conf->entity])) {
14177 $dir_temp = $conf->$module->temp[$conf->entity];
14178 } elseif (!empty($conf->$module->dir_temp)) {
14179 $dir_temp = $conf->$module->dir_temp;
14180 }
14181 }
14182
14183 // Overwrite value for special cases
14184 if ($element == 'order_supplier' && isModEnabled('fournisseur')) {
14185 $dir_output = $conf->fournisseur->commande->dir_output;
14186 $dir_temp = $conf->fournisseur->commande->dir_temp;
14187 } elseif ($element == 'invoice_supplier' && isModEnabled('fournisseur')) {
14188 $dir_output = $conf->fournisseur->facture->dir_output;
14189 $dir_temp = $conf->fournisseur->facture->dir_temp;
14190 }
14191 $dir_output .= $subdir;
14192 $dir_temp .= $subdir;
14193
14194 $elementProperties = array(
14195 'module' => $module,
14196 'element' => $element,
14197 'table_element' => $table_element,
14198 'subelement' => $subelement,
14199 'classpath' => $classpath,
14200 'classfile' => $classfile,
14201 'classname' => $classname,
14202 'dir_output' => $dir_output,
14203 'dir_temp' => $dir_temp,
14204 'parent_element' => $parent_element,
14205 );
14206
14207
14208 // Add hook
14209 if (!is_object($hookmanager)) {
14210 include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
14211 $hookmanager = new HookManager($db);
14212 }
14213 $hookmanager->initHooks(array('elementproperties'));
14214
14215
14216 // Hook params
14217 $parameters = array(
14218 'elementType' => $elementType,
14219 'elementProperties' => $elementProperties
14220 );
14221
14222 $reshook = $hookmanager->executeHooks('getElementProperties', $parameters);
14223
14224 if ($reshook) {
14225 $elementProperties = $hookmanager->resArray;
14226 } elseif (!empty($hookmanager->resArray) && is_array($hookmanager->resArray)) { // resArray is always an array but for sécurity against misconfigured external modules
14227 $elementProperties = array_replace($elementProperties, $hookmanager->resArray);
14228 }
14229
14230 // context of elementproperties doesn't need to exist out of this function so delete it to avoid elementproperties context is equal to all
14231 if (($key = array_search('elementproperties', $hookmanager->contextarray)) !== false) {
14232 unset($hookmanager->contextarray[$key]);
14233 }
14234
14235 return $elementProperties;
14236}
14237
14250function fetchObjectByElement($element_id, $element_type, $element_ref = '', $useCache = 0, $maxCacheByType = 10)
14251{
14252 global $db, $conf;
14253
14254 $ret = 0;
14255
14256 $element_prop = getElementProperties($element_type);
14257
14258 if ($element_prop['module'] == 'product' || $element_prop['module'] == 'service') {
14259 // For example, for an extrafield 'product' (shared for both product and service) that is a link to an object,
14260 // this is called with $element_type = 'product' when we need element properties of a service, we must return a product. If we create the
14261 // extrafield for a service, it is not supported and not found when editing the product/service card. So we must keep 'product' for extrafields
14262 // of service and we will return properties of a product.
14263 $ismodenabled = (isModEnabled('product') || isModEnabled('service'));
14264 } elseif ($element_prop['module'] == 'societeaccount') {
14265 $ismodenabled = isModEnabled('website') || isModEnabled('webportal');
14266 } else {
14267 $ismodenabled = isModEnabled($element_prop['module']);
14268 }
14269 //var_dump('element_type='.$element_type);
14270 //var_dump($element_prop);
14271 //var_dump($element_prop['module'].' '.$ismodenabled);
14272 if (is_array($element_prop) && (empty($element_prop['module']) || $ismodenabled)) {
14273 if ($useCache === 1 && $element_id > 0
14274 && !empty($conf->cache['fetchObjectByElement'][$element_type])
14275 && !empty($conf->cache['fetchObjectByElement'][$element_type][$element_id])
14276 && is_object($conf->cache['fetchObjectByElement'][$element_type][$element_id])
14277 ) {
14278 return $conf->cache['fetchObjectByElement'][$element_type][$element_id];
14279 }
14280
14281 dol_include_once('/'.$element_prop['classpath'].'/'.$element_prop['classfile'].'.class.php');
14282
14283 if (class_exists($element_prop['classname'])) {
14284 $className = $element_prop['classname'];
14285 $objecttmp = new $className($db);
14286 '@phan-var-force CommonObject $objecttmp';
14287
14288 if ($element_id > 0 || !empty($element_ref)) {
14289 $ret = $objecttmp->fetch($element_id, $element_ref);
14290 if ($ret >= 0) {
14291 if (empty($objecttmp->module)) {
14292 $objecttmp->module = $element_prop['module'];
14293 }
14294
14295 if ($useCache > 0) {
14296 if (!isset($conf->cache['fetchObjectByElement'][$element_type])) {
14297 $conf->cache['fetchObjectByElement'][$element_type] = [];
14298 }
14299
14300 // Manage cache limit
14301 if (! empty($conf->cache['fetchObjectByElement'][$element_type]) && is_array($conf->cache['fetchObjectByElement'][$element_type]) && count($conf->cache['fetchObjectByElement'][$element_type]) >= $maxCacheByType) {
14302 array_shift($conf->cache['fetchObjectByElement'][$element_type]);
14303 }
14304
14305 $conf->cache['fetchObjectByElement'][$element_type][$element_id] = $objecttmp;
14306 }
14307
14308 return $objecttmp;
14309 }
14310 } else {
14311 return $objecttmp; // returned an object without fetch
14312 }
14313 } else {
14314 dol_syslog($element_prop['classname'].' doesn\'t exists in /'.$element_prop['classpath'].'/'.$element_prop['classfile'].'.class.php');
14315 return -1;
14316 }
14317 }
14318
14319 return $ret;
14320}
14321
14327function getExecutableContent()
14328{
14329 $arrayofregexextension = array(
14330 'htm', 'html', 'shtml', 'js', 'phar', 'php', 'php3', 'php4', 'php5', 'phtml', 'pht', 'pl', 'py', 'cgi', 'ksh', 'sh', 'shtml',
14331 'bash', 'bat', 'cmd', 'wpk', 'exe', 'dmg', 'appimage'
14332 );
14333
14334 return $arrayofregexextension;
14335}
14336
14343function isAFileWithExecutableContent($filename)
14344{
14345 $arrayofregexextension = getExecutableContent();
14346
14347 foreach ($arrayofregexextension as $fileextension) {
14348 if (preg_match('/\.'.preg_quote($fileextension, '/').'$/i', $filename)) {
14349 return true;
14350 }
14351 }
14352
14353 return false;
14354}
14355
14363function newToken()
14364{
14365 return empty($_SESSION['newtoken']) ? '' : $_SESSION['newtoken'];
14366}
14367
14375function currentToken()
14376{
14377 return isset($_SESSION['token']) ? $_SESSION['token'] : '';
14378}
14379
14385function getNonce()
14386{
14387 global $conf;
14388
14389 if (empty($conf->cache['nonce'])) {
14390 $conf->cache['nonce'] = dolGetRandomBytes(8);
14391 }
14392
14393 return $conf->cache['nonce'];
14394}
14395
14396
14410function startSimpleTable($header, $link = "", $arguments = "", $emptyColumns = 0, $number = -1, $pictofulllist = '')
14411{
14412 global $langs;
14413
14414 print '<div class="div-table-responsive-no-min">';
14415 print '<table class="noborder centpercent">';
14416 print '<tr class="liste_titre">';
14417
14418 print ($emptyColumns < 1) ? '<th>' : '<th colspan="'.($emptyColumns + 1).'">';
14419
14420 print '<span class="valignmiddle">'.$langs->trans($header).'</span>';
14421
14422 if (!empty($link)) {
14423 if (!empty($arguments)) {
14424 print '<a href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
14425 } else {
14426 print '<a href="'.DOL_URL_ROOT.'/'.$link.'">';
14427 }
14428 }
14429
14430 if ($number > -1) {
14431 print '<span class="badge marginleftonlyshort">'.$number.'</span>';
14432 } elseif (!empty($link)) {
14433 print '<span class="badge marginleftonlyshort">...</span>';
14434 }
14435
14436 if (!empty($link)) {
14437 print '</a>';
14438 }
14439
14440 print '</th>';
14441
14442 if ($number < 0 && !empty($link)) {
14443 print '<th class="right">';
14444 print '</th>';
14445 }
14446
14447 print '</tr>';
14448}
14449
14458function finishSimpleTable($addLineBreak = false)
14459{
14460 print '</table>';
14461 print '</div>';
14462
14463 if ($addLineBreak) {
14464 print '<br>';
14465 }
14466}
14467
14479function addSummaryTableLine($tableColumnCount, $num, $nbofloop = 0, $total = 0, $noneWord = "None", $extraRightColumn = false)
14480{
14481 global $langs;
14482
14483 if ($num === 0) {
14484 print '<tr class="oddeven">';
14485 print '<td colspan="'.$tableColumnCount.'"><span class="opacitymedium">'.$langs->trans($noneWord).'</span></td>';
14486 print '</tr>';
14487 return;
14488 }
14489
14490 if ($nbofloop === 0) {
14491 // don't show a summary line
14492 return;
14493 }
14494
14495 /* Case already handled above, commented to satisfy phpstan.
14496 if ($num === 0) {
14497 $colspan = $tableColumnCount;
14498 } else
14499 */
14500 if ($num > $nbofloop) {
14501 $colspan = $tableColumnCount;
14502 } else {
14503 $colspan = $tableColumnCount - 1;
14504 }
14505
14506 if ($extraRightColumn) {
14507 $colspan--;
14508 }
14509
14510 print '<tr class="liste_total">';
14511
14512 if ($nbofloop > 0 && $num > $nbofloop) {
14513 print '<td colspan="'.$colspan.'" class="right">'.$langs->trans("XMoreLines", ($num - $nbofloop)).'</td>';
14514 } else {
14515 print '<td colspan="'.$colspan.'" class="right"> '.$langs->trans("Total").'</td>';
14516 print '<td class="right centpercent">'.price($total).'</td>';
14517 }
14518
14519 if ($extraRightColumn) {
14520 print '<td></td>';
14521 }
14522
14523 print '</tr>';
14524}
14525
14534function readfileLowMemory($fullpath_original_file_osencoded, $method = -1)
14535{
14536 if ($method == -1) {
14537 $method = 0;
14538 if (getDolGlobalString('MAIN_FORCE_READFILE_WITH_FREAD')) {
14539 $method = 1;
14540 }
14541 if (getDolGlobalString('MAIN_FORCE_READFILE_WITH_STREAM_COPY')) {
14542 $method = 2;
14543 }
14544 }
14545
14546 // Be sure we don't have output buffering enabled to have readfile working correctly
14547 while (ob_get_level()) {
14548 ob_end_flush();
14549 }
14550
14551 // Solution 0
14552 if ($method == 0) {
14553 readfile($fullpath_original_file_osencoded);
14554 } elseif ($method == 1) {
14555 // Solution 1
14556 $handle = fopen($fullpath_original_file_osencoded, "rb");
14557 while (!feof($handle)) {
14558 print fread($handle, 8192);
14559 }
14560 fclose($handle);
14561 } elseif ($method == 2) {
14562 // Solution 2
14563 $handle1 = fopen($fullpath_original_file_osencoded, "rb");
14564 $handle2 = fopen("php://output", "wb");
14565 stream_copy_to_stream($handle1, $handle2);
14566 fclose($handle1);
14567 fclose($handle2);
14568 }
14569}
14570
14580function showValueWithClipboardCPButton($valuetocopy, $showonlyonhover = 1, $texttoshow = '')
14581{
14582 global $langs;
14583
14584 $tag = 'span'; // Using div (like any style of type 'block') does not work when using the js copy code.
14585
14586 $result = '<span class="clipboardCP'.($showonlyonhover ? ' clipboardCPShowOnHover' : '').'">';
14587 if ($texttoshow === 'none') {
14588 $result .= '<'.$tag.' class="clipboardCPValue hidewithsize">'.dol_escape_htmltag($valuetocopy, 1, 1).'</'.$tag.'>';
14589 $result .= '<span class="clipboardCPValueToPrint"></span>';
14590 } elseif ($texttoshow) {
14591 $result .= '<'.$tag.' class="clipboardCPValue hidewithsize">'.dol_escape_htmltag($valuetocopy, 1, 1).'</'.$tag.'>';
14592 $result .= '<span class="clipboardCPValueToPrint">'.dol_escape_htmltag($texttoshow, 1, 1).'</span>';
14593 } else {
14594 $result .= '<'.$tag.' class="clipboardCPValue">'.dol_escape_htmltag($valuetocopy, 1, 1).'</'.$tag.'>';
14595 }
14596 $result .= '<span class="clipboardCPButton far fa-clipboard opacitymedium paddingleft pictomodule" title="'.dolPrintHTML($langs->trans("ClickToCopyToClipboard")).'"></span>';
14597 $result .= img_picto('', 'tick', 'class="clipboardCPTick hidden paddingleft pictomodule"');
14598 $result .= '<span class="clipboardCPText"></span>';
14599 $result .= '</span>';
14600
14601 return $result;
14602}
14603
14604
14611function jsonOrUnserialize($stringtodecode)
14612{
14613 $result = json_decode($stringtodecode);
14614 if ($result === null) {
14615 $result = unserialize($stringtodecode);
14616 }
14617
14618 return $result;
14619}
14620
14621
14638function forgeSQLFromUniversalSearchCriteria($filter, &$errorstr = '', $noand = 0, $nopar = 0, $noerror = 0)
14639{
14640 global $db, $user;
14641
14642 if (is_null($filter) || !is_string($filter) || $filter === '') {
14643 return '';
14644 }
14645 if (!preg_match('/^\‍(.*\‍)$/', $filter)) { // If $filter does not start and end with ()
14646 $filter = '(' . $filter . ')';
14647 }
14648
14649 $regexstring = '\‍(([a-zA-Z0-9_\.]+:[<>!=insotlke]+:[^\‍(\‍)]+)\‍)'; // Must be (aaa:bbb:...) with aaa is a field name (with alias or not) and bbb is one of this operator '=', '<', '>', '<=', '>=', '!=', 'in', 'notin', 'like', 'notlike', 'is', 'isnot'
14650 $firstandlastparenthesis = 0;
14651
14652 if (!dolCheckFilters($filter, $errorstr, $firstandlastparenthesis)) {
14653 if ($noerror) {
14654 return '1 = 2';
14655 } else {
14656 return 'Filter syntax error - '.$errorstr; // Bad balance of parenthesis, we return an error message or force a SQL not found
14657 }
14658 }
14659
14660 // Test the filter syntax
14661 $t = preg_replace_callback('/'.$regexstring.'/i', 'dolForgeDummyCriteriaCallback', $filter);
14662 $t = str_ireplace(array('and', 'or', ' '), '', $t); // Remove the only strings allowed between each () criteria
14663 // If the string result contains something else than '()', the syntax was wrong
14664
14665 if (preg_match('/[^\‍(\‍)]/', $t)) {
14666 $tmperrorstr = 'Bad syntax of the search string';
14667 $errorstr = 'Bad syntax of the search string: '.$filter;
14668 if ($noerror) {
14669 return '1 = 2';
14670 } else {
14671 dol_syslog("forgeSQLFromUniversalSearchCriteria Filter error - ".$errorstr, LOG_WARNING);
14672 return 'Filter error - '.$tmperrorstr; // Bad syntax of the search string, we return an error message or force a SQL not found
14673 }
14674 }
14675
14676 $ret = ($noand ? "" : " AND ").($nopar ? "" : '(').preg_replace_callback('/'.$regexstring.'/i', 'dolForgeSQLCriteriaCallback', $filter).($nopar ? "" : ')');
14677
14678 if (is_object($db)) {
14679 $ret = str_replace('__NOW__', "'".$db->idate(dol_now())."'", $ret);
14680 }
14681 if (is_object($user)) {
14682 $ret = str_replace('__USER_ID__', (string) $user->id, $ret);
14683 }
14684
14685 return $ret;
14686}
14687
14695function dolForgeExplodeAnd($sqlfilters)
14696{
14697 $arrayofandtags = array();
14698 $nbofchars = dol_strlen($sqlfilters);
14699
14700 $error = '';
14701 $parenthesislevel = 0;
14702 $result = dolCheckFilters($sqlfilters, $error, $parenthesislevel);
14703 if (!$result) {
14704 return array();
14705 }
14706 if ($parenthesislevel >= 1) {
14707 $sqlfilters = preg_replace('/^\‍(/', '', preg_replace('/\‍)$/', '', $sqlfilters));
14708 }
14709
14710 $i = 0;
14711 $s = '';
14712 $countparenthesis = 0;
14713 while ($i < $nbofchars) {
14714 $char = dol_substr($sqlfilters, $i, 1);
14715
14716 if ($char == '(') {
14717 $countparenthesis++;
14718 } elseif ($char == ')') {
14719 $countparenthesis--;
14720 }
14721
14722 if ($countparenthesis == 0) {
14723 $char2 = dol_substr($sqlfilters, $i + 1, 1);
14724 $char3 = dol_substr($sqlfilters, $i + 2, 1);
14725 if ($char == 'A' && $char2 == 'N' && $char3 == 'D') {
14726 // We found a AND
14727 $s = trim($s);
14728 if (!preg_match('/^\‍(.*\‍)$/', $s)) {
14729 $s = '('.$s.')';
14730 }
14731 $arrayofandtags[] = $s;
14732 $s = '';
14733 $i += 2;
14734 } else {
14735 $s .= $char;
14736 }
14737 } else {
14738 $s .= $char;
14739 }
14740 $i++;
14741 }
14742 if ($s) {
14743 $s = trim($s);
14744 if (!preg_match('/^\‍(.*\‍)$/', $s)) {
14745 $s = '('.$s.')';
14746 }
14747 $arrayofandtags[] = $s;
14748 }
14749
14750 return $arrayofandtags;
14751}
14752
14762function dolCheckFilters($sqlfilters, &$error = '', &$parenthesislevel = 0)
14763{
14764 //$regexstring='\‍(([^:\'\‍(\‍)]+:[^:\'\‍(\‍)]+:[^:\‍(\‍)]+)\‍)';
14765 //$tmp=preg_replace_all('/'.$regexstring.'/', '', $sqlfilters);
14766 $tmp = $sqlfilters;
14767
14768 $nb = dol_strlen($tmp);
14769 $counter = 0;
14770 $parenthesislevel = 0;
14771
14772 $error = '';
14773
14774 $i = 0;
14775 while ($i < $nb) {
14776 $char = dol_substr($tmp, $i, 1);
14777
14778 if ($char == '(') {
14779 if ($i == $parenthesislevel && $parenthesislevel == $counter) {
14780 // We open a parenthesis and it is the first char
14781 $parenthesislevel++;
14782 }
14783 $counter++;
14784 } elseif ($char == ')') {
14785 $nbcharremaining = ($nb - $i - 1);
14786 if ($nbcharremaining >= $counter) {
14787 $parenthesislevel = min($parenthesislevel, $counter - 1);
14788 }
14789 if ($parenthesislevel > $counter && $nbcharremaining >= $counter) {
14790 $parenthesislevel = $counter;
14791 }
14792 $counter--;
14793 }
14794
14795 if ($counter < 0) {
14796 $error = "Wrong balance of parenthesis in sqlfilters=".$sqlfilters;
14797 $parenthesislevel = 0;
14798 dol_syslog($error, LOG_WARNING);
14799 return false;
14800 }
14801
14802 $i++;
14803 }
14804
14805 if ($counter > 0) {
14806 $error = "Wrong balance of parenthesis in sqlfilters=".$sqlfilters;
14807 $parenthesislevel = 0;
14808 dol_syslog($error, LOG_WARNING);
14809 return false;
14810 }
14811
14812 return true;
14813}
14814
14822function dolForgeDummyCriteriaCallback($matches)
14823{
14824 //dol_syslog("Convert matches ".$matches[1]);
14825 if (empty($matches[1])) {
14826 return '';
14827 }
14828 $tmp = explode(':', $matches[1]);
14829 if (count($tmp) < 3) {
14830 return '';
14831 }
14832
14833 return '()'; // An empty criteria
14834}
14835
14844function dolForgeSQLCriteriaCallback($matches)
14845{
14846 global $db;
14847
14848 //dol_syslog("Convert matches ".$matches[1]);
14849 if (empty($matches[1])) {
14850 return '';
14851 }
14852 $tmp = explode(':', $matches[1], 3);
14853 if (count($tmp) < 3) {
14854 return '';
14855 }
14856
14857 $operand = preg_replace('/[^a-z0-9\._]/i', '', trim($tmp[0]));
14858
14859 $operator = strtoupper(preg_replace('/[^a-z<>!=]/i', '', trim($tmp[1])));
14860
14861 $realOperator = [
14862 'NOTLIKE' => 'NOT LIKE',
14863 'ISNOT' => 'IS NOT',
14864 'NOTIN' => 'NOT IN',
14865 '!=' => '<>',
14866 ];
14867
14868 if (array_key_exists($operator, $realOperator)) {
14869 $operator = $realOperator[$operator];
14870 }
14871
14872 $tmpescaped = $tmp[2];
14873
14874 //print "Case: ".$operator." ".$operand." ".$tmpescaped."\n";
14875
14876 $regbis = array();
14877
14878 if ($operator == 'IN' || $operator == 'NOT IN') { // IN is allowed for list of ID/code/field only (or subrequest if MAIN_DISALLOW_UNSECURED_SELECT_INTO_EXTRAFIELDS_FILTERnot enabled)
14879 //if (!preg_match('/^\‍(.*\‍)$/', $tmpescaped)) {
14880 $tmpescaped2 = '(';
14881 // Explode and sanitize each element in list
14882 $tmpelemarray = explode(',', $tmpescaped);
14883 foreach ($tmpelemarray as $tmpkey => $tmpelem) {
14884 $reg = array();
14885 $tmpelem = trim($tmpelem);
14886 if (preg_match('/^\'(.*)\'$/', $tmpelem, $reg)) {
14887 $tmpelemarray[$tmpkey] = "'".$db->escape($db->sanitize($reg[1], 2, 1, 1, 1))."'";
14888 } elseif (preg_match('/^[0-9]+$/', (string) $tmpelem)) { // if only 0-9 chars, no .
14889 $tmpelemarray[$tmpkey] = (int) $tmpelem;
14890 } elseif (is_numeric((string) $tmpelem)) { // it can be a float with a .
14891 $tmpelemarray[$tmpkey] = (float) $tmpelem;
14892 } elseif (!getDolGlobalString("MAIN_DISALLOW_UNSECURED_SELECT_INTO_EXTRAFIELDS_FILTER")) {
14893 $tmpelemarray[$tmpkey] = preg_replace('/[^a-z0-9_<>=!\s]/i', '', $tmpelem); // it can be a full subrequest
14894 } else {
14895 $tmpelemarray[$tmpkey] = preg_replace('/[^a-z0-9_]/i', '', $tmpelem); // it can be a name of field or a substitution variable like '__NOW__'
14896 }
14897 }
14898 $tmpescaped2 .= implode(',', $tmpelemarray);
14899 $tmpescaped2 .= ')';
14900
14901 $tmpescaped = $tmpescaped2;
14902 } elseif ($operator == 'LIKE' || $operator == 'NOT LIKE') {
14903 if (preg_match('/^\'([^\']*)\'$/', $tmpescaped, $regbis)) {
14904 $tmpescaped = $regbis[1];
14905 }
14906 //$tmpescaped = "'".$db->escape($db->escapeforlike($regbis[1]))."'";
14907 $tmpescaped = "'".$db->escape($tmpescaped)."'"; // We do not escape the _ and % so the LIKE will work as expected
14908 } elseif (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) {
14909 // TODO Retrieve type of field for $operand field name.
14910 // So we can complete format. For example we could complete a year with month and day.
14911 $tmpescaped = "'".$db->escape($regbis[1])."'";
14912 } else {
14913 if (strtoupper($tmpescaped) == 'NULL') {
14914 $tmpescaped = 'NULL';
14915 } elseif (preg_match('/^[0-9]+$/', (string) $tmpescaped)) { // if only 0-9 chars, no .
14916 $tmpescaped = (int) $tmpescaped;
14917 } elseif (is_numeric((string) $tmpescaped)) { // it can be a float with a .
14918 $tmpescaped = (float) $tmpescaped;
14919 } else {
14920 $tmpescaped = preg_replace('/[^a-z0-9_]/i', '', $tmpescaped); // it can be a name of field or a substitution variable like '__NOW__'
14921 }
14922 }
14923
14924 return '('.$db->escape($operand).' '.strtoupper($operator).' '.$tmpescaped.')';
14925}
14926
14927
14937function getTimelineIcon($actionstatic, &$histo, $key)
14938{
14939 global $langs;
14940
14941 $out = '<!-- timeline icon -->'."\n";
14942 $iconClass = 'fa fa-comments';
14943 $img_picto = '';
14944 $colorClass = '';
14945 $pictoTitle = '';
14946
14947 if ($histo[$key]['percent'] == -1) {
14948 $colorClass = 'timeline-icon-not-applicble';
14949 $pictoTitle = $langs->trans('StatusNotApplicable');
14950 } elseif ($histo[$key]['percent'] == 0) {
14951 $colorClass = 'timeline-icon-todo';
14952 $pictoTitle = $langs->trans('StatusActionToDo').' (0%)';
14953 } elseif ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100) {
14954 $colorClass = 'timeline-icon-in-progress';
14955 $pictoTitle = $langs->trans('StatusActionInProcess').' ('.$histo[$key]['percent'].'%)';
14956 } elseif ($histo[$key]['percent'] >= 100) {
14957 $colorClass = 'timeline-icon-done';
14958 $pictoTitle = $langs->trans('StatusActionDone').' (100%)';
14959 }
14960
14961 if ($actionstatic->code == 'AC_TICKET_CREATE') {
14962 $iconClass = 'fa fa-ticket';
14963 } elseif ($actionstatic->code == 'AC_TICKET_MODIFY') {
14964 $iconClass = 'fa fa-pencilxxx';
14965 } elseif (preg_match('/^TICKET_MSG/', $actionstatic->code)) {
14966 $iconClass = 'fa fa-comments';
14967 } elseif (preg_match('/^TICKET_MSG_PRIVATE/', $actionstatic->code)) {
14968 $iconClass = 'fa fa-mask';
14969 } elseif (getDolGlobalString('AGENDA_USE_EVENT_TYPE')) {
14970 if ($actionstatic->type_picto) {
14971 $img_picto = img_picto('', $actionstatic->type_picto);
14972 } else {
14973 if ($actionstatic->type_code == 'AC_RDV') {
14974 $iconClass = 'fa fa-handshake';
14975 } elseif ($actionstatic->type_code == 'AC_TEL') {
14976 $iconClass = 'fa fa-phone';
14977 } elseif ($actionstatic->type_code == 'AC_FAX') {
14978 $iconClass = 'fa fa-fax';
14979 } elseif ($actionstatic->type_code == 'AC_EMAIL') {
14980 $iconClass = 'fa fa-envelope';
14981 } elseif ($actionstatic->type_code == 'AC_INT') {
14982 $iconClass = 'fa fa-shipping-fast';
14983 } elseif ($actionstatic->type_code == 'AC_OTH_AUTO') {
14984 $iconClass = 'fa fa-robot';
14985 } elseif (!preg_match('/_AUTO/', $actionstatic->type_code)) {
14986 $iconClass = 'fa fa-robot';
14987 }
14988 }
14989 }
14990
14991 $out .= '<i class="'.$iconClass.' '.$colorClass.'" title="'.$pictoTitle.'">'.$img_picto.'</i>'."\n";
14992 return $out;
14993}
14994
15002{
15003 global $conf, $db;
15004
15005 $documents = array();
15006
15007 $sql = 'SELECT ecm.rowid as id, ecm.src_object_type, ecm.src_object_id, ecm.filepath, ecm.filename, ecm.agenda_id';
15008 $sql .= ' FROM '.MAIN_DB_PREFIX.'ecm_files ecm';
15009 $sql .= " WHERE ecm.filepath = 'agenda/".((int) $object->id)."'";
15010 //$sql.= " ecm.src_object_type = '".$db->escape($object->element)."' AND ecm.src_object_id = ".((int) $object->id); // Old version didn't add object_type during upload
15011 $sql.= ' OR ecm.agenda_id = '.(int) $object->id;
15012 $sql .= ' ORDER BY ecm.position ASC';
15013
15014 $resql = $db->query($sql);
15015 if ($resql) {
15016 if ($db->num_rows($resql)) {
15017 while ($obj = $db->fetch_object($resql)) {
15018 $documents[$obj->id] = $obj;
15019 }
15020 }
15021 }
15022
15023 return $documents;
15024}
15025
15026
15044function show_actions_messaging($conf, $langs, $db, $filterobj, $objcon = null, $noprint = 0, $actioncode = '', $donetodo = 'done', $filters = array(), $sortfield = 'a.datep,a.id', $sortorder = 'DESC')
15045{
15046 global $user, $conf;
15047 global $form;
15048
15049 global $param, $massactionbutton;
15050
15051 require_once DOL_DOCUMENT_ROOT . '/comm/action/class/actioncomm.class.php';
15052
15053 // Check parameters
15054 if (!is_object($filterobj) && !is_object($objcon)) {
15055 dol_print_error(null, 'BadParameter');
15056 }
15057
15058 $histo = array();
15059 '@phan-var-force array<int,array{type:string,tododone:string,id:string,datestart:int|string,dateend:int|string,note:string,message:string,percent:string,userid:string,login:string,userfirstname:string,userlastname:string,userphoto:string,msg_from?:string,contact_id?:string,socpeopleassigned?:int[],lastname?:string,firstname?:string,fk_element?:int,elementtype?:string,acode:string,alabel?:string,libelle?:string,apicto?:string}> $histo';
15060
15061 $numaction = 0;
15062 $now = dol_now();
15063
15064 $sortfield_list = explode(',', $sortfield);
15065 $sortfield_label_list = array('a.id' => 'id', 'a.datep' => 'dp', 'a.percent' => 'percent');
15066 $sortfield_new_list = array();
15067 foreach ($sortfield_list as $sortfield_value) {
15068 $sortfield_new_list[] = $sortfield_label_list[trim($sortfield_value)];
15069 }
15070 $sortfield_new = implode(',', $sortfield_new_list);
15071
15072 $sql = null;
15073 $sql2 = null;
15074
15075 if (isModEnabled('agenda')) {
15076 // Search histo on actioncomm
15077 if (is_object($objcon) && $objcon->id > 0) {
15078 $sql = "SELECT DISTINCT a.id, a.label as label,";
15079 } else {
15080 $sql = "SELECT a.id, a.label as label,";
15081 }
15082 $sql .= " a.datep as dp,";
15083 $sql .= " a.note as message,";
15084 $sql .= " a.datep2 as dp2,";
15085 $sql .= " a.percent as percent, 'action' as type,";
15086 $sql .= " a.fk_element, a.elementtype,";
15087 $sql .= " a.fk_contact,";
15088 $sql .= " a.email_from as msg_from,";
15089 $sql .= " c.code as acode, c.libelle as alabel, c.picto as apicto,";
15090 $sql .= " u.rowid as user_id, u.login as user_login, u.photo as user_photo, u.firstname as user_firstname, u.lastname as user_lastname";
15091 if (is_object($filterobj) && get_class($filterobj) == 'Societe') {
15092 $sql .= ", sp.lastname, sp.firstname";
15093 } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
15094 $sql .= ", m.lastname, m.firstname";
15095 } elseif (is_object($filterobj) && in_array(get_class($filterobj), array('Commande', 'CommandeFournisseur', 'Product', 'Ticket', 'BOM', 'Contrat', 'Facture', 'FactureFournisseur'))) {
15096 $sql .= ", o.ref";
15097 }
15098 $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a";
15099 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_action";
15100 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action = c.id";
15101
15102 $force_filter_contact = $filterobj instanceof User;
15103
15104 if (is_object($objcon) && $objcon->id > 0) {
15105 $force_filter_contact = true;
15106 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."actioncomm_resources as r ON a.id = r.fk_actioncomm";
15107 $sql .= " AND r.element_type = '".$db->escape($objcon->table_element)."' AND r.fk_element = ".((int) $objcon->id);
15108 }
15109
15110 if ((is_object($filterobj) && get_class($filterobj) == 'Societe') || (is_object($filterobj) && get_class($filterobj) == 'Contact')) {
15111 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as sp ON a.fk_contact = sp.rowid";
15112 } elseif (is_object($filterobj) && get_class($filterobj) == 'Dolresource') {
15113 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."element_resources as er";
15114 $sql .= " ON er.resource_type = 'dolresource'";
15115 $sql .= " AND er.element_id = a.id";
15116 $sql .= " AND er.resource_id = ".((int) $filterobj->id);
15117 } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
15118 $sql .= ", ".MAIN_DB_PREFIX."adherent as m";
15119 } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
15120 $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseur as o";
15121 } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
15122 $sql .= ", ".MAIN_DB_PREFIX."product as o";
15123 } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
15124 $sql .= ", ".MAIN_DB_PREFIX."ticket as o";
15125 } elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') {
15126 $sql .= ", ".MAIN_DB_PREFIX."bom_bom as o";
15127 } elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') {
15128 $sql .= ", ".MAIN_DB_PREFIX."contrat as o";
15129 } elseif (is_object($filterobj) && get_class($filterobj) == 'Facture') {
15130 $sql .= ", ".MAIN_DB_PREFIX."facture as o";
15131 } elseif (is_object($filterobj) && get_class($filterobj) == 'FactureFournisseur') {
15132 $sql .= ", ".MAIN_DB_PREFIX."facture_fourn as o";
15133 }
15134
15135 $sql .= " WHERE a.entity IN (".getEntity('agenda').")";
15136 if (!$force_filter_contact) {
15137 if (is_object($filterobj) && in_array(get_class($filterobj), array('Societe', 'Client', 'Fournisseur')) && $filterobj->id) {
15138 $sql .= " AND a.fk_soc = ".((int) $filterobj->id);
15139 } elseif (is_object($filterobj) && get_class($filterobj) == 'Project' && $filterobj->id) {
15140 $sql .= " AND a.fk_project = ".((int) $filterobj->id);
15141 } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
15142 $sql .= " AND a.fk_element = m.rowid AND a.elementtype = 'member'";
15143 if ($filterobj->id) {
15144 $sql .= " AND a.fk_element = ".((int) $filterobj->id);
15145 }
15146 } elseif (is_object($filterobj) && get_class($filterobj) == 'Commande') {
15147 $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'order'";
15148 if ($filterobj->id) {
15149 $sql .= " AND a.fk_element = ".((int) $filterobj->id);
15150 }
15151 } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
15152 $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'order_supplier'";
15153 if ($filterobj->id) {
15154 $sql .= " AND a.fk_element = ".((int) $filterobj->id);
15155 }
15156 } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
15157 $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'product'";
15158 if ($filterobj->id) {
15159 $sql .= " AND a.fk_element = ".((int) $filterobj->id);
15160 }
15161 } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
15162 $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'ticket'";
15163 if ($filterobj->id) {
15164 $sql .= " AND a.fk_element = ".((int) $filterobj->id);
15165 }
15166 } elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') {
15167 $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'bom'";
15168 if ($filterobj->id) {
15169 $sql .= " AND a.fk_element = ".((int) $filterobj->id);
15170 }
15171 } elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') {
15172 $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'contract'";
15173 if ($filterobj->id) {
15174 $sql .= " AND a.fk_element = ".((int) $filterobj->id);
15175 }
15176 } elseif (is_object($filterobj) && get_class($filterobj) == 'Contact' && $filterobj->id) {
15177 $sql .= " AND a.fk_contact = sp.rowid";
15178 if ($filterobj->id) {
15179 $sql .= " AND a.fk_contact = ".((int) $filterobj->id);
15180 }
15181 } elseif (is_object($filterobj) && get_class($filterobj) == 'Facture') {
15182 $sql .= " AND a.fk_element = o.rowid";
15183 if ($filterobj->id) {
15184 $sql .= " AND a.fk_element = ".((int) $filterobj->id)." AND a.elementtype = 'invoice'";
15185 }
15186 } elseif (is_object($filterobj) && get_class($filterobj) == 'FactureFournisseur') {
15187 $sql .= " AND a.fk_element = o.rowid";
15188 if ($filterobj->id) {
15189 $sql .= " AND a.fk_element = ".((int) $filterobj->id)." AND a.elementtype = 'invoice_supplier'";
15190 }
15191 }
15192 } else {
15193 $sql .= " AND u.rowid = ". ((int) $filterobj->id);
15194 }
15195
15196 // Condition on actioncode
15197 if (!empty($actioncode) && $actioncode != '-1') {
15198 if (!getDolGlobalString('AGENDA_USE_EVENT_TYPE')) {
15199 if ($actioncode == 'AC_NON_AUTO') {
15200 $sql .= " AND c.type != 'systemauto'";
15201 } elseif ($actioncode == 'AC_ALL_AUTO') {
15202 $sql .= " AND c.type = 'systemauto'";
15203 } else {
15204 if ($actioncode == 'AC_OTH') {
15205 $sql .= " AND c.type != 'systemauto'";
15206 } elseif ($actioncode == 'AC_OTH_AUTO') {
15207 $sql .= " AND c.type = 'systemauto'";
15208 }
15209 }
15210 } else {
15211 if ($actioncode == 'AC_NON_AUTO') {
15212 $sql .= " AND c.type != 'systemauto'";
15213 } elseif ($actioncode == 'AC_ALL_AUTO') {
15214 $sql .= " AND c.type = 'systemauto'";
15215 } else {
15216 $sql .= " AND c.code = '".$db->escape($actioncode)."'";
15217 }
15218 }
15219 }
15220 if ($donetodo == 'todo') {
15221 $sql .= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))";
15222 } elseif ($donetodo == 'done') {
15223 $sql .= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))";
15224 }
15225 if (is_array($filters) && $filters['search_agenda_label']) {
15226 $sql .= natural_search('a.label', $filters['search_agenda_label']);
15227 }
15228 }
15229
15230 // Add also event from emailings. TODO This should be replaced by an automatic event ? May be it's too much for very large emailing.
15231 if (isModEnabled('mailing') && !empty($objcon->email)
15232 && (empty($actioncode) || $actioncode == 'AC_OTH_AUTO' || $actioncode == 'AC_EMAILING')) {
15233 $langs->load("mails");
15234
15235 $sql2 = "SELECT m.rowid as id, m.titre as label, mc.date_envoi as dp, mc.date_envoi as dp2, '100' as percent, 'mailing' as type";
15236 $sql2 .= ", null as fk_element, '' as elementtype, null as contact_id";
15237 $sql2 .= ", 'AC_EMAILING' as acode, '' as alabel, '' as apicto";
15238 $sql2 .= ", u.rowid as user_id, u.login as user_login, u.photo as user_photo, u.firstname as user_firstname, u.lastname as user_lastname"; // User that valid action
15239 if (is_object($filterobj) && get_class($filterobj) == 'Societe') {
15240 $sql2 .= ", '' as lastname, '' as firstname";
15241 } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
15242 $sql2 .= ", '' as lastname, '' as firstname";
15243 } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
15244 $sql2 .= ", '' as ref";
15245 } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
15246 $sql2 .= ", '' as ref";
15247 } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
15248 $sql2 .= ", '' as ref";
15249 }
15250 $sql2 .= " FROM ".MAIN_DB_PREFIX."mailing as m, ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."user as u";
15251 $sql2 .= " WHERE mc.email = '".$db->escape($objcon->email)."'"; // Search is done on email.
15252 $sql2 .= " AND mc.statut = 1";
15253 $sql2 .= " AND u.rowid = m.fk_user_valid";
15254 $sql2 .= " AND mc.fk_mailing=m.rowid";
15255 }
15256
15257 if ($sql || $sql2) { // May not be defined if module Agenda is not enabled and mailing module disabled too
15258 if (!empty($sql) && !empty($sql2)) {
15259 $sql = $sql." UNION ".$sql2;
15260 } elseif (empty($sql) && !empty($sql2)) {
15261 $sql = $sql2;
15262 }
15263
15264 //TODO Add navigation with this limits...
15265 $offset = 0;
15266 $limit = 1000;
15267
15268 // Complete request and execute it with limit
15269 $sql .= $db->order($sortfield_new, $sortorder);
15270 if ($limit) {
15271 $sql .= $db->plimit($limit + 1, $offset);
15272 }
15273
15274 dol_syslog("function.lib::show_actions_messaging", LOG_DEBUG);
15275 $resql = $db->query($sql);
15276 if ($resql) {
15277 $i = 0;
15278 $num = $db->num_rows($resql);
15279
15280 $imaxinloop = ($limit ? min($num, $limit) : $num);
15281 while ($i < $imaxinloop) {
15282 $obj = $db->fetch_object($resql);
15283
15284 if ($obj->type == 'action') {
15285 $contactaction = new ActionComm($db);
15286 $contactaction->id = $obj->id;
15287 $result = $contactaction->fetchResources();
15288 if ($result < 0) {
15289 dol_print_error($db);
15290 setEventMessage("actions.lib::show_actions_messaging Error fetch resource", 'errors');
15291 }
15292
15293 //if ($donetodo == 'todo') $sql.= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))";
15294 //elseif ($donetodo == 'done') $sql.= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))";
15295 $tododone = '';
15296 if (($obj->percent >= 0 and $obj->percent < 100) || ($obj->percent == -1 && $obj->dp > $now)) {
15297 $tododone = 'todo';
15298 }
15299
15300 $histo[$numaction] = array(
15301 'type' => $obj->type,
15302 'tododone' => $tododone,
15303 'id' => $obj->id,
15304 'datestart' => $db->jdate($obj->dp),
15305 'dateend' => $db->jdate($obj->dp2),
15306 'note' => $obj->label,
15307 'message' => dol_htmlentitiesbr($obj->message),
15308 'percent' => $obj->percent,
15309
15310 'userid' => $obj->user_id,
15311 'login' => $obj->user_login,
15312 'userfirstname' => $obj->user_firstname,
15313 'userlastname' => $obj->user_lastname,
15314 'userphoto' => $obj->user_photo,
15315 'msg_from' => $obj->msg_from,
15316
15317 'contact_id' => $obj->fk_contact,
15318 'socpeopleassigned' => $contactaction->socpeopleassigned,
15319 'lastname' => (empty($obj->lastname) ? '' : $obj->lastname),
15320 'firstname' => (empty($obj->firstname) ? '' : $obj->firstname),
15321 'fk_element' => $obj->fk_element,
15322 'elementtype' => $obj->elementtype,
15323 // Type of event
15324 'acode' => $obj->acode,
15325 'alabel' => $obj->alabel,
15326 'libelle' => $obj->alabel, // deprecated
15327 'apicto' => $obj->apicto
15328 );
15329 } else {
15330 $histo[$numaction] = array(
15331 'type' => $obj->type,
15332 'tododone' => 'done',
15333 'id' => $obj->id,
15334 'datestart' => $db->jdate($obj->dp),
15335 'dateend' => $db->jdate($obj->dp2),
15336 'note' => $obj->label,
15337 'message' => dol_htmlentitiesbr($obj->message),
15338 'percent' => $obj->percent,
15339 'acode' => $obj->acode,
15340
15341 'userid' => $obj->user_id,
15342 'login' => $obj->user_login,
15343 'userfirstname' => $obj->user_firstname,
15344 'userlastname' => $obj->user_lastname,
15345 'userphoto' => $obj->user_photo
15346 );
15347 }
15348
15349 $numaction++;
15350 $i++;
15351 }
15352 } else {
15353 dol_print_error($db);
15354 }
15355 }
15356
15357 // Set $out to show events
15358 $out = '';
15359
15360 if (!isModEnabled('agenda')) {
15361 $langs->loadLangs(array("admin", "errors"));
15362 $out = info_admin($langs->trans("WarningModuleXDisabledSoYouMayMissEventHere", $langs->transnoentitiesnoconv("Module2400Name")), 0, 0, 'warning');
15363 }
15364
15365 if (isModEnabled('agenda') || (isModEnabled('mailing') && !empty($objcon->email))) {
15366 $delay_warning = getDolGlobalInt('MAIN_DELAY_ACTIONS_TODO') * 24 * 60 * 60;
15367
15368 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
15369 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
15370 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
15371 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
15372
15373 $formactions = new FormActions($db);
15374
15375 $actionstatic = new ActionComm($db);
15376 $userstatic = new User($db);
15377 $contactstatic = new Contact($db);
15378 $userGetNomUrlCache = array();
15379 $contactGetNomUrlCache = array();
15380
15381 $out .= '<div class="filters-container" >';
15382 $out .= '<form name="listactionsfilter" class="listactionsfilter" action="'.$_SERVER["PHP_SELF"].'" method="POST">';
15383 $out .= '<input type="hidden" name="token" value="'.newToken().'">';
15384
15385 if ($objcon && get_class($objcon) == 'Contact' &&
15386 (is_null($filterobj) || get_class($filterobj) == 'Societe')) {
15387 $out .= '<input type="hidden" name="id" value="'.$objcon->id.'" />';
15388 } else {
15389 $out .= '<input type="hidden" name="id" value="'.$filterobj->id.'" />';
15390 }
15391 if (($filterobj && get_class($filterobj) == 'Societe')) {
15392 $out .= '<input type="hidden" name="socid" value="'.$filterobj->id.'" />';
15393 } else {
15394 $out .= '<input type="hidden" name="userid" value="'.$filterobj->id.'" />';
15395 }
15396
15397 $out .= "\n";
15398
15399 $out .= '<div class="div-table-responsive-no-min">';
15400 $out .= '<table class="noborder borderbottom centpercent">';
15401
15402 $out .= '<tr class="liste_titre">';
15403
15404 // Action column
15405 if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
15406 $out .= '<th class="liste_titre width50 middle">';
15407 $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1);
15408 $out .= $searchpicto;
15409 $out .= '</th>';
15410 }
15411
15412 // Date
15413 $out .= getTitleFieldOfList('Date', 0, $_SERVER["PHP_SELF"], 'a.datep', '', $param, '', $sortfield, $sortorder, 'nowraponall nopaddingleftimp ')."\n";
15414
15415 $out .= '<th class="liste_titre hideonsmartphone"><strong class="hideonsmartphone">'.$langs->trans("Search").' : </strong></th>';
15416 if ($donetodo) {
15417 $out .= '<th class="liste_titre"></th>';
15418 }
15419 // Type of event
15420 $out .= '<th class="liste_titre">';
15421 $out .= '<span class="fas fa-square inline-block fawidth30 hideonsmartphone" style="color: #ddd;" title="'.$langs->trans("ActionType").'"></span>';
15422 $out .= $formactions->select_type_actions($actioncode, "actioncode", '', getDolGlobalString('AGENDA_USE_EVENT_TYPE') ? -1 : 1, 0, 0, 1, 'selecttype minwidth100', $langs->trans("Type"));
15423 $out .= '</th>';
15424 // Label
15425 $out .= '<th class="liste_titre maxwidth100onsmartphone">';
15426 $out .= '<input type="text" class="maxwidth100onsmartphone" name="search_agenda_label" value="'.$filters['search_agenda_label'].'" placeholder="'.$langs->trans("Label").'">';
15427 $out .= '</th>';
15428
15429 // Action column
15430 if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
15431 $out .= '<th class="liste_titre width50 middle">';
15432 $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1);
15433 $out .= $searchpicto;
15434 $out .= '</th>';
15435 }
15436
15437 $out .= '</tr>';
15438
15439 $out .= '</table>';
15440
15441 $out .= '</form>';
15442 $out .= '</div>';
15443
15444 $out .= "\n";
15445
15446 $out .= '<ul class="timeline">';
15447
15448 if ($donetodo) {
15449 $tmp = '';
15450 if ($filterobj instanceof Societe) {
15451 $tmp .= '<a href="'.DOL_URL_ROOT.'/comm/action/list.php?mode=show_list&socid='.$filterobj->id.'&status=done">';
15452 }
15453 if ($filterobj instanceof User) {
15454 $tmp .= '<a href="'.DOL_URL_ROOT.'/comm/action/list.php?mode=show_list&socid='.$filterobj->id.'&status=done">';
15455 }
15456 $tmp .= ($donetodo != 'done' ? $langs->trans("ActionsToDoShort") : '');
15457 $tmp .= ($donetodo != 'done' && $donetodo != 'todo' ? ' / ' : '');
15458 $tmp .= ($donetodo != 'todo' ? $langs->trans("ActionsDoneShort") : '');
15459 //$out.=$langs->trans("ActionsToDoShort").' / '.$langs->trans("ActionsDoneShort");
15460 if ($filterobj instanceof Societe) {
15461 $tmp .= '</a>';
15462 }
15463 if ($filterobj instanceof User) {
15464 $tmp .= '</a>';
15465 }
15466 $out .= getTitleFieldOfList($tmp);
15467 }
15468
15469 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/cactioncomm.class.php';
15470 $caction = new CActionComm($db);
15471 $arraylist = $caction->liste_array(1, 'code', '', (!getDolGlobalString('AGENDA_USE_EVENT_TYPE') ? 1 : 0), '', 1);
15472
15473 $actualCycleDate = false;
15474
15475 // Loop on each event to show it
15476 foreach ($histo as $key => $value) {
15477 $actionstatic->fetch($histo[$key]['id']); // TODO Do we need this, we already have a lot of data of line into $histo
15478
15479 $actionstatic->type_picto = $histo[$key]['apicto'];
15480 $actionstatic->type_code = $histo[$key]['acode'];
15481
15482 $labeltype = $actionstatic->type_code;
15483 if (!getDolGlobalString('AGENDA_USE_EVENT_TYPE') && empty($arraylist[$labeltype])) {
15484 $labeltype = 'AC_OTH';
15485 }
15486 if (!empty($actionstatic->code) && preg_match('/^TICKET_MSG/', $actionstatic->code)) {
15487 $labeltype = $langs->trans("Message");
15488 } else {
15489 if (!empty($arraylist[$labeltype])) {
15490 $labeltype = $arraylist[$labeltype];
15491 }
15492 if ($actionstatic->type_code == 'AC_OTH_AUTO' && ($actionstatic->type_code != $actionstatic->code) && $labeltype && !empty($arraylist[$actionstatic->code])) {
15493 $labeltype .= ' - '.$arraylist[$actionstatic->code]; // Use code in priority on type_code
15494 }
15495 }
15496
15497 $url = DOL_URL_ROOT.'/comm/action/card.php?id='.$histo[$key]['id'];
15498
15499 $tmpa = dol_getdate($histo[$key]['datestart'], false);
15500
15501 if (isset($tmpa['year']) && isset($tmpa['yday']) && $actualCycleDate !== $tmpa['year'].'-'.$tmpa['yday']) {
15502 $actualCycleDate = $tmpa['year'].'-'.$tmpa['yday'];
15503 $out .= '<!-- timeline time label -->';
15504 $out .= '<li class="time-label">';
15505 $out .= '<span class="timeline-badge-date">';
15506 $out .= dol_print_date($histo[$key]['datestart'], 'daytext', 'tzuserrel', $langs);
15507 $out .= '</span>';
15508 $out .= '</li>';
15509 $out .= '<!-- /.timeline-label -->';
15510 }
15511
15512
15513 $out .= '<!-- timeline item -->'."\n";
15514 $out .= '<li class="timeline-code-'.(!empty($actionstatic->code) ? strtolower($actionstatic->code) : "none").'">';
15515
15516 //$timelineicon = getTimelineIcon($actionstatic, $histo, $key);
15517 $typeicon = $actionstatic->getTypePicto('pictofixedwidth timeline-icon-not-applicble', $labeltype);
15518 //$out .= $timelineicon;
15519 //var_dump($timelineicon);
15520 $out .= $typeicon;
15521
15522 $out .= '<div class="timeline-item">'."\n";
15523
15524 $out .= '<span class="time timeline-header-action2">';
15525
15526 if (isset($histo[$key]['type']) && $histo[$key]['type'] == 'mailing') {
15527 $out .= '<a class="paddingleft paddingright timeline-btn2 editfielda" href="'.DOL_URL_ROOT.'/comm/mailing/card.php?id='.$histo[$key]['id'].'">'.img_object($langs->trans("ShowEMailing"), "email").' ';
15528 $out .= $histo[$key]['id'];
15529 $out .= '</a> ';
15530 } else {
15531 $out .= $actionstatic->getNomUrl(1, -1, 'valignmiddle').' ';
15532 }
15533
15534 if ($user->hasRight('agenda', 'allactions', 'create') ||
15535 (($actionstatic->authorid == $user->id || $actionstatic->userownerid == $user->id) && $user->hasRight('agenda', 'myactions', 'create'))) {
15536 $out .= '<a class="paddingleft paddingright timeline-btn2 editfielda" href="'.DOL_MAIN_URL_ROOT.'/comm/action/card.php?action=edit&token='.newToken().'&id='.$actionstatic->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?'.$param).'">';
15537 //$out .= '<i class="fa fa-pencil" title="'.$langs->trans("Modify").'" ></i>';
15538 $out .= img_picto($langs->trans("Modify"), 'edit', 'class="edita"');
15539 $out .= '</a>';
15540 }
15541
15542 $out .= '</span>';
15543
15544 // Date
15545 $out .= '<span class="time"><i class="fa fa-clock-o valignmiddle"></i> <span class="valignmiddle">';
15546 $out .= dol_print_date($histo[$key]['datestart'], 'dayhour', 'tzuserrel');
15547 if ($histo[$key]['dateend'] && $histo[$key]['dateend'] != $histo[$key]['datestart']) {
15548 $tmpa = dol_getdate($histo[$key]['datestart'], true);
15549 $tmpb = dol_getdate($histo[$key]['dateend'], true);
15550 if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year']) {
15551 $out .= '-'.dol_print_date($histo[$key]['dateend'], 'hour', 'tzuserrel');
15552 } else {
15553 $out .= '-'.dol_print_date($histo[$key]['dateend'], 'dayhour', 'tzuserrel');
15554 }
15555 }
15556 $late = 0;
15557 if ($histo[$key]['percent'] == 0 && $histo[$key]['datestart'] && $histo[$key]['datestart'] < ($now - $delay_warning)) {
15558 $late = 1;
15559 }
15560 if ($histo[$key]['percent'] == 0 && !$histo[$key]['datestart'] && $histo[$key]['dateend'] && $histo[$key]['datestart'] < ($now - $delay_warning)) {
15561 $late = 1;
15562 }
15563 if ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100 && $histo[$key]['dateend'] && $histo[$key]['dateend'] < ($now - $delay_warning)) {
15564 $late = 1;
15565 }
15566 if ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100 && !$histo[$key]['dateend'] && $histo[$key]['datestart'] && $histo[$key]['datestart'] < ($now - $delay_warning)) {
15567 $late = 1;
15568 }
15569 if ($late) {
15570 $out .= img_warning($langs->trans("Late")).' ';
15571 }
15572 $out .= "</span></span>\n";
15573
15574 $out .= '<span class="time">';
15575 $out .= $actionstatic->getLibStatut(2);
15576 $out .= '</span>';
15577
15578 // Ref
15579 $out .= '<h3 class="timeline-header">';
15580
15581 // Author of event
15582 $out .= '<div class="messaging-author inline-block tdoverflowmax150 valignmiddle marginrightonly">';
15583 if ($histo[$key]['userid'] > 0) {
15584 if (!isset($userGetNomUrlCache[$histo[$key]['userid']])) { // is in cache ?
15585 $userstatic->fetch($histo[$key]['userid']);
15586 $userGetNomUrlCache[$histo[$key]['userid']] = $userstatic->getNomUrl(-1, '', 0, 0, 16, 0, 'firstelselast', '');
15587 }
15588 $out .= $userGetNomUrlCache[$histo[$key]['userid']];
15589 } elseif (!empty($histo[$key]['msg_from']) && $actionstatic->code == 'TICKET_MSG') {
15590 if (!isset($contactGetNomUrlCache[$histo[$key]['msg_from']])) {
15591 if ($contactstatic->fetch(0, null, '', $histo[$key]['msg_from']) > 0) {
15592 $contactGetNomUrlCache[$histo[$key]['msg_from']] = $contactstatic->getNomUrl(-1, '', 16);
15593 } else {
15594 $contactGetNomUrlCache[$histo[$key]['msg_from']] = $histo[$key]['msg_from'];
15595 }
15596 }
15597 $out .= $contactGetNomUrlCache[$histo[$key]['msg_from']];
15598 }
15599 $out .= '</div>';
15600
15601 // Title
15602 $out .= ' <div class="messaging-title inline-block">';
15603 //$out .= $actionstatic->getTypePicto(); // The type of event is already into the timeline on left.
15604 if (empty($conf->dol_optimize_smallscreen) && $actionstatic->type_code != 'AC_OTH_AUTO') {
15605 $out .= $labeltype.' - ';
15606 }
15607
15608 $libelle = '';
15609
15610 if (!empty($actionstatic->code) && preg_match('/^TICKET_MSG_PRIVATE/', $actionstatic->code)) {
15611 $out .= $langs->trans('TicketNewMessage').' <em>('.$langs->trans('Private').')</em>';
15612 } elseif (!empty($actionstatic->code) && preg_match('/^TICKET_MSG/', $actionstatic->code)) {
15613 $out .= $langs->trans('TicketNewMessage');
15614 } elseif (isset($histo[$key]['type'])) {
15615 if ($histo[$key]['type'] == 'action') {
15616 $transcode = $langs->transnoentitiesnoconv("Action".$histo[$key]['acode']);
15617 $libelle = ($transcode != "Action".$histo[$key]['acode'] ? $transcode : $histo[$key]['alabel']);
15618 $libelle = $histo[$key]['note'];
15619 $actionstatic->id = $histo[$key]['id'];
15620 if ($libelle != $labeltype) {
15621 $out .= dol_escape_htmltag(dol_trunc($libelle, 120));
15622 }
15623 } elseif ($histo[$key]['type'] == 'mailing') {
15624 $out .= '<a href="'.DOL_URL_ROOT.'/comm/mailing/card.php?id='.$histo[$key]['id'].'">'.img_object($langs->trans("ShowEMailing"), "email").' ';
15625 $transcode = $langs->transnoentitiesnoconv("Action".$histo[$key]['acode']);
15626 $libelle = ($transcode != "Action".$histo[$key]['acode'] ? $transcode : 'Send mass mailing');
15627 $out .= dol_escape_htmltag(dol_trunc($libelle, 120));
15628 } else {
15629 $libelle .= $histo[$key]['note'];
15630 $out .= dol_escape_htmltag(dol_trunc($libelle, 120));
15631 }
15632 }
15633 $out = preg_replace('/ - $/', '', $out); // Remove ending ' - '
15634
15635 if (isset($histo[$key]['elementtype']) && !empty($histo[$key]['fk_element'])) {
15636 if (isset($conf->cache['elementlinkcache'][$histo[$key]['elementtype']]) && isset($conf->cache['elementlinkcache'][$histo[$key]['elementtype']][$histo[$key]['fk_element']])) {
15637 $link = $conf->cache['elementlinkcache'][$histo[$key]['elementtype']][$histo[$key]['fk_element']];
15638 } else {
15639 if (!isset($conf->cache['elementlinkcache'][$histo[$key]['elementtype']])) {
15640 $conf->cache['elementlinkcache'][$histo[$key]['elementtype']] = array();
15641 }
15642 $link = dolGetElementUrl($histo[$key]['fk_element'], $histo[$key]['elementtype'], 1);
15643 $conf->cache['elementlinkcache'][$histo[$key]['elementtype']][$histo[$key]['fk_element']] = $link;
15644 }
15645 if ($link) {
15646 $out .= ' - '.$link;
15647 }
15648 }
15649
15650 $out .= '</div>';
15651
15652 $out .= '</h3>';
15653
15654 // Message
15655 if (!empty($histo[$key]['message'] && $histo[$key]['message'] != $libelle)
15656 && $actionstatic->code != 'AC_TICKET_CREATE'
15657 && $actionstatic->code != 'AC_TICKET_MODIFY'
15658 ) {
15659 $out .= '<div class="timeline-body wordbreak small">';
15660 $truncateLines = getDolGlobalInt('MAIN_TRUNCATE_TIMELINE_MESSAGE', 3);
15661 $truncatedText = dolGetFirstLineOfText($histo[$key]['message'], $truncateLines);
15662 if ($truncateLines > 0 && strlen($histo[$key]['message']) > strlen($truncatedText)) {
15663 $out .= '<div class="readmore-block --closed" >';
15664 $out .= ' <div class="readmore-block__excerpt">';
15665 $out .= dolPrintHTML($truncatedText);
15666 $out .= ' <br><a class="read-more-link" data-read-more-action="open" href="'.DOL_MAIN_URL_ROOT.'/comm/action/card.php?id='.$actionstatic->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?'.$param).'" >'.$langs->trans("ReadMore").' <span class="fa fa-chevron-right" aria-hidden="true"></span></a>';
15667 $out .= ' </div>';
15668 $out .= ' <div class="readmore-block__full-text" >';
15669 $out .= dolPrintHTML($histo[$key]['message']);
15670 $out .= ' <a class="read-less-link" data-read-more-action="close" href="#" ><span class="fa fa-chevron-up" aria-hidden="true"></span> '.$langs->trans("ReadLess").'</a>';
15671 $out .= ' </div>';
15672 $out .= '</div>';
15673 } else {
15674 $out .= dolPrintHTML($histo[$key]['message']);
15675 }
15676
15677 $out .= '</div>';
15678 }
15679
15680 // Timeline footer
15681 $footer = '';
15682
15683 // Contact for this action
15684 if (isset($histo[$key]['socpeopleassigned']) && is_array($histo[$key]['socpeopleassigned']) && count($histo[$key]['socpeopleassigned']) > 0) {
15685 $contactList = '';
15686 foreach ($histo[$key]['socpeopleassigned'] as $cid => $Tab) {
15687 if (empty($conf->cache['contact'][$cid])) {
15688 $contact = new Contact($db);
15689 $contact->fetch($cid);
15690 $conf->cache['contact'][$cid] = $contact;
15691 } else {
15692 $contact = $conf->cache['contact'][$cid];
15693 }
15694
15695 if ($contact) {
15696 $contactList .= !empty($contactList) ? ', ' : '';
15697 $contactList .= $contact->getNomUrl(1);
15698 if (isset($histo[$key]['acode']) && $histo[$key]['acode'] == 'AC_TEL') {
15699 if (!empty($contact->phone_pro)) {
15700 $contactList .= '('.dol_print_phone($contact->phone_pro).')';
15701 }
15702 }
15703 }
15704 }
15705
15706 $footer .= $langs->trans('ActionOnContact').' : '.$contactList;
15707 } elseif (empty($objcon->id) && isset($histo[$key]['contact_id']) && $histo[$key]['contact_id'] > 0) {
15708 if (empty($conf->cache['contact'][$histo[$key]['contact_id']])) {
15709 $contact = new Contact($db);
15710 $result = $contact->fetch($histo[$key]['contact_id']);
15711 $conf->cache['contact'][$histo[$key]['contact_id']] = $contact;
15712 } else {
15713 $contact = $conf->cache['contact'][$histo[$key]['contact_id']];
15714 $result = ($contact instanceof Contact) ? $contact->id : 0;
15715 }
15716
15717 if ($result > 0) {
15718 $footer .= $contact->getNomUrl(1);
15719 if (isset($histo[$key]['acode']) && $histo[$key]['acode'] == 'AC_TEL') {
15720 if (!empty($contact->phone_pro)) {
15721 $footer .= '('.dol_print_phone($contact->phone_pro).')';
15722 }
15723 }
15724 }
15725 }
15726
15727 $documents = getActionCommEcmList($actionstatic);
15728 if (!empty($documents)) {
15729 $footer .= '<div class="timeline-documents-container">';
15730 foreach ($documents as $doc) {
15731 $footer .= '<span id="document_'.$doc->id.'" class="timeline-documents" ';
15732 $footer .= ' data-id="'.$doc->id.'" ';
15733 $footer .= ' data-path="'.$doc->filepath.'"';
15734 $footer .= ' data-filename="'.dol_escape_htmltag($doc->filename).'" ';
15735 $footer .= '>';
15736
15737 $filePath = DOL_DATA_ROOT.'/'.$doc->filepath.'/'.$doc->filename;
15738 $mime = dol_mimetype($filePath);
15739 if (empty($doc->agenda_id)) {
15740 $dir_ref = $actionstatic->id;
15741 $modulepart = 'actions';
15742 } else {
15743 $split_dir = explode('/', $doc->filepath);
15744 $modulepart = array_shift($split_dir);
15745 $dir_ref = implode('/', $split_dir);
15746 }
15747
15748 $file = $dir_ref.'/'.$doc->filename;
15749 $thumb = $dir_ref.'/thumbs/'.substr($doc->filename, 0, strrpos($doc->filename, '.')).'_mini'.substr($doc->filename, strrpos($doc->filename, '.'));
15750 $doclink = dol_buildpath('document.php', 1).'?modulepart='.$modulepart.'&attachment=0&file='.urlencode($file).'&entity='.$conf->entity;
15751 $viewlink = dol_buildpath('viewimage.php', 1).'?modulepart='.$modulepart.'&file='.urlencode($thumb).'&entity='.$conf->entity;
15752
15753
15754
15755 $mimeAttr = ' mime="'.$mime.'" ';
15756 $class = '';
15757 if (in_array($mime, array('image/png', 'image/jpeg', 'application/pdf'))) {
15758 $class .= ' documentpreview';
15759 }
15760
15761 $footer .= '<a href="'.$doclink.'" class="btn-link '.$class.'" target="_blank" rel="noopener noreferrer" '.$mimeAttr.' >';
15762 $footer .= img_mime($filePath).' '.$doc->filename;
15763 $footer .= '</a>';
15764
15765 $footer .= '</span>';
15766 }
15767 $footer .= '</div>';
15768 }
15769
15770 if (!empty($footer)) {
15771 $out .= '<div class="timeline-footer">'.$footer.'</div>';
15772 }
15773
15774 $out .= '</div>'."\n"; // end timeline-item
15775
15776 $out .= '</li>';
15777 $out .= '<!-- END timeline item -->';
15778 }
15779
15780 $out .= "</ul>\n";
15781
15782 // Code to manage the click on button data-read-more-action to show full description of an event
15783 $out .= '<script>
15784 jQuery(document).ready(function () {
15785 $(document).on("click", "[data-read-more-action]", function(e){
15786 console.log("We click on data-read-more-action");
15787 let readMoreBloc = $(this).closest(".readmore-block");
15788 if(readMoreBloc.length > 0){
15789 e.preventDefault();
15790 if($(this).attr("data-read-more-action") == "close"){
15791 readMoreBloc.addClass("--closed").removeClass("--open");
15792 $("html, body").animate({
15793 scrollTop: readMoreBloc.offset().top - 200
15794 }, 100);
15795 }else{
15796 readMoreBloc.addClass("--open").removeClass("--closed");
15797 }
15798 }
15799 });
15800 });
15801 </script>';
15802
15803
15804 if (empty($histo)) {
15805 $out .= '<span class="opacitymedium">'.$langs->trans("NoRecordFound").'</span>';
15806 }
15807 }
15808
15809 if ($noprint) {
15810 return $out;
15811 } else {
15812 print $out;
15813 return null;
15814 }
15815}
15816
15828function buildParamDate($prefix, $timestamp = null, $hourTime = '', $gm = 'auto')
15829{
15830 if ($timestamp === null) {
15831 $timestamp = GETPOSTDATE($prefix, $hourTime, $gm);
15832 }
15833 $TParam = array(
15834 $prefix . 'day' => intval(dol_print_date($timestamp, '%d')),
15835 $prefix . 'month' => intval(dol_print_date($timestamp, '%m')),
15836 $prefix . 'year' => intval(dol_print_date($timestamp, '%Y')),
15837 );
15838 if ($hourTime === 'getpost' || ($timestamp !== null && dol_print_date($timestamp, '%H:%M:%S') !== '00:00:00')) {
15839 $TParam = array_merge($TParam, array(
15840 $prefix . 'hour' => intval(dol_print_date($timestamp, '%H')),
15841 $prefix . 'min' => intval(dol_print_date($timestamp, '%M')),
15842 $prefix . 'sec' => intval(dol_print_date($timestamp, '%S'))
15843 ));
15844 }
15845
15846 return '&' . http_build_query($TParam);
15847}
15848
15867function recordNotFound($message = '', $printheader = 1, $printfooter = 1, $showonlymessage = 0, $params = null)
15868{
15869 global $conf, $db, $langs, $hookmanager;
15870 global $action, $object;
15871
15872 if (!is_object($langs)) {
15873 include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
15874 $langs = new Translate('', $conf);
15875 $langs->setDefaultLang();
15876 }
15877
15878 $langs->load("errors");
15879
15880 if ($printheader) {
15881 if (function_exists("llxHeader")) {
15882 llxHeader('');
15883 } elseif (function_exists("llxHeaderVierge")) {
15884 llxHeaderVierge('');
15885 }
15886 }
15887
15888 print '<div class="error">';
15889 if (empty($message)) {
15890 print $langs->trans("ErrorRecordNotFound");
15891 } else {
15892 print $langs->trans($message);
15893 }
15894 print '</div>';
15895 print '<br>';
15896
15897 if (empty($showonlymessage)) {
15898 if (empty($hookmanager)) {
15899 include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
15900 $hookmanager = new HookManager($db);
15901 // Initialize a technical object to manage hooks of page. Note that conf->hooks_modules contains an array of hook context
15902 $hookmanager->initHooks(array('main'));
15903 }
15904
15905 $parameters = array('message' => $message, 'params' => $params);
15906 $reshook = $hookmanager->executeHooks('getErrorRecordNotFound', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
15907 print $hookmanager->resPrint;
15908 }
15909
15910 if ($printfooter && function_exists("llxFooter")) {
15911 llxFooter();
15912 if (is_object($db)) {
15913 $db->close();
15914 }
15915 }
15916 exit(0);
15917}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:48
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:67
if(!defined( 'NOTOKENRENEWAL')) if(!defined('NOREQUIREMENU')) if(!defined( 'NOREQUIREHTML')) if(!defined('NOREQUIREAJAX')) if(!defined( 'NOLOGIN')) if(!defined('NOCSRFCHECK')) if(!defined( 'NOIPCHECK')) llxHeaderVierge($title, $head="", $disablejs=0, $disablehead=0, $arrayofjs=[], $arrayofcss=[])
Header function.
ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $forcefocus=0, $widthTypeOfAutocomplete='resolve', $idforemptyvalue='-1', $morecss='')
Convert a html select field into an ajax combobox.
Definition ajax.lib.php:475
ajax_object_onoff($object, $code, $field, $text_on, $text_off, $input=array(), $morecss='', $htmlname='', $forcenojs=0, $moreparam='')
On/off button to change a property status of an object This uses the ajax service objectonoff....
Definition ajax.lib.php:766
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Empty footer.
Definition wrapper.php:91
if(!defined('NOREQUIRESOC')) if(!defined( 'NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined( 'NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined( 'NOREQUIREAJAX')) llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='', $disablenofollow=0, $disablenoindex=0)
Empty header.
Definition wrapper.php:73
$c
Definition line.php:331
$object ref
Definition info.php:90
Class to manage agenda events (actions)
Class to manage different types of events.
Class to manage contact/addresses.
Class to manage GeoIP conversion Usage: $geoip=new GeoIP('country',$datfile); $geoip->getCountryCodeF...
Class to manage standard extra fields.
Class to manage invoices.
Class to manage building of HTML components.
Class to manage generation of HTML components Only common components must be here.
Class to manage hooks.
Class to manage predefined suppliers products.
Class to manage products or services.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage translations.
Class to manage Dolibarr users.
isInEEC($object)
Return if a country of an object is inside the EEC (European Economic Community)
dol_get_prev_month($month, $year)
Return previous month.
Definition date.lib.php:519
dol_get_next_day($day, $month, $year)
Return next day.
Definition date.lib.php:504
getServerTimeZoneInt($refgmtdate='now')
Return server timezone int.
Definition date.lib.php:86
dol_get_prev_day($day, $month, $year)
Return previous day.
Definition date.lib.php:488
dol_get_next_month($month, $year)
Return next month.
Definition date.lib.php:538
dol_convert_file($fileinput, $ext='png', $fileoutput='', $page='')
Convert an image file or a PDF into another image format.
dragAndDropFileUpload($htmlname)
Function to manage the drag and drop of a file.
dol_is_file($pathoffile)
Return if path is a file.
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:63
dol_is_dir($folder)
Test if filename is a directory.
dolGetElementUrl($objectid, $objecttype, $withpicto=0, $option='')
Return link url to an object.
isValidVATID($company)
Check if VAT numero is valid (check done on syntax only, no database or remote access)
dol_html_entity_decode($a, $b, $c='UTF-8', $keepsomeentities=0)
Replace html_entity_decode functions to manage errors.
dol_fiche_end($notab=0)
Show tab footer of a card.
verifCond($strToEvaluate, $onlysimplestring='1')
Verify if condition in string is ok or not.
recordNotFound($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Displays an error page when a record is not found.
getDolGlobalFloat($key, $default=0)
Return a Dolibarr global constant float value.
dol_print_size($size, $shortvalue=0, $shortunit=0)
Return string with formatted size.
isOnlyOneLocalTax($local)
Return true if LocalTax (1 or 2) is unique.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
get_default_localtax($thirdparty_seller, $thirdparty_buyer, $local, $idprod=0)
Function that return localtax of a product line (according to seller, buyer and product vat rate) If ...
img_weather($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $morecss='')
Show weather picto.
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='', $useCache=true)
Return an id or code from a code or id.
dolCheckFilters($sqlfilters, &$error='', &$parenthesislevel=0)
Return if a $sqlfilters parameter has a valid balance of parenthesis.
show_actions_messaging($conf, $langs, $db, $filterobj, $objcon=null, $noprint=0, $actioncode='', $donetodo='done', $filters=array(), $sortfield='a.datep, a.id', $sortorder='DESC')
Show html area with actions in messaging format.
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='')
Load a title with picto.
getLanguageCodeFromCountryCode($countrycode)
Return default language from country code.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
setEntity($currentobject)
Set entity id to use when to create an object.
dolForgeExplodeAnd($sqlfilters)
Explode an universal search string with AND parts.
vatrate($rate, $addpercent=false, $info_bits=0, $usestarfornpr=0, $html=0)
Return a string with VAT rate label formatted for view output Used into pdf and HTML pages.
GETPOSTDATE($prefix, $hourTime='', $gm='auto', $saverestore='')
Helper function that combines values of a dolibarr DatePicker (such as Form\selectDate) for year,...
dol_print_ip($ip, $mode=0, $showname=0)
Return an IP formatted to be shown on screen.
picto_from_langcode($codelang, $moreatt='', $notitlealt=0)
Return img flag of country for a language code or country code.
dol_ucfirst($string, $encoding="UTF-8")
Convert first character of the first word of a string to upper.
print_liste_field_titre($name, $file="", $field="", $begin="", $param="", $moreattrib="", $sortfield="", $sortorder="", $prefix="", $tooltip="", $forcenowrapcolumntitle=0)
Show title line of an array.
img_right($titlealt='default', $selected=0, $moreatt='')
Show right arrow logo.
print_barre_liste($title, $page, $file, $options='', $sortfield='', $sortorder='', $morehtmlcenter='', $num=-1, $totalnboflines='', $picto='generic', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limit=-1, $selectlimitsuffix=0, $hidenavigation=0, $pagenavastextinput=0, $morehtmlrightbeforearrow='')
Print a title with navigation controls for pagination.
img_help($usehelpcursor=1, $usealttitle=1)
Show help logo with cursor "?".
dol_strtolower($string, $encoding="UTF-8")
Convert a string to lower.
showValueWithClipboardCPButton($valuetocopy, $showonlyonhover=1, $texttoshow='')
Create a button to copy $valuetocopy in the clipboard (for copy and paste feature).
dol_htmlentitiesbr_decode($stringtodecode, $pagecodeto='UTF-8')
This function is called to decode a HTML string (it decodes entities and br tags)
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
img_warning($titlealt='default', $moreatt='', $morecss='pictowarning')
Show warning logo.
img_left($titlealt='default', $selected=0, $moreatt='')
Show left arrow logo.
img_delete($titlealt='default', $other='class="pictodelete"', $morecss='')
Show delete logo.
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dolGetFirstLineOfText($text, $nboflines=1, $charset='UTF-8')
Return first line of text.
dol_format_address($object, $withcountry=0, $sep="\n", $outputlangs=null, $mode=0, $extralangcode='')
Return a formatted address (part address/zip/town/state) according to country rules.
getDolUserInt($key, $default=0, $tmpuser=null)
Return Dolibarr user constant int value.
dol_print_phone($phone, $countrycode='', $cid=0, $socid=0, $addlink='', $separ="&nbsp;", $withpicto='', $titlealt='', $adddivfloat=0, $morecss='paddingright')
Format phone numbers according to country.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='', $dragdropfile=0, $morecssdiv='')
Show tabs of a record.
dolPrintHTML($s, $allowiframe=0)
Return a string (that can be on several lines) ready to be output on a HTML page.
isASecretKey($keyname)
Return if string has a name dedicated to store a secret.
dolPrintHTMLForTextArea($s, $allowiframe=0)
Return a string ready to be output on input textarea.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_eval_new($s)
Replace eval function to add more security.
getCallerInfoString()
Get caller info as a string that can be appended to a log message.
get_htmloutput_errors($mesgstring='', $mesgarray=array(), $keepembedded=0)
Get formatted error messages to output (Used to show messages on html output).
dol_user_country()
Return country code for current user.
dol_string_onlythesehtmlattributes($stringtoclean, $allowed_attributes=null)
Clean a string from some undesirable HTML tags.
getMultidirTemp($object, $module='', $forobject=0)
Return the full path of the directory where a module (or an object of a module) stores its temporary ...
isHTTPS()
Return if we are using a HTTPS connection Check HTTPS (no way to be modified by user but may be empty...
dol_get_fiche_end($notab=0)
Return tab footer of a card.
picto_required()
Return picto saying a field is required.
isDolTms($timestamp)
isDolTms check if a timestamp is valid.
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='', $keepspaces=0)
Clean a string from all punctuation characters to use it as a ref or login.
dol_eval($s, $returnvalue=1, $hideerrors=1, $onlysimplestring='1')
Replace eval function to add more security.
img_action($titlealt, $numaction, $picto='', $moreatt='')
Show logo action.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
dol_nl2br($stringtoencode, $nl2brmode=0, $forxml=false)
Replace CRLF in string with a HTML BR tag.
natural_search($fields, $value, $mode=0, $nofirstand=0)
Generate natural SQL search string for a criteria (this criteria can be tested on one or several fiel...
dol_print_url($url, $target='_blank', $max=32, $withpicto=0, $morecss='')
Show Url link.
setEventMessage($mesgs, $style='mesgs', $noduplicate=0, $attop=0)
Set event message in dol_events session object.
printCommonFooter($zone='private')
Print common footer : conf->global->MAIN_HTML_FOOTER js for switch of menu hider js for conf->global-...
checkVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
img_down($titlealt='default', $selected=0, $moreclass='')
Show down arrow logo.
getTaxesFromId($vatrate, $buyer=null, $seller=null, $firstparamisid=1)
Get tax (VAT) main information from Id.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
dolPrintText($s)
Return a string label (possible on several lines and that should not contains any HTML) ready to be o...
utf8_valid($str)
Check if a string is in UTF8.
getPictoForType($key, $morecss='')
Return the picto for a data type.
getDolUserString($key, $default='', $tmpuser=null)
Return Dolibarr user constant string value.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
img_allow($allow, $titlealt='default')
Show tick logo if allowed.
isValidMXRecord($domain)
Return if the domain name has a valid MX record.
dolButtonToOpenExportDialog($name, $label, $buttonstring, $exportSiteName, $overwriteGitUrl, $website)
Create a dialog with two buttons for export and overwrite of a website.
GETPOSTISARRAY($paramname, $method=0)
Return true if the parameter $paramname is submit from a POST OR GET as an array.
dol_print_socialnetworks($value, $contactid, $socid, $type, $dictsocialnetworks=array())
Show social network link.
getImgPictoNameList()
Get all usage icon key usable for img_picto(..., key)
dolChmod($filepath, $newmask='')
Change mod of a file.
dol_now($mode='auto')
Return date for now.
dol_fiche_head($links=array(), $active='0', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='')
Show tab header of a card.
img_mime($file, $titlealt='', $morecss='')
Show MIME img of a file.
get_localtax_by_third($local)
Get values of localtaxes (1 or 2) for company country for the common vat with the highest value.
dol_escape_php($stringtoescape, $stringforquotes=2)
Returns text escaped for inclusion into a php string, build with double quotes " or '.
dolSetCookie(string $cookiename, string $cookievalue, int $expire=-1)
Set a cookie.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into javascript code.
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
ajax_autoselect($htmlname, $addlink='', $textonlink='Link')
Make content of an input box selected when we click into input field.
img_view($titlealt='default', $float=0, $other='class="valignmiddle"')
Show logo view card.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_get_object_properties($obj, $properties=[])
Get properties for an object - including magic properties when requested.
dol_sort_array(&$array, $index, $order='asc', $natsort=0, $case_sensitive=0, $keepindex=0)
Advanced sort array by the value of a given key, which produces ascending (default) or descending out...
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
dol_set_focus($selector)
Set focus onto field with selector (similar behaviour of 'autofocus' HTML5 tag)
showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round=-1, $forceunitoutput='no', $use_short_label=0)
Output a dimension with best unit.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
dol_string_unaccent($str)
Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName.
dol_strftime($fmt, $ts=false, $is_gmt=false)
Format a string.
img_picto_common($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $notitle=0)
Show picto (generic function)
img_search($titlealt='default', $other='')
Show search logo.
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
dol_string_neverthesehtmltags($stringtoclean, $disallowed_tags=array('textarea'), $cleanalsosomestyles=0)
Clean a string from some undesirable HTML tags.
isValidPhone($phone)
Return true if phone number syntax is ok TODO Decide what to do with this.
dol_htmlcleanlastbr($stringtodecode)
This function remove all ending and br at end.
img_previous($titlealt='default', $moreatt='')
Show previous logo.
get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Function that returns whether VAT must be recoverable collected VAT (e.g.: VAT NPR in France)
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
dol_htmlentities($string, $flags=ENT_QUOTES|ENT_SUBSTITUTE, $encoding='UTF-8', $double_encode=false)
Replace htmlentities functions.
dolPrintHTMLForAttribute($s, $escapeonlyhtmltags=0, $allowothertags=array())
Return a string ready to be output into an HTML attribute (alt, title, data-html, ....
fieldLabel($langkey, $fieldkey, $fieldrequired=0)
Show a string with the label tag dedicated to the HTML edit field.
getBrowserInfo($user_agent)
Return information about user browser.
dolGetFirstLetters($s, $nbofchar=1)
Return first letters of a strings.
dol_eval_standard($s, $returnvalue=1, $hideerrors=1, $onlysimplestring='1')
Replace eval function to add more security.
dol_print_email($email, $cid=0, $socid=0, $addlink=0, $max=64, $showinvalid=1, $withpicto=0, $morecss='paddingrightonly')
Show EMail link formatted for HTML output.
dolPrintLabel($s, $escapeonlyhtmltags=0)
Return a string label (so on 1 line only and that should not contains any HTML) ready to be output on...
dol_strtoupper($string, $encoding="UTF-8")
Convert a string to upper.
getMultidirVersion($object, $module='', $forobject=0)
Return the full path of the directory where a module (or an object of a module) stores its versioned ...
dol_sanitizeUrl($stringtoclean, $type=1)
Clean a string to use it as an URL (into a href or src attribute)
yn($yesno, $format=1, $color=0)
Return yes or no in current language.
img_printer($titlealt="default", $other='')
Show printer logo.
dol_htmloutput_events($disabledoutputofmessages=0)
Print formatted messages to output (Used to show messages on html output).
getTitleFieldOfList($name, $thead=0, $file="", $field="", $begin="", $moreparam="", $moreattrib="", $sortfield="", $sortorder="", $prefix="", $disablesortlink=0, $tooltip='', $forcenowrapcolumntitle=0)
Get title line of an array.
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...
dol_substr($string, $start, $length=null, $stringencoding='', $trunconbytes=0)
Make a substring.
ascii_check($str)
Check if a string is in ASCII.
get_date_range($date_start, $date_end, $format='', $outputlangs=null, $withparenthesis=1)
Format output for start and end date.
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
getImgPictoConv($mode='fa')
Get array to convert the Dolibarr picto keys into font awesome keys.
print_date_range($date_start, $date_end, $format='', $outputlangs=null)
Format output for start and end date.
getArrayOfSocialNetworks()
Get array of social network dictionary.
num2Alpha($n)
Return a numeric value into an Excel like column number.
dol_size($size, $type='')
Optimize a size for some browsers (phone, smarphone...)
img_split($titlealt='default', $other='class="pictosplit"')
Show split logo.
img_pdf($titlealt='default', $size=3)
Show pdf logo.
dolGetCountryCodeFromIp($ip)
Return a country code from IP.
dol_textishtml($msg, $option=0)
Return if a text is a html content.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
dolPrintPassword($s)
Return a string ready to be output on an HTML attribute (alt, title, ...)
dol_escape_all($stringtoescape)
Returns text escaped for all protocols (so only alpha chars and numbers)
GETPOSTFLOAT($paramname, $rounding='')
Return the value of a $_GET or $_POST supervariable, converted into float.
dolForgeSQLCriteriaCallback($matches)
Function to forge a SQL criteria from a USF (Universal Filter Syntax) string.
if(!function_exists( 'utf8_encode')) if(!function_exists('utf8_decode')) if(!function_exists( 'str_starts_with')) if(!function_exists('str_ends_with')) if(!function_exists( 'str_contains')) getMultidirOutput($object, $module='', $forobject=0, $mode='output')
Return the full path of the directory where a module (or an object of a module) stores its files.
dol_shutdown()
Function called at end of web php process.
dol_print_address($address, $htmlid, $element, $id, $noprint=0, $charfornl='')
Format address string.
dol_print_error_email($prefixcode, $errormessage='', $errormessages=array(), $morecss='error', $email='')
Show a public email and error code to contact if technical error.
dol_escape_uri($stringtoescape)
Returns text escaped by RFC 3986 for inclusion into a clickable link.
dol_print_profids($profID, $profIDtype, $countrycode='', $addcpButton=1)
Format professional IDs according to their country.
print_titre($title)
Show a title.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_string_nounprintableascii($str, $removetabcrlf=1)
Clean a string from all non printable ASCII chars (0x00-0x1F and 0x7F).
getDolGlobalBool($key, $default=false)
Return a Dolibarr global constant boolean value.
img_error($titlealt='default')
Show error logo.
getTimelineIcon($actionstatic, &$histo, $key)
Get timeline icon.
dol_htmloutput_mesg($mesgstring='', $mesgarray=array(), $style='ok', $keepembedded=0)
Print formatted messages to output (Used to show messages on html output).
dol_clone($object, $native=2)
Create a clone of instance of object (new instance with same value for each properties) With native =...
getUserRemoteIP($trusted=0)
Return the real IP of remote user.
buildParamDate($prefix, $timestamp=null, $hourTime='', $gm='auto')
Helper function that combines values of a dolibarr DatePicker (such as Form\selectDate) for year,...
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
img_next($titlealt='default', $moreatt='')
Show next logo.
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
dol_string_is_good_iso($s, $clean=0)
Check if a string is a correct iso string If not, it will not be considered as HTML encoded even if i...
getNonce()
Return a random string to be used as a nonce value for js.
isStringVarMatching($var, $regextext, $matchrule=1)
Check if a variable with name $var startx with $text.
dolSlugify($stringtoslugify)
Returns text slugified (lowercase and no special char, separator is "-").
complete_head_from_modules($conf, $langs, $object, &$head, &$h, $type, $mode='add', $filterorigmodule='')
Complete or removed entries into a head array (used to build tabs).
get_htmloutput_mesg($mesgstring='', $mesgarray=[], $style='ok', $keepembedded=0)
Get formatted messages to output (Used to show messages on html output).
dol_htmlentitiesbr($stringtoencode, $nl2brmode=0, $pagecodefrom='UTF-8', $removelasteolbr=1)
This function is called to encode a string into a HTML string but differs from htmlentities because a...
get_product_localtax_for_country($idprod, $local, $thirdpartytouse)
Return localtax vat rate of a product in a particular country or default country vat if product is un...
print_fleche_navigation($page, $file, $options='', $nextpage=0, $betweenarrows='', $afterarrows='', $limit=-1, $totalnboflines=0, $selectlimitsuffix='', $beforearrows='', $hidenavigation=0)
Function to show navigation arrows into lists.
dol_nboflines($s, $maxchar=0)
Return nb of lines of a clear text.
dol_htmlwithnojs($stringtoencode, $nouseofiframesandbox=0, $check='restricthtml')
Sanitize a HTML to remove js, dangerous content and external links.
jsonOrUnserialize($stringtodecode)
Decode an encode string.
isValidEmail($address, $acceptsupervisorkey=0, $acceptuserkey=0)
Return true if email syntax is ok.
dol_escape_xml($stringtoescape)
Returns text escaped for inclusion into a XML string.
getActionCommEcmList($object)
getActionCommEcmList
dol_ucwords($string, $encoding="UTF-8")
Convert first character of all the words of a string to upper.
img_edit_add($titlealt='default', $other='')
Show logo +.
print_fiche_titre($title, $mesg='', $picto='generic', $pictoisfullpath=0, $id='')
Show a title with picto.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0)
Clean a string to use it as a file name.
get_product_vat_for_country($idprod, $thirdpartytouse, $idprodfournprice=0)
Return vat rate of a product in a particular country, or default country vat if product is unknown.
dolForgeDummyCriteriaCallback($matches)
Function to forge a SQL criteria from a Dolibarr filter syntax string.
dol_string_onlythesehtmltags($stringtoclean, $cleanalsosomestyles=1, $removeclassattribute=1, $cleanalsojavascript=0, $allowiframe=0, $allowed_tags=array(), $allowlink=0, $allowscript=0, $allowstyle=0, $allowphp=0)
Clean a string to keep only desirable HTML tags.
dol_escape_json($stringtoescape)
Returns text escaped for inclusion into javascript code.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.
dol_validElement($element)
Return if var element is ok.
dol_sanitizeKeyCode($str)
Clean a string to use it as a key or code.
img_credit_card($brand, $morecss=null)
Return image of a credit card according to its brand name.
info_admin($text, $infoonimgalt=0, $nodiv=0, $admin='1', $morecss='hideonsmartphone', $textfordropdown='', $picto='')
Show information in HTML for admin users or standard users.
img_searchclear($titlealt='default', $other='')
Show search logo.
getWarningDelay($module, $parmlevel1, $parmlevel2='')
Return a warning delay You can use it like this: if (getWarningDelay('module', 'paramlevel1')) It rep...
utf8_check($str)
Check if a string is in UTF8.
img_edit($titlealt='default', $float=0, $other='')
Show logo edit/modify fiche.
get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Function that return vat rate of a product line (according to seller, buyer and product vat rate) VAT...
img_up($titlealt='default', $selected=0, $moreclass='')
Show top arrow logo.
dol_htmloutput_errors($mesgstring='', $mesgarray=array(), $keepembedded=0)
Print formatted error messages to output (Used to show messages on html output).
get_localtax($vatrate, $local, $thirdparty_buyer=null, $thirdparty_seller=null, $vatnpr=0)
Return localtax rate for a particular vat, when selling a product with vat $vatrate,...
get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart='')
Return a path to have a the directory according to object where files are stored.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_sanitizePathName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a path name.
dolPrintHTMLForAttributeUrl($s)
Return a string ready to be output on a href attribute (this one need a special because we need conte...
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
img_edit_remove($titlealt='default', $other='')
Show logo -.
img_info($titlealt='default')
Show info logo.
getDoliDBInstance($type, $host, $user, $pass, $name, $port)
Return a DoliDB instance (database handler).
dol_sanitizeEmail($stringtoclean)
Clean a string to use it as an Email.
dol_nboflines_bis($text, $maxlinesize=0, $charset='UTF-8')
Return nb of lines of a formatted text with and (WARNING: string must not have mixed and br sep...
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
const MODULE_MAPPING
This mapping defines the conversion to the current internal names from the alternative allowed names ...
dolBECalculateStructuredCommunication($invoice_number, $invoice_type)
Calculate Structured Communication / BE Bank payment reference number.
dol_convertToWord($num, $langs, $currency='', $centimes=false)
Function to return a number into a text.
treeview li table
No Email.
ui state ui widget content ui state ui widget header ui state a ui button
0 = Do not include form tag and submit button -1 = Do not include form tag but include submit button
div refaddress div address
if(!defined( 'NOREQUIREMENU')) if(!empty(GETPOST('seteventmessages', 'alpha'))) if(!function_exists("llxHeader")) top_httphead($contenttype='text/html', $forcenocache=0)
Show HTTP header.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79
dol_setcache($memoryid, $data, $expire=0, $filecache=0, $replace=0)
Save data into a memory area shared by all users, all sessions on server.
dol_getcache($memoryid, $filecache=0)
Read a memory area shared by all users, all sessions on server.
if(preg_match('/(crypted|dolcrypt):/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
Definition repair.php:158
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:161
realCharForNumericEntities($matches)
Return the real char for a numeric entities.
Definition waf.inc.php:66