dolibarr 23.0.4
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-2026 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-2026 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) 2025 Vincent Maury <vmaury@timgroup.fr>
29 * Copyright (C) 2026 Benjamin Falière <benjamin@faliere.com>
30 *
31 * This program is free software; you can redistribute it and/or modify
32 * it under the terms of the GNU General Public License as published by
33 * the Free Software Foundation; either version 3 of the License, or
34 * (at your option) any later version.
35 *
36 * This program is distributed in the hope that it will be useful,
37 * but WITHOUT ANY WARRANTY; without even the implied warranty of
38 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
39 * GNU General Public License for more details.
40 *
41 * You should have received a copy of the GNU General Public License
42 * along with this program. If not, see <https://www.gnu.org/licenses/>.
43 * or see https://www.gnu.org/
44 */
45
52//include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
53
54// Function for better PHP x compatibility
55if (!function_exists('utf8_encode')) {
63 function utf8_encode($elements)
64 {
65 return mb_convert_encoding($elements, 'UTF-8', 'ISO-8859-1');
66 }
67}
68
69if (!function_exists('utf8_decode')) {
77 function utf8_decode($elements)
78 {
79 return mb_convert_encoding($elements, 'ISO-8859-1', 'UTF-8');
80 }
81}
82if (!function_exists('str_starts_with')) {
91 function str_starts_with($haystack, $needle)
92 {
93 return (string) $needle !== '' && strncmp($haystack, $needle, strlen($needle)) === 0;
94 }
95}
96if (!function_exists('str_ends_with')) {
105 function str_ends_with($haystack, $needle)
106 {
107 return $needle !== '' && substr($haystack, -strlen($needle)) === (string) $needle;
108 }
109}
110if (!function_exists('str_contains')) {
119 function str_contains($haystack, $needle)
120 {
121 return $needle !== '' && mb_strpos($haystack, $needle) !== false;
122 }
123}
124
125
137function getMultidirOutput($object, $module = '', $forobject = 0, $mode = 'output')
138{
139 global $conf;
140
141 $subdirectory = '';
142 if (!is_object($object) && empty($module)) {
143 return null;
144 }
145 if (empty($module) && !empty($object->element)) {
146 $module = $object->element;
147 }
148
149 // Special case for backward compatibility
150 switch ($module) {
151 case 'fichinter':
152 $module = 'ficheinter';
153 break;
154 case 'invoice_supplier':
155 $module = 'supplier_invoice';
156 break;
157 case 'order_supplier':
158 $module = 'supplier_order';
159 break;
160 case 'recruitmentjobposition':
161 $module = 'recruitment';
162 $subdirectory = '/recruitmentjobposition';
163 break;
164 case 'recruitmentcandidature':
165 $module = 'recruitment';
166 $subdirectory = '/recruitmentcandidature';
167 break;
168 case 'knowledgerecord':
169 $module = 'knowledgemanagement';
170 $subdirectory = '/knowledgerecord';
171 break;
172 case 'service':
173 case 'produit':
174 $module = 'product';
175 break;
176 case 'action':
177 case 'actioncomm':
178 case 'event':
179 $module = 'agenda';
180 break;
181 default:
182 break;
183 }
184
185 // Get the relative path of directory
186 if ($mode == 'output' || $mode == 'outputrel' || $mode == 'version') {
187 if (isset($conf->$module) && property_exists($conf->$module, 'multidir_output')) {
188 $s = '';
189 if ($mode != 'outputrel') {
190 // An entity with no declared directory returned an undefined index, so an empty path that
191 // made the caller read or write a relative path under the web root. Answer the error instead.
192 $entity = (int) (empty($object->entity) ? $conf->entity : $object->entity);
193 if (!isset($conf->$module->multidir_output[$entity])) {
194 return 'error-diroutput-not-defined-for-this-entity-and-object='.$module;
195 }
196 $s = $conf->$module->multidir_output[$entity] . $subdirectory;
197 }
198 if ($forobject && $object->id > 0) {
199 $s .= ($mode != 'outputrel' ? '/' : '') . get_exdir(0, 0, 0, 0, $object);
200 }
201 return $s;
202 } elseif (isset($conf->$module) && property_exists($conf->$module, 'dir_output')) {
203 $s = '';
204 if ($mode != 'outputrel') {
205 $s = $conf->$module->dir_output . $subdirectory;
206 }
207 if ($forobject && $object->id > 0) {
208 $s .= ($mode != 'outputrel' ? '/' : '') . get_exdir(0, 0, 0, 0, $object);
209 }
210 return $s;
211 } else {
212 return 'error-diroutput-not-defined-for-this-entity-and-object='.$module;
213 }
214 } elseif ($mode == 'temp') {
215 if (isset($conf->$module) && property_exists($conf->$module, 'multidir_temp')) {
216 // Same guard as the 'output' mode above, see the comment there
217 $entity = (int) (empty($object->entity) ? $conf->entity : $object->entity);
218 if (!isset($conf->$module->multidir_temp[$entity])) {
219 return 'error-dirtemp-not-defined-for-this-entity-and-object='.$module;
220 }
221 return $conf->$module->multidir_temp[$entity];
222 } elseif (isset($conf->$module) && property_exists($conf->$module, 'dir_temp')) {
223 return $conf->$module->dir_temp;
224 } else {
225 return 'error-dirtemp-not-defined-for-this-entity-and-object='.$module;
226 }
227 } else {
228 return 'error-bad-value-for-mode';
229 }
230}
231
241function getMultidirTemp($object, $module = '', $forobject = 0)
242{
243 return getMultidirOutput($object, $module, $forobject, 'temp');
244}
245
255function getMultidirVersion($object, $module = '', $forobject = 0)
256{
257 return getMultidirOutput($object, $module, $forobject, 'version');
258}
259
260
269function getDolGlobalString($key, $default = '')
270{
271 global $conf;
272 return (string) (isset($conf->global->$key) ? $conf->global->$key : $default);
273}
274
284function getDolGlobalInt($key, $default = 0)
285{
286 global $conf;
287 return (int) (isset($conf->global->$key) ? $conf->global->$key : $default);
288}
289
299function getDolGlobalFloat($key, $default = 0)
300{
301 global $conf;
302 return (float) (isset($conf->global->$key) ? $conf->global->$key : $default);
303}
304
313function getDolGlobalBool($key, $default = false)
314{
315 global $conf;
316 return (bool) ($conf->global->$key ?? $default);
317}
318
325{
326 global $conf;
327 return (string) $conf->currency;
328}
329
336{
337 global $conf;
338 return (string) $conf->dol_optimize_smallscreen;
339}
340
346function getDolEntity()
347{
348 global $conf;
349 return (int) $conf->entity;
350}
351
357function getDolDBType()
358{
359 global $conf;
360 return $conf->db->type;
361}
362
370{
371 return str_replace('_', '', basename(dirname($s)).basename($s, '.php'));
372}
373
383function getDolUserString($key, $default = '', $tmpuser = null)
384{
385 if (empty($tmpuser)) {
386 global $user;
387 $tmpuser = $user;
388 }
389
390 return (string) (isset($tmpuser->conf->$key) ? $tmpuser->conf->$key : $default);
391}
392
401function getDolUserInt($key, $default = 0, $tmpuser = null)
402{
403 if (empty($tmpuser)) {
404 global $user;
405 $tmpuser = $user;
406 }
407
408 return (int) (isset($tmpuser->conf->$key) ? $tmpuser->conf->$key : $default);
409}
410
411
421define(
422 'MODULE_MAPPING',
423 array(
424 // Map deprecated names to new names
425 'adherent' => 'member', // Has new directory
426 'member_type' => 'adherent_type', // No directory, but file called adherent_type
427 'banque' => 'bank', // Has new directory
428 'contrat' => 'contract', // Has new directory
429 'entrepot' => 'stock', // Has new directory
430 'projet' => 'project', // Has new directory
431 'categorie' => 'category', // Has old directory
432 'commande' => 'order', // Has old directory
433 'expedition' => 'shipping', // Has old directory
434 'facture' => 'invoice', // Has old directory
435 'fichinter' => 'intervention', // Has old directory
436 'ficheinter' => 'intervention', // Backup for 'fichinter'
437 'propale' => 'propal', // Has old directory
438 'socpeople' => 'contact', // Has old directory
439 'fournisseur' => 'supplier', // Has old directory
440
441 'actioncomm' => 'agenda', // NO module directory (public dir agenda)
442 'product_price' => 'productprice', // NO directory
443 'product_fournisseur_price' => 'productsupplierprice', // NO directory
444 )
445);
446
453function isModEnabled($module)
454{
455 global $conf;
456
457 // Fix old names (map to new names)
458 $arrayconv = MODULE_MAPPING;
459 $arrayconvbis = array_flip(MODULE_MAPPING);
460
461 if (!getDolGlobalString('MAIN_USE_NEW_SUPPLIERMOD')) {
462 // Special cases: both use the same module.
463 $arrayconv['supplier_order'] = 'fournisseur';
464 $arrayconv['supplier_invoice'] = 'fournisseur';
465 }
466
467 $module_alt = $module;
468 if (!empty($arrayconv[$module])) {
469 $module_alt = $arrayconv[$module];
470 }
471 $module_bis = $module;
472 if (!empty($arrayconvbis[$module])) {
473 $module_bis = $arrayconvbis[$module];
474 }
475
476 return !empty($conf->modules[$module]) || !empty($conf->modules[$module_alt]) || !empty($conf->modules[$module_bis]);
477}
478
489function getWarningDelay($module, $parmlevel1, $parmlevel2 = '')
490{
491 global $conf;
492
493 // For compatibility with bad naming on module
494 $moduletomoduletouse = array(
495 'invoice' => 'facture',
496 );
497 $moduleParmsMapping = array(
498 'product' => 'produit',
499 );
500
501 if (!empty($moduletomoduletouse[$module])) {
502 $module = $moduletomoduletouse[$module];
503 }
504
505 $warningDelayPath = $parmlevel1;
506 if (!empty($moduleParmsMapping[$warningDelayPath])) {
507 $warningDelayPath = $moduleParmsMapping[$warningDelayPath];
508 }
509
510 if ($parmlevel2) {
511 if (!empty($conf->$module) && !empty($conf->$module->$warningDelayPath) && !empty($conf->$module->$warningDelayPath->$parmlevel2) && !empty($conf->$module->$warningDelayPath->$parmlevel2->warning_delay)) {
512 return (int) $conf->$module->$warningDelayPath->$parmlevel2->warning_delay;
513 }
514 } else {
515 if (!empty($conf->$module) && !empty($conf->$module->$warningDelayPath) && !empty($conf->$module->$warningDelayPath->warning_delay)) {
516 return (int) $conf->$module->$warningDelayPath->warning_delay;
517 }
518 }
519
520 return 0;
521}
522
529function isDolTms($timestamp)
530{
531 if ($timestamp === '') {
532 dol_syslog('Using empty string for a timestamp is deprecated, prefer use of null when calling page ' . $_SERVER["PHP_SELF"] . getCallerInfoString(), LOG_DEBUG);
533 return false;
534 }
535 if (is_null($timestamp) || !is_numeric($timestamp)) {
536 return false;
537 }
538
539 return true;
540}
541
553function getDoliDBInstance($type, $host, $user, $pass, $name, $port)
554{
555 require_once DOL_DOCUMENT_ROOT . "/core/db/" . $type . '.class.php';
556
557 $class = 'DoliDB' . ucfirst($type);
558 $db = new $class($type, $host, $user, $pass, $name, $port);
559 return $db;
560}
561
579function getEntity($element, $shared = 1, $currentobject = null)
580{
581 global $conf, $mc, $hookmanager, $object, $action, $db;
582
583 if (!is_object($hookmanager)) {
584 include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
585 $hookmanager = new HookManager($db);
586 }
587
588 // fix different element names (France to English)
589 switch ($element) {
590 case 'projet':
591 $element = 'project';
592 break;
593 case 'contrat':
594 $element = 'contract';
595 break; // "/contrat/class/contrat.class.php"
596 case 'order_supplier':
597 $element = 'supplier_order';
598 break; // "/fourn/class/fournisseur.commande.class.php"
599 case 'invoice_supplier':
600 $element = 'supplier_invoice';
601 break; // "/fourn/class/fournisseur.facture.class.php"
602 }
603
604 if (is_object($mc)) {
605 $out = $mc->getEntity($element, $shared, $currentobject);
606 } else {
607 $out = '';
608 $addzero = array('user', 'usergroup', 'cronjob', 'c_email_templates', 'email_template', 'default_values', 'overwrite_trans', 'extrafields');
609 if (getDolGlobalString('HOLIDAY_ALLOW_ZERO_IN_DIC')) { // this constant break the dictionary admin without Multicompany
610 $addzero[] = 'c_holiday_types';
611 }
612 if (in_array($element, $addzero)) {
613 $out .= '0,';
614 }
615 $out .= ((int) $conf->entity);
616 }
617
618 // Manipulate entities to query on the fly
619 $parameters = array(
620 'element' => $element,
621 'shared' => $shared,
622 'object' => $object,
623 'currentobject' => $currentobject,
624 'out' => $out
625 );
626 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable
627 $reshook = $hookmanager->executeHooks('hookGetEntity', $parameters, $currentobject, $action); // Note that $action and $object may have been modified by some hooks
628
629 if (is_numeric($reshook)) {
630 if ($reshook == 0 && !empty($hookmanager->resPrint)) {
631 $out .= ',' . $hookmanager->resPrint; // add
632 } elseif ($reshook == 1) {
633 $out = $hookmanager->resPrint; // replace
634 }
635 }
636
637 return $out;
638}
639
646function setEntity($currentobject)
647{
648 global $conf, $mc;
649
650 if (is_object($mc) && method_exists($mc, 'setEntity')) {
651 return $mc->setEntity($currentobject);
652 } else {
653 return ((is_object($currentobject) && $currentobject->id > 0 && ((int) $currentobject->entity) > 0) ? (int) $currentobject->entity : $conf->entity);
654 }
655}
656
663function isASecretKey($keyname)
664{
665 return preg_match('/(_pass|password|_pw|_key|securekey|serverkey|secret\d?|p12key|exportkey|_PW_[a-z]+|token)$/i', $keyname);
666}
667
668
675function num2Alpha($n)
676{
677 $r = '';
678 for ($r = ""; $n >= 0; $n = intval($n / 26) - 1) {
679 $r = chr($n % 26 + 0x41) . $r;
680 }
681 return $r;
682}
683
684
701function getBrowserInfo($user_agent)
702{
703 include_once DOL_DOCUMENT_ROOT . '/includes/mobiledetect/mobiledetectlib/Mobile_Detect.php';
704
705 $name = 'unknown';
706 $version = '';
707 $os = 'unknown';
708 $phone = '';
709
710 $user_agent = substr($user_agent, 0, 512); // Avoid to process too large user agent
711
712 // @phan-suppress-next-line PhanTypeMismatchArgumentProbablyReal Bad definition of Mobile_Detect function
713 $detectmobile = new Mobile_Detect(null, $user_agent);
714 $tablet = $detectmobile->isTablet();
715
716 if ($detectmobile->isMobile()) {
717 $phone = 'unknown';
718
719 // If phone/smartphone, we set phone os name.
720 if ($detectmobile->is('AndroidOS')) {
721 $os = $phone = 'android';
722 } elseif ($detectmobile->is('BlackBerryOS')) {
723 $os = $phone = 'blackberry';
724 } elseif ($detectmobile->is('iOS')) {
725 $os = 'ios';
726 $phone = 'iphone';
727 } elseif ($detectmobile->is('PalmOS')) {
728 $os = $phone = 'palm';
729 } elseif ($detectmobile->is('SymbianOS')) {
730 $os = 'symbian';
731 } elseif ($detectmobile->is('webOS')) {
732 $os = 'webos';
733 } elseif ($detectmobile->is('MaemoOS')) {
734 $os = 'maemo';
735 } elseif ($detectmobile->is('WindowsMobileOS') || $detectmobile->is('WindowsPhoneOS')) {
736 $os = 'windows';
737 }
738 }
739
740 // OS
741 if (preg_match('/linux/i', $user_agent)) {
742 $os = 'linux';
743 } elseif (preg_match('/macintosh/i', $user_agent)) {
744 $os = 'macintosh';
745 } elseif (preg_match('/windows/i', $user_agent)) {
746 $os = 'windows';
747 }
748
749 // Name
750 $reg = array();
751 if (preg_match('/firefox(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
752 $name = 'firefox';
753 $version = empty($reg[2]) ? '' : $reg[2];
754 } elseif (preg_match('/edge(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
755 $name = 'edge';
756 $version = empty($reg[2]) ? '' : $reg[2];
757 } elseif (preg_match('/chrome(\/|\s)([\d\.]+)/i', $user_agent, $reg)) {
758 $name = 'chrome';
759 $version = empty($reg[2]) ? '' : $reg[2];
760 } elseif (preg_match('/chrome/i', $user_agent, $reg)) {
761 // we can have 'chrome (Mozilla...) chrome x.y' in one string
762 $name = 'chrome';
763 } elseif (preg_match('/iceweasel/i', $user_agent)) {
764 $name = 'iceweasel';
765 } elseif (preg_match('/epiphany/i', $user_agent)) {
766 $name = 'epiphany';
767 } elseif (preg_match('/safari(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
768 $name = 'safari';
769 $version = empty($reg[2]) ? '' : $reg[2];
770 } elseif (preg_match('/opera(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
771 // Safari is often present in string for mobile but its not.
772 $name = 'opera';
773 $version = empty($reg[2]) ? '' : $reg[2];
774 } elseif (preg_match('/(MSIE\s([0-9]+\.[0-9]))|.*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
775 $name = 'ie';
776 $version = end($reg);
777 } elseif (preg_match('/(Windows NT\s([0-9]+\.[0-9])).*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
778 // MS products at end
779 $name = 'ie';
780 $version = end($reg);
781 } elseif (preg_match('/l[iy]n(x|ks)(\‍(|\/|\s)*([\d\.]+)/i', $user_agent, $reg)) {
782 // MS products at end
783 $name = 'textbrowser';
784 $version = empty($reg[3]) ? '' : $reg[3];
785 } elseif (preg_match('/w3m\/([\d\.]+)/i', $user_agent, $reg)) {
786 // MS products at end
787 $name = 'textbrowser';
788 $version = empty($reg[1]) ? '' : $reg[1];
789 }
790
791 if ($tablet) {
792 $layout = 'tablet';
793 } elseif ($phone) {
794 $layout = 'phone';
795 } else {
796 $layout = 'classic';
797 }
798
799 return array(
800 'browsername' => $name,
801 'browserversion' => $version,
802 'browseros' => $os,
803 'browserua' => $user_agent,
804 'layout' => $layout, // tablet, phone, classic
805 'phone' => $phone, // deprecated
806 'tablet' => $tablet // deprecated
807 );
808}
809
815function dol_shutdown()
816{
817 global $db;
818 $disconnectdone = false;
819 $depth = 0;
820 if (is_object($db) && !empty($db->connected)) {
821 $depth = $db->transaction_opened;
822 $disconnectdone = $db->close();
823 }
824 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));
825}
826
836function GETPOSTISSET($paramname)
837{
838 $isset = false;
839
840 $relativepathstring = $_SERVER["PHP_SELF"];
841 // Clean $relativepathstring
842 if (constant('DOL_URL_ROOT')) {
843 $relativepathstring = preg_replace('/^' . preg_quote(constant('DOL_URL_ROOT'), '/') . '/', '', $relativepathstring);
844 }
845 $relativepathstring = ltrim($relativepathstring, '/');
846 $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
847
848 // Code for search criteria persistence.
849 // Retrieve values if restore_lastsearch_values
850 if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
851 if (!empty($_SESSION['lastsearch_values_' . $relativepathstring])) { // If there is saved values
852 $tmp = json_decode($_SESSION['lastsearch_values_' . $relativepathstring], true);
853 if (is_array($tmp)) {
854 foreach ($tmp as $key => $val) {
855 if ($key == $paramname) { // We are on the requested parameter
856 $isset = true;
857 break;
858 }
859 }
860 }
861 }
862 // If there is saved contextpage, limit, page or mode
863 if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_' . $relativepathstring])) {
864 $isset = true;
865 } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_' . $relativepathstring])) {
866 $isset = true;
867 } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_' . $relativepathstring])) {
868 $isset = true;
869 } elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_' . $relativepathstring])) {
870 $isset = true;
871 }
872 } else {
873 $isset = (isset($_POST[$paramname]) || isset($_GET[$paramname])); // We must keep $_POST and $_GET here
874 }
875
876 return $isset;
877}
878
887function GETPOSTISARRAY($paramname, $method = 0)
888{
889 // for $method test need return the same $val as GETPOST
890 if (empty($method)) {
891 $val = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
892 } elseif ($method == 1) {
893 $val = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
894 } elseif ($method == 2) {
895 $val = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
896 } elseif ($method == 3) {
897 $val = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
898 } else {
899 $val = 'BadFirstParameterForGETPOST';
900 }
901
902 return is_array($val);
903}
904
905
915function GETPOSTINT($paramname, $method = 0)
916{
917 return (int) GETPOST($paramname, 'int', $method, null, null, 0);
918}
919
933function GETPOSTFLOAT($paramname, $rounding = '', $option = 2)
934{
935 // price2num() can be used to round to an expected accuracy and/or to sanitize any valid user input (such as "1 234.5", "1 234,5", "1'234,5", "1·234,5", "1,234.5", etc.)
936 return (float) price2num(GETPOST($paramname), $rounding, $option);
937}
938
954function GETPOSTDATE($prefix, $hourTime = '', $gm = 'auto', $saverestore = '')
955{
956 $m = array();
957 if ($hourTime === 'getpost' || $hourTime === 'getpostend') {
958 $hour = (GETPOSTISSET($prefix . 'hour') && GETPOSTINT($prefix . 'hour') >= 0) ? GETPOSTINT($prefix . 'hour') : ($hourTime === 'getpostend' ? 23 : 0);
959 $minute = (GETPOSTISSET($prefix . 'min') && GETPOSTINT($prefix . 'min') >= 0) ? GETPOSTINT($prefix . 'min') : ($hourTime === 'getpostend' ? 59 : 0);
960 $second = (GETPOSTISSET($prefix . 'sec') && GETPOSTINT($prefix . 'sec') >= 0) ? GETPOSTINT($prefix . 'sec') : ($hourTime === 'getpostend' ? 59 : 0);
961 } elseif (preg_match('/^(\d\d):(\d\d):(\d\d)$/', $hourTime, $m)) {
962 $hour = intval($m[1]);
963 $minute = intval($m[2]);
964 $second = intval($m[3]);
965 } elseif ($hourTime === 'end') {
966 $hour = 23;
967 $minute = 59;
968 $second = 59;
969 } else {
970 $hour = $minute = $second = 0;
971 }
972
973 if (
974 $saverestore
975 && !GETPOSTISSET($prefix . 'day')
976 && !GETPOSTISSET($prefix . 'month')
977 && !GETPOSTISSET($prefix . 'year')
978 && isset($_SESSION['DOLDATE_' . $saverestore . '_day'])
979 && isset($_SESSION['DOLDATE_' . $saverestore . '_month'])
980 && isset($_SESSION['DOLDATE_' . $saverestore . '_year'])
981 ) {
982 $day = $_SESSION['DOLDATE_' . $saverestore . '_day'];
983 $month = $_SESSION['DOLDATE_' . $saverestore . '_month'];
984 $year = $_SESSION['DOLDATE_' . $saverestore . '_year'];
985 } else {
986 $month = GETPOSTINT($prefix . 'month');
987 $day = GETPOSTINT($prefix . 'day');
988 $year = GETPOSTINT($prefix . 'year');
989 }
990
991 // normalize out of range values
992 $hour = (int) min($hour, 23);
993 $minute = (int) min($minute, 59);
994 $second = (int) min($second, 59);
995
996 if ($saverestore) {
997 $_SESSION['DOLDATE_' . $saverestore . '_day'] = $day;
998 $_SESSION['DOLDATE_' . $saverestore . '_month'] = $month;
999 $_SESSION['DOLDATE_' . $saverestore . '_year'] = $year;
1000 }
1001
1002 //print "$hour, $minute, $second, $month, $day, $year, $gm<br>";
1003 return dol_mktime($hour, $minute, $second, $month, $day, $year, $gm);
1004}
1005
1046function GETPOST($paramname, $check = 'alphanohtml', $method = 0, $filter = null, $options = null, $noreplace = 0)
1047{
1048 global $mysoc, $user, $conf;
1049
1050 if (empty($paramname)) { // Explicit test for null for phan.
1051 return 'BadFirstParameterForGETPOST';
1052 }
1053 if (empty($check)) {
1054 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);
1055 // Enable this line to know who call the GETPOST with '' $check parameter.
1056 //var_dump(getCallerInfoString());
1057 }
1058
1059 if (empty($method)) {
1060 $out = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
1061 } elseif ($method == 1) {
1062 $out = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
1063 } elseif ($method == 2) {
1064 $out = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
1065 } elseif ($method == 3) {
1066 $out = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
1067 } else {
1068 return 'BadThirdParameterForGETPOST';
1069 }
1070
1071 $relativepathstring = ''; // For static analysis - looks possibly undefined if not set.
1072
1073 if (empty($method) || $method == 3 || $method == 4) {
1074 $relativepathstring = (empty($_SERVER["PHP_SELF"]) ? '' : $_SERVER["PHP_SELF"]);
1075 // Clean $relativepathstring
1076 if (constant('DOL_URL_ROOT')) {
1077 $relativepathstring = preg_replace('/^' . preg_quote(constant('DOL_URL_ROOT'), '/') . '/', '', $relativepathstring);
1078 }
1079 $relativepathstring = ltrim($relativepathstring, '/');
1080 $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
1081
1082 // Code for search criteria persistence.
1083 // Retrieve saved values if restore_lastsearch_values is set
1084 if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
1085 if (!empty($_SESSION['lastsearch_values_' . $relativepathstring])) { // If there is saved values
1086 $tmp = json_decode($_SESSION['lastsearch_values_' . $relativepathstring], true);
1087 if (is_array($tmp)) {
1088 foreach ($tmp as $key => $val) {
1089 if ($key == $paramname) { // We are on the requested parameter
1090 $out = $val;
1091 break;
1092 }
1093 }
1094 }
1095 }
1096 // If there is saved contextpage, page or limit
1097 if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_' . $relativepathstring])) {
1098 $out = $_SESSION['lastsearch_contextpage_' . $relativepathstring];
1099 } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_' . $relativepathstring])) {
1100 $out = $_SESSION['lastsearch_limit_' . $relativepathstring];
1101 } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_' . $relativepathstring])) {
1102 $out = $_SESSION['lastsearch_page_' . $relativepathstring];
1103 } elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_' . $relativepathstring])) {
1104 $out = $_SESSION['lastsearch_mode_' . $relativepathstring];
1105 }
1106 } elseif (!isset($_GET['sortfield'])) {
1107 // Else, retrieve default values if we are not doing a sort
1108 // 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
1109 if (!empty($_GET['action']) && $_GET['action'] == 'create' && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
1110 // Search default value from $object->field
1111 global $object;
1112 '@phan-var-force CommonObject $object'; // Suppose it's a CommonObject for analysis, but other objects have the $fields field as well
1113 if (is_object($object) && isset($object->fields[$paramname]['default'])) {
1114 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
1115 $out = $object->fields[$paramname]['default'];
1116 }
1117 }
1118 if (getDolGlobalString('MAIN_ENABLE_DEFAULT_VALUES')) {
1119 if (!empty($_GET['action']) && (preg_match('/^create/', $_GET['action']) || preg_match('/^presend/', $_GET['action'])) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
1120 // Now search in setup to overwrite default values
1121 if (!empty($user->default_values)) { // $user->default_values defined from menu 'Setup - Default values'
1122 if (isset($user->default_values[$relativepathstring]['createform'])) {
1123 foreach ($user->default_values[$relativepathstring]['createform'] as $defkey => $defval) {
1124 $qualified = 0;
1125 if ($defkey != '_noquery_') {
1126 $tmpqueryarraytohave = explode('&', $defkey);
1127 $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
1128 $foundintru = 0;
1129 foreach ($tmpqueryarraytohave as $tmpquerytohave) {
1130 if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
1131 $foundintru = 1;
1132 }
1133 }
1134 if (!$foundintru) {
1135 $qualified = 1;
1136 }
1137 } else {
1138 $qualified = 1;
1139 }
1140
1141 if ($qualified) {
1142 if (isset($user->default_values[$relativepathstring]['createform'][$defkey][$paramname])) {
1143 $out = $user->default_values[$relativepathstring]['createform'][$defkey][$paramname];
1144 break;
1145 }
1146 }
1147 }
1148 }
1149 }
1150 } elseif (!empty($paramname) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
1151 // Management of default search_filters and sort order
1152 if (!empty($user->default_values)) {
1153 // $user->default_values defined from menu 'Setup - Default values'
1154 //var_dump($user->default_values[$relativepathstring]);
1155 if ($paramname == 'sortfield' || $paramname == 'sortorder') {
1156 // Sorted on which fields ? ASC or DESC ?
1157 if (isset($user->default_values[$relativepathstring]['sortorder'])) {
1158 // Even if paramname is sortfield, data are stored into ['sortorder...']
1159 foreach ($user->default_values[$relativepathstring]['sortorder'] as $defkey => $defval) {
1160 $qualified = 0;
1161 if ($defkey != '_noquery_') {
1162 $tmpqueryarraytohave = explode('&', $defkey);
1163 $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
1164 $foundintru = 0;
1165 foreach ($tmpqueryarraytohave as $tmpquerytohave) {
1166 if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
1167 $foundintru = 1;
1168 }
1169 }
1170 if (!$foundintru) {
1171 $qualified = 1;
1172 }
1173 } else {
1174 $qualified = 1;
1175 }
1176
1177 if ($qualified) {
1178 $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
1179 foreach ($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val) {
1180 if ($out) {
1181 $out .= ', ';
1182 }
1183 if ($paramname == 'sortfield') {
1184 $out .= dol_string_nospecial($key, '', $forbidden_chars_to_replace);
1185 }
1186 if ($paramname == 'sortorder') {
1187 $out .= dol_string_nospecial($val, '', $forbidden_chars_to_replace);
1188 }
1189 }
1190 //break; // No break for sortfield and sortorder so we can cumulate fields (is it really useful ?)
1191 }
1192 }
1193 }
1194 } elseif (isset($user->default_values[$relativepathstring]['filters'])) {
1195 foreach ($user->default_values[$relativepathstring]['filters'] as $defkey => $defval) { // $defkey is a querystring like 'a=b&c=d', $defval is key of user
1196 if (!empty($_GET['disabledefaultvalues'])) { // If set of default values has been disabled by a request parameter
1197 continue;
1198 }
1199 $qualified = 0;
1200 if ($defkey != '_noquery_') {
1201 $tmpqueryarraytohave = explode('&', $defkey);
1202 $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
1203 $foundintru = 0;
1204 foreach ($tmpqueryarraytohave as $tmpquerytohave) {
1205 if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
1206 $foundintru = 1;
1207 }
1208 }
1209 if (!$foundintru) {
1210 $qualified = 1;
1211 }
1212 } else {
1213 $qualified = 1;
1214 }
1215
1216 if ($qualified && isset($user->default_values[$relativepathstring]['filters'][$defkey][$paramname])) {
1217 // We must keep $_POST and $_GET here
1218 if (isset($_POST['search_all']) || isset($_GET['search_all'])) {
1219 // We made a search from quick search menu, do we still use default filter ?
1220 if (!getDolGlobalString('MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH')) {
1221 $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
1222 $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
1223 }
1224 } else {
1225 $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
1226 $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
1227 }
1228 break;
1229 }
1230 }
1231 }
1232 }
1233 }
1234 }
1235 }
1236 }
1237
1238 // 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)
1239 // Example of variables: __DAY__, __MONTH__, __YEAR__, __MYCOMPANY_COUNTRY_ID__, __USER_ID__, ...
1240 // 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.
1241 '@phan-var-force string $paramname';
1242 if (!is_array($out) && empty($_POST[$paramname]) && empty($noreplace)) {
1243 $reg = array();
1244 $regreplace = array();
1245 $maxloop = 20;
1246 $loopnb = 0; // Protection against infinite loop
1247
1248 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.
1249 $loopnb++;
1250 $newout = '';
1251
1252 if ($reg[1] == 'DAY') {
1253 $tmp = dol_getdate(dol_now(), true);
1254 $newout = $tmp['mday'];
1255 } elseif ($reg[1] == 'MONTH') {
1256 $tmp = dol_getdate(dol_now(), true);
1257 $newout = $tmp['mon'];
1258 } elseif ($reg[1] == 'YEAR') {
1259 $tmp = dol_getdate(dol_now(), true);
1260 $newout = $tmp['year'];
1261 } elseif ($reg[1] == 'PREVIOUS_DAY') {
1262 $tmp = dol_getdate(dol_now(), true);
1263 $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
1264 $newout = $tmp2['day'];
1265 } elseif ($reg[1] == 'PREVIOUS_MONTH') {
1266 $tmp = dol_getdate(dol_now(), true);
1267 $tmp2 = dol_get_prev_month($tmp['mon'], $tmp['year']);
1268 $newout = $tmp2['month'];
1269 } elseif ($reg[1] == 'PREVIOUS_YEAR') {
1270 $tmp = dol_getdate(dol_now(), true);
1271 $newout = ($tmp['year'] - 1);
1272 } elseif ($reg[1] == 'NEXT_DAY') {
1273 $tmp = dol_getdate(dol_now(), true);
1274 $tmp2 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
1275 $newout = $tmp2['day'];
1276 } elseif ($reg[1] == 'NEXT_MONTH') {
1277 $tmp = dol_getdate(dol_now(), true);
1278 $tmp2 = dol_get_next_month($tmp['mon'], $tmp['year']);
1279 $newout = $tmp2['month'];
1280 } elseif ($reg[1] == 'NEXT_YEAR') {
1281 $tmp = dol_getdate(dol_now(), true);
1282 $newout = ($tmp['year'] + 1);
1283 } elseif ($reg[1] == 'MYCOMPANY_COUNTRY_ID' || $reg[1] == 'MYCOUNTRY_ID' || $reg[1] == 'MYCOUNTRYID') {
1284 $newout = $mysoc->country_id;
1285 } elseif ($reg[1] == 'USER_ID' || $reg[1] == 'USERID') {
1286 $newout = $user->id;
1287 } elseif ($reg[1] == 'USER_SUPERVISOR_ID' || $reg[1] == 'SUPERVISOR_ID' || $reg[1] == 'SUPERVISORID') {
1288 $newout = $user->fk_user;
1289 } elseif ($reg[1] == 'ENTITY_ID' || $reg[1] == 'ENTITYID') {
1290 $newout = $conf->entity;
1291 } elseif ($reg[1] == 'ID') {
1292 $newout = '__ID__'; // We keep __ID__ we find into backtopage url
1293 } else {
1294 $newout = 'REGREPLACE_' . $loopnb; // Key not found, we replace with temporary string to reload later
1295 $regreplace[$loopnb] = $reg[0];
1296 }
1297 //var_dump('__'.$reg[1].'__ -> '.$newout);
1298 $out = preg_replace('/__' . preg_quote($reg[1], '/') . '__/', $newout, $out);
1299 }
1300 if (!empty($regreplace)) {
1301 foreach ($regreplace as $key => $value) {
1302 $out = preg_replace('/REGREPLACE_' . $key . '/', $value, $out);
1303 }
1304 }
1305 }
1306
1307 // Check type of variable and make sanitization according to this
1308 if (preg_match('/^array/', $check)) { // If 'array' or 'array:restricthtml' or 'array:aZ09' or 'array:intcomma'
1309 $tmpcheck = 'alphanohtml';
1310 if (empty($out)) {
1311 $out = array();
1312 } elseif (!is_array($out)) {
1313 $out = explode(',', $out);
1314 } else {
1315 $tmparray = explode(':', $check);
1316 if (!empty($tmparray[1])) {
1317 $tmpcheck = $tmparray[1];
1318 }
1319 }
1320 foreach ($out as $outkey => $outval) {
1321 $out[$outkey] = sanitizeVal($outval, $tmpcheck, $filter, $options);
1322 }
1323 } else {
1324 // If field name is 'search_xxx' then we force the add of space after each < and > (when following char is numeric) because it means
1325 // 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
1326 if (strpos($paramname, 'search_') === 0) {
1327 $out = preg_replace('/([<>])([-+]?\d)/', '\1 \2', $out);
1328 }
1329
1330 // @phan-suppress-next-line UnknownSanitizeType
1331 $out = sanitizeVal($out, $check, $filter, $options);
1332 }
1333
1334 // Sanitizing for special parameters.
1335 // 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.
1336 // @TODO Merge backtopage with backtourl
1337 // @TODO Rename backtolist into backtopagelist
1338 if (preg_match('/^backto/i', $paramname)) {
1339 $out = str_replace('\\', '/', $out); // Can be before the loop because only 1 char is replaced. No risk to get it after other replacements.
1340 $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.
1341 do {
1342 $oldstringtoclean = $out;
1343 $out = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $out);
1344 $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'
1345 $out = preg_replace(array('/^[a-z]*\/\s*\/+/i'), '', $out); // We remove schema*// to remove external URL
1346 } while ($oldstringtoclean != $out);
1347 }
1348
1349 // Code for search criteria persistence.
1350 // Save data into session if key start with 'search_'
1351 if (empty($method) || $method == 3 || $method == 4) {
1352 if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder', 'sortfield'))) {
1353 //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]);
1354
1355 // We save search key only if $out not empty that means:
1356 // - posted value not empty, or
1357 // - 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).
1358
1359 if ($out != '' && isset($user)) { // $out = '0' or 'abc', it is a search criteria to keep
1360 $user->lastsearch_values_tmp[$relativepathstring][$paramname] = $out;
1361 }
1362 }
1363 }
1364
1365 if ($paramname == 'hashp' && $out == 'shared') {
1366 $out = ''; // We refuse to have hashp=shared as a parameter
1367 }
1368
1369 return $out;
1370}
1371
1381function sanitizeVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
1382{
1383 // TODO : use class "Validate" to perform tests (and add missing tests) if needed for factorize
1384 // Check is done after replacement
1385 if ($out === null) {
1386 $out = '';
1387 }
1388 switch ($check) {
1389 case 'none':
1390 case 'password':
1391 break;
1392 case 'int': // Check param is a numeric value (integer but also float or hexadecimal)
1393 if (!is_numeric($out)) {
1394 $out = '';
1395 }
1396 break;
1397 case 'intcomma':
1398 if (is_array($out)) {
1399 $out = implode(',', $out);
1400 }
1401 if (preg_match('/[^0-9,-]+/i', $out)) {
1402 $out = '';
1403 }
1404 break;
1405 case 'san_alpha':
1406 dol_syslog("Use of parameter value 'san_alpha' in GETPOST is deprecated. Use 'alphanohtml', 'aZ09comma', ...", LOG_WARNING);
1407 $out = filter_var($out, FILTER_SANITIZE_STRING);
1408 break;
1409 case 'email':
1410 $out = filter_var($out, FILTER_SANITIZE_EMAIL);
1411 break;
1412 case 'url':
1413 //$out = filter_var($out, FILTER_SANITIZE_URL); // Not reliable, replaced with FILTER_VALIDATE_URL
1414 $out = preg_replace('/[^:\/\[\]a-z0-9@\$\'\*\~\.\-_,;\?\!=%&+#]+/i', '', $out);
1415 // TODO Allow ( ) but only into password of https://login:password@domain...
1416 break;
1417 case 'aZ':
1418 if (!is_array($out)) {
1419 $out = trim($out);
1420 if (preg_match('/[^a-z]+/i', $out)) {
1421 $out = '';
1422 }
1423 }
1424 break;
1425 case 'aZ09':
1426 if (!is_array($out)) {
1427 $out = trim($out);
1428 if (preg_match('/[^a-z0-9_\-\.]+/i', $out)) {
1429 $out = '';
1430 }
1431 }
1432 break;
1433 case 'aZ09arobase': // great to sanitize $objecttype parameter
1434 if (!is_array($out)) {
1435 $out = trim($out);
1436 if (preg_match('/[^a-z0-9_\-\.@]+/i', $out)) {
1437 $out = '';
1438 }
1439 }
1440 break;
1441 case 'aZ09comma': // great to sanitize $sortfield or $sortorder params that can be 't.abc,t.def_gh'
1442 if (!is_array($out)) {
1443 $out = trim($out);
1444 if (preg_match('/[^a-z0-9_\-\.,]+/i', $out)) {
1445 $out = '';
1446 }
1447 }
1448 break;
1449 case 'alpha': // No html and no ../ and "
1450 case 'alphanohtml': // Recommended for most scalar parameters and search parameters. Not valid for json string.
1451 if (!is_array($out)) {
1452 $out = trim($out);
1453 do {
1454 $oldstringtoclean = $out;
1455 // Remove html tags
1456 $out = dol_string_nohtmltag($out, 0);
1457 // 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).
1458 $out = preg_replace('/\\\‍([0-9xu])/', '/\1', $out);
1459 // Remove also other dangerous string sequences
1460 // '../' or '..\' is dangerous because it allows dir transversals
1461 // '&#38', '&#0000038', '&#x26'... is a the char '&' alone but there is no reason to accept such way to encode input char
1462 // '"' = '&#34' = '&#0000034' = '&#x22' is dangerous because param in url can close the href= or src= and add javascript functions.
1463 // '&#47', '&#0000047', '&#x2F' is the char '/' but there is no reason to accept such way to encode this input char
1464 // '&#92' = '&#0000092' = '&#x5C' is the char '\' but there is no reason to accept such way to encode this input char
1465 $out = str_ireplace(array('../', '..\\', '&#38', '&#0000038', '&#x26', '&quot', '"', '&#34', '&#0000034', '&#x22', '&#47', '&#0000047', '&#x2F', '&#92', '&#0000092', '&#x5C'), '', $out);
1466 } while ($oldstringtoclean != $out);
1467 // keep lines feed
1468 }
1469 break;
1470 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'
1471 if (!is_array($out)) {
1472 $out = trim($out);
1473 do {
1474 $oldstringtoclean = $out;
1475 // Decode html entities
1476 $out = dol_html_entity_decode($out, ENT_COMPAT | ENT_HTML5, 'UTF-8');
1477 // 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).
1478 $out = preg_replace('/\\\‍([0-9xu])/', '/\1', $out);
1479 // Remove also other dangerous string sequences
1480 // '../' or '..\' is dangerous because it allows dir transversals
1481 // '&#38', '&#0000038', '&#x26'... is a the char '&' alone but there is no reason to accept such way to encode input char
1482 // '"' = '&#34' = '&#0000034' = '&#x22' is dangerous because param in url can close the href= or src= and add javascript functions.
1483 // '&#47', '&#0000047', '&#x2F' is the char '/' but there is no reason to accept such way to encode this input char
1484 // '&#92' = '&#0000092' = '&#x5C' is the char '\' but there is no reason to accept such way to encode this input char
1485 $out = str_ireplace(array('../', '..\\', '&#38', '&#0000038', '&#x26', '&quot', '"', '&#34', '&#0000034', '&#x22', '&#47', '&#0000047', '&#x2F', '&#92', '&#0000092', '&#x5C'), '', $out);
1486 } while ($oldstringtoclean != $out);
1487 }
1488 break;
1489 case 'nohtml': // No html. Valid for JSON strings.
1490 $out = dol_string_nohtmltag($out, 0);
1491 break;
1492 case 'restricthtmlnolink':
1493 case 'restricthtml': // Recommended for most html textarea
1494 case 'restricthtmlallowclass':
1495 case 'restricthtmlallowiframe':
1496 case 'restricthtmlallowlinkscript': // Allow link and script tag for head section.
1497 case 'restricthtmlallowunvalid':
1498 $out = dol_htmlwithnojs($out, 1, $check);
1499 break;
1500 case 'custom':
1501 if (!empty($out)) {
1502 if (empty($filter)) {
1503 return 'BadParameterForGETPOST - Param 3 of sanitizeVal()';
1504 }
1505 if (is_null($options)) {
1506 $options = 0;
1507 }
1508 $out = filter_var($out, $filter, $options);
1509 }
1510 break;
1511 default:
1512 dol_syslog("Error, you call sanitizeVal() with a bad value for the check type. Data will be sanitized with alphanohtml.", LOG_ERR);
1513 $out = GETPOST($out, 'alphanohtml');
1514 break;
1515 }
1516
1517 return $out;
1518}
1519
1528function dolSetCookie(string $cookiename, string $cookievalue, int $expire = -1)
1529{
1530 global $dolibarr_main_force_https;
1531
1532 if ($expire == -1) {
1533 $expire = (time() + (86400 * 354)); // keep cookie 1 year.
1534 }
1535
1536 if (PHP_VERSION_ID < 70300) {
1537 setcookie($cookiename, empty($cookievalue) ? '' : $cookievalue, empty($cookievalue) ? 0 : $expire, '/', '', !(empty($dolibarr_main_force_https) && isHTTPS() === false), true); // add tag httponly
1538 } else {
1539 // Only available for php >= 7.3
1540 $cookieparams = array(
1541 'expires' => empty($cookievalue) ? 0 : $expire,
1542 'path' => '/',
1543 //'domain' => '.mywebsite.com', // the dot at the beginning allows compatibility with subdomains
1544 'secure' => !(empty($dolibarr_main_force_https) && isHTTPS() === false),
1545 'httponly' => true,
1546 'samesite' => 'Lax' // None || Lax || Strict
1547 );
1548 setcookie($cookiename, empty($cookievalue) ? '' : $cookievalue, $cookieparams);
1549 }
1550 if (empty($cookievalue)) {
1551 unset($_COOKIE[$cookiename]);
1552 }
1553}
1554
1555if (!function_exists('dol_getprefix')) {
1566 function dol_getprefix($mode = '')
1567 {
1568 // If prefix is for email (we need to have $conf already loaded for this case)
1569 if ($mode == 'email') {
1570 global $conf;
1571
1572 if (getDolGlobalString('MAIL_PREFIX_FOR_EMAIL_ID')) { // If MAIL_PREFIX_FOR_EMAIL_ID is set
1573 if (getDolGlobalString('MAIL_PREFIX_FOR_EMAIL_ID') != 'SERVER_NAME') {
1574 return getDolGlobalString('MAIL_PREFIX_FOR_EMAIL_ID');
1575 } elseif (isset($_SERVER["SERVER_NAME"])) { // If MAIL_PREFIX_FOR_EMAIL_ID is set to 'SERVER_NAME'
1576 return $_SERVER["SERVER_NAME"];
1577 }
1578 }
1579
1580 // The recommended value if MAIL_PREFIX_FOR_EMAIL_ID is not defined (may be not defined for old versions)
1581 if (!empty($conf->file->instance_unique_id)) {
1582 return sha1('dolibarr' . $conf->file->instance_unique_id);
1583 }
1584
1585 // For backward compatibility when instance_unique_id is not set
1586 return sha1(DOL_DOCUMENT_ROOT . DOL_URL_ROOT);
1587 }
1588
1589 // If prefix is for session (no need to have $conf loaded)
1590 global $dolibarr_main_instance_unique_id, $dolibarr_main_cookie_cryptkey; // This is loaded by filefunc.inc.php
1591 $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
1592
1593 // The recommended value (may be not defined for old versions)
1594 if (!empty($tmp_instance_unique_id)) {
1595 return sha1('dolibarr' . $tmp_instance_unique_id);
1596 }
1597
1598 // For backward compatibility when instance_unique_id is not set
1599 if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"])) {
1600 return sha1($_SERVER["SERVER_NAME"] . $_SERVER["DOCUMENT_ROOT"] . DOL_DOCUMENT_ROOT . DOL_URL_ROOT);
1601 } else {
1602 return sha1(DOL_DOCUMENT_ROOT . DOL_URL_ROOT);
1603 }
1604 }
1605}
1606
1617function dol_include_once($relpath, $classname = '')
1618{
1619 global $conf, $langs, $user, $mysoc; // Do not remove this. They must be defined for files we make "include". Other globals var must be retrieved with $GLOBALS['var']
1620
1621 if (strpos($relpath, '..') !== false) {
1622 // Found a not valid path
1623 dol_syslog('functions::dol_include_once Tried to load a file with a path including a forbidden sequence ".." : ' . $relpath, LOG_WARNING);
1624 return false;
1625 }
1626 if (!preg_match('/\.php$/', $relpath)) {
1627 // Found a not valid path
1628 dol_syslog('functions::dol_include_once Tried to load a file that is not a PHP file : ' . $relpath, LOG_WARNING);
1629 return false;
1630 }
1631
1632 $fullpath = dol_buildpath($relpath);
1633
1634 if (!file_exists($fullpath)) {
1635 dol_syslog('functions::dol_include_once Tried to load unexisting file: ' . $relpath, LOG_WARNING);
1636 return false;
1637 }
1638 if (!empty($classname) && !class_exists($classname)) {
1639 return include $fullpath;
1640 } else {
1641 return include_once $fullpath;
1642 }
1643}
1644
1645
1659function dol_buildpath($path, $type = 0, $returnemptyifnotfound = 0)
1660{
1661 global $conf;
1662
1663 $path = preg_replace('/^\//', '', $path);
1664
1665 if (empty($type)) { // For a filesystem path
1666 $res = DOL_DOCUMENT_ROOT . '/' . $path; // Standard default path
1667 if (is_array($conf->file->dol_document_root)) {
1668 foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array("main"=>"/home/main/htdocs", "alt0"=>"/home/dirmod/htdocs", ...)
1669 if ($key == 'main') {
1670 continue;
1671 }
1672 // if (@file_exists($dirroot.'/'.$path)) {
1673 if (@file_exists($dirroot . '/' . $path)) { // avoid [php:warn]
1674 if ($key != 'main' && preg_match('/^core\//', $path)) { // When searching into an alternative custom path, we don't want path like 'core/...' because path should be 'modulename/core/...'
1675 continue;
1676 }
1677 $res = $dirroot . '/' . $path;
1678 return $res;
1679 }
1680 }
1681 }
1682 if ($returnemptyifnotfound) {
1683 // Not found into alternate dir
1684 if ($returnemptyifnotfound == 1 || !file_exists($res)) {
1685 return '';
1686 }
1687 }
1688 } else {
1689 // For an url path
1690 // We try to get local path of file on filesystem from url
1691 // Note that trying to know if a file on disk exist by forging path on disk from url
1692 // works only for some web server and some setup. This is bugged when
1693 // using proxy, rewriting, virtual path, etc...
1694 $res = '';
1695 if ($type == 1) {
1696 $res = DOL_URL_ROOT . '/' . $path; // Standard value
1697 }
1698 if ($type == 2) {
1699 $res = DOL_MAIN_URL_ROOT . '/' . $path; // Standard value
1700 }
1701 if ($type == 3) {
1702 $res = DOL_URL_ROOT . '/' . $path;
1703 }
1704
1705 foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
1706 if ($key == 'main') {
1707 if ($type == 3) {
1708 /*global $dolibarr_main_url_root;*/
1709
1710 // Define $urlwithroot
1711 $urlwithouturlroot = preg_replace('/' . preg_quote(DOL_URL_ROOT, '/') . '$/i', '', trim($conf->file->dol_main_url_root));
1712 $urlwithroot = $urlwithouturlroot . DOL_URL_ROOT; // This is to use external domain name found into config file
1713 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
1714
1715 $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : $urlwithroot) . '/' . $path; // Test on start with http is for old conf syntax
1716 }
1717 continue;
1718 }
1719 $regs = array();
1720 preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i', $path, $regs); // Take part before '?'
1721 if (!empty($regs[1])) {
1722 //print $key.'-'.$dirroot.'/'.$path.'-'.$conf->file->dol_url_root[$type].'<br>'."\n";
1723 //if (file_exists($dirroot.'/'.$regs[1])) {
1724 if (@file_exists($dirroot . '/' . $regs[1])) { // avoid [php:warn]
1725 if ($type == 1) {
1726 $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_URL_ROOT) . $conf->file->dol_url_root[$key] . '/' . $path;
1727 } elseif ($type == 2) {
1728 $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_MAIN_URL_ROOT) . $conf->file->dol_url_root[$key] . '/' . $path;
1729 } elseif ($type == 3) {
1730 /*global $dolibarr_main_url_root;*/
1731
1732 // Define $urlwithroot
1733 $urlwithouturlroot = preg_replace('/' . preg_quote(DOL_URL_ROOT, '/') . '$/i', '', trim($conf->file->dol_main_url_root));
1734 $urlwithroot = $urlwithouturlroot . DOL_URL_ROOT; // This is to use external domain name found into config file
1735 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
1736
1737 $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
1738 }
1739 break;
1740 }
1741 }
1742 }
1743 }
1744
1745 return $res;
1746}
1747
1756function dolBuildUrl($url, $params = [], $addtoken = false)
1757{
1758 global $db, $hookmanager;
1759
1760 if (!is_object($hookmanager)) {
1761 include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
1762 $hookmanager = new HookManager($db);
1763 }
1764 if ((!isset($params['mainmenu']) || empty($params['mainmenu'])) && GETPOSTISSET('mainmenu')) {
1765 $params = array_merge($params, ['mainmenu' => (GETPOST('mainmenu', 'restricthtml'))]);
1766 }
1767 if ((!isset($params['leftmenu'])/* || empty($params['leftmenu']) */) && GETPOSTISSET('leftmenu')) { // do not fill leftmenu if we have leftmenu=
1768 $params = array_merge($params, ['leftmenu' => (GETPOST('leftmenu', 'restricthtml'))]);
1769 }
1770 $parameters = [
1771 'path' => &$url,
1772 'params' => &$params,
1773 'addtoken' => &$addtoken,
1774 ];
1775 $hookmanager->executeHooks('buildurl', $parameters);
1776 if ($addtoken) {
1777 $params = array_merge($params, ['token' => newToken()]);
1778 }
1779 // TODO TO REMOVE
1780 if (getDolGlobalString('MAIN_DEBUG_DOL_BUILDURL')) {
1781 $params = array_merge($params, ['debug' => 'debug']);
1782 }
1783 if ($params) {
1784 $url .= '?' . http_build_query($params);
1785 }
1786
1787 return $url;
1788}
1789
1800function dol_get_object_properties($obj, $properties = [])
1801{
1802 // Get real properties using get_object_vars() if $properties is empty
1803 if (empty($properties)) {
1804 return get_object_vars($obj);
1805 }
1806
1807 $existingProperties = [];
1808 $realProperties = get_object_vars($obj);
1809
1810 // Get the real or magic property values
1811 foreach ($properties as $property) {
1812 if (array_key_exists($property, $realProperties)) {
1813 // Real property, add the value
1814 $existingProperties[$property] = $obj->{$property};
1815 } elseif (property_exists($obj, $property)) {
1816 // Magic property
1817 $existingProperties[$property] = $obj->{$property};
1818 }
1819 }
1820
1821 return $existingProperties;
1822}
1823
1824
1840function dol_clone($srcobject, $native = 2)
1841{
1842 if ($native == 0) {
1843 // deprecated method, use the method with native = 2 instead
1844 dol_syslog("Warning, call to dol_clone() with the deprecated parameter native=0, use 2 instead", LOG_WARNING);
1845
1846 $tmpsavdb = null;
1847 if (isset($srcobject->db) && isset($srcobject->db->db) && is_object($srcobject->db->db) && get_class($srcobject->db->db) == 'PgSql\Connection') {
1848 $tmpsavdb = $srcobject->db;
1849 unset($srcobject->db); // Such property can not be serialized with pgsl (when object->db->db = 'PgSql\Connection')
1850 }
1851
1852 $myclone = unserialize(serialize($srcobject)); // serialize then unserialize is a hack to be sure to have a new object for all fields
1853
1854 if (!empty($tmpsavdb)) {
1855 $srcobject->db = $tmpsavdb;
1856 }
1857 } elseif ($native == 2) {
1858 // recommended method to have a full secured isolated cloned object
1859 $myclone = new stdClass();
1860 $tmparray = get_object_vars($srcobject); // return only public properties
1861
1862 if (is_array($tmparray)) {
1863 foreach ($tmparray as $propertykey => $propertyval) {
1864 if (is_scalar($propertyval) || is_array($propertyval)) {
1865 $myclone->$propertykey = $propertyval;
1866 }
1867 }
1868 }
1869 } else {
1870 $myclone = clone $srcobject; // 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)
1871 }
1872
1873 return $myclone;
1874}
1875
1876
1885function dol_clone_in_array($srcobject, $startlevel = 0)
1886{
1887 if (is_object($srcobject)) {
1888 $srcobject = get_object_vars($srcobject); // exclude private/protected properties
1889 }
1890
1891 if (is_array($srcobject)) {
1892 $result = [];
1893 foreach ($srcobject as $key => $value) {
1894 if (in_array($key, array('db', 'fields', 'error', 'errorhidden', 'errors', 'oldcopy', 'linkedObjects', 'linked_objects'))) {
1895 continue;
1896 }
1897 $result[$key] = dol_clone_in_array($value, $startlevel + 1);
1898 }
1899 return $result;
1900 }
1901
1902 return $srcobject;
1903}
1904
1905
1915function dol_size($size, $type = '')
1916{
1917 global $conf;
1918 if (empty($conf->dol_optimize_smallscreen)) {
1919 return $size;
1920 }
1921 if ($type == 'width' && $size > 250) {
1922 return 250;
1923 } else {
1924 return 10;
1925 }
1926}
1927
1928
1942function dol_sanitizeFileName($str, $newstr = '_', $unaccent = 1, $includequotes = 0, $allowdash = 0)
1943{
1944 // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
1945 // Char '>' '<' '|' '$' and ';' are special chars for shells.
1946 // Char '/' and '\' are file delimiters.
1947 // 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
1948 $filesystem_forbidden_chars = array('<', '>', '/', '\\', '?', '*', '|', '"', ':', '°', '$', ';', '`');
1949 if ($includequotes) {
1950 $filesystem_forbidden_chars[] = "'";
1951 }
1952 $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
1953 $tmp = preg_replace('/\-\-+/', '_', $tmp);
1954 if (empty($allowdash)) {
1955 $tmp = preg_replace('/\s+\-([^\s])/', ' _$1', $tmp);
1956 $tmp = preg_replace('/\s+\-$/', '', $tmp);
1957 }
1958 $tmp = str_replace('..', '', $tmp);
1959 $tmp = str_replace('~', $newstr, $tmp);
1960 $tmp = preg_replace('/\s{2,}/', ' ', $tmp);
1961
1962 return $tmp;
1963}
1964
1965
1978function dol_sanitizePathName($str, $newstr = '_', $unaccent = 0, $allowdash = 0)
1979{
1980 // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
1981 // Char '>' '<' '|' '$' ';' and '`' are special chars for shells.
1982 // Char '?' and '*' are for wild card chars.
1983 // Char '"' is dangerous.
1984 // Char '°' is just not expected.
1985 // Chars '-' and '--' 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
1986 // Chars '--' and '~' can be used for path transversal
1987 $filesystem_forbidden_chars = array('<', '>', '?', '*', '|', '"', '°', '$', ';', '`');
1988
1989 $tmp = $str;
1990 if ($unaccent) {
1991 $tmp = dol_string_unaccent($tmp);
1992 }
1993 $tmp = dol_string_nospecial($tmp, $newstr, $filesystem_forbidden_chars);
1994 $tmp = preg_replace('/\-\-+/', $newstr, $tmp);
1995 if (empty($allowdash)) {
1996 $tmp = preg_replace('/\s+\-([^\s])/', ' '.$newstr.'$1', $tmp);
1997 $tmp = preg_replace('/\s+\-$/', '', $tmp);
1998 }
1999 $tmp = str_replace('..', $newstr, $tmp);
2000 $tmp = str_replace('~', $newstr, $tmp);
2001 $tmp = preg_replace('/\s{2,}/', ' ', $tmp);
2002
2003 return $tmp;
2004}
2005
2013function dol_sanitizeUrl($stringtoclean, $type = 1)
2014{
2015 // 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)
2016 // We should use dol_string_nounprintableascii but function may not be yet loaded/available
2017 $stringtoclean = preg_replace('/[\x00-\x1F\x7F]/u', '', $stringtoclean); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
2018 // We clean html comments because some hacks try to obfuscate evil strings by inserting HTML comments. Example: on<!-- -->error=alert(1)
2019 $stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
2020
2021 $stringtoclean = str_replace('\\', '/', $stringtoclean);
2022 if ($type == 1) {
2023 // removing : should disable links to external url like http:aaa)
2024 // removing ';' should disable "named" html entities encode into an url (we should not have this into an url)
2025 $stringtoclean = str_replace(array(':', ';', '@'), '', $stringtoclean);
2026 }
2027
2028 do {
2029 $oldstringtoclean = $stringtoclean;
2030 // removing '&colon' should disable links to external url like http:aaa)
2031 // removing '&#' should disable "numeric" html entities encode into an url (we should not have this into an url)
2032 $stringtoclean = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $stringtoclean);
2033 } while ($oldstringtoclean != $stringtoclean);
2034
2035 if ($type == 1) {
2036 // removing '//' should disable links to external url like //aaa or http//)
2037 $stringtoclean = preg_replace(array('/^[a-z]*\/\/+/i'), '', $stringtoclean);
2038 }
2039
2040 return $stringtoclean;
2041}
2042
2049function dol_sanitizeEmail($stringtoclean)
2050{
2051 do {
2052 $oldstringtoclean = $stringtoclean;
2053 $stringtoclean = str_ireplace(array('"', ':', '[', ']', "\n", "\r", '\\', '\/'), '', $stringtoclean);
2054 } while ($oldstringtoclean != $stringtoclean);
2055
2056 return $stringtoclean;
2057}
2058
2067function dol_sanitizeKeyCode($str)
2068{
2069 return preg_replace('/[^\w]+/', '', $str);
2070}
2071
2072
2081function dol_string_unaccent($str)
2082{
2083 if (is_null($str)) {
2084 return '';
2085 }
2086
2087 if (utf8_check($str)) {
2088 if (extension_loaded('intl') && getDolGlobalString('MAIN_UNACCENT_USE_TRANSLITERATOR')) {
2089 $transliterator = Transliterator::createFromRules(':: Any-Latin; :: Latin-ASCII; :: NFD; :: [:Nonspacing Mark:] Remove; :: NFC;', Transliterator::FORWARD);
2090 return $transliterator->transliterate($str);
2091 }
2092 // See http://www.utf8-chartable.de/
2093 $string = rawurlencode($str);
2094 $replacements = array(
2095 '%C3%80' => 'A', '%C3%81' => 'A', '%C3%82' => 'A', '%C3%83' => 'A', '%C3%84' => 'A', '%C3%85' => 'A',
2096 '%C3%87' => 'C',
2097 '%C3%88' => 'E', '%C3%89' => 'E', '%C3%8A' => 'E', '%C3%8B' => 'E',
2098 '%C3%8C' => 'I', '%C3%8D' => 'I', '%C3%8E' => 'I', '%C3%8F' => 'I',
2099 '%C3%91' => 'N',
2100 '%C3%92' => 'O', '%C3%93' => 'O', '%C3%94' => 'O', '%C3%95' => 'O', '%C3%96' => 'O', '%C5%90' => 'O',
2101 '%C5%A0' => 'S',
2102 '%C3%99' => 'U', '%C3%9A' => 'U', '%C3%9B' => 'U', '%C3%9C' => 'U', '%C5%B0' => 'U',
2103 '%C3%9D' => 'Y', '%C5%B8' => 'y',
2104 '%C3%A0' => 'a', '%C3%A1' => 'a', '%C3%A2' => 'a', '%C3%A3' => 'a', '%C3%A4' => 'a', '%C3%A5' => 'a',
2105 '%C3%A7' => 'c',
2106 '%C3%A8' => 'e', '%C3%A9' => 'e', '%C3%AA' => 'e', '%C3%AB' => 'e',
2107 '%C3%AC' => 'i', '%C3%AD' => 'i', '%C3%AE' => 'i', '%C3%AF' => 'i',
2108 '%C3%B1' => 'n',
2109 '%C3%B2' => 'o', '%C3%B3' => 'o', '%C3%B4' => 'o', '%C3%B5' => 'o', '%C3%B6' => 'o', '%C5%91' => 'o',
2110 '%C5%A1' => 's',
2111 '%C3%B9' => 'u', '%C3%BA' => 'u', '%C3%BB' => 'u', '%C3%BC' => 'u', '%C5%B1' => 'u',
2112 '%C3%BD' => 'y', '%C3%BF' => 'y',
2113 '%CC%80' => '',
2114 '%CC%81' => '',
2115 '%CC%82' => '',
2116 '%CC%83' => '',
2117 '%CC%84' => '',
2118 '%CC%85' => '',
2119 '%CC%86' => '',
2120 '%CC%87' => '',
2121 '%CC%88' => '',
2122 '%CC%89' => '',
2123 '%CC%8A' => '',
2124 '%CC%8B' => '',
2125 '%CC%8C' => '',
2126 '%CC%8D' => '',
2127 '%CC%8E' => '',
2128 '%CC%8F' => '',
2129 '%CC%90' => '',
2130 '%CC%91' => '',
2131 '%CC%A7' => ''
2132 );
2133 $string = strtr($string, $replacements);
2134 return rawurldecode($string);
2135 } else {
2136 // See http://www.ascii-code.com/
2137 $string = strtr(
2138 $str,
2139 "\xC0\xC1\xC2\xC3\xC4\xC5\xC7
2140 \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
2141 \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
2142 \xE0\xE1\xE2\xE3\xE4\xE5\xE7\xE8\xE9\xEA\xEB
2143 \xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
2144 \xF9\xFA\xFB\xFC\xFD\xFF",
2145 "AAAAAAC
2146 EEEEIIIIDN
2147 OOOOOUUUY
2148 aaaaaaceeee
2149 iiiidnooooo
2150 uuuuyy"
2151 );
2152 $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"));
2153 return $string;
2154 }
2155}
2156
2170function dol_string_nospecial($str, $newstr = '_', $badcharstoreplace = '', $badcharstoremove = '', $keepspaces = 0)
2171{
2172 $forbidden_chars_to_replace = array("'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°', '$', ';'); // more complete than dol_sanitizeFileName
2173 if (empty($keepspaces)) {
2174 $forbidden_chars_to_replace[] = " ";
2175 }
2176 $forbidden_chars_to_remove = array();
2177 //$forbidden_chars_to_remove=array("(",")");
2178
2179 if (is_array($badcharstoreplace)) {
2180 $forbidden_chars_to_replace = $badcharstoreplace;
2181 }
2182 if (is_array($badcharstoremove)) {
2183 $forbidden_chars_to_remove = $badcharstoremove;
2184 }
2185
2186 // @phan-suppress-next-line PhanPluginSuspiciousParamOrderInternal
2187 return str_replace($forbidden_chars_to_replace, $newstr, str_replace($forbidden_chars_to_remove, "", $str));
2188}
2189
2190
2204function dol_string_nounprintableascii($str, $removetabcrlf = 1)
2205{
2206 if ($removetabcrlf) {
2207 return preg_replace('/[\x00-\x1F\x7F]/u', '', $str); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
2208 } else {
2209 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
2210 }
2211}
2212
2219function dolSlugify($stringtoslugify)
2220{
2221 $slug = dol_string_unaccent($stringtoslugify);
2222
2223 // Convert special characters to their ASCII equivalents
2224 if (function_exists('iconv')) {
2225 $slug = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $slug);
2226 }
2227
2228 // Convert to lowercase
2229 $slug = strtolower($slug);
2230
2231 // Replace non-alphanumeric characters with hyphens
2232 $slug = preg_replace('/[^a-z0-9]+/', '-', $slug);
2233
2234 // Remove leading and trailing hyphens
2235 $slug = trim($slug, '-');
2236
2237 return $slug;
2238}
2239
2248function dol_escape_js($stringtoescape, $mode = 0, $noescapebackslashn = 0)
2249{
2250 if (is_null($stringtoescape)) {
2251 return '';
2252 }
2253
2254 // escape quotes and backslashes, newlines, etc.
2255 $substitjs = array("&#039;" => "\\'", "\r" => '\\r');
2256 //$substitjs['</']='<\/'; // We removed this. Should be useless.
2257 if (empty($noescapebackslashn)) {
2258 $substitjs["\n"] = '\\n';
2259 $substitjs['\\'] = '\\\\';
2260 }
2261 if (empty($mode)) {
2262 $substitjs["'"] = "\\'";
2263 $substitjs['"'] = "\\'";
2264 } elseif ($mode == 1) {
2265 $substitjs["'"] = "\\'";
2266 } elseif ($mode == 2) {
2267 $substitjs['"'] = '\\"';
2268 } elseif ($mode == 3) {
2269 $substitjs["'"] = "\\'";
2270 $substitjs['"'] = "\\\"";
2271 }
2272 return strtr((string) $stringtoescape, $substitjs);
2273}
2274
2284function dol_escape_uri($stringtoescape)
2285{
2286 return rawurlencode($stringtoescape);
2287}
2288
2295function dol_escape_json($stringtoescape)
2296{
2297 return str_replace('"', '\"', $stringtoescape);
2298}
2299
2307function dol_escape_php($stringtoescape, $stringforquotes = 2)
2308{
2309 if (is_null($stringtoescape)) {
2310 return '';
2311 }
2312
2313 if ($stringforquotes == 2) {
2314 return str_replace('"', "'", $stringtoescape);
2315 } elseif ($stringforquotes == 1) {
2316 // We remove the \ char.
2317 // If we allow the \ char, we can have $stringtoescape =
2318 // abc\';phpcodedanger; so the escapement will become
2319 // abc\\';phpcodedanger; and injecting this into
2320 // $a='...' will give $ac='abc\\';phpcodedanger;
2321 $stringtoescape = str_replace('\\', '', $stringtoescape);
2322 return str_replace("'", "\'", str_replace('"', "'", $stringtoescape));
2323 }
2324
2325 return 'Bad parameter for stringforquotes in dol_escape_php';
2326}
2327
2334function dol_escape_all($stringtoescape)
2335{
2336 return preg_replace('/[^a-z0-9_]/i', '', $stringtoescape);
2337}
2338
2345function dol_escape_xml($stringtoescape)
2346{
2347 $stringtoescape = (string) preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', '', (string) $stringtoescape); // Characters not allowed in XML 1.0
2348
2349 return htmlspecialchars($stringtoescape, ENT_XML1 | ENT_QUOTES, 'UTF-8');
2350}
2351
2361function dolPrintLabel($s, $escapeonlyhtmltags = 0)
2362{
2363 return dol_escape_htmltag(dol_string_nohtmltag($s, 1, 'UTF-8', 0, 0), 0, 0, '', $escapeonlyhtmltags, 1);
2364}
2365
2374function dolPrintText($s)
2375{
2376 return dol_escape_htmltag(dol_string_nohtmltag($s, 2, 'UTF-8', 0, 0), 0, 1, '', 0, 1);
2377}
2378
2389function dolPrintHTML($s, $allowiframe = 0)
2390{
2391 // If text is already HTML, we want to escape only dangerous chars else we want to escape all content.
2392 //$isAlreadyHTML = dol_textishtml($s);
2393
2394 // dol_htmlentitiesbr encode all chars except "'" if string is not already HTML, but
2395 // encode only special char like é but not &, <, >, ", ' if already HTML.
2396 $stringWithEntitesForSpecialChar = dol_htmlentitiesbr((string) $s);
2397
2398 return dol_escape_htmltag(dol_htmlwithnojs(dol_string_onlythesehtmltags($stringWithEntitesForSpecialChar, 1, 1, 1, $allowiframe)), 1, 1, 'common', 0, 1);
2399}
2400
2411function dolPrintHTMLForAttribute($s, $escapeonlyhtmltags = 0, $allowothertags = array())
2412{
2413 $allowedtags = array('br', 'b', 'font', 'hr', 'span');
2414 if (!empty($allowothertags) && is_array($allowothertags)) {
2415 $allowedtags = array_merge($allowedtags, $allowothertags);
2416 }
2417 // The dol_htmlentitiesbr will convert simple text into html, including switching accent into HTML entities
2418 // The dol_escape_htmltag will escape html tags.
2419 if ($escapeonlyhtmltags) {
2420 return dol_escape_htmltag(dol_string_onlythesehtmltags($s, 1, 0, 0, 0, $allowedtags), 1, -1, '', 1, 1);
2421 } else {
2422 return dol_escape_htmltag(dol_string_onlythesehtmltags(dol_htmlentitiesbr($s), 1, 0, 0, 0, $allowedtags), 1, -1, '', 0, 1);
2423 }
2424}
2425
2434function dolPrintHTMLForAttributeUrl($s)
2435{
2436 // 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)
2437 // The dol_escape_htmltag will escape html chars.
2438 $escapeonlyhtmltags = 1;
2439 return dol_escape_htmltag(dol_string_onlythesehtmltags($s, 1, 1, 1, 0, array()), 0, 0, '', $escapeonlyhtmltags, 1);
2440}
2441
2451function dolPrintHTMLForTextArea($s, $allowiframe = 0)
2452{
2453 return dol_escape_htmltag(dol_htmlwithnojs(dol_string_onlythesehtmltags(dol_htmlentitiesbr($s), 1, 1, 1, $allowiframe)), 1, 1, '', 0, 1);
2454}
2455
2462function dolPrintPassword($s)
2463{
2464 return htmlspecialchars($s, ENT_HTML5, 'UTF-8');
2465}
2466
2467
2484function dol_escape_htmltag($stringtoescape, $keepb = 0, $keepn = 0, $noescapetags = '', $escapeonlyhtmltags = 0, $cleanalsojavascript = 0)
2485{
2486 if ($noescapetags == 'common') {
2487 $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';
2488 // Add also html5 tags
2489 $noescapetags .= ',header,footer,nav,section,menu,menuitem';
2490 }
2491 if ($cleanalsojavascript) {
2492 $stringtoescape = dol_string_onlythesehtmltags($stringtoescape, 0, 0, $cleanalsojavascript, 0, array(), 0);
2493 }
2494
2495 // escape quotes and backslashes, newlines, etc.
2496 if ($escapeonlyhtmltags) {
2497 $tmp = htmlspecialchars_decode((string) $stringtoescape, ENT_COMPAT);
2498 } else {
2499 // We make a manipulation by calling the html_entity_decode() to convert content into NON HTML UTF8 string.
2500 // Because content can be or not already HTML.
2501 // For example, this decode &egrave; into è so string is UTF8 (but numbers entities like &#39; is not decoded).
2502 // In a future, we should not need this
2503
2504 $tmp = (string) $stringtoescape;
2505
2506 // We protect the 6 special entities that we don't want to decode.
2507 $tmp = str_ireplace('&lt', '__DONOTDECODELT', $tmp);
2508 $tmp = str_ireplace('&gt', '__DONOTDECODEGT', $tmp);
2509 $tmp = str_ireplace('&amp', '__DONOTDECODEAMP', $tmp);
2510 $tmp = str_ireplace('&quot', '__DONOTDECODEQUOT', $tmp);
2511 $tmp = str_ireplace('&apos', '__DONOTDECODEAPOS', $tmp);
2512 $tmp = str_ireplace('&#39', '__DONOTDECODE39', $tmp);
2513
2514 $tmp = html_entity_decode((string) $tmp, ENT_COMPAT, 'UTF-8'); // Convert entities into UTF8
2515
2516 // We restore the 6 special entities that we don't want to have been decoded by previous command
2517 $tmp = str_ireplace('__DONOTDECODELT', '&lt', $tmp);
2518 $tmp = str_ireplace('__DONOTDECODEGT', '&gt', $tmp);
2519 $tmp = str_ireplace('__DONOTDECODEAMP', '&amp', $tmp);
2520 $tmp = str_ireplace('__DONOTDECODEQUOT', '&quot', $tmp);
2521 $tmp = str_ireplace('__DONOTDECODEAPOS', '&apos', $tmp);
2522 $tmp = str_ireplace('__DONOTDECODE39', '&#39', $tmp);
2523
2524 $tmp = str_ireplace('&#39;', '__SIMPLEQUOTE__', $tmp); // HTML 4
2525 }
2526 if (!$keepb) {
2527 $tmp = strtr($tmp, array("<b>" => '', '</b>' => '', '<strong>' => '', '</strong>' => ''));
2528 }
2529 if (!$keepn) {
2530 $tmp = strtr($tmp, array("\r" => '\\r', "\n" => '\\n'));
2531 } elseif ($keepn == -1) {
2532 $tmp = strtr($tmp, array("\r" => '', "\n" => ''));
2533 }
2534
2535 if ($escapeonlyhtmltags) {
2536 $tmp = htmlspecialchars($tmp, ENT_COMPAT, 'UTF-8');
2537 return $tmp;
2538 } else {
2539 // Now we protect all the tags we want to keep
2540 $tmparrayoftags = array();
2541 if ($noescapetags) {
2542 $tmparrayoftags = explode(',', $noescapetags);
2543 }
2544
2545 if (count($tmparrayoftags)) {
2546 // Now we will protect tags (defined into $tmparrayoftags) that we want to keep untouched
2547
2548 $reg = array();
2549 // Remove reserved keywords. They are forbidden in a source string
2550 $tmp = str_ireplace(array('__DOUBLEQUOTE', '__BEGINTAGTOREPLACE', '__ENDTAGTOREPLACE', '__BEGINENDTAGTOREPLACE'), '', $tmp);
2551
2552 foreach ($tmparrayoftags as $tagtoreplace) {
2553 // For case of tag without attributes '<abc>', '</abc>', '<abc />', we protect them to avoid transformation by htmlentities() later
2554 $tmp = preg_replace('/<' . preg_quote($tagtoreplace, '/') . '>/', '__BEGINTAGTOREPLACE' . $tagtoreplace . '__', $tmp);
2555 $tmp = str_ireplace('</' . $tagtoreplace . '>', '__ENDTAGTOREPLACE' . $tagtoreplace . '__', $tmp);
2556 $tmp = preg_replace('/<' . preg_quote($tagtoreplace, '/') . ' \/>/', '__BEGINENDTAGTOREPLACE' . $tagtoreplace . '__', $tmp);
2557
2558 // For case of tag with attributes
2559 do {
2560 $tmpold = $tmp;
2561
2562 if (preg_match('/<' . preg_quote($tagtoreplace, '/') . '(\s+)([^>]+)>/', $tmp, $reg)) {
2563 // We want to protect the attribute part ... in '<xxx ...>' to avoid transformation by htmlentities() later
2564 $tmpattributes = str_ireplace(array('[', ']'), '_', $reg[2]); // We must never have [ ] inside the attribute string
2565 $tmpattributes = str_ireplace('"', '__DOUBLEQUOTE__', $tmpattributes);
2566 $tmpattributes = preg_replace('/[^a-z0-9_%,\/\?\;\s=&\.\-@:\.#\+]/i', '', $tmpattributes);
2567 //$tmpattributes = preg_replace("/float:\s*(left|right)/", "", $tmpattributes); // Disabled: we must not remove content
2568 $tmp = str_replace('<' . $tagtoreplace . $reg[1] . $reg[2] . '>', '__BEGINTAGTOREPLACE' . $tagtoreplace . '[' . $tmpattributes . ']__', $tmp);
2569 }
2570
2571 $diff = strcmp($tmpold, $tmp);
2572 } while ($diff);
2573 }
2574
2575 $tmp = str_ireplace('&amp', '__ANDNOSEMICOLON__', $tmp);
2576 $tmp = str_ireplace('&quot', '__DOUBLEQUOTENOSEMICOLON__', $tmp);
2577 $tmp = str_ireplace('&lt', '__LESSTHAN__', $tmp);
2578 $tmp = str_ireplace('&gt', '__GREATERTHAN__', $tmp);
2579 }
2580
2581 // Warning: htmlentities encode all special chars that remains (except "'" with ENT_COMPAT).
2582 $result = htmlentities($tmp, ENT_COMPAT, 'UTF-8');
2583
2584 //print $result;
2585
2586 if (count($tmparrayoftags)) {
2587 // Restore protected tags
2588 foreach ($tmparrayoftags as $tagtoreplace) {
2589 $result = str_ireplace('__BEGINTAGTOREPLACE' . $tagtoreplace . '__', '<' . $tagtoreplace . '>', $result);
2590 $result = preg_replace('/__BEGINTAGTOREPLACE' . $tagtoreplace . '\[([^\]]*)\]__/', '<' . $tagtoreplace . ' \1>', $result);
2591 $result = str_ireplace('__ENDTAGTOREPLACE' . $tagtoreplace . '__', '</' . $tagtoreplace . '>', $result);
2592 $result = str_ireplace('__BEGINENDTAGTOREPLACE' . $tagtoreplace . '__', '<' . $tagtoreplace . ' />', $result);
2593 $result = preg_replace('/__BEGINENDTAGTOREPLACE' . $tagtoreplace . '\[([^\]]*)\]__/', '<' . $tagtoreplace . ' \1 />', $result);
2594 }
2595
2596 $result = str_ireplace('__DOUBLEQUOTE__', '"', $result);
2597
2598 $result = str_ireplace('__ANDNOSEMICOLON__', '&amp', $result);
2599 $result = str_ireplace('__DOUBLEQUOTENOSEMICOLON__', '&quot', $result);
2600 $result = str_ireplace('__LESSTHAN__', '&lt', $result);
2601 $result = str_ireplace('__GREATERTHAN__', '&gt', $result);
2602 }
2603
2604 $result = str_ireplace('__SIMPLEQUOTE__', '&#39;', $result);
2605
2606 //$result="\n\n\n".var_export($tmp, true)."\n\n\n".var_export($result, true);
2607
2608 return $result;
2609 }
2610}
2611
2619function dol_strtolower($string, $encoding = "UTF-8")
2620{
2621 if (function_exists('mb_strtolower')) {
2622 return mb_strtolower($string, $encoding);
2623 } else {
2624 return strtolower($string);
2625 }
2626}
2627
2636function dol_strtoupper($string, $encoding = "UTF-8")
2637{
2638 if (function_exists('mb_strtoupper')) {
2639 return mb_strtoupper($string, $encoding);
2640 } else {
2641 return strtoupper($string);
2642 }
2643}
2644
2653function dol_ucfirst($string, $encoding = "UTF-8")
2654{
2655 if (function_exists('mb_substr')) {
2656 return mb_strtoupper(mb_substr($string, 0, 1, $encoding), $encoding) . mb_substr($string, 1, null, $encoding);
2657 } else {
2658 return ucfirst($string);
2659 }
2660}
2661
2670function dol_ucwords($string, $encoding = "UTF-8")
2671{
2672 if (function_exists('mb_convert_case')) {
2673 return mb_convert_case($string, MB_CASE_TITLE, $encoding);
2674 } else {
2675 return ucwords($string);
2676 }
2677}
2678
2679
2685function getCallerInfoString()
2686{
2687 $backtrace = debug_backtrace();
2688 $msg = "";
2689 if (count($backtrace) >= 1) {
2690 $pos = 1;
2691 if (count($backtrace) == 1) {
2692 $pos = 0;
2693 }
2694 $trace = $backtrace[$pos];
2695 if (isset($trace['file'], $trace['line'])) {
2696 $msg = " From {$trace['file']}:{$trace['line']}.";
2697 }
2698 }
2699 return $msg;
2700}
2701
2724function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename = '', $restricttologhandler = '', $logcontext = null)
2725{
2726 global $conf, $user, $debugbar;
2727
2728 // If syslog module enabled
2729 if (!isModEnabled('syslog')) {
2730 return;
2731 }
2732
2733 // Check if we are into execution of code of a website
2734 if (defined('USEEXTERNALSERVER') && !defined('USEDOLIBARRSERVER') && !defined('USEDOLIBARREDITOR')) {
2735 global $website, $websitekey;
2736 if (is_object($website) && !empty($website->ref)) {
2737 $suffixinfilename .= '_website_' . $website->ref;
2738 } elseif (!empty($websitekey)) {
2739 $suffixinfilename .= '_website_' . $websitekey;
2740 }
2741 }
2742
2743 // Check if we have a forced suffix
2744 if (defined('USESUFFIXINLOG')) {
2745 $suffixinfilename .= constant('USESUFFIXINLOG');
2746 }
2747
2748 if ($ident < 0) {
2749 foreach ($conf->loghandlers as $loghandlerinstance) {
2750 $loghandlerinstance->setIdent($ident);
2751 }
2752 }
2753
2754 if (!empty($message)) {
2755 // Test log level
2756 // @phan-suppress-next-line PhanPluginDuplicateArrayKey
2757 $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');
2758
2759 if (!array_key_exists($level, $logLevels)) {
2760 dol_syslog('Error Bad Log Level ' . $level, LOG_ERR);
2761 $level = LOG_ERR;
2762 }
2763 if ($level > getDolGlobalInt('SYSLOG_LEVEL')) {
2764 return;
2765 }
2766
2767 if (!getDolGlobalString('MAIN_SHOW_PASSWORD_INTO_LOG')) {
2768 $message = preg_replace('/password=\'[^\']*\'/', 'password=\'hidden\'', $message); // protection to avoid to have value of password in log
2769 }
2770
2771 // If adding log inside HTML page is required
2772 if ((!empty($_REQUEST['logtohtml']) && getDolGlobalString('MAIN_ENABLE_LOG_TO_HTML'))
2773 || (is_object($user) && $user->hasRight('debugbar', 'read') && is_object($debugbar))
2774 ) {
2775 $ospid = sprintf("%7s", dol_trunc((string) getmypid(), 7, 'right', 'UTF-8', 1));
2776 $osuser = " " . sprintf("%6s", dol_trunc(function_exists('posix_getuid') ? posix_getuid() : '', 6, 'right', 'UTF-8', 1));
2777
2778 $conf->logbuffer[] = dol_print_date(time(), "%Y-%m-%d %H:%M:%S") . " " . sprintf("%-7s", $logLevels[$level]) . " " . $ospid . " " . $osuser . " " . $message;
2779 }
2780
2781 //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output
2782 // If html log tag enabled and url parameter log defined, we show output log on HTML comments
2783 if (getDolGlobalString('MAIN_ENABLE_LOG_INLINE_HTML') && GETPOSTINT("log")) {
2784 print "\n\n<!-- Log start\n";
2785 print dol_escape_htmltag($message) . "\n";
2786 print "Log end -->\n";
2787 }
2788
2789 $data = array(
2790 'message' => $message,
2791 'script' => (isset($_SERVER['PHP_SELF']) ? basename($_SERVER['PHP_SELF'], '.php') : ''),
2792 'level' => $level,
2793 'user' => ((is_object($user) && $user->id) ? $user->login : ''),
2794 'ip' => '',
2795 'osuser' => function_exists('posix_getuid') ? (string) posix_getuid() : '',
2796 'ospid' => (string) getmypid() // on linux, max value is defined into cat /proc/sys/kernel/pid_max
2797 );
2798
2799 // For log, we want the reliable IP first.
2800 $remoteip = getUserRemoteIP(1); // Get ip when page run on a web server
2801 if (!empty($remoteip)) {
2802 $data['ip'] = $remoteip;
2803 // This is when server run behind a reverse proxy
2804 // A HTTP_X_FORWARDED_FOR as format "ip real of user, ip of proxy1, ip of proxy2, ..."
2805 // $data['ip'] is last
2806 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
2807 $tmpips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
2808 $data['ip'] = '';
2809 $foundremoteip = 0;
2810 $j = 0;
2811 foreach ($tmpips as $tmpip) {
2812 $tmpip = trim($tmpip);
2813 if (strtolower($tmpip) == strtolower($remoteip)) {
2814 $foundremoteip = 1;
2815 }
2816 if (empty($data['ip'])) {
2817 $data['ip'] = $tmpip;
2818 } else {
2819 $j++;
2820 $data['ip'] .= (($j == 1) ? ' [via ' : ',') . $tmpip;
2821 }
2822 }
2823 if (!$foundremoteip) {
2824 $j++;
2825 $data['ip'] .= (($j == 1) ? ' [via ' : ',') . $remoteip;
2826 }
2827 $data['ip'] .= (($j > 0) ? ']' : '');
2828 } elseif (!empty($_SERVER['HTTP_CLIENT_IP'])) {
2829 $tmpips = explode(',', $_SERVER['HTTP_CLIENT_IP']);
2830 $data['ip'] = '';
2831 $foundremoteip = 0;
2832 $j = 0;
2833 foreach ($tmpips as $tmpip) {
2834 $tmpip = trim($tmpip);
2835 if (strtolower($tmpip) == strtolower($remoteip)) {
2836 $foundremoteip = 1;
2837 }
2838 if (empty($data['ip'])) {
2839 $data['ip'] = $tmpip;
2840 } else {
2841 $j++;
2842 $data['ip'] .= (($j == 1) ? ' [via ' : ',') . $tmpip;
2843 }
2844 }
2845 if (!$foundremoteip) {
2846 $j++;
2847 $data['ip'] .= (($j == 1) ? ' [via ' : ',') . $remoteip;
2848 }
2849 $data['ip'] .= (($j > 0) ? ']' : '');
2850 }
2851 } elseif (!empty($_SERVER['SERVER_ADDR'])) {
2852 // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
2853 $data['ip'] = (string) $_SERVER['SERVER_ADDR'];
2854 } elseif (!empty($_SERVER['COMPUTERNAME'])) {
2855 // 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).
2856 $data['ip'] = (string) $_SERVER['COMPUTERNAME'];
2857 } else {
2858 $data['ip'] = '???';
2859 }
2860
2861 if (!empty($_SERVER['USERNAME'])) {
2862 // 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).
2863 $data['osuser'] = (string) $_SERVER['USERNAME'];
2864 } elseif (!empty($_SERVER['LOGNAME'])) {
2865 // 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).
2866 $data['osuser'] = (string) $_SERVER['LOGNAME'];
2867 }
2868
2869 // Loop on each log handler and send output
2870 foreach ($conf->loghandlers as $loghandlerinstance) {
2871 if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler) {
2872 continue;
2873 }
2874 $loghandlerinstance->export($data, $suffixinfilename);
2875 }
2876 unset($data);
2877 }
2878
2879 if ($ident > 0) {
2880 foreach ($conf->loghandlers as $loghandlerinstance) {
2881 $loghandlerinstance->setIdent($ident);
2882 }
2883 }
2884}
2885
2897function dolButtonToOpenExportDialog($name, $label, $buttonstring, $exportSiteName, $overwriteGitUrl, $website)
2898{
2899 global $langs, $db;
2900
2901 $form = new Form($db);
2902
2903 $templatenameforexport = $website->name_template; // Example 'website_template-corporate'
2904 if (empty($templatenameforexport)) {
2905 $templatenameforexport = 'website_' . $website->ref;
2906 }
2907
2908 $out = '';
2909 $out .= '<input type="button" class="cursorpointer button bordertransp" id="open-dialog-' . $name . '" value="' . dol_escape_htmltag($buttonstring) . '"/>';
2910
2911 // for generate popup
2912 $out .= '<script nonce="' . getNonce() . '" type="text/javascript">';
2913 $out .= 'jQuery(document).ready(function () {';
2914 $out .= ' jQuery("#open-dialog-' . $name . '").click(function () {';
2915 $out .= ' var dialogHtml = \'';
2916
2917 $dialogcontent = ' <div id="custom-dialog-' . $name . '">';
2918 $dialogcontent .= ' <div style="margin-top: 20px;">';
2919 $dialogcontent .= ' <label for="export-site-' . $name . '"><strong>' . $langs->trans("ExportSiteLabel") . '...</label><br>';
2920 $dialogcontent .= ' <button class="button smallpaddingimp" id="export-site-' . $name . '">' . dol_escape_htmltag($langs->trans("DownloadZip")) . '</button>';
2921 $dialogcontent .= ' </div>';
2922 $dialogcontent .= ' <br>';
2923 $dialogcontent .= ' <div style="margin-top: 20px;">';
2924 $dialogcontent .= ' <strong>' . $langs->trans("ExportSiteGitLabel") . ' ' . $form->textwithpicto('', $langs->trans("SourceFiles"), 1, 'help', '', 0, 3, '') . '</strong><br>';
2925 $dialogcontent .= ' <form action="' . dol_escape_htmltag($overwriteGitUrl) . '" method="POST">';
2926 $dialogcontent .= ' <input type="hidden" name="action" value="overwritesite">';
2927 $dialogcontent .= ' <input type="hidden" name="token" value="' . newToken() . '">';
2928 $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>';
2929 $dialogcontent .= ' <button type="submit" class="button smallpaddingimp" id="overwrite-git-' . $name . '">' . dol_escape_htmltag($langs->trans("ExportIntoGIT")) . '</button>';
2930 $dialogcontent .= ' </form>';
2931 $dialogcontent .= ' </div>';
2932 $dialogcontent .= ' </div>';
2933
2934 $out .= dol_escape_js($dialogcontent);
2935
2936 $out .= '\';';
2937
2938
2939 // Add the content of the dialog to the body of the page
2940 $out .= ' var $dialog = jQuery("#custom-dialog-' . $name . '");';
2941 $out .= ' if ($dialog.length > 0) {
2942 $dialog.remove();
2943 }
2944 jQuery("body").append(dialogHtml);';
2945
2946 // Configuration of popup
2947 $out .= ' jQuery("#custom-dialog-' . $name . '").dialog({';
2948 $out .= ' autoOpen: false,';
2949 $out .= ' modal: true,';
2950 $out .= ' height: 290,';
2951 $out .= ' width: "40%",';
2952 $out .= ' title: "' . dol_escape_js($label) . '",';
2953 $out .= ' });';
2954
2955 // Simulate a click on the original "submit" input to export the site.
2956 $out .= ' jQuery("#export-site-' . $name . '").click(function () {';
2957 $out .= ' console.log("Clic on exportsite.");';
2958 $out .= ' var target = jQuery("input[name=\'' . dol_escape_js($exportSiteName) . '\']");';
2959 $out .= ' console.log("element founded:", target.length > 0);';
2960 $out .= ' if (target.length > 0) { target.click(); }';
2961 $out .= ' jQuery("#custom-dialog-' . $name . '").dialog("close");';
2962 $out .= ' });';
2963
2964 // open popup
2965 $out .= ' jQuery("#custom-dialog-' . $name . '").dialog("open");';
2966 $out .= ' return false;';
2967 $out .= ' });';
2968 $out .= '});';
2969 $out .= '</script>';
2970
2971 return $out;
2972}
2973
2974
2991function dolButtonToOpenUrlInDialogPopup($name, $label, $buttonstring, $url, $disabled = '', $morecss = 'classlink button bordertransp', $jsonopen = '', $jsonclose = '', $accesskey = '')
2992{
2993 global $conf;
2994
2995 if (strpos($url, '?') > 0) {
2996 $url .= '&dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup=' . urlencode($name);
2997 } else {
2998 $url .= '?dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup=' . urlencode($name);
2999 }
3000
3001 if (preg_match('/^https/i', $url)) {
3002 $urltoopen = $url;
3003 } else {
3004 $urltoopen = DOL_URL_ROOT . $url;
3005 }
3006
3007 $out = '';
3008
3009 //print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("MediaFiles")).'" name="file_manager">';
3010 $out .= '<!-- a link for button to open url into a dialog popup -->';
3011 $out .= '<a ' . ($accesskey ? ' accesskey="' . $accesskey . '"' : '') . ' class="cursorpointer reposition button_' . $name . ($morecss ? ' ' . $morecss : '') . '"' . $disabled . ' title="' . dol_escape_htmltag($label) . '"';
3012 if (empty($conf->use_javascript_ajax)) {
3013 $out .= ' href="' . $urltoopen . '" target="_blank"';
3014 } elseif ($jsonopen) {
3015 $out .= ' href="#" onclick="' . $jsonopen . '"';
3016 } else {
3017 $out .= ' href="#"';
3018 }
3019 $out .= '>' . $buttonstring . '</a>';
3020
3021 if (!empty($conf->use_javascript_ajax)) {
3022 // Add code to open url using the popup.
3023 $out .= '<!-- code to open popup and variables to retrieve returned variables -->';
3024 $out .= '<div id="idfordialog' . $name . '" class="hidden">' . (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER') < 2 ? 'div for dialog' : '') . '</div>';
3025
3026 $out .= '<!-- Add js code to open dialog popup on dialog -->';
3027 $out .= '<script nonce="' . getNonce() . '" type="text/javascript">
3028 jQuery(document).ready(function () {
3029 jQuery(".button_' . $name . '").click(function () {
3030 console.log(\'Open popup with jQuery(...).dialog() on URL ' . dol_escape_js($urltoopen) . '\');
3031 var $tmpdialog = $(\'#idfordialog' . $name . '\');
3032 $tmpdialog.html(\'<iframe class="iframedialog" id="iframedialog' . $name . '" style="border: 0px;" src="' . $urltoopen . '" width="100%" height="98%"></iframe>\');
3033 $tmpdialog.dialog({
3034 autoOpen: false,
3035 modal: true,
3036 height: (window.innerHeight - 150),
3037 width: \'80%\',
3038 title: \'' . dol_escape_js($label) . '\',
3039 open: function (event, ui) {
3040 console.log("open popup name=' . $name . '");
3041 },
3042 close: function (event, ui) {
3043 console.log("Popup is closed, run jsonclose = ' . $jsonclose . '");
3044 ' . (empty($jsonclose) ? '' : $jsonclose . ';') . '
3045 }
3046 });
3047
3048 $tmpdialog.dialog(\'open\');
3049 return false;
3050 });
3051 });
3052 </script>';
3053 }
3054 return $out;
3055}
3056
3073function dol_fiche_head($links = array(), $active = '0', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
3074{
3075 print dol_get_fiche_head($links, $active, $title, $notab, $picto, $pictoisfullpath, $morehtmlright, $morecss, $limittoshow, $moretabssuffix);
3076}
3077
3095function dol_get_fiche_head($links = array(), $active = '', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '', $dragdropfile = 0, $morecssdiv = '')
3096{
3097 global $conf, $langs, $hookmanager;
3098
3099 // Show title
3100 $showtitle = 1;
3101 if (!empty($conf->dol_optimize_smallscreen)) {
3102 $showtitle = 0;
3103 }
3104
3105 $out = "\n" . '<!-- dol_fiche_head - dol_get_fiche_head -->';
3106
3107 if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
3108 $out .= '<div class="tabs' . ($picto ? '' : ' nopaddingleft') . '" data-role="controlgroup" data-type="horizontal">' . "\n";
3109 }
3110
3111 // Show right part
3112 if ($morehtmlright) {
3113 $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.
3114 }
3115
3116 // Show tabs
3117
3118 // Define max of key (max may be higher than sizeof because of hole due to module disabling some tabs).
3119 $maxkey = -1;
3120 if (is_array($links) && !empty($links)) {
3121 $keys = array_keys($links);
3122 if (count($keys)) {
3123 $maxkey = max($keys);
3124 }
3125 }
3126
3127 // Show tabs
3128 // if =0 we don't use the feature
3129 if (empty($limittoshow)) {
3130 $limittoshow = getDolGlobalInt('MAIN_MAXTABS_IN_CARD', 99);
3131 }
3132 if (!empty($conf->dol_optimize_smallscreen)) {
3133 $limittoshow = 2;
3134 }
3135
3136 $displaytab = 0;
3137 $nbintab = 0;
3138 $popuptab = 0;
3139 $outmore = '';
3140 for ($i = 0; $i <= $maxkey; $i++) {
3141 if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
3142 // If active tab is already present
3143 if ($i >= $limittoshow) {
3144 $limittoshow--;
3145 }
3146 }
3147 }
3148
3149 for ($i = 0; $i <= $maxkey; $i++) {
3150 if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
3151 $isactive = true;
3152 } else {
3153 $isactive = false;
3154 }
3155
3156 if ($i < $limittoshow || $isactive) {
3157 // Output entry with a visible tab
3158 $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])) . ' -->';
3159
3160 if (isset($links[$i][2]) && $links[$i][2] == 'image') {
3161 if (!empty($links[$i][0])) {
3162 $out .= '<a class="tabimage' . ($morecss ? ' ' . $morecss : '') . '" href="' . $links[$i][0] . '">' . $links[$i][1] . '</a>' . "\n";
3163 } else {
3164 $out .= '<span class="tabspan">' . $links[$i][1] . '</span>' . "\n";
3165 }
3166 } elseif (!empty($links[$i][1])) {
3167 //print "x $i $active ".$links[$i][2]." z";
3168 $out .= '<div class="tab tab' . ($isactive ? 'active' : 'unactive') . '" style="margin: 0 !important">';
3169
3170 if (!empty($links[$i][0])) {
3171 $titletoshow = preg_replace('/<.*$/', '', $links[$i][1]);
3172 $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) . '">';
3173 }
3174
3175 if ($displaytab == 0 && $picto) {
3176 $out .= img_picto($title, $picto, '', $pictoisfullpath, 0, 0, '', 'imgTabTitle paddingright marginrightonlyshort');
3177 }
3178
3179 $out .= $links[$i][1];
3180 if (!empty($links[$i][0])) {
3181 $out .= '</a>' . "\n";
3182 }
3183 $out .= empty($links[$i][4]) ? '' : $links[$i][4];
3184 $out .= '</div>';
3185 }
3186
3187 $out .= '</div>';
3188 } else {
3189 // Add entry into the combo popup with the other tabs
3190 if (!$popuptab) {
3191 $popuptab = 1;
3192 $outmore .= '<div class="popuptabset wordwrap">'; // The css used to hide/show popup
3193 }
3194 $outmore_content = '';
3195
3196 if (isset($links[$i][2]) && $links[$i][2] == 'image') {
3197 if (!empty($links[$i][0])) {
3198 $outmore_content .= '<a class="tabimage' . ($morecss ? ' ' . $morecss : '') . '" href="' . $links[$i][0] . '">' . $links[$i][1] . '</a>' . "\n";
3199 } else {
3200 $outmore_content .= '<span class="tabspan">' . $links[$i][1] . '</span>' . "\n";
3201 }
3202 } elseif (!empty($links[$i][1])) {
3203 $outmore_content .= '<a' . (!empty($links[$i][2]) ? ' id="' . $links[$i][2] . '"' : '') . ' class="wordwrap inline-block' . ($morecss ? ' ' . $morecss : '') . '" href="' . $links[$i][0] . '">';
3204 $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.
3205 $outmore_content .= '</a>' . "\n";
3206 }
3207 if ($outmore_content !== '') {
3208 $outmore .= '<div class="popuptab wordwrap" style="display:inherit;">' . $outmore_content . '</div>';
3209 }
3210
3211 $nbintab++;
3212 }
3213
3214 $displaytab = $i + 1;
3215 }
3216 if ($popuptab) {
3217 $outmore .= '</div>';
3218 }
3219
3220 if ($popuptab) { // If there is some tabs not shown
3221 $left = ($langs->trans("DIRECTION") == 'rtl' ? 'right' : 'left');
3222 $right = ($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right');
3223 $widthofpopup = 240;
3224
3225 $tabsname = $moretabssuffix;
3226 if (empty($tabsname)) {
3227 $tabsname = str_replace("@", "", $picto);
3228 }
3229 $out .= '<div id="moretabs' . $tabsname . '" class="inline-block tabsElem valignmiddle">';
3230 if (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER') < 2) {
3231 $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".
3232 }
3233 $out .= '<div id="moretabsList' . $tabsname . '" style="width: ' . $widthofpopup . 'px; position: absolute; ' . $left . ': -999em; text-align: ' . $left . '; margin:0px; padding:2px; z-index:10;">';
3234 $out .= $outmore;
3235 $out .= '</div>';
3236 $out .= '<div></div>';
3237 $out .= "</div>\n";
3238
3239 $out .= '<script nonce="' . getNonce() . '">';
3240 $out .= "$('#moretabs" . $tabsname . "').mouseenter( function() {
3241 var x = this.offsetLeft, y = this.offsetTop;
3242 console.log('mouseenter " . $left . " x='+x+' y='+y+' window.innerWidth='+window.innerWidth);
3243 if ((window.innerWidth - x) < " . ($widthofpopup + 10) . ") {
3244 $('#moretabsList" . $tabsname . "').css('" . $right . "','8px');
3245 }
3246 $('#moretabsList" . $tabsname . "').css('" . $left . "','auto');
3247 });
3248 ";
3249 $out .= "$('#moretabs" . $tabsname . "').mouseleave( function() { console.log('mouseleave " . $left . "'); $('#moretabsList" . $tabsname . "').css('" . $left . "','-999em');});";
3250 $out .= "</script>";
3251 }
3252
3253 if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
3254 $out .= "</div>\n";
3255 }
3256
3257 if (!$notab || $notab == -1 || $notab == -2 || $notab == -3 || $notab == -4) {
3258 $out .= "\n" . '<div id="dragDropAreaTabBar" class="tabBar' . ($notab == -1 ? '' : ($notab == -2 ? ' tabBarNoTop' : ((($notab == -3 || $notab == -4) ? ' noborderbottom' : '') . ($notab == -4 ? '' : ' tabBarWithBottom'))));
3259 $out .= ($morecssdiv ? ' ' . $morecssdiv : '');
3260 $out .= '">' . "\n";
3261 }
3262 if (!empty($dragdropfile)) {
3263 include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
3264 $out .= dragAndDropFileUpload("dragDropAreaTabBar");
3265 }
3266 $parameters = array('tabname' => $active, 'out' => $out);
3267 $reshook = $hookmanager->executeHooks('printTabsHead', $parameters); // This hook usage is called just before output the head of tabs. Take also a look at "completeTabsHead"
3268 if ($reshook > 0) {
3269 $out = $hookmanager->resPrint;
3270 }
3271
3272 return $out;
3273}
3274
3282function dol_fiche_end($notab = 0)
3283{
3284 print dol_get_fiche_end($notab);
3285}
3286
3293function dol_get_fiche_end($notab = 0)
3294{
3295 if (!$notab || $notab == -1) {
3296 return "\n</div>\n";
3297 } else {
3298 return '';
3299 }
3300}
3301
3321function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $onlybanner = 0, $morehtmlright = '')
3322{
3323 global $conf, $form, $user, $langs, $hookmanager, $action;
3324
3325 $error = 0;
3326
3327 $maxvisiblephotos = 1;
3328 $showimage = 1;
3329 $entity = (empty($object->entity) ? $conf->entity : $object->entity);
3330 // @phan-suppress-next-line PhanUndeclaredMethod
3331 $showbarcode = !isModEnabled('barcode') ? 0 : (empty($object->barcode) ? 0 : 1);
3332 if (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !$user->hasRight('barcode', 'lire_advance')) {
3333 $showbarcode = 0;
3334 }
3335 $modulepart = 'unknown';
3336
3337 if (in_array($object->element, ['societe', 'contact', 'product', 'ticket', 'bom'])) {
3338 $modulepart = $object->element;
3339 } elseif ($object->element == 'member') {
3340 $modulepart = 'memberphoto';
3341 } elseif ($object->element == 'user') {
3342 $modulepart = 'userphoto';
3343 }
3344
3345 if (class_exists("Imagick")) {
3346 if ($object->element == 'expensereport' || $object->element == 'propal' || $object->element == 'commande' || $object->element == 'facture' || $object->element == 'supplier_proposal') {
3347 $modulepart = $object->element;
3348 } elseif ($object->element == 'fichinter' || $object->element == 'intervention') {
3349 $modulepart = 'ficheinter';
3350 } elseif ($object->element == 'contrat' || $object->element == 'contract') {
3351 $modulepart = 'contract';
3352 } elseif ($object->element == 'order_supplier') {
3353 $modulepart = 'supplier_order';
3354 } elseif ($object->element == 'invoice_supplier') {
3355 $modulepart = 'supplier_invoice';
3356 }
3357 }
3358
3359 if ($object->element == 'product') {
3361 '@phan-var-force Product $object';
3362 $width = 80;
3363 $cssclass = 'photowithmargin photoref';
3364 $showimage = $object->is_photo_available($conf->product->multidir_output[$entity]);
3365 $maxvisiblephotos = getDolGlobalInt('PRODUCT_MAX_VISIBLE_PHOTO', 5);
3366 if ($conf->browser->layout == 'phone') {
3367 $maxvisiblephotos = 1;
3368 }
3369 if ($showimage) {
3370 $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>';
3371 } else {
3372 if (getDolGlobalString('PRODUCT_NODISPLAYIFNOPHOTO')) {
3373 $nophoto = '';
3374 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
3375 } else { // Show no photo link
3376 $nophoto = '/public/theme/common/nophoto.png';
3377 $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>';
3378 }
3379 }
3380 } elseif ($object->element == 'category') {
3382 '@phan-var-force Categorie $object';
3383 $width = 80;
3384 $cssclass = 'photowithmargin photoref';
3385 $showimage = $object->isAnyPhotoAvailable($conf->categorie->multidir_output[$entity]);
3386 $maxvisiblephotos = getDolGlobalInt('CATEGORY_MAX_VISIBLE_PHOTO', 5);
3387 if ($conf->browser->layout == 'phone') {
3388 $maxvisiblephotos = 1;
3389 }
3390 if ($showimage) {
3391 $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>';
3392 } else {
3393 if (getDolGlobalString('CATEGORY_NODISPLAYIFNOPHOTO')) {
3394 $nophoto = '';
3395 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
3396 } else { // Show no photo link
3397 $nophoto = '/public/theme/common/nophoto.png';
3398 $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>';
3399 }
3400 }
3401 } elseif ($object->element == 'bom') {
3403 '@phan-var-force Bom $object';
3404 $width = 80;
3405 $cssclass = 'photowithmargin photoref';
3406 $showimage = $object->is_photo_available($conf->bom->multidir_output[$entity]);
3407 $maxvisiblephotos = getDolGlobalInt('BOM_MAX_VISIBLE_PHOTO', 5);
3408 if ($conf->browser->layout == 'phone') {
3409 $maxvisiblephotos = 1;
3410 }
3411 if ($showimage) {
3412 $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>';
3413 } else {
3414 if (getDolGlobalString('BOM_NODISPLAYIFNOPHOTO')) {
3415 $nophoto = '';
3416 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
3417 } else { // Show no photo link
3418 $nophoto = '/public/theme/common/nophoto.png';
3419 $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>';
3420 }
3421 }
3422 } elseif ($object->element == 'ticket') {
3423 $width = 80;
3424 $cssclass = 'photoref';
3426 '@phan-var-force Ticket $object';
3427 $showimage = $object->is_photo_available($conf->ticket->multidir_output[$entity] . '/' . $object->ref);
3428 $maxvisiblephotos = getDolGlobalInt('TICKET_MAX_VISIBLE_PHOTO', 2);
3429 if ($conf->browser->layout == 'phone') {
3430 $maxvisiblephotos = 1;
3431 }
3432
3433 if ($showimage) {
3434 $showphoto = $object->show_photos('ticket', $conf->ticket->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0);
3435 if ($object->nbphoto > 0) {
3436 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">' . $showphoto . '</div>';
3437 } else {
3438 $showimage = 0;
3439 }
3440 }
3441 if (!$showimage) {
3442 if (getDolGlobalString('TICKET_NODISPLAYIFNOPHOTO')) {
3443 $nophoto = '';
3444 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
3445 } else { // Show no photo link
3446 $nophoto = img_picto('No photo', 'object_ticket');
3447 $morehtmlleft .= '<!-- No photo to show -->';
3448 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
3449 $morehtmlleft .= $nophoto;
3450 $morehtmlleft .= '</div></div>';
3451 }
3452 }
3453 } else {
3454 if ($modulepart != 'unknown' || method_exists($object, 'getDataToShowPhoto')) {
3455 $phototoshow = '';
3456 // Check if a preview file is available
3457 if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice', 'expensereport')) && class_exists("Imagick")) {
3458 $objectref = dol_sanitizeFileName($object->ref);
3459 $dir_output = (empty($conf->$modulepart->multidir_output[$entity]) ? $conf->$modulepart->dir_output : $conf->$modulepart->multidir_output[$entity]) . "/";
3460 if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice'))) {
3461 $subdir = get_exdir($object->id, 2, 0, 1, $object, $modulepart);
3462 $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
3463 } else {
3464 $subdir = get_exdir($object->id, 0, 0, 1, $object, $modulepart);
3465 }
3466 if (empty($subdir)) {
3467 $subdir = 'errorgettingsubdirofobject'; // Protection to avoid to return empty path
3468 }
3469
3470 $filepath = $dir_output . $subdir . "/";
3471
3472 $filepdf = $filepath . $objectref . ".pdf";
3473 $relativepath = $subdir . '/' . $objectref . '.pdf';
3474
3475 // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png")
3476 $fileimage = $filepdf . '_preview.png';
3477 $relativepathimage = $relativepath . '_preview.png';
3478
3479 $pdfexists = file_exists($filepdf);
3480
3481 // If PDF file exists
3482 if ($pdfexists) {
3483 // Conversion du PDF en image png si fichier png non existent
3484 if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf))) {
3485 if (!getDolGlobalString('MAIN_DISABLE_PDF_THUMBS')) { // If you experience trouble with pdf thumb generation and imagick, you can disable here.
3486 include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
3487 $ret = dol_convert_file($filepdf, 'png', $fileimage, '0'); // Convert first page of PDF into a file _preview.png
3488 if ($ret < 0) {
3489 $error++;
3490 }
3491 }
3492 }
3493 }
3494
3495 if ($pdfexists && !$error) {
3496 $heightforphotref = 80;
3497 if (!empty($conf->dol_optimize_smallscreen)) {
3498 $heightforphotref = 60;
3499 }
3500 // If the preview file is found
3501 if (file_exists($fileimage)) {
3502 $phototoshow = '<div class="photoref">';
3503 $phototoshow .= '<img height="' . $heightforphotref . '" class="photo photowithborder" src="' . DOL_URL_ROOT . '/viewimage.php?modulepart=apercu' . $modulepart . '&amp;file=' . urlencode($relativepathimage) . '">';
3504 $phototoshow .= '</div>';
3505 }
3506 }
3507 } elseif (!$phototoshow) { // example if modulepart = 'societe' or 'photo' or 'memberphoto'
3508 $phototoshow .= $form->showphoto($modulepart, $object, 0, 0, 0, 'photowithmargin photoref', 'small', 1, 0);
3509 }
3510
3511 if ($phototoshow) {
3512 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">';
3513 $morehtmlleft .= $phototoshow;
3514 $morehtmlleft .= '</div>';
3515 }
3516 }
3517
3518 if (empty($phototoshow)) { // Show No photo link (picto of object)
3519 if ($object->element == 'action') {
3520 $width = 80;
3521 $cssclass = 'photorefcenter';
3522 $nophoto = img_picto('No photo', 'title_agenda');
3523 } else {
3524 $width = 14;
3525 $cssclass = 'photorefcenter';
3526 $picto = $object->picto; // @phan-suppress-current-line PhanUndeclaredProperty
3527 $prefix = 'object_';
3528 if ($object->element == 'project' && !$object->public) { // @phan-suppress-current-line PhanUndeclaredProperty
3529 $picto = 'project'; // instead of projectpub
3530 }
3531 if (strpos($picto, 'fontawesome_') !== false) {
3532 $prefix = '';
3533 }
3534 $nophoto = img_picto('No photo', $prefix . $picto);
3535 }
3536 $morehtmlleft .= '<!-- No photo to show -->';
3537 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
3538 $morehtmlleft .= $nophoto;
3539 $morehtmlleft .= '</div></div>';
3540 }
3541 }
3542
3543 // Show barcode
3544 if ($showbarcode) {
3545 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">' . $form->showbarcode($object, 100, 'photoref valignmiddle') . '</div>';
3546 }
3547
3548 if ($object->element == 'societe') {
3550 if (!empty($conf->use_javascript_ajax) && $user->hasRight('societe', 'creer') && getDolGlobalString('MAIN_DIRECT_STATUS_UPDATE')) {
3551 $morehtmlstatus .= ajax_object_onoff($object, 'status', 'status', 'InActivity', 'ActivityCeased');
3552 } else {
3553 $morehtmlstatus .= $object->getLibStatut(6);
3554 }
3555 } elseif ($object->element == 'product') {
3557 //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Sell").') ';
3558 if (!empty($conf->use_javascript_ajax) && $user->hasRight('produit', 'creer') && getDolGlobalString('MAIN_DIRECT_STATUS_UPDATE')) {
3559 $morehtmlstatus .= ajax_object_onoff($object, 'status', 'status', 'ProductStatusOnSell', 'ProductStatusNotOnSell');
3560 } else {
3561 $morehtmlstatus .= '<span class="statusrefsell">' . $object->getLibStatut(6, 0) . '</span>';
3562 }
3563 $morehtmlstatus .= ' &nbsp; ';
3564 //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Buy").') ';
3565 if (!empty($conf->use_javascript_ajax) && $user->hasRight('produit', 'creer') && getDolGlobalString('MAIN_DIRECT_STATUS_UPDATE')) {
3566 $morehtmlstatus .= ajax_object_onoff($object, 'status_buy', 'status_buy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy');
3567 } else {
3568 $morehtmlstatus .= '<span class="statusrefbuy">' . $object->getLibStatut(6, 1) . '</span>';
3569 }
3570 } elseif (in_array($object->element, array('salary'))) {
3572 '@phan-var-force Salary $object';
3573 $tmptxt = $object->getLibStatut(6, $object->alreadypaid);
3574 if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
3575 $tmptxt = $object->getLibStatut(5, $object->alreadypaid);
3576 }
3577 $morehtmlstatus .= $tmptxt;
3578 } elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier'))) {
3580 '@phan-var-force Facture|FactureFournisseur|CommonInvoice $object';
3581 if (!isset($object->alreadypaid)) {
3582 $object->totalpaid = $object->getSommePaiement(0);
3583 $object->totalcreditnotes = $object->getSumCreditNotesUsed(0);
3584 $object->totaldeposits = $object->getSumDepositsUsed(0);
3585 $object->alreadypaid = $object->totalpaid + $object->totalcreditnotes + $object->totaldeposits;
3586 }
3587 $tmptxt = $object->getLibStatut(6, (float) $object->alreadypaid);
3588 if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
3589 $tmptxt = $object->getLibStatut(5, (float) $object->alreadypaid);
3590 }
3591 $morehtmlstatus .= $tmptxt;
3592 } elseif (in_array($object->element, array('chargesociales', 'loan', 'tva'))) { // TODO Move this to use ->alreadypaid like for invoices
3594 '@phan-var-force ChargeSociales|Loan|Tva $object';
3595 $tmptxt = $object->getLibStatut(6, $object->totalpaid);
3596 if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
3597 $tmptxt = $object->getLibStatut(5, $object->totalpaid);
3598 }
3599 $morehtmlstatus .= $tmptxt;
3600 } elseif ($object->element == 'contrat' || $object->element == 'contract') {
3602 if ($object->status == 0) {
3603 $morehtmlstatus .= $object->getLibStatut(5);
3604 } else {
3605 $morehtmlstatus .= $object->getLibStatut(4);
3606 }
3607 } elseif ($object->element == 'facturerec') {
3609 '@phan-var-force FactureRec $object';
3610 if ($object->frequency == 0) {
3611 $morehtmlstatus .= $object->getLibStatut(2);
3612 } else {
3613 $morehtmlstatus .= $object->getLibStatut(5);
3614 }
3615 } elseif ($object->element == 'project_task') {
3617 $tmptxt = $object->getLibStatut(4);
3618 $morehtmlstatus .= $tmptxt;
3619 } elseif (method_exists($object, 'getLibStatut')) { // Generic case for status
3620 $tmptxt = $object->getLibStatut(6);
3621 if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
3622 $tmptxt = $object->getLibStatut(5);
3623 }
3624 $morehtmlstatus .= $tmptxt;
3625 }
3626
3627 // Say if object was dispatched/transferred "into accountancy"
3628 if (isModEnabled('accounting') && in_array($object->element, array('bank', 'paiementcharge', 'facture', 'invoice', 'invoice_supplier', 'expensereport', 'payment_various'))) {
3629 // Note: For 'chargesociales', 'salaries'... this is the payments that are dispatched (so element = 'bank')
3630 if (method_exists($object, 'getVentilExportCompta')) {
3631 $accounted = $object->getVentilExportCompta(1);
3632 $langs->load("accountancy");
3633 $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>';
3634 }
3635 }
3636
3637 // Add alias for thirdparty
3638 if (!empty($object->name_alias)) {
3640 '@phan-var-force Societe $object';
3641 $morehtmlref .= '<div class="refidno opacitymedium">' . dol_escape_htmltag($object->name_alias) . '</div>';
3642 }
3643
3644 // Add label
3645 if (in_array($object->element, array('product', 'bank_account', 'project_task'))) {
3647 if (!empty($object->label)) {
3648 $morehtmlref .= '<div class="refidno banner-object-label">' . $object->label . '</div>';
3649 }
3650 }
3651 // Show address and email
3652 if (method_exists($object, 'getBannerAddress') && !in_array($object->element, array('product', 'bookmark', 'ecm_directories', 'ecm_files'))) {
3653 $moreaddress = $object->getBannerAddress('refaddress', $object); // address, email, url, social networks
3654 if ($moreaddress) {
3655 $morehtmlref .= '<div class="refidno refaddress">';
3656 $morehtmlref .= $moreaddress;
3657 $morehtmlref .= '</div>';
3658 }
3659 }
3660 if (getDolGlobalString('MAIN_SHOW_TECHNICAL_ID') && (getDolGlobalString('MAIN_SHOW_TECHNICAL_ID') == '1' || preg_match('/' . preg_quote($object->element, '/') . '/i', getDolGlobalString('MAIN_SHOW_TECHNICAL_ID'))) && !empty($object->id)) {
3661 $morehtmlref .= '<div style="clear: both;"></div>';
3662 $morehtmlref .= '<div class="refidno opacitymedium">';
3663 $morehtmlref .= $langs->trans("TechnicalID") . ': ' . ((int) $object->id);
3664 $morehtmlref .= '</div>';
3665 }
3666
3667 $parameters = array('morehtmlref' => &$morehtmlref, 'moreparam' => &$moreparam, 'morehtmlleft' => &$morehtmlleft, 'morehtmlstatus' => &$morehtmlstatus, 'morehtmlright' => &$morehtmlright);
3668 $reshook = $hookmanager->executeHooks('formDolBanner', $parameters, $object, $action);
3669 if ($reshook < 0) {
3670 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
3671 } elseif (empty($reshook)) {
3672 $morehtmlref .= $hookmanager->resPrint;
3673 } elseif ($reshook > 0) {
3674 $morehtmlref = $hookmanager->resPrint;
3675 }
3676
3677 // $morehtml is the right part (link "Back to list")
3678 // $morehtmlref is the part after the ref
3679 // $morehtmlleft is the picto or photo of banner
3680 // $morehtmlstatus is part under the status
3681 // $morehtmlright is part of htmlright
3682
3683 print '<div class="' . ($onlybanner ? 'arearefnobottom ' : 'arearef ') . 'heightref valignmiddle centpercent object-banner-tab-container" data-module-part="'.dolPrintHTMLForAttribute($modulepart).'">';
3684 print $form->showrefnav($object, $paramid, $morehtml, $shownav, $fieldid, $fieldref, $morehtmlref, $moreparam, $nodbprefix, $morehtmlleft, $morehtmlstatus, $morehtmlright);
3685 print '</div>';
3686 print '<div class="underrefbanner clearboth"></div>';
3687}
3688
3698function fieldLabel($langkey, $fieldkey, $fieldrequired = 0)
3699{
3700 global $langs;
3701 $ret = '';
3702 if ($fieldrequired) {
3703 $ret .= '<span class="fieldrequired">';
3704 }
3705 $ret .= '<label for="' . $fieldkey . '">';
3706 $ret .= $langs->trans($langkey);
3707 $ret .= '</label>';
3708 if ($fieldrequired) {
3709 $ret .= '</span>';
3710 }
3711 return $ret;
3712}
3713
3727function dol_format_address($object, $withcountry = 0, $sep = "\n", $outputlangs = null, $mode = 0, $extralangcode = '')
3728{
3729 global $langs, $hookmanager;
3730
3731 $ret = '';
3732 $countriesusingstate = array('AU', 'CA', 'US', 'IN', 'GB', 'ES', 'UK', 'TR', 'CN'); // See also MAIN_FORCE_STATE_INTO_ADDRESS
3733
3734 // See format of addresses on https://en.wikipedia.org/wiki/Address
3735 // Address
3736 if (empty($mode)) {
3737 $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)));
3738 }
3739 // Zip/Town/State
3740 if (isset($object->country_code) && in_array($object->country_code, array('AU', 'CA', 'US', 'CN')) || getDolGlobalString('MAIN_FORCE_STATE_INTO_ADDRESS')) {
3741 // US: title firstname name \n address lines \n town, state, zip \n country
3742 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
3743 $ret .= (($ret && $town) ? $sep : '') . $town;
3744
3745 if (!empty($object->state)) {
3746 $ret .= ($ret ? ($town ? ", " : $sep) : '') . $object->state;
3747 }
3748 if (!empty($object->zip)) {
3749 $ret .= ($ret ? (($town || $object->state) ? ", " : $sep) : '') . $object->zip;
3750 }
3751 } elseif (isset($object->country_code) && in_array($object->country_code, array('GB', 'UK'))) {
3752 // UK: title firstname name \n address lines \n town state \n zip \n country
3753 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
3754 $ret .= ($ret ? $sep : '') . $town;
3755 if (!empty($object->state)) {
3756 $ret .= ($ret ? ", " : '') . $object->state;
3757 }
3758 if (!empty($object->zip)) {
3759 $ret .= ($ret ? $sep : '') . $object->zip;
3760 }
3761 } elseif (isset($object->country_code) && in_array($object->country_code, array('ES', 'TR'))) {
3762 // ES: title firstname name \n address lines \n zip town \n state \n country
3763 $ret .= ($ret ? $sep : '') . $object->zip;
3764 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
3765 $ret .= ($town ? (($object->zip ? ' ' : '') . $town) : '');
3766 if (!empty($object->state)) {
3767 $ret .= $sep . $object->state;
3768 }
3769 } elseif (isset($object->country_code) && in_array($object->country_code, array('JP'))) {
3770 // JP: In romaji, title firstname name\n address lines \n [state,] town zip \n country
3771 // See https://www.sljfaq.org/afaq/addresses.html
3772 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
3773 $ret .= ($ret ? $sep : '') . ($object->state ? $object->state . ', ' : '') . $town . ($object->zip ? ' ' : '') . $object->zip;
3774 } elseif (isset($object->country_code) && in_array($object->country_code, array('IT'))) {
3775 // IT: title firstname name\n address lines \n zip town state_code \n country
3776 $ret .= ($ret ? $sep : '') . $object->zip;
3777 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
3778 $ret .= ($town ? (($object->zip ? ' ' : '') . $town) : '');
3779 $ret .= (empty($object->state_code) ? '' : (' ' . $object->state_code));
3780 } else {
3781 // Other: title firstname name \n address lines \n zip town[, state] \n country
3782 $town = (($extralangcode && !empty($object->array_languages['address'][$extralangcode])) ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
3783 $ret .= !empty($object->zip) ? (($ret ? $sep : '') . $object->zip) : '';
3784 $ret .= ($town ? (($object->zip ? ' ' : ($ret ? $sep : '')) . $town) : '');
3785 if (!empty($object->state) && in_array($object->country_code, $countriesusingstate)) {
3786 $ret .= ($ret ? ", " : '') . $object->state;
3787 }
3788 }
3789
3790 if (!is_object($outputlangs)) {
3791 $outputlangs = $langs;
3792 }
3793 if ($withcountry) {
3794 $langs->load("dict");
3795 $ret .= (empty($object->country_code) ? '' : ($ret ? $sep : '') . $outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country" . $object->country_code)));
3796 }
3797 if ($hookmanager) {
3798 $parameters = array('withcountry' => $withcountry, 'sep' => $sep, 'outputlangs' => $outputlangs, 'mode' => $mode, 'extralangcode' => $extralangcode);
3799 $reshook = $hookmanager->executeHooks('formatAddress', $parameters, $object);
3800 if ($reshook > 0) {
3801 $ret = '';
3802 }
3803 $ret .= $hookmanager->resPrint;
3804 }
3805
3806 return $ret;
3807}
3808
3809
3810
3820function dol_strftime($fmt, $ts = false, $is_gmt = false)
3821{
3822 if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
3823 return dol_print_date($ts, $fmt, $is_gmt);
3824 } else {
3825 return 'Error date outside supported range';
3826 }
3827}
3828
3851function dol_print_date($time, $format = '', $tzoutput = 'auto', $outputlangs = null, $encodetooutput = false, $decorate = 0)
3852{
3853 global $conf, $langs;
3854
3855 // If date undefined or "", we return ""
3856 if (dol_strlen((string) $time) == 0) {
3857 return ''; // $time=0 allowed (it means 01/01/1970 00:00:00)
3858 }
3859
3860 if ($tzoutput === 'auto') {
3861 $tzoutput = (empty($conf) ? 'tzserver' : (isset($conf->tzuserinputkey) ? $conf->tzuserinputkey : 'tzserver'));
3862 }
3863
3864 // Clean parameters
3865 $to_gmt = false; // false if we want date in server timezone, true if we want to add offset
3866 $offsettz = $offsetdst = 0;
3867 if ($tzoutput) {
3868 $to_gmt = true; // For backward compatibility
3869 if (is_string($tzoutput)) {
3870 if ($tzoutput == 'tzserver') {
3871 $to_gmt = false;
3872 $offsettzstring = @date_default_timezone_get(); // Example 'Europe/Berlin' or 'Indian/Reunion'
3873 // @phan-suppress-next-line PhanPluginRedundantAssignment
3874 $offsettz = 0; // Timezone offset with server timezone (because to_gmt is false), so 0
3875 // @phan-suppress-next-line PhanPluginRedundantAssignment
3876 $offsetdst = 0; // Dst offset with server timezone (because to_gmt is false), so 0
3877 } elseif ($tzoutput == 'tzuser' || $tzoutput == 'tzuserrel') {
3878 $to_gmt = true;
3879 // if no session (by example in cron) may use MAIN_DOLIBARR_USER_TIMEZONE instead UTC
3880 $offsettzstring = (empty($_SESSION['dol_tz_string']) ? getDolGlobalString('MAIN_DOLIBARR_USER_TIMEZONE', 'UTC') : $_SESSION['dol_tz_string']); // Example 'Europe/Berlin' or 'Indian/Reunion'
3881
3882 if (class_exists('DateTimeZone')) {
3883 try {
3884 $user_date_tz = new DateTimeZone($offsettzstring);
3885 } catch (Exception $e) {
3886 // Bad value for $offsettzstring
3887 dol_syslog("DateInvalidTimeZoneException for timezone string '".$offsettzstring."'. Falling back to UTC.", LOG_ERR);
3888 $user_date_tz = new DateTimeZone('UTC'); // Force valid timezone as UTC
3889 }
3890 $user_dt = new DateTime();
3891 $user_dt->setTimezone($user_date_tz);
3892 $user_dt->setTimestamp($tzoutput == 'tzuser' ? dol_now() : (int) $time);
3893 $offsettz = $user_dt->getOffset(); // should include dst ?
3894 } else { // with old method (The 'tzuser' was processed like the 'tzuserrel')
3895 $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60; // Will not be used anymore
3896 $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60; // Will not be used anymore
3897 }
3898 }
3899 }
3900 }
3901 if (!is_object($outputlangs)) {
3902 $outputlangs = $langs;
3903 }
3904 if (!$format) {
3905 $format = 'daytextshort';
3906 }
3907
3908 // Do we have to reduce the length of date (year on 2 chars) to save space.
3909 // Note: dayinputnoreduce is same than day but no reduction of year length will be done
3910 $reduceformat = (!empty($conf->dol_optimize_smallscreen) && in_array($format, array('day', 'dayhour', 'dayhoursec'))) ? 1 : 0; // Test on original $format param.
3911 $format = preg_replace('/inputnoreduce/', '', $format); // so format 'dayinputnoreduce' is processed like day
3912 $formatwithoutreduce = preg_replace('/reduceformat/', '', $format);
3913 if ($formatwithoutreduce != $format) {
3914 $format = $formatwithoutreduce;
3915 $reduceformat = 1;
3916 } // so format 'dayreduceformat' is processed like day
3917
3918 // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
3919 // TODO Add format daysmallyear and dayhoursmallyear
3920 if ($format == 'day') {
3921 $format = ($outputlangs->trans("FormatDateShort") != "FormatDateShort" ? $outputlangs->trans("FormatDateShort") : $conf->format_date_short);
3922 } elseif ($format == 'hour') {
3923 $format = ($outputlangs->trans("FormatHourShort") != "FormatHourShort" ? $outputlangs->trans("FormatHourShort") : $conf->format_hour_short);
3924 } elseif ($format == 'hourduration') {
3925 $format = ($outputlangs->trans("FormatHourShortDuration") != "FormatHourShortDuration" ? $outputlangs->trans("FormatHourShortDuration") : $conf->format_hour_short_duration);
3926 } elseif ($format == 'daytext') {
3927 $format = ($outputlangs->trans("FormatDateText") != "FormatDateText" ? $outputlangs->trans("FormatDateText") : $conf->format_date_text);
3928 } elseif ($format == 'daytextshort') {
3929 $format = ($outputlangs->trans("FormatDateTextShort") != "FormatDateTextShort" ? $outputlangs->trans("FormatDateTextShort") : $conf->format_date_text_short);
3930 } elseif ($format == 'dayhour') {
3931 $format = ($outputlangs->trans("FormatDateHourShort") != "FormatDateHourShort" ? $outputlangs->trans("FormatDateHourShort") : $conf->format_date_hour_short);
3932 } elseif ($format == 'dayhoursec') {
3933 $format = ($outputlangs->trans("FormatDateHourSecShort") != "FormatDateHourSecShort" ? $outputlangs->trans("FormatDateHourSecShort") : $conf->format_date_hour_sec_short);
3934 } elseif ($format == 'dayhourtext') {
3935 $format = ($outputlangs->trans("FormatDateHourText") != "FormatDateHourText" ? $outputlangs->trans("FormatDateHourText") : $conf->format_date_hour_text);
3936 } elseif ($format == 'dayhourtextshort') {
3937 $format = ($outputlangs->trans("FormatDateHourTextShort") != "FormatDateHourTextShort" ? $outputlangs->trans("FormatDateHourTextShort") : $conf->format_date_hour_text_short);
3938 } elseif ($format == 'dayhourlog') {
3939 // Format not sensitive to language
3940 $format = '%Y%m%d%H%M%S';
3941 } elseif ($format == 'dayhourlogsmall') {
3942 // Format not sensitive to language
3943 $format = '%y%m%d%H%M';
3944 } elseif ($format == 'dayhourldap') {
3945 $format = '%Y%m%d%H%M%SZ';
3946 } elseif ($format == 'dayhourxcard') {
3947 $format = '%Y%m%dT%H%M%SZ';
3948 } elseif ($format == 'dayxcard') {
3949 $format = '%Y%m%d';
3950 } elseif ($format == 'dayrfc') {
3951 $format = '%Y-%m-%d'; // DATE_RFC3339
3952 } elseif ($format == 'dayhourrfc') {
3953 $format = '%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339
3954 } elseif ($format == 'standard') {
3955 $format = '%Y-%m-%d %H:%M:%S';
3956 }
3957
3958 if ($reduceformat) {
3959 $format = str_replace('%Y', '%y', $format);
3960 $format = str_replace('yyyy', 'yy', $format);
3961 }
3962
3963 // Clean format
3964 if (preg_match('/%b/i', $format)) { // There is some text to translate
3965 // We inhibit translation to text made by strftime functions. We will use trans instead later.
3966 $format = str_replace('%b', '__b__', $format);
3967 $format = str_replace('%B', '__B__', $format);
3968 }
3969 if (preg_match('/%a/i', $format)) { // There is some text to translate
3970 // We inhibit translation to text made by strftime functions. We will use trans instead later.
3971 $format = str_replace('%a', '__a__', $format);
3972 $format = str_replace('%A', '__A__', $format);
3973 }
3974
3975 // Analyze date
3976 $reg = array();
3977 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
3978 dol_print_error(null, "Functions.lib::dol_print_date function called with a bad value" . getCallerInfoString());
3979 return '';
3980 } 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
3981 // This part of code should not be used anymore.
3982 dol_syslog("Functions.lib::dol_print_date function called with a bad value" . getCallerInfoString(), LOG_WARNING);
3983 // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
3984 $syear = (!empty($reg[1]) ? $reg[1] : '');
3985 $smonth = (!empty($reg[2]) ? $reg[2] : '');
3986 $sday = (!empty($reg[3]) ? $reg[3] : '');
3987 $shour = (!empty($reg[4]) ? $reg[4] : '');
3988 $smin = (!empty($reg[5]) ? $reg[5] : '');
3989 $ssec = (!empty($reg[6]) ? $reg[6] : '');
3990
3991 $time = dol_mktime((int) $shour, (int) $smin, (int) $ssec, (int) $smonth, (int) $sday, (int) $syear, true);
3992
3993 if ($to_gmt) {
3994 $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
3995 } else {
3996 $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
3997 }
3998 $dtts = new DateTime();
3999 $dtts->setTimestamp($time);
4000 $dtts->setTimezone($tzo);
4001 $newformat = str_replace(
4002 array('%Y', '%y', '%m', '%d', '%H', '%I', '%M', '%S', '%p', 'T', 'Z', '__a__', '__A__', '__b__', '__B__'),
4003 array('Y', 'y', 'm', 'd', 'H', 'h', 'i', 's', 'A', '__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
4004 $format
4005 );
4006 $ret = $dtts->format($newformat);
4007 $ret = str_replace(
4008 array('__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
4009 array('T', 'Z', '__a__', '__A__', '__b__', '__B__'),
4010 $ret
4011 );
4012 } else {
4013 // Date is a timestamps
4014 if ($time < 100000000000) { // Protection against bad date values
4015 $dtts = new DateTime();
4016 //var_dump($tzoutput.' '.$offsettzstring.' '.$offsettz.$offsetdst.' x '.$to_gmt);
4017 if ($to_gmt) { // to_gmt means "not in php server timezone" (if tzoutput = 'gmt', offsets should be 0 but if = 'tzuser...', offsets may be defined
4018 $timetouse = (int) $time + $offsettz + $offsetdst; // TODO We could be able to disable use of offsettz and offsetdst to use only offsettzstring.
4019
4020 $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
4021 $dtts->setTimezone($tzo); // important: must be before the setTimestamp
4022 $dtts->setTimestamp($timetouse);
4023 } else {
4024 $timetouse = (int) $time + $offsettz + $offsetdst; // TODO We could be able to disable use of offsettz and offsetdst to use only offsettzstring.
4025
4026 $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
4027 $dtts->setTimestamp($timetouse); // TODO May be we can invert setTimestamp and setTimezone
4028 $dtts->setTimezone($tzo);
4029 }
4030
4031 $newformat = str_replace(
4032 array('%Y', '%y', '%m', '%d', '%H', '%I', '%M', '%S', '%p', '%w', 'T', 'Z', '__a__', '__A__', '__b__', '__B__'),
4033 array('Y', 'y', 'm', 'd', 'H', 'h', 'i', 's', 'A', 'w', '__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
4034 $format
4035 );
4036
4037 $ret = $dtts->format($newformat);
4038 //var_dump($timetouse, $offsettz, $offsetdst, $tzo, $newformat, $ret);
4039 $ret = str_replace(
4040 array('__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
4041 array('T', 'Z', '__a__', '__A__', '__b__', '__B__'),
4042 $ret
4043 );
4044 } else {
4045 $ret = 'Bad value ' . $time . ' for date';
4046 }
4047 }
4048
4049 if (preg_match('/__b__/i', $format)) {
4050 $timetouse = $time + $offsettz + $offsetdst; // TODO We could be able to disable use of offsettz and offsetdst to use only offsettzstring.
4051
4052 if ($to_gmt) {
4053 $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
4054 } else {
4055 $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
4056 }
4057 $dtts = new DateTime();
4058 $dtts->setTimestamp($timetouse);
4059 $dtts->setTimezone($tzo);
4060 $month = (int) $dtts->format("m");
4061 $month = sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'.
4062 if ($encodetooutput) {
4063 $monthtext = $outputlangs->transnoentities('Month' . $month);
4064 $monthtextshort = $outputlangs->transnoentities('MonthShort' . $month);
4065 } else {
4066 $monthtext = $outputlangs->transnoentitiesnoconv('Month' . $month);
4067 $monthtextshort = $outputlangs->transnoentitiesnoconv('MonthShort' . $month);
4068 }
4069 //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
4070 $ret = str_replace('__b__', $monthtextshort, $ret);
4071 $ret = str_replace('__B__', $monthtext, $ret);
4072 //print 'x'.$outputlangs->charset_output.'-'.$ret.'x';
4073 //return $ret;
4074 }
4075 if (preg_match('/__a__/i', $format)) {
4076 //print "time=$time offsettz=$offsettz offsetdst=$offsetdst offsettzstring=$offsettzstring";
4077 $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
4078
4079 if ($to_gmt) {
4080 $tzo = new DateTimeZone('UTC');
4081 } else {
4082 $tzo = new DateTimeZone(date_default_timezone_get());
4083 }
4084 $dtts = new DateTime();
4085 $dtts->setTimestamp($timetouse);
4086 $dtts->setTimezone($tzo);
4087 $w = $dtts->format("w");
4088 $dayweek = $outputlangs->transnoentitiesnoconv('Day' . $w);
4089
4090 $ret = str_replace('__A__', $dayweek, $ret);
4091 $ret = str_replace('__a__', dol_substr($dayweek, 0, 3), $ret);
4092 }
4093
4094 if ($decorate) {
4095 $ret = preg_replace('/(\d\d:\d\d [AP]M)$/', '<span class="'.($decorate === 1 ? 'opacitymedium' : $decorate).'">\1</span>', $ret);
4096 $ret = preg_replace('/(\d\d:\d\d)$/', '<span class="'.($decorate === 1 ? 'opacitymedium' : $decorate).'">\1</span>', $ret);
4097 }
4098
4099 return $ret;
4100}
4101
4102
4123function dol_getdate($timestamp, $fast = false, $forcetimezone = '')
4124{
4125 if ($timestamp === '') {
4126 return array();
4127 }
4128
4129 $datetimeobj = new DateTime();
4130 $datetimeobj->setTimestamp($timestamp); // Use local PHP server timezone
4131 if ($forcetimezone) {
4132 $datetimeobj->setTimezone(new DateTimeZone($forcetimezone == 'gmt' ? 'UTC' : $forcetimezone)); // (add timezone relative to the date entered)
4133 }
4134 $arrayinfo = array(
4135 'year' => ((int) date_format($datetimeobj, 'Y')),
4136 'mon' => ((int) date_format($datetimeobj, 'm')),
4137 'mday' => ((int) date_format($datetimeobj, 'd')),
4138 'wday' => ((int) date_format($datetimeobj, 'w')),
4139 'yday' => ((int) date_format($datetimeobj, 'z')),
4140 'hours' => ((int) date_format($datetimeobj, 'H')),
4141 'minutes' => ((int) date_format($datetimeobj, 'i')),
4142 'seconds' => ((int) date_format($datetimeobj, 's')),
4143 '0' => $timestamp
4144 );
4145
4146 return $arrayinfo;
4147}
4148
4170function dol_mktime($hour, $minute, $second, $month, $day, $year, $gm = 'auto', $check = 1)
4171{
4172 global $conf;
4173 //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
4174
4175 if ($gm === 'auto') {
4176 $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
4177 }
4178 //print 'gm:'.$gm.' gm === auto:'.($gm === 'auto').'<br>';exit;
4179
4180 // Clean parameters
4181 if ($hour == -1 || empty($hour)) {
4182 $hour = 0;
4183 }
4184 if ($minute == -1 || empty($minute)) {
4185 $minute = 0;
4186 }
4187 if ($second == -1 || empty($second)) {
4188 $second = 0;
4189 }
4190
4191 // Check parameters
4192 if ($check) {
4193 if (!$month || !$day) {
4194 return '';
4195 }
4196 if ($day > 31) {
4197 return '';
4198 }
4199 if ($month > 12) {
4200 return '';
4201 }
4202 if ($hour < 0 || $hour > 24) {
4203 return '';
4204 }
4205 if ($minute < 0 || $minute > 60) {
4206 return '';
4207 }
4208 if ($second < 0 || $second > 60) {
4209 return '';
4210 }
4211 }
4212
4213 if (empty($gm) || ($gm === 'server' || $gm === 'tzserver')) {
4214 $default_timezone = @date_default_timezone_get(); // Example 'Europe/Berlin'
4215 $localtz = new DateTimeZone($default_timezone);
4216 } elseif ($gm === 'user' || $gm === 'tzuser' || $gm === 'tzuserrel') {
4217 // We use dol_tz_string first because it is more reliable.
4218 $default_timezone = (empty($_SESSION["dol_tz_string"]) ? @date_default_timezone_get() : $_SESSION["dol_tz_string"]); // Example 'Europe/Berlin'
4219 try {
4220 $localtz = new DateTimeZone($default_timezone);
4221 } catch (Exception $e) {
4222 dol_syslog("Warning dol_tz_string contains an invalid value " . json_encode($_SESSION["dol_tz_string"] ?? null), LOG_WARNING);
4223 $default_timezone = @date_default_timezone_get();
4224 }
4225 } elseif (strrpos($gm, "tz,") !== false) {
4226 $timezone = str_replace("tz,", "", $gm); // Example 'tz,Europe/Berlin'
4227 try {
4228 $localtz = new DateTimeZone($timezone);
4229 } catch (Exception $e) {
4230 dol_syslog("Warning passed timezone contains an invalid value " . $timezone, LOG_WARNING);
4231 }
4232 }
4233
4234 if (empty($localtz)) {
4235 $localtz = new DateTimeZone('UTC');
4236 }
4237 $dt = new DateTime('now', $localtz);
4238 $dt->setDate((int) $year, (int) $month, (int) $day);
4239 $dt->setTime((int) $hour, (int) $minute, (int) $second);
4240 $date = $dt->getTimestamp(); // should include daylight saving time
4241
4242 return $date;
4243}
4244
4245
4256function dol_now($mode = 'gmt')
4257{
4258 $ret = 0;
4259
4260 if ($mode === 'auto') {
4261 $mode = 'gmt';
4262 }
4263
4264 if ($mode == 'gmt') {
4265 $ret = time(); // Time for now at greenwich.
4266 } elseif ($mode == 'tzserver') { // Time for now with PHP server timezone added
4267 require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
4268 $tzsecond = getServerTimeZoneInt('now'); // Contains tz+dayling saving time
4269 $ret = (int) (dol_now('gmt') + ($tzsecond * 3600));
4270 // } elseif ($mode == 'tzref') {// Time for now with parent company timezone is added
4271 // require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
4272 // $tzsecond=getParentCompanyTimeZoneInt(); // Contains tz+dayling saving time
4273 // $ret=dol_now('gmt')+($tzsecond*3600);
4274 } elseif ($mode == 'tzuser' || $mode == 'tzuserrel') {
4275 // Time for now with user timezone added
4276 // print 'time: '.time();
4277 $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60;
4278 $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60;
4279 $ret = (int) (dol_now('gmt') + ($offsettz + $offsetdst));
4280 }
4281
4282 return $ret;
4283}
4284
4285
4294function dol_print_size($size, $shortvalue = 0, $shortunit = 0)
4295{
4296 global $conf, $langs;
4297 $level = 1024;
4298
4299 if (!empty($conf->dol_optimize_smallscreen)) {
4300 $shortunit = 1;
4301 }
4302
4303 // Set value text
4304 if (empty($shortvalue) || $size < ($level * 10)) {
4305 $ret = $size;
4306 $textunitshort = $langs->trans("b");
4307 $textunitlong = $langs->trans("Bytes");
4308 } else {
4309 $ret = round($size / $level, 0);
4310 $textunitshort = $langs->trans("Kb");
4311 $textunitlong = $langs->trans("KiloBytes");
4312 }
4313 // Use long or short text unit
4314 if (empty($shortunit)) {
4315 $ret .= ' ' . $textunitlong;
4316 } else {
4317 $ret .= ' ' . $textunitshort;
4318 }
4319
4320 return $ret;
4321}
4322
4333function dol_print_url($url, $target = '_blank', $max = 32, $withpicto = 0, $morecss = '')
4334{
4335 global $langs;
4336
4337 if (empty($url)) {
4338 return '';
4339 }
4340
4341 $linkstart = '<a href="';
4342 if (!preg_match('/^http/i', $url)) {
4343 $linkstart .= 'http://';
4344 }
4345 $linkstart .= $url;
4346 $linkstart .= '"';
4347 if ($target) {
4348 $linkstart .= ' target="' . $target . '"';
4349 }
4350 $linkstart .= ' title="' . $langs->trans("URL") . ': ' . $url . '"';
4351 $linkstart .= '>';
4352
4353 $link = '';
4354 if (!preg_match('/^http/i', $url)) {
4355 $link .= 'http://';
4356 }
4357 $link .= dol_trunc($url, $max);
4358
4359 $linkend = '</a>';
4360
4361 if ($morecss == 'float') { // deprecated
4362 return '<div class="nospan' . ($morecss ? ' ' . $morecss : '') . '" style="margin-right: 10px">' . ($withpicto ? img_picto($langs->trans("Url"), 'globe', 'class="paddingrightonly"') : '') . $link . '</div>';
4363 } else {
4364 return $linkstart . '<span class="nospan' . ($morecss ? ' ' . $morecss : '') . '" style="margin-right: 10px">' . ($withpicto ? img_picto('', 'globe', 'class="paddingrightonly"') : '') . $link . '</span>' . $linkend;
4365 }
4366}
4367
4381function dol_print_email($email, $contactid = 0, $socid = 0, $addlink = 0, $max = 0, $showinvalid = 2, $withpicto = 0, $morecss = 'paddingrightonly')
4382{
4383 global $user, $langs, $hookmanager;
4384
4385 //global $conf; $conf->global->AGENDA_ADDACTIONFOREMAIL = 1;
4386 //$showinvalid = 1; $email = 'rrrrr';
4387
4388 $newemail = dol_escape_htmltag($email);
4389
4390 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') && $withpicto) {
4391 $withpicto = 0;
4392 }
4393
4394 if (empty($email)) {
4395 return '&nbsp;';
4396 }
4397
4398 if ($addlink == 1) {
4399 $newemail = '<a class="' . ($morecss ? $morecss : '') . '" style="text-overflow: ellipsis;" href="';
4400 if (!preg_match('/^mailto:/i', $email)) {
4401 $newemail .= 'mailto:';
4402 }
4403 $newemail .= $email;
4404 $newemail .= '" target="_blank">';
4405
4406 $newemail .= ($withpicto ? img_picto($langs->trans("EMail") . ' : ' . $email, (is_numeric($withpicto) ? 'email' : $withpicto), 'class="paddingrightonly"') : '');
4407
4408 if ($max > 0) {
4409 $newemail .= dol_trunc($email, $max);
4410 } else {
4411 $newemail .= $email;
4412 }
4413 $newemail .= '</a>';
4414
4415 if ($showinvalid) {
4416 include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
4417 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
4418 $emailonly = CMailFile::getValidAddress($email, 2);
4419 if (!isValidEmail($emailonly)) {
4420 $langs->load("errors");
4421 $newemail .= img_warning($langs->transnoentitiesnoconv("ErrorBadEMail", $emailonly), '', 'paddingrightonly');
4422 } elseif ($showinvalid == 2 && !isValidMailDomain($emailonly)) {
4423 $langs->load("errors");
4424 $newemail .= img_warning($langs->transnoentitiesnoconv("ErrorBadMXDomain", $emailonly), '', 'paddingrightonly');
4425 }
4426 }
4427
4428 if (($contactid || $socid) && isModEnabled('agenda') && $user->hasRight("agenda", "myactions", "create")) {
4429 $type = 'AC_EMAIL';
4430 $linktoaddaction = '';
4431 if (getDolGlobalString('AGENDA_ADDACTIONFOREMAIL')) {
4432 $linktoaddaction = '<a href="' . DOL_URL_ROOT . '/comm/action/card.php?action=create&amp;backtopage=1&amp;actioncode=' . urlencode($type) . '&amp;contactid=' . ((int) $contactid) . '&amp;socid=' . ((int) $socid) . '">' . img_object($langs->trans("AddAction"), "calendar") . '</a>';
4433 }
4434 if ($linktoaddaction) {
4435 $newemail = '<div>' . $newemail . ' ' . $linktoaddaction . '</div>';
4436 }
4437 }
4438 } elseif ($addlink === 'thirdparty') {
4439 $tmpnewemail = '<a class="' . ($morecss ? $morecss : '') . '" style="text-overflow: ellipsis;" href="' . DOL_URL_ROOT . '/societe/card.php?socid=' . $socid . '&action=presend&mode=init#formmailbeforetitle">';
4440 $tmpnewemail .= ($withpicto ? img_picto($langs->trans("EMail") . ' : ' . $email, (is_numeric($withpicto) ? 'email' : $withpicto), 'class="paddingrightonly"') : '');
4441 if ($withpicto == 1) {
4442 $tmpnewemail .= $newemail;
4443 }
4444 $tmpnewemail .= '</a>';
4445
4446 $newemail = $tmpnewemail;
4447 } else {
4448 $newemail = ($withpicto ? img_picto($langs->trans("EMail") . ' : ' . $email, (is_numeric($withpicto) ? 'email' : $withpicto), 'class="paddingrightonly"') : '') . $newemail;
4449
4450 if ($showinvalid) {
4451 include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
4452 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
4453 $emailonly = CMailFile::getValidAddress($email, 2);
4454 if (!isValidEmail($emailonly)) {
4455 $langs->load("errors");
4456 $newemail .= img_warning($langs->transnoentitiesnoconv("ErrorBadEMail", $email));
4457 } elseif ($showinvalid == 2 && !isValidMailDomain($emailonly)) {
4458 $langs->load("errors");
4459 $newemail .= img_warning($langs->transnoentitiesnoconv("ErrorBadMXDomain", $emailonly));
4460 }
4461 }
4462 }
4463
4464 //$rep = '<div class="nospan" style="margin-right: 10px">';
4465 //$rep = ($withpicto ? img_picto($langs->trans("EMail").' : '.$email, (is_numeric($withpicto) ? 'email' : $withpicto), 'class="paddingrightonly"') : '').$newemail;
4466 //$rep .= '</div>';
4467 $rep = $newemail;
4468
4469 if ($hookmanager) {
4470 $parameters = array('cid' => $contactid, 'socid' => $socid, 'addlink' => $addlink, 'picto' => $withpicto);
4471
4472 $reshook = $hookmanager->executeHooks('printEmail', $parameters, $email);
4473 if ($reshook > 0) {
4474 $rep = '';
4475 }
4476 $rep .= $hookmanager->resPrint;
4477 }
4478
4479 return $rep;
4480}
4481
4487function getArrayOfSocialNetworks()
4488{
4489 global $db;
4490
4491 $socialnetworks = array();
4492 // Enable caching of array
4493 require_once DOL_DOCUMENT_ROOT . '/core/lib/memory.lib.php';
4494 $cachekey = dol_sanitizeKeyCode(str_replace(',', '_', 'socialnetworks_'.getEntity('c_socialnetworks')));
4495 $dataretrieved = dol_getcache($cachekey);
4496
4497 if (!is_null($dataretrieved)) {
4498 $socialnetworks = $dataretrieved;
4499 } else {
4500 $sql = "SELECT rowid, code, label, url, icon, active FROM " . MAIN_DB_PREFIX . "c_socialnetworks";
4501 $sql .= " WHERE entity IN (" . getEntity('c_socialnetworks').")";
4502
4503 $resql = $db->query($sql);
4504 if ($resql) {
4505 while ($obj = $db->fetch_object($resql)) {
4506 $socialnetworks[$obj->code] = array(
4507 'rowid' => $obj->rowid,
4508 'label' => $obj->label,
4509 'url' => $obj->url,
4510 'icon' => $obj->icon,
4511 'active' => $obj->active,
4512 );
4513 }
4514 }
4515 dol_setcache($cachekey, $socialnetworks); // If setting cache fails, this is not a problem, so we do not test result.
4516 }
4517
4518 return (is_array($socialnetworks) ? $socialnetworks : array());
4519}
4520
4531function dol_print_socialnetworks($value, $contactid, $socid, $type, $dictsocialnetworks = array())
4532{
4533 global $hookmanager, $langs, $user;
4534
4535 $htmllink = $value;
4536
4537 if (empty($value)) {
4538 return '&nbsp;';
4539 }
4540
4541 if (!empty($type)) {
4542 $htmllink = '<div class="divsocialnetwork inline-block valignmiddle">';
4543 // Use dictionary definition for picto $dictsocialnetworks[$type]['icon']
4544 $htmllink .= '<span class="fab pictofixedwidth ' . ($dictsocialnetworks[$type]['icon'] ? $dictsocialnetworks[$type]['icon'] : 'fa-link') . '"></span>';
4545 if ($type == 'skype') {
4546 $htmllink .= dol_escape_htmltag($value);
4547 $htmllink .= '&nbsp; <a href="skype:';
4548 $htmllink .= dol_string_nospecial($value, '_', '', array('@'));
4549 $htmllink .= '?call" alt="' . $langs->trans("Call") . '&nbsp;' . $value . '" title="' . dol_escape_htmltag($langs->trans("Call") . ' ' . $value) . '">';
4550 $htmllink .= '<img src="' . DOL_URL_ROOT . '/theme/common/skype_callbutton.png" border="0">';
4551 $htmllink .= '</a><a href="skype:';
4552 $htmllink .= dol_string_nospecial($value, '_', '', array('@'));
4553 $htmllink .= '?chat" alt="' . $langs->trans("Chat") . '&nbsp;' . $value . '" title="' . dol_escape_htmltag($langs->trans("Chat") . ' ' . $value) . '">';
4554 $htmllink .= '<img class="paddingleft" src="' . DOL_URL_ROOT . '/theme/common/skype_chatbutton.png" border="0">';
4555 $htmllink .= '</a>';
4556 if (($contactid || $socid) && isModEnabled('agenda') && $user->hasRight('agenda', 'myactions', 'create')) {
4557 $addlink = 'AC_SKYPE';
4558 $link = '';
4559 if (getDolGlobalString('AGENDA_ADDACTIONFORSKYPE')) {
4560 $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>';
4561 }
4562 $htmllink .= ($link ? ' ' . $link : '');
4563 }
4564 } else {
4565 if (!empty($dictsocialnetworks[$type]['url'])) {
4566 $tmpvirginurl = preg_replace('/\/?{socialid}/', '', $dictsocialnetworks[$type]['url']);
4567 if ($tmpvirginurl) {
4568 $value = preg_replace('/^www\.' . preg_quote($tmpvirginurl, '/') . '\/?/', '', $value);
4569 $value = preg_replace('/^' . preg_quote($tmpvirginurl, '/') . '\/?/', '', $value);
4570
4571 $tmpvirginurl3 = preg_replace('/^https:\/\//i', 'https://www.', $tmpvirginurl);
4572 if ($tmpvirginurl3) {
4573 $value = preg_replace('/^www\.' . preg_quote($tmpvirginurl3, '/') . '\/?/', '', $value);
4574 $value = preg_replace('/^' . preg_quote($tmpvirginurl3, '/') . '\/?/', '', $value);
4575 }
4576
4577 $tmpvirginurl2 = preg_replace('/^https?:\/\//i', '', $tmpvirginurl);
4578 if ($tmpvirginurl2) {
4579 $value = preg_replace('/^www\.' . preg_quote($tmpvirginurl2, '/') . '\/?/', '', $value);
4580 $value = preg_replace('/^' . preg_quote($tmpvirginurl2, '/') . '\/?/', '', $value);
4581 }
4582 }
4583 if (preg_match('/^https?:\/\//i', $value)) {
4584 $link = $value;
4585 } else {
4586 $link = str_replace('{socialid}', $value, $dictsocialnetworks[$type]['url']);
4587 }
4588 $valuetoshow = $value;
4589 $valuetoshow = preg_replace('/https:\/\/www\.(twitter|x|linkedin)\.com\/?/', '', $valuetoshow);
4590 if (preg_match('/^https?:\/\//i', $link)) {
4591 $htmllink .= '<a href="' . dol_sanitizeUrl($link, 0) . '" target="_blank" rel="noopener noreferrer">' . dol_escape_htmltag($valuetoshow) . '</a>';
4592 } else {
4593 $htmllink .= '<a href="' . dol_sanitizeUrl($link, 1) . '" target="_blank" rel="noopener noreferrer">' . dol_escape_htmltag($valuetoshow) . '</a>';
4594 }
4595 } else {
4596 $htmllink .= dol_escape_htmltag($value);
4597 }
4598 }
4599 $htmllink .= '</div>';
4600 } else {
4601 $langs->load("errors");
4602 $htmllink .= img_warning($langs->trans("ErrorBadSocialNetworkValue", $value));
4603 }
4604
4605 if ($hookmanager) {
4606 $parameters = array(
4607 'value' => $value,
4608 'cid' => $contactid,
4609 'socid' => $socid,
4610 'type' => $type,
4611 'dictsocialnetworks' => $dictsocialnetworks,
4612 );
4613
4614 $reshook = $hookmanager->executeHooks('printSocialNetworks', $parameters);
4615 if ($reshook > 0) {
4616 $htmllink = '';
4617 }
4618 $htmllink .= $hookmanager->resPrint;
4619 }
4620
4621 return $htmllink;
4622}
4623
4633function dol_print_profids($profID, $profIDtype, $countrycode = '', $addcpButton = 1)
4634{
4635 global $mysoc;
4636
4637 if (empty($profID) || empty($profIDtype)) {
4638 return '';
4639 }
4640 if (empty($countrycode)) {
4641 $countrycode = $mysoc->country_code;
4642 }
4643 $newProfID = $profID;
4644 $id = substr($profIDtype, -1);
4645 $ret = '';
4646 if (strtoupper($countrycode) == 'FR') {
4647 // France
4648 // (see https://www.economie.gouv.fr/entreprises/numeros-identification-entreprise)
4649
4650 if ($id == 1 && dol_strlen($newProfID) == 9) {
4651 // SIREN (ex: 123 123 123)
4652 $newProfID = substr($newProfID, 0, 3) . ' ' . substr($newProfID, 3, 3) . ' ' . substr($newProfID, 6, 3);
4653 }
4654 if ($id == 2 && dol_strlen($newProfID) == 14) {
4655 // SIRET (ex: 123 123 123 12345)
4656 $newProfID = substr($newProfID, 0, 3) . ' ' . substr($newProfID, 3, 3) . ' ' . substr($newProfID, 6, 3) . ' ' . substr($newProfID, 9, 5);
4657 }
4658 if ($id == 3 && dol_strlen($newProfID) == 5) {
4659 // NAF/APE (ex: 69.20Z)
4660 $newProfID = substr($newProfID, 0, 2) . '.' . substr($newProfID, 2, 3);
4661 }
4662 if ($profIDtype === 'VAT' && dol_strlen($newProfID) == 13) {
4663 // TVA intracommunautaire (ex: FR12 123 123 123)
4664 $newProfID = substr($newProfID, 0, 4) . ' ' . substr($newProfID, 4, 3) . ' ' . substr($newProfID, 7, 3) . ' ' . substr($newProfID, 10, 3);
4665 }
4666 }
4667 if (!empty($addcpButton)) {
4668 $ret = showValueWithClipboardCPButton(dol_escape_htmltag($profID), ($addcpButton == 1 ? 1 : 0), $newProfID);
4669 } else {
4670 $ret = $newProfID;
4671 }
4672 return $ret;
4673}
4674
4690function dol_print_phone($phone, $countrycode = '', $contactid = 0, $socid = 0, $addlink = '', $separ = "&nbsp;", $withpicto = '', $titlealt = '', $adddivfloat = 0, $morecss = 'paddingright')
4691{
4692 global $conf, $user, $langs, $mysoc, $hookmanager;
4693
4694 // Clean phone parameter
4695 $phone = is_null($phone) ? '' : preg_replace("/[\s.-]/", "", trim($phone));
4696 if (empty($phone)) {
4697 return '';
4698 }
4699 if (getDolGlobalString('MAIN_PHONE_SEPAR')) {
4700 $separ = getDolGlobalString('MAIN_PHONE_SEPAR');
4701 }
4702 if (empty($countrycode) && is_object($mysoc)) {
4703 $countrycode = $mysoc->country_code;
4704 }
4705
4706 // Short format for small screens
4707 if (!empty($conf->dol_optimize_smallscreen) && $separ != 'hidenum') {
4708 $separ = '';
4709 }
4710
4711 $newphone = $phone;
4712 $newphonewa = $phone;
4713 if (strtoupper($countrycode) == "FR") {
4714 // France
4715 if (dol_strlen($phone) == 10) {
4716 $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);
4717 } elseif (dol_strlen($phone) == 7) {
4718 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 2) . $separ . substr($newphone, 5, 2);
4719 } elseif (dol_strlen($phone) == 9) {
4720 $newphone = substr($newphone, 0, 2) . $separ . substr($newphone, 2, 3) . $separ . substr($newphone, 5, 2) . $separ . substr($newphone, 7, 2);
4721 } elseif (dol_strlen($phone) == 11) {
4722 $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);
4723 } elseif (dol_strlen($phone) == 12) {
4724 $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);
4725 } elseif (dol_strlen($phone) == 13) {
4726 $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);
4727 }
4728 } elseif (strtoupper($countrycode) == "CA") {
4729 if (dol_strlen($phone) == 10) {
4730 $newphone = ($separ != '' ? '(' : '') . substr($newphone, 0, 3) . ($separ != '' ? ')' : '') . $separ . substr($newphone, 3, 3) . ($separ != '' ? '-' : '') . substr($newphone, 6, 4);
4731 }
4732 } elseif (strtoupper($countrycode) == "PT") { //Portugal
4733 if (dol_strlen($phone) == 13) { //ex: +351_ABC_DEF_GHI
4734 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 3) . $separ . substr($newphone, 10, 3);
4735 }
4736 } elseif (strtoupper($countrycode) == "SR") { //Suriname
4737 if (dol_strlen($phone) == 10) { //ex: +597_ABC_DEF
4738 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 3);
4739 } elseif (dol_strlen($phone) == 11) { //ex: +597_ABC_DEFG
4740 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 4);
4741 }
4742 } elseif (strtoupper($countrycode) == "DE") { //Allemagne
4743 if (dol_strlen($phone) == 14) { //ex: +49_ABCD_EFGH_IJK
4744 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 4) . $separ . substr($newphone, 7, 4) . $separ . substr($newphone, 11, 3);
4745 } elseif (dol_strlen($phone) == 13) { //ex: +49_ABC_DEFG_HIJ
4746 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 4) . $separ . substr($newphone, 10, 3);
4747 }
4748 } elseif (strtoupper($countrycode) == "ES") { //Espagne
4749 if (dol_strlen($phone) == 12) { //ex: +34_ABC_DEF_GHI
4750 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 3) . $separ . substr($newphone, 9, 3);
4751 }
4752 } elseif (strtoupper($countrycode) == "BF") { // Burkina Faso
4753 if (dol_strlen($phone) == 12) { //ex : +22 A BC_DE_FG_HI
4754 $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);
4755 }
4756 } elseif (strtoupper($countrycode) == "RO") { // Roumanie
4757 if (dol_strlen($phone) == 12) { //ex : +40 AB_CDE_FG_HI
4758 $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);
4759 }
4760 } elseif (strtoupper($countrycode) == "TR") { //Turquie
4761 if (dol_strlen($phone) == 13) { //ex : +90 ABC_DEF_GHIJ
4762 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 3) . $separ . substr($newphone, 9, 4);
4763 }
4764 } elseif (strtoupper($countrycode) == "US") { //Etat-Unis
4765 if (dol_strlen($phone) == 12) { //ex: +1 ABC_DEF_GHIJ
4766 $newphone = substr($newphone, 0, 2) . $separ . substr($newphone, 2, 3) . $separ . substr($newphone, 5, 3) . $separ . substr($newphone, 8, 4);
4767 }
4768 } elseif (strtoupper($countrycode) == "MX") { //Mexique
4769 if (dol_strlen($phone) == 12) { //ex: +52 ABCD_EFG_HI
4770 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 4) . $separ . substr($newphone, 7, 3) . $separ . substr($newphone, 10, 2);
4771 } elseif (dol_strlen($phone) == 11) { //ex: +52 AB_CD_EF_GH
4772 $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);
4773 } elseif (dol_strlen($phone) == 13) { //ex: +52 ABC_DEF_GHIJ
4774 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 3) . $separ . substr($newphone, 9, 4);
4775 }
4776 } elseif (strtoupper($countrycode) == "ML") { //Mali
4777 if (dol_strlen($phone) == 12) { //ex: +223 AB_CD_EF_GH
4778 $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);
4779 }
4780 } elseif (strtoupper($countrycode) == "TH") { //Thaïlande
4781 if (dol_strlen($phone) == 11) { //ex: +66_ABC_DE_FGH
4782 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 2) . $separ . substr($newphone, 8, 3);
4783 } elseif (dol_strlen($phone) == 12) { //ex: +66_A_BCD_EF_GHI
4784 $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);
4785 }
4786 } elseif (strtoupper($countrycode) == "MU") {
4787 //Maurice
4788 if (dol_strlen($phone) == 11) { //ex: +230_ABC_DE_FG
4789 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 2) . $separ . substr($newphone, 9, 2);
4790 } elseif (dol_strlen($phone) == 12) { //ex: +230_ABCD_EF_GH
4791 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 4) . $separ . substr($newphone, 8, 2) . $separ . substr($newphone, 10, 2);
4792 }
4793 } elseif (strtoupper($countrycode) == "ZA") { //Afrique du sud
4794 if (dol_strlen($phone) == 12) { //ex: +27_AB_CDE_FG_HI
4795 $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);
4796 }
4797 } elseif (strtoupper($countrycode) == "SY") { //Syrie
4798 if (dol_strlen($phone) == 12) { //ex: +963_AB_CD_EF_GH
4799 $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);
4800 } elseif (dol_strlen($phone) == 13) { //ex: +963_AB_CD_EF_GHI
4801 $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);
4802 }
4803 } elseif (strtoupper($countrycode) == "AE") { //Emirats Arabes Unis
4804 if (dol_strlen($phone) == 12) { //ex: +971_ABC_DEF_GH
4805 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 3) . $separ . substr($newphone, 10, 2);
4806 } elseif (dol_strlen($phone) == 13) { //ex: +971_ABC_DEF_GHI
4807 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 3) . $separ . substr($newphone, 10, 3);
4808 } elseif (dol_strlen($phone) == 14) { //ex: +971_ABC_DEF_GHIK
4809 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 3) . $separ . substr($newphone, 10, 4);
4810 }
4811 } elseif (strtoupper($countrycode) == "DZ") { //Algérie
4812 if (dol_strlen($phone) == 13) { //ex: +213_ABC_DEF_GHI
4813 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 3) . $separ . substr($newphone, 10, 3);
4814 }
4815 } elseif (strtoupper($countrycode) == "BE") { //Belgique
4816 if (dol_strlen($phone) == 11) { //ex: +32_ABC_DE_FGH
4817 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 2) . $separ . substr($newphone, 8, 3);
4818 } elseif (dol_strlen($phone) == 12) { //ex: +32_ABC_DEF_GHI
4819 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 3) . $separ . substr($newphone, 9, 3);
4820 }
4821 } elseif (strtoupper($countrycode) == "PF") { //Polynésie française
4822 if (dol_strlen($phone) == 12) { //ex: +689_AB_CD_EF_GH
4823 $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);
4824 }
4825 } elseif (strtoupper($countrycode) == "CO") { //Colombie
4826 if (dol_strlen($phone) == 13) { //ex: +57_ABC_DEF_GH_IJ
4827 $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);
4828 }
4829 } elseif (strtoupper($countrycode) == "JO") { //Jordanie
4830 if (dol_strlen($phone) == 12) { //ex: +962_A_BCD_EF_GH
4831 $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);
4832 }
4833 } elseif (strtoupper($countrycode) == "JM") { //Jamaïque
4834 if (dol_strlen($newphone) == 12) { //ex: +1867_ABC_DEFG
4835 $newphone = substr($newphone, 0, 5) . $separ . substr($newphone, 5, 3) . $separ . substr($newphone, 8, 4);
4836 }
4837 } elseif (strtoupper($countrycode) == "MG") { //Madagascar
4838 if (dol_strlen($phone) == 13) { //ex: +261_AB_CD_EFG_HI
4839 $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);
4840 }
4841 } elseif (strtoupper($countrycode) == "GB") { //Royaume uni
4842 if (dol_strlen($phone) == 13) { //ex: +44_ABCD_EFG_HIJ
4843 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 4) . $separ . substr($newphone, 7, 3) . $separ . substr($newphone, 10, 3);
4844 }
4845 } elseif (strtoupper($countrycode) == "CH") { //Suisse
4846 if (dol_strlen($phone) == 12) { //ex: +41_AB_CDE_FG_HI
4847 $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);
4848 } elseif (dol_strlen($phone) == 15) { // +41_AB_CDE_FGH_IJKL
4849 $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);
4850 }
4851 } elseif (strtoupper($countrycode) == "TN") { //Tunisie
4852 if (dol_strlen($phone) == 12) { //ex: +216_AB_CDE_FGH
4853 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 2) . $separ . substr($newphone, 6, 3) . $separ . substr($newphone, 9, 3);
4854 }
4855 } elseif (strtoupper($countrycode) == "GF") { //Guyane francaise
4856 if (dol_strlen($phone) == 13) { //ex: +594_ABC_DE_FG_HI (ABC=594 de nouveau)
4857 $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);
4858 }
4859 } elseif (strtoupper($countrycode) == "GP") { //Guadeloupe
4860 if (dol_strlen($phone) == 13) { //ex: +590_ABC_DE_FG_HI (ABC=590 de nouveau)
4861 $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);
4862 }
4863 } elseif (strtoupper($countrycode) == "MQ") { //Martinique
4864 if (dol_strlen($phone) == 13) { //ex: +596_ABC_DE_FG_HI (ABC=596 de nouveau)
4865 $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);
4866 }
4867 } elseif (strtoupper($countrycode) == "IT") { //Italie
4868 if (dol_strlen($phone) == 12) { //ex: +39_ABC_DEF_GHI
4869 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 3) . $separ . substr($newphone, 9, 3);
4870 } elseif (dol_strlen($phone) == 13) { //ex: +39_ABC_DEF_GH_IJ
4871 $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);
4872 }
4873 } elseif (strtoupper($countrycode) == "AU") {
4874 //Australie
4875 if (dol_strlen($phone) == 12) {
4876 //ex: +61_A_BCDE_FGHI
4877 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 1) . $separ . substr($newphone, 4, 4) . $separ . substr($newphone, 8, 4);
4878 }
4879 } elseif (strtoupper($countrycode) == "LU") {
4880 // Luxembourg
4881 if (dol_strlen($phone) == 10) { // fix 6 digits +352_AA_BB_CC
4882 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 2) . $separ . substr($newphone, 6, 2) . $separ . substr($newphone, 8, 2);
4883 } elseif (dol_strlen($phone) == 11) { // fix 7 digits +352_AA_BB_CC_D
4884 $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);
4885 } elseif (dol_strlen($phone) == 12) { // fix 8 digits +352_AA_BB_CC_DD
4886 $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);
4887 } elseif (dol_strlen($phone) == 13) { // mobile +352_AAA_BB_CC_DD
4888 $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);
4889 }
4890 } elseif (strtoupper($countrycode) == "PE") {
4891 // Peru
4892 if (dol_strlen($phone) == 7) { // fix 7 chiffres without code AAA_BBBB
4893 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 4);
4894 } elseif (dol_strlen($phone) == 9) { // mobile add code and fix 9 chiffres +51_AAA_BBB_CCC
4895 $newphonewa = '+51' . $newphone;
4896 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 3);
4897 } elseif (dol_strlen($phone) == 11) { // fix 11 chiffres +511_AAA_BBBB
4898 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 4);
4899 } elseif (dol_strlen($phone) == 12) { // mobile +51_AAA_BBB_CCC
4900 $newphonewa = $newphone;
4901 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 3) . $separ . substr($newphone, 9, 3);
4902 }
4903 } elseif (strtoupper($countrycode) == "IN") { //India
4904 if (dol_strlen($phone) == 13) {
4905 if ($withpicto == 'phone') { //ex: +91_AB_CDEF_GHIJ
4906 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 2) . $separ . substr($newphone, 5, 4) . $separ . substr($newphone, 9, 4);
4907 } else { //ex: +91_ABCDE_FGHIJ
4908 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 5) . $separ . substr($newphone, 8, 5);
4909 }
4910 }
4911 }
4912
4913 $newphoneastart = $newphoneaend = '';
4914 if (!empty($addlink)) { // Link on phone number (+ link to add action if conf->global->AGENDA_ADDACTIONFORPHONE set)
4915 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
4916 // Keep the leading '+' of international numbers: it is allowed in a tel: URI (RFC 3966) and many
4917 // softphones/CTI handlers do not decode '%2B', so they drop the '%' and dial a wrong leading '2'.
4918 // Spaces were removed above, so a '+' produced here can only come from a real '+'.
4919 $newphoneastart = '<a href="tel:' . str_replace('%2B', '+', urlencode($phone)) . '">';
4920 $newphoneaend .= '</a>';
4921 } elseif (isModEnabled('clicktodial') && $addlink == 'AC_TEL') { // If click to dial, we use click to dial url
4922 if (empty($user->clicktodial_loaded)) {
4923 $user->fetch_clicktodial();
4924 }
4925
4926 // Define urlmask
4927 $urlmask = getDolGlobalString('CLICKTODIAL_URL', 'ErrorClickToDialModuleNotConfigured');
4928 if (!empty($user->clicktodial_url)) {
4929 $urlmask = $user->clicktodial_url;
4930 }
4931
4932 $clicktodial_poste = (!empty($user->clicktodial_poste) ? urlencode($user->clicktodial_poste) : '');
4933 $clicktodial_login = (!empty($user->clicktodial_login) ? urlencode($user->clicktodial_login) : '');
4934 $clicktodial_password = (!empty($user->clicktodial_password) ? urlencode($user->clicktodial_password) : '');
4935 // This line is for backward compatibility @phan-suppress-next-line PhanPluginPrintfVariableFormatString
4936 $url = sprintf($urlmask, urlencode($phone), $clicktodial_poste, $clicktodial_login, $clicktodial_password);
4937 // Those lines are for substitution
4938 $substitarray = array(
4939 '__PHONEFROM__' => $clicktodial_poste,
4940 '__PHONETO__' => urlencode($phone),
4941 '__LOGIN__' => $clicktodial_login,
4942 '__PASS__' => $clicktodial_password
4943 );
4944 $url = make_substitutions($url, $substitarray);
4945 if (!getDolGlobalString('CLICKTODIAL_DO_NOT_USE_AJAX_CALL')) {
4946 // Default and recommended: New method using ajax without submitting a page making a javascript history.go(-1) back
4947 $newphoneastart = '<a href="' . $url . '" class="cssforclicktodial">'; // Call of ajax is handled by the lib_foot.js.php on class 'cssforclicktodial'
4948 $newphoneaend = '</a>';
4949 } else {
4950 // Old method
4951 $newphoneastart = '<a href="' . $url . '"';
4952 if (getDolGlobalString('CLICKTODIAL_FORCENEWTARGET')) {
4953 $newphoneastart .= ' target="_blank" rel="noopener noreferrer"';
4954 }
4955 $newphoneastart .= '>';
4956 $newphoneaend .= '</a>';
4957 }
4958 }
4959
4960 //if (($contactid || $socid) && isModEnabled('agenda') && $user->hasRight('agenda', 'myactions', 'create'))
4961 if (isModEnabled('agenda') && $user->hasRight("agenda", "myactions", "create")) {
4962 $type = 'AC_TEL';
4963 $addlinktoagenda = '';
4964 if ($addlink == 'AC_FAX') {
4965 $type = 'AC_FAX';
4966 }
4967 if (getDolGlobalString('AGENDA_ADDACTIONFORPHONE')) {
4968 $addlinktoagenda = '<a href="' . DOL_URL_ROOT . '/comm/action/card.php?action=create&amp;backtopage=' . urlencode($_SERVER['REQUEST_URI']) . '&amp;actioncode=' . $type . ($contactid ? '&amp;contactid=' . $contactid : '') . ($socid ? '&amp;socid=' . $socid : '') . '">' . img_object($langs->trans("AddAction"), "calendar") . '</a>';
4969 }
4970 if ($addlinktoagenda) {
4971 $newphone = '<span>' . $newphone . ' ' . $addlinktoagenda . '</span>';
4972 }
4973 }
4974 }
4975
4976 if (getDolGlobalString('CONTACT_PHONEMOBILE_SHOW_LINK_TO_WHATSAPP') && $withpicto == 'mobile') {
4977 // Link to Whatsapp
4978 $newphone .= ' <a href="https://wa.me/' . $newphonewa . '" target="_blank"'; // Use api to whatasapp contacts
4979 $newphone .= '><span class="paddingright fab fa-whatsapp" style="color:#25D366;" title="WhatsApp"></span></a>';
4980 }
4981
4982 if (empty($titlealt)) {
4983 $titlealt = ($withpicto == 'fax' ? $langs->trans("Fax") : $langs->trans("Phone"));
4984 }
4985 $rep = '';
4986
4987 if ($hookmanager) {
4988 $parameters = array('countrycode' => $countrycode, 'cid' => $contactid, 'socid' => $socid, 'titlealt' => $titlealt, 'picto' => $withpicto);
4989 $reshook = $hookmanager->executeHooks('printPhone', $parameters, $phone);
4990 $rep .= $hookmanager->resPrint;
4991 }
4992 if (empty($reshook)) {
4993 $picto = '';
4994 if ($withpicto) {
4995 if ($withpicto == 'fax') {
4996 $picto = 'phoning_fax';
4997 } elseif ($withpicto == 'phone') {
4998 $picto = 'phone';
4999 } elseif ($withpicto == 'mobile') {
5000 $picto = 'phoning_mobile';
5001 } else {
5002 $picto = '';
5003 }
5004 }
5005 if ($adddivfloat == 1) {
5006 $rep .= '<div class="nospan float' . ($morecss ? ' ' . $morecss : '') . '">';
5007 } elseif (empty($adddivfloat)) {
5008 $rep .= '<span' . ($morecss ? ' class="' . $morecss . '"' : '') . '>';
5009 }
5010
5011 $rep .= $newphoneastart;
5012 $rep .= ($withpicto ? img_picto($titlealt, $picto) : '');
5013 if ($separ != 'hidenum') {
5014 $rep .= ($withpicto ? ' ' : '') . $newphone;
5015 }
5016 $rep .= $newphoneaend;
5017
5018 if ($adddivfloat == 1) {
5019 $rep .= '</div>';
5020 } elseif (empty($adddivfloat)) {
5021 $rep .= '</span>';
5022 }
5023 }
5024
5025 return $rep;
5026}
5027
5036function dol_print_ip($ip, $mode = 0, $showname = 0)
5037{
5038 global $conf;
5039
5040 $ret = '';
5041 if (!isset($conf->cache['resolveips'])) {
5042 $conf->cache['resolveips'] = array();
5043 }
5044
5045 if ($mode != 2) {
5046 $countrycode = dolGetCountryCodeFromIp($ip);
5047 if ($countrycode) { // If success, countrycode is us, fr, ...
5048 if (file_exists(DOL_DOCUMENT_ROOT . '/theme/common/flags/' . $countrycode . '.png')) {
5049 $ret .= picto_from_langcode($countrycode);
5050 } else {
5051 $ret .= '(' . $countrycode . ')';
5052 }
5053 $ret .= '&nbsp;';
5054 } else {
5055 // Nothing
5056 }
5057 }
5058
5059 if (in_array($mode, [0, 2])) {
5060 $domain = '';
5061 if ($showname) {
5062 if (!array_key_exists($ip, $conf->cache['resolveips'])) {
5063 $domain = gethostbyaddr($ip);
5064 $conf->cache['resolveips'][$ip] = $domain; // false or domain
5065 } else {
5066 $domain = $conf->cache['resolveips'][$ip];
5067 }
5068 }
5069 if ($domain) {
5070 $ret .= $domain;
5071 } else {
5072 $ret .= $ip;
5073 }
5074 }
5075
5076 return $ret;
5077}
5078
5091function getUserRemoteIP($trusted = 0)
5092{
5093 if ($trusted) { // Return only IP we can rely on (not spoofable by the client)
5094 $ip = (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']); // value may be the IP of a proxy
5095 // 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)
5096 // This can happen if the proxy were added in the list of trusted proxy.
5097 return $ip;
5098 }
5099
5100 // Try to guess the real IP of client (but this may not be reliable)
5101 if (empty($_SERVER['HTTP_X_FORWARDED_FOR']) || preg_match('/[^0-9\.\:,\[\]\s]/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {
5102 if (empty($_SERVER['HTTP_CLIENT_IP']) || preg_match('/[^0-9\.\:,\[\]\s]/', $_SERVER['HTTP_CLIENT_IP'])) {
5103 if (empty($_SERVER["HTTP_CF_CONNECTING_IP"])) {
5104 $ip = (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']); // value may be the IP of the proxy and not the client
5105 } else {
5106 $ip = $_SERVER["HTTP_CF_CONNECTING_IP"]; // value here may have been forged by client
5107 }
5108 } else {
5109 $ip = preg_replace('/,.*$/', '', $_SERVER['HTTP_CLIENT_IP']); // value is clean here but may have been forged by proxy
5110 }
5111 } else {
5112 $ip = preg_replace('/,.*$/', '', $_SERVER['HTTP_X_FORWARDED_FOR']); // value is clean here but may have been forged by proxy
5113 }
5114 return $ip;
5115}
5116
5125function isHTTPS()
5126{
5127 $isSecure = false;
5128 if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
5129 $isSecure = true;
5130 } 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') {
5131 $isSecure = true;
5132 }
5133 return $isSecure;
5134}
5135
5142function dolGetCountryCodeFromIp($ip)
5143{
5144 $countrycode = '';
5145
5146 if (isModEnabled('geoipmaxmind')) {
5147 if (getDolGlobalString('GEOIP_VERSION') == 'php') {
5148 $datafile = getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE');
5149 } else {
5150 $diroffile = getMultidirOutput(null, 'geoipmaxmind');
5151 $datafile = $diroffile . '/' . getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE_EMBEDDED');
5152 }
5153 //$ip='24.24.24.24';
5154 //$datafile='/usr/share/GeoIP/GeoIP.dat'; Note that this must be downloaded datafile (not same than datafile provided with ubuntu packages)
5155 if ($datafile) {
5156 try {
5157 include_once DOL_DOCUMENT_ROOT . '/core/class/dolgeoip.class.php';
5158 $geoip = new DolGeoIP('country', $datafile);
5159 //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
5160 $countrycode = $geoip->getCountryCodeFromIP($ip);
5161 } catch (Exception $e) {
5162 //print 'Error with GeoIP database: '.$e->getMessage();
5163 }
5164 }
5165 }
5166
5167 return $countrycode;
5168}
5169
5170
5177function dol_user_country()
5178{
5179 global $conf, $langs, $user;
5180
5181 //$ret=$user->xxx;
5182 $ret = '';
5183 if (isModEnabled('geoipmaxmind')) {
5184 $ip = getUserRemoteIP();
5185 $datafile = getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE');
5186 //$ip='24.24.24.24';
5187 //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';
5188 include_once DOL_DOCUMENT_ROOT . '/core/class/dolgeoip.class.php';
5189 $geoip = new DolGeoIP('country', $datafile);
5190 $countrycode = $geoip->getCountryCodeFromIP($ip);
5191 $ret = $countrycode;
5192 }
5193 return $ret;
5194}
5195
5208function dol_print_address($address, $htmlid, $element, $id, $noprint = 0, $charfornl = '')
5209{
5210 global $hookmanager;
5211
5212 $out = '';
5213
5214 if ($address) {
5215 if ($hookmanager) {
5216 $parameters = array('element' => $element, 'id' => $id);
5217 $reshook = $hookmanager->executeHooks('printAddress', $parameters, $address);
5218 $out .= $hookmanager->resPrint;
5219 }
5220 if (empty($reshook)) {
5221 if (empty($charfornl)) {
5222 $out .= nl2br((string) $address);
5223 } else {
5224 $out .= preg_replace('/[\r\n]+/', $charfornl, (string) $address);
5225 }
5226
5227 // TODO Remove this block, we can add this using the hook now
5228 $showgmap = $showomap = 0;
5229 if (($element == 'thirdparty' || $element == 'societe') && isModEnabled('google') && getDolGlobalString('GOOGLE_ENABLE_GMAPS')) {
5230 $showgmap = 1;
5231 }
5232 if ($element == 'contact' && isModEnabled('google') && getDolGlobalString('GOOGLE_ENABLE_GMAPS_CONTACTS')) {
5233 $showgmap = 1;
5234 }
5235 if ($element == 'member' && isModEnabled('google') && getDolGlobalString('GOOGLE_ENABLE_GMAPS_MEMBERS')) {
5236 $showgmap = 1;
5237 }
5238 if ($element == 'user' && isModEnabled('google') && getDolGlobalString('GOOGLE_ENABLE_GMAPS_USERS')) {
5239 $showgmap = 1;
5240 }
5241 if (($element == 'thirdparty' || $element == 'societe') && isModEnabled('openstreetmap') && getDolGlobalString('OPENSTREETMAP_ENABLE_MAPS')) {
5242 $showomap = 1;
5243 }
5244 if ($element == 'contact' && isModEnabled('openstreetmap') && getDolGlobalString('OPENSTREETMAP_ENABLE_MAPS_CONTACTS')) {
5245 $showomap = 1;
5246 }
5247 if ($element == 'member' && isModEnabled('openstreetmap') && getDolGlobalString('OPENSTREETMAP_ENABLE_MAPS_MEMBERS')) {
5248 $showomap = 1;
5249 }
5250 if ($element == 'user' && isModEnabled('openstreetmap') && getDolGlobalString('OPENSTREETMAP_ENABLE_MAPS_USERS')) {
5251 $showomap = 1;
5252 }
5253 if ($showgmap) {
5254 $url = dol_buildpath('/google/gmaps.php?mode=' . $element . '&id=' . $id, 1);
5255 $out .= ' <a href="' . $url . '" target="_gmaps"><img id="' . $htmlid . '" class="valigntextbottom" src="' . DOL_URL_ROOT . '/theme/common/gmap.png"></a>';
5256 }
5257 if ($showomap) {
5258 $url = dol_buildpath('/openstreetmap/maps.php?mode=' . $element . '&id=' . $id, 1);
5259 $out .= ' <a href="' . $url . '" target="_gmaps"><img id="' . $htmlid . '_openstreetmap" class="valigntextbottom" src="' . DOL_URL_ROOT . '/theme/common/gmap.png"></a>';
5260 }
5261 }
5262 }
5263 if ($noprint) {
5264 return $out;
5265 } else {
5266 print $out;
5267 return null;
5268 }
5269}
5270
5271
5281function isValidEmail($address, $acceptsupervisorkey = 0, $acceptuserkey = 0)
5282{
5283 if ($acceptsupervisorkey && $address == '__SUPERVISOREMAIL__') {
5284 return true;
5285 }
5286 if ($acceptuserkey && $address == '__USER_EMAIL__') {
5287 return true;
5288 }
5289 if (filter_var($address, FILTER_VALIDATE_EMAIL)) {
5290 return true;
5291 }
5292
5293 return false;
5294}
5295
5305function isValidMXRecord($domain)
5306{
5307 if (function_exists('idn_to_ascii') && function_exists('checkdnsrr')) {
5308 if (!checkdnsrr(idn_to_ascii($domain), 'MX')) {
5309 return 0;
5310 }
5311 if (function_exists('getmxrr')) {
5312 $mxhosts = array();
5313 $weight = array();
5314 getmxrr(idn_to_ascii($domain), $mxhosts, $weight);
5315 if (count($mxhosts) > 1) {
5316 return 1;
5317 }
5318 if (count($mxhosts) == 1 && !in_array((string) $mxhosts[0], array('', '.'))) {
5319 return 1;
5320 }
5321
5322 return 0;
5323 }
5324 }
5325
5326 // function idn_to_ascii or checkdnsrr or getmxrr does not exists
5327 return -1;
5328}
5329
5337function isValidPhone($phone)
5338{
5339 return true;
5340}
5341
5342
5352function dolGetFirstLetters($s, $nbofchar = 1)
5353{
5354 $ret = '';
5355 $tmparray = explode(' ', $s);
5356 foreach ($tmparray as $tmps) {
5357 $ret .= dol_substr($tmps, 0, $nbofchar);
5358 }
5359
5360 return $ret;
5361}
5362
5363
5371function dol_strlen($string, $stringencoding = 'UTF-8')
5372{
5373 if (is_null($string)) {
5374 return 0;
5375 }
5376
5377 if (function_exists('mb_strlen')) {
5378 return mb_strlen($string, $stringencoding);
5379 } else {
5380 return strlen($string);
5381 }
5382}
5383
5394function dol_substr($string, $start, $length = null, $stringencoding = '', $trunconbytes = 0)
5395{
5396 global $langs;
5397
5398 if (empty($stringencoding)) {
5399 $stringencoding = (empty($langs) ? 'UTF-8' : $langs->charset_output);
5400 }
5401
5402 $ret = '';
5403 if (empty($trunconbytes)) {
5404 if (function_exists('mb_substr')) {
5405 $ret = mb_substr($string, $start, $length, $stringencoding);
5406 } else {
5407 $ret = substr($string, $start, $length);
5408 }
5409 } else {
5410 if (function_exists('mb_strcut')) {
5411 $ret = mb_strcut($string, $start, $length, $stringencoding);
5412 } else {
5413 $ret = substr($string, $start, $length);
5414 }
5415 }
5416 return $ret;
5417}
5418
5419
5433function dol_trunc($string, $size = 40, $trunc = 'right', $stringencoding = 'UTF-8', $nodot = 0, $display = 0)
5434{
5435 global $conf;
5436
5437 if (empty($size) || getDolGlobalString('MAIN_DISABLE_TRUNC')) {
5438 return $string;
5439 }
5440
5441 if (empty($stringencoding)) {
5442 $stringencoding = 'UTF-8';
5443 }
5444 // reduce for small screen
5445 if (!empty($conf->dol_optimize_smallscreen) && $conf->dol_optimize_smallscreen == 1 && $display == 1) {
5446 $size = round($size / 3);
5447 }
5448
5449 // We go always here
5450 if ($trunc == 'right') {
5451 $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
5452 if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
5453 // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
5454 return dol_substr($newstring, 0, $size, $stringencoding) . ($nodot ? '' : '…');
5455 } else {
5456 //return 'u'.$size.'-'.$newstring.'-'.dol_strlen($newstring,$stringencoding).'-'.$string;
5457 return $string;
5458 }
5459 } elseif ($trunc == 'middle') {
5460 $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
5461 if (dol_strlen($newstring, $stringencoding) > 2 && dol_strlen($newstring, $stringencoding) > ($size + 1)) {
5462 $size1 = (int) round($size / 2);
5463 $size2 = (int) round($size / 2);
5464 return dol_substr($newstring, 0, $size1, $stringencoding) . '…' . dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size2, $size2, $stringencoding);
5465 } else {
5466 return $string;
5467 }
5468 } elseif ($trunc == 'left') {
5469 $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
5470 if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
5471 // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
5472 return '…' . dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size, $size, $stringencoding);
5473 } else {
5474 return $string;
5475 }
5476 } elseif ($trunc == 'wrap') {
5477 $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
5478 if (dol_strlen($newstring, $stringencoding) > ($size + 1)) {
5479 return dol_substr($newstring, 0, $size, $stringencoding) . "\n" . dol_trunc(dol_substr($newstring, $size, dol_strlen($newstring, $stringencoding) - $size, $stringencoding), $size, $trunc);
5480 } else {
5481 return $string;
5482 }
5483 } else {
5484 return 'BadParam3CallingDolTrunc';
5485 }
5486}
5487
5495function getPictoForType($key, $morecss = '')
5496{
5497 // Set array with type -> picto
5498 $type2picto = array(
5499 'varchar' => 'font',
5500 'text' => 'font',
5501 'html' => 'code',
5502 'int' => 'sort-numeric-down',
5503 'double' => 'sort-numeric-down',
5504 'price' => 'currency',
5505 'pricecy' => 'multicurrency',
5506 'password' => 'key',
5507 'boolean' => 'check-square',
5508 'date' => 'calendar',
5509 'datetime' => 'calendar',
5510 'duration' => 'hourglass',
5511 'phone' => 'phone',
5512 'mail' => 'email',
5513 'url' => 'url',
5514 'ip' => 'country',
5515 'select' => 'list',
5516 'sellist' => 'list',
5517 'stars' => 'fontawesome_star_fas',
5518 'radio' => 'check-circle',
5519 'checkbox' => 'list',
5520 'chkbxlst' => 'list',
5521 'link' => 'link',
5522 'icon' => "question",
5523 'point' => "country",
5524 'multipts' => 'country',
5525 'linestrg' => "country",
5526 'polygon' => "country",
5527 'separate' => 'minus'
5528 );
5529
5530 if (!empty($type2picto[$key])) {
5531 return img_picto('', $type2picto[$key], 'class="pictofixedwidth' . ($morecss ? ' ' . $morecss : '') . '"');
5532 }
5533
5534 return img_picto('', 'generic', 'class="pictofixedwidth' . ($morecss ? ' ' . $morecss : '') . '"');
5535}
5536
5537
5561function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $srconly = 0, $notitle = 0, $alt = '', $morecss = '', $marginleftonlyshort = 2, $allowothertags = array())
5562{
5563 global $conf;
5564
5565 // We forge fullpathpicto for image to $path/img/$picto. By default, we take DOL_URL_ROOT/theme/$conf->theme/img/$picto
5566 $url = DOL_URL_ROOT;
5567 $theme = isset($conf->theme) ? $conf->theme : null;
5568 $path = 'theme/' . $theme;
5569 if (empty($picto)) {
5570 $picto = 'generic';
5571 }
5572
5573 if ($titlealt) {
5574 $titlealt = str_replace(array('\n', "\n"), ' - ', $titlealt);
5575 }
5576
5577 // Define fullpathpicto to use into src
5578 if ($pictoisfullpath) {
5579 // Clean parameters
5580 if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
5581 $picto .= '.png';
5582 }
5583 $fullpathpicto = $picto;
5584 $reg = array();
5585 if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
5586 $morecss .= ($morecss ? ' ' : '') . $reg[1];
5587 $moreatt = str_replace('class="' . $reg[1] . '"', '', $moreatt);
5588 }
5589 } else {
5590 // $picto can not be null since replaced with 'generic' in that case
5591 // $pictowithouttext = preg_replace('/(\.png|\.gif|\.svg)$/', '', (is_null($picto) ? '' : $picto));
5592 $pictowithouttext = preg_replace('/(\.png|\.gif|\.svg)$/', '', $picto);
5593 $pictowithouttext = str_replace('object_', '', $pictowithouttext);
5594 $pictowithouttext = str_replace('_nocolor', '', $pictowithouttext);
5595
5596 // Fix some values of $pictowithouttext
5597 $pictoconvertkey = array(
5598 'facture' => 'bill',
5599 'shipping' => 'shipment',
5600 'fichinter' => 'intervention',
5601 'agenda' => 'calendar',
5602 'invoice_supplier' => 'supplier_invoice',
5603 'order_supplier' => 'supplier_order');
5604 if (in_array($pictowithouttext, array_keys($pictoconvertkey))) {
5605 $pictowithouttext = $pictoconvertkey[$pictowithouttext];
5606 }
5607
5608 if (strpos($pictowithouttext, 'fontawesome_') === 0 || strpos($pictowithouttext, 'fa-') === 0) {
5609 // This is a font awesome image 'fontawesome_xxx' or 'fa-xxx'
5610 $pictowithouttext = str_replace('fontawesome_', '', $pictowithouttext);
5611 $pictowithouttext = str_replace('fa-', '', $pictowithouttext);
5612
5613 // Compatibility with old fontawesome versions
5614 if ($pictowithouttext == 'file-o') {
5615 $pictowithouttext = 'file';
5616 }
5617
5618 $pictowithouttextarray = explode('_', $pictowithouttext);
5619 $marginleftonlyshort = 0;
5620
5621 if (!empty($pictowithouttextarray[1])) {
5622 // Syntax is 'fontawesome_fakey_faprefix_facolor_fasize' or 'fa-fakey_faprefix_facolor_fasize'
5623 $fakey = 'fa-' . $pictowithouttextarray[0];
5624 $faprefix = empty($pictowithouttextarray[1]) ? 'fas' : $pictowithouttextarray[1];
5625 $facolor = empty($pictowithouttextarray[2]) ? '' : $pictowithouttextarray[2];
5626 $fasize = empty($pictowithouttextarray[3]) ? '' : $pictowithouttextarray[3];
5627 } else {
5628 $fakey = 'fa-' . $pictowithouttext;
5629 $faprefix = 'fas';
5630 $facolor = '';
5631 $fasize = '';
5632 }
5633
5634 // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
5635 // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
5636 $morestyle = '';
5637 $reg = array();
5638 if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
5639 $morecss .= ($morecss ? ' ' : '') . $reg[1];
5640 $moreatt = str_replace('class="' . $reg[1] . '"', '', $moreatt);
5641 }
5642 if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
5643 $morestyle = $reg[1];
5644 $moreatt = str_replace('style="' . $reg[1] . '"', '', $moreatt);
5645 }
5646 $moreatt = trim($moreatt);
5647
5648 $enabledisablehtml = '<span class="' . $faprefix . ' ' . $fakey . ($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
5649 $enabledisablehtml .= ($morecss ? ' ' . $morecss : '') . '" style="' . ($fasize ? ('font-size: ' . $fasize . ';') : '') . ($facolor ? (' color: ' . $facolor . ';') : '') . ($morestyle ? ' ' . $morestyle : '') . '"' . (($notitle || empty($titlealt)) ? '' : ' title="' . dol_escape_htmltag($titlealt) . '"') . ($moreatt ? ' ' . $moreatt : '') . '>';
5650 $enabledisablehtml .= '</span>';
5651
5652 return $enabledisablehtml;
5653 }
5654
5655 if (empty($srconly) && !preg_match('/[\.\/@]/', $picto)) { // If original picto code does not contains a / and no . inside, it is not a path to an image file on disk
5656 $fakey = $pictowithouttext;
5657 $facolor = '';
5658 $fasize = '';
5659 $fa = getDolGlobalString('MAIN_FONTAWESOME_ICON_STYLE', 'fas');
5660 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'))) {
5661 $fa = 'far';
5662 }
5663 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'))) {
5664 $fa = 'fab';
5665 }
5666
5667 $arrayconvpictotofa = getImgPictoConv('fa');
5668
5669 if ($pictowithouttext == 'off') {
5670 $fakey = 'fa-square';
5671 $fasize = '1.3em';
5672 } elseif ($pictowithouttext == 'on') {
5673 $fakey = 'fa-check-square';
5674 $fasize = '1.3em';
5675 } elseif ($pictowithouttext == 'listlight') {
5676 $fakey = 'fa-download';
5677 $marginleftonlyshort = 1;
5678 } elseif ($pictowithouttext == 'printer') {
5679 $fakey = 'fa-print';
5680 $fasize = '1.2em';
5681 } elseif ($pictowithouttext == 'note') {
5682 $fakey = 'fa-sticky-note';
5683 $marginleftonlyshort = 1;
5684 } elseif (in_array($pictowithouttext, array('1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'))) {
5685 $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');
5686 $fakey = 'fa-' . $convertarray[$pictowithouttext];
5687 if (preg_match('/selected/', $pictowithouttext)) {
5688 $facolor = '#888';
5689 }
5690 $marginleftonlyshort = 1;
5691 } elseif (!empty($arrayconvpictotofa[$pictowithouttext])) {
5692 $fakey = 'fa-' . $arrayconvpictotofa[$pictowithouttext];
5693 } else {
5694 $fakey = 'fa-' . $pictowithouttext;
5695 }
5696
5697 if (in_array($pictowithouttext, array('dollyrevert', 'member', 'members', 'contract', 'group', 'resource', 'shipment', 'reception'))) {
5698 $morecss .= ' em092';
5699 }
5700 if (in_array($pictowithouttext, array('conferenceorbooth', 'eventorganization', 'holiday', 'info', 'info_black', 'project', 'workstation'))) {
5701 $morecss .= ' em088';
5702 }
5703 if (in_array($pictowithouttext, array('asset', 'intervention', 'payment', 'loan', 'partnership', 'stock', 'technic'))) {
5704 $morecss .= ' em080';
5705 }
5706
5707 // Define $marginleftonlyshort
5708 $arrayconvpictotomarginleftonly = array(
5709 'bank',
5710 'check',
5711 'delete',
5712 'generic',
5713 'grip',
5714 'grip_title',
5715 'jabber',
5716 'grip_title',
5717 'grip',
5718 'listlight',
5719 'note',
5720 'on',
5721 'off',
5722 'playdisabled',
5723 'printer',
5724 'resize',
5725 'sign-out',
5726 'stats',
5727 'switch_on',
5728 'switch_on_grey',
5729 'switch_on_red',
5730 'switch_off',
5731 'switch_off_grey',
5732 'switch_off_red',
5733 'uparrow',
5734 '1uparrow',
5735 '1downarrow',
5736 '1leftarrow',
5737 '1rightarrow',
5738 '1uparrow_selected',
5739 '1downarrow_selected',
5740 '1leftarrow_selected',
5741 '1rightarrow_selected'
5742 );
5743 if (!array_key_exists($pictowithouttext, $arrayconvpictotomarginleftonly)) {
5744 $marginleftonlyshort = 0;
5745 }
5746
5747 // Add CSS
5748 $arrayconvpictotomorcess = array(
5749 'action' => 'infobox-action',
5750 'account' => 'infobox-bank_account',
5751 'accounting_account' => 'infobox-bank_account',
5752 'accountline' => 'infobox-bank_account',
5753 'accountancy' => 'infobox-bank_account',
5754 'admin' => 'opacitymedium',
5755 'asset' => 'infobox-bank_account',
5756 'bank_account' => 'infobox-bank_account',
5757 'bill' => 'infobox-commande',
5758 'billa' => 'infobox-commande',
5759 'billr' => 'infobox-commande',
5760 'billd' => 'infobox-commande',
5761 'bookcal' => 'infobox-portal',
5762 'margin' => 'infobox-bank_account',
5763 'conferenceorbooth' => 'infobox-project',
5764 'cash-register' => 'infobox-portal',
5765 'contract' => 'infobox-contrat',
5766 'check' => 'font-status4',
5767 'conversation' => 'infobox-contrat',
5768 'donation' => 'infobox-commande',
5769 'dolly' => 'infobox-commande',
5770 'dollyrevert' => 'flip infobox-order_supplier',
5771 'ecm' => 'infobox-action',
5772 'eventorganization' => 'infobox-project',
5773 'hrm' => 'infobox-adherent',
5774 'group' => 'infobox-adherent',
5775 'intervention' => 'infobox-contrat',
5776 'incoterm' => 'infobox-supplier_proposal',
5777 'intracommreport' => 'infobox-bank_account',
5778 'currency' => 'infobox-bank_account',
5779 'multicurrency' => 'infobox-bank_account',
5780 'members' => 'infobox-adherent',
5781 'member' => 'infobox-adherent',
5782 'money-bill-alt' => 'infobox-bank_account',
5783 'order' => 'infobox-commande',
5784 'user' => 'infobox-adherent',
5785 'users' => 'infobox-adherent',
5786 'error' => 'pictoerror',
5787 'warning' => 'pictowarning',
5788 'switch_on' => 'font-status4',
5789 'switch_on_warning' => 'font-status4 warning',
5790 'switch_on_red' => 'font-status8',
5791 'switch_off_warning' => 'font-status4 warning',
5792 'switch_off_red' => 'font-status8',
5793 'holiday' => 'infobox-holiday',
5794 'info' => 'opacityhigh',
5795 'info_black' => 'purple',
5796 'invoice' => 'infobox-commande',
5797 'knowledgemanagement' => 'infobox-contrat rotate90',
5798 'loan' => 'infobox-commande',
5799 'payment' => 'infobox-bank_account',
5800 'payment_vat' => 'infobox-bank_account',
5801 'poll' => 'infobox-portal',
5802 'pos' => 'infobox-bank_account',
5803 'project' => 'infobox-project',
5804 'projecttask' => 'infobox-project',
5805 'propal' => 'infobox-propal',
5806 'proposal' => 'infobox-propal',
5807 'private' => 'infobox-project',
5808 'reception' => 'flip infobox-order_supplier',
5809 'recruitmentjobposition' => 'infobox-adherent',
5810 'recruitmentcandidature' => 'infobox-adherent',
5811 'resource' => 'infobox-action',
5812 'salary' => 'infobox-commande',
5813 'shapes' => 'infobox-adherent',
5814 'shipment' => 'infobox-commande',
5815 'store' => 'infobox-portal',
5816 'stripe' => 'infobox-bank_account',
5817 'supplier_invoice' => 'infobox-order_supplier',
5818 'supplier_invoicea' => 'infobox-order_supplier',
5819 'supplier_invoiced' => 'infobox-order_supplier',
5820 'supplier' => 'infobox-order_supplier',
5821 'supplier_order' => 'infobox-order_supplier',
5822 'supplier_proposal' => 'infobox-supplier_proposal',
5823 'ticket' => 'infobox-contrat',
5824 'title_accountancy' => 'infobox-bank_account',
5825 'title_hrm' => 'infobox-holiday',
5826 'expensereport' => 'infobox-expensereport',
5827 'trip' => 'infobox-expensereport',
5828 'title_agenda' => 'infobox-action',
5829 'vat' => 'infobox-bank_account',
5830 'webportal' => 'infobox-portal',
5831 //'title_setup'=>'infobox-action', 'tools'=>'infobox-action',
5832 'list-alt' => 'imgforviewmode',
5833 'calendar' => 'imgforviewmode',
5834 'calendarweek' => 'imgforviewmode',
5835 'calendarmonth' => 'imgforviewmode',
5836 'calendarday' => 'imgforviewmode',
5837 'calendarperuser' => 'imgforviewmode',
5838 'calendarpertype' => 'imgforviewmode'
5839 );
5840 if (!empty($arrayconvpictotomorcess[$pictowithouttext]) && strpos($picto, '_nocolor') === false) {
5841 $morecss .= ($morecss ? ' ' : '') . $arrayconvpictotomorcess[$pictowithouttext];
5842 }
5843
5844 // Define $color
5845 $arrayconvpictotocolor = array(
5846 'address' => '#6c6aa8',
5847 'building' => '#6c6aa8',
5848 'bom' => '#a69944',
5849 'clone' => '#999',
5850 'cog' => '#999',
5851 'companies' => '#6c6aa8',
5852 'company' => '#6c6aa8',
5853 'contact' => '#6c6aa8',
5854 'cron' => '#555',
5855 'dynamicprice' => '#a69944',
5856 'edit' => '#444',
5857 'note' => '#999',
5858 'error' => '',
5859 'help' => '#bbb',
5860 'listlight' => '#999',
5861 'language' => '#555',
5862 //'dolly'=>'#a69944', 'dollyrevert'=>'#a69944',
5863 'lock' => '#ddd',
5864 'lot' => '#a69944',
5865 'map-marker-alt' => '#aaa',
5866 'mrp' => '#a69944',
5867 'product' => '#a69944',
5868 'service' => '#a69944',
5869 'inventory' => '#a69944',
5870 'stock' => '#a69944',
5871 'movement' => '#a69944',
5872 'other' => '#ddd',
5873 'world' => '#986c6a',
5874 'partnership' => '#6c6aa8',
5875 'playdisabled' => '#ccc',
5876 'printer' => '#444',
5877 'projectpub' => '#986c6a',
5878 'resize' => '#444',
5879 'rss' => '#cba',
5880 //'shipment'=>'#a69944',
5881 'search-plus' => '#808080',
5882 'security' => '#999',
5883 'square' => '#888',
5884 'stop-circle' => '#888',
5885 'stats' => '#444',
5886 'superadmin' => '#600',
5887 'switch_off' => '#999',
5888 'technic' => '#999',
5889 'tick' => '#282',
5890 'timespent' => '#555',
5891 'uncheck' => '#800',
5892 'uparrow' => '#555',
5893 'user-cog' => '#999',
5894 'country' => '#aaa',
5895 'globe-americas' => '#aaa',
5896 'region' => '#aaa',
5897 'state' => '#aaa',
5898 'website' => '#304',
5899 'workstation' => '#a69944'
5900 );
5901 if (isset($arrayconvpictotocolor[$pictowithouttext]) && strpos($picto, '_nocolor') === false) {
5902 $facolor = $arrayconvpictotocolor[$pictowithouttext];
5903 }
5904
5905 // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
5906 // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
5907 $morestyle = '';
5908 $reg = array();
5909 if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
5910 $morecss .= ($morecss ? ' ' : '') . $reg[1];
5911 $moreatt = str_replace('class="' . $reg[1] . '"', '', $moreatt);
5912 }
5913 if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
5914 $morestyle = $reg[1];
5915 $moreatt = str_replace('style="' . $reg[1] . '"', '', $moreatt);
5916 }
5917 $moreatt = trim($moreatt);
5918
5919 $enabledisablehtml = '<span class="' . $fa . ' ' . $fakey . ($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
5920 $enabledisablehtml .= ($morecss ? ' ' . $morecss : '') . '" style="' . ($fasize ? ('font-size: ' . $fasize . ';') : '') . ($facolor ? (' color: ' . $facolor . ';') : '') . ($morestyle ? ' ' . $morestyle : '') . '"' . (($notitle || empty($titlealt)) ? '' : ' title="' . dol_escape_htmltag($titlealt) . '"') . ($moreatt ? ' ' . $moreatt : '') . '>';
5921 $enabledisablehtml .= '</span>';
5922
5923 return $enabledisablehtml;
5924 }
5925
5926 if (getDolGlobalString('MAIN_OVERWRITE_THEME_PATH')) {
5927 $path = getDolGlobalString('MAIN_OVERWRITE_THEME_PATH') . '/theme/' . $theme; // If the theme does not have the same name as the module
5928 } elseif (getDolGlobalString('MAIN_OVERWRITE_THEME_RES')) {
5929 $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
5930 } elseif (!empty($conf->modules_parts['theme']) && array_key_exists($theme, $conf->modules_parts['theme'])) {
5931 $path = $theme . '/theme/' . $theme; // If the theme have the same name as the module
5932 }
5933
5934 // If we ask an image into $url/$mymodule/img (instead of default path)
5935 $regs = array();
5936 if (preg_match('/^([^@]+)@([^@]+)$/i', $picto, $regs)) {
5937 $picto = $regs[1];
5938 $path = $regs[2]; // $path is $mymodule
5939 }
5940
5941 // Clean parameters
5942 if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
5943 $picto .= '.png';
5944 }
5945 // If alt path are defined, define url where img file is, according to physical path
5946 // ex: array(["main"]=>"/home/maindir/htdocs", ["alt0"]=>"/home/moddir0/htdocs", ...)
5947 foreach ($conf->file->dol_document_root as $type => $dirroot) {
5948 if ($type == 'main') {
5949 continue;
5950 }
5951 // This consumes a lot of time, that's why enabling alternative dir like "custom" dir should be avoid
5952 if (file_exists($dirroot . '/' . $path . '/img/' . $picto) && !empty($conf->file->dol_url_root)) {
5953 $url = DOL_URL_ROOT . $conf->file->dol_url_root[$type];
5954 break;
5955 }
5956 }
5957
5958 // $url is '' or '/custom', $path is current theme or
5959 $fullpathpicto = $url . '/' . $path . '/img/' . $picto;
5960 }
5961
5962 if ($srconly) {
5963 return $fullpathpicto;
5964 }
5965
5966 // tag title is used for tooltip on <a>, tag alt can be used with very simple text on image for blind people
5967 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
5968}
5969
5977function getImgPictoConv($mode = 'fa')
5978{
5979 global $conf;
5980
5981 if (empty($mode) || $mode == 'fa') {
5982 // Array when the fa picto key is different than the Dolibarr picto key.
5983 $arrayconvpictotofa = array(
5984 'account' => 'university',
5985 'accounting_account' => 'clipboard-list',
5986 'accountline' => 'receipt',
5987 'accountancy' => 'search-dollar',
5988 'action' => 'calendar-alt',
5989 'add' => 'plus-circle',
5990 'address' => 'address-book',
5991 'ai' => 'magic',
5992 'admin' => 'star',
5993 'asset' => 'money-check-alt',
5994 'autofill' => 'fill',
5995 'back' => 'arrow-left',
5996 'bank_account' => 'university',
5997 'bill' => 'file-invoice-dollar',
5998 'billa' => 'file-excel',
5999 'billr' => 'file-invoice-dollar',
6000 'billd' => 'file-medical',
6001 'blockedlog' => 'file-archive',
6002 'bookcal' => 'calendar-check',
6003 'supplier_invoice' => 'file-invoice-dollar',
6004 'supplier_invoicea' => 'file-excel',
6005 'supplier_invoicer' => 'file-invoice-dollar',
6006 'supplier_invoiced' => 'file-medical',
6007 'bom' => 'shapes',
6008 'card' => 'address-card',
6009 'chart' => 'chart-line',
6010 'company' => 'building',
6011 'contact' => 'address-book',
6012 'contract' => 'suitcase',
6013 'collab' => 'people-arrows',
6014 'conversation' => 'comments',
6015 'country' => 'globe-americas',
6016 'cron' => 'business-time',
6017 'cross' => 'times',
6018 'chevron-double-left' => 'angle-double-left',
6019 'chevron-double-right' => 'angle-double-right',
6020 'chevron-double-down' => 'angle-double-down',
6021 'chevron-double-top' => 'angle-double-up',
6022 'donation' => 'gift',
6023 'dynamicprice' => 'hand-holding-usd',
6024 'setup' => 'cog',
6025 'companies' => 'building',
6026 'products' => 'cube',
6027 'commercial' => 'suitcase',
6028 'invoicing' => 'coins',
6029 'accounting' => 'search-dollar',
6030 'category' => 'tag',
6031 'dollyrevert' => 'dolly',
6032 'file-o' => 'file',
6033 'generate' => 'plus-square',
6034 'hrm' => 'user-tie',
6035 'incoterm' => 'truck-loading',
6036 'margin' => 'calculator',
6037 'members' => 'user-friends',
6038 'ticket' => 'ticket-alt',
6039 'globe' => 'external-link-alt',
6040 'lot' => 'barcode',
6041 'email' => 'at',
6042 'establishment' => 'building',
6043 'edit' => 'pencil-alt',
6044 'entity' => 'globe',
6045 'graph' => 'chart-line',
6046 'grip_title' => 'arrows-alt',
6047 'grip' => 'arrows-alt',
6048 'help' => 'question-circle',
6049 'generic' => 'file',
6050 'holiday' => 'umbrella-beach',
6051 'info' => 'info-circle',
6052 'info_black' => 'info-circle',
6053 'inventory' => 'boxes',
6054 'intracommreport' => 'globe-europe',
6055 'jobprofile' => 'cogs',
6056 'knowledgemanagement' => 'ticket-alt',
6057 'label' => 'layer-group',
6058 'layout' => 'columns',
6059 'line' => 'bars',
6060 'loan' => 'money-bill-alt',
6061 'member' => 'user-alt',
6062 'meeting' => 'chalkboard-teacher',
6063 'mrp' => 'cubes',
6064 'next' => 'arrow-alt-circle-right',
6065 'trip' => 'wallet',
6066 'expensereport' => 'wallet',
6067 'group' => 'users',
6068 'movement' => 'people-carry',
6069 'sign-out' => 'sign-out-alt',
6070 'superadmin' => 'star',
6071 'switch_off' => 'toggle-off',
6072 'switch_off_grey' => 'toggle-off',
6073 'switch_off_warning' => 'toggle-off',
6074 'switch_off_red' => 'toggle-off',
6075 'switch_on' => 'toggle-on',
6076 'switch_on_grey' => 'toggle-on',
6077 'switch_on_warning' => 'toggle-on',
6078 'switch_on_red' => 'toggle-on',
6079 'check' => 'check',
6080 'bookmark' => 'star',
6081 'bank' => 'university',
6082 'close_title' => 'times',
6083 'delete' => 'trash',
6084 'filter' => 'filter',
6085 'list-alt' => 'list-alt',
6086 'calendarlist' => 'bars',
6087 'calendar' => 'calendar-alt',
6088 'calendarmonth' => 'calendar-alt',
6089 'calendarweek' => 'calendar-week',
6090 'calendarday' => 'calendar-day',
6091 'calendarperuser' => 'table',
6092 'calendarpertype' => 'table',
6093 'intervention' => 'ambulance',
6094 'invoice' => 'file-invoice-dollar',
6095 'order' => 'file-invoice',
6096 'error' => 'exclamation-triangle',
6097 'warning' => 'exclamation-triangle',
6098 'other' => 'square',
6099 'playdisabled' => 'play',
6100 'pdf' => 'file-pdf',
6101 'poll' => 'check-double',
6102 'pos' => 'cash-register',
6103 'preview' => 'binoculars',
6104 'project' => 'project-diagram',
6105 'projectpub' => 'project-diagram',
6106 'projecttask' => 'tasks',
6107 'propal' => 'file-signature',
6108 'proposal' => 'file-signature',
6109 'partnership' => 'handshake',
6110 'payment' => 'money-check-alt',
6111 'payment_vat' => 'money-check-alt',
6112 'pictoconfirm' => 'check-square',
6113 'phoning' => 'phone',
6114 'phoning_mobile' => 'mobile-alt',
6115 'phoning_fax' => 'fax',
6116 'previous' => 'arrow-alt-circle-left',
6117 'printer' => 'print',
6118 'product' => 'cube',
6119 'puce' => 'angle-right',
6120 'recent' => 'check-square',
6121 'reception' => 'dolly',
6122 'recruitmentjobposition' => 'id-card-alt',
6123 'recruitmentcandidature' => 'id-badge',
6124 'resize' => 'crop',
6125 'supplier_order' => 'dol-order_supplier',
6126 'supplier_proposal' => 'file-signature',
6127 'refresh' => 'redo',
6128 'region' => 'map-marked',
6129 'replacement' => 'exchange-alt',
6130 'resource' => 'laptop-house',
6131 'recurring' => 'history',
6132 'service' => 'concierge-bell',
6133 'skill' => 'shapes',
6134 'state' => 'map-marked-alt',
6135 'security' => 'key',
6136 'salary' => 'wallet',
6137 'shipment' => 'dolly',
6138 'stock' => 'box-open',
6139 'stats' => 'chart-bar',
6140 'split' => 'code-branch',
6141 'status' => 'stop-circle',
6142 'stripe' => 'stripe-s',
6143 'supplier' => 'building',
6144 'technic' => 'cogs',
6145 'tick' => 'check',
6146 'timespent' => 'clock',
6147 'title_setup' => 'tools',
6148 'title_accountancy' => 'money-check-alt',
6149 'title_bank' => 'university',
6150 'title_hrm' => 'umbrella-beach',
6151 'title_agenda' => 'calendar-alt',
6152 'uncheck' => 'times',
6153 'uparrow' => 'share',
6154 'url' => 'external-link-alt',
6155 'vat' => 'money-check-alt',
6156 'vcard' => 'arrow-alt-circle-down',
6157 'jabber' => 'comment',
6158 'website' => 'globe-americas',
6159 'workstation' => 'pallet',
6160 'webhook' => 'bullseye',
6161 'world' => 'globe',
6162 'private' => 'user-lock',
6163 'conferenceorbooth' => 'chalkboard-teacher',
6164 'eventorganization' => 'project-diagram',
6165 'webportal' => 'door-open'
6166 );
6167
6168 if ($conf->currency == 'EUR') {
6169 $arrayconvpictotofa['currency'] = 'euro-sign';
6170 $arrayconvpictotofa['multicurrency'] = 'dollar-sign';
6171 } else {
6172 $arrayconvpictotofa['currency'] = 'dollar-sign';
6173 $arrayconvpictotofa['multicurrency'] = 'euro-sign';
6174 }
6175 } else {
6176 $arrayconvpictotofa = array();
6177 }
6178
6179 return $arrayconvpictotofa;
6180}
6181
6182
6197function img_object($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $srconly = 0, $notitle = 0, $allowothertags = array())
6198{
6199 if (strpos($picto, '^') === 0) {
6200 return img_picto($titlealt, str_replace('^', '', $picto), $moreatt, $pictoisfullpath, $srconly, $notitle, '', '', 2, $allowothertags);
6201 } else {
6202 return img_picto($titlealt, 'object_' . $picto, $moreatt, $pictoisfullpath, $srconly, $notitle, '', '', 2, $allowothertags);
6203 }
6204}
6205
6217function img_weather($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $morecss = '')
6218{
6219 global $conf;
6220
6221 if (is_numeric($picto)) {
6222 //$leveltopicto = array(0=>'weather-clear.png', 1=>'weather-few-clouds.png', 2=>'weather-clouds.png', 3=>'weather-many-clouds.png', 4=>'weather-storm.png');
6223 //$picto = $leveltopicto[$picto];
6224 return '<i class="fa fa-weather-level' . $picto . '"></i>';
6225 } elseif (!preg_match('/(\.png|\.gif)$/i', $picto)) {
6226 $picto .= '.png';
6227 }
6228
6229 $path = DOL_URL_ROOT . '/theme/' . $conf->theme . '/img/weather/' . $picto;
6230
6231 return img_picto($titlealt, $path, $moreatt, 1, 0, 0, '', $morecss);
6232}
6233
6245function img_picto_common($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $notitle = 0)
6246{
6247 global $conf;
6248
6249 if (!preg_match('/(\.png|\.gif)$/i', $picto)) {
6250 $picto .= '.png';
6251 }
6252
6253 if ($pictoisfullpath) {
6254 $path = $picto;
6255 } else {
6256 $path = DOL_URL_ROOT . '/theme/common/' . $picto;
6257
6258 if (getDolGlobalInt('MAIN_MODULE_CAN_OVERWRITE_COMMONICONS')) {
6259 $themepath = DOL_DOCUMENT_ROOT . '/theme/' . $conf->theme . '/img/' . $picto;
6260
6261 if (file_exists($themepath)) {
6262 $path = $themepath;
6263 }
6264 }
6265 }
6266
6267 return img_picto($titlealt, $path, $moreatt, 1, 0, $notitle);
6268}
6269
6283function img_action($titlealt, $numaction, $picto = '', $moreatt = '')
6284{
6285 global $langs;
6286
6287 if (empty($titlealt) || $titlealt == 'default') {
6288 if ($numaction == '-1' || $numaction == 'ST_NO') {
6289 $numaction = -1;
6290 $titlealt = $langs->transnoentitiesnoconv('ChangeDoNotContact');
6291 } elseif ($numaction == '0' || $numaction == 'ST_NEVER') {
6292 $numaction = 0;
6293 $titlealt = $langs->transnoentitiesnoconv('ChangeNeverContacted');
6294 } elseif ($numaction == '1' || $numaction == 'ST_TODO') {
6295 $numaction = 1;
6296 $titlealt = $langs->transnoentitiesnoconv('ChangeToContact');
6297 } elseif ($numaction == '2' || $numaction == 'ST_PEND') {
6298 $numaction = 2;
6299 $titlealt = $langs->transnoentitiesnoconv('ChangeContactInProcess');
6300 } elseif ($numaction == '3' || $numaction == 'ST_DONE') {
6301 $numaction = 3;
6302 $titlealt = $langs->transnoentitiesnoconv('ChangeContactDone');
6303 } else {
6304 $titlealt = $langs->transnoentitiesnoconv('ChangeStatus ' . $numaction);
6305 $numaction = 0;
6306 }
6307 }
6308 if (!is_numeric($numaction)) {
6309 $numaction = 0;
6310 }
6311
6312 return img_picto($titlealt, (empty($picto) ? 'stcomm' . $numaction . '.png' : $picto), $moreatt);
6313}
6314
6322function img_edit_add($titlealt = 'default', $other = '')
6323{
6324 global $langs;
6325
6326 if ($titlealt == 'default') {
6327 $titlealt = $langs->trans('Add');
6328 }
6329
6330 return img_picto($titlealt, 'edit_add.png', $other);
6331}
6339function img_edit_remove($titlealt = 'default', $other = '')
6340{
6341 global $langs;
6342
6343 if ($titlealt == 'default') {
6344 $titlealt = $langs->trans('Remove');
6345 }
6346
6347 return img_picto($titlealt, 'edit_remove.png', $other);
6348}
6349
6358function img_edit($titlealt = 'default', $float = 0, $other = '')
6359{
6360 global $langs;
6361
6362 if ($titlealt == 'default') {
6363 $titlealt = $langs->trans('Modify');
6364 }
6365
6366 return img_picto($titlealt, 'edit', ($float ? 'style="float: ' . ($langs->tab_translate["DIRECTION"] == 'rtl' ? 'left' : 'right') . '"' : "") . ($other ? ' ' . $other : ''));
6367}
6368
6377function img_view($titlealt = 'default', $float = 0, $other = 'class="valignmiddle"')
6378{
6379 global $langs;
6380
6381 if ($titlealt == 'default') {
6382 $titlealt = $langs->trans('View');
6383 }
6384
6385 $moreatt = ($float ? 'style="float: right" ' : '') . $other;
6386
6387 return img_picto($titlealt, 'eye', $moreatt);
6388}
6389
6398function img_delete($titlealt = 'default', $other = 'class="pictodelete"', $morecss = '')
6399{
6400 global $langs;
6401
6402 if ($titlealt == 'default') {
6403 $titlealt = $langs->trans('Delete');
6404 }
6405
6406 return img_picto($titlealt, 'delete', $other, 0, 0, 0, '', $morecss);
6407}
6408
6416function img_printer($titlealt = "default", $other = '')
6417{
6418 global $langs;
6419 if ($titlealt == "default") {
6420 $titlealt = $langs->trans("Print");
6421 }
6422 return img_picto($titlealt, 'printer', $other);
6423}
6424
6432function img_split($titlealt = 'default', $other = 'class="pictosplit"')
6433{
6434 global $langs;
6435
6436 if ($titlealt == 'default') {
6437 $titlealt = $langs->trans('Split');
6438 }
6439
6440 return img_picto($titlealt, 'split', $other);
6441}
6442
6450function img_help($usehelpcursor = 1, $usealttitle = 1)
6451{
6452 global $langs;
6453
6454 if ($usealttitle) {
6455 if (is_string($usealttitle)) {
6456 $usealttitle = dol_escape_htmltag($usealttitle);
6457 } else {
6458 $usealttitle = $langs->trans('Info');
6459 }
6460 }
6461
6462 return img_picto($usealttitle, 'info', 'style="vertical-align: middle;' . ($usehelpcursor == 1 ? ' cursor: help' : ($usehelpcursor == 2 ? ' cursor: pointer' : '')) . '"');
6463}
6464
6471function img_info($titlealt = 'default')
6472{
6473 global $langs;
6474
6475 if ($titlealt == 'default') {
6476 $titlealt = $langs->trans('Informations');
6477 }
6478
6479 return img_picto($titlealt, 'info', 'style="vertical-align: middle;"');
6480}
6481
6490function img_warning($titlealt = 'default', $moreatt = '', $morecss = 'pictowarning')
6491{
6492 global $langs;
6493
6494 if ($titlealt == 'default') {
6495 $titlealt = $langs->trans('Warning');
6496 }
6497
6498 //return '<div class="imglatecoin">'.img_picto($titlealt, 'warning_white.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): '')).'</div>';
6499 return img_picto($titlealt, 'warning', 'class="' . $morecss . '"' . ($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' ' . $moreatt) : ''));
6500}
6501
6508function img_error($titlealt = 'default')
6509{
6510 global $langs;
6511
6512 if ($titlealt == 'default') {
6513 $titlealt = $langs->trans('Error');
6514 }
6515
6516 return img_picto($titlealt, 'error');
6517}
6518
6526function img_next($titlealt = 'default', $moreatt = '')
6527{
6528 global $langs;
6529
6530 if ($titlealt == 'default') {
6531 $titlealt = $langs->trans('Next');
6532 }
6533
6534 //return img_picto($titlealt, 'next.png', $moreatt);
6535 return '<span class="fa fa-chevron-right paddingright paddingleft" title="' . dol_escape_htmltag($titlealt) . '"></span>';
6536}
6537
6545function img_previous($titlealt = 'default', $moreatt = '')
6546{
6547 global $langs;
6548
6549 if ($titlealt == 'default') {
6550 $titlealt = $langs->trans('Previous');
6551 }
6552
6553 //return img_picto($titlealt, 'previous.png', $moreatt);
6554 return '<span class="fa fa-chevron-left paddingright paddingleft" title="' . dol_escape_htmltag($titlealt) . '"></span>';
6555}
6556
6565function img_down($titlealt = 'default', $selected = 0, $moreclass = '')
6566{
6567 global $langs;
6568
6569 if ($titlealt == 'default') {
6570 $titlealt = $langs->trans('Down');
6571 }
6572
6573 return img_picto($titlealt, ($selected ? '1downarrow_selected' : '1downarrow'), 'class="imgdown' . ($moreclass ? " " . $moreclass : "") . '"');
6574}
6575
6584function img_up($titlealt = 'default', $selected = 0, $moreclass = '')
6585{
6586 global $langs;
6587
6588 if ($titlealt == 'default') {
6589 $titlealt = $langs->trans('Up');
6590 }
6591
6592 return img_picto($titlealt, ($selected ? '1uparrow_selected' : '1uparrow'), 'class="imgup' . ($moreclass ? " " . $moreclass : "") . '"');
6593}
6594
6603function img_left($titlealt = 'default', $selected = 0, $moreatt = '')
6604{
6605 global $langs;
6606
6607 if ($titlealt == 'default') {
6608 $titlealt = $langs->trans('Left');
6609 }
6610
6611 return img_picto($titlealt, ($selected ? '1leftarrow_selected' : '1leftarrow'), $moreatt);
6612}
6613
6622function img_right($titlealt = 'default', $selected = 0, $moreatt = '')
6623{
6624 global $langs;
6625
6626 if ($titlealt == 'default') {
6627 $titlealt = $langs->trans('Right');
6628 }
6629
6630 return img_picto($titlealt, ($selected ? '1rightarrow_selected' : '1rightarrow'), $moreatt);
6631}
6632
6640function img_allow($allow, $titlealt = 'default')
6641{
6642 global $langs;
6643
6644 if ($titlealt == 'default') {
6645 $titlealt = $langs->trans('Active');
6646 }
6647
6648 if ($allow == 1) {
6649 return img_picto($titlealt, 'tick');
6650 }
6651
6652 return '-';
6653}
6654
6662function img_credit_card($brand, $morecss = 'fa-2x inline-block valignmiddle')
6663{
6664 if (is_null($morecss)) {
6665 $morecss = 'fa-2x';
6666 }
6667
6668 if ($brand == 'visa' || $brand == 'Visa') {
6669 $brand = 'cc-visa';
6670 } elseif ($brand == 'mastercard' || $brand == 'MasterCard') {
6671 $brand = 'cc-mastercard';
6672 } elseif ($brand == 'amex' || $brand == 'American Express') {
6673 $brand = 'cc-amex';
6674 } elseif ($brand == 'discover' || $brand == 'Discover') {
6675 $brand = 'cc-discover';
6676 } elseif ($brand == 'jcb' || $brand == 'JCB') {
6677 $brand = 'cc-jcb';
6678 } elseif ($brand == 'diners' || $brand == 'Diners club') {
6679 $brand = 'cc-diners-club';
6680 } elseif (!in_array($brand, array('cc-visa', 'cc-mastercard', 'cc-amex', 'cc-discover', 'cc-jcb', 'cc-diners-club'))) {
6681 $brand = 'credit-card';
6682 }
6683
6684 return '<span class="fa fa-' . $brand . ' fa-fw' . ($morecss ? ' ' . $morecss : '') . '"></span>';
6685}
6686
6695function img_mime($file, $titlealt = '', $morecss = '')
6696{
6697 require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
6698
6699 $mimetype = dol_mimetype($file, '', 1);
6700 //$mimeimg = dol_mimetype($file, '', 2);
6701 $mimefa = dol_mimetype($file, '', 4);
6702
6703 if (empty($titlealt)) {
6704 $titlealt = 'Mime type: ' . $mimetype;
6705 }
6706
6707 //return img_picto_common($titlealt, 'mime/'.$mimeimg, 'class="'.$morecss.'"');
6708 return '<i class="fa fa-' . $mimefa . ' ' . (preg_match('/pictofixedwidth/', $morecss) ? '' : 'paddingright ') . ($morecss ? ' ' . $morecss : '') . '"' . ($titlealt ? ' title="' . dolPrintHTMLForAttribute($titlealt) . '"' : '') . '></i>';
6709}
6710
6711
6719function img_search($titlealt = 'default', $other = '')
6720{
6721 global $langs;
6722
6723 if ($titlealt == 'default') {
6724 $titlealt = $langs->trans('Search');
6725 }
6726
6727 $img = img_picto($titlealt, 'search', $other, 0, 1);
6728
6729 $input = '<input type="image" class="liste_titre" name="button_search" src="' . $img . '" ';
6730 $input .= 'value="' . dol_escape_htmltag($titlealt) . '" title="' . dol_escape_htmltag($titlealt) . '" >';
6731
6732 return $input;
6733}
6734
6742function img_searchclear($titlealt = 'default', $other = '')
6743{
6744 global $langs;
6745
6746 if ($titlealt == 'default') {
6747 $titlealt = $langs->trans('Search');
6748 }
6749
6750 $img = img_picto($titlealt, 'searchclear.png', $other, 0, 1);
6751
6752 $input = '<input type="image" class="liste_titre" name="button_removefilter" src="' . $img . '" ';
6753 $input .= 'value="' . dol_escape_htmltag($titlealt) . '" title="' . dol_escape_htmltag($titlealt) . '" >';
6754
6755 return $input;
6756}
6757
6770function info_admin($text, $infoonimgalt = 0, $nodiv = 0, $admin = '1', $morecss = 'hideonsmartphone', $textfordropdown = '', $picto = '')
6771{
6772 global $conf, $langs;
6773
6774 if ($infoonimgalt) {
6775 $result = img_picto($text, 'info', 'class="' . ($morecss ? ' ' . $morecss : '') . '"');
6776 } else {
6777 if (empty($conf->use_javascript_ajax)) {
6778 $textfordropdown = '';
6779 }
6780
6781 $class = (empty($admin) ? 'undefined' : ((string) $admin == '1' ? 'info' : $admin));
6782 $fa = 'info-circle';
6783 if ($picto == 'warning') {
6784 $fa = 'exclamation-triangle';
6785 }
6786 $result = ($nodiv ? '' : '<div class="wordbreak ' . $class . ($morecss ? ' ' . $morecss : '') . ($textfordropdown ? ' hidden' : '') . '">');
6787 $result .= img_picto((string) $admin ? $langs->trans('InfoAdmin') : $langs->trans('Note'), $fa);
6788 $result .= ' ';
6789 $result .= dol_escape_htmltag($text, 1, 0, 'div,span,b,br,a');
6790 $result .= ($nodiv ? '' : '</div>');
6791
6792 if ($textfordropdown) {
6793 $tmpresult = '<span class="' . $class . 'text opacitymedium cursorpointer">' . $langs->trans($textfordropdown) . ' ' . img_picto($langs->trans($textfordropdown), '1downarrow') . '</span>';
6794 $tmpresult .= '<script nonce="' . getNonce() . '" type="text/javascript">
6795 jQuery(document).ready(function() {
6796 jQuery(".' . $class . 'text").click(function() {
6797 console.log("toggle text");
6798 jQuery(".' . $class . '").toggle();
6799 });
6800 });
6801 </script>';
6802
6803 $result = $tmpresult . $result;
6804 }
6805 }
6806
6807 return $result;
6808}
6809
6810
6822function dol_print_error($db = null, $error = '', $errors = null)
6823{
6824 global $conf, $langs, $user, $argv;
6825 global $dolibarr_main_prod;
6826
6827 $out = '';
6828 $syslog = '';
6829
6830 // If error occurs before the $lang object was loaded
6831 if (!$langs) {
6832 require_once DOL_DOCUMENT_ROOT . '/core/class/translate.class.php';
6833 $langs = new Translate('', $conf);
6834 $langs->load("main");
6835 }
6836
6837 // Load translation files required by the error messages
6838 $langs->loadLangs(array('main', 'errors'));
6839
6840 if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
6841 $out .= $langs->trans("DolibarrHasDetectedError") . ".<br>\n";
6842 if (getDolGlobalInt('MAIN_FEATURES_LEVEL') > 0) {
6843 $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";
6844 }
6845 $out .= $langs->trans("InformationToHelpDiagnose") . ":<br>\n";
6846
6847 $out .= "<b>" . $langs->trans("Date") . ":</b> " . dol_print_date(time(), 'dayhourlog') . "<br>\n";
6848 $out .= "<b>" . $langs->trans("Dolibarr") . ":</b> " . DOL_VERSION . " - https://www.dolibarr.org<br>\n";
6849 if (isset($conf->global->MAIN_FEATURES_LEVEL)) {
6850 $out .= "<b>" . $langs->trans("LevelOfFeature") . ":</b> " . getDolGlobalInt('MAIN_FEATURES_LEVEL') . "<br>\n";
6851 }
6852 if ($user instanceof User) {
6853 $out .= "<b>" . $langs->trans("Login") . ":</b> " . $user->login . "<br>\n";
6854 }
6855 if (function_exists("phpversion")) {
6856 $out .= "<b>" . $langs->trans("PHP") . ":</b> " . phpversion() . "<br>\n";
6857 }
6858 $out .= "<b>" . $langs->trans("Server") . ":</b> " . (isset($_SERVER["SERVER_SOFTWARE"]) ? dol_htmlentities($_SERVER["SERVER_SOFTWARE"], ENT_COMPAT) : '') . "<br>\n";
6859 if (function_exists("php_uname")) {
6860 $out .= "<b>" . $langs->trans("OS") . ":</b> " . php_uname() . "<br>\n";
6861 }
6862 $out .= "<b>" . $langs->trans("UserAgent") . ":</b> " . (isset($_SERVER["HTTP_USER_AGENT"]) ? dol_htmlentities($_SERVER["HTTP_USER_AGENT"], ENT_COMPAT) : '') . "<br>\n";
6863 $out .= "<br>\n";
6864 $out .= "<b>" . $langs->trans("RequestedUrl") . ":</b> " . (isset($_SERVER["REQUEST_URI"]) ? dol_htmlentities($_SERVER["REQUEST_URI"], ENT_COMPAT) : '') . "<br>\n";
6865 $out .= "<b>" . $langs->trans("Referer") . ":</b> " . (isset($_SERVER["HTTP_REFERER"]) ? dol_htmlentities($_SERVER["HTTP_REFERER"], ENT_COMPAT) : '') . "<br>\n";
6866 $out .= "<b>" . $langs->trans("MenuManager") . ":</b> " . (isset($conf->standard_menu) ? dol_htmlentities($conf->standard_menu, ENT_COMPAT) : '') . "<br>\n";
6867 $out .= "<br>\n";
6868 $syslog .= "url=" . (isset($_SERVER["REQUEST_URI"]) ? dol_escape_htmltag($_SERVER["REQUEST_URI"]) : '');
6869 $syslog .= ", query_string=" . (isset($_SERVER["QUERY_STRING"]) ? dol_escape_htmltag($_SERVER["QUERY_STRING"]) : '');
6870 } else { // Mode CLI
6871 $out .= '> ' . $langs->transnoentities("ErrorInternalErrorDetected") . ":\n" . $argv[0] . "\n";
6872 $syslog .= "pid=" . dol_getmypid();
6873 }
6874
6875 if (!empty($conf->modules)) {
6876 $out .= "<b>" . $langs->trans("Modules") . ":</b> " . implode(', ', $conf->modules) . "<br>\n";
6877 }
6878
6879 if (is_object($db)) {
6880 if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
6881 $out .= "<b>" . $langs->trans("DatabaseTypeManager") . ":</b> " . $db->type . "<br>\n";
6882 $lastqueryerror = $db->lastqueryerror();
6883 if (!utf8_check($lastqueryerror)) {
6884 $lastqueryerror = "SQL error string is not a valid UTF8 string. We can't show it.";
6885 }
6886 $out .= "<b>" . $langs->trans("RequestLastAccessInError") . ":</b> " . ($lastqueryerror ? dol_escape_htmltag($lastqueryerror) : $langs->trans("ErrorNoRequestInError")) . "<br>\n";
6887 $out .= "<b>" . $langs->trans("ReturnCodeLastAccessInError") . ":</b> " . ($db->lasterrno() ? dol_escape_htmltag($db->lasterrno()) : $langs->trans("ErrorNoRequestInError")) . "<br>\n";
6888 $out .= "<b>" . $langs->trans("InformationLastAccessInError") . ":</b> " . ($db->lasterror() ? dol_escape_htmltag($db->lasterror()) : $langs->trans("ErrorNoRequestInError")) . "<br>\n";
6889 $out .= "<br>\n";
6890 } else { // Mode CLI
6891 // No dol_escape_htmltag for output, we are in CLI mode
6892 $out .= '> ' . $langs->transnoentities("DatabaseTypeManager") . ":\n" . $db->type . "\n";
6893 $out .= '> ' . $langs->transnoentities("RequestLastAccessInError") . ":\n" . ($db->lastqueryerror() ? $db->lastqueryerror() : $langs->transnoentities("ErrorNoRequestInError")) . "\n";
6894 $out .= '> ' . $langs->transnoentities("ReturnCodeLastAccessInError") . ":\n" . ($db->lasterrno() ? $db->lasterrno() : $langs->transnoentities("ErrorNoRequestInError")) . "\n";
6895 $out .= '> ' . $langs->transnoentities("InformationLastAccessInError") . ":\n" . ($db->lasterror() ? $db->lasterror() : $langs->transnoentities("ErrorNoRequestInError")) . "\n";
6896 }
6897 $syslog .= ", sql=" . $db->lastquery();
6898 $syslog .= ", db_error=" . $db->lasterror();
6899 }
6900
6901 if ($error || $errors) {
6902 // Merge all into $errors array
6903 if (is_array($error) && is_array($errors)) {
6904 $errors = array_merge($error, $errors);
6905 } elseif (is_array($error)) { // deprecated, use second parameters
6906 $errors = $error;
6907 } elseif (is_array($errors) && !empty($error)) {
6908 $errors = array_merge(array($error), $errors);
6909 } elseif (!empty($error)) {
6910 $errors = array_merge(array($error), array($errors));
6911 }
6912
6913 $langs->load("errors");
6914
6915 foreach ($errors as $msg) {
6916 if (empty($msg)) {
6917 continue;
6918 }
6919 if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
6920 $out .= "<b>" . $langs->trans("Message") . ":</b> " . dol_escape_htmltag($msg) . "<br>\n";
6921 } else { // Mode CLI
6922 $out .= '> ' . $langs->transnoentities("Message") . ":\n" . $msg . "\n";
6923 }
6924 $syslog .= ", msg=" . $msg;
6925 }
6926 }
6927 if (empty($dolibarr_main_prod) && $_SERVER['DOCUMENT_ROOT'] && function_exists('xdebug_print_function_stack') && function_exists('xdebug_call_file')) {
6928 xdebug_print_function_stack();
6929 $out .= '<b>XDebug information:</b>' . "<br>\n";
6930 $out .= 'File: ' . xdebug_call_file() . "<br>\n";
6931 $out .= 'Line: ' . xdebug_call_line() . "<br>\n";
6932 $out .= 'Function: ' . xdebug_call_function() . "<br>\n";
6933 $out .= "<br>\n";
6934 }
6935
6936 // Return a http header with error code if possible
6937 if (!headers_sent()) {
6938 if (function_exists('top_httphead')) { // In CLI context, the method does not exists
6939 top_httphead();
6940 }
6941 //http_response_code(500); // If we use 500, message is not output with some command line tools
6942 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
6943 }
6944
6945 if (empty($dolibarr_main_prod)) {
6946 print $out;
6947 } else {
6948 if (empty($langs->defaultlang)) {
6949 $langs->setDefaultLang();
6950 }
6951 $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.
6952 // This should not happen, except if there is a bug somewhere. Enabled and check log in such case.
6953 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";
6954 print $langs->trans("DolibarrHasDetectedError") . '. ';
6955 print $langs->trans("YouCanSetOptionDolibarrMainProdToZero");
6956 if (!defined("MAIN_CORE_ERROR")) {
6957 define("MAIN_CORE_ERROR", 1);
6958 }
6959 }
6960
6961 dol_syslog("Error " . $syslog, LOG_ERR);
6962}
6963
6974function dol_print_error_email($prefixcode, $errormessage = '', $errormessages = array(), $morecss = 'error', $email = '')
6975{
6976 global $langs;
6977
6978 if (empty($email)) {
6979 $email = getDolGlobalString('MAIN_INFO_SOCIETE_MAIL');
6980 }
6981
6982 $langs->load("errors");
6983 $now = dol_now();
6984
6985 print '<br><div class="center login_main_message"><div class="' . $morecss . '">';
6986 print $langs->trans("ErrorContactEMail", $email, $prefixcode . '-' . dol_print_date($now, '%Y%m%d%H%M%S'));
6987 if ($errormessage) {
6988 print '<br><br>' . $errormessage;
6989 }
6990 if (is_array($errormessages) && count($errormessages)) {
6991 foreach ($errormessages as $mesgtoshow) {
6992 print '<br><br>' . $mesgtoshow;
6993 }
6994 }
6995 print '</div></div>';
6996}
6997
7014function print_liste_field_titre($name, $file = "", $field = "", $begin = "", $param = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $tooltip = "", $forcenowrapcolumntitle = 0)
7015{
7016 print getTitleFieldOfList($name, 0, $file, $field, $begin, $param, $moreattrib, $sortfield, $sortorder, $prefix, 0, $tooltip, $forcenowrapcolumntitle);
7017}
7018
7037function getTitleFieldOfList($name, $thead = 0, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $disablesortlink = 0, $tooltip = '', $forcenowrapcolumntitle = 0)
7038{
7039 global $langs, $form;
7040 //print "$name, $file, $field, $begin, $options, $moreattrib, $sortfield, $sortorder<br>\n";
7041
7042 if ($moreattrib == 'class="right"') {
7043 $prefix .= 'right '; // For backward compatibility
7044 }
7045
7046 $tooltip = (string) $tooltip; // In case $tooltip is null
7047
7048 $sortorder = strtoupper((string) $sortorder);
7049 $out = '';
7050 $sortimg = '';
7051
7052 $tag = 'th';
7053 if ($thead == 2) {
7054 $tag = 'div';
7055 }
7056
7057 $tmpsortfield = explode(',', (string) $sortfield);
7058 $sortfield1 = trim($tmpsortfield[0]); // If $sortfield is 'd.datep,d.id', it becomes 'd.datep'
7059 $tmpfield = explode(',', $field);
7060 $field1 = trim($tmpfield[0]); // If $field is 'd.datep,d.id', it becomes 'd.datep'
7061
7062 if (strpos((string) $tooltip, ':') !== false) {
7063 $tmptooltip = explode(':', (string) $tooltip);
7064 } else {
7065 $tmptooltip = array($tooltip);
7066 }
7067
7068 $wrapcolumntitle = (empty($forcenowrapcolumntitle) || (!empty($tmptooltip[2]) && $tmptooltip[2] == '-1'));
7069
7070 if (!getDolGlobalString('MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE') && $wrapcolumntitle) {
7071 $prefix = 'wrapcolumntitle ' . $prefix;
7072 }
7073
7074 //var_dump('field='.$field.' field1='.$field1.' sortfield='.$sortfield.' sortfield1='.$sortfield1);
7075 // If field is used as sort criteria we use a specific css class liste_titre_sel
7076 // Example if (sortfield,field)=("nom","xxx.nom") or (sortfield,field)=("nom","nom")
7077 $liste_titre = 'liste_titre';
7078 if ($field1 && ($sortfield1 == $field1 || $sortfield1 == preg_replace("/^[^\.]+\./", "", $field1))) {
7079 $liste_titre = 'liste_titre_sel';
7080 }
7081
7082 $tagstart = '<' . $tag . ' class="' . $prefix . $liste_titre . '" ' . $moreattrib;
7083 //$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)).'"' : '');
7084 $tagstart .= ($name && !getDolGlobalString('MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE') && $wrapcolumntitle && !dol_textishtml($name)) ? ' title="' . dolPrintHTMLForAttribute($langs->trans($name)) . '"' : '';
7085 $tagstart .= '>';
7086
7087 if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
7088 $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
7089 $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
7090 $options = preg_replace('/&+/i', '&', $options);
7091 if (!preg_match('/^&/', $options)) {
7092 $options = '&' . $options;
7093 }
7094
7095 $sortordertouseinlink = '';
7096 if ($field1 != $sortfield1) { // We are on another field than current sorted field
7097 if (preg_match('/^DESC/i', $sortorder)) {
7098 $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
7099 } else { // We reverse the var $sortordertouseinlink
7100 $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
7101 }
7102 } else { // We are on field that is the first current sorting criteria
7103 if (preg_match('/^ASC/i', $sortorder)) { // We reverse the var $sortordertouseinlink
7104 $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
7105 } else {
7106 $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
7107 }
7108 }
7109 $sortordertouseinlink = preg_replace('/,$/', '', $sortordertouseinlink);
7110 $out .= '<a class="reposition" href="' . dolBuildUrl($file, ['sortfield' => $field, 'sortorder' => $sortordertouseinlink, 'begin' => $begin]) . $options . '"';
7111 //$out .= (getDolGlobalString('MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE') ? '' : ' title="'.dol_escape_htmltag($langs->trans($name)).'"');
7112 $out .= '>';
7113 }
7114 if ($tooltip && $tmptooltip[0]) {
7115 // You can also use 'TranslationString:[keyfortooltiponclick]:[tooltipdirection]' for a tooltip on click or to change tooltip position.
7116 $out .= $form->textwithpicto($langs->trans((string) $name), $langs->trans((string) $tmptooltip[0]), (empty($tmptooltip[2]) ? '1' : $tmptooltip[2]), 'help', ((!empty($tmptooltip[2]) && $tmptooltip[2] == '-1') ? 'paddingrightonly' : ''), 0, 3, (empty($tmptooltip[1]) ? '' : 'extra_' . str_replace('.', '_', $field) . '_' . $tmptooltip[1]));
7117 } else {
7118 $out .= $langs->trans((string) $name);
7119 }
7120
7121 if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
7122 $out .= '</a>';
7123 }
7124
7125 if (empty($thead) && $field) { // If this is a sort field
7126 $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
7127 $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
7128 $options = preg_replace('/&+/i', '&', $options);
7129 if (!preg_match('/^&/', $options)) {
7130 $options = '&' . $options;
7131 }
7132
7133 if (!$sortorder || ($field1 != $sortfield1)) {
7134 // Nothing
7135 } else {
7136 if (preg_match('/^DESC/', $sortorder)) {
7137 $sortimg .= '<span class="nowrap">' . img_up("Z-A", 0, 'paddingright') . '</span>';
7138 }
7139 if (preg_match('/^ASC/', $sortorder)) {
7140 $sortimg .= '<span class="nowrap">' . img_down("A-Z", 0, 'paddingright') . '</span>';
7141 }
7142 }
7143 }
7144
7145 $tagend = '</' . $tag . '>';
7146
7147 $out = $tagstart . $sortimg . $out . $tagend;
7148
7149 return $out;
7150}
7151
7160function print_titre($title)
7161{
7162 dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);
7163
7164 print '<div class="titre">' . $title . '</div>';
7165}
7166
7178function print_fiche_titre($title, $mesg = '', $picto = 'generic', $pictoisfullpath = 0, $id = '')
7179{
7180 print load_fiche_titre($title, $mesg, $picto, $pictoisfullpath, $id);
7181}
7182
7197function load_fiche_titre($title, $morehtmlright = '', $picto = 'generic', $pictoisfullpath = 0, $id = '', $morecssontable = '', $morehtmlcenter = '', $morecssonpicto = 'widthpictotitle')
7198{
7199 $return = '';
7200
7201 if ($picto == 'setup') {
7202 $picto = 'generic';
7203 }
7204
7205 $return .= "\n";
7206 $return .= '<table ' . ($id ? 'id="' . $id . '" ' : '') . 'class="centpercent notopnoleftnoright table-fiche-title' . ($morecssontable ? ' ' . $morecssontable : '') . '">'; // margin bottom must be same than into print_barre_list
7207 $return .= '<tr class="toptitle">';
7208 if ($picto) {
7209 $return .= '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">' . img_picto('', $picto, 'class="valignmiddle pictotitle'.($morecssonpicto ? ' '.$morecssonpicto : '').'"', $pictoisfullpath) . '</td>';
7210 }
7211 $return .= '<td class="nobordernopadding valignmiddle col-title">';
7212 $return .= '<div class="titre inline-block">';
7213 $return .= '<span class="inline-block valignmiddle">' . $title . '</span>'; // $title is already HTML sanitized content
7214 $return .= '</div>';
7215 $return .= '</td>';
7216 if (dol_strlen($morehtmlcenter)) {
7217 $return .= '<td class="nobordernopadding center valignmiddle col-center">' . $morehtmlcenter . '</td>';
7218 }
7219 if (dol_strlen($morehtmlright)) {
7220 $return .= '<td class="nobordernopadding titre_right wordbreakimp right valignmiddle col-right">' . $morehtmlright . '</td>';
7221 }
7222 $return .= '</tr></table>' . "\n";
7223
7224 return $return;
7225}
7226
7250function 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 = '')
7251{
7252 global $conf, $langs;
7253
7254 $savlimit = $limit;
7255 $savtotalnboflines = $totalnboflines;
7256 if (is_numeric($totalnboflines)) {
7257 $totalnboflines = abs($totalnboflines);
7258 }
7259
7260 // Detect if there is a subtitle
7261 $subtitle = '';
7262 $tmparray = preg_split('/<br>/i', $title, 2);
7263 if (!empty($tmparray[1])) {
7264 $title = $tmparray[0];
7265 $subtitle = $tmparray[1];
7266 }
7267
7268 $page = (int) $page;
7269
7270 if ($picto == 'setup') {
7271 $picto = 'title_setup';
7272 }
7273 if (($conf->browser->name == 'ie') && $picto == 'generic') {
7274 $picto = 'title.gif';
7275 }
7276 if ($limit < 0) {
7277 $limit = $conf->liste_limit;
7278 }
7279
7280 if ($savlimit != 0 && (($num > $limit) || ($num == -1) || ($limit == 0))) {
7281 $nextpage = 1;
7282 } else {
7283 $nextpage = 0;
7284 }
7285 //print 'totalnboflines='.$totalnboflines.'-savlimit='.$savlimit.'-limit='.$limit.'-num='.$num.'-nextpage='.$nextpage.'-selectlimitsuffix='.$selectlimitsuffix.'-hidenavigation='.$hidenavigation;
7286
7287 print "\n";
7288 print "<!-- Begin print_barre_liste -->\n";
7289 print '<table class="centpercent notopnoleftnoright table-fiche-title' . ($morecss ? ' ' . $morecss : '') . '">';
7290 print '<tr class="toptitle">'; // margin bottom must be same than into load_fiche_tire
7291
7292 // Left
7293
7294 if ($picto && $title) {
7295 print '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">';
7296 print img_picto('', $picto, 'class="valignmiddle pictotitle widthpictotitle"', $pictoisfullpath);
7297 print '</td>';
7298 }
7299
7300 print '<td class="nobordernopadding valignmiddle col-title">';
7301 print '<div class="titre inline-block">';
7302 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()
7303 if (!empty($title) && $savtotalnboflines >= 0 && (string) $savtotalnboflines != '' && $totalnboflines > 0) {
7304 print '<span class="opacitymedium colorblack marginleftonly totalnboflines valignmiddle" title="' . $langs->trans("NbRecordQualified") . '">(' . $totalnboflines . ')</span>';
7305 }
7306 print '</div>';
7307 if (!empty($subtitle)) {
7308 print '<br><div class="subtitle inline-block hideonsmartphone">' . $subtitle . '</div>';
7309 }
7310 print '</td>';
7311
7312 // Center
7313 if ($morehtmlcenter && empty($conf->dol_optimize_smallscreen)) {
7314 print '<td class="nobordernopadding center valignmiddle col-center">' . $morehtmlcenter . '</td>';
7315 }
7316
7317 // Right
7318 print '<td class="nobordernopadding valignmiddle right col-right">';
7319 print '<input type="hidden" name="pageplusoneold" value="' . ((int) $page + 1) . '">';
7320 $query = [];
7321 parse_str($options, $query);
7322 if ($sortfield) {
7323 $query += ['sortfield' => $sortfield];
7324 }
7325 if ($sortorder) {
7326 $query += ['sortorder' => $sortorder];
7327 }
7328
7329 $options = '&' . http_build_query($query);
7330 if ($page) {
7331 $query = array_merge($query, ['page' => $page]);
7332 }
7333 // Show navigation bar
7334 $pagelist = '';
7335 if ($savlimit != 0 && ($page > 0 || $num > $limit)) {
7336 if ($totalnboflines) { // If we know total nb of lines
7337 // Define nb of extra page links before and after selected page + ... + first or last
7338 $maxnbofpage = (empty($conf->dol_optimize_smallscreen) ? 4 : 0);
7339
7340 if ($limit > 0) {
7341 $nbpages = ceil($totalnboflines / $limit);
7342 } else {
7343 $nbpages = 1;
7344 }
7345 $cpt = ($page - $maxnbofpage);
7346 if ($cpt < 0) {
7347 $cpt = 0;
7348 }
7349
7350 if ($cpt >= 1) {
7351 if (empty($pagenavastextinput)) {
7352 $query['page'] = 0;
7353 $pagelist .= '<li class="pagination"><a class="reposition" href="' . dolBuildUrl($file, $query) . '">1</a></li>';
7354 if ($cpt > 2) {
7355 $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
7356 } elseif ($cpt == 2) {
7357 $query['page'] = 0;
7358 $pagelist .= '<li class="pagination"><a class="reposition" href="' . dolBuildUrl($file, $query) . '">2</a></li>';
7359 }
7360 }
7361 }
7362
7363 do {
7364 if ($pagenavastextinput) {
7365 if ($cpt == $page) {
7366 $pagelist .= '<li class="pagination pageplusone valignmiddle"><input type="text" class="' . ($totalnboflines > 100 ? 'width40' : 'width25') . ' center pageplusone heightofcombo" name="pageplusone" value="' . ($page + 1) . '"></li>';
7367 $pagelist .= '/';
7368 }
7369 } else {
7370 if ($cpt == $page) {
7371 $pagelist .= '<li class="pagination"><span class="active">' . ($page + 1) . '</span></li>';
7372 } else {
7373 $query['page'] = $cpt;
7374 $pagelist .= '<li class="pagination"><a class="reposition" href="' . dolBuildUrl($file, $query) . '">' . ($cpt + 1) . '</a></li>';
7375 }
7376 }
7377 $cpt++;
7378 } while ($cpt < $nbpages && $cpt <= ($page + $maxnbofpage));
7379
7380 if (empty($pagenavastextinput)) {
7381 if ($cpt < $nbpages) {
7382 if ($cpt < $nbpages - 2) {
7383 $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
7384 } elseif ($cpt == $nbpages - 2) {
7385 $query['page'] = ($nbpages - 2);
7386 $pagelist .= '<li class="pagination"><a class="reposition" href="' . dolBuildUrl($file, $query) . '">' . ($nbpages - 1) . '</a></li>';
7387 }
7388 $query['page'] = ($nbpages - 1);
7389 $pagelist .= '<li class="pagination"><a class="reposition" href="' . dolBuildUrl($file, $query) . '">' . $nbpages . '</a></li>';
7390 }
7391 } else {
7392 $query['page'] = ($nbpages - 1);
7393 $pagelist .= '<li class="pagination paginationlastpage"><a class="reposition" href="' . dolBuildUrl($file, $query) . '">' . $nbpages . '</a></li>';
7394 }
7395 } else {
7396 $pagelist .= '<li class="pagination"><span class="active">' . ($page + 1) . "</li>";
7397 }
7398 }
7399
7400 if ($savlimit || $morehtmlright || $morehtmlrightbeforearrow) {
7401 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
7402 }
7403
7404 // js to autoselect page field on focus
7405 if ($pagenavastextinput) {
7406 print ajax_autoselect('.pageplusone');
7407 }
7408
7409 print '</td>';
7410 print '</tr>';
7411
7412 print "</table>\n";
7413
7414 // Center
7415 if ($morehtmlcenter && !empty($conf->dol_optimize_smallscreen)) {
7416 print '<div class="nobordernopadding marginbottomonly center valignmiddle col-center centpercent">' . $morehtmlcenter . '</div>';
7417 }
7418
7419 print "<!-- End title -->\n\n";
7420}
7421
7438function print_fleche_navigation($page, $file, $options = '', $nextpage = 0, $betweenarrows = '', $afterarrows = '', $limit = -1, $totalnboflines = 0, $selectlimitsuffix = '', $beforearrows = '', $hidenavigation = 0)
7439{
7440 global $conf, $langs;
7441
7442 print '<div class="pagination"><ul>';
7443 if ($beforearrows) {
7444 print '<li class="paginationbeforearrows">';
7445 print $beforearrows;
7446 print '</li>';
7447 }
7448
7449 if (empty($hidenavigation)) {
7450 if ((int) $limit > 0 && (empty($selectlimitsuffix) || !is_numeric($selectlimitsuffix))) {
7451 $pagesizechoices = '10:10,15:15,20:20,25:25,50:50,100:100,250:250,500:500,1000:1000';
7452 $pagesizechoices .= ',5000:5000';
7453 //$pagesizechoices .= ',10000:10000'; // Memory trouble on most browsers
7454 //$pagesizechoices .= ',20000:20000'; // Memory trouble on most browsers
7455 //$pagesizechoices .= ',0:'.$langs->trans("All"); // Not yet supported
7456 //$pagesizechoices .= ',2:2';
7457 if (getDolGlobalString('MAIN_PAGESIZE_CHOICES')) {
7458 $pagesizechoices = getDolGlobalString('MAIN_PAGESIZE_CHOICES');
7459 }
7460
7461 if (getDolGlobalString('MAIN_USE_HTML5_LIMIT_SELECTOR')) {
7462 print '<li class="pagination">';
7463 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 . '">';
7464 print '<datalist id="limitlist">';
7465 } else {
7466 print '<li class="paginationcombolimit valignmiddle">';
7467 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")) . '">';
7468 }
7469 $tmpchoice = explode(',', $pagesizechoices);
7470 $tmpkey = $limit . ':' . $limit;
7471 if (!in_array($tmpkey, $tmpchoice)) {
7472 $tmpchoice[$tmpkey] = $tmpkey;
7473 }
7474 $tmpkey = $conf->liste_limit . ':' . $conf->liste_limit;
7475 if (!in_array($tmpkey, $tmpchoice)) {
7476 $tmpchoice[$tmpkey] = $tmpkey;
7477 }
7478 asort($tmpchoice, SORT_NUMERIC);
7479 foreach ($tmpchoice as $val) {
7480 $selected = '';
7481 $tmp = explode(':', $val);
7482 $key = $tmp[0];
7483 $val = $tmp[1];
7484 if ($key != '' && $val != '') {
7485 if ((int) $key == (int) $limit) {
7486 $selected = ' selected="selected"';
7487 }
7488 print '<option name="' . $key . '"' . $selected . '>' . dol_escape_htmltag($val) . '</option>' . "\n";
7489 }
7490 }
7491 if (getDolGlobalString('MAIN_USE_HTML5_LIMIT_SELECTOR')) {
7492 print '</datalist>';
7493 } else {
7494 print '</select>';
7495 print ajax_combobox("limit" . (is_numeric($selectlimitsuffix) ? '' : $selectlimitsuffix), array(), 0, 0, 'resolve', '-1', 'limit');
7496 //print ajax_combobox("limit");
7497 }
7498
7499 if ($conf->use_javascript_ajax) {
7500 print '<!-- JS CODE TO ENABLE select limit to launch submit of page -->
7501 <script>
7502 jQuery(document).ready(function () {
7503 jQuery(".selectlimit").change(function() {
7504 console.log("We change limit so we submit the form");
7505 $(this).parents(\'form:first\').submit();
7506 });
7507 });
7508 </script>
7509 ';
7510 }
7511 print '</li>';
7512 }
7513 if ($page > 0) {
7514 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>';
7515 }
7516 if ($betweenarrows) {
7517 print '<!--<div class="betweenarrows nowraponall inline-block">-->';
7518 print $betweenarrows;
7519 print '<!--</div>-->';
7520 }
7521 if ($nextpage > 0) {
7522 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>';
7523 }
7524 if ($afterarrows) {
7525 print '<li class="paginationafterarrows">';
7526 print $afterarrows;
7527 print '</li>';
7528 }
7529 }
7530 print '</ul></div>' . "\n";
7531}
7532
7533
7545function vatrate($rate, $addpercent = false, $info_bits = 0, $usestarfornpr = 0, $html = 0)
7546{
7547 $morelabel = '';
7548
7549 if (preg_match('/%/', $rate)) {
7550 $rate = str_replace('%', '', $rate);
7551 $addpercent = true;
7552 }
7553 $reg = array();
7554 if (preg_match('/\‍((.*)\‍)/', $rate, $reg)) {
7555 $morelabel = ' (' . $reg[1] . ')';
7556 $rate = preg_replace('/\s*' . preg_quote($morelabel, '/') . '/', '', $rate);
7557 $morelabel = ' ' . ($html ? '<span class="opacitymedium">' : '') . '(' . $reg[1] . ')' . ($html ? '</span>' : '');
7558 }
7559 if (preg_match('/\*/', $rate)) {
7560 $rate = str_replace('*', '', $rate);
7561 $info_bits |= 1;
7562 }
7563
7564 // If rate is '9/9/9' we don't change it. If rate is '9.000' we apply price()
7565 if (!preg_match('/\//', $rate)) {
7566 $ret = price($rate, 0, '', 0, 0) . ($addpercent ? '%' : '');
7567 } else {
7568 // TODO Split on / and output with a price2num to have clean numbers without ton of 000.
7569 $ret = $rate . ($addpercent ? '%' : '');
7570 }
7571 if (($info_bits & 1) && $usestarfornpr >= 0) {
7572 $ret .= ' *';
7573 }
7574 $ret .= $morelabel;
7575 return $ret;
7576}
7577
7578
7594function price($amount, $form = 0, $outlangs = '', $trunc = 1, $rounding = -1, $forcerounding = -1, $currency_code = '')
7595{
7596 global $langs, $conf;
7597
7598 // Clean parameters
7599 if (empty($amount)) {
7600 $amount = 0; // To have a numeric value if amount not defined or = ''
7601 }
7602 $amount = (is_numeric($amount) ? $amount : 0); // Check if amount is numeric, for example, an error occurred when amount value = o (letter) instead 0 (number)
7603 if ($rounding == -1) {
7604 $rounding = min(getDolGlobalString('MAIN_MAX_DECIMALS_UNIT'), getDolGlobalString('MAIN_MAX_DECIMALS_TOT'));
7605 }
7606 $nbdecimal = $rounding;
7607
7608 if ($outlangs === 'none') {
7609 // Use international separators
7610 $dec = '.';
7611 $thousand = '';
7612 } else {
7613 // Output separators by default (french)
7614 $dec = ',';
7615 $thousand = ' ';
7616
7617 // If $outlangs not forced, we use use language
7618 if (!($outlangs instanceof Translate)) {
7619 $outlangs = $langs;
7620 }
7621
7622 if ($outlangs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
7623 $dec = $outlangs->transnoentitiesnoconv("SeparatorDecimal");
7624 }
7625 if ($outlangs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
7626 $thousand = $outlangs->transnoentitiesnoconv("SeparatorThousand");
7627 }
7628 if ($thousand == 'None') {
7629 $thousand = '';
7630 } elseif ($thousand == 'Space') {
7631 $thousand = ' ';
7632 }
7633 }
7634 //print "outlangs=".$outlangs->defaultlang." amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
7635
7636 //print "amount=".$amount."-";
7637 $amount = str_replace(',', '.', $amount); // should be useless
7638 //print $amount."-";
7639 $data = explode('.', $amount);
7640 $decpart = isset($data[1]) ? $data[1] : '';
7641 $decpart = preg_replace('/0+$/i', '', $decpart); // Remove 0 at end of decimal part
7642 //print "decpart=".$decpart."<br>";
7643 $end = '';
7644
7645 // We increase nbdecimal if there is more decimal than asked (to not loose information)
7646 if (dol_strlen($decpart) > $nbdecimal) {
7647 $nbdecimal = dol_strlen($decpart);
7648 }
7649
7650 // If nbdecimal is higher than max to show
7651 $nbdecimalmaxshown = (int) str_replace('...', '', getDolGlobalString('MAIN_MAX_DECIMALS_SHOWN'));
7652 if ($trunc && $nbdecimal > $nbdecimalmaxshown) {
7653 $nbdecimal = $nbdecimalmaxshown;
7654 if (preg_match('/\.\.\./i', getDolGlobalString('MAIN_MAX_DECIMALS_SHOWN'))) {
7655 // If output is truncated, we show ...
7656 $end = '...';
7657 }
7658 }
7659
7660 // If force rounding
7661 if ((string) $forcerounding != '-1' && (string) $forcerounding != '') {
7662 if ($forcerounding === 'MU') {
7663 $nbdecimal = getDolGlobalInt('MAIN_MAX_DECIMALS_UNIT');
7664 } elseif ($forcerounding === 'MT') {
7665 $nbdecimal = getDolGlobalInt('MAIN_MAX_DECIMALS_TOT');
7666 } elseif ($forcerounding >= 0) {
7667 $nbdecimal = (int) $forcerounding;
7668 }
7669 }
7670
7671 // Format number
7672 $output = number_format((float) $amount, $nbdecimal, $dec, $thousand);
7673 // Add symbol of currency if requested
7674 $cursymbolbefore = $cursymbolafter = '';
7675 if ($currency_code && is_object($outlangs)) {
7676 if ($currency_code == 'auto') {
7677 $currency_code = $conf->currency;
7678 }
7679
7680 $listofcurrenciesbefore = array('AUD', 'CAD', 'CNY', 'COP', 'CLP', 'GBP', 'HKD', 'MXN', 'PEN', 'USD', 'CRC', 'ZAR');
7681 $listoflanguagesbefore = array('nl_NL');
7682 if (in_array($currency_code, $listofcurrenciesbefore) || in_array($outlangs->defaultlang, $listoflanguagesbefore)) {
7683 $cursymbolbefore .= $outlangs->getCurrencySymbol($currency_code);
7684 } else {
7685 $tmpcur = $outlangs->getCurrencySymbol($currency_code);
7686 $cursymbolafter .= ($tmpcur == $currency_code ? ' ' . $tmpcur : $tmpcur);
7687 }
7688 }
7689 $output = $cursymbolbefore . $output . $end . ($cursymbolafter ? ' ' : '') . $cursymbolafter;
7690 if ($form) {
7691 $output = preg_replace('/\s/', '&nbsp;', $output);
7692 $output = preg_replace('/\'/', '&#039;', $output);
7693 }
7694
7695 return $output;
7696}
7697
7723function price2num($amount, $rounding = '', $option = 0)
7724{
7725 global $langs;
7726
7727 // Clean parameters
7728 if (is_null($amount)) {
7729 $amount = '';
7730 }
7731
7732 // Round PHP function does not allow number like '1,234.56' nor '1.234,56' nor '1 234,56'
7733 // Numbers must be '1234.56'
7734 // Decimal delimiter for PHP and database SQL requests must be '.'
7735 $dec = ',';
7736 $thousand = ' ';
7737 if (is_null($langs)) { // $langs is not defined, we use english values.
7738 $dec = '.';
7739 $thousand = ',';
7740 } else {
7741 if ($langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
7742 $dec = $langs->transnoentitiesnoconv("SeparatorDecimal");
7743 }
7744 if ($langs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
7745 $thousand = $langs->transnoentitiesnoconv("SeparatorThousand");
7746 }
7747 }
7748 if ($thousand == 'None') {
7749 $thousand = '';
7750 } elseif ($thousand == 'Space') {
7751 $thousand = ' ';
7752 }
7753 //print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
7754
7755 // Convert value to universal number format (no thousand separator, '.' as decimal separator)
7756 if ($option != 1) { // If not a PHP number or unknown, we change or clean format
7757 //print "\n".'PP'.$amount.' - '.$dec.' - '.$thousand.' - '.intval($amount).'<br>';
7758 if (!is_numeric($amount)) {
7759 $amount = preg_replace('/[a-zA-Z\/\\\*\‍(\‍)<>\_]/', '', $amount);
7760 }
7761
7762 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
7763 $amount = str_replace($thousand, '', $amount);
7764 }
7765
7766 // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
7767 // to format defined by LC_NUMERIC after a calculation and we want source format to be like defined by Dolibarr setup.
7768 // So if number was already a good number, it is converted into local Dolibarr setup.
7769 if (is_numeric($amount)) {
7770 // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
7771 $temps = sprintf("%10.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
7772 $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
7773 $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
7774 $amount = number_format($amount, $nbofdec, $dec, $thousand);
7775 }
7776 //print "QQ".$amount."<br>\n";
7777
7778 // Now make replaceents (the main goal of function)
7779
7780 if ($thousand != ',' && $thousand != '.') {
7781 // Accept the two types of decimal points french users (i.e., using ' ' for thousands)
7782
7783 // REGEX: Find the integral and decimal parts.
7784 //
7785 // We require that the decimal point only appears once in $amount.
7786 // The regex `/^(?<int>[^,]*,|[^.]*\.)(?<dec>[^.,]*)$/u` can be broken down as follows:
7787 // - `(?<int>[^,]*,|[^.]*\.)` is any accepted sequence up to the last potential decimal point '.' or ',' and named `int`.
7788 // It covers two cases:
7789 // - `[^,]*,`: Any sequence of characters that is not ',' with ',' accepted as the decimal point (from start of string because of earlier `^`);
7790 // - `[^.]*\.`: Any sequence of characters that is not a '.' with '.' accepted as the decimal point (from start of string.
7791 // - `(?<dec>[^.,]*)`: The sequence after the character accepted as the decimal point, not including it.
7792 $matches = array();
7793 if (preg_match('/^(?<int>[^,]*,|[^.]*\.)(?<dec>[^.,]*)$/u', $amount, $matches)) {
7794 $intPart = $matches['int'];
7795 $decPart = $matches['dec'];
7796
7797 // Remove all commas and dots from intPart
7798 $intPart = str_replace(['.', ','], '', $intPart);
7799
7800 // Combine intPart and decPart with a dot
7801 $amount = $intPart . $dec . $decPart;
7802 }
7803 }
7804
7805 $amount = str_replace(' ', '', $amount); // To avoid spaces
7806 $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
7807 $amount = str_replace($dec, '.', $amount);
7808
7809 $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
7810 }
7811 //print ' XX'.$amount.' '.$rounding;
7812
7813 // Now, $amount is a real PHP float number. We make a rounding if required.
7814 if ($rounding) {
7815 $nbofdectoround = '';
7816 if ($rounding == 'MU') {
7817 $nbofdectoround = getDolGlobalInt('MAIN_MAX_DECIMALS_UNIT'); // usually 5
7818 } elseif ($rounding == 'MT') {
7819 $nbofdectoround = getDolGlobalInt('MAIN_MAX_DECIMALS_TOT'); // usually 2 or 3
7820 } elseif ($rounding == 'MS') {
7821 $nbofdectoround = getDolGlobalInt('MAIN_MAX_DECIMALS_STOCK', 5);
7822 } elseif ($rounding == 'CU') {
7823 $nbofdectoround = getDolGlobalInt('MAIN_MAX_DECIMALS_CURRENCY_UNIT', getDolGlobalInt('MAIN_MAX_DECIMALS_UNIT')); // TODO Use param of currency
7824 } elseif ($rounding == 'CT') {
7825 $nbofdectoround = getDolGlobalInt('MAIN_MAX_DECIMALS_CURRENCY_TOT', getDolGlobalInt('MAIN_MAX_DECIMALS_TOT')); // TODO Use param of currency
7826 } elseif (is_numeric($rounding)) {
7827 $nbofdectoround = (int) $rounding;
7828 }
7829
7830 //print " RR".$amount.' - '.$nbofdectoround.'<br>';
7831 if (dol_strlen($nbofdectoround)) {
7832 $amount = round(is_string($amount) ? (float) $amount : $amount, $nbofdectoround); // $nbofdectoround can be 0.
7833 } else {
7834 return 'ErrorBadParameterProvidedToFunction';
7835 }
7836 //print ' SS'.$amount.' - '.$nbofdec.' - '.$dec.' - '.$thousand.' - '.$nbofdectoround.'<br>';
7837
7838 // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
7839 // to format defined by LC_NUMERIC after a calculation and we want source format to be defined by Dolibarr setup.
7840 if (is_numeric($amount)) {
7841 // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
7842 $temps = sprintf("%10.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
7843 $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
7844 $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
7845 $amount = number_format($amount, min($nbofdec, $nbofdectoround), $dec, $thousand); // Convert amount to format with dolibarr dec and thousand
7846 }
7847 //print "TT".$amount.'<br>';
7848
7849 // Always make replace because each math function (like round) replace
7850 // with local values and we want a number that has a SQL string format x.y
7851 if ($thousand != ',' && $thousand != '.') {
7852 $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
7853 }
7854
7855 $amount = str_replace(' ', '', $amount); // To avoid spaces
7856 $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
7857 $amount = str_replace($dec, '.', $amount);
7858
7859 $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
7860 }
7861
7862 return $amount;
7863}
7864
7877function showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round = -1, $forceunitoutput = 'no', $use_short_label = 0)
7878{
7879 require_once DOL_DOCUMENT_ROOT . '/core/lib/product.lib.php';
7880
7881 if (($forceunitoutput == 'no' && $dimension < 1 / 10000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -6)) {
7882 $dimension *= 1000000;
7883 $unit -= 6;
7884 } elseif (($forceunitoutput == 'no' && $dimension < 1 / 10 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -3)) {
7885 $dimension *= 1000;
7886 $unit -= 3;
7887 } elseif (($forceunitoutput == 'no' && $dimension > 100000000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 6)) {
7888 $dimension /= 1000000;
7889 $unit += 6;
7890 } elseif (($forceunitoutput == 'no' && $dimension > 100000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 3)) {
7891 $dimension /= 1000;
7892 $unit += 3;
7893 }
7894 // Special case when we want output unit into pound or ounce
7895 /* TODO
7896 if ($unit < 90 && $type == 'weight' && is_numeric($forceunitoutput) && (($forceunitoutput == 98) || ($forceunitoutput == 99))
7897 {
7898 $dimension = // convert dimension from standard unit into ounce or pound
7899 $unit = $forceunitoutput;
7900 }
7901 if ($unit > 90 && $type == 'weight' && is_numeric($forceunitoutput) && $forceunitoutput < 90)
7902 {
7903 $dimension = // convert dimension from standard unit into ounce or pound
7904 $unit = $forceunitoutput;
7905 }*/
7906
7907 $ret = price($dimension, 0, $outputlangs, 0, 0, $round);
7908 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
7909 $ret .= ' ' . measuringUnitString(0, $type, $unit, $use_short_label, $outputlangs);
7910
7911 return $ret;
7912}
7913
7914
7927function get_localtax($vatrate, $local, $thirdparty_buyer = null, $thirdparty_seller = null, $vatnpr = 0)
7928{
7929 global $db, $conf, $mysoc;
7930
7931 if (empty($thirdparty_seller) || !is_object($thirdparty_seller)) {
7932 $thirdparty_seller = $mysoc;
7933 }
7934
7935 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);
7936
7937 $vatratecleaned = $vatrate;
7938 $reg = array();
7939 if (preg_match('/^(.*)\s*\‍((.*)\‍)$/', (string) $vatrate, $reg)) { // If vat is "xx (yy)"
7940 $vatratecleaned = trim($reg[1]);
7941 $vatratecode = $reg[2];
7942 }
7943
7944 /*if ($thirdparty_buyer->country_code != $thirdparty_seller->country_code)
7945 {
7946 return 0;
7947 }*/
7948
7949 // Some test to guess with no need to make database access
7950 if ($mysoc->country_code == 'ES') { // For spain localtaxes 1 and 2, tax is qualified if buyer use local tax
7951 if ($local == 1) {
7952 if (!$mysoc->localtax1_assuj || (string) $vatratecleaned == "0") {
7953 return 0;
7954 }
7955 if ($thirdparty_seller->id == $mysoc->id) {
7956 if (!$thirdparty_buyer->localtax1_assuj) {
7957 return 0;
7958 }
7959 } else {
7960 if (!$thirdparty_seller->localtax1_assuj) {
7961 return 0;
7962 }
7963 }
7964 }
7965
7966 if ($local == 2) {
7967 //if (! $mysoc->localtax2_assuj || (string) $vatratecleaned == "0") return 0;
7968 if (!$mysoc->localtax2_assuj) {
7969 return 0; // If main vat is 0, IRPF may be different than 0.
7970 }
7971 if ($thirdparty_seller->id == $mysoc->id) {
7972 if (!$thirdparty_buyer->localtax2_assuj) {
7973 return 0;
7974 }
7975 } else {
7976 if (!$thirdparty_seller->localtax2_assuj) {
7977 return 0;
7978 }
7979 }
7980 }
7981 } else {
7982 if ($local == 1 && !$thirdparty_seller->localtax1_assuj) {
7983 return 0;
7984 }
7985 if ($local == 2 && !$thirdparty_seller->localtax2_assuj) {
7986 return 0;
7987 }
7988 }
7989
7990 // For some country MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY is forced to on.
7991 if (in_array($mysoc->country_code, array('ES'))) {
7992 $conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY = 1;
7993 }
7994
7995 // Search local taxes
7996 if (getDolGlobalString('MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY')) {
7997 if ($local == 1) {
7998 if ($thirdparty_seller != $mysoc) {
7999 if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
8000 return $thirdparty_seller->localtax1_value;
8001 }
8002 } else { // i am the seller
8003 if (!isOnlyOneLocalTax($local)) { // TODO If seller is me, why not always returning this, even if there is only one locatax vat.
8004 return getDolGlobalString('MAIN_INFO_VALUE_LOCALTAX1');
8005 }
8006 }
8007 }
8008 if ($local == 2) {
8009 if ($thirdparty_seller != $mysoc) {
8010 if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
8011 // TODO We should also return value defined on thirdparty only if defined
8012 return $thirdparty_seller->localtax2_value;
8013 }
8014 } else { // i am the seller
8015 if (in_array($mysoc->country_code, array('ES'))) {
8016 return $thirdparty_buyer->localtax2_value;
8017 } else {
8018 return getDolGlobalString('MAIN_INFO_VALUE_LOCALTAX2');
8019 }
8020 }
8021 }
8022 }
8023
8024 // By default, search value of local tax on line of common tax
8025 $sql = "SELECT t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
8026 $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t, " . MAIN_DB_PREFIX . "c_country as c";
8027 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '" . $db->escape($thirdparty_seller->country_code) . "'";
8028 $sql .= " AND t.taux = " . ((float) $vatratecleaned) . " AND t.active = 1";
8029 $sql .= " AND t.entity IN (" . getEntity('c_tva') . ")";
8030 if (!empty($vatratecode)) {
8031 $sql .= " AND t.code ='" . $db->escape($vatratecode) . "'"; // If we have the code, we use it in priority
8032 } else {
8033 $sql .= " AND t.recuperableonly = '" . $db->escape((string) $vatnpr) . "'";
8034 }
8035
8036 $resql = $db->query($sql);
8037
8038 if ($resql) {
8039 $obj = $db->fetch_object($resql);
8040 if ($obj) {
8041 if ($local == 1) {
8042 return $obj->localtax1;
8043 } elseif ($local == 2) {
8044 return $obj->localtax2;
8045 }
8046 }
8047 }
8048
8049 return 0;
8050}
8051
8052
8061function isOnlyOneLocalTax($local)
8062{
8063 $tax = get_localtax_by_third($local);
8064
8065 $valors = explode(":", $tax);
8066
8067 if (count($valors) > 1) {
8068 return false;
8069 } else {
8070 return true;
8071 }
8072}
8073
8080function get_localtax_by_third($local)
8081{
8082 global $db, $mysoc;
8083
8084 $sql = " SELECT t.localtax" . $local . " as localtax";
8085 $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t INNER JOIN " . MAIN_DB_PREFIX . "c_country as c ON c.rowid = t.fk_pays";
8086 $sql .= " WHERE c.code = '" . $db->escape($mysoc->country_code) . "' AND t.active = 1 AND t.entity IN (" . getEntity('c_tva') . ") AND t.taux = (";
8087 $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";
8088 $sql .= " WHERE c.code = '" . $db->escape($mysoc->country_code) . "' AND t.entity IN (" . getEntity('c_tva') . ") AND tt.active = 1)";
8089 $sql .= " AND t.localtax" . $local . "_type <> '0'";
8090 $sql .= " ORDER BY t.rowid DESC";
8091
8092 $resql = $db->query($sql);
8093 if ($resql) {
8094 $obj = $db->fetch_object($resql);
8095 if ($obj) {
8096 return $obj->localtax;
8097 } else {
8098 return '0';
8099 }
8100 }
8101
8102 return 'Error';
8103}
8104
8105
8117function getTaxesFromId($vatrate, $buyer = null, $seller = null, $firstparamisid = 1)
8118{
8119 global $db;
8120
8121 dol_syslog("getTaxesFromId vat id or rate = " . $vatrate);
8122
8123 // Search local taxes
8124 $sql = "SELECT t.rowid, t.code, t.taux as rate, t.recuperableonly as npr, t.accountancy_code_sell, t.accountancy_code_buy,";
8125 $sql .= " t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type";
8126 $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t";
8127 if ($firstparamisid) {
8128 $sql .= " WHERE t.rowid = " . (int) $vatrate;
8129 } else {
8130 $vatratecleaned = $vatrate;
8131 $vatratecode = '';
8132 $reg = array();
8133 if (preg_match('/^(.*)\s*\‍((.*)\‍)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
8134 $vatratecleaned = $reg[1];
8135 $vatratecode = $reg[2];
8136 }
8137
8138 $sql .= ", " . MAIN_DB_PREFIX . "c_country as c";
8139 /*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 ??
8140 else $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";*/
8141 $sql .= " WHERE t.fk_pays = c.rowid";
8142 if (getDolGlobalString('SERVICE_ARE_ECOMMERCE_200238EC')) {
8143 $sql .= " AND c.code = '" . $db->escape($buyer->country_code) . "'";
8144 } else {
8145 $sql .= " AND c.code = '" . $db->escape($seller->country_code) . "'";
8146 }
8147 $sql .= " AND t.taux = " . ((float) $vatratecleaned) . " AND t.active = 1";
8148 $sql .= " AND t.entity IN (" . getEntity('c_tva') . ")";
8149 if ($vatratecode) {
8150 $sql .= " AND t.code = '" . $db->escape($vatratecode) . "'";
8151 }
8152 }
8153
8154 $resql = $db->query($sql);
8155 if ($resql) {
8156 $obj = $db->fetch_object($resql);
8157 if ($obj) {
8158 return array(
8159 'rowid' => $obj->rowid,
8160 'code' => $obj->code,
8161 'rate' => $obj->rate,
8162 'localtax1' => $obj->localtax1,
8163 'localtax1_type' => $obj->localtax1_type,
8164 'localtax2' => $obj->localtax2,
8165 'localtax2_type' => $obj->localtax2_type,
8166 'npr' => $obj->npr,
8167 'accountancy_code_sell' => $obj->accountancy_code_sell,
8168 'accountancy_code_buy' => $obj->accountancy_code_buy
8169 );
8170 } else {
8171 return array();
8172 }
8173 } else {
8174 dol_print_error($db);
8175 }
8176
8177 return array();
8178}
8179
8196function getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid = 0)
8197{
8198 global $db, $mysoc;
8199
8200 dol_syslog("getLocalTaxesFromRate vatrate=" . $vatrate . " local=" . $local);
8201
8202 // Search local taxes
8203 $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";
8204 $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t";
8205 if ($firstparamisid) {
8206 $sql .= " WHERE t.rowid = " . (int) $vatrate;
8207 } else {
8208 $vatratecleaned = $vatrate;
8209 $vatratecode = '';
8210 $reg = array();
8211 if (preg_match('/^(.*)\s*\‍((.*)\‍)$/', $vatrate, $reg)) { // If vat is "x.x (yy)"
8212 $vatratecleaned = $reg[1];
8213 $vatratecode = $reg[2];
8214 }
8215
8216 $sql .= ", " . MAIN_DB_PREFIX . "c_country as c";
8217 if (!empty($mysoc) && $mysoc->country_code == 'ES') {
8218 $countrycodetouse = ((empty($buyer) || empty($buyer->country_code)) ? $mysoc->country_code : $buyer->country_code);
8219 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '" . $db->escape($countrycodetouse) . "'"; // local tax in spain use the buyer country ??
8220 } else {
8221 $countrycodetouse = ((empty($seller) || empty($seller->country_code)) ? $mysoc->country_code : $seller->country_code);
8222 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '" . $db->escape($countrycodetouse) . "'";
8223 }
8224 $sql .= " AND t.taux = " . ((float) $vatratecleaned) . " AND t.active = 1";
8225 if ($vatratecode) {
8226 $sql .= " AND t.code = '" . $db->escape($vatratecode) . "'";
8227 }
8228 }
8229
8230 $resql = $db->query($sql);
8231 if ($resql) {
8232 $obj = $db->fetch_object($resql);
8233
8234 if ($obj) {
8235 $vateratestring = $obj->rate . ($obj->code ? ' (' . $obj->code . ')' : '');
8236
8237 if ($local == 1) {
8238 return array($obj->localtax1_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
8239 } elseif ($local == 2) {
8240 return array($obj->localtax2_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
8241 } else {
8242 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);
8243 }
8244 }
8245 }
8246
8247 return array();
8248}
8249
8260function get_product_vat_for_country($idprod, $thirdpartytouseforcountry, $idprodfournprice = 0)
8261{
8262 global $db, $mysoc;
8263
8264 require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
8265
8266 $ret = 0;
8267 $found = 0;
8268
8269 if ($idprod > 0) {
8270 // Load product
8271 $product = new Product($db);
8272 $product->fetch($idprod);
8273
8274 if (($mysoc->country_code == $thirdpartytouseforcountry->country_code)
8275 || (in_array($mysoc->country_code, array('FR', 'MC')) && in_array($thirdpartytouseforcountry->country_code, array('FR', 'MC')))
8276 || (in_array($mysoc->country_code, array('MQ', 'GP')) && in_array($thirdpartytouseforcountry->country_code, array('MQ', 'GP')))
8277 ) {
8278 // If country of thirdparty to consider is ours
8279 if ($idprodfournprice > 0) { // We want vat for product for a "supplier" object
8280 $result = $product->get_buyprice($idprodfournprice, 0, 0, '');
8281 if ($result > 0) {
8282 $ret = $product->vatrate_supplier;
8283 if ($product->default_vat_code_supplier) {
8284 $ret .= ' (' . $product->default_vat_code_supplier . ')';
8285 }
8286 $found = 1;
8287 }
8288 }
8289 if (!$found) {
8290 $ret = $product->tva_tx; // Default sales vat of product
8291 if ($product->default_vat_code) {
8292 $ret .= ' (' . $product->default_vat_code . ')';
8293 }
8294 $found = 1;
8295 }
8296 } else {
8297 // TODO Read default product vat according to product and an other countrycode.
8298 // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
8299 }
8300 }
8301
8302 if (!$found) {
8303 if (!getDolGlobalString('MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS')) {
8304 // 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).
8305 $sql = "SELECT t.taux as vat_rate, t.code as default_vat_code";
8306 $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t, " . MAIN_DB_PREFIX . "c_country as c";
8307 $sql .= " WHERE t.active = 1 AND t.fk_pays = c.rowid AND c.code = '" . $db->escape($thirdpartytouseforcountry->country_code) . "'";
8308 $sql .= " AND t.entity IN (" . getEntity('c_tva') . ")";
8309 $sql .= " ORDER BY t.use_default DESC, t.taux DESC, t.code ASC, t.recuperableonly ASC";
8310 $sql .= $db->plimit(1);
8311
8312 $resql = $db->query($sql);
8313 if ($resql) {
8314 $obj = $db->fetch_object($resql);
8315 if ($obj) {
8316 $ret = $obj->vat_rate;
8317 if ($obj->default_vat_code) {
8318 $ret .= ' (' . $obj->default_vat_code . ')';
8319 }
8320 }
8321 $db->free($resql);
8322 } else {
8323 dol_print_error($db);
8324 }
8325 } else {
8326 // Forced value if autodetect fails. MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS can be
8327 // '1.23'
8328 // or '1.23 (CODE)'
8329 $defaulttx = '';
8330 if (getDolGlobalString('MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS') != 'none') {
8331 $defaulttx = getDolGlobalString('MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS');
8332 }
8333 /*if (preg_match('/\‍((.*)\‍)/', $defaulttx, $reg)) {
8334 $defaultcode = $reg[1];
8335 $defaulttx = preg_replace('/\s*\‍(.*\‍)/', '', $defaulttx);
8336 }*/
8337
8338 $ret = $defaulttx;
8339 }
8340 }
8341
8342 dol_syslog("get_product_vat_for_country: ret=" . $ret);
8343
8344 return $ret;
8345}
8346
8356function get_product_localtax_for_country($idprod, $local, $thirdpartytouseforcountry)
8357{
8358 global $db, $mysoc;
8359
8360 if (!class_exists('Product')) {
8361 require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
8362 }
8363
8364 $ret = 0;
8365 $found = 0;
8366
8367 if ($idprod > 0) {
8368 // Load product
8369 $product = new Product($db);
8370 $result = $product->fetch($idprod);
8371
8372 if ($mysoc->country_code == $thirdpartytouseforcountry->country_code) { // If selling country is ours
8373 /* Not defined yet, so we don't use this
8374 if ($local==1) $ret=$product->localtax1_tx;
8375 elseif ($local==2) $ret=$product->localtax2_tx;
8376 $found=1;
8377 */
8378 } else {
8379 // TODO Read default product vat according to product and another countrycode.
8380 // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
8381 }
8382 }
8383
8384 if (!$found) {
8385 // If vat of product for the country not found or not defined, we return higher vat of country.
8386 $sql = "SELECT taux as vat_rate, localtax1, localtax2";
8387 $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t, " . MAIN_DB_PREFIX . "c_country as c";
8388 $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='" . $db->escape($thirdpartytouseforcountry->country_code) . "'";
8389 $sql .= " AND t.entity IN (" . getEntity('c_tva') . ")";
8390 $sql .= " ORDER BY t.taux DESC, t.recuperableonly ASC";
8391 $sql .= $db->plimit(1);
8392
8393 $resql = $db->query($sql);
8394 if ($resql) {
8395 $obj = $db->fetch_object($resql);
8396 if ($obj) {
8397 if ($local == 1) {
8398 $ret = $obj->localtax1;
8399 } elseif ($local == 2) {
8400 $ret = $obj->localtax2;
8401 }
8402 }
8403 } else {
8404 dol_print_error($db);
8405 }
8406 }
8407
8408 dol_syslog("get_product_localtax_for_country: ret=" . $ret);
8409 return $ret;
8410}
8411
8430function get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
8431{
8432 global $mysoc, $db, $hookmanager;
8433
8434 require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
8435
8436 // Note: possible values for tva_assuj are 0/1 or franchise/reel
8437 $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;
8438
8439 if (empty($thirdparty_seller->country_code)) {
8440 $thirdparty_seller->country_code = $mysoc->country_code;
8441 }
8442 $seller_country_code = $thirdparty_seller->country_code;
8443 $seller_in_cee = isInEEC($thirdparty_seller);
8444
8445 if (empty($thirdparty_buyer->country_code)) {
8446 $thirdparty_buyer->country_code = $mysoc->country_code;
8447 }
8448 $buyer_country_code = $thirdparty_buyer->country_code;
8449 $buyer_in_cee = isInEEC($thirdparty_buyer);
8450
8451 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'));
8452
8453 $vatvalue = 0;
8454 $vatrule = '';
8455
8456 // 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)
8457 // we use the buyer VAT.
8458 if (getDolGlobalString('SERVICE_ARE_ECOMMERCE_200238EC')) {
8459 if ($seller_in_cee && $buyer_in_cee) {
8460 $isacompany = $thirdparty_buyer->isACompany();
8461 if ($isacompany && !getDolGlobalString('MAIN_USE_VAT_ZERO_FOR_COMPANIES_IN_EEC_EVEN_IF_VAT_ID_UNKNOWN')) {
8462 require_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php';
8463 if (!isValidVATID($thirdparty_buyer)) {
8464 $isacompany = 0;
8465 }
8466 }
8467
8468 if (!$isacompany) {
8469 $vatvalue = get_product_vat_for_country($idprod, $thirdparty_buyer, $idprodfournprice);
8470 $vatrule = 'VATRULE 0';
8471 }
8472 }
8473 }
8474
8475 // If seller does not use VAT, default VAT is 0. End of rule.
8476 if (empty($vatrule) && !$seller_use_vat) {
8477 //print 'VATRULE 1';
8478 // TODO get the VAT Code of exemption asked into setup if country isInEEC (from an array list of possible
8479 // values like VATEX-EU-132-*, VATEX-FR-FRANCHISE, VATEX-EU-AE...
8480 // When we had recorded it, we also added a corresponding entry into table of vat code if it does not exists yet.
8481 // Here we test if entry for the VAT exemption code exists in llx_vat, we can return '0 (VATEX-EU-132-xx)'
8482 // If not, we add it and we return '0 (VATEX-EU-132-xx)'
8483 $vatvalue = 0;
8484 $vatrule = 'VATRULE 1';
8485 }
8486
8487 // 'VATRULE 2' - Force VAT if a buyer department is defined on vat rates dictionary
8488 if (empty($vatrule) && !empty($thirdparty_buyer->state_id)) {
8489 $sql = "SELECT d.rowid, t.taux as vat_default_rate, t.code as vat_default_code ";
8490 $sql .= " FROM " . $db->prefix() . "c_tva as t";
8491 $sql .= " INNER JOIN " . $db->prefix() . "c_departements as d ON t.fk_department_buyer = d.rowid";
8492 $sql .= " WHERE d.rowid = " . ((int) $thirdparty_buyer->state_id);
8493 $sql .= " AND t.active > 0";
8494 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
8495 $sql .= " ORDER BY t.use_default DESC, t.taux DESC, t.code ASC, t.recuperableonly ASC";
8496
8497 $res = $db->query($sql);
8498 if ($res) {
8499 if ($db->num_rows($res)) {
8500 $obj = $db->fetch_object($res);
8501
8502 $vatvalue = $obj->vat_default_rate . ' (' . $obj->vat_default_code . ')';
8503 $vatrule = 'VATRULE 2';
8504 }
8505 $db->free($res);
8506 }
8507 }
8508
8509 // If the (seller country = buyer country) then the default VAT = VAT of the product sold. End of rule.
8510 if (empty($vatrule) && (
8511 ($seller_country_code == $buyer_country_code)
8512 || (in_array($seller_country_code, array('FR', 'MC')) && in_array($buyer_country_code, array('FR', 'MC')))
8513 || (in_array($seller_country_code, array('MQ', 'GP')) && in_array($buyer_country_code, array('MQ', 'GP'))) // We should be able to manage the case of MQ, GP, ... with a deicated vat rate at previous step.
8514 )) { // Warning ->country_code not always defined
8515 //print 'VATRULE 3';
8516 $tmpvat = get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
8517
8518 if ($seller_country_code == 'IN' && getDolGlobalString('MAIN_SALETAX_AUTOSWITCH_I_CS_FOR_INDIA')) {
8519 // Special case for india.
8520 //print 'VATRULE 3b';
8521 $reg = array();
8522 if (preg_match('/\‍(C\+S-(\d+(?:\.\d+)?)\‍)/', $tmpvat, $reg) && $thirdparty_seller->state_id != $thirdparty_buyer->state_id) {
8523 // we must revert the C+S into I (rate of I-xx is xx)
8524 $tmpvat = $reg[1].' (I-'.$reg[1].')';
8525 } elseif (preg_match('/\‍(I-(\d+(?:\.\d+)?)\‍)/', $tmpvat, $reg) && $thirdparty_seller->state_id == $thirdparty_buyer->state_id) {
8526 // we must revert the I into C+S (rate of C+S-xx is 0, xx is shared between localtax1 and localtax2)
8527 $tmpvat = '0 (C+S-'.$reg[1].')';
8528 }
8529 }
8530
8531 $vatvalue = $tmpvat;
8532 $vatrule = 'VATRULE 3b';
8533 }
8534
8535 // 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.
8536 // 'VATRULE 4' - Not supported
8537
8538 // If (seller and buyer in the European Community) and (buyer = individual) then VAT by default = VAT of the product sold. End of rule
8539 // If (seller and buyer in European Community) and (buyer = company) then VAT by default=0. End of rule
8540 if (empty($vatrule) && ($seller_in_cee && $buyer_in_cee)) {
8541 $isacompany = $thirdparty_buyer->isACompany();
8542 if ($isacompany && !getDolGlobalString('MAIN_USE_VAT_ZERO_FOR_COMPANIES_IN_EEC_EVEN_IF_VAT_ID_UNKNOWN')) {
8543 require_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php';
8544 if (!isValidVATID($thirdparty_buyer)) {
8545 $isacompany = 0;
8546 }
8547 }
8548
8549 if (!$isacompany) {
8550 //print 'VATRULE 5';
8551 $vatvalue = get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
8552 $vatrule = 'VATRULE 5';
8553 } else {
8554 //print 'VATRULE 6';
8555 // TODO This is the case of VAT exemption 'VATEX-EU-IC'
8556 // If entry for the VAT exemption code exists in llx_vat, we can return '0 (VATEX-EU-IC)'
8557 // If not, we add it and we return '0 (VATEX-EU-IC)'
8558 $vatvalue = 0;
8559 $vatrule = 'VATRULE 6';
8560 }
8561 }
8562
8563 // 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
8564 // I don't see any use case that need this rule, this case is on only if MAIN_USE_VAT_OF_PRODUCT_FOR_INDIVIDUAL_CUSTOMER_OUT_OF_EEC set
8565 if (empty($vatrule) && getDolGlobalString('MAIN_USE_VAT_OF_PRODUCT_FOR_INDIVIDUAL_CUSTOMER_OUT_OF_EEC') && empty($buyer_in_cee)) {
8566 $isacompany = $thirdparty_buyer->isACompany();
8567 if (!$isacompany) {
8568 $vatvalue = get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
8569 $vatrule = 'VATRULE extra';
8570 //print 'VATRULE extra';
8571 }
8572 }
8573
8574 // Otherwise the VAT proposed by default=0. End of rule.
8575 // Rem: This means that at least one of the 2 is outside the European Community and the country differs
8576 //print 'VATRULE 7';
8577 // TODO This is the case of VAT exemption 'VATEX-EU-G'
8578 // If entry for the VAT exemption code exists in llx_vat, we can return '0 (VATEX-xxx)'
8579 // If not, we add it and we return '0 (VATEX-xxx)'
8580
8581 // Allow an external module to bypass the calculation of prices
8582 $parameters = array('vatvalue' => $vatvalue, 'vatrule' => $vatrule);
8583 $tmpobject = null;
8584 $tmpaction = '';
8585 // @phan-suppress-next-line PhanPluginConstantVariableNull
8586 $reshook = $hookmanager->executeHooks('get_default_tva', $parameters, $tmpobject, $tmpaction); // @phan-suppress-current-line PhanPluginConstantVariableNull
8587 if ($reshook > 0 && !empty($hookmanager->resArray['vatvalue'])) {
8588 $vatvalue = $hookmanager->resArray['vatvalue'];
8589 $vatrule = $hookmanager->resArray['vatrule']; // For information
8590 }
8591
8592 return $vatvalue;
8593}
8594
8595
8606function get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
8607{
8608 global $db;
8609
8610 if ($idprodfournprice > 0) {
8611 if (!class_exists('ProductFournisseur')) {
8612 require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.product.class.php';
8613 }
8614 $prodprice = new ProductFournisseur($db);
8615 $prodprice->fetch_product_fournisseur_price($idprodfournprice);
8616 return $prodprice->fourn_tva_npr;
8617 } elseif ($idprod > 0) {
8618 if (!class_exists('Product')) {
8619 require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
8620 }
8621 $prod = new Product($db);
8622 $prod->fetch($idprod);
8623 return $prod->tva_npr;
8624 }
8625
8626 return 0;
8627}
8628
8642function get_default_localtax($thirdparty_seller, $thirdparty_buyer, $local, $idprod = 0)
8643{
8644 global $mysoc;
8645
8646 if (!is_object($thirdparty_seller)) {
8647 return -1;
8648 }
8649 if (!is_object($thirdparty_buyer)) {
8650 return -1;
8651 }
8652
8653 if (empty($thirdparty_seller->country_code)) {
8654 $thirdparty_seller->country_code = $mysoc->country_code;
8655 }
8656 $seller_country_code = $thirdparty_seller->country_code;
8657 //$seller_in_cee = isInEEC($thirdparty_seller);
8658
8659 if (empty($thirdparty_buyer->country_code)) {
8660 $thirdparty_buyer->country_code = $mysoc->country_code;
8661 }
8662 $buyer_country_code = $thirdparty_buyer->country_code;
8663 //$buyer_in_cee = isInEEC($thirdparty_buyer);
8664
8665 if ($local == 1) { // Localtax 1
8666 if ($mysoc->country_code == 'ES') {
8667 if (is_numeric($thirdparty_buyer->localtax1_assuj) && !$thirdparty_buyer->localtax1_assuj) {
8668 return 0;
8669 }
8670 } else {
8671 // Si vendeur non assujeti a Localtax1, localtax1 par default=0
8672 if (is_numeric($thirdparty_seller->localtax1_assuj) && !$thirdparty_seller->localtax1_assuj) {
8673 return 0;
8674 }
8675 if (!is_numeric($thirdparty_seller->localtax1_assuj) && $thirdparty_seller->localtax1_assuj == 'localtax1off') {
8676 return 0;
8677 }
8678 }
8679 } elseif ($local == 2) { //I Localtax 2
8680 // Si vendeur non assujeti a Localtax2, localtax2 par default=0
8681 if (is_numeric($thirdparty_seller->localtax2_assuj) && !$thirdparty_seller->localtax2_assuj) {
8682 return 0;
8683 }
8684 if (!is_numeric($thirdparty_seller->localtax2_assuj) && $thirdparty_seller->localtax2_assuj == 'localtax2off') {
8685 return 0;
8686 }
8687 }
8688
8689 if ($seller_country_code == $buyer_country_code) {
8690 return get_product_localtax_for_country($idprod, $local, $thirdparty_seller);
8691 }
8692
8693 return 0;
8694}
8695
8704function yn($yesno, $format = 1, $color = 0)
8705{
8706 global $langs;
8707
8708 $result = 'unknown';
8709 $classname = '';
8710 if ($yesno === true || (int) $yesno == 1 || (isset($yesno) && (strtolower($yesno) == 'yes' || strtolower($yesno) == 'true'))) { // To set to 'no' before the test because of the '== 0'
8711 $result = $langs->trans('yes');
8712 if ($format == 1 || $format == 3) {
8713 $result = $langs->trans("Yes");
8714 }
8715 if ($format == 2) {
8716 $result = '<input type="checkbox" value="1" checked disabled>';
8717 }
8718 if ($format == 3) {
8719 $result = '<input type="checkbox" value="1" checked disabled> ' . $result;
8720 }
8721 if ($format == 4 || !is_numeric($format)) {
8722 $result = img_picto(is_numeric($format) ? '' : $format, 'check');
8723 }
8724
8725 $classname = 'ok';
8726 } else {
8727 $result = $langs->trans("no");
8728 if ($format == 1 || $format == 3) {
8729 $result = $langs->trans("No");
8730 }
8731 if ($format == 2) {
8732 $result = '<input type="checkbox" value="0" disabled>';
8733 }
8734 if ($format == 3) {
8735 $result = '<input type="checkbox" value="0" disabled> ' . $result;
8736 }
8737 if ($format == 4 || !is_numeric($format)) {
8738 $result = img_picto(is_numeric($format) ? '' : $format, 'uncheck');
8739 }
8740
8741 if ($color == 2) {
8742 $classname = 'ok';
8743 } else {
8744 $classname = 'error';
8745 }
8746 }
8747 if ($color) {
8748 return '<span class="' . $classname . '">' . $result . '</span>';
8749 }
8750 return $result;
8751}
8752
8771function get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart = '')
8772{
8773 if (empty($modulepart) && is_object($object)) {
8774 if (!empty($object->module)) {
8775 $modulepart = $object->module;
8776 } elseif (!empty($object->element)) {
8777 $modulepart = $object->element;
8778 }
8779 }
8780
8781 $path = '';
8782
8783 // Define $arrayforoldpath that is module path using a hierarchy on more than 1 level.
8784 $arrayforoldpath = array('cheque' => 2, 'category' => 2, 'supplier_invoice' => 2, 'invoice_supplier' => 2, 'mailing' => 2, 'supplier_payment' => 2);
8785 if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
8786 $arrayforoldpath['product'] = 2;
8787 }
8788
8789 if (empty($level) && array_key_exists($modulepart, $arrayforoldpath)) {
8790 $level = $arrayforoldpath[$modulepart];
8791 }
8792 if (!empty($level) && array_key_exists($modulepart, $arrayforoldpath)) {
8793 // This part should be removed once all code is using "get_exdir" to forge path, with parameter $object and $modulepart provided.
8794 if (empty($num) && is_object($object)) {
8795 $num = $object->id;
8796 }
8797 if (empty($alpha)) {
8798 $num = preg_replace('/([^0-9])/i', '', $num);
8799 } else {
8800 $num = preg_replace('/^.*\-/i', '', $num);
8801 }
8802 $num = substr("000" . $num, -$level);
8803 if ($level == 1) {
8804 $path = substr($num, 0, 1);
8805 }
8806 if ($level == 2) {
8807 $path = substr($num, 1, 1) . '/' . substr($num, 0, 1);
8808 }
8809 if ($level == 3) {
8810 $path = substr($num, 2, 1) . '/' . substr($num, 1, 1) . '/' . substr($num, 0, 1);
8811 }
8812 } else {
8813 // We will enhance here a common way of forging path for document storage.
8814 // In a future, we may distribute directories on several levels depending on setup and object.
8815 // Here, $object->id, $object->ref and $modulepart are required.
8816 if (in_array($modulepart, array('societe', 'thirdparty')) && $object instanceof Societe) {
8817 // 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
8818 $path = dol_sanitizeFileName((string) $object->id);
8819 } else {
8820 $path = dol_sanitizeFileName(empty($object->ref) ? (string) ((is_object($object) && property_exists($object, 'id')) ? $object->id : '') : $object->ref);
8821 }
8822 }
8823
8824 if (empty($withoutslash) && !empty($path)) {
8825 $path .= '/';
8826 }
8827
8828 return $path;
8829}
8830
8839function dol_mkdir($dir, $dataroot = '', $newmask = '')
8840{
8841 dol_syslog("functions.lib::dol_mkdir: dir=" . $dir, LOG_INFO);
8842
8843 $dir = dol_sanitizePathName($dir, '_', 0);
8844
8845 $dir_osencoded = dol_osencode($dir);
8846 if (@is_dir($dir_osencoded)) {
8847 return 0;
8848 }
8849
8850 $nberr = 0;
8851 $nbcreated = 0;
8852
8853 $ccdir = '';
8854 if (!empty($dataroot)) {
8855 // Remove data root from loop
8856 $dir = str_replace($dataroot . '/', '', $dir);
8857 $ccdir = $dataroot . '/';
8858 }
8859
8860 $cdir = explode("/", $dir);
8861 $num = count($cdir);
8862 for ($i = 0; $i < $num; $i++) {
8863 if ($i > 0) {
8864 $ccdir .= '/' . $cdir[$i];
8865 } else {
8866 $ccdir .= $cdir[$i];
8867 }
8868 $regs = array();
8869 if (preg_match("/^.:$/", $ccdir, $regs)) {
8870 continue; // If the Windows path is incomplete, continue with next directory
8871 }
8872
8873 // Attention, is_dir() can fail event if the directory exists
8874 // (i.e. according the open_basedir configuration)
8875 if ($ccdir) {
8876 $ccdir_osencoded = dol_osencode($ccdir);
8877 if (!@is_dir($ccdir_osencoded)) {
8878 dol_syslog("functions.lib::dol_mkdir: Directory '" . $ccdir . "' is not found (does not exists or is outside open_basedir PHP setting).", LOG_DEBUG);
8879
8880 umask(0);
8881 $dirmaskdec = octdec((string) $newmask);
8882 if (empty($newmask)) {
8883 $dirmaskdec = octdec(getDolGlobalString('MAIN_UMASK', '0755'));
8884 }
8885 $dirmaskdec |= octdec('0111'); // Set x bit required for directories
8886 if (!@mkdir($ccdir_osencoded, $dirmaskdec)) {
8887 // If the is_dir has returned a false information, we arrive here
8888 dol_syslog("functions.lib::dol_mkdir: Fails to create directory '" . $ccdir . "' (no permission to write into parent or directory already exists).", LOG_WARNING);
8889 $nberr++;
8890 } else {
8891 dol_syslog("functions.lib::dol_mkdir: Directory '" . $ccdir . "' created", LOG_DEBUG);
8892 $nberr = 0; // At this point in the code, the previous failures can be ignored -> set $nberr to 0
8893 $nbcreated++;
8894 }
8895 } else {
8896 $nberr = 0; // At this point in the code, the previous failures can be ignored -> set $nberr to 0
8897 }
8898 }
8899 }
8900 return ($nberr ? -$nberr : $nbcreated);
8901}
8902
8903
8911function dolChmod($filepath, $newmask = '')
8912{
8913 if (!empty($newmask)) {
8914 @chmod($filepath, octdec($newmask));
8915 } elseif (getDolGlobalString('MAIN_UMASK')) {
8916 @chmod($filepath, octdec(getDolGlobalString('MAIN_UMASK')));
8917 }
8918}
8919
8920
8926function picto_required()
8927{
8928 return '<span class="fieldrequired">*</span>';
8929}
8930
8931
8948function dol_string_nohtmltag($stringtoclean, $removelinefeed = 1, $pagecodeto = 'UTF-8', $strip_tags = 0, $removedoublespaces = 1)
8949{
8950 if (is_null($stringtoclean)) {
8951 return '';
8952 }
8953
8954 if ($removelinefeed == 2) {
8955 $stringtoclean = preg_replace('/<br[^>]*>(\n|\r)+/ims', '<br>', $stringtoclean);
8956 }
8957 $temp = preg_replace('/<br[^>]*>/i', "\n", $stringtoclean);
8958
8959 // 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)
8960 $temp = dol_html_entity_decode($temp, ENT_COMPAT | ENT_HTML5, $pagecodeto);
8961
8962 $temp = str_replace('< ', '__ltspace__', $temp);
8963 $temp = str_replace('<:', '__lttwopoints__', $temp);
8964
8965 if ($strip_tags) {
8966 $temp = strip_tags($temp);
8967 } else {
8968 // 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).
8969 $pattern = "/<[^<>]+>/";
8970 // Example of $temp: <a href="/myurl" title="<u>A title</u>">0000-021</a>
8971 // pass 1 - $temp after pass 1: <a href="/myurl" title="A title">0000-021
8972 // pass 2 - $temp after pass 2: 0000-021
8973 $tempbis = $temp;
8974 do {
8975 $temp = $tempbis;
8976 $tempbis = str_replace('<>', '', $temp); // No reason to have this into a text, except if value is to try bypass the next html cleaning
8977 $tempbis = preg_replace($pattern, '', $tempbis);
8978 //$idowhile++; print $temp.'-'.$tempbis."\n"; if ($idowhile > 100) break;
8979 } while ($tempbis != $temp);
8980
8981 $temp = $tempbis;
8982
8983 // 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).
8984 $temp = preg_replace('/<+([a-z]+)/i', '\1', $temp);
8985 }
8986
8987 $temp = dol_html_entity_decode($temp, ENT_COMPAT, $pagecodeto);
8988
8989 // Remove also carriage returns
8990 if ($removelinefeed == 1) {
8991 $temp = str_replace(array("\r\n", "\r", "\n"), " ", $temp);
8992 }
8993
8994 // And double spaces
8995 if ($removedoublespaces) {
8996 while (strpos($temp, " ") !== false) {
8997 $temp = str_replace(" ", " ", $temp);
8998 }
8999 }
9000
9001 $temp = str_replace('__ltspace__', '< ', $temp);
9002 $temp = str_replace('__lttwopoints__', '<:', $temp);
9003
9004 return trim($temp);
9005}
9006
9026function dol_string_onlythesehtmltags($stringtoclean, $cleanalsosomestyles = 1, $removeclassattribute = 1, $cleanalsojavascript = 0, $allowiframe = 0, $allowed_tags = array(), $allowlink = 0, $allowscript = 0, $allowstyle = 0, $allowphp = 0)
9027{
9028 if (empty($allowed_tags)) {
9029 $allowed_tags = array(
9030 // HTML 4
9031 "html",
9032 "head",
9033 "body",
9034 "article",
9035 "a",
9036 "abbr",
9037 "b",
9038 "blockquote",
9039 "br",
9040 "cite",
9041 "div",
9042 "dl",
9043 "dd",
9044 "dt",
9045 "em",
9046 "font",
9047 "img",
9048 "ins",
9049 "hr",
9050 "i",
9051 "li",
9052 "ol",
9053 "p",
9054 "q",
9055 "s",
9056 "span",
9057 "strike",
9058 "strong",
9059 "title",
9060 "table",
9061 "tr",
9062 "th",
9063 "td",
9064 "u",
9065 "ul",
9066 "sup",
9067 "sub",
9068 "blockquote",
9069 "pre",
9070 "h1",
9071 "h2",
9072 "h3",
9073 "h4",
9074 "h5",
9075 "h6",
9076
9077 // HTML 5
9078 "footer",
9079 "header",
9080 "menu",
9081 "menuitem",
9082 "nav",
9083 "section"
9084 );
9085 }
9086 $allowed_tags[] = "comment"; // this tags is added to manage comment <!--...--> that are replaced into <comment>...</comment>
9087 if ($allowiframe) {
9088 if (!in_array('iframe', $allowed_tags)) {
9089 $allowed_tags[] = "iframe";
9090 }
9091 }
9092 if ($allowlink) {
9093 if (!in_array('link', $allowed_tags)) {
9094 $allowed_tags[] = "link";
9095 }
9096 if (!in_array('meta', $allowed_tags)) {
9097 $allowed_tags[] = "meta";
9098 }
9099 }
9100 if ($allowscript) {
9101 if (!in_array('script', $allowed_tags)) {
9102 $allowed_tags[] = "script";
9103 }
9104 }
9105 if ($allowstyle) {
9106 if (!in_array('style', $allowed_tags)) {
9107 $allowed_tags[] = "style";
9108 }
9109 }
9110
9111 $allowed_tags_string = implode("><", $allowed_tags);
9112 $allowed_tags_string = '<' . $allowed_tags_string . '>';
9113
9114 $stringtoclean = str_replace('<!DOCTYPE html>', '__!DOCTYPE_HTML__', $stringtoclean); // Replace DOCTYPE to avoid to have it removed by the strip_tags
9115
9116 $stringtoclean = dol_string_nounprintableascii($stringtoclean, 0);
9117
9118 //$stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
9119 $stringtoclean = preg_replace('/<!--([^>]*)-->/', '<comment>\1</comment>', $stringtoclean);
9120
9121 if ($allowphp) {
9122 $allowed_tags[] = "commentphp";
9123 $stringtoclean = preg_replace('/^<\?php([^"]+)\?>$/i', '<commentphp>\1__</commentphp>', $stringtoclean); // Note: <?php ... > is allowed only if on the same line
9124 $stringtoclean = preg_replace('/"<\?php([^"]+)\?>"/i', '"<commentphp>\1</commentphp>"', $stringtoclean); // Note: "<?php ... >" is allowed only if on the same line
9125 }
9126
9127 $stringtoclean = preg_replace('/&colon;/i', ':', $stringtoclean);
9128 $stringtoclean = preg_replace('/&#58;|&#0+58|&#x3A/i', '', $stringtoclean); // refused string ':' encoded (no reason to have a : encoded like this) to disable 'javascript:...'
9129
9130 // Remove all HTML tags
9131 $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
9132
9133 if ($cleanalsosomestyles) { // Clean for remaining html tags
9134 $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
9135 }
9136 if ($removeclassattribute) { // Clean for remaining html tags
9137 $temp = preg_replace('/(<[^>]+)\s+class=((["\']).*?\\3|\\w*)/i', '\\1', $temp);
9138 }
9139
9140 // Remove 'javascript:' that we should not find into a text
9141 // 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)).
9142 if ($cleanalsojavascript) {
9143 $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);
9144 }
9145
9146 $temp = str_replace('__!DOCTYPE_HTML__', '<!DOCTYPE html>', $temp); // Restore the DOCTYPE
9147
9148 if ($allowphp) {
9149 $temp = preg_replace('/<commentphp>(.*)<\/commentphp>/', '<?php\1?>', $temp); // Restore php code
9150 }
9151
9152 $temp = preg_replace('/<comment>([^>]*)<\/comment>/', '<!--\1-->', $temp); // Restore html comments
9153
9154
9155 return $temp;
9156}
9157
9158
9171function dol_string_onlythesehtmlattributes($stringtoclean, $allowed_attributes = null)
9172{
9173 if (is_null($allowed_attributes)) {
9174 $allowed_attributes = array(
9175 // HTML 4
9176 "allow",
9177 "allowfullscreen",
9178 "alt",
9179 "async",
9180 "class",
9181 "contenteditable",
9182 "crossorigin",
9183 "data-html",
9184 "frameborder",
9185 "height",
9186 "href",
9187 "id",
9188 "name",
9189 "property",
9190 "rel",
9191 "src",
9192 "style",
9193 "target",
9194 "title",
9195 "type",
9196 "width",
9197
9198 // HTML5
9199 "footer",
9200 "header",
9201 "menu",
9202 "menuitem",
9203 "nav",
9204 "section"
9205 );
9206 }
9207 // Always add content and http-equiv for meta tags, required to force encoding and keep html content in utf8 by load/saveHTML functions.
9208 if (!in_array("content", $allowed_attributes)) {
9209 $allowed_attributes[] = "content";
9210 }
9211 if (!in_array("http-equiv", $allowed_attributes)) {
9212 $allowed_attributes[] = "http-equiv";
9213 }
9214
9215 if (class_exists('DOMDocument') && !empty($stringtoclean)) {
9216 //$stringtoclean = '<?xml encoding="UTF-8"><html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"></head><body>'.$stringtoclean.'</body></html>';
9217 $stringtoclean = '<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"></head><body>' . $stringtoclean . '</body></html>';
9218
9219 // Warning: loadHTML does not support HTML5 on old libxml versions.
9220 $dom = new DOMDocument('', 'UTF-8');
9221 // If $stringtoclean is wrong, it will generates warnings. So we disable warnings and restore them later.
9222 $savwarning = error_reporting();
9223 error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE);
9224 $dom->loadHTML($stringtoclean, LIBXML_ERR_NONE | LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD | LIBXML_NONET | LIBXML_NOWARNING | LIBXML_NOXMLDECL);
9225 error_reporting($savwarning);
9226
9227 if ($dom instanceof DOMDocument) {
9228 for ($els = $dom->getElementsByTagname('*'), $i = $els->length - 1; $i >= 0; $i--) {
9229 $el = $els->item($i);
9230 if (!$el instanceof DOMElement) {
9231 continue;
9232 }
9233 $attrs = $el->attributes;
9234 for ($ii = $attrs->length - 1; $ii >= 0; $ii--) {
9235 //var_dump($attrs->item($ii));
9236 if (!empty($attrs->item($ii)->name)) {
9237 if (! in_array($attrs->item($ii)->name, $allowed_attributes)) {
9238 // Delete attribute if not into allowed_attributes @phan-suppress-next-line PhanUndeclaredMethod
9239 $els->item($i)->removeAttribute($attrs->item($ii)->name);
9240 } elseif (in_array($attrs->item($ii)->name, array('style'))) {
9241 // If attribute is 'style'
9242 $valuetoclean = $attrs->item($ii)->value;
9243
9244 if (isset($valuetoclean)) {
9245 do {
9246 $oldvaluetoclean = $valuetoclean;
9247 $valuetoclean = preg_replace('/\/\*.*\*\//m', '', $valuetoclean); // clean css comments
9248 $valuetoclean = preg_replace('/position\s*:\s*[a-z]+/mi', '', $valuetoclean);
9249 if ($els->item($i)->tagName == 'a') { // more paranoiac cleaning for clickable tags.
9250 $valuetoclean = preg_replace('/display\s*:/mi', '', $valuetoclean);
9251 $valuetoclean = preg_replace('/z-index\s*:/mi', '', $valuetoclean);
9252 $valuetoclean = preg_replace('/\s+(top|left|right|bottom)\s*:/mi', '', $valuetoclean);
9253 }
9254
9255 // We do not allow logout|passwordforgotten.php and action= into the content of a "style" tag
9256 $valuetoclean = preg_replace('/(logout|passwordforgotten)\.php/mi', '', $valuetoclean);
9257 $valuetoclean = preg_replace('/action=/mi', '', $valuetoclean);
9258 } while ($oldvaluetoclean != $valuetoclean);
9259 }
9260
9261 $attrs->item($ii)->value = $valuetoclean;
9262 }
9263 }
9264 }
9265 }
9266 }
9267
9268 $dom->encoding = 'UTF-8';
9269
9270 $return = $dom->saveHTML(); // This may add a LF at end of lines, so we will trim later
9271 //$return = '<html><body>aaaa</p>bb<p>ssdd</p>'."\n<p>aaa</p>aa<p>bb</p>";
9272
9273 //$return = preg_replace('/^'.preg_quote('<?xml encoding="UTF-8">', '/').'/', '', $return);
9274 $return = preg_replace('/^' . preg_quote('<html><head><', '/') . '[^<>]*' . preg_quote('></head><body>', '/') . '/', '', $return);
9275 $return = preg_replace('/' . preg_quote('</body></html>', '/') . '$/', '', trim($return));
9276
9277 return trim($return);
9278 } else {
9279 return $stringtoclean;
9280 }
9281}
9282
9294function dol_string_neverthesehtmltags($stringtoclean, $disallowed_tags = array('textarea'), $cleanalsosomestyles = 0)
9295{
9296 $temp = $stringtoclean;
9297 foreach ($disallowed_tags as $tagtoremove) {
9298 $temp = preg_replace('/<\/?' . $tagtoremove . '>/', '', $temp);
9299 $temp = preg_replace('/<\/?' . $tagtoremove . '\s+[^>]*>/', '', $temp);
9300 }
9301
9302 if ($cleanalsosomestyles) {
9303 $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
9304 }
9305
9306 return $temp;
9307}
9308
9309
9319function dolCloseUnclosedHtmlTags($text)
9320{
9321 if (!is_string($text) || $text === '') {
9322 return $text;
9323 }
9324
9325 // Tags that never carry a closing tag
9326 $selfclosing = array('br', 'hr', 'img', 'input', 'meta', 'link', 'source', 'col', 'area', 'base', 'embed', 'param', 'track', 'wbr');
9327
9328 $opened = array();
9329 if (preg_match_all('/<\s*(\/?)([a-zA-Z][a-zA-Z0-9]*)[^>]*?(\/?)\s*>/', $text, $matches, PREG_SET_ORDER)) {
9330 foreach ($matches as $match) {
9331 $tag = strtolower($match[2]);
9332 if (in_array($tag, $selfclosing) || !empty($match[3])) {
9333 continue;
9334 }
9335 if (empty($match[1])) {
9336 $opened[] = $tag;
9337 } else {
9338 // Close the most recent matching opened tag, ignore a stray closing tag
9339 $idx = array_search($tag, array_reverse($opened, true), true);
9340 if ($idx !== false) {
9341 unset($opened[$idx]);
9342 }
9343 }
9344 }
9345 }
9346
9347 foreach (array_reverse($opened) as $tag) {
9348 $text .= '</'.$tag.'>';
9349 }
9350
9351 return $text;
9352}
9353
9363function dolGetFirstLineOfText($text, $nboflines = 1, $charset = 'UTF-8')
9364{
9365 if ($nboflines == 1) {
9366 if (dol_textishtml($text)) {
9367 $firstline = preg_replace('/<br[^>]*>.*$/s', '', $text); // The s pattern modifier means the . can match newline characters
9368 $firstline = preg_replace('/<div[^>]*>.*$/s', '', $firstline); // The s pattern modifier means the . can match newline characters
9369 } else {
9370 if (isset($text)) {
9371 $firstline = preg_replace('/[\n\r].*/', '', $text);
9372 } else {
9373 $firstline = '';
9374 }
9375 }
9376 return $firstline . (isset($firstline) && isset($text) && (strlen($firstline) != strlen($text)) ? '...' : '');
9377 } else {
9378 $ishtml = 0;
9379 if (dol_textishtml($text)) {
9380 $text = preg_replace('/\n/', '', $text);
9381 $ishtml = 1;
9382 $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
9383 } else {
9384 $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
9385 }
9386
9387 $text = strtr($text, $repTable);
9388 if ($charset == 'UTF-8') {
9389 $pattern = '/(<br[^>]*>)/Uu';
9390 } else {
9391 // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
9392 $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
9393 }
9394 $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
9395
9396 $firstline = '';
9397 $i = 0;
9398 $countline = 0;
9399 $lastaddediscontent = 1;
9400 while ($countline < $nboflines && isset($a[$i])) {
9401 if (preg_match('/<br[^>]*>/', $a[$i])) {
9402 if (array_key_exists($i + 1, $a) && !empty($a[$i + 1])) {
9403 $firstline .= ($ishtml ? "<br>\n" : "\n");
9404 // Is it a br for a new line of after a printed line ?
9405 if (!$lastaddediscontent) {
9406 $countline++;
9407 }
9408 $lastaddediscontent = 0;
9409 }
9410 } else {
9411 $firstline .= $a[$i];
9412 $lastaddediscontent = 1;
9413 $countline++;
9414 }
9415 $i++;
9416 }
9417
9418 $adddots = (isset($a[$i]) && (!preg_match('/<br[^>]*>/', $a[$i]) || (array_key_exists($i + 1, $a) && !empty($a[$i + 1]))));
9419 //unset($a);
9420 $ret = $firstline . ($adddots ? '...' : '');
9421 //exit;
9422 return $ret;
9423 }
9424}
9425
9426
9438function dol_nl2br($stringtoencode, $nl2brmode = 0, $forxml = false)
9439{
9440 if (is_null($stringtoencode)) {
9441 return '';
9442 }
9443
9444 if (!$nl2brmode) {
9445 return nl2br($stringtoencode, $forxml);
9446 } else {
9447 $ret = preg_replace('/(\r\n|\r|\n)/i', ($forxml ? '<br />' : '<br>'), $stringtoencode);
9448 return $ret;
9449 }
9450}
9451
9461function dol_htmlwithnojs($stringtoencode, $nouseofiframesandbox = 0, $check = 'restricthtml')
9462{
9463 if (empty($nouseofiframesandbox) && getDolGlobalString('MAIN_SECURITY_USE_SANDBOX_FOR_HTMLWITHNOJS')) {
9464 // TODO using sandbox on inline html content is not possible yet with current browsers
9465 //$s = '<iframe class="iframewithsandbox" sandbox><html><body>';
9466 //$s .= $stringtoencode;
9467 //$s .= '</body></html></iframe>';
9468 return $stringtoencode;
9469 } else {
9470 $out = $stringtoencode;
9471
9472 // First clean HTML content
9473 do {
9474 $oldstringtoclean = $out;
9475
9476 $outishtml = 0;
9477 if (dol_textishtml($out)) {
9478 $outishtml = 1;
9479 }
9480
9481 // HTML sanitizer by DOMDocument
9482 if (!empty($out) && getDolGlobalString('MAIN_RESTRICTHTML_ONLY_VALID_HTML') && $check != 'restricthtmlallowunvalid') {
9483 try {
9484 libxml_use_internal_errors(false); // Avoid to fill memory with xml errors
9485 if (LIBXML_VERSION < 20900) {
9486 // Avoid load of external entities (security problem).
9487 // Required only if LIBXML_VERSION < 20900
9488 // @phan-suppress-next-line PhanDeprecatedFunctionInternal
9489 libxml_disable_entity_loader(true);
9490 }
9491
9492 $dom = new DOMDocument();
9493 // Add a trick '<div class="tricktoremove">' to solve pb with text without parent tag
9494 // like '<h1>Foo</h1><p>bar</p>' that wrongly ends up, without the trick, with '<h1>Foo<p>bar</p></h1>'
9495 // like 'abc' that wrongly ends up, without the trick, with '<p>abc</p>'
9496 // Add also a trick <html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"> to solve utf8 lost.
9497 // I don't know what the xml encoding is the trick for
9498 if ($outishtml) {
9499 //$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>';
9500 $out = '<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"></head><body><div class="tricktoremove">' . $out . '</div></body></html>';
9501 //$out = '<html><head><meta charset="utf-8"></head><body><div class="tricktoremove">'.$out.'</div></body></html>';
9502 } else {
9503 //$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>';
9504 $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>';
9505 //$out = '<html><head><meta charset="utf-8"></head><body><div class="tricktoremove">'.dol_nl2br($out).'</div></body></html>';
9506 }
9507
9508 // Note: <a href="https://__[aaa]__/aaa.html"> is transformed into <a href="https://__[aaa]__/aaa.html">
9509 // We don't want that, so we protect __[xxx]__ by replacing [ and ] before loadHTML and restore them after saveHTML
9510 $out = preg_replace_callback(
9511 '/__\[([0-9a-zA-Z_]+)\]__/',
9516 function ($m) {
9517 return '__BRACKETSTART' . $m[1] . 'BRACKETEND__';
9518 },
9519 $out
9520 );
9521
9522 $dom->loadHTML($out, LIBXML_HTML_NODEFDTD | LIBXML_ERR_NONE | LIBXML_HTML_NOIMPLIED | LIBXML_NONET | LIBXML_NOWARNING | LIBXML_NOERROR | LIBXML_NOXMLDECL);
9523
9524 $dom->encoding = 'UTF-8';
9525
9526 $out = trim($dom->saveHTML());
9527
9528 // Restore [ and ] that were protected before loadHTML
9529 $out = preg_replace_callback(
9530 '/__BRACKETSTART([0-9a-zA-Z_]+)BRACKETEND__/',
9535 function ($m) {
9536 return '__[' . $m[1] . ']__';
9537 },
9538 $out
9539 );
9540
9541 // Remove the trick added to solve pb with text in utf8 and text without parent tag
9542 //$out = preg_replace('/^'.preg_quote('<?xml encoding="UTF-8">', '/').'/', '', $out);
9543 $out = preg_replace('/^' . preg_quote('<html><head><', '/') . '[^<>]+' . preg_quote('></head><body><div class="tricktoremove">', '/') . '/', '', $out);
9544 $out = preg_replace('/' . preg_quote('</div></body></html>', '/') . '$/', '', trim($out));
9545 //$out = preg_replace('/^<\?xml encoding="UTF-8"><div class="tricktoremove">/', '', $out);
9546 //$out = preg_replace('/<\/div>$/', '', $out);
9547
9548 if (!$outishtml) { // If $out was not HTML content we made before a dol_nl2br so we must do the opposite operation now
9549 $out = str_replace('<br>', '', $out);
9550 }
9551 } catch (Exception $e) {
9552 // If error, invalid HTML string with no way to clean it
9553 //print $e->getMessage();
9554 $out = 'InvalidHTMLStringCantBeCleaned ' . $e->getMessage();
9555 }
9556 }
9557
9558 // HTML sanitizer by Tidy
9559 // Tidy can't be used for restricthtmlallowunvalid and restricthtmlallowlinkscript
9560 // Tidy can't be used for non html text content as it is corrupting the new lines fields.
9561 if (!empty($out) && getDolGlobalString('MAIN_RESTRICTHTML_ONLY_VALID_HTML_TIDY') && !in_array($check, array('restricthtmlallowunvalid', 'restricthtmlallowlinkscript')) && $outishtml) {
9562 // TODO Try to implement a hack for restricthtmlallowlinkscript by renaming tag <link> and <script> ?
9563 try {
9564 //var_dump($out);
9565
9566 // Try cleaning using tidy
9567 if (extension_loaded('tidy') && class_exists("tidy")) {
9568 //print "aaa".$out."\n";
9569
9570 // See options at https://tidy.sourceforge.net/docs/quickref.html
9571 $config = array(
9572 'clean' => false,
9573 // 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;
9574 'quote-marks' => false,
9575 'doctype' => 'strict',
9576 'show-body-only' => true,
9577 "indent-attributes" => false,
9578 "vertical-space" => false,
9579 //'ident' => false, // Not always supported
9580 "wrap" => 0,
9581 'preserve-entities' => true
9582 // HTML5 tags
9583 //'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',
9584 //'new-blocklevel-tags' => 'footer header section menu menuitem'
9585 //'new-empty-tags' => 'command embed keygen source track wbr',
9586 //'new-inline-tags' => 'audio command datalist embed keygen mark menuitem meter output progress source time video wbr',
9587 );
9588
9589 // Tidy
9590 $tidy = new tidy();
9591 $out = $tidy->repairString($out, $config, 'utf8');
9592
9593 //print "xxx".$out;exit;
9594 }
9595
9596 //var_dump($out);
9597 } catch (Exception $e) {
9598 // If error, invalid HTML string with no way to clean it
9599 //print $e->getMessage();
9600 $out = 'InvalidHTMLStringCantBeCleaned ' . $e->getMessage();
9601 }
9602 }
9603
9604 // Clear ZERO WIDTH NO-BREAK SPACE, ZERO WIDTH SPACE, ZERO WIDTH JOINER
9605 // TODO $out = preg_replace('/[\x{2000}-\x{200D}\x{FEFF}]/u', ' ', $out);
9606 $out = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', ' ', $out);
9607
9608 // Clean some html entities that are useless so text is cleaner
9609 $out = preg_replace('/&(tab|newline);/i', ' ', $out);
9610
9611 // Ckeditor uses the numeric entity for apostrophe, so we force it to
9612 // the text entity (all other special chars are encoded using text entities) so we can then exclude all numeric entities.
9613 $out = preg_replace('/&#39;/i', '&apos;', $out);
9614
9615 // 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).
9616 // 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
9617 // using a non conventionnal way to be encoded, to not have them sanitized just after)
9618 if (function_exists('realCharForNumericEntities')) { // May not exist when main.inc.php not loaded, for example in a CLI context
9619 $out = preg_replace_callback(
9620 '/&#(x?[0-9][0-9a-f]+;?)/i',
9625 static function ($m) {
9626 return realCharForNumericEntities($m);
9627 },
9628 $out
9629 );
9630 }
9631
9632 // Now we remove all remaining HTML entities starting with a number. We don't want such entities.
9633 $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'.
9634
9635 // Keep only some html tags and remove also some 'javascript:' strings
9636 if ($check == 'restricthtmlallowlinkscript') {
9637 $out = dol_string_onlythesehtmltags($out, 0, 1, 0, 0, array(), 1, 1, 1, getDolGlobalInt("UNSECURED_restricthtmlallowlinkscript_ALLOW_PHP"));
9638 } elseif ($check == 'restricthtmlallowclass' || $check == 'restricthtmlallowunvalid') {
9639 $out = dol_string_onlythesehtmltags($out, 0, 0, 1);
9640 } elseif ($check == 'restricthtmlallowiframe') {
9641 $out = dol_string_onlythesehtmltags($out, 0, 0, 1, 1);
9642 } else {
9643 $out = dol_string_onlythesehtmltags($out, 0, 1, 1);
9644 }
9645
9646 // Keep only some html attributes and exclude non expected HTML attributes and clean content of some attributes (keep only alt=, title=...).
9647 if (getDolGlobalString('MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES')) {
9649 }
9650
9651 // Restore entity &apos; into &#39; (restricthtml is for html content so we can use html entity) because it is
9652 // compatible with HTML 4 used y CKEditor, and HTML 5 (when &apos; works only with HTML5).
9653 $out = preg_replace('/&apos;/i', "&#39;", $out);
9654
9655 // Now remove js
9656 // 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
9657 $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)>
9658 $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);
9659 $out = preg_replace('/on(dblclick|drop|durationchange|emptied|end|ended|error|focus(in|out)?|formdata|gotpointercapture|hashchange|input|invalid)[a-z]*\s*=/i', '', $out);
9660 $out = preg_replace('/on(lostpointercapture|offline|online|pagehide|pageshow)[a-z]*\s*=/i', '', $out);
9661 $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);
9662 $out = preg_replace('/on(timeupdate|toggle|unload|volumechange|waiting|wheel)[a-z]*\s*=/i', '', $out);
9663 // More not into the previous list
9664 $out = preg_replace('/on(repeat|begin|finish|beforeinput)[a-z]*\s*=/i', '', $out);
9665 } while ($oldstringtoclean != $out);
9666
9667 // Check the limit of external links that are automatically executed in a Rich text content. We count:
9668 // '<img' to avoid <img src="http...">, we can only accept "<img src="data:..."
9669 // 'url(' to avoid inline style like background: url(http...
9670 // '<link' to avoid <link href="http...">
9671 $reg = array();
9672 $tmpout = preg_replace('/<img src="data:/mi', '<__IMG_SRC_DATA__ src="data:', $out);
9673 preg_match_all('/(<img|url\‍(|<link)/i', $tmpout, $reg);
9674 $nblinks = count($reg[0]);
9675 if ($nblinks > getDolGlobalInt("MAIN_SECURITY_MAX_IMG_IN_HTML_CONTENT", 1000)) {
9676 $out = 'ErrorTooManyLinksIntoHTMLString';
9677 }
9678
9679 if (getDolGlobalInt('MAIN_DISALLOW_URL_INTO_DESCRIPTIONS') == 2 || $check == 'restricthtmlnolink') {
9680 if ($nblinks > 0) {
9681 $out = 'ErrorHTMLLinksNotAllowed';
9682 }
9683 } elseif (getDolGlobalInt('MAIN_DISALLOW_URL_INTO_DESCRIPTIONS') == 1) {
9684 // Refuse any links except it they are to the wrapper document.php or viewimage.php
9685 $nblinks = 0;
9686
9687 // Loop on each url in src= and url(
9688 $pattern = '/src=["\']?(http[^"\']+)|url\‍(["\']?(http[^\‍)]+)/';
9689
9691
9692 $matches = array();
9693 if (preg_match_all($pattern, $out, $matches)) {
9694 // URLs are into $matches[1] or $matches[2]
9695 $urls = array();
9696 foreach ($matches[1] as $tmpval) {
9697 if (!empty($tmpval)) {
9698 $urls[] = $tmpval;
9699 }
9700 }
9701 foreach ($matches[2] as $tmpval) {
9702 if (!empty($tmpval)) {
9703 $urls[] = $tmpval;
9704 }
9705 }
9706
9707 // Show URLs
9708 $firstexturl = '';
9709 $secondexturl = '';
9710 foreach ($urls as $url) {
9711 $urlok = 0;
9712 $parsedurl = parse_url($url);
9713 if (!empty($parsedurl)) {
9714 if (preg_match('/'.preg_quote($dolibarr_main_url_root, '/').'/', $url)
9715 //&& preg_match('/(document|viewimage)\.php$/', $parsedurl['path']) && preg_match('/modulepart=(media|mycompany)/', $parsedurl['query'])
9716 ) {
9717 $urlok = 1;
9718 }
9719 }
9720 if (!$urlok) {
9721 $nblinks++;
9722 if (empty($firstexturl)) {
9723 $firstexturl = $url;
9724 } elseif (empty($secondexturl)) {
9725 $secondexturl = $url;
9726 }
9727 //echo "Found url = ".$url . "\n";
9728 }
9729 }
9730 if ($nblinks > 0) {
9731 $out = 'ErrorHTMLExternalLinksNotAllowed (Example: '.$firstexturl.($secondexturl ? ' '.$secondexturl : '').')';
9732 }
9733 }
9734 }
9735
9736 return $out;
9737 }
9738}
9739
9760function dol_htmlentitiesbr($stringtoencode, $nl2brmode = 0, $pagecodefrom = 'UTF-8', $removelasteolbr = 1)
9761{
9762 if (is_null($stringtoencode)) {
9763 return '';
9764 }
9765
9766 $newstring = $stringtoencode;
9767 if (dol_textishtml($stringtoencode)) { // Check if text is already HTML or not
9768 $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.
9769 if ($removelasteolbr) {
9770 $newstring = preg_replace('/<br>$/i', '', $newstring); // Remove last <br> (remove only last one)
9771 }
9772 $newstring = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', ' ', $newstring);
9773 $newstring = strtr($newstring, array('&' => '__PROTECTand__', '<' => '__PROTECTlt__', '>' => '__PROTECTgt__', '"' => '__PROTECTdquot__'));
9774 $newstring = dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom); // Make entity encoding
9775 $newstring = strtr($newstring, array('__PROTECTand__' => '&', '__PROTECTlt__' => '<', '__PROTECTgt__' => '>', '__PROTECTdquot__' => '"'));
9776 } else {
9777 if ($removelasteolbr) {
9778 $newstring = preg_replace('/(\r\n|\r|\n)$/i', '', $newstring); // Remove last \n (may remove several)
9779 }
9780 $newstring = dol_nl2br(dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom), $nl2brmode);
9781 }
9782 // Other substitutions that htmlentities does not do
9783 //$newstring=str_replace(chr(128),'&euro;',$newstring); // 128 = 0x80. Not in html entity table. // Seems useles with TCPDF. Make bug with UTF8 languages
9784 return $newstring;
9785}
9786
9794function dol_htmlentitiesbr_decode($stringtodecode, $pagecodeto = 'UTF-8')
9795{
9796 $ret = dol_html_entity_decode($stringtodecode, ENT_COMPAT | ENT_HTML5, $pagecodeto);
9797 $ret = preg_replace('/' . "\r\n" . '<br(\s[\sa-zA-Z_="]*)?\/?>/i', "<br>", $ret);
9798 $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>' . "\r\n" . '/i', "\r\n", $ret);
9799 $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>' . "\n" . '/i', "\n", $ret);
9800 $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i', "\n", $ret);
9801 return $ret;
9802}
9803
9810function dol_htmlcleanlastbr($stringtodecode)
9811{
9812 $ret = preg_replace('/&nbsp;$/i', "", $stringtodecode); // Because wysiwyg editor may add a &nbsp; at end of last line
9813 $ret = preg_replace('/(<br>|<br(\s[\sa-zA-Z_="]*)?\/?>|' . "\n" . '|' . "\r" . ')+$/i', "", $ret);
9814 return $ret;
9815}
9816
9826function dol_html_entity_decode($a, $b, $c = 'UTF-8', $keepsomeentities = 0)
9827{
9828 $newstring = $a;
9829 if ($keepsomeentities) {
9830 $newstring = strtr($newstring, array('&amp;' => '__andamp__', '&lt;' => '__andlt__', '&gt;' => '__andgt__', '"' => '__dquot__'));
9831 }
9832 $newstring = html_entity_decode((string) $newstring, (int) $b, (string) $c);
9833 if ($keepsomeentities) {
9834 $newstring = strtr($newstring, array('__andamp__' => '&amp;', '__andlt__' => '&lt;', '__andgt__' => '&gt;', '__dquot__' => '"'));
9835 }
9836 return $newstring;
9837}
9838
9850function dol_htmlentities($string, $flags = ENT_QUOTES | ENT_SUBSTITUTE, $encoding = 'UTF-8', $double_encode = false)
9851{
9852 return htmlentities($string, $flags, $encoding, $double_encode);
9853}
9854
9866function dol_string_is_good_iso($s, $clean = 0)
9867{
9868 $len = dol_strlen($s);
9869 $out = '';
9870 $ok = 1;
9871 for ($scursor = 0; $scursor < $len; $scursor++) {
9872 $ordchar = ord($s[$scursor]);
9873 //print $scursor.'-'.$ordchar.'<br>';
9874 if ($ordchar < 32 && $ordchar != 13 && $ordchar != 10) {
9875 $ok = 0;
9876 break;
9877 } elseif ($ordchar > 126 && $ordchar < 160) {
9878 $ok = 0;
9879 break;
9880 } elseif ($clean) {
9881 $out .= $s[$scursor];
9882 }
9883 }
9884 if ($clean) {
9885 return $out;
9886 }
9887 return $ok;
9888}
9889
9898function dol_nboflines($s, $maxchar = 0)
9899{
9900 if ($s == '') {
9901 return 0;
9902 }
9903 $arraystring = explode("\n", $s);
9904 $nb = count($arraystring);
9905
9906 return $nb;
9907}
9908
9909
9919function dol_nboflines_bis($text, $maxlinesize = 0, $charset = 'UTF-8')
9920{
9921 $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
9922 if (dol_textishtml($text)) {
9923 $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
9924 }
9925
9926 $text = strtr($text, $repTable);
9927 if ($charset == 'UTF-8') {
9928 $pattern = '/(<br[^>]*>)/Uu';
9929 } else {
9930 // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
9931 $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
9932 }
9933 $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
9934
9935 $nblines = (int) floor((count($a) + 1) / 2);
9936 // count possible auto line breaks
9937 if ($maxlinesize) {
9938 foreach ($a as $line) {
9939 if (dol_strlen($line) > $maxlinesize) {
9940 //$line_dec = html_entity_decode(strip_tags($line));
9941 $line_dec = html_entity_decode($line);
9942 if (dol_strlen($line_dec) > $maxlinesize) {
9943 $line_dec = wordwrap($line_dec, $maxlinesize, '\n', true);
9944 $nblines += substr_count($line_dec, '\n');
9945 }
9946 }
9947 }
9948 }
9949
9950 unset($a);
9951 return $nblines;
9952}
9953
9962function dol_textishtml($msg, $option = 0)
9963{
9964 if (is_null($msg)) {
9965 return false;
9966 }
9967
9968 if ($option == 1) {
9969 if (preg_match('/<(html|link|script)/i', $msg)) {
9970 return true;
9971 } elseif (preg_match('/<body/i', $msg)) {
9972 return true;
9973 } elseif (preg_match('/<\/textarea/i', $msg)) {
9974 return true;
9975 } elseif (preg_match('/<(b|em|i|u)(\s+[^>]+)?>/i', $msg)) {
9976 return true;
9977 } elseif (preg_match('/<br/i', $msg)) {
9978 return true;
9979 }
9980 return false;
9981 } else {
9982 // Remove all urls because 'http://aa?param1=abc&amp;param2=def' must not be used inside detection
9983 $msg = preg_replace('/https?:\/\/[^"\'\s]+/i', '', $msg);
9984 if (preg_match('/<(html|link|script|body)/i', $msg)) {
9985 return true;
9986 } elseif (preg_match('/<\/textarea/i', $msg)) {
9987 return true;
9988 } elseif (preg_match('/<(b|em|i|u)(\s+[^>]+)?>/i', $msg)) {
9989 return true;
9990 } elseif (preg_match('/<(br|hr)\/>/i', $msg)) {
9991 return true;
9992 } elseif (preg_match('/<(br|hr|div|font|li|p|span|strong|table)>/i', $msg)) {
9993 return true;
9994 } elseif (preg_match('/<(br|hr|div|font|li|p|span|strong|table)\s+[^<>\/]*\/?>/i', $msg)) {
9995 return true;
9996 } elseif (preg_match('/<img\s+[^<>]*src[^<>]*>/i', $msg)) {
9997 return true; // must accept <img src="http://example.com/aaa.png" />
9998 } elseif (preg_match('/<a\s+[^<>]*href[^<>]*>/i', $msg)) {
9999 return true; // must accept <a href="http://example.com/aaa.png" />
10000 } elseif (preg_match('/<h[0-9]>/i', $msg)) {
10001 return true;
10002 } elseif (preg_match('/&[A-Z0-9]{1,6};/i', $msg)) {
10003 // TODO If content is 'A link https://aaa?param=abc&amp;param2=def', it return true but must be false
10004 return true; // Html entities names (http://www.w3schools.com/tags/ref_entities.asp)
10005 } elseif (preg_match('/&#[0-9]{2,3};/i', $msg)) {
10006 return true; // Html entities numbers (http://www.w3schools.com/tags/ref_entities.asp)
10007 } elseif (preg_match('/&#x[a-f0-9][a-f0-9];/i', $msg)) {
10008 return true; // Html entities numbers in hexa
10009 }
10010
10011 return false;
10012 }
10013}
10014
10029function dol_concatdesc($text1, $text2, $forxml = false, $invert = false)
10030{
10031 if (!empty($invert)) {
10032 $tmp = $text1;
10033 $text1 = $text2;
10034 $text2 = $tmp;
10035 }
10036
10037 $ret = '';
10038 $ret .= (!dol_textishtml($text1) && dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text1, 0, 1, '', 1), 0, $forxml) : $text1;
10039 $ret .= (!empty($text1) && !empty($text2)) ? ((dol_textishtml($text1) || dol_textishtml($text2)) ? ($forxml ? "<br >\n" : "<br>\n") : "\n") : "";
10040 $ret .= (dol_textishtml($text1) && !dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text2, 0, 1, '', 1), 0, $forxml) : $text2;
10041 return $ret;
10042}
10043
10052function dol_concat($text1, $text2)
10053{
10054 return $text1.$text2;
10055}
10056
10070function getCommonSubstitutionArray($outputlangs, $onlykey = 0, $exclude = null, $object = null, $include = null)
10071{
10072 global $db, $conf, $mysoc, $user, $extrafields;
10073
10074 $substitutionarray = array();
10075
10076 if ((empty($exclude) || !in_array('user', $exclude)) && (empty($include) || in_array('user', $include)) && $user instanceof User) {
10077 // Add SIGNATURE into substitutionarray first, so, when we will make the substitution,
10078 // this will include signature content first and then replace var found into content of signature
10079 //var_dump($onlykey);
10080 $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()
10081 $usersignature = $user->signature;
10082 $substitutionarray = array_merge($substitutionarray, array(
10083 '__SENDEREMAIL_SIGNATURE__' => (string) ((!getDolGlobalString('MAIN_MAIL_DO_NOT_USE_SIGN')) ? ($onlykey == 2 ? dol_trunc('SignatureFromTheSelectedSenderProfile', 30) : $emailsendersignature) : ''),
10084 '__USER_SIGNATURE__' => (string) (($usersignature && !getDolGlobalString('MAIN_MAIL_DO_NOT_USE_SIGN')) ? ($onlykey == 2 ? dol_trunc(dol_string_nohtmltag($usersignature), 30) : $usersignature) : '')
10085 ));
10086
10087 if (is_object($user) && ($user instanceof User)) {
10088 $substitutionarray = array_merge($substitutionarray, array(
10089 '__USER_ID__' => (string) $user->id,
10090 '__USER_LOGIN__' => (string) $user->login,
10091 '__USER_EMAIL__' => (string) $user->email,
10092 '__USER_PHONE__' => (string) dol_print_phone($user->office_phone, '', 0, 0, '', " ", '', '', -1),
10093 '__USER_PHONEPRO__' => (string) dol_print_phone($user->user_mobile, '', 0, 0, '', " ", '', '', -1),
10094 '__USER_PHONEMOBILE__' => (string) dol_print_phone($user->personal_mobile, '', 0, 0, '', " ", '', '', -1),
10095 '__USER_FAX__' => (string) $user->office_fax,
10096 '__USER_LASTNAME__' => (string) $user->lastname,
10097 '__USER_FIRSTNAME__' => (string) $user->firstname,
10098 '__USER_FULLNAME__' => (string) $user->getFullName($outputlangs),
10099 '__USER_SUPERVISOR_ID__' => (string) ($user->fk_user ? $user->fk_user : '0'),
10100 '__USER_JOB__' => (string) $user->job,
10101 '__USER_REMOTE_IP__' => (string) getUserRemoteIP(),
10102 '__USER_VCARD_URL__' => (string) $user->getOnlineVirtualCardUrl('', 'external')
10103 ));
10104 }
10105 }
10106 if ((empty($exclude) || !in_array('mycompany', $exclude)) && is_object($mysoc) && (empty($include) || in_array('mycompany', $include))) {
10107 $substitutionarray = array_merge($substitutionarray, array(
10108 '__MYCOMPANY_NAME__' => $mysoc->name,
10109 '__MYCOMPANY_EMAIL__' => $mysoc->email,
10110 '__MYCOMPANY_URL__' => $mysoc->url,
10111 '__MYCOMPANY_PHONE__' => dol_print_phone($mysoc->phone, '', 0, 0, '', " ", '', '', -1),
10112 '__MYCOMPANY_PHONEMOBILE__' => dol_print_phone($mysoc->phone_mobile, '', 0, 0, '', " ", '', '', -1),
10113 '__MYCOMPANY_FAX__' => dol_print_phone($mysoc->fax, '', 0, 0, '', " ", '', '', -1),
10114 '__MYCOMPANY_PROFID1__' => $mysoc->idprof1,
10115 '__MYCOMPANY_PROFID2__' => $mysoc->idprof2,
10116 '__MYCOMPANY_PROFID3__' => $mysoc->idprof3,
10117 '__MYCOMPANY_PROFID4__' => $mysoc->idprof4,
10118 '__MYCOMPANY_PROFID5__' => $mysoc->idprof5,
10119 '__MYCOMPANY_PROFID6__' => $mysoc->idprof6,
10120 '__MYCOMPANY_PROFID7__' => $mysoc->idprof7,
10121 '__MYCOMPANY_PROFID8__' => $mysoc->idprof8,
10122 '__MYCOMPANY_PROFID9__' => $mysoc->idprof9,
10123 '__MYCOMPANY_PROFID10__' => $mysoc->idprof10,
10124 '__MYCOMPANY_CAPITAL__' => $mysoc->capital,
10125 '__MYCOMPANY_FULLADDRESS__' => (method_exists($mysoc, 'getFullAddress') ? $mysoc->getFullAddress(1, ', ') : ''), // $mysoc may be stdClass
10126 '__MYCOMPANY_ADDRESS__' => $mysoc->address,
10127 '__MYCOMPANY_VATNUMBER__' => $mysoc->tva_intra,
10128 '__MYCOMPANY_ZIP__' => $mysoc->zip,
10129 '__MYCOMPANY_TOWN__' => $mysoc->town,
10130 '__MYCOMPANY_STATE__' => $mysoc->state,
10131 '__MYCOMPANY_COUNTRY__' => $mysoc->country,
10132 '__MYCOMPANY_COUNTRY_ID__' => $mysoc->country_id,
10133 '__MYCOMPANY_COUNTRY_CODE__' => $mysoc->country_code,
10134 '__MYCOMPANY_CURRENCY_CODE__' => $conf->currency
10135 ));
10136 }
10137
10138 if (($onlykey || is_object($object)) && (empty($exclude) || !in_array('object', $exclude)) && (empty($include) || in_array('object', $include))) {
10139 if ($onlykey) {
10140 $substitutionarray['__ID__'] = '__ID__';
10141 $substitutionarray['__REF__'] = '__REF__';
10142 $substitutionarray['__NEWREF__'] = '__NEWREF__';
10143 $substitutionarray['__LABEL__'] = '__LABEL__';
10144 $substitutionarray['__REF_CLIENT__'] = '__REF_CLIENT__';
10145 $substitutionarray['__REF_SUPPLIER__'] = '__REF_SUPPLIER__';
10146 $substitutionarray['__NOTE_PUBLIC__'] = '__NOTE_PUBLIC__';
10147 $substitutionarray['__NOTE_PRIVATE__'] = '__NOTE_PRIVATE__';
10148 $substitutionarray['__EXTRAFIELD_XXX__'] = '__EXTRAFIELD_XXX__';
10149
10150 if (isModEnabled("societe")) { // Most objects are concerned
10151 $substitutionarray['__THIRDPARTY_ID__'] = '__THIRDPARTY_ID__';
10152 $substitutionarray['__THIRDPARTY_NAME__'] = '__THIRDPARTY_NAME__';
10153 $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = '__THIRDPARTY_NAME_ALIAS__';
10154 $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = '__THIRDPARTY_CODE_CLIENT__';
10155 $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = '__THIRDPARTY_CODE_FOURNISSEUR__';
10156 $substitutionarray['__THIRDPARTY_EMAIL__'] = '__THIRDPARTY_EMAIL__';
10157 //$substitutionarray['__THIRDPARTY_EMAIL_URLENCODED__'] = '__THIRDPARTY_EMAIL_URLENCODED__'; // We hide this one
10158 $substitutionarray['__THIRDPARTY_URL__'] = '__THIRDPARTY_URL__';
10159 //$substitutionarray['__THIRDPARTY_URL_URLENCODED__'] = '__THIRDPARTY_URL_URLENCODED__'; // We hide this one
10160 $substitutionarray['__THIRDPARTY_PHONE__'] = '__THIRDPARTY_PHONE__';
10161 $substitutionarray['__THIRDPARTY_FAX__'] = '__THIRDPARTY_FAX__';
10162 $substitutionarray['__THIRDPARTY_ADDRESS__'] = '__THIRDPARTY_ADDRESS__';
10163 $substitutionarray['__THIRDPARTY_ZIP__'] = '__THIRDPARTY_ZIP__';
10164 $substitutionarray['__THIRDPARTY_TOWN__'] = '__THIRDPARTY_TOWN__';
10165 $substitutionarray['__THIRDPARTY_STATE__'] = '__THIRDPARTY_STATE__';
10166 $substitutionarray['__THIRDPARTY_IDPROF1__'] = '__THIRDPARTY_IDPROF1__';
10167 $substitutionarray['__THIRDPARTY_IDPROF2__'] = '__THIRDPARTY_IDPROF2__';
10168 $substitutionarray['__THIRDPARTY_IDPROF3__'] = '__THIRDPARTY_IDPROF3__';
10169 $substitutionarray['__THIRDPARTY_IDPROF4__'] = '__THIRDPARTY_IDPROF4__';
10170 $substitutionarray['__THIRDPARTY_IDPROF5__'] = '__THIRDPARTY_IDPROF5__';
10171 $substitutionarray['__THIRDPARTY_IDPROF6__'] = '__THIRDPARTY_IDPROF6__';
10172 $substitutionarray['__THIRDPARTY_IDPROF7__'] = '__THIRDPARTY_IDPROF7__';
10173 $substitutionarray['__THIRDPARTY_IDPROF8__'] = '__THIRDPARTY_IDPROF8__';
10174 $substitutionarray['__THIRDPARTY_IDPROF9__'] = '__THIRDPARTY_IDPROF9__';
10175 $substitutionarray['__THIRDPARTY_IDPROF10__'] = '__THIRDPARTY_IDPROF10__';
10176 $substitutionarray['__THIRDPARTY_TVAINTRA__'] = '__THIRDPARTY_TVAINTRA__';
10177 $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = '__THIRDPARTY_NOTE_PUBLIC__';
10178 $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = '__THIRDPARTY_NOTE_PRIVATE__';
10179 }
10180 if (isModEnabled('member') && (!is_object($object) || $object->element == 'adherent') && (empty($exclude) || !in_array('member', $exclude)) && (empty($include) || in_array('member', $include))) {
10181 $substitutionarray['__MEMBER_ID__'] = '__MEMBER_ID__';
10182 $substitutionarray['__MEMBER_TITLE__'] = '__MEMBER_TITLE__';
10183 $substitutionarray['__MEMBER_FIRSTNAME__'] = '__MEMBER_FIRSTNAME__';
10184 $substitutionarray['__MEMBER_LASTNAME__'] = '__MEMBER_LASTNAME__';
10185 $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = 'Login and pass of the external user account';
10186 /*$substitutionarray['__MEMBER_NOTE_PUBLIC__'] = '__MEMBER_NOTE_PUBLIC__';
10187 $substitutionarray['__MEMBER_NOTE_PRIVATE__'] = '__MEMBER_NOTE_PRIVATE__';*/
10188 }
10189 // add substitution variables for ticket
10190 if (isModEnabled('ticket') && (!is_object($object) || $object->element == 'ticket') && (empty($exclude) || !in_array('ticket', $exclude)) && (empty($include) || in_array('ticket', $include))) {
10191 $substitutionarray['__TICKET_TRACKID__'] = '__TICKET_TRACKID__';
10192 $substitutionarray['__TICKET_SUBJECT__'] = '__TICKET_SUBJECT__';
10193 $substitutionarray['__TICKET_TYPE__'] = '__TICKET_TYPE__';
10194 $substitutionarray['__TICKET_SEVERITY__'] = '__TICKET_SEVERITY__';
10195 $substitutionarray['__TICKET_CATEGORY__'] = '__TICKET_CATEGORY__';
10196 $substitutionarray['__TICKET_ANALYTIC_CODE__'] = '__TICKET_ANALYTIC_CODE__';
10197 $substitutionarray['__TICKET_MESSAGE__'] = '__TICKET_MESSAGE__';
10198 $substitutionarray['__TICKET_PROGRESSION__'] = '__TICKET_PROGRESSION__';
10199 $substitutionarray['__TICKET_USER_ASSIGN__'] = '__TICKET_USER_ASSIGN__';
10200 }
10201
10202 if (isModEnabled('recruitment') && (!is_object($object) || $object->element == 'recruitmentcandidature') && (empty($exclude) || !in_array('recruitment', $exclude)) && (empty($include) || in_array('recruitment', $include))) {
10203 $substitutionarray['__CANDIDATE_FULLNAME__'] = '__CANDIDATE_FULLNAME__';
10204 $substitutionarray['__CANDIDATE_FIRSTNAME__'] = '__CANDIDATE_FIRSTNAME__';
10205 $substitutionarray['__CANDIDATE_LASTNAME__'] = '__CANDIDATE_LASTNAME__';
10206 }
10207 if (isModEnabled('project') && (empty($exclude) || !in_array('project', $exclude)) && (empty($include) || in_array('project', $include))) { // Most objects
10208 $substitutionarray['__PROJECT_ID__'] = '__PROJECT_ID__';
10209 $substitutionarray['__PROJECT_REF__'] = '__PROJECT_REF__';
10210 $substitutionarray['__PROJECT_NAME__'] = '__PROJECT_NAME__';
10211 /*$substitutionarray['__PROJECT_NOTE_PUBLIC__'] = '__PROJECT_NOTE_PUBLIC__';
10212 $substitutionarray['__PROJECT_NOTE_PRIVATE__'] = '__PROJECT_NOTE_PRIVATE__';*/
10213 }
10214 if (isModEnabled('contract') && (!is_object($object) || $object->element == 'contract') && (empty($exclude) || !in_array('contract', $exclude)) && (empty($include) || in_array('contract', $include))) {
10215 $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = 'Highest date planned for a service start';
10216 $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = 'Highest date and hour planned for service start';
10217 $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = 'Lowest data for planned expiration of service';
10218 $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = 'Lowest date and hour for planned expiration of service';
10219 }
10220 if (isModEnabled("propal") && (!is_object($object) || $object->element == 'propal') && (empty($exclude) || !in_array('propal', $exclude)) && (empty($include) || in_array('propal', $include))) {
10221 $substitutionarray['__ONLINE_SIGN_URL__'] = 'ToOfferALinkForOnlineSignature';
10222 }
10223 if (isModEnabled("intervention") && (!is_object($object) || $object->element == 'fichinter') && (empty($exclude) || !in_array('intervention', $exclude)) && (empty($include) || in_array('intervention', $include))) {
10224 $substitutionarray['__ONLINE_SIGN_FICHINTER_URL__'] = 'ToOfferALinkForOnlineSignature';
10225 }
10226 $substitutionarray['__ONLINE_PAYMENT_URL__'] = 'UrlToPayOnlineIfApplicable';
10227 $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = 'TextAndUrlToPayOnlineIfApplicable';
10228 $substitutionarray['__SECUREKEYPAYMENT__'] = 'Security key (if key is not unique per record)';
10229 $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = 'Security key for payment on a member subscription (one key per member)';
10230 $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = 'Security key for payment on an order';
10231 $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = 'Security key for payment on an invoice';
10232 $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = 'Security key for payment on a service of a contract';
10233
10234 $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = 'Direct download url of a proposal';
10235 $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = 'Direct download url of an order';
10236 $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = 'Direct download url of an invoice';
10237 $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = 'Direct download url of a contract';
10238 $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = 'Direct download url of a supplier proposal';
10239
10240 if (isModEnabled("shipping") && (!is_object($object) || $object->element == 'shipping')) {
10241 $substitutionarray['__SHIPPINGTRACKNUM__'] = 'Shipping tracking number';
10242 $substitutionarray['__SHIPPINGTRACKNUMURL__'] = 'Shipping tracking url';
10243 $substitutionarray['__SHIPPINGMETHOD__'] = 'Shipping method';
10244 }
10245 if (isModEnabled("reception") && (!is_object($object) || $object->element == 'reception')) {
10246 $substitutionarray['__RECEPTIONTRACKNUM__'] = 'Shipping tracking number of shipment';
10247 $substitutionarray['__RECEPTIONTRACKNUMURL__'] = 'Shipping tracking url';
10248 }
10249 } else {
10250 '@phan-var-force Adherent|Delivery $object';
10252 $substitutionarray['__ID__'] = $object->id;
10253 $substitutionarray['__REF__'] = $object->ref;
10254 $substitutionarray['__NEWREF__'] = $object->newref;
10255 $substitutionarray['__LABEL__'] = (isset($object->label) ? $object->label : (isset($object->title) ? $object->title : null));
10256 $substitutionarray['__REF_CLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
10257 $substitutionarray['__REF_SUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
10258 $substitutionarray['__NOTE_PUBLIC__'] = (isset($object->note_public) ? $object->note_public : null);
10259 $substitutionarray['__NOTE_PRIVATE__'] = (isset($object->note_private) ? $object->note_private : null);
10260
10261 $substitutionarray['__DATE_CREATION__'] = (isset($object->date_creation) ? dol_print_date($object->date_creation, 'day', false, $outputlangs) : '');
10262 $substitutionarray['__DATE_MODIFICATION__'] = (isset($object->date_modification) ? dol_print_date($object->date_modification, 'day', false, $outputlangs) : '');
10263 $substitutionarray['__DATE_VALIDATION__'] = (isset($object->date_validation) ? dol_print_date($object->date_validation, 'day', false, $outputlangs) : '');
10264
10265 // handle date_delivery: in customer order/supplier order, the property name is delivery_date, in shipment/reception it is date_delivery
10266 $date_delivery = null;
10267 if (property_exists($object, 'date_delivery')) {
10268 $date_delivery = $object->date_delivery;
10269 } elseif (property_exists($object, 'delivery_date')) {
10270 $date_delivery = $object->delivery_date;
10271 }
10272 $substitutionarray['__DATE_DELIVERY__'] = (isset($date_delivery) ? dol_print_date($date_delivery, 'day', false, $outputlangs) : '');
10273 $substitutionarray['__DATE_DELIVERY_DAY__'] = (isset($date_delivery) ? dol_print_date($date_delivery, "%d") : '');
10274 $substitutionarray['__DATE_DELIVERY_DAY_TEXT__'] = (isset($date_delivery) ? dol_print_date($date_delivery, "%A") : '');
10275 $substitutionarray['__DATE_DELIVERY_MON__'] = (isset($date_delivery) ? dol_print_date($date_delivery, "%m") : '');
10276 $substitutionarray['__DATE_DELIVERY_MON_TEXT__'] = (isset($date_delivery) ? dol_print_date($date_delivery, "%b") : '');
10277 $substitutionarray['__DATE_DELIVERY_YEAR__'] = (isset($date_delivery) ? dol_print_date($date_delivery, "%Y") : '');
10278 $substitutionarray['__DATE_DELIVERY_HH__'] = (isset($date_delivery) ? dol_print_date($date_delivery, "%H") : '');
10279 $substitutionarray['__DATE_DELIVERY_MM__'] = (isset($date_delivery) ? dol_print_date($date_delivery, "%M") : '');
10280 $substitutionarray['__DATE_DELIVERY_SS__'] = (isset($date_delivery) ? dol_print_date($date_delivery, "%S") : '');
10281
10282 // For backward compatibility (deprecated)
10283 $substitutionarray['__REFCLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
10284 $substitutionarray['__REFSUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
10285
10286 $substitutionarray['__SUPPLIER_ORDER_DATE_DELIVERY__'] = (isset($date_delivery) ? dol_print_date($date_delivery, 'day', false, $outputlangs) : '');
10287 $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 : '')) : '');
10288 $substitutionarray['__EXPIRATION_DATE__'] = (isset($object->fin_validite) ? dol_print_date($object->fin_validite, 'daytext') : '');
10289
10290 if (is_object($object) && ($object->element == 'adherent' || $object->element == 'member') && $object->id > 0) {
10291 '@phan-var-force Adherent $object';
10293 $birthday = (empty($object->birth) ? '' : dol_print_date($object->birth, 'day'));
10294
10295 $substitutionarray['__MEMBER_ID__'] = (isset($object->id) ? $object->id : '');
10296 if (method_exists($object, 'getCivilityLabel')) {
10297 $substitutionarray['__MEMBER_TITLE__'] = $object->getCivilityLabel();
10298 }
10299 $substitutionarray['__MEMBER_FIRSTNAME__'] = (isset($object->firstname) ? $object->firstname : '');
10300 $substitutionarray['__MEMBER_LASTNAME__'] = (isset($object->lastname) ? $object->lastname : '');
10301 $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = '';
10302 if (method_exists($object, 'getFullName')) {
10303 $substitutionarray['__MEMBER_FULLNAME__'] = $object->getFullName($outputlangs);
10304 }
10305 $substitutionarray['__MEMBER_COMPANY__'] = (isset($object->societe) ? $object->societe : '');
10306 $substitutionarray['__MEMBER_ADDRESS__'] = (isset($object->address) ? $object->address : '');
10307 $substitutionarray['__MEMBER_ZIP__'] = (isset($object->zip) ? $object->zip : '');
10308 $substitutionarray['__MEMBER_TOWN__'] = (isset($object->town) ? $object->town : '');
10309 $substitutionarray['__MEMBER_STATE__'] = (isset($object->state) ? $object->state : '');
10310 $substitutionarray['__MEMBER_COUNTRY__'] = (isset($object->country) ? $object->country : '');
10311 $substitutionarray['__MEMBER_EMAIL__'] = (isset($object->email) ? $object->email : '');
10312 $substitutionarray['__MEMBER_BIRTH__'] = (isset($birthday) ? $birthday : '');
10313 $substitutionarray['__MEMBER_PHOTO__'] = (isset($object->photo) ? $object->photo : '');
10314 $substitutionarray['__MEMBER_LOGIN__'] = (isset($object->login) ? $object->login : '');
10315 $substitutionarray['__MEMBER_PASSWORD__'] = (isset($object->pass) ? $object->pass : '');
10316 $substitutionarray['__MEMBER_PHONE__'] = (isset($object->phone) ? dol_print_phone($object->phone) : '');
10317 $substitutionarray['__MEMBER_PHONEPRO__'] = (isset($object->phone_perso) ? dol_print_phone($object->phone_perso) : '');
10318 $substitutionarray['__MEMBER_PHONEMOBILE__'] = (isset($object->phone_mobile) ? dol_print_phone($object->phone_mobile) : '');
10319 $substitutionarray['__MEMBER_TYPE__'] = (isset($object->type) ? $object->type : '');
10320 $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE__'] = dol_print_date($object->first_subscription_date, 'day');
10321
10322 $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_RFC__'] = dol_print_date($object->first_subscription_date, 'dayrfc');
10323 $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_START__'] = (isset($object->first_subscription_date_start) ? dol_print_date($object->first_subscription_date_start, 'day') : '');
10324 $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_START_RFC__'] = (isset($object->first_subscription_date_start) ? dol_print_date($object->first_subscription_date_start, 'dayrfc') : '');
10325 $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_END__'] = (isset($object->first_subscription_date_end) ? dol_print_date($object->first_subscription_date_end, 'day') : '');
10326 $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_END_RFC__'] = (isset($object->first_subscription_date_end) ? dol_print_date($object->first_subscription_date_end, 'dayrfc') : '');
10327 $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE__'] = dol_print_date($object->last_subscription_date, 'day');
10328 $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_RFC__'] = dol_print_date($object->last_subscription_date, 'dayrfc');
10329 $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->last_subscription_date_start, 'day');
10330 $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_START_RFC__'] = dol_print_date($object->last_subscription_date_start, 'dayrfc');
10331 $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->last_subscription_date_end, 'day');
10332 $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_END_RFC__'] = dol_print_date($object->last_subscription_date_end, 'dayrfc');
10333 }
10334
10335 if (is_object($object) && $object->element == 'societe') {
10337 '@phan-var-force Societe $object';
10338 $substitutionarray['__THIRDPARTY_ID__'] = $object->id ?? '';
10339 $substitutionarray['__THIRDPARTY_NAME__'] = $object->name ?? '';
10340 $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = $object->name_alias ?? '';
10341 $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = $object->code_client ?? '';
10342 $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = $object->code_fournisseur ?? '';
10343 $substitutionarray['__THIRDPARTY_EMAIL__'] = $object->email ?? '';
10344 $substitutionarray['__THIRDPARTY_EMAIL_URLENCODED__'] = urlencode($object->email ?? '');
10345 $substitutionarray['__THIRDPARTY_URL__'] = $object->url ?? '';
10346 $substitutionarray['__THIRDPARTY_URL_URLENCODED__'] = urlencode($object->url ?? '');
10347 $substitutionarray['__THIRDPARTY_PHONE__'] = dol_print_phone($object->phone ?? '');
10348 $substitutionarray['__THIRDPARTY_FAX__'] = dol_print_phone($object->fax ?? '');
10349 $substitutionarray['__THIRDPARTY_ADDRESS__'] = $object->address ?? '';
10350 $substitutionarray['__THIRDPARTY_ZIP__'] = $object->zip ?? '';
10351 $substitutionarray['__THIRDPARTY_TOWN__'] = $object->town ?? '';
10352 $substitutionarray['__THIRDPARTY_STATE__'] = $object->state ?? '';
10353 $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = ($object->country_id > 0 ? $object->country_id : '');
10354 $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = $object->country_code ?? '';
10355 $substitutionarray['__THIRDPARTY_IDPROF1__'] = $object->idprof1 ?? '';
10356 $substitutionarray['__THIRDPARTY_IDPROF2__'] = $object->idprof2 ?? '';
10357 $substitutionarray['__THIRDPARTY_IDPROF3__'] = $object->idprof3 ?? '';
10358 $substitutionarray['__THIRDPARTY_IDPROF4__'] = $object->idprof4 ?? '';
10359 $substitutionarray['__THIRDPARTY_IDPROF5__'] = $object->idprof5 ?? '';
10360 $substitutionarray['__THIRDPARTY_IDPROF6__'] = $object->idprof6 ?? '';
10361 $substitutionarray['__THIRDPARTY_TVAINTRA__'] = $object->tva_intra ?? '';
10362 $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = dol_htmlentitiesbr($object->note_public ?? '');
10363 $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = dol_htmlentitiesbr($object->note_private ?? '');
10364 } elseif (is_object($object) && is_object($object->thirdparty)) {
10365 $substitutionarray['__THIRDPARTY_ID__'] = $object->thirdparty->id ?? '';
10366 $substitutionarray['__THIRDPARTY_NAME__'] = $object->thirdparty->name ?? '';
10367 $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = $object->thirdparty->name_alias ?? '';
10368 $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = $object->thirdparty->code_client ?? '';
10369 $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = $object->thirdparty->code_fournisseur ?? '';
10370 $substitutionarray['__THIRDPARTY_EMAIL__'] = $object->thirdparty->email ?? '';
10371 $substitutionarray['__THIRDPARTY_EMAIL_URLENCODED__'] = urlencode($object->thirdparty->email ?? '');
10372 $substitutionarray['__THIRDPARTY_PHONE__'] = dol_print_phone($object->thirdparty->phone ?? '');
10373 $substitutionarray['__THIRDPARTY_FAX__'] = dol_print_phone($object->thirdparty->fax ?? '');
10374 $substitutionarray['__THIRDPARTY_ADDRESS__'] = $object->thirdparty->address ?? '';
10375 $substitutionarray['__THIRDPARTY_ZIP__'] = $object->thirdparty->zip ?? '';
10376 $substitutionarray['__THIRDPARTY_TOWN__'] = $object->thirdparty->town ?? '';
10377 $substitutionarray['__THIRDPARTY_STATE__'] = $object->thirdparty->state ?? '';
10378 $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = ($object->thirdparty->country_id > 0 ? $object->thirdparty->country_id : '');
10379 $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = $object->thirdparty->country_code ?? '';
10380 $substitutionarray['__THIRDPARTY_IDPROF1__'] = $object->thirdparty->idprof1 ?? '';
10381 $substitutionarray['__THIRDPARTY_IDPROF2__'] = $object->thirdparty->idprof2 ?? '';
10382 $substitutionarray['__THIRDPARTY_IDPROF3__'] = $object->thirdparty->idprof3 ?? '';
10383 $substitutionarray['__THIRDPARTY_IDPROF4__'] = $object->thirdparty->idprof4 ?? '';
10384 $substitutionarray['__THIRDPARTY_IDPROF5__'] = $object->thirdparty->idprof5 ?? '';
10385 $substitutionarray['__THIRDPARTY_IDPROF6__'] = $object->thirdparty->idprof6 ?? '';
10386 $substitutionarray['__THIRDPARTY_TVAINTRA__'] = $object->thirdparty->tva_intra ?? '';
10387 $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = dol_htmlentitiesbr($object->thirdparty->note_public ?? '');
10388 $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = dol_htmlentitiesbr($object->thirdparty->note_private ?? '');
10389 }
10390
10391 if (is_object($object) && $object->element == 'recruitmentcandidature') {
10392 '@phan-var-force RecruitmentCandidature $object';
10394 $substitutionarray['__CANDIDATE_FULLNAME__'] = $object->getFullName($outputlangs);
10395 $substitutionarray['__CANDIDATE_FIRSTNAME__'] = isset($object->firstname) ? $object->firstname : '';
10396 $substitutionarray['__CANDIDATE_LASTNAME__'] = isset($object->lastname) ? $object->lastname : '';
10397 }
10398 if (is_object($object) && $object->element == 'conferenceorboothattendee') {
10399 '@phan-var-force ConferenceOrBoothAttendee $object';
10401 $substitutionarray['__ATTENDEE_FULLNAME__'] = $object->getFullName($outputlangs);
10402 $substitutionarray['__ATTENDEE_FIRSTNAME__'] = isset($object->firstname) ? $object->firstname : '';
10403 $substitutionarray['__ATTENDEE_LASTNAME__'] = isset($object->lastname) ? $object->lastname : '';
10404 }
10405
10406 if (is_object($object) && $object->element == 'project') {
10407 '@phan-var-force Project $object';
10409 $substitutionarray['__PROJECT_ID__'] = $object->id;
10410 $substitutionarray['__PROJECT_REF__'] = $object->ref;
10411 $substitutionarray['__PROJECT_NAME__'] = $object->title;
10412 } elseif (is_object($object)) {
10413 $project = null;
10414 if (!empty($object->project)) {
10415 $project = $object->project;
10416 }
10417 if (!is_null($project) && is_object($project)) {
10418 $substitutionarray['__PROJECT_ID__'] = $project->id;
10419 $substitutionarray['__PROJECT_REF__'] = $project->ref;
10420 $substitutionarray['__PROJECT_NAME__'] = $project->title;
10421 } else {
10422 // can substitute variables for project : uses lazy load in "make_substitutions" method
10423 $project_id = 0;
10424 if (!empty($object->fk_project) && $object->fk_project > 0) {
10425 $project_id = $object->fk_project;
10426 } elseif (!empty($object->fk_projet) && $object->fk_projet > 0) {
10427 $project_id = $object->fk_project;
10428 }
10429 if ($project_id > 0) {
10430 // path:class:method:id
10431 $substitutionarray['__PROJECT_ID__@lazyload'] = '/projet/class/project.class.php:Project:fetchAndSetSubstitution:' . $project_id;
10432 $substitutionarray['__PROJECT_REF__@lazyload'] = '/projet/class/project.class.php:Project:fetchAndSetSubstitution:' . $project_id;
10433 $substitutionarray['__PROJECT_NAME__@lazyload'] = '/projet/class/project.class.php:Project:fetchAndSetSubstitution:' . $project_id;
10434 }
10435 }
10436 }
10437
10438 if (is_object($object) && $object->element == 'facture') {
10439 '@phan-var-force Facture $object';
10441 $substitutionarray['__INVOICE_SITUATION_NUMBER__'] = isset($object->situation_counter) ? $object->situation_counter : '';
10442 }
10443 if (is_object($object) && $object->element == 'shipping') {
10444 '@phan-var-force Expedition $object';
10446 $substitutionarray['__SHIPPINGTRACKNUM__'] = $object->tracking_number;
10447 $substitutionarray['__SHIPPINGTRACKNUMURL__'] = $object->tracking_url;
10448 $substitutionarray['__SHIPPINGMETHOD__'] = $object->shipping_method;
10449 }
10450 if (is_object($object) && $object->element == 'reception') {
10451 '@phan-var-force Reception $object';
10453 $substitutionarray['__RECEPTIONTRACKNUM__'] = $object->tracking_number;
10454 $substitutionarray['__RECEPTIONTRACKNUMURL__'] = $object->tracking_url;
10455 }
10456
10457 if (is_object($object) && $object->element == 'contrat' && $object->id > 0 && is_array($object->lines)) {
10458 '@phan-var-force Contrat $object';
10460 $dateplannedstart = '';
10461 $datenextexpiration = '';
10462 foreach ($object->lines as $line) {
10463 if ($line->date_start > $dateplannedstart) {
10464 $dateplannedstart = $line->date_start;
10465 }
10466 if ($line->statut == 4 && $line->date_end && (!$datenextexpiration || $line->date_end < $datenextexpiration)) {
10467 $datenextexpiration = $line->date_end;
10468 }
10469 }
10470 $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = dol_print_date($dateplannedstart, 'day');
10471 $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE_RFC__'] = dol_print_date($dateplannedstart, 'dayrfc');
10472 $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = dol_print_date($dateplannedstart, 'standard');
10473
10474 $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = dol_print_date($datenextexpiration, 'day');
10475 $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE_RFC__'] = dol_print_date($datenextexpiration, 'dayrfc');
10476 $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = dol_print_date($datenextexpiration, 'standard');
10477 }
10478 // add substitution variables for ticket
10479 if (is_object($object) && $object->element == 'ticket') {
10480 '@phan-var-force Ticket $object';
10482 $substitutionarray['__TICKET_TRACKID__'] = $object->track_id;
10483 $substitutionarray['__TICKET_SUBJECT__'] = $object->subject;
10484 $substitutionarray['__TICKET_TYPE__'] = $object->type_code;
10485 $substitutionarray['__TICKET_SEVERITY__'] = $object->severity_code;
10486 $substitutionarray['__TICKET_CATEGORY__'] = $object->category_code; // For backward compatibility
10487 $substitutionarray['__TICKET_ANALYTIC_CODE__'] = $object->category_code;
10488 $substitutionarray['__TICKET_MESSAGE__'] = $object->message;
10489 $substitutionarray['__TICKET_PROGRESSION__'] = $object->progress;
10490 $userstat = new User($db);
10491 if ($object->fk_user_assign > 0) {
10492 $userstat->fetch($object->fk_user_assign);
10493 $substitutionarray['__TICKET_USER_ASSIGN__'] = dolGetFirstLastname($userstat->firstname, $userstat->lastname);
10494 }
10495
10496 if ($object->fk_user_create > 0) {
10497 $userstat->fetch($object->fk_user_create);
10498 $substitutionarray['__USER_CREATE__'] = dolGetFirstLastname($userstat->firstname, $userstat->lastname);
10499 }
10500 }
10501
10502 // Create dynamic tags for __EXTRAFIELD_FIELD__
10503 if ($object->table_element && $object->id > 0) {
10504 if (!is_object($extrafields)) {
10505 $extrafields = new ExtraFields($db);
10506 }
10507 $extrafields->fetch_name_optionals_label($object->table_element, true);
10508
10509 if ($object->fetch_optionals() > 0) {
10510 if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) {
10511 foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) {
10512 if ($extrafields->attributes[$object->table_element]['type'][$key] == 'date') {
10513 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '__'] = dol_print_date($object->array_options['options_' . $key], 'day');
10514 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '_LOCALE__'] = dol_print_date($object->array_options['options_' . $key], 'day', 'tzserver', $outputlangs);
10515 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '_RFC__'] = dol_print_date($object->array_options['options_' . $key], 'dayrfc');
10516 } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'datetime') {
10517 $datetime = $object->array_options['options_' . $key];
10518 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour') : '');
10519 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour', 'tzserver', $outputlangs) : '');
10520 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '_DAY_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'day', 'tzserver', $outputlangs) : '');
10521 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '_RFC__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhourrfc') : '');
10522 } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'phone') {
10523 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '__'] = dol_print_phone($object->array_options['options_' . $key]);
10524 } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'price') {
10525 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '__'] = $object->array_options['options_' . $key];
10526 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '_FORMATED__'] = price($object->array_options['options_' . $key]); // For compatibility
10527 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '_FORMATTED__'] = price($object->array_options['options_' . $key]);
10528 } elseif ($extrafields->attributes[$object->table_element]['type'][$key] != 'separator') {
10529 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '__'] = !empty($object->array_options['options_' . $key]) ? $object->array_options['options_' . $key] : '';
10530 }
10531 }
10532 }
10533 }
10534 }
10535
10536 // Complete substitution array with the url to make online payment
10537 if (empty($substitutionarray['__REF__'])) {
10538 $paymenturl = '';
10539 } else {
10540 // Set the online payment url link into __ONLINE_PAYMENT_URL__ key
10541 require_once DOL_DOCUMENT_ROOT . '/core/lib/payments.lib.php';
10542 $outputlangs->loadLangs(array('paypal', 'other'));
10543
10544 $amounttouse = 0;
10545 $typeforonlinepayment = 'free';
10546 if (is_object($object) && $object->element == 'commande') {
10547 $typeforonlinepayment = 'order';
10548 }
10549 if (is_object($object) && $object->element == 'facture') {
10550 $typeforonlinepayment = 'invoice';
10551 }
10552 if (is_object($object) && $object->element == 'member') {
10553 $typeforonlinepayment = 'member';
10554 if (!empty($object->last_subscription_amount)) {
10555 $amounttouse = $object->last_subscription_amount;
10556 }
10557 }
10558 if (is_object($object) && $object->element == 'contrat') {
10559 $typeforonlinepayment = 'contract';
10560 }
10561 if (is_object($object) && $object->element == 'fichinter') {
10562 $typeforonlinepayment = 'ficheinter';
10563 }
10564
10565 $url = getOnlinePaymentUrl(0, $typeforonlinepayment, $substitutionarray['__REF__'], (float) $amounttouse);
10566 $paymenturl = $url;
10567 }
10568
10569 if ($object->id > 0) {
10570 $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = ($paymenturl ? str_replace('\n', "\n", $outputlangs->trans("PredefinedMailContentLink", $paymenturl)) : '');
10571 $substitutionarray['__ONLINE_PAYMENT_URL__'] = $paymenturl;
10572
10573 // Show structured communication
10574 if (getDolGlobalString('INVOICE_PAYMENT_ENABLE_STRUCTURED_COMMUNICATION') && $object->element == 'facture') {
10575 include_once DOL_DOCUMENT_ROOT . '/core/lib/functions_be.lib.php';
10576 $substitutionarray['__PAYMENT_STRUCTURED_COMMUNICATION__'] = dolBECalculateStructuredCommunication($object->ref, $object->type);
10577 }
10578
10579 if (getDolGlobalString('PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD') && is_object($object) && $object->element == 'propal') {
10580 $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
10581 } else {
10582 $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = '';
10583 }
10584 if (getDolGlobalString('ORDER_ALLOW_EXTERNAL_DOWNLOAD') && is_object($object) && $object->element == 'commande') {
10585 $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = $object->getLastMainDocLink($object->element);
10586 } else {
10587 $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = '';
10588 }
10589 if (getDolGlobalString('INVOICE_ALLOW_EXTERNAL_DOWNLOAD') && is_object($object) && $object->element == 'facture') {
10590 $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = $object->getLastMainDocLink($object->element);
10591 } else {
10592 $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = '';
10593 }
10594 if (getDolGlobalString('CONTRACT_ALLOW_EXTERNAL_DOWNLOAD') && is_object($object) && $object->element == 'contrat') {
10595 $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = $object->getLastMainDocLink($object->element);
10596 } else {
10597 $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = '';
10598 }
10599 if (getDolGlobalString('FICHINTER_ALLOW_EXTERNAL_DOWNLOAD') && is_object($object) && $object->element == 'fichinter') {
10600 $substitutionarray['__DIRECTDOWNLOAD_URL_FICHINTER__'] = $object->getLastMainDocLink($object->element);
10601 } else {
10602 $substitutionarray['__DIRECTDOWNLOAD_URL_FICHINTER__'] = '';
10603 }
10604 if (getDolGlobalString('SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD') && is_object($object) && $object->element == 'supplier_proposal') {
10605 $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
10606 } else {
10607 $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = '';
10608 }
10609
10610 if (is_object($object) && $object->element == 'propal') {
10611 '@phan-var-force Propal $object';
10613 $substitutionarray['__URL_PROPOSAL__'] = DOL_MAIN_URL_ROOT . "/comm/propal/card.php?id=" . $object->id;
10614 require_once DOL_DOCUMENT_ROOT . '/core/lib/signature.lib.php';
10615 $substitutionarray['__ONLINE_SIGN_URL__'] = getOnlineSignatureUrl(0, 'proposal', $object->ref, 1, $object);
10616 }
10617 if (is_object($object) && $object->element == 'commande') {
10618 '@phan-var-force Commande $object';
10620 $substitutionarray['__URL_ORDER__'] = DOL_MAIN_URL_ROOT . "/commande/card.php?id=" . $object->id;
10621 }
10622 if (is_object($object) && $object->element == 'facture') {
10623 '@phan-var-force Facture $object';
10625 $substitutionarray['__URL_INVOICE__'] = DOL_MAIN_URL_ROOT . "/compta/facture/card.php?id=" . $object->id;
10626 }
10627 if (is_object($object) && $object->element == 'contrat') {
10628 '@phan-var-force Contrat $object';
10630 $substitutionarray['__URL_CONTRACT__'] = DOL_MAIN_URL_ROOT . "/contrat/card.php?id=" . $object->id;
10631 require_once DOL_DOCUMENT_ROOT . '/core/lib/signature.lib.php';
10632 $substitutionarray['__ONLINE_SIGN_URL__'] = getOnlineSignatureUrl(0, 'contract', $object->ref, 1, $object);
10633 }
10634 if (is_object($object) && $object->element == 'fichinter') {
10635 '@phan-var-force Fichinter $object';
10637 $substitutionarray['__URL_FICHINTER__'] = DOL_MAIN_URL_ROOT . "/fichinter/card.php?id=" . $object->id;
10638 require_once DOL_DOCUMENT_ROOT . '/core/lib/signature.lib.php';
10639 $substitutionarray['__ONLINE_SIGN_FICHINTER_URL__'] = getOnlineSignatureUrl(0, 'fichinter', $object->ref, 1, $object);
10640 }
10641 if (is_object($object) && $object->element == 'supplier_proposal') {
10642 '@phan-var-force SupplierProposal $object';
10644 $substitutionarray['__URL_SUPPLIER_PROPOSAL__'] = DOL_MAIN_URL_ROOT . "/supplier_proposal/card.php?id=" . $object->id;
10645 }
10646 if (is_object($object) && $object->element == 'invoice_supplier') {
10647 '@phan-var-force FactureFournisseur $object';
10649 $substitutionarray['__URL_SUPPLIER_INVOICE__'] = DOL_MAIN_URL_ROOT . "/fourn/facture/card.php?id=" . $object->id;
10650 }
10651 if (is_object($object) && $object->element == 'payment_supplier') {
10652 '@phan-var-force PaiementFourn $object';
10654 //print_r($object);
10655 $liste_factures = [];
10656 $total = 0;
10657
10658 $sql = 'SELECT f.ref,f.multicurrency_code as f_mccode, pf.*
10659 FROM '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf
10660 JOIN '.MAIN_DB_PREFIX.'facture_fourn as f ON pf.fk_facturefourn = f.rowid
10661 WHERE pf.fk_paiementfourn = '.((int) $object->id);
10662
10663 $resql = $db->query($sql);
10664 if ($resql) {
10665 while ($objp = $db->fetch_object($resql)) {
10666 $liste_factures[] = ' - '.$outputlangs->trans('Invoice').' '. $objp->ref.' '.$outputlangs->trans('AmountPayed').' '.price($objp->multicurrency_amount, 0, $outputlangs, 0, -1, -1, $objp->multicurrency_code);
10667 }
10668 }
10669 $substitutionarray['__SUPPLIER_PAYMENT_INVOICES_LIST__'] = implode("\n", $liste_factures);
10670 ;
10671 $substitutionarray['__SUPPLIER_PAYMENT_INVOICES_TOTAL__'] = price($object->multicurrency_amount, 0, $outputlangs, 0, -1, -1, $object->multicurrency_code ? $object->multicurrency_code : $conf->currency);
10672 }
10673 if (is_object($object) && $object->element == 'shipping') {
10674 '@phan-var-force Expedition $object';
10676 $substitutionarray['__URL_SHIPMENT__'] = DOL_MAIN_URL_ROOT . "/expedition/card.php?id=" . $object->id;
10677 }
10678 }
10679
10680 if (is_object($object) && $object->element == 'action') {
10681 '@phan-var-force ActionComm $object';
10683 $substitutionarray['__EVENT_LABEL__'] = $object->label;
10684 $substitutionarray['__EVENT_DESCRIPTION__'] = $object->note;
10685 $substitutionarray['__EVENT_TYPE__'] = $outputlangs->trans("Action" . $object->type_code);
10686 $substitutionarray['__EVENT_DATE__'] = dol_print_date($object->datep, 'day', 'auto', $outputlangs);
10687 $substitutionarray['__EVENT_TIME__'] = dol_print_date($object->datep, 'hour', 'auto', $outputlangs);
10688 $substitutionarray['__EVENT_DATE_TZUSER__'] = dol_print_date($object->datep, 'day', 'tzuserrel', $outputlangs);
10689 $substitutionarray['__EVENT_TIME_TZUSER__'] = dol_print_date($object->datep, 'hour', 'tzuserrel', $outputlangs);
10690 }
10691 }
10692 }
10693
10694 if ((empty($exclude) || !in_array('objectamount', $exclude)) && (empty($include) || in_array('objectamount', $include))) {
10695 '@phan-var-force Facture|FactureRec $object';
10697 include_once DOL_DOCUMENT_ROOT . '/core/lib/functionsnumtoword.lib.php';
10698
10699 $substitutionarray['__DATE_YMD__'] = is_object($object) ? (isset($object->date) ? dol_print_date($object->date, 'day', false, $outputlangs) : null) : '';
10700 $substitutionarray['__DATE_DUE_YMD__'] = is_object($object) ? (isset($object->date_lim_reglement) ? dol_print_date($object->date_lim_reglement, 'day', false, $outputlangs) : null) : '';
10701 $substitutionarray['__DATE_YMD_TEXT__'] = is_object($object) ? (isset($object->date) ? dol_print_date($object->date, 'daytext', false, $outputlangs) : null) : '';
10702 $substitutionarray['__DATE_DUE_YMD_TEXT__'] = is_object($object) ? (isset($object->date_lim_reglement) ? dol_print_date($object->date_lim_reglement, 'daytext', false, $outputlangs) : null) : '';
10703
10704 $already_payed_all = 0;
10705 if (is_object($object) && ($object instanceof Facture)) {
10706 $already_payed_all = $object->totalpaid + $object->totaldeposits + $object->totalcreditnotes;
10707 }
10708
10709 $substitutionarray['__AMOUNT_EXCL_TAX__'] = is_object($object) ? $object->total_ht : '';
10710 $substitutionarray['__AMOUNT_EXCL_TAX_TEXT__'] = is_object($object) ? dol_convertToWord($object->total_ht, $outputlangs, '', true) : '';
10711 $substitutionarray['__AMOUNT_EXCL_TAX_TEXTCURRENCY__'] = is_object($object) ? dol_convertToWord($object->total_ht, $outputlangs, $conf->currency, true) : '';
10712
10713 $substitutionarray['__AMOUNT__'] = is_object($object) ? $object->total_ttc : '';
10714 $substitutionarray['__AMOUNT_TEXT__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, '', true) : '';
10715 $substitutionarray['__AMOUNT_TEXTCURRENCY__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, $conf->currency, true) : '';
10716
10717 $substitutionarray['__AMOUNT_REMAIN__'] = is_object($object) ? price2num($object->total_ttc - $already_payed_all, 'MT') : '';
10718
10719 $substitutionarray['__AMOUNT_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
10720 $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)) : '';
10721 $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)) : '';
10722
10723 $mysocuselocaltax1 = false;
10724 $mysocuselocaltax2 = false;
10725 if ($mysoc instanceof Societe && !empty($mysoc->country_code)) {
10726 $tmparray = $mysoc->useLocalTax(-1);
10727 $mysocuselocaltax1 = $tmparray[1];
10728 $mysocuselocaltax2 = $tmparray[2];
10729 }
10730
10731 // Local taxes
10732 if ($onlykey != 2 || $mysocuselocaltax1) {
10733 $substitutionarray['__AMOUNT_TAX2__'] = is_object($object) ? $object->total_localtax1 : '';
10734 }
10735 if ($onlykey != 2 || $mysocuselocaltax2) {
10736 $substitutionarray['__AMOUNT_TAX3__'] = is_object($object) ? $object->total_localtax2 : '';
10737 }
10738
10739 // Amount keys formatted in a currency
10740 $substitutionarray['__AMOUNT_EXCL_TAX_FORMATTED__'] = is_object($object) ? ($object->total_ht ? price($object->total_ht, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
10741 $substitutionarray['__AMOUNT_FORMATTED__'] = is_object($object) ? ($object->total_ttc ? price($object->total_ttc, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
10742 $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) : '';
10743 $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)) : '';
10744 if ($onlykey != 2 || $mysocuselocaltax1) {
10745 $substitutionarray['__AMOUNT_TAX2_FORMATTED__'] = is_object($object) ? ($object->total_localtax1 ? price($object->total_localtax1, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
10746 }
10747 if ($onlykey != 2 || $mysocuselocaltax2) {
10748 $substitutionarray['__AMOUNT_TAX3_FORMATTED__'] = is_object($object) ? ($object->total_localtax2 ? price($object->total_localtax2, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
10749 }
10750 // Amount keys formatted in a currency (with the typo error for backward compatibility)
10751 if ($onlykey != 2) {
10752 $substitutionarray['__AMOUNT_EXCL_TAX_FORMATED__'] = $substitutionarray['__AMOUNT_EXCL_TAX_FORMATTED__'];
10753 $substitutionarray['__AMOUNT_FORMATED__'] = $substitutionarray['__AMOUNT_FORMATTED__'];
10754 $substitutionarray['__AMOUNT_REMAIN_FORMATED__'] = $substitutionarray['__AMOUNT_REMAIN_FORMATTED__'];
10755 $substitutionarray['__AMOUNT_VAT_FORMATED__'] = $substitutionarray['__AMOUNT_VAT_FORMATTED__'];
10756 if ($mysocuselocaltax1) {
10757 $substitutionarray['__AMOUNT_TAX2_FORMATED__'] = $substitutionarray['__AMOUNT_TAX2_FORMATTED__'];
10758 }
10759 if ($mysoc->useLocalTax2) {
10760 $substitutionarray['__AMOUNT_TAX3_FORMATED__'] = $substitutionarray['__AMOUNT_TAX3_FORMATTED__'];
10761 }
10762 }
10763
10764 $substitutionarray['__AMOUNT_MULTICURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? $object->multicurrency_total_ttc : '';
10765 $substitutionarray['__AMOUNT_MULTICURRENCY_FORMATED__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? price($object->multicurrency_total_ttc, 0, $outputlangs, 0, -1, -1, $object->multicurrency_code) : '';
10766 $substitutionarray['__AMOUNT_MULTICURRENCY_TEXT__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, '', true) : '';
10767 $substitutionarray['__AMOUNT_MULTICURRENCY_TEXTCURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, $object->multicurrency_code, true) : '';
10768 $substitutionarray['__MULTICURRENCY_CODE__'] = (is_object($object) && isset($object->multicurrency_code)) ? $object->multicurrency_code : '';
10769 // TODO Add other keys for foreign multicurrency
10770
10771 // For backward compatibility
10772 if ($onlykey != 2) {
10773 $substitutionarray['__TOTAL_TTC__'] = is_object($object) ? $object->total_ttc : '';
10774 $substitutionarray['__TOTAL_HT__'] = is_object($object) ? $object->total_ht : '';
10775 $substitutionarray['__TOTAL_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
10776 }
10777 }
10778
10779
10780 if ((empty($exclude) || !in_array('date', $exclude)) && (empty($include) || in_array('date', $include))) {
10781 include_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
10782
10783 $now = dol_now();
10784
10785 $tmp = dol_getdate($now, true);
10786 $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
10787 $tmp3 = dol_get_prev_month($tmp['mon'], $tmp['year']);
10788 $tmp4 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
10789 $tmp5 = dol_get_next_month($tmp['mon'], $tmp['year']);
10790
10791 $daytext = $outputlangs->trans('Day' . $tmp['wday']);
10792
10793 $substitutionarray = array_merge($substitutionarray, array(
10794 '__NOW_TMS__' => (string) $now, // Must be the string that represent the int
10795 '__NOW_TMS_YMD__' => dol_print_date($now, 'day', 'auto', $outputlangs),
10796 '__DAY__' => (string) $tmp['mday'],
10797 '__DAY_TEXT__' => $daytext, // Monday
10798 '__DAY_TEXT_SHORT__' => dol_trunc($daytext, 3, 'right', 'UTF-8', 1), // Mon
10799 '__DAY_TEXT_MIN__' => dol_trunc($daytext, 1, 'right', 'UTF-8', 1), // M
10800 '__MONTH__' => (string) $tmp['mon'],
10801 '__MONTH_TEXT__' => $outputlangs->trans('Month' . sprintf("%02d", $tmp['mon'])),
10802 '__MONTH_TEXT_SHORT__' => $outputlangs->trans('MonthShort' . sprintf("%02d", $tmp['mon'])),
10803 '__MONTH_TEXT_MIN__' => $outputlangs->trans('MonthVeryShort' . sprintf("%02d", $tmp['mon'])),
10804 '__YEAR__' => (string) $tmp['year'],
10805 '__YEAR_PREVIOUS_MONTH__' => (string) $tmp3['year'],
10806 '__YEAR_NEXT_MONTH__' => (string) $tmp5['year'],
10807 '__PREVIOUS_DAY__' => (string) $tmp2['day'],
10808 '__PREVIOUS_MONTH__' => (string) $tmp3['month'],
10809 '__PREVIOUS_MONTH_TEXT__' => $outputlangs->trans('Month' . sprintf("%02d", $tmp3['month'])),
10810 '__PREVIOUS_MONTH_TEXT_SHORT__' => $outputlangs->trans('MonthShort' . sprintf("%02d", $tmp3['month'])),
10811 '__PREVIOUS_MONTH_TEXT_MIN__' => $outputlangs->trans('MonthVeryShort' . sprintf("%02d", $tmp3['month'])),
10812 '__PREVIOUS_YEAR__' => (string) ($tmp['year'] - 1),
10813 '__NEXT_DAY__' => (string) $tmp4['day'],
10814 '__NEXT_MONTH__' => (string) $tmp5['month'],
10815 '__NEXT_MONTH_TEXT__' => $outputlangs->trans('Month' . sprintf("%02d", $tmp5['month'])),
10816 '__NEXT_MONTH_TEXT_SHORT__' => $outputlangs->trans('MonthShort' . sprintf("%02d", $tmp5['month'])),
10817 '__NEXT_MONTH_TEXT_MIN__' => $outputlangs->trans('MonthVeryShort' . sprintf("%02d", $tmp5['month'])),
10818 '__NEXT_YEAR__' => (string) ($tmp['year'] + 1),
10819 ));
10820 }
10821
10822 if (isModEnabled('multicompany')) {
10823 $substitutionarray = array_merge($substitutionarray, array('__ENTITY_ID__' => $conf->entity));
10824 }
10825 if ((empty($exclude) || !in_array('system', $exclude)) && (empty($include) || in_array('user', $include))) {
10826 $substitutionarray['__DOL_MAIN_URL_ROOT__'] = DOL_MAIN_URL_ROOT;
10827 $substitutionarray['__(AnyTranslationKey)__'] = $outputlangs->trans('TranslationOfKey');
10828 $substitutionarray['__(AnyTranslationKey|langfile)__'] = $outputlangs->trans('TranslationOfKey') . ' (load also language file before)';
10829 $substitutionarray['__[AnyConstantKey]__'] = $outputlangs->trans('ValueOfConstantKey');
10830 }
10831
10832 // Note: The lazyload variables are replaced only during the call by make_substitutions, and only if necessary
10833
10834 return $substitutionarray;
10835}
10836
10853function make_substitutions($text, $substitutionarray, $outputlangs = null, $converttextinhtmlifnecessary = 0)
10854{
10855 global $db, $langs;
10856
10857 if (!is_array($substitutionarray)) {
10858 return 'ErrorBadParameterSubstitutionArrayWhenCalling_make_substitutions';
10859 }
10860
10861 if (empty($outputlangs)) {
10862 $outputlangs = $langs;
10863 }
10864
10865 // Is initial text HTML or simple text ?
10866 $msgishtml = 0;
10867 if (dol_textishtml($text, 1)) {
10868 $msgishtml = 1;
10869 }
10870
10871 // Make substitution for language keys: __(AnyTranslationKey)__ or __(AnyTranslationKey|langfile)__
10872 if (is_object($outputlangs)) {
10873 $reg = array();
10874 while (preg_match('/__\‍(([^\‍)]+)\‍)__/', $text, $reg)) {
10875 // If key is __(TranslationKey|langfile)__, then force load of langfile.lang
10876 $tmp = explode('|', $reg[1]);
10877 if (!empty($tmp[1])) {
10878 $outputlangs->load($tmp[1]);
10879 }
10880
10881 $value = $outputlangs->transnoentitiesnoconv($reg[1]);
10882
10883 if (empty($converttextinhtmlifnecessary)) {
10884 // convert $newval into HTML is necessary
10885 $text = preg_replace('/__\‍(' . preg_quote($reg[1], '/') . '\‍)__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
10886 } else {
10887 if (! $msgishtml) {
10888 $valueishtml = dol_textishtml($value, 1);
10889 //var_dump("valueishtml=".$valueishtml);
10890
10891 if ($valueishtml) {
10892 $text = dol_htmlentitiesbr($text);
10893 $msgishtml = 1;
10894 }
10895 } else {
10896 $value = dol_nl2br((string) $value);
10897 }
10898
10899 $text = preg_replace('/__\‍(' . preg_quote($reg[1], '/') . '\‍)__/', $value, $text);
10900 }
10901 }
10902 }
10903
10904 // Make substitution for constant keys.
10905 // Must be after the substitution of translation, so if the text of translation contains a string __[xxx]__, it is also converted.
10906 $reg = array();
10907 while (preg_match('/__\[([^\]]+)\]__/', $text, $reg)) {
10908 $originalkeyfound = $reg[1];
10909 $keyfound = preg_replace('/\|urlencode$/', '', $originalkeyfound);
10910
10911 if (isASecretKey($keyfound)) {
10912 $value = '*****forbidden*****';
10913 } else {
10914 $value = getDolGlobalString($keyfound);
10915 // Execute some functions on value of substitution key
10916 if (preg_match('/\|urlencode$/', $originalkeyfound)) {
10917 $value = urlencode($value);
10918 }
10919 }
10920
10921 if (empty($converttextinhtmlifnecessary)) {
10922 // convert $newval into HTML is necessary
10923 $text = preg_replace('/__\[' . preg_quote($originalkeyfound, '/') . '\]__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
10924 } else {
10925 if (! $msgishtml) {
10926 $valueishtml = dol_textishtml($value, 1);
10927
10928 if ($valueishtml) {
10929 $text = dol_htmlentitiesbr($text);
10930 $msgishtml = 1;
10931 }
10932 } else {
10933 $value = dol_nl2br((string) $value);
10934 }
10935
10936 $text = preg_replace('/__\[' . preg_quote($originalkeyfound, '/') . '\]__/', $value, $text);
10937 }
10938 }
10939
10940 // Make substitution for array $substitutionarray
10941 foreach ($substitutionarray as $key => $value) {
10942 if (!isset($value)) {
10943 continue; // If value is null, it same than not having substitution key at all into array, we do not replace.
10944 }
10945
10946 if (getDolGlobalString('MAIN_MAIL_DO_NOT_USE_SIGN') && ($key == '__USER_SIGNATURE__' || $key == '__SENDEREMAIL_SIGNATURE__')) {
10947 $value = ''; // Protection
10948 }
10949
10950 if (empty($converttextinhtmlifnecessary)) {
10951 $text = str_replace((string) $key, (string) $value, $text); // Cast to string is needed when value is 123.5 for example
10952 } else {
10953 if (! $msgishtml) {
10954 $valueishtml = dol_textishtml($value, 1);
10955
10956 if ($valueishtml) {
10957 $text = dol_htmlentitiesbr($text);
10958 $msgishtml = 1;
10959 }
10960 } else {
10961 $value = dol_nl2br((string) $value);
10962 }
10963 $text = str_replace((string) $key, (string) $value, $text); // Cast to string is needed 123.5 for example
10964 }
10965 }
10966
10967 // TODO Implement the lazyload substitution
10968 /*
10969 add a loop to scan $substitutionarray:
10970 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.
10971 If no, we don't need to make replacement, so we do nothing.
10972 If yes, we can make the substitution:
10973
10974 include_once $path;
10975 $tmpobj = new $class($db);
10976 $valuetouseforsubstitution = $tmpobj->$method($id, '__XXX__');
10977 And make the replacement of "__XXX__@lazyload" with $valuetouseforsubstitution
10978 */
10979 $memory_object_list = array();
10980 foreach ($substitutionarray as $key => $value) {
10981 $lazy_load_arr = array();
10982 if (preg_match('/(__[A-Z\_]+__)@lazyload$/', $key, $lazy_load_arr)) {
10983 if (isset($lazy_load_arr[1]) && !empty($lazy_load_arr[1])) {
10984 $key_to_substitute = $lazy_load_arr[1];
10985 if (preg_match('/' . preg_quote($key_to_substitute, '/') . '/', $text)) {
10986 $param_arr = explode(':', (string) $value);
10987 // path:class:method:id
10988 if (count($param_arr) == 4) {
10989 $path = $param_arr[0];
10990 $class = $param_arr[1];
10991 $method = $param_arr[2];
10992 $id = (int) $param_arr[3];
10993
10994 // load class file and init object list in memory
10995 if (!isset($memory_object_list[$class])) {
10996 if (dol_is_file(DOL_DOCUMENT_ROOT . $path)) {
10997 require_once DOL_DOCUMENT_ROOT . $path;
10998 if (class_exists($class)) {
10999 $memory_object_list[$class] = array(
11000 'list' => array(),
11001 );
11002 }
11003 }
11004 }
11005
11006 // fetch object and set substitution
11007 if (isset($memory_object_list[$class]) && isset($memory_object_list[$class]['list'])) {
11008 if (method_exists($class, $method)) {
11009 if (!isset($memory_object_list[$class]['list'][$id])) {
11010 $tmpobj = new $class($db);
11011 // @phan-suppress-next-line PhanPluginUnknownObjectMethodCall
11012 $valuetouseforsubstitution = $tmpobj->$method($id, $key_to_substitute);
11013 $memory_object_list[$class]['list'][$id] = $tmpobj;
11014 } else {
11015 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
11016 $tmpobj = $memory_object_list[$class]['list'][$id];
11017 // @phan-suppress-next-line PhanPluginUnknownObjectMethodCall
11018 $valuetouseforsubstitution = $tmpobj->$method($id, $key_to_substitute, true);
11019 }
11020
11021 $text = str_replace((string) $key_to_substitute, (string) $valuetouseforsubstitution, $text); // Cast to string in case value is 123.5 for example
11022 }
11023 }
11024 }
11025 }
11026 }
11027 }
11028 }
11029
11030 return $text;
11031}
11032
11045function complete_substitutions_array(&$substitutionarray, $outputlangs, $object = null, $parameters = null, $callfunc = "completesubstitutionarray")
11046{
11047 global $conf, $user;
11048
11049 require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
11050
11051 // Note: substitution key for each extrafields, using key __EXTRA_XXX__ is already available into the getCommonSubstitutionArray used to build the substitution array.
11052
11053 // Check if there is external substitution to do, requested by plugins
11054 $dirsubstitutions = array_merge(array(), (array) $conf->modules_parts['substitutions']);
11055
11056 foreach ($dirsubstitutions as $reldir) {
11057 $dir = dol_buildpath($reldir, 0);
11058
11059 // Check if directory exists
11060 if (!dol_is_dir($dir)) {
11061 continue;
11062 }
11063
11064 $substitfiles = dol_dir_list($dir, 'files', 0, 'functions_');
11065 foreach ($substitfiles as $substitfile) {
11066 $reg = array();
11067 if (preg_match('/functions_(.*)\.lib\.php/i', $substitfile['name'], $reg)) {
11068 $module = $reg[1];
11069
11070 dol_syslog("Library " . $substitfile['name'] . " found into " . $dir);
11071 // Include the user's functions file
11072 require_once $dir . $substitfile['name'];
11073 // Call the user's function, and only if it is defined
11074 $function_name = $module . "_" . $callfunc;
11075 if (function_exists($function_name)) {
11076 $function_name($substitutionarray, $outputlangs, $object, $parameters);
11077 }
11078 }
11079 }
11080 }
11081 if (getDolGlobalString('ODT_ENABLE_ALL_TAGS_IN_SUBSTITUTIONS')) {
11082 // to list all tags in odt template
11083 $tags = '';
11084 foreach ($substitutionarray as $key => $value) {
11085 $tags .= '{' . $key . '} => ' . $value . "\n";
11086 }
11087 $substitutionarray = array_merge($substitutionarray, array('__ALL_TAGS__' => $tags));
11088 }
11089}
11090
11100function print_date_range($date_start, $date_end, $format = '', $outputlangs = null)
11101{
11102 print get_date_range($date_start, $date_end, $format, $outputlangs);
11103}
11104
11115function get_date_range($date_start, $date_end, $format = '', $outputlangs = null, $withparenthesis = 1)
11116{
11117 global $langs;
11118
11119 $out = '';
11120
11121 if (!is_object($outputlangs)) {
11122 $outputlangs = $langs;
11123 }
11124
11125 if ($date_start && $date_end) {
11126 $out .= ($withparenthesis ? ($withparenthesis == 1 ? ' ' : '').'(' : '') . $outputlangs->transnoentitiesnoconv('DateFromTo', dol_print_date($date_start, $format, false, $outputlangs), dol_print_date($date_end, $format, false, $outputlangs)) . ($withparenthesis ? ')' : '');
11127 }
11128 if ($date_start && !$date_end) {
11129 $out .= ($withparenthesis ? ($withparenthesis == 1 ? ' ' : '').'(' : '') . $outputlangs->transnoentitiesnoconv('DateFrom', dol_print_date($date_start, $format, false, $outputlangs)) . ($withparenthesis ? ')' : '');
11130 }
11131 if (!$date_start && $date_end) {
11132 $out .= ($withparenthesis ? ($withparenthesis == 1 ? ' ' : '').'(' : '') . $outputlangs->transnoentitiesnoconv('DateUntil', dol_print_date($date_end, $format, false, $outputlangs)) . ($withparenthesis ? ')' : '');
11133 }
11134
11135 return $out;
11136}
11137
11146function dolGetFirstLastname($firstname, $lastname, $nameorder = -1)
11147{
11148 $ret = '';
11149 // If order not defined, we use the setup
11150 if ($nameorder < 0) {
11151 $nameorder = (!getDolGlobalString('MAIN_FIRSTNAME_NAME_POSITION') ? 1 : 0);
11152 }
11153 if ($nameorder == 1) {
11154 $ret .= $firstname;
11155 if ($firstname && $lastname) {
11156 $ret .= ' ';
11157 }
11158 $ret .= $lastname;
11159 } elseif ($nameorder == 2 || $nameorder == 3) {
11160 $ret .= $firstname;
11161 if (empty($ret) && $nameorder == 3) {
11162 $ret .= $lastname;
11163 }
11164 } else { // 0, 4 or 5
11165 $ret .= $lastname;
11166 if (empty($ret) && $nameorder == 5) {
11167 $ret .= $firstname;
11168 }
11169 if ($nameorder == 0) {
11170 if ($firstname && $lastname) {
11171 $ret .= ' ';
11172 }
11173 $ret .= $firstname;
11174 }
11175 }
11176 return $ret;
11177}
11178
11179
11192function setEventMessage($mesgs, $style = 'mesgs', $noduplicate = 0, $attop = 0)
11193{
11194 //dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING); This is not deprecated, it is used by setEventMessages function
11195 if (!is_array($mesgs)) {
11196 $mesgs = trim((string) $mesgs);
11197 // If mesgs is a not an empty string
11198 if ($mesgs) {
11199 if (!empty($noduplicate) && isset($_SESSION['dol_events'][$style]) && in_array($mesgs, $_SESSION['dol_events'][$style])) {
11200 return;
11201 }
11202 if ($attop) {
11203 array_unshift($_SESSION['dol_events'][$style], $mesgs);
11204 } else {
11205 $_SESSION['dol_events'][$style][] = $mesgs;
11206 }
11207 }
11208 } else {
11209 // If mesgs is an array
11210 foreach ($mesgs as $mesg) {
11211 $mesg = trim((string) $mesg);
11212 if ($mesg) {
11213 if (!empty($noduplicate) && isset($_SESSION['dol_events'][$style]) && in_array($mesg, $_SESSION['dol_events'][$style])) {
11214 return;
11215 }
11216 if ($attop) {
11217 array_unshift($_SESSION['dol_events'][$style], $mesgs);
11218 } else {
11219 $_SESSION['dol_events'][$style][] = $mesg;
11220 }
11221 }
11222 }
11223 }
11224}
11225
11239function setEventMessages($mesg, $mesgs, $style = 'mesgs', $messagekey = '', $noduplicate = 0, $attop = 0)
11240{
11241 if (empty($mesg) && empty($mesgs)) {
11242 dol_syslog("Try to add a message in stack, but value to add is empty message" . getCallerInfoString(), LOG_WARNING);
11243 } else {
11244 if ($messagekey) {
11245 // Complete message with a js link to set a cookie "DOLHIDEMESSAGE".$messagekey;
11246 // TODO
11247 $mesg .= '';
11248 }
11249 if (empty($messagekey) || empty($_COOKIE["DOLUSER_HIDEMESSAGE" . $messagekey])) {
11250 if (!in_array((string) $style, array('mesgs', 'warnings', 'errors'))) {
11251 dol_print_error(null, 'Bad parameter style=' . $style . ' for setEventMessages');
11252 }
11253 if (empty($mesgs)) {
11254 setEventMessage((string) $mesg, $style, $noduplicate, $attop);
11255 } else {
11256 if (!empty($mesg) && !in_array($mesg, $mesgs)) {
11257 setEventMessage($mesg, $style, $noduplicate, $attop); // Add message string if not already into array
11258 }
11259 setEventMessage($mesgs, $style, $noduplicate, $attop);
11260 }
11261 }
11262 }
11263}
11264
11274function dol_htmloutput_events($disabledoutputofmessages = 0)
11275{
11276 // Show mesgs
11277 if (isset($_SESSION['dol_events']['mesgs'])) {
11278 if (empty($disabledoutputofmessages)) {
11279 dol_htmloutput_mesg('', $_SESSION['dol_events']['mesgs']);
11280 }
11281 unset($_SESSION['dol_events']['mesgs']);
11282 }
11283 // Show errors
11284 if (isset($_SESSION['dol_events']['errors'])) {
11285 if (empty($disabledoutputofmessages)) {
11286 dol_htmloutput_mesg('', $_SESSION['dol_events']['errors'], 'error');
11287 }
11288 unset($_SESSION['dol_events']['errors']);
11289 }
11290
11291 // Show warnings
11292 if (isset($_SESSION['dol_events']['warnings'])) {
11293 if (empty($disabledoutputofmessages)) {
11294 dol_htmloutput_mesg('', $_SESSION['dol_events']['warnings'], 'warning');
11295 }
11296 unset($_SESSION['dol_events']['warnings']);
11297 }
11298}
11299
11314function get_htmloutput_mesg($mesgstring = '', $mesgarray = [], $style = 'ok', $keepembedded = 0)
11315{
11316 global $conf, $langs;
11317
11318 $ret = 0;
11319 $return = '';
11320 $out = '';
11321 $divstart = $divend = '';
11322
11323 // If inline message with no format, we add it.
11324 if ((empty($conf->use_javascript_ajax) || getDolGlobalString('MAIN_DISABLE_JQUERY_JNOTIFY') || defined('DISABLE_JQUERY_JNOTIFY') || $keepembedded) && !preg_match('/<div class=".*">/i', $out)) {
11325 $divstart = '<div class="' . $style . ' clearboth">';
11326 $divend = '</div>';
11327 }
11328
11329 if ((is_array($mesgarray) && count($mesgarray)) || $mesgstring) {
11330 $langs->load("errors");
11331 $out .= $divstart;
11332 if (is_array($mesgarray) && count($mesgarray)) {
11333 foreach ($mesgarray as $message) {
11334 $ret++;
11335 $out .= $langs->trans($message);
11336 if ($ret < count($mesgarray)) {
11337 $out .= "<br>\n";
11338 }
11339 }
11340 }
11341 if ($mesgstring) {
11342 $ret++;
11343 $out .= $langs->trans($mesgstring);
11344 }
11345 $out .= $divend;
11346 }
11347
11348 if ($out) {
11349 if (!empty($conf->use_javascript_ajax) && !getDolGlobalString('MAIN_DISABLE_JQUERY_JNOTIFY') && !defined('DISABLE_JQUERY_JNOTIFY') && empty($keepembedded)) {
11350 $return = '<script nonce="' . getNonce() . '">
11351 $(document).ready(function() {
11352 /* jnotify(message, preset of message type, keepmessage) */
11353 $.jnotify("' . dol_escape_js($out) . '", "' . ($style == "ok" ? 3000 : $style) . '", ' . ($style == "ok" ? "false" : "true") . ',{ remove: function (){} } );
11354 });
11355 </script>';
11356 } else {
11357 $return = $out;
11358 }
11359 }
11360
11361 return $return;
11362}
11363
11375function get_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
11376{
11377 return get_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
11378}
11379
11393function dol_htmloutput_mesg($mesgstring = '', $mesgarray = array(), $style = 'ok', $keepembedded = 0)
11394{
11395 if (empty($mesgstring) && (!is_array($mesgarray) || count($mesgarray) == 0)) {
11396 return;
11397 }
11398
11399 $iserror = 0;
11400 $iswarning = 0;
11401 if (is_array($mesgarray)) {
11402 foreach ($mesgarray as $val) {
11403 if ($val && preg_match('/class="error"/i', $val)) {
11404 $iserror++;
11405 break;
11406 }
11407 if ($val && preg_match('/class="warning"/i', $val)) {
11408 $iswarning++;
11409 break;
11410 }
11411 }
11412 } elseif ($mesgstring && preg_match('/class="error"/i', $mesgstring)) {
11413 $iserror++;
11414 } elseif ($mesgstring && preg_match('/class="warning"/i', $mesgstring)) {
11415 $iswarning++;
11416 }
11417 if ($style == 'error' || $style == 'errors') {
11418 $iserror++;
11419 }
11420 if ($style == 'warning' || $style == 'warnings') {
11421 $iswarning++;
11422 }
11423
11424 if ($iserror || $iswarning) {
11425 // Remove div from texts
11426 $mesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $mesgstring);
11427 $mesgstring = preg_replace('/<div class="(error|warning)">/', '', $mesgstring);
11428 $mesgstring = preg_replace('/<\/div>/', '', $mesgstring);
11429 // Remove div from texts array
11430 if (is_array($mesgarray)) {
11431 $newmesgarray = array();
11432 foreach ($mesgarray as $val) {
11433 if (is_string($val)) {
11434 $tmpmesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $val);
11435 $tmpmesgstring = preg_replace('/<div class="(error|warning)">/', '', $tmpmesgstring);
11436 $tmpmesgstring = preg_replace('/<\/div>/', '', $tmpmesgstring);
11437 $newmesgarray[] = $tmpmesgstring;
11438 } else {
11439 dol_syslog("Error call of dol_htmloutput_mesg with an array with a value that is not a string", LOG_WARNING);
11440 }
11441 }
11442 $mesgarray = $newmesgarray;
11443 }
11444 print get_htmloutput_mesg($mesgstring, $mesgarray, ($iserror ? 'error' : 'warning'), $keepembedded);
11445 } else {
11446 print get_htmloutput_mesg($mesgstring, $mesgarray, 'ok', $keepembedded);
11447 }
11448}
11449
11461function dol_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
11462{
11463 dol_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
11464}
11465
11486function dol_sort_array(&$array, $index, $order = 'asc', $natsort = 0, $case_sensitive = 0, $keepindex = 0)
11487{
11488 // Clean parameters
11489 $order = strtolower($order);
11490
11491 if (is_array($array)) {
11492 $sizearray = count($array);
11493 if ($sizearray > 0) {
11494 // Build a temp array with sorting key as value
11495 $temp = array();
11496 foreach (array_keys($array) as $key) {
11497 $tmpmultikey = explode(',', $index);
11498 $newindex = $tmpmultikey[0];
11499 if (is_object($array[$key])) {
11500 $temp[$key] = empty($array[$key]->$newindex) ? 0 : $array[$key]->$newindex;
11501 // Add other keys
11502 if (!empty($tmpmultikey[1])) {
11503 $newindex = $tmpmultikey[1];
11504 $temp[$key] .= '__' . (empty($array[$key]->$newindex) ? 0 : $array[$key]->$newindex);
11505 }
11506 } else {
11507 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable,PhanTypeArraySuspicious,PhanTypeMismatchDimFetch
11508 $temp[$key] = empty($array[$key][$newindex]) ? 0 : $array[$key][$newindex];
11509 // Add other keys
11510 if (!empty($tmpmultikey[1])) {
11511 $newindex = $tmpmultikey[1];
11512 // @phan-suppress-next-line PhanTypeArraySuspicious,PhanTypeMismatchDimFetch
11513 $temp[$key] .= '__' . (empty($array[$key][$newindex]) ? 0 : $array[$key][$newindex]);
11514 }
11515 }
11516 if ($natsort == -1) {
11517 $temp[$key] = '___' . $temp[$key]; // We add a string at begin of value to force an alpha order when using asort.
11518 }
11519 }
11520 if (empty($natsort) || $natsort == -1) {
11521 if ($order == 'asc') {
11522 asort($temp);
11523 } else {
11524 arsort($temp);
11525 }
11526 } else {
11527 if ($case_sensitive) {
11528 natsort($temp);
11529 } else {
11530 natcasesort($temp); // natecasesort is not sensible to case
11531 }
11532 if ($order != 'asc') {
11533 $temp = array_reverse($temp, true);
11534 }
11535 }
11536
11537 $sorted = array();
11538
11539 foreach (array_keys($temp) as $key) {
11540 (is_numeric($key) && empty($keepindex)) ? $sorted[] = $array[$key] : $sorted[$key] = $array[$key];
11541 }
11542
11543 return $sorted;
11544 }
11545 }
11546 return $array;
11547}
11548
11549
11557function utf8_check($str)
11558{
11559 $str = (string) $str; // Sometimes string is an int.
11560
11561 // We must use here a binary strlen function (so not dol_strlen)
11562 $strLength = strlen($str);
11563 for ($i = 0; $i < $strLength; $i++) {
11564 if (ord($str[$i]) < 0x80) {
11565 continue; // 0bbbbbbb
11566 } elseif ((ord($str[$i]) & 0xE0) == 0xC0) {
11567 $n = 1; // 110bbbbb
11568 } elseif ((ord($str[$i]) & 0xF0) == 0xE0) {
11569 $n = 2; // 1110bbbb
11570 } elseif ((ord($str[$i]) & 0xF8) == 0xF0) {
11571 $n = 3; // 11110bbb
11572 } elseif ((ord($str[$i]) & 0xFC) == 0xF8) {
11573 $n = 4; // 111110bb
11574 } elseif ((ord($str[$i]) & 0xFE) == 0xFC) {
11575 $n = 5; // 1111110b
11576 } else {
11577 return false; // Does not match any model
11578 }
11579 for ($j = 0; $j < $n; $j++) { // n bytes matching 10bbbbbb follow ?
11580 if ((++$i == strlen($str)) || ((ord($str[$i]) & 0xC0) != 0x80)) {
11581 return false;
11582 }
11583 }
11584 }
11585 return true;
11586}
11587
11595function utf8_valid($str)
11596{
11597 /* 2 other methods to test if string is utf8
11598 $validUTF8 = mb_check_encoding($messagetext, 'UTF-8');
11599 $validUTF8b = ! (false === mb_detect_encoding($messagetext, 'UTF-8', true));
11600 */
11601 return preg_match('//u', $str) ? true : false;
11602}
11603
11604
11611function ascii_check($str)
11612{
11613 if (function_exists('mb_check_encoding')) {
11614 //if (mb_detect_encoding($str, 'ASCII', true) return false;
11615 if (!mb_check_encoding($str, 'ASCII')) {
11616 return false;
11617 }
11618 } else {
11619 if (preg_match('/[^\x00-\x7f]/', $str)) {
11620 return false; // Contains a byte > 7f
11621 }
11622 }
11623
11624 return true;
11625}
11626
11627
11635function dol_osencode($str)
11636{
11637 $tmp = ini_get("unicode.filesystem_encoding");
11638 if (empty($tmp) && !empty($_SERVER["WINDIR"])) {
11639 $tmp = 'iso-8859-1'; // By default for windows
11640 }
11641 if (empty($tmp)) {
11642 $tmp = 'utf-8'; // By default for other
11643 }
11644 if (getDolGlobalString('MAIN_FILESYSTEM_ENCODING')) {
11645 $tmp = getDolGlobalString('MAIN_FILESYSTEM_ENCODING');
11646 }
11647
11648 if ($tmp == 'iso-8859-1') {
11649 return mb_convert_encoding($str, 'ISO-8859-1', 'UTF-8');
11650 }
11651 return $str;
11652}
11653
11654
11670function dol_getIdFromCode($db, $key, $tablename, $fieldkey = 'code', $fieldid = 'id', $entityfilter = 0, $filters = '', $useCache = true)
11671{
11672 global $conf;
11673
11674 // If key empty
11675 if ($key == '') {
11676 return 0;
11677 }
11678
11679 // Check in cache
11680 if ($useCache && isset($conf->cache['codeid'][$tablename][$key][$fieldid])) { // Can be defined to 0 or ''
11681 return $conf->cache['codeid'][$tablename][$key][$fieldid]; // Found in cache
11682 }
11683
11684 dol_syslog('dol_getIdFromCode (value for field ' . $fieldid . ' from key ' . $key . ' not found into cache)', LOG_DEBUG);
11685
11686 $sql = "SELECT " . $fieldid . " as valuetoget";
11687 $sql .= " FROM " . MAIN_DB_PREFIX . $tablename;
11688 if ($fieldkey == 'id' || $fieldkey == 'rowid') {
11689 $sql .= " WHERE " . $fieldkey . " = " . ((int) $key);
11690 } else {
11691 $sql .= " WHERE " . $fieldkey . " = '" . $db->escape($key) . "'";
11692 }
11693 if (!empty($entityfilter)) {
11694 $sql .= " AND entity IN (" . getEntity($tablename) . ")";
11695 }
11696 if ($filters) {
11697 $sql .= $filters;
11698 }
11699
11700 $resql = $db->query($sql);
11701 if ($resql) {
11702 $obj = $db->fetch_object($resql);
11703 $valuetoget = '';
11704 if ($obj) {
11705 $valuetoget = $obj->valuetoget;
11706 $conf->cache['codeid'][$tablename][$key][$fieldid] = $valuetoget;
11707 } else {
11708 $conf->cache['codeid'][$tablename][$key][$fieldid] = '';
11709 }
11710 $db->free($resql);
11711
11712 return $valuetoget;
11713 } else {
11714 return -1;
11715 }
11716}
11717
11727function isStringVarMatching($var, $regextext, $matchrule = 1)
11728{
11729 // Tolerate callers (custom modules, older code) that already pass a full regex with delimiters
11730 // like '/^(aaa|bbb)/' instead of the bare body. Without this, the function would build
11731 // '/^/^(aaa|bbb)//' which trips preg_match() with 'Unknown modifier ^'.
11732 $regextext = preg_replace('#^/\^?#', '', (string) $regextext);
11733 $regextext = preg_replace('#\$?/[imsxuADSUXJ]*$#', '', $regextext);
11734
11735 if ($matchrule == 1) {
11736 if ($var == 'mainmenu') {
11737 global $mainmenu;
11738 return (preg_match('/^' . $regextext . '/', $mainmenu));
11739 } elseif ($var == 'leftmenu') {
11740 global $leftmenu;
11741 return (preg_match('/^' . $regextext . '/', $leftmenu));
11742 } else {
11743 return 'This variable is not accessible with dol_eval';
11744 }
11745 } else {
11746 return 'This value '.$matchrule.' for param $matchrule is not yet implemented';
11747 }
11748}
11749
11750
11760function verifCond($strToEvaluate, $onlysimplestring = '1')
11761{
11762 //print $strToEvaluate."<br>\n";
11763 $rights = true;
11764 if (isset($strToEvaluate) && $strToEvaluate !== '') {
11765 //var_dump($strToEvaluate);
11766 //$rep = dol_eval($strToEvaluate, 1, 0, '1'); // to show the error
11767 $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
11768 //var_dump($strToEvaluate, $rep);
11769 $rights = (bool) $rep && (!is_string($rep) || strpos($rep, 'Bad string syntax to evaluate') === false);
11770 //var_dump($rights);
11771 }
11772 return $rights;
11773}
11774
11789function dol_eval($s, $returnvalue = 1, $hideerrors = 1, $onlysimplestring = '1')
11790{
11791 if ($returnvalue != 1) {
11792 dol_syslog("Use of dol_eval with parameter returnvalue = 0 is now forbidden. Please fix this", LOG_ERR);
11793 }
11794
11795 if (getDolGlobalString("MAIN_USE_DOL_EVAL_NEW")) {
11796 return dol_eval_new($s);
11797 } else {
11798 return dol_eval_standard($s, $hideerrors, $onlysimplestring);
11799 }
11800}
11801
11811function dol_eval_new($s)
11812{
11813 // Only this global variables can be read by eval function and returned to caller
11814 global $conf, // Read of const is done with getDolGlobalString() but we need $conf->currency for example
11815 $db, $langs, $user, $website, $websitepage,
11816 $action, $mainmenu, $leftmenu,
11817 $mysoc,
11818 $objectoffield, // To allow the use of $objectoffield in computed fields
11819
11820 // Old variables used
11821 $object,
11822 $obj; // To get $obj used into list when dol_eval() is used for computed fields and $obj is not yet $object
11823
11824 // PHP < 7.4.0
11825 defined('T_COALESCE_EQUAL') || define('T_COALESCE_EQUAL', PHP_INT_MAX);
11826 defined('T_FN') || define('T_FN', PHP_INT_MAX);
11827
11828 // PHP < 8.0.0
11829 defined('T_ATTRIBUTE') || define('T_ATTRIBUTE', PHP_INT_MAX);
11830 defined('T_MATCH') || define('T_MATCH', PHP_INT_MAX);
11831 defined('T_NAME_FULLY_QUALIFIED') || define('T_NAME_FULLY_QUALIFIED', PHP_INT_MAX);
11832 defined('T_NAME_QUALIFIED') || define('T_NAME_QUALIFIED', PHP_INT_MAX);
11833 defined('T_NAME_RELATIVE') || define('T_NAME_RELATIVE', PHP_INT_MAX);
11834
11835 // PHP < 8.1.0
11836 defined('T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG') || define('T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG', PHP_INT_MAX);
11837 defined('T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG') || define('T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG', PHP_INT_MAX);
11838 defined('T_ENUM') || define('T_ENUM', PHP_INT_MAX);
11839 defined('T_READONLY') || define('T_READONLY', PHP_INT_MAX);
11840
11841 // PHP < 8.4.0
11842 defined('T_PRIVATE_SET') || define('T_PRIVATE_SET', PHP_INT_MAX);
11843 defined('T_PROTECTED_SET') || define('T_PROTECTED_SET', PHP_INT_MAX);
11844 defined('T_PUBLIC_SET') || define('T_PUBLIC_SET', PHP_INT_MAX);
11845
11846 $prohibited_token_ids = [
11847 /*
11848 * Prohibited int tokens
11849 */
11850
11851 // T_AND_EQUAL', 'T_ARRAY', 'T_ARRAY_CAST', 'T_AS',
11852 'T_ABSTRACT',
11853 'T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG',
11854 'T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG',
11855 'T_ATTRIBUTE',
11856 // 'T_BOOLEAN_AND', 'T_BOOLEAN_OR', 'T_BOOL_CAST', 'T_BREAK',
11857 'T_BAD_CHARACTER',
11858 // 'T_CASE', 'T_CLASS_C', 'T_CLONE', 'T_COALESCE', 'T_COALESCE_EQUAL', 'T_COMMENT', 'T_CONCAT_EQUAL',
11859 // 'T_CONSTANT_ENCAPSED_STRING', 'T_CONTINUE', 'T_CURLY_OPEN',
11860 'T_CALLABLE',
11861 'T_CATCH',
11862 'T_CLASS',
11863 'T_CLOSE_TAG',
11864 'T_CONST',
11865 // 'T_DEC', 'T_DEFAULT', 'T_DIV_EQUAL', 'T_DNUMBER', 'T_DO', 'T_DOC_COMMENT',
11866 // 'T_DOLLAR_OPEN_CURLY_BRACES', 'T_DOUBLE_ARROW', 'T_DOUBLE_CAST', 'T_DOUBLE_COLON',
11867 'T_DECLARE',
11868 'T_DIR',
11869 // 'T_ELLIPSIS', 'T_ELSE', 'T_ELSEIF', 'T_EMPTY', 'T_ENCAPSED_AND_WHITESPACE', 'T_ENDFOR',
11870 // 'T_ENDFOREACH', 'T_ENDIF', 'T_ENDSWITCH', 'T_ENDWHILE', 'T_END_HEREDOC',
11871 'T_ECHO',
11872 'T_ENDDECLARE',
11873 'T_ENUM',
11874 'T_EVAL',
11875 'T_EXIT',
11876 'T_EXTENDS',
11877 // 'T_FOR', 'T_FOREACH',
11878 'T_FILE',
11879 'T_FINAL',
11880 'T_FINALLY',
11881 'T_FN',
11882 'T_FUNCTION',
11883 'T_FUNC_C',
11884 'T_GLOBAL',
11885 'T_GOTO',
11886 'T_HALT_COMPILER',
11887 // 'T_IF', 'T_INC', 'T_INLINE_HTML', 'T_INSTANCEOF', 'T_INT_CAST', 'T_ISSET', 'T_IS_EQUAL', 'T_IS_GREATER_OR_EQUAL',
11888 // 'T_IS_IDENTICAL', 'T_IS_NOT_EQUAL', 'T_IS_NOT_IDENTICAL', 'T_IS_SMALLER_OR_EQUAL',
11889 'T_IMPLEMENTS',
11890 'T_INCLUDE',
11891 'T_INCLUDE_ONCE',
11892 'T_INSTEADOF',
11893 'T_INTERFACE',
11894 // 'T_LIST', 'T_LNUMBER', 'T_LOGICAL_AND', 'T_LOGICAL_OR', 'T_LOGICAL_XOR',
11895 'T_LINE',
11896 // 'T_MINUS_EQUAL', 'T_MOD_EQUAL', 'T_MUL_EQUAL',
11897 'T_METHOD_C',
11898 // 'T_NEW',
11899 // 'T_NS_SEPARATOR', 'T_NUM_STRING',
11900 'T_NAMESPACE',
11901 // 'T_NAME_FULLY_QUALIFIED', 'T_NAME_QUALIFIED', 'T_NAME_RELATIVE', 'T_NS_C',
11902 // 'T_OBJECT_CAST', 'T_OBJECT_OPERATOR', 'T_OR_EQUAL',
11903 'T_OPEN_TAG',
11904 'T_OPEN_TAG_WITH_ECHO',
11905 // 'T_PAAMAYIM_NEKUDOTAYIM', 'T_PLUS_EQUAL', 'T_POW', 'T_POW_EQUAL',
11906 'T_PRINT',
11907 'T_PRIVATE',
11908 'T_PROTECTED',
11909 'T_PUBLIC',
11910 // 'T_PROPERTY_C',
11911 'T_READONLY',
11912 'T_REQUIRE',
11913 'T_REQUIRE_ONCE',
11914 'T_RETURN',
11915 // 'T_SL', 'T_SL_EQUAL', 'T_SPACESHIP', 'T_SR', 'T_SR_EQUAL', 'T_START_HEREDOC', 'T_STATIC',
11916 // 'T_STRING', 'T_STRING_CAST', 'T_STRING_VARNAME', 'T_SWITCH',
11917 'T_STATIC',
11918 'T_THROW',
11919 'T_TRAIT',
11920 'T_TRAIT_C',
11921 'T_TRY',
11922 'T_UNSET',
11923 'T_UNSET_CAST',
11924 'T_USE',
11925 // 'T_VARIABLE',
11926 'T_VAR',
11927 // 'T_WHILE', 'T_WHITESPACE',
11928 // 'T_XOR_EQUAL',
11929 // 'T_YIELD', 'T_YIELD_FROM',
11930
11931 /*
11932 * Prohibited string tokens
11933 */
11934 ';',
11935 '`',
11936 ];
11937
11938 $prohibited_variables = [
11939 '$_COOKIE',
11940 '$_ENV',
11941 '$_FILES',
11942 '$GLOBALS',
11943 '$_GET',
11944 '$_POST',
11945 '$_REQUEST',
11946 '$_SERVER',
11947 '$_SESSION',
11948 ];
11949
11950 $prohibited_functions = [
11951 // 'base64_decode', 'rawurldecode', 'urldecode', 'str_rot13', 'hex2bin', // I haven't managed to inject anything with these functions yet, can someone confirm?
11952 // 'get_defined_functions', 'get_defined_vars', 'get_defined_constants', 'get_declared_classes', // Should we really block the admin from viewing these lists?
11953 'override_function',
11954 'session_id',
11955 'session_create_id',
11956 'session_regenerate_id',
11957 'call_user_func',
11958 'call_user_func_array', // PREVENT calling forbidden functions
11959 'exec',
11960 'passthru',
11961 'shell_exec',
11962 'system',
11963 'proc_open',
11964 'popen',
11965 'dol_eval',
11966 'dol_eval_new',
11967 'dol_eval_standard',
11968 'dol_contctdesc',
11969 'executeCLI',
11970 'verifCond',
11971 'GETPOST', // Native Dolibarr functions
11972 'create_function',
11973 'assert',
11974 'mb_ereg_replace',
11975 'mb_eregi_replace', // function with eval capabilities
11976 'dol_compress_dir',
11977 'dol_decode',
11978 'dol_delete_file',
11979 'dol_delete_dir',
11980 'dol_delete_dir_recursive',
11981 'dol_copy',
11982 'archiveOrBackupFile', // more dolibarr functions
11983 'fopen',
11984 'file_put_contents',
11985 'fputs',
11986 'fputscsv',
11987 'fwrite',
11988 'fpassthru',
11989 'mkdir',
11990 'rmdir',
11991 'symlink',
11992 'touch',
11993 'unlink',
11994 'umask', // PHP functions related to file operations
11995 'invoke',
11996 'invokeArgs', // Method of ReflectionFunction to execute a function
11997 'filter_input',
11998 'filter_input_array',
11999 'GETPOST', // PREVENT CODE INJECTION
12000 ];
12001
12002 $prohibited_token_arrangements = [
12003 // Variable functions « $a( », « "$a"( », « 'FN_NAME'( », ('FN_NAME')()
12004 ' T_VARIABLE ( ',
12005 ' " ( ',
12006 ' \' ( ',
12007 ' T_CONSTANT_ENCAPSED_STRING ( ',
12008 ' ) ( ',
12009 ];
12010
12011 $tokens = token_get_all("<?php return {$s};", TOKEN_PARSE);
12012
12013 $tokens_arrangement = ' ';
12014
12015 for ($i = 2, $c = count($tokens) - 1; $i < $c; ++$i) { // ignore <?php return and ;
12016 if (is_array($tokens[$i])) {
12017 $token_id = $tokens[$i][0];
12018 $token_value = $tokens[$i][1];
12019 $token_name = token_name($tokens[$i][0]);
12020 } else {
12021 $token_id = $tokens[$i];
12022 $token_value = $tokens[$i];
12023 $token_name = $tokens[$i];
12024 }
12025
12026 // Ignore whitespaces
12027 if (T_WHITESPACE === $token_id) {
12028 continue;
12029 }
12030
12031 // Keep history to check arrangements
12032 $tokens_arrangement .= "{$token_name} ";
12033
12034 // Prohibited Variables
12035 if (
12036 T_VARIABLE === $token_id
12037 && in_array($token_value, $prohibited_variables, true)
12038 ) {
12039 return "« {$token_value} » is prohibited in « {$s} »";
12040 }
12041
12042 // Prohibited Functions
12043 if (
12044 T_STRING === $token_id
12045 && in_array($token_value, $prohibited_functions, true)
12046 ) {
12047 return "« {$token_value} » is prohibited in « {$s} »";
12048 }
12049 }
12050
12051 // Prohibited Token IDs
12052 $maxi = count($prohibited_token_ids);
12053 for ($i = 0; $i < $maxi; ++$i) {
12054 if (false !== strpos($tokens_arrangement, " {$prohibited_token_ids[$i]} ")) {
12055 return "« {$prohibited_token_ids[$i]} » is prohibited in « {$s} »";
12056 }
12057 }
12058
12059 // Prohibited token arrangements
12060 $maxi = count($prohibited_token_arrangements);
12061 for ($i = 0; $i < $maxi; ++$i) {
12062 if (false !== strpos($tokens_arrangement, $prohibited_token_arrangements[$i])) {
12063 return "« {$prohibited_token_arrangements[$i]} » is prohibited in « {$s} »";
12064 }
12065 }
12066
12067 // Return result
12068 try {
12069 return @eval("return {$s};") ?? '';
12070 } catch (Throwable $ex) {
12071 return "Exception during evaluation: " . $s . " - " . $ex->getMessage();
12072 }
12073}
12074
12088function dol_eval_standard($s, $hideerrors = 1, $onlysimplestring = '1')
12089{
12090 // Only this global variables can be read by eval function and returned to caller
12091 // The less we have, the better it is.
12092
12093 global $conf; // TODO Remove this to exclude $conf. We can read $conf->module->enabled with isModEnabled(), $conf->global->xxx properties with getDolGlobalString(), $conf->currency with getDolCurrency(), $conf->entity with getDolEntity()
12094 global $db, $langs, $user, $website, $websitepage;
12095 global $action, $mainmenu, $leftmenu;
12096 global $mysoc;
12097 global $objectoffield; // To allow the use of $objectoffield in computed fields
12098 global $object;
12099
12100 // Old variables (deprecated)
12101 if (getDolGlobalString('MAIN_ALLOW_OLD_VAR_OBJ_IN_DOL_EVAL')) {
12102 global $obj; // To get $obj used into list when dol_eval() is used for computed fields and $obj is not yet $objectoffield
12103 }
12104
12105 $isObBufferActive = false; // When true, the ObBuffer must be cleaned in the exception handler
12106 if ($onlysimplestring == '0') { // '0' is deprecated, we process it as the more secured '1'
12107 $onlysimplestring = '1';
12108 }
12109 if (!in_array($onlysimplestring, array('1', '2'))) {
12110 return "Bad call of dol_eval. Parameter onlysimplestring must be '1' or '2'.";
12111 }
12112 if (!is_scalar($s)) {
12113 return "Bad call of dol_eval. First parameter must be a string, found ".var_export($s, true);
12114 }
12115
12116 try {
12117 global $dolibarr_main_restrict_eval_methods;
12118
12119 // Set $dolibarr_main_restrict_eval_methods_array
12120 if (!isset($dolibarr_main_restrict_eval_methods)) {
12121 $dolibarr_main_restrict_eval_methods = 'getDolGlobalString, getDolGlobalInt, getDolCurrency, getDolEntity, getDolDBType, fetchNoCompute, hasRight, isAdmin, isModEnabled, isStringVarMatching, abs, min, max, round, dol_now, preg_match';
12122 }
12123 //print '$dolibarr_main_restrict_eval_methods = '.$dolibarr_main_restrict_eval_methods."\n";
12124 $dolibarr_main_restrict_eval_methods_array = explode(',', str_replace(" ", "", $dolibarr_main_restrict_eval_methods));
12125
12126 // Test on dangerous char (used for RCE), we allow only characters to make PHP variable testing
12127 // We must accept with 1: '1 && getDolGlobalInt("doesnotexist1") && getDolGlobalString("MAIN_FEATURES_LEVEL")'
12128 // We must accept with 1: '$user->hasRight("cabinetmed", "read") && !$objectoffield->canvas == "patient@cabinetmed"'
12129 // We must accept with 2: (($var1 = new Task($db)) && ($var1->fetchNoCompute($object->id) <= 99) && ($var2 = new Project($db)) && ($var2->fetchNoCompute($var1->fk_project) > 0)) ? $var2->ref : "Parent project not found"
12130
12131 // Check if there is dynamic call (first we check chars are all into a whitelist chars)
12132 $specialcharsallowed = '^$_+-.*>&|=!?():"\',/@';
12133 if ($onlysimplestring == '2') {
12134 $specialcharsallowed .= '<[]'; // Later we check that < has space before and after
12135 }
12136 global $dolibarr_main_allow_unsecured_special_chars_in_dol_eval;
12137 if (!empty($dolibarr_main_allow_unsecured_special_chars_in_dol_eval)) {
12138 $specialcharsallowed .= (string) $dolibarr_main_allow_unsecured_special_chars_in_dol_eval;
12139 }
12140 if (preg_match('/[^a-z0-9\s' . preg_quote($specialcharsallowed, '/') . ']/i', $s)) {
12141 return 'Bad string syntax to evaluate (found chars that are not chars for a simple one line clean eval string): ' . $s;
12142 }
12143
12144 // Check if we found a | without a space before and after
12145 /* Disabled to allow preg_match('/(AAA|BBB)/')
12146 $tmps = str_replace(' || ', '__XXX__', $s);
12147 if (strpos($tmps, '|') !== false) {
12148 return 'Bad string syntax to evaluate (The char | can be used only when duplicated || with a space before and after): ' . $s;
12149 }
12150 */
12151
12152 // Check if there is PHP comments (can be used to obfuscate code)
12153 if (strpos($s, '/*') !== false || strpos($s, '//') !== false) {
12154 return 'Bad string syntax to evaluate (The comment string /* and // are not allowed): ' . $s;
12155 }
12156
12157 // Check if we found a ? without a space before and after
12158 $tmps = str_replace(' ? ', '__XXX__', $s);
12159 if (strpos($tmps, '?') !== false) {
12160 return 'Bad string syntax to evaluate (The char ? can be used only with a space before and after): ' . $s;
12161 }
12162
12163 // Check if there is a < or <= without spaces after
12164 if (preg_match('/<=?[^\s]/', $s)) {
12165 return 'Bad string syntax to evaluate (mode ' . $onlysimplestring . ', found a < or <= without space after): ' . $s;
12166 }
12167
12168 // Check if there is dynamic call (first we use black list patterns)
12169 if (preg_match('/\$[\w]*\s*\‍(/', $s)) {
12170 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;
12171 }
12172
12173 if (empty($dolibarr_main_restrict_eval_methods)) {
12174 // If $dolibarr_main_restrict_eval_methods was set to '', we must check if we try dynamic call
12175
12176 // First we remove white list pattern of using parenthesis then testing if one open parenthesis exists
12177 $savescheck = '';
12178 $scheck = $s;
12179 while ($scheck && $savescheck != $scheck) {
12180 $savescheck = $scheck;
12181 $scheck = preg_replace('/->[a-zA-Z0-9_]+\‍(/', '->__METHOD__', $scheck); // accept parenthesis in '...->method(...'
12182 $scheck = preg_replace('/::[a-zA-Z0-9_]+\‍(/', '->__METHOD__', $scheck); // accept parenthesis in '...::method(...'
12183 $scheck = preg_replace('/^\‍(+/', '__PARENTHESIS__ ', $scheck); // accept parenthesis in '(...'. Must replace with "__PARENTHESIS__ with a space after "to allow following substitutions
12184 $scheck = preg_replace('/\&\&\s+\‍(/', '__ANDPARENTHESIS__ ', $scheck); // accept parenthesis in '&& ('. Must replace with "__PARENTHESIS__ with a space after" to allow following substitutions
12185 $scheck = preg_replace('/\|\|\s+\‍(/', '__ORPARENTHESIS__ ', $scheck); // accept parenthesis in '|| ('. Must replace with "__PARENTHESIS__ with a space after" to allow following substitutions
12186 $scheck = preg_replace('/^!?[a-zA-Z0-9_]+\‍(/', '__FUNCTION__', $scheck); // accept parenthesis in 'function(' and '!function('
12187 $scheck = preg_replace('/\s!?[a-zA-Z0-9_]+\‍(/', '__FUNCTION__', $scheck); // accept parenthesis in '... function(' and '... !function('
12188 $scheck = preg_replace('/^!\‍(/', '__NOTANDPARENTHESIS__', $scheck); // accept parenthesis in '!('
12189 $scheck = preg_replace('/\s!\‍(/', ' __NOTANDPARENTHESIS__', $scheck); // accept parenthesis in '... !('
12190 $scheck = preg_replace('/(\^|\')\‍(/', '__REGEXSTART__', $scheck); // To allow preg_match('/^(aaa|bbb)/'... or isStringVarMatching('leftmenu', '(aaa|bbb)')
12191 }
12192 //print 'scheck='.$scheck." : ".strpos($scheck, '(')."<br>\n";
12193
12194 // Now test if it remains 1 open parenthesis.
12195 if (strpos($scheck, '(') !== false) {
12196 return 'Bad string syntax to evaluate (mode ' . $onlysimplestring . ', found call of a function or method without using the direct name of the function): ' . $s;
12197 }
12198 }
12199
12200 if (strpos($s, '`') !== false) {
12201 return 'Bad string syntax to evaluate (backtick char is forbidden): ' . $s;
12202 }
12203
12204 // Disallow also concat operator
12205 if (!getDolGlobalString('MAIN_ALLOW_OBFUSCATION_METHODS_IN_DOL_EVAL')) {
12206 if (preg_match('/[^0-9]+\.[^0-9]+/', $s)) { // We refuse . if not between 2 numbers
12207 return 'Bad string syntax to evaluate (dot char is forbidden if not strictly between 2 numbers): ' . $s;
12208 }
12209 }
12210
12211 // We exclude string using a $ character that are not an expected global or temporary vars, so that are not:
12212 // $db, $langs, $leftmenu, $topmenu, $user, $langs, $objectoffield, $var....
12213 $savescheck = '';
12214 $scheck = $s;
12215 while ($scheck && $savescheck != $scheck) {
12216 $savescheck = $scheck;
12217 $scheck = preg_replace('/\$conf->[a-z\_]+->enabled/', '__VARCONFENABLED__', $scheck); // Remove this once $user->module->enabled has been replaced everywhere with isModEnabled.
12218 $scheck = preg_replace('/\$user->id/', '__VARUSERID__', $scheck);
12219 $scheck = preg_replace('/\$user->hasRight/', '__VARUSERHASRIGHT__', $scheck);
12220 $scheck = preg_replace('/\$user->rights/', '__VARUSERHASRIGHT__', $scheck); // Remove this once $user->rights->xxx is replaced everywhere with $user->hasRight()
12221 $scheck = preg_replace('/\$user->admin/', '__VARUSERISADMIN__', $scheck); // Remove this once $user->admin is replaced everywhere with $user->isAdmin()
12222 $scheck = preg_replace('/\‍(\$db\‍)/', '__VARDB__', $scheck);
12223 $scheck = preg_replace('/\$langs/', '__VARLANGSTRANS__', $scheck);
12224 $scheck = preg_replace('/\$mysoc/', '__VARMYSOC__', $scheck);
12225 $scheck = preg_replace('/\$action/', '__VARACTION__', $scheck);
12226 $scheck = preg_replace('/\$mainmenu/', '__VARMAINMENU__', $scheck); // Remove this once all tests on $mainmenu has been replaced with isStringVarMatching
12227 $scheck = preg_replace('/\$leftmenu/', '__VARLEFTMENU__', $scheck); // Remove this once all tests on $mainmenu has been replaced with isStringVarMatching
12228 $scheck = preg_replace('/\$websitepage/', '__VARWEBSITEPAGE__', $scheck);
12229 $scheck = preg_replace('/\$website/', '__VARWEBSITE__', $scheck);
12230 $scheck = preg_replace('/\$objectoffield/', '__VAROBJECTOFFIELD__', $scheck);
12231 $scheck = preg_replace('/\$object/', '__VAROBJECT__', $scheck);
12232 $scheck = preg_replace('/\$var/', '__VARVAR__', $scheck);
12233
12234 // deprecated (now we use $objecf->canvas or $objectoffield->canvas)
12235 $scheck = preg_replace('/\$soc->canvas/', '__VARSOCCANVAS__', $scheck);
12236 $scheck = preg_replace('/\$obj->canvas/', '__VAROBJCANVAS__', $scheck);
12237
12238 // Now test if it remains one '$'
12239 if (strpos($scheck, '$') !== false) {
12240 dol_syslog('Bad string syntax to evaluate (found use of $ not matching pattern: $user->hasRight, ($db), $langs, $mysoc, $action, $mainmenu, $leftmenu, $website, $websitepage, $objectoffield or $var123): ' . $s, LOG_WARNING);
12241 return 'Bad string syntax to evaluate (found use of $ not matching pattern: $user->hasRight, ($db), $langs, $mysoc, $action, $mainmenu, $leftmenu, $website, $websitepage, $objectoffield or $var123): ' . $s;
12242 }
12243 }
12244
12245 // We block use of php exec or php file functions
12246 $forbiddenphpstrings = array('_ENV', '_SESSION', '_COOKIE', '_GET', '_GLOBAL', '_POST', '_REQUEST', 'ReflectionFunction', 'SplFileObject', 'SplTempFileObject');
12247
12248 if (empty($dolibarr_main_restrict_eval_methods)) { // If forced to ''
12249 // We list all forbidden function as keywords we don't want to see (we don't mind it if is "keyword(" or just "keyword", we don't want "keyword" at all)
12250 // 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
12251 // like we can do with array_map and its callable parameter: dol_eval('json_encode(array_map(implode("",["ex","ec"]), ["id"]))', 1, 1, '0')
12252 $forbiddenphpfunctions = array();
12253 $forbiddenphpmethods = array();
12254
12255 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("override_function", "session_id", "session_create_id", "session_regenerate_id"));
12256 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("get_defined_functions", "get_defined_vars", "get_defined_constants", "get_declared_classes"));
12257 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("function", "call_user_func", "call_user_func_array"));
12258
12259 $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"));
12260 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("usort", "uasort", "uksort", "preg_replace_callback", "preg_replace_callback_array", "header_register_callback"));
12261 $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"));
12262 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("spl_autoload_register", "spl_autoload_unregister", "iterator_apply", "session_set_save_handler"));
12263 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("forward_static_call", "forward_static_call_array", "register_postsend_function"));
12264
12265 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("ob_start"));
12266
12267 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("require", "include", "require_once", "include_once"));
12268 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("exec", "passthru", "shell_exec", "system", "proc_open", "popen"));
12269 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("pcntl_alarm", "pcntl_exec", "pcntl_fork", "pcntl_waitpid", "pcntl_wait", "pcntl_wifexited", "pcntl_wifstopped", "pcntl_wifsignaled", "pcntl_wifcontinued", "pcntl_wexitstatus", "pcntl_wtermsig", "pcntl_wstopsig", "pcntl_signal"));
12270 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("pcntl_signal_get_handler", "pcntl_signal_dispatch", "pcntl_get_last_error", "pcntl_strerror", "pcntl_sigprocmask", "pcntl_sigwaitinfo", "pcntl_sigtimedwait", "pcntl_getpriority", "pcntl_async_signals", "pcntl_unshare", ));
12271 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("putenv", "dl", "apache_child_terminate", "apache_setenv"));
12272 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("posix_kill", "posix_setuid", "posix_setgid"));
12273 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("dol_eval", "dol_eval_new", "dol_eval_standard", "executeCLI", "verifCond", "GETPOST", "dolEncrypt", "dolDecrypt")); // native dolibarr functions
12274 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("eval", "create_function", "assert", "mb_ereg_replace")); // function with eval capabilities
12275 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("readline_completion_function", "readline_callback_handler_install"));
12276 $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
12277 $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"));
12278 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("require", "include"));
12279 if (!getDolGlobalString('MAIN_ALLOW_OBFUSCATION_METHODS_IN_DOL_EVAL')) { // We disallow all function that allow to obfuscate the real name of a function
12280 // @phpcs:ignore
12281 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("base64" . "_" . "decode", "rawurl" . "decode", "url" . "decode", "str" . "_rot13", "hex" . "2bin", "printf", "sprintf")); // name of forbidden functions are split to avoid false positive
12282 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("dol_concat", "dol_concatdesc")); // native dolibarr functions
12283 }
12284 // Remove from blacklist the function that are into the whitelist
12285 /*foreach ($forbiddenphpfunctions as $key => $forbiddenphpfunction) {
12286 if (in_array($forbiddenphpfunction, $dolibarr_main_restrict_eval_methods_array)) {
12287 unset($forbiddenphpfunctions[$key]);
12288 }
12289 }*/
12290
12291 $forbiddenphpmethods = array_merge($forbiddenphpmethods, array('invoke', 'invokeArgs')); // Methods of ReflectionFunction to execute a function
12292 // Remove from blacklist the function that are into the whitelist
12293 /*foreach ($forbiddenphpmethods as $key => $forbiddenphpmethod) {
12294 if (in_array($forbiddenphpmethod, $dolibarr_main_restrict_eval_methods_array)) {
12295 unset($forbiddenphpmethods[$key]);
12296 }
12297 }*/
12298
12299 $forbiddenphpregex = 'global\s*\$';
12300 $forbiddenphpregex .= '|';
12301 $forbiddenphpregex .= '\b(' . implode('|', $forbiddenphpfunctions) . ')\b';
12302
12303 $forbiddenphpmethodsregex = '->(' . implode('|', $forbiddenphpmethods) . ')';
12304
12305 // Now scan all forbidden patterns
12306 do {
12307 $oldstringtoclean = $s;
12308 $s = str_ireplace($forbiddenphpstrings, '__forbiddenstring__', $s);
12309 $s = preg_replace('/' . $forbiddenphpregex . '/i', '__forbiddenstring__', $s);
12310 $s = preg_replace('/' . $forbiddenphpmethodsregex . '/i', '__forbiddenstring__', $s);
12311 //$s = preg_replace('/\$[a-zA-Z0-9_\->\$]+\‍(/i', '', $s); // Remove $function( call and $mycall->mymethod(
12312 } while ($oldstringtoclean != $s);
12313
12314 if (strpos($s, '__forbiddenstring__') !== false) {
12315 dol_syslog('Bad string syntax to evaluate: ' . $s, LOG_WARNING);
12316 return 'Bad string syntax to evaluate: ' . $s;
12317 }
12318 }
12319
12320 if (!empty($dolibarr_main_restrict_eval_methods)) {
12321 // Accept only white-listed allowed function and classes
12322 // TODO Get all pattern '/([\s\w]+)\‍(/', then check that $reg[1] is a defined class or a function into a given list
12323 $pattern = '/([\s\w\'\]\"]+)\‍(/';
12324
12325 $matches = array();
12326 preg_match_all($pattern, $s, $matches);
12327
12328 if (count($matches)) {
12329 foreach ($matches[1] as $m) {
12330 $m = trim($m);
12331 if (empty($m)) {
12332 continue;
12333 }
12334 $reg = array();
12335 if (!preg_match('/new ([A-Z][\w]+)/i', $m, $reg)) {
12336 if (!in_array($m, $dolibarr_main_restrict_eval_methods_array)) {
12337 if ($m != "'" && $m != '"') {
12338 dol_syslog('Bad string syntax to evaluate: ' . $s, LOG_WARNING);
12339 return 'Bad string syntax to evaluate. A function or method "'.$m.'" was called and is not into the parameter $dolibarr_main_restrict_eval_methods of white-listed functions and methods: ' . $s;
12340 }
12341 }
12342 } else {
12343 if (!class_exists($reg[1])) {
12344 dol_syslog('Bad string syntax to evaluate: Class "'.$reg[1].'" does not exist. ' . $s, LOG_WARNING);
12345 return 'Bad string syntax to evaluate. Class "'.$reg[1].'" does not exist. ' . $s;
12346 }
12347 $parents = class_parents($reg[1]); // Get list of parent classes of class we want to check
12348 if (!in_array('CommonObject', $parents)) { // Only classes that inherit CommonObject are ok. This forbid dangerous classes like ReflectionFunction, SplFileObject, ...
12349 dol_syslog('Bad string syntax to evaluate: Class "'.$reg[1].'" is not allowed because only classes extended CommonObject can be used in dynamic evaluation. ' . $s, LOG_WARNING);
12350 return 'Bad string syntax to evaluate. Class "'.$reg[1].'" is not allowed because only classes extended CommonObject can be used in dynamic evaluation. ' . $s;
12351 }
12352 }
12353 }
12354 }
12355
12356 $forbiddenphpregex = 'global\s*\$';
12357 $forbiddenphpregex .= '|'; // or
12358 $forbiddenphpregex .= '}\s*\[';
12359 $forbiddenphpregex .= '|'; // or
12360 $forbiddenphpregex .= '\‍)\s*\‍(';
12361
12362 // Now scan all forbidden patterns
12363 do {
12364 $oldstringtoclean = $s;
12365 $s = str_ireplace($forbiddenphpstrings, '__forbiddenstring__', $s);
12366 $s = preg_replace('/' . $forbiddenphpregex . '/i', '__forbiddenstring__', $s);
12367 //$s = preg_replace('/' . $forbiddenphpmethodsregex . '/i', '__forbiddenstring__', $s);
12368 //$s = preg_replace('/\$[a-zA-Z0-9_\->\$]+\‍(/i', '', $s); // Remove $function( call and $mycall->mymethod(
12369 } while ($oldstringtoclean != $s);
12370
12371 if (strpos($s, '__forbiddenstring__') !== false) {
12372 dol_syslog('Bad string syntax to evaluate: ' . $s, LOG_WARNING);
12373 return 'Bad string syntax to evaluate: ' . $s;
12374 }
12375 }
12376
12377 //print $s."<br>\n";
12378 ob_start(); // An evaluation has no reason to output data
12379 $isObBufferActive = true;
12380 $tmps = $hideerrors ? @eval('return ' . $s . ';') : eval('return ' . $s . ';');
12381 $tmpo = ob_get_clean();
12382 $isObBufferActive = false;
12383 if ($tmpo) {
12384 print 'Bad string syntax to evaluate. Some data were output when it should not when evaluating: ' . $s;
12385 }
12386 return $tmps;
12387 } catch (Error $e) {
12388 if ($isObBufferActive) {
12389 // Clean up buffer which was left behind due to exception.
12390 $tmpo = ob_get_clean();
12391 $isObBufferActive = false;
12392 }
12393 $error = 'dol_eval try/catch error : ';
12394 $error .= $e->getMessage();
12395 dol_syslog($error, LOG_WARNING);
12396 return 'Exception during evaluation: ' . $s;
12397 }
12398}
12399
12407function dol_validElement($element)
12408{
12409 return (trim($element) != '');
12410}
12411
12420function picto_from_langcode($codelang, $moreatt = '', $notitlealt = 0)
12421{
12422 if (empty($codelang)) {
12423 return '';
12424 }
12425
12426 if ($codelang == 'auto') {
12427 return '<span class="fa fa-language"></span>';
12428 }
12429
12430 $langtocountryflag = array(
12431 'ar_AR' => '',
12432 'ca_ES' => 'catalonia',
12433 'da_DA' => 'dk',
12434 'fr_CA' => 'mq',
12435 'sv_SV' => 'se',
12436 'sw_SW' => 'unknown',
12437 'AQ' => 'unknown',
12438 'CW' => 'unknown',
12439 'IM' => 'unknown',
12440 'JE' => 'unknown',
12441 'MF' => 'unknown',
12442 'BL' => 'unknown',
12443 'SX' => 'unknown'
12444 );
12445
12446 if (isset($langtocountryflag[$codelang])) {
12447 $flagImage = $langtocountryflag[$codelang];
12448 } else {
12449 $tmparray = explode('_', $codelang);
12450 $flagImage = empty($tmparray[1]) ? $tmparray[0] : $tmparray[1];
12451 }
12452
12453 $morecss = '';
12454 $reg = array();
12455 if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
12456 $morecss = $reg[1];
12457 $moreatt = "";
12458 }
12459
12460 // return img_picto_common($codelang, 'flags/'.strtolower($flagImage).'.png', $moreatt, 0, $notitlealt);
12461 return '<span class="flag-sprite ' . strtolower($flagImage) . ($morecss ? ' ' . $morecss : '') . '"' . ($moreatt ? ' ' . $moreatt : '') . (!$notitlealt ? ' title="' . $codelang . '"' : '') . '></span>';
12462}
12463
12471function getLanguageCodeFromCountryCode($countrycode)
12472{
12473 global $mysoc;
12474
12475 if (empty($countrycode)) {
12476 return null;
12477 }
12478
12479 if (strtoupper($countrycode) == 'MQ') {
12480 return 'fr_CA';
12481 }
12482 if (strtoupper($countrycode) == 'SE') {
12483 return 'sv_SE'; // se_SE is Sami/Sweden, and we want in priority sv_SE for SE country
12484 }
12485 if (strtoupper($countrycode) == 'CH') {
12486 if ($mysoc->country_code == 'FR') {
12487 return 'fr_CH';
12488 }
12489 if ($mysoc->country_code == 'DE') {
12490 return 'de_CH';
12491 }
12492 if ($mysoc->country_code == 'IT') {
12493 return 'it_CH';
12494 }
12495 }
12496
12497 // Locale list taken from:
12498 // http://stackoverflow.com/questions/3191664/
12499 // list-of-all-locales-and-their-short-codes
12500 $locales = array(
12501 'af-ZA',
12502 'am-ET',
12503 'ar-AE',
12504 'ar-BH',
12505 'ar-DZ',
12506 'ar-EG',
12507 'ar-IQ',
12508 'ar-JO',
12509 'ar-KW',
12510 'ar-LB',
12511 'ar-LY',
12512 'ar-MA',
12513 'ar-OM',
12514 'ar-QA',
12515 'ar-SA',
12516 'ar-SY',
12517 'ar-TN',
12518 'ar-YE',
12519 //'as-IN', // Moved after en-IN
12520 'ba-RU',
12521 'be-BY',
12522 'bg-BG',
12523 'bn-BD',
12524 //'bn-IN', // Moved after en-IN
12525 'bo-CN',
12526 'br-FR',
12527 'ca-ES',
12528 'co-FR',
12529 'cs-CZ',
12530 'cy-GB',
12531 'da-DK',
12532 'de-AT',
12533 'de-CH',
12534 'de-DE',
12535 'de-LI',
12536 'de-LU',
12537 'dv-MV',
12538 'el-GR',
12539 'en-AU',
12540 'en-BZ',
12541 'en-CA',
12542 'en-GB',
12543 'en-IE',
12544 'en-IN',
12545 'as-IN', // as-IN must be after en-IN (en in priority if country is IN)
12546 'bn-IN', // bn-IN must be after en-IN (en in priority if country is IN)
12547 'en-JM',
12548 'en-MY',
12549 'en-NZ',
12550 'en-PH',
12551 'en-SG',
12552 'en-TT',
12553 'en-US',
12554 'en-ZA',
12555 'en-ZW',
12556 'es-AR',
12557 'es-BO',
12558 'es-CL',
12559 'es-CO',
12560 'es-CR',
12561 'es-DO',
12562 'es-EC',
12563 'es-ES',
12564 'es-GT',
12565 'es-HN',
12566 'es-MX',
12567 'es-NI',
12568 'es-PA',
12569 'es-PE',
12570 'es-PR',
12571 'es-PY',
12572 'es-SV',
12573 'es-US',
12574 'es-UY',
12575 'es-VE',
12576 'et-EE',
12577 'eu-ES',
12578 'fa-IR',
12579 'fi-FI',
12580 'fo-FO',
12581 'fr-BE',
12582 'fr-CA',
12583 'fr-CH',
12584 'fr-FR',
12585 'fr-LU',
12586 'fr-MC',
12587 'fy-NL',
12588 'ga-IE',
12589 'gd-GB',
12590 'gl-ES',
12591 'gu-IN',
12592 'he-IL',
12593 'hi-IN',
12594 'hr-BA',
12595 'hr-HR',
12596 'hu-HU',
12597 'hy-AM',
12598 'id-ID',
12599 'ig-NG',
12600 'ii-CN',
12601 'is-IS',
12602 'it-CH',
12603 'it-IT',
12604 'ja-JP',
12605 'ka-GE',
12606 'kk-KZ',
12607 'kl-GL',
12608 'km-KH',
12609 'kn-IN',
12610 'ko-KR',
12611 'ky-KG',
12612 'lb-LU',
12613 'lo-LA',
12614 'lt-LT',
12615 'lv-LV',
12616 'mi-NZ',
12617 'mk-MK',
12618 'ml-IN',
12619 'mn-MN',
12620 'mr-IN',
12621 'ms-BN',
12622 'ms-MY',
12623 'mt-MT',
12624 'nb-NO',
12625 'ne-NP',
12626 'nl-BE',
12627 'nl-NL',
12628 'nn-NO',
12629 'oc-FR',
12630 'or-IN',
12631 'pa-IN',
12632 'pl-PL',
12633 'ps-AF',
12634 'pt-BR',
12635 'pt-PT',
12636 'rm-CH',
12637 'ro-MD',
12638 'ro-RO',
12639 'ru-RU',
12640 'rw-RW',
12641 'sa-IN',
12642 'se-FI',
12643 'se-NO',
12644 'se-SE',
12645 'si-LK',
12646 'sk-SK',
12647 'sl-SI',
12648 'sq-AL',
12649 'sv-FI',
12650 'sv-SE',
12651 'sw-KE',
12652 'ta-IN',
12653 'te-IN',
12654 'th-TH',
12655 'tk-TM',
12656 'tn-ZA',
12657 'tr-TR',
12658 'tt-RU',
12659 'ug-CN',
12660 'uk-UA',
12661 'ur-PK',
12662 'vi-VN',
12663 'wo-SN',
12664 'xh-ZA',
12665 'yo-NG',
12666 'zh-CN',
12667 'zh-HK',
12668 'zh-MO',
12669 'zh-SG',
12670 'zh-TW',
12671 'zu-ZA',
12672 );
12673
12674 $buildprimarykeytotest = strtolower($countrycode) . '-' . strtoupper($countrycode);
12675 if (in_array($buildprimarykeytotest, $locales)) {
12676 return strtolower($countrycode) . '_' . strtoupper($countrycode);
12677 }
12678
12679 if (function_exists('locale_get_primary_language') && function_exists('locale_get_region')) { // Need extension php-intl
12680 foreach ($locales as $locale) {
12681 $locale_language = locale_get_primary_language($locale);
12682 $locale_region = locale_get_region($locale);
12683 if (strtoupper($countrycode) == $locale_region) {
12684 //var_dump($locale.' - '.$locale_language.' - '.$locale_region);
12685 return strtolower($locale_language) . '_' . strtoupper($locale_region);
12686 }
12687 }
12688 } else {
12689 dol_syslog("Warning Extension php-intl is not available", LOG_WARNING);
12690 }
12691
12692 return null;
12693}
12694
12725function complete_head_from_modules($conf, $langs, $object, &$head, &$h, $type, $mode = 'add', $filterorigmodule = '')
12726{
12727 global $hookmanager, $db;
12728
12729 if (isset($conf->modules_parts['tabs'][$type]) && is_array($conf->modules_parts['tabs'][$type])) {
12730 foreach ($conf->modules_parts['tabs'][$type] as $value) {
12731 $values = explode(':', $value);
12732
12733 $reg = array();
12734 if ($mode == 'add' && !preg_match('/^\-/', $values[1])) {
12735 if (count($values) !== 6) {
12736 dol_syslog('The module_parts["tabs"] entries must be composed of 6 values separated by ":", but got "' . $value . '". Please check your module descriptor classes.', LOG_ERR);
12737 continue;
12738 }
12739
12740 // new declaration with permissions:
12741 // $value='objecttype:+tabname1:Title1:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
12742 // $value='objecttype:+tabname1:Title1,class,pathfile,method:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
12743 if ($values[0] != $type) {
12744 continue;
12745 }
12746
12747 $newtab = array();
12748 $postab = $h;
12749 // detect if position set in $values[1] ie : +(2)mytab@mymodule (first tab is 0, second is one, ...)
12750 $str = $values[1];
12751 $posstart = strpos($str, '(');
12752 if ($posstart > 0) {
12753 $posend = strpos($str, ')');
12754 if ($posstart > 0) {
12755 $res1 = substr($str, $posstart + 1, $posend - $posstart - 1);
12756 if (is_numeric($res1)) {
12757 $postab = (int) $res1;
12758 $values[1] = '+' . substr($str, $posend + 1);
12759 }
12760 }
12761 }
12762
12763 global $objectoffield; // So we can use $objectoffield int verifCond
12764 $objectoffield = $object;
12765
12766 if (!verifCond($values[4], '2')) {
12767 continue;
12768 }
12769
12770 if ($values[3]) {
12771 if ($filterorigmodule) { // If a filter of module origin has been requested
12772 if (strpos($values[3], '@')) { // This is an external module
12773 if ($filterorigmodule != 'external') {
12774 continue;
12775 }
12776 } else { // This looks a core module
12777 if ($filterorigmodule != 'core') {
12778 continue;
12779 }
12780 }
12781 }
12782 $langs->load($values[3]);
12783 }
12784
12785 if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
12786 // If label is "SUBSTITUION_..."
12787 $substitutionarray = array();
12788 complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey' => $values[2]));
12789 $label = make_substitutions($reg[1], $substitutionarray);
12790 } else {
12791 // If label is "Label,Class,File,Method", we call the method to show content inside the badge
12792 $labeltemp = explode(',', $values[2]);
12793 $label = $langs->trans($labeltemp[0]);
12794
12795 if (!empty($labeltemp[1]) && is_object($object) && !empty($object->id)) {
12796 dol_include_once($labeltemp[2]);
12797 $classtoload = $labeltemp[1];
12798 if (class_exists($classtoload)) {
12799 $obj = new $classtoload($db);
12800 $function = $labeltemp[3];
12801 if ($obj && $function && method_exists($obj, $function)) {
12802 // @phan-suppress-next-line PhanPluginUnknownObjectMethodCall
12803 $nbrec = $obj->$function($object->id, $obj);
12804 if (!empty($nbrec)) {
12805 $label .= '<span class="badge marginleftonlyshort">' . $nbrec . '</span>';
12806 }
12807 }
12808 }
12809 }
12810 }
12811 $url = preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[5]);
12812 $link = parse_url($url);
12813 $query = [];
12814 if (isset($link['query'])) {
12815 parse_str($link['query'], $query);
12816 }
12817 $newtab[0] = dolBuildUrl(dol_buildpath($link['path'], 1), $query);
12818 $newtab[1] = $label;
12819 $newtab[2] = str_replace('+', '', $values[1]);
12820 $h++;
12821
12822 // set tab at its position
12823 $head = array_merge(array_slice($head, 0, $postab), array($newtab), array_slice($head, $postab));
12824 } elseif ($mode == 'remove' && preg_match('/^\-/', $values[1])) {
12825 if ($values[0] != $type) {
12826 continue;
12827 }
12828 $tabname = str_replace('-', '', $values[1]);
12829 foreach ($head as $key => $val) {
12830 $condition = (!empty($values[3]) ? verifCond($values[3], '2') : 1);
12831 //var_dump($key.' - '.$tabname.' - '.$head[$key][2].' - '.$values[3].' - '.$condition);
12832 if ($head[$key][2] == $tabname && $condition) {
12833 unset($head[$key]);
12834 break;
12835 }
12836 }
12837 }
12838 }
12839 }
12840
12841 // No need to make a return $head. Var is modified as a reference
12842 if (!empty($hookmanager)) {
12843 $parameters = array('object' => $object, 'mode' => $mode, 'head' => &$head, 'filterorigmodule' => $filterorigmodule);
12844 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable
12845 $reshook = $hookmanager->executeHooks('completeTabsHead', $parameters, $object);
12846 if ($reshook > 0) { // Hook ask to replace completely the array
12847 $head = $hookmanager->resArray;
12848 } else { // Hook
12849 $head = array_merge($head, $hookmanager->resArray);
12850 }
12851 $h = count($head);
12852 }
12853}
12854
12866function printCommonFooter($zone = 'private')
12867{
12868 global $conf, $hookmanager, $user, $langs;
12869 global $action;
12870 global $micro_start_time;
12871
12872 if ($zone == 'private') {
12873 print "\n" . '<!-- Common footer for private page -->' . "\n";
12874 } else {
12875 print "\n" . '<!-- Common footer for public page -->' . "\n";
12876 }
12877
12878 // A div to store page_y POST parameter so we can read it using javascript
12879 print "\n<!-- A div to store page_y POST parameter -->\n";
12880 print '<div id="page_y" style="display: none;">' . (GETPOST('page_y') ? GETPOST('page_y') : '') . '</div>' . "\n";
12881
12882 $parameters = array('zone' => $zone);
12883 $tmpobject = null;
12884 // @phan-suppress-next-line PhanPluginConstantVariableNull
12885 $reshook = $hookmanager->executeHooks('printCommonFooter', $parameters, $tmpobject, $action); // Note that $action and $object may have been modified by some hooks
12886 if (empty($reshook)) {
12887 if (getDolGlobalString('MAIN_HTML_FOOTER')) {
12888 print getDolGlobalString('MAIN_HTML_FOOTER') . "\n";
12889 }
12890
12891 print "\n";
12892 if (!empty($conf->use_javascript_ajax)) {
12893 print "\n<!-- A script section to add menuhider handler on backoffice, manage focus and mandatory fields, tuning info, ... -->\n";
12894 print '<script>' . "\n";
12895 print 'jQuery(document).ready(function() {' . "\n";
12896
12897 if ($zone == 'private' && empty($conf->dol_use_jmobile)) {
12898 print "\n";
12899 print '/* JS CODE TO ENABLE to manage handler to switch left menu page (menuhider) */' . "\n";
12900 print 'jQuery("li.menuhider").click(function(event) {';
12901 print ' if (!$( "body" ).hasClass( "sidebar-collapse" )){ event.preventDefault(); }' . "\n";
12902 print ' console.log("We click on .menuhider");' . "\n";
12903 print ' $("body").toggleClass("sidebar-collapse")' . "\n";
12904 print '});' . "\n";
12905 }
12906
12907 // Management of focus and mandatory for fields
12908 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"])))) {
12909 print '/* JS CODE TO ENABLE to manage focus and mandatory form fields */' . "\n";
12910 $relativepathstring = $_SERVER["PHP_SELF"];
12911 // Clean $relativepathstring
12912 if (constant('DOL_URL_ROOT')) {
12913 $relativepathstring = preg_replace('/^' . preg_quote(constant('DOL_URL_ROOT'), '/') . '/', '', $relativepathstring);
12914 }
12915 $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
12916 $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
12917 //$tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
12918
12919 if (!empty($user->default_values[$relativepathstring]['focus'])) {
12920 foreach ($user->default_values[$relativepathstring]['focus'] as $defkey => $defval) {
12921 $qualified = 0;
12922 if ($defkey != '_noquery_') {
12923 $tmpqueryarraytohave = explode('&', $defkey);
12924 $foundintru = 0;
12925 foreach ($tmpqueryarraytohave as $tmpquerytohave) {
12926 $tmpquerytohaveparam = explode('=', $tmpquerytohave);
12927 //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
12928 if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) {
12929 $foundintru = 1;
12930 }
12931 }
12932 if (!$foundintru) {
12933 $qualified = 1;
12934 }
12935 //var_dump($defkey.'-'.$qualified);
12936 } else {
12937 $qualified = 1;
12938 }
12939
12940 if ($qualified) {
12941 print 'console.log("set the focus by executing jQuery(...).focus();")' . "\n";
12942 foreach ($defval as $paramkey => $paramval) {
12943 // Set focus on field
12944 print 'jQuery("input[name=\'' . $paramkey . '\']").focus();' . "\n";
12945 print 'jQuery("textarea[name=\'' . $paramkey . '\']").focus();' . "\n"; // TODO KO with ckeditor
12946 print 'jQuery("select[name=\'' . $paramkey . '\']").focus();' . "\n"; // Not really useful, but we keep it in case of.
12947 }
12948 }
12949 }
12950 }
12951 if (!empty($user->default_values[$relativepathstring]['mandatory'])) {
12952 foreach ($user->default_values[$relativepathstring]['mandatory'] as $defkey => $defval) {
12953 $qualified = 0;
12954 if ($defkey != '_noquery_') {
12955 $tmpqueryarraytohave = explode('&', $defkey);
12956 $foundintru = 0;
12957 foreach ($tmpqueryarraytohave as $tmpquerytohave) {
12958 $tmpquerytohaveparam = explode('=', $tmpquerytohave);
12959 //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
12960 if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) {
12961 $foundintru = 1;
12962 }
12963 }
12964 if (!$foundintru) {
12965 $qualified = 1;
12966 }
12967 //var_dump($defkey.'-'.$qualified);
12968 } else {
12969 $qualified = 1;
12970 }
12971
12972 if ($qualified) {
12973 print 'console.log("set the js code to manage fields that are set as mandatory");' . "\n";
12974
12975 foreach ($defval as $paramkey => $paramval) {
12976 // Solution 1: Add handler on submit to check if mandatory fields are empty
12977 print 'var form = $(\'[name="'.dol_escape_js($paramkey).'"]\').closest("form");'."\n";
12978 print "form.on('submit', function(event) {
12979 var submitter = \$(this).find(':submit:focus').get(0);
12980 var buttonName = submitter ? \$(submitter).attr('name') : 'save';
12981
12982 if (buttonName == 'cancel') {
12983 console.log('We click on cancel button so we accept submit with no need to check mandatory fields');
12984 return true;
12985 }
12986
12987 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');
12988
12989 var tmpvalue = jQuery('[name=\"".dol_escape_js($paramkey)."\"]').val();
12990 let tmptypefield = jQuery('[name=\"".dol_escape_js($paramkey)."\"]').prop('nodeName').toLowerCase(); // Get the tag name (div, section, footer...)
12991
12992 if (tmptypefield == 'textarea') {
12993 // We must instead check the content of ckeditor
12994 var tmpeditor = (typeof CKEDITOR !== 'undefined') ? CKEDITOR.instances['".dol_escape_js($paramkey)."'] : null;
12995 if (tmpeditor) {
12996 tmpvalue = tmpeditor.getData();
12997 console.log('For textarea tmpvalue is '+tmpvalue);
12998 }
12999 }
13000
13001 let tmpvalueisempty = false;
13002 if (tmpvalue === null || tmpvalue === undefined || tmpvalue === '' || tmpvalue === -1 || tmpvalue === '-1') {
13003 tmpvalueisempty = true;
13004 }
13005 if (tmpvalue === '0' && (tmptypefield == 'select' || tmptypefield == 'input')) {
13006 tmpvalueisempty = true;
13007 }
13008 if (tmpvalueisempty && buttonName !== 'cancel') {
13009 console.log('field has type '+tmptypefield+' and is empty, we cancel the submit');
13010 event.preventDefault(); // Stop submission of form to allow custom code to decide.
13011 event.stopPropagation(); // Stop other handlers.
13012
13013 alert('".dol_escape_js($langs->transnoentitiesnoconv("ErrorFieldRequired", $paramkey).' ('.$langs->transnoentitiesnoconv("CustomMandatoryFieldRule").')')."');
13014
13015 return false;
13016 }
13017 console.log('field has type '+tmptypefield+' and is defined to '+tmpvalue);
13018 return true;
13019 });
13020 \n";
13021
13022 // Solution 2: Add property 'required' on input
13023 // so browser will check value and try to focus on it when submitting the form.
13024 //print 'setTimeout(function() {'; // If we want to wait that ckeditor beuatifier has finished its job.
13025 //print 'jQuery("input[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
13026 //print 'jQuery("textarea[id=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
13027 //print 'jQuery("select[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";*/
13028 //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";
13029 //print 'jQuery("select[name=\''.$paramkey.'\'] option[value=\'-1\']").prop(\'value\', \'\');'."\n";
13030 //print 'jQuery("select[name=\''.$paramkey.'\'] option[value=\'0\']").prop(\'value\', \'\');'."\n";
13031 // Add 'field required' class on closest td for all input elements : input, textarea and select
13032 //print '}, 500);'; // 500 milliseconds delay
13033
13034 // Now set the class "fieldrequired"
13035 print 'jQuery(\':input[name="' . dol_escape_js($paramkey) . '"]\').closest("tr").find("td:first").addClass("fieldrequired");' . "\n";
13036 }
13037
13038 // If we submit using the cancel button, we remove the required attributes
13039 print 'jQuery("input[name=\'cancel\']").click(function() {
13040 console.log("We click on cancel button so removed all required attribute");
13041 jQuery("input, textarea, select").each(function(){this.removeAttribute(\'required\');});
13042 });' . "\n";
13043 }
13044 }
13045 }
13046 }
13047
13048 print '});' . "\n";
13049
13050 // End of tuning
13051 if (!empty($_SERVER['MAIN_SHOW_TUNING_INFO']) || getDolGlobalString('MAIN_SHOW_TUNING_INFO')) {
13052 print "\n";
13053 print "/* JS CODE TO ENABLE to add memory info */\n";
13054 print 'window.console && console.log("';
13055 if (getDolGlobalString('MEMCACHED_SERVER')) {
13056 print 'MEMCACHED_SERVER=' . getDolGlobalString('MEMCACHED_SERVER') . ' - ';
13057 }
13058 print 'MAIN_OPTIMIZE_SPEED=' . getDolGlobalString('MAIN_OPTIMIZE_SPEED', 'off');
13059 if (!empty($micro_start_time)) { // Works only if MAIN_SHOW_TUNING_INFO is defined at $_SERVER level. Not in global variable.
13060 $micro_end_time = microtime(true);
13061 print ' - Build time: ' . ceil(1000 * ($micro_end_time - $micro_start_time)) . ' ms';
13062 }
13063
13064 if (function_exists("memory_get_usage")) {
13065 print ' - Mem: ' . memory_get_usage(); // Do not use true here, it seems it takes the peak amount
13066 }
13067 if (function_exists("memory_get_peak_usage")) {
13068 print ' - Real mem peak: ' . memory_get_peak_usage(true);
13069 }
13070 if (function_exists("zend_loader_file_encoded")) {
13071 print ' - Zend encoded file: ' . (zend_loader_file_encoded() ? 'yes' : 'no');
13072 }
13073 print '");' . "\n";
13074 }
13075
13076 print "\n" . '</script>' . "\n";
13077
13078 // Google Analytics
13079 // TODO Remove this, can be replaced with the hook printCommonFooter
13080 if (isModEnabled('google') && getDolGlobalString('MAIN_GOOGLE_AN_ID')) {
13081 $tmptagarray = explode(',', getDolGlobalString('MAIN_GOOGLE_AN_ID'));
13082 foreach ($tmptagarray as $tmptag) {
13083 print "\n";
13084 print "<!-- JS CODE TO ENABLE for google analtics tag -->\n";
13085 print '
13086 <!-- Global site tag (gtag.js) - Google Analytics -->
13087 <script nonce="' . getNonce() . '" async src="https://www.googletagmanager.com/gtag/js?id=' . trim($tmptag) . '"></script>
13088 <script>
13089 window.dataLayer = window.dataLayer || [];
13090 function gtag(){dataLayer.push(arguments);}
13091 gtag(\'js\', new Date());
13092
13093 gtag(\'config\', \'' . trim($tmptag) . '\');
13094 </script>';
13095 print "\n";
13096 }
13097 }
13098 }
13099
13100 // Add Xdebug coverage of code
13101 if (defined('XDEBUGCOVERAGE')) {
13102 print_r(xdebug_get_code_coverage());
13103 }
13104
13105 // Output string from hooks
13106 if (!empty($hookmanager->resPrint)) {
13107 print $hookmanager->resPrint;
13108 }
13109
13110 // Add DebugBar data
13111 if ($user->hasRight('debugbar', 'read')) {
13112 global $debugbar;
13113 if ($debugbar instanceof DebugBar\DebugBar) {
13114 if (isset($debugbar['time'])) {
13115 // @phan-suppress-next-line PhanPluginUnknownObjectMethodCall
13116 $debugbar['time']->stopMeasure('pageaftermaster');
13117 }
13118 print '<!-- Output debugbar data -->' . "\n";
13119 $renderer = $debugbar->getJavascriptRenderer();
13120 print $renderer->render();
13121 }
13122 } elseif (count($conf->logbuffer)) { // If there is some logs in buffer to show
13123 print "\n";
13124 print "<!-- Start of log output\n";
13125 //print '<div class="hidden">'."\n";
13126 foreach ($conf->logbuffer as $logline) {
13127 print $logline . "<br>\n";
13128 }
13129 //print '</div>'."\n";
13130 print "End of log output -->\n";
13131 }
13132 }
13133}
13134
13144function dolExplodeIntoArray($string, $delimiter = ';', $kv = '=')
13145{
13146 if (is_null($string)) {
13147 return array();
13148 }
13149
13150 if (preg_match('/^\[.*\]$/sm', $delimiter) || preg_match('/^\‍(.*\‍)$/sm', $delimiter)) {
13151 // This is a regex string
13152 $newdelimiter = $delimiter;
13153 } else {
13154 // This is a simple string
13155 // @phan-suppress-next-line PhanPluginSuspiciousParamPositionInternal
13156 $newdelimiter = preg_quote($delimiter, '/');
13157 }
13158
13159 if ($a = preg_split('/' . $newdelimiter . '/', $string)) {
13160 $ka = array();
13161 foreach ($a as $s) { // each part
13162 if ($s) {
13163 if ($pos = strpos($s, $kv)) { // key/value delimiter
13164 $ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv)));
13165 } else { // key delimiter not found
13166 $ka[] = trim($s);
13167 }
13168 }
13169 }
13170 return $ka;
13171 }
13172
13173 return array();
13174}
13175
13183function dolExplodeKeepIfQuotes($input)
13184{
13185 // Use regexp to capture words and section in quotes
13186 $matches = array();
13187 preg_match_all('/"([^"]*)"|\'([^\']*)\'|(\S+)/', $input, $matches);
13188
13189 // Merge result and delete empty values
13190
13191 $result = array_map(
13198 static function ($a, $b, $c) {
13199 if ($a !== '') {
13200 return $a;
13201 }
13202 if ($b !== '') {
13203 return $b;
13204 }
13205 if ($c !== '') {
13206 return $c;
13207 }
13208 return '';
13209 },
13210 $matches[1],
13211 $matches[2],
13212 $matches[3]
13213 );
13214 return array_values(array_filter(
13215 $result,
13222 static function ($val) {
13223 return $val !== '';
13224 }
13225 ));
13226}
13227
13228
13235function dol_set_focus($selector)
13236{
13237 print "\n" . '<!-- Set focus onto a specific field -->' . "\n";
13238 print '<script nonce="' . getNonce() . '">jQuery(document).ready(function() { console.log("Force focus by dol_set_focus"); jQuery("' . dol_escape_js($selector) . '").focus(); });</script>' . "\n";
13239}
13240
13241
13249function dol_getmypid()
13250{
13251 if (!function_exists('getmypid')) {
13252 return mt_rand(99900000, 99965535);
13253 } else {
13254 return getmypid(); // May be a number on 64 bits (depending on OS)
13255 }
13256}
13257
13280function natural_search($fields, $value, $mode = 0, $nofirstand = 0, $sqltoadd = '')
13281{
13282 global $db, $langs;
13283
13284 $value = trim($value);
13285
13286 if ($mode == 0) {
13287 $value = preg_replace('/\*/', '%', $value); // Replace * with %
13288 }
13289 if ($mode == 1) {
13290 $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
13291 }
13292
13293 $value = preg_replace('/\s*\|\s*/', '|', $value);
13294
13295 // Split criteria on ' ' but not if we are inside quotes.
13296 // For mode 3, the split is done later on the , only and not on the ' '.
13297 if ($mode != -3 && $mode != 3) {
13298 $crits = dolExplodeKeepIfQuotes($value);
13299 } else {
13300 $crits = array($value);
13301 }
13302
13303 $res = '';
13304 if (!is_array($fields)) {
13305 $fields = array($fields);
13306 }
13307 $i1 = 0; // count the nb of "and" criteria added (all fields / criteria)
13308 foreach ($crits as $crit) { // Loop on each AND criteria
13309 $crit = trim($crit);
13310 $i2 = 0; // count the nb of valid criteria added for this this first criteria
13311 $newres = '';
13312
13313 foreach ($fields as $field) {
13314 if ($mode == 1) {
13315 $tmpcrits = explode('|', $crit);
13316 $i3 = 0; // count the nb of valid criteria added for this current field
13317 foreach ($tmpcrits as $tmpcrit) {
13318 if ($tmpcrit !== '0' && empty($tmpcrit)) {
13319 continue;
13320 }
13321 $tmpcrit = trim($tmpcrit);
13322
13323 $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
13324
13325 $operator = '=';
13326 $newcrit = preg_replace('/([!<>=]+)/', '', $tmpcrit);
13327
13328 $reg = array();
13329 preg_match('/([!<>=]+)/', $tmpcrit, $reg);
13330 if (!empty($reg[1])) {
13331 $operator = $reg[1];
13332 }
13333 if ($newcrit != '') {
13334 $numnewcrit = price2num($newcrit);
13335 if (is_numeric($numnewcrit)) {
13336 $newres .= $db->sanitize($field) . ' ' . $operator . ' ' . ((float) $numnewcrit); // should be a numeric
13337 } else {
13338 $newres .= '1 = 2'; // force false, we received a corrupted data
13339 }
13340 $i3++; // a criteria was added to string
13341 }
13342 }
13343 $i2++; // a criteria for 1 more field was added to string
13344 } elseif ($mode == 2 || $mode == -2) {
13345 $crit = preg_replace('/[^\-0-9,]/', '', $crit); // ID are always integer
13346 $newres .= ($i2 > 0 ? ' OR ' : '') . $db->sanitize($field) . " " . ($mode == -2 ? 'NOT ' : '');
13347 $newres .= $crit ? "IN (" . $db->sanitize($db->escape($crit)) . ")" : "IN (0)";
13348 if ($mode == -2) {
13349 $newres .= ' OR ' . $db->sanitize($field) . ' IS NULL';
13350 }
13351 $i2++; // a criteria for 1 more field was added to string
13352 } elseif ($mode == 3 || $mode == -3) {
13353 $tmparray = explode(',', $crit);
13354 if (count($tmparray)) {
13355 $listofcodes = '';
13356 foreach ($tmparray as $val) {
13357 $val = trim($val);
13358 if ($val) { // TODO Test with if ($val !== '') {
13359 $listofcodes .= ($listofcodes ? ',' : '');
13360 $listofcodes .= "'" . $db->escape($val) . "'";
13361 }
13362 }
13363 $newres .= ($i2 > 0 ? ' OR ' : '') . $db->sanitize($field) . " " . ($mode == -3 ? 'NOT ' : '') . "IN (" . $db->sanitize($listofcodes, 1, 0, 1) . ")";
13364 $i2++; // a criteria for 1 more field was added to string
13365 }
13366 if ($mode == -3) {
13367 $newres .= ' OR ' . $db->sanitize($field) . ' IS NULL';
13368 }
13369 } elseif ($mode == 4) {
13370 $tmparray = explode(',', $crit);
13371 if (count($tmparray)) {
13372 $listofcodes = '';
13373 foreach ($tmparray as $val) {
13374 $val = trim($val);
13375 if ($val) {
13376 $newres .= ($i2 > 0 ? " OR (" : "(") . $db->sanitize($field) . " LIKE '" . $db->escape($val) . ",%'";
13377 $newres .= ' OR ' . $db->sanitize($field) . " = '" . $db->escape($val) . "'";
13378 $newres .= ' OR ' . $db->sanitize($field) . " LIKE '%," . $db->escape($val) . "'";
13379 $newres .= ' OR ' . $db->sanitize($field) . " LIKE '%," . $db->escape($val) . ",%'";
13380 $newres .= ')';
13381 $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)
13382 }
13383 }
13384 }
13385 } else { // $mode=0
13386 $tmpcrits = explode('|', $crit);
13387 $i3 = 0; // count the nb of valid criteria added for the current couple criteria/field
13388 foreach ($tmpcrits as $tmpcrit) { // loop on each OR criteria
13389 if ($tmpcrit !== '0' && empty($tmpcrit)) {
13390 continue;
13391 }
13392 $tmpcrit = trim($tmpcrit);
13393
13394 if ($tmpcrit == '^$' || strpos($crit, '!') === 0) { // If we search empty, we must combined different OR fields with AND
13395 $newres .= (($i2 > 0 || $i3 > 0) ? ' AND ' : '');
13396 } else {
13397 $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
13398 }
13399
13400 $isSellist = false;
13401 $table = $label = $key = null;
13402
13403 if (strpos($field, 'ef.') === 0) {
13404 $extrafieldName = substr($field, 3);
13405 $extrafields = new ExtraFields($db);
13406 $extrafields->fetch_name_optionals_label('product');
13407
13408 if (isset($extrafields->attributes['product']['type'][$extrafieldName]) && $extrafields->attributes['product']['type'][$extrafieldName] === 'sellist') {
13409 $isSellist = true;
13410 $paramArray = $extrafields->attributes['product']['param'][$extrafieldName]['options'] ?? [];
13411 $param = array_key_first($paramArray);
13412 list($table, $label, $key) = explode(':', $param);
13413 }
13414 }
13415
13416 if (preg_match('/\.(id|rowid)$/', $field)) { // Special case for rowid that is sometimes a ref so used as a search field
13417 $newres .= $db->sanitize($field) . " = " . (is_numeric($tmpcrit) ? ((float) $tmpcrit) : '0');
13418 } else {
13419 $tmpcrit2 = $tmpcrit;
13420 $tmpbefore = '%';
13421 $tmpafter = '%';
13422 $tmps = '';
13423
13424 if ($isSellist) {
13425 $newres .= $field . " IN (SELECT t." . $db->sanitize($key) . " FROM " . $db->prefix() . $db->sanitize($table) . " AS t WHERE t." . $db->sanitize($label) . " LIKE '%" . $db->escape($tmpcrit2) . "%')";
13426 } else {
13427 if (preg_match('/^!/', $tmpcrit)) {
13428 $tmps .= $db->sanitize($field) . " NOT LIKE "; // ! as exclude character
13429 $tmpcrit2 = preg_replace('/^!/', '', $tmpcrit2);
13430 } else {
13431 $tmps .= $db->sanitize($field) . " LIKE ";
13432 }
13433 $tmps .= "'";
13434
13435 if (preg_match('/^[\^\$]/', $tmpcrit)) {
13436 $tmpbefore = '';
13437 $tmpcrit2 = preg_replace('/^[\^\$]/', '', $tmpcrit2);
13438 }
13439 if (preg_match('/[\^\$]$/', $tmpcrit)) {
13440 $tmpafter = '';
13441 $tmpcrit2 = preg_replace('/[\^\$]$/', '', $tmpcrit2);
13442 }
13443
13444 if ($tmpcrit2 == '' || preg_match('/^!/', $tmpcrit)) {
13445 $tmps = "(" . $tmps;
13446 }
13447 $newres .= $tmps;
13448 $newres .= $tmpbefore;
13449 $newres .= $db->escape($tmpcrit2);
13450 $newres .= $tmpafter;
13451 $newres .= "'";
13452 if ($tmpcrit2 == '' || preg_match('/^!/', $tmpcrit)) {
13453 $newres .= " OR " . $db->sanitize($field) . " IS NULL)";
13454 }
13455 }
13456 }
13457
13458 $i3++;
13459 }
13460
13461 $i2++; // a criteria for 1 more field was added to string
13462 }
13463 }
13464
13465 if ($sqltoadd) {
13466 $newres .= ($newres ? '' : ' OR ').str_replace('__KEYTOSEARCH__', $db->escape($crit), $sqltoadd);
13467 }
13468
13469 if ($newres) {
13470 $res = $res . ($res ? ' AND ' : '') . ($i2 > 1 ? '(' : '') . $newres . ($i2 > 1 ? ')' : '');
13471 }
13472 $i1++;
13473 }
13474 $res = ($nofirstand ? "" : " AND ") . "(" . $res . ")";
13475
13476 return $res;
13477}
13478
13485function showDirectDownloadLink($object)
13486{
13487 global $langs;
13488
13489 $out = '';
13490 $url = $object->getLastMainDocLink($object->element);
13491
13492 $out .= img_picto($langs->trans("PublicDownloadLinkDesc"), 'globe') . ' <span class="opacitymedium">' . $langs->trans("DirectDownloadLink") . '</span><br>';
13493 if ($url) {
13494 $out .= '<div class="urllink"><input type="text" id="directdownloadlink" class="quatrevingtpercent" value="' . $url . '"></div>';
13495 $out .= ajax_autoselect("directdownloadlink", '');
13496 } else {
13497 $out .= '<div class="urllink">' . $langs->trans("FileNotShared") . '</div>';
13498 }
13499
13500 return $out;
13501}
13502
13511function getImageFileNameForSize($file, $extName, $extImgTarget = '')
13512{
13513 $dirName = dirname($file);
13514 if ($dirName == '.') {
13515 $dirName = '';
13516 }
13517
13518 if (!in_array($extName, array('', '_small', '_mini'))) {
13519 return 'Bad parameter extName';
13520 }
13521
13522 $fileName = preg_replace('/(\.gif|\.jpeg|\.jpg|\.png|\.bmp|\.webp)$/i', '', $file); // We remove image extension, whatever is its case
13523 $fileName = basename($fileName);
13524
13525 if (empty($extImgTarget)) {
13526 $extImgTarget = (preg_match('/\.jpg$/i', $file) ? '.jpg' : '');
13527 }
13528 if (empty($extImgTarget)) {
13529 $extImgTarget = (preg_match('/\.jpeg$/i', $file) ? '.jpeg' : '');
13530 }
13531 if (empty($extImgTarget)) {
13532 $extImgTarget = (preg_match('/\.gif$/i', $file) ? '.gif' : '');
13533 }
13534 if (empty($extImgTarget)) {
13535 $extImgTarget = (preg_match('/\.png$/i', $file) ? '.png' : '');
13536 }
13537 if (empty($extImgTarget)) {
13538 $extImgTarget = (preg_match('/\.bmp$/i', $file) ? '.bmp' : '');
13539 }
13540 if (empty($extImgTarget)) {
13541 $extImgTarget = (preg_match('/\.webp$/i', $file) ? '.webp' : '');
13542 }
13543
13544 if (!$extImgTarget) {
13545 return $file;
13546 }
13547
13548 $subdir = '';
13549 if ($extName) {
13550 $subdir = 'thumbs/';
13551 }
13552
13553 return ($dirName ? $dirName . '/' : '') . $subdir . $fileName . $extName . $extImgTarget; // New filename for thumb
13554}
13555
13556
13566function getAdvancedPreviewUrl($modulepart, $relativepath, $alldata = 0, $param = '')
13567{
13568 global $conf, $langs;
13569
13570 if (empty($conf->use_javascript_ajax)) {
13571 return '';
13572 }
13573
13574 $isAllowedForPreview = dolIsAllowedForPreview($relativepath);
13575
13576 if ($alldata == 1) {
13577 if ($isAllowedForPreview) {
13578 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));
13579 } else {
13580 return array();
13581 }
13582 }
13583
13584 // old behavior, return a string
13585 if ($isAllowedForPreview) {
13586 $tmpurl = DOL_URL_ROOT . '/document.php?modulepart=' . urlencode($modulepart) . '&attachment=0&file=' . urlencode($relativepath) . ($param ? '&' . $param : '');
13587 $title = $langs->transnoentities("Preview");
13588 //$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().
13589 //$tmpurl = 'file='.urlencode("'-alert(document.domain)-'_small.jpg"); // An example of tmpurl that should be blocked by the dol_escape_uri()
13590
13591 // 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,
13592 // 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.
13593 // Using the dol_escape_uri guarantee that we encode for URI so decode retrieve original expected value.
13594 return 'javascript:' . dol_escape_uri('document_preview(\'' . dol_escape_js($tmpurl) . '\', \'' . dol_escape_js(dol_mimetype($relativepath)) . '\', \'' . dol_escape_js($title) . '\')');
13595 } else {
13596 return '';
13597 }
13598}
13599
13606function getLabelSpecialCode($idcode)
13607{
13608 global $langs;
13609
13610 $arrayspecialines = array(1 => 'Transport', 2 => 'EcoTax', 3 => 'Option');
13611 if ($idcode > 10) {
13612 return 'Module ID ' . $idcode;
13613 }
13614 if (!empty($arrayspecialines[$idcode])) {
13615 return $langs->trans($arrayspecialines[$idcode]);
13616 }
13617 return '';
13618}
13619
13628function ajax_autoselect($htmlname, $addlink = '', $textonlink = 'Link')
13629{
13630 global $langs;
13631 $out = '<script nonce="' . getNonce() . '">
13632 jQuery(document).ready(function () {
13633 jQuery("' . ((strpos($htmlname, '.') === 0 ? '' : '#') . $htmlname) . '").click(function() { jQuery(this).select(); } );
13634 });
13635 </script>';
13636 if ($addlink) {
13637 if ($textonlink === 'image') {
13638 $out .= ' <a href="' . $addlink . '" target="_blank" rel="noopener noreferrer">' . img_picto('', 'globe') . '</a>';
13639 } else {
13640 $out .= ' <a href="' . $addlink . '" target="_blank" rel="noopener noreferrer">' . $langs->trans("Link") . '</a>';
13641 }
13642 }
13643 return $out;
13644}
13645
13653function dolIsAllowedForPreview($file)
13654{
13655 // Check .noexe extension in filename
13656 if (preg_match('/\.noexe$/i', $file)) {
13657 return 0;
13658 }
13659
13660 // Check mime types
13661 $mime_preview = array('bmp', 'jpeg', 'png', 'gif', 'tiff', 'pdf', 'plain', 'css', 'webp', 'webm', 'mp4');
13662 if (getDolGlobalString('MAIN_ALLOW_SVG_FILES_AS_IMAGES')) {
13663 $mime_preview[] = 'svg+xml';
13664 }
13665 if (getDolGlobalString('MAIN_ALLOW_XML_FILES_AS_PREVIEW')) {
13666 $mime_preview[] = 'xml';
13667 }
13668
13669 //$mime_preview[]='vnd.oasis.opendocument.presentation';
13670 //$mime_preview[]='archive';
13671 $num_mime = array_search(dol_mimetype($file, '', 1), $mime_preview);
13672 if ($num_mime !== false) {
13673 return 1;
13674 }
13675
13676 // By default, not allowed for preview
13677 return 0;
13678}
13679
13680
13690function dol_mimetype($file, $default = 'application/octet-stream', $mode = 0)
13691{
13692 $mime = $default;
13693 $imgmime = 'other.png';
13694 $famime = 'file-o';
13695 $srclang = '';
13696
13697 $tmpfile = preg_replace('/\.noexe$/', '', $file);
13698
13699 // Plain text files
13700 if (preg_match('/\.txt$/i', $tmpfile)) {
13701 $mime = 'text/plain';
13702 $imgmime = 'text.png';
13703 $famime = 'file-alt';
13704 } elseif (preg_match('/\.rtx$/i', $tmpfile)) {
13705 $mime = 'text/richtext';
13706 $imgmime = 'text.png';
13707 $famime = 'file-alt';
13708 } elseif (preg_match('/\.csv$/i', $tmpfile)) {
13709 $mime = 'text/csv';
13710 $imgmime = 'text.png';
13711 $famime = 'file-csv';
13712 } elseif (preg_match('/\.tsv$/i', $tmpfile)) {
13713 $mime = 'text/tab-separated-values';
13714 $imgmime = 'text.png';
13715 $famime = 'file-alt';
13716 } elseif (preg_match('/\.(cf|conf|log)$/i', $tmpfile)) {
13717 $mime = 'text/plain';
13718 $imgmime = 'text.png';
13719 $famime = 'file-alt';
13720 } elseif (preg_match('/\.ini$/i', $tmpfile)) {
13721 $mime = 'text/plain';
13722 $imgmime = 'text.png';
13723 $srclang = 'ini';
13724 $famime = 'file-alt';
13725 } elseif (preg_match('/\.md$/i', $tmpfile)) {
13726 $mime = 'text/plain';
13727 $imgmime = 'text.png';
13728 $srclang = 'md';
13729 $famime = 'file-alt';
13730 } elseif (preg_match('/\.css$/i', $tmpfile)) {
13731 $mime = 'text/css';
13732 $imgmime = 'css.png';
13733 $srclang = 'css';
13734 $famime = 'file-alt';
13735 } elseif (preg_match('/\.lang$/i', $tmpfile)) {
13736 $mime = 'text/plain';
13737 $imgmime = 'text.png';
13738 $srclang = 'lang';
13739 $famime = 'file-alt';
13740 } elseif (preg_match('/\.(crt|cer|key|pub)$/i', $tmpfile)) { // Certificate files
13741 $mime = 'text/plain';
13742 $imgmime = 'text.png';
13743 $famime = 'file-alt';
13744 } elseif (preg_match('/\.(html|htm|shtml)$/i', $tmpfile)) { // XML based (HTML/XML/XAML)
13745 $mime = 'text/html';
13746 $imgmime = 'html.png';
13747 $srclang = 'html';
13748 $famime = 'file-alt';
13749 } elseif (preg_match('/\.(xml|xhtml)$/i', $tmpfile)) {
13750 $mime = 'text/xml';
13751 $imgmime = 'other.png';
13752 $srclang = 'xml';
13753 $famime = 'file-alt';
13754 } elseif (preg_match('/\.xaml$/i', $tmpfile)) {
13755 $mime = 'text/xml';
13756 $imgmime = 'other.png';
13757 $srclang = 'xaml';
13758 $famime = 'file-alt';
13759 } elseif (preg_match('/\.bas$/i', $tmpfile)) { // Languages
13760 $mime = 'text/plain';
13761 $imgmime = 'text.png';
13762 $srclang = 'bas';
13763 $famime = 'file-code';
13764 } elseif (preg_match('/\.(c)$/i', $tmpfile)) {
13765 $mime = 'text/plain';
13766 $imgmime = 'text.png';
13767 $srclang = 'c';
13768 $famime = 'file-code';
13769 } elseif (preg_match('/\.(cpp)$/i', $tmpfile)) {
13770 $mime = 'text/plain';
13771 $imgmime = 'text.png';
13772 $srclang = 'cpp';
13773 $famime = 'file-code';
13774 } elseif (preg_match('/\.cs$/i', $tmpfile)) {
13775 $mime = 'text/plain';
13776 $imgmime = 'text.png';
13777 $srclang = 'cs';
13778 $famime = 'file-code';
13779 } elseif (preg_match('/\.(h)$/i', $tmpfile)) {
13780 $mime = 'text/plain';
13781 $imgmime = 'text.png';
13782 $srclang = 'h';
13783 $famime = 'file-code';
13784 } elseif (preg_match('/\.(java|jsp)$/i', $tmpfile)) {
13785 $mime = 'text/plain';
13786 $imgmime = 'text.png';
13787 $srclang = 'java';
13788 $famime = 'file-code';
13789 } elseif (preg_match('/\.php([0-9]{1})?$/i', $tmpfile)) {
13790 $mime = 'text/plain';
13791 $imgmime = 'php.png';
13792 $srclang = 'php';
13793 $famime = 'file-code';
13794 } elseif (preg_match('/\.phtml$/i', $tmpfile)) {
13795 $mime = 'text/plain';
13796 $imgmime = 'php.png';
13797 $srclang = 'php';
13798 $famime = 'file-code';
13799 } elseif (preg_match('/\.(pl|pm)$/i', $tmpfile)) {
13800 $mime = 'text/plain';
13801 $imgmime = 'pl.png';
13802 $srclang = 'perl';
13803 $famime = 'file-code';
13804 } elseif (preg_match('/\.sql$/i', $tmpfile)) {
13805 $mime = 'text/plain';
13806 $imgmime = 'text.png';
13807 $srclang = 'sql';
13808 $famime = 'file-code';
13809 } elseif (preg_match('/\.js$/i', $tmpfile)) {
13810 $mime = 'text/x-javascript';
13811 $imgmime = 'jscript.png';
13812 $srclang = 'js';
13813 $famime = 'file-code';
13814 } elseif (preg_match('/\.odp$/i', $tmpfile)) { // Open office
13815 $mime = 'application/vnd.oasis.opendocument.presentation';
13816 $imgmime = 'ooffice.png';
13817 $famime = 'file-powerpoint';
13818 } elseif (preg_match('/\.ods$/i', $tmpfile)) {
13819 $mime = 'application/vnd.oasis.opendocument.spreadsheet';
13820 $imgmime = 'ooffice.png';
13821 $famime = 'file-excel';
13822 } elseif (preg_match('/\.odt$/i', $tmpfile)) {
13823 $mime = 'application/vnd.oasis.opendocument.text';
13824 $imgmime = 'ooffice.png';
13825 $famime = 'file-word';
13826 } elseif (preg_match('/\.mdb$/i', $tmpfile)) { // MS Office
13827 $mime = 'application/msaccess';
13828 $imgmime = 'mdb.png';
13829 $famime = 'file';
13830 } elseif (preg_match('/\.doc[xm]?$/i', $tmpfile)) {
13831 $mime = 'application/msword';
13832 $imgmime = 'doc.png';
13833 $famime = 'file-word';
13834 } elseif (preg_match('/\.dot[xm]?$/i', $tmpfile)) {
13835 $mime = 'application/msword';
13836 $imgmime = 'doc.png';
13837 $famime = 'file-word';
13838 } elseif (preg_match('/\.xlt(x)?$/i', $tmpfile)) {
13839 $mime = 'application/vnd.ms-excel';
13840 $imgmime = 'xls.png';
13841 $famime = 'file-excel';
13842 } elseif (preg_match('/\.xla(m)?$/i', $tmpfile)) {
13843 $mime = 'application/vnd.ms-excel';
13844 $imgmime = 'xls.png';
13845 $famime = 'file-excel';
13846 } elseif (preg_match('/\.xls$/i', $tmpfile)) {
13847 $mime = 'application/vnd.ms-excel';
13848 $imgmime = 'xls.png';
13849 $famime = 'file-excel';
13850 } elseif (preg_match('/\.xls[bmx]$/i', $tmpfile)) {
13851 $mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
13852 $imgmime = 'xls.png';
13853 $famime = 'file-excel';
13854 } elseif (preg_match('/\.pps[mx]?$/i', $tmpfile)) {
13855 $mime = 'application/vnd.ms-powerpoint';
13856 $imgmime = 'ppt.png';
13857 $famime = 'file-powerpoint';
13858 } elseif (preg_match('/\.ppt[mx]?$/i', $tmpfile)) {
13859 $mime = 'application/x-mspowerpoint';
13860 $imgmime = 'ppt.png';
13861 $famime = 'file-powerpoint';
13862 } elseif (preg_match('/\.pdf$/i', $tmpfile)) { // Other
13863 $mime = 'application/pdf';
13864 $imgmime = 'pdf.png';
13865 $famime = 'file-pdf';
13866 } elseif (preg_match('/\.bat$/i', $tmpfile)) { // Scripts
13867 $mime = 'text/x-bat';
13868 $imgmime = 'script.png';
13869 $srclang = 'dos';
13870 $famime = 'file-code';
13871 } elseif (preg_match('/\.sh$/i', $tmpfile)) {
13872 $mime = 'text/x-sh';
13873 $imgmime = 'script.png';
13874 $srclang = 'bash';
13875 $famime = 'file-code';
13876 } elseif (preg_match('/\.ksh$/i', $tmpfile)) {
13877 $mime = 'text/x-ksh';
13878 $imgmime = 'script.png';
13879 $srclang = 'bash';
13880 $famime = 'file-code';
13881 } elseif (preg_match('/\.bash$/i', $tmpfile)) {
13882 $mime = 'text/x-bash';
13883 $imgmime = 'script.png';
13884 $srclang = 'bash';
13885 $famime = 'file-code';
13886 } elseif (preg_match('/\.ico$/i', $tmpfile)) { // Images
13887 $mime = 'image/x-icon';
13888 $imgmime = 'image.png';
13889 $famime = 'file-image';
13890 } elseif (preg_match('/\.(jpg|jpeg)$/i', $tmpfile)) {
13891 $mime = 'image/jpeg';
13892 $imgmime = 'image.png';
13893 $famime = 'file-image';
13894 } elseif (preg_match('/\.png$/i', $tmpfile)) {
13895 $mime = 'image/png';
13896 $imgmime = 'image.png';
13897 $famime = 'file-image';
13898 } elseif (preg_match('/\.gif$/i', $tmpfile)) {
13899 $mime = 'image/gif';
13900 $imgmime = 'image.png';
13901 $famime = 'file-image';
13902 } elseif (preg_match('/\.bmp$/i', $tmpfile)) {
13903 $mime = 'image/bmp';
13904 $imgmime = 'image.png';
13905 $famime = 'file-image';
13906 } elseif (preg_match('/\.(tif|tiff)$/i', $tmpfile)) {
13907 $mime = 'image/tiff';
13908 $imgmime = 'image.png';
13909 $famime = 'file-image';
13910 } elseif (preg_match('/\.svg$/i', $tmpfile)) {
13911 $mime = 'image/svg+xml';
13912 $imgmime = 'image.png';
13913 $famime = 'file-image';
13914 } elseif (preg_match('/\.webp$/i', $tmpfile)) {
13915 $mime = 'image/webp';
13916 $imgmime = 'image.png';
13917 $famime = 'file-image';
13918 } elseif (preg_match('/\.vcs$/i', $tmpfile)) { // Calendar
13919 $mime = 'text/calendar';
13920 $imgmime = 'other.png';
13921 $famime = 'file-alt';
13922 } elseif (preg_match('/\.ics$/i', $tmpfile)) {
13923 $mime = 'text/calendar';
13924 $imgmime = 'other.png';
13925 $famime = 'file-alt';
13926 } elseif (preg_match('/\.torrent$/i', $tmpfile)) { // Other
13927 $mime = 'application/x-bittorrent';
13928 $imgmime = 'other.png';
13929 $famime = 'file-o';
13930 } elseif (preg_match('/\.(mp3|ogg|au|wav|wma|mid)$/i', $tmpfile)) { // Audio
13931 $mime = 'audio';
13932 $imgmime = 'audio.png';
13933 $famime = 'file-audio';
13934 } elseif (preg_match('/\.mp4$/i', $tmpfile)) { // Video
13935 $mime = 'video/mp4';
13936 $imgmime = 'video.png';
13937 $famime = 'file-video';
13938 } elseif (preg_match('/\.ogv$/i', $tmpfile)) {
13939 $mime = 'video/ogg';
13940 $imgmime = 'video.png';
13941 $famime = 'file-video';
13942 } elseif (preg_match('/\.webm$/i', $tmpfile)) {
13943 $mime = 'video/webm';
13944 $imgmime = 'video.png';
13945 $famime = 'file-video';
13946 } elseif (preg_match('/\.avi$/i', $tmpfile)) {
13947 $mime = 'video/x-msvideo';
13948 $imgmime = 'video.png';
13949 $famime = 'file-video';
13950 } elseif (preg_match('/\.divx$/i', $tmpfile)) {
13951 $mime = 'video/divx';
13952 $imgmime = 'video.png';
13953 $famime = 'file-video';
13954 } elseif (preg_match('/\.xvid$/i', $tmpfile)) {
13955 $mime = 'video/xvid';
13956 $imgmime = 'video.png';
13957 $famime = 'file-video';
13958 } elseif (preg_match('/\.(wmv|mpg|mpeg)$/i', $tmpfile)) {
13959 $mime = 'video';
13960 $imgmime = 'video.png';
13961 $famime = 'file-video';
13962 } elseif (preg_match('/\.(zip|rar|gz|tgz|xz|z|cab|bz2|7z|tar|lzh|zst)$/i', $tmpfile)) { // Archive
13963 // application/xxx where zzz is zip, ...
13964 $mime = 'archive';
13965 $imgmime = 'archive.png';
13966 $famime = 'file-archive';
13967 } elseif (preg_match('/\.(exe|com)$/i', $tmpfile)) { // Exe
13968 $mime = 'application/octet-stream';
13969 $imgmime = 'other.png';
13970 $famime = 'file-o';
13971 } elseif (preg_match('/\.(dll|lib|o|so|a)$/i', $tmpfile)) { // Lib
13972 $mime = 'library';
13973 $imgmime = 'library.png';
13974 $famime = 'file-o';
13975 } elseif (preg_match('/\.err$/i', $tmpfile)) { // phpcs:ignore
13976 $mime = 'error';
13977 $imgmime = 'error.png';
13978 $famime = 'file-alt';
13979 }
13980
13981 if ($famime == 'file-o') {
13982 // file-o seems to not work in fontawesome 5
13983 $famime = 'file';
13984 }
13985
13986 // Return mimetype string
13987 switch ((int) $mode) {
13988 case 1:
13989 $tmp = explode('/', $mime);
13990 return (!empty($tmp[1]) ? $tmp[1] : $tmp[0]);
13991 case 2:
13992 return $imgmime;
13993 case 3:
13994 return $srclang;
13995 case 4:
13996 return $famime;
13997 }
13998 return $mime;
13999}
14000
14012function getDictionaryValue($tablename, $field, $id, $checkentity = false, $rowidfield = 'rowid')
14013{
14014 global $conf, $db;
14015
14016 $tablename = preg_replace('/^' . preg_quote(MAIN_DB_PREFIX, '/') . '/', '', $tablename); // Clean name of table for backward compatibility.
14017
14018 $dictvalues = (isset($conf->cache['dictvalues_' . $tablename]) ? $conf->cache['dictvalues_' . $tablename] : null);
14019
14020 if (is_null($dictvalues)) {
14021 $dictvalues = array();
14022
14023 $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
14024 if ($checkentity) {
14025 $sql .= ' AND entity IN (0,' . getEntity($tablename) . ')';
14026 }
14027
14028 $resql = $db->query($sql);
14029 if ($resql) {
14030 while ($obj = $db->fetch_object($resql)) {
14031 $dictvalues[$obj->$rowidfield] = $obj; // $obj is stdClass
14032 }
14033 } else {
14034 dol_print_error($db);
14035 }
14036
14037 $conf->cache['dictvalues_' . $tablename] = $dictvalues;
14038 }
14039
14040 if (!empty($dictvalues[$id])) {
14041 // Found
14042 $tmp = $dictvalues[$id];
14043 return (property_exists($tmp, $field) ? $tmp->$field : '');
14044 } else {
14045 // Not found
14046 return '';
14047 }
14048}
14049
14056function colorIsLight($stringcolor)
14057{
14058 $stringcolor = str_replace('#', '', $stringcolor);
14059 $res = -1;
14060 if (!empty($stringcolor)) {
14061 $res = 0;
14062 $tmp = explode(',', $stringcolor);
14063 if (count($tmp) > 1) { // This is a comma RGB ('255','255','255')
14064 $r = $tmp[0];
14065 $g = $tmp[1];
14066 $b = $tmp[2];
14067 } else {
14068 $hexr = $stringcolor[0] . $stringcolor[1];
14069 $hexg = $stringcolor[2] . $stringcolor[3];
14070 $hexb = $stringcolor[4] . $stringcolor[5];
14071 $r = hexdec($hexr);
14072 $g = hexdec($hexg);
14073 $b = hexdec($hexb);
14074 }
14075 $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm
14076 if ($bright > 0.6) {
14077 $res = 1;
14078 }
14079 }
14080 return $res;
14081}
14082
14091function isVisibleToUserType($type_user, &$menuentry, &$listofmodulesforexternal)
14092{
14093 //print 'type_user='.$type_user.' module='.$menuentry['module'].' enabled='.$menuentry['enabled'].' perms='.$menuentry['perms'];
14094 //print 'ok='.in_array($menuentry['module'], $listofmodulesforexternal);
14095 if (empty($menuentry['enabled'])) {
14096 return 0; // Entry disabled by condition
14097 }
14098 if ($type_user && array_key_exists('module', $menuentry) && $menuentry['module']) {
14099 $tmploops = explode('|', $menuentry['module']);
14100 $found = 0;
14101 foreach ($tmploops as $tmploop) {
14102 if (in_array($tmploop, $listofmodulesforexternal)) {
14103 $found++;
14104 break;
14105 }
14106 }
14107 if (!$found) {
14108 return 0; // Entry is for menus all excluded to external users
14109 }
14110 }
14111 if (!$menuentry['perms'] && $type_user) {
14112 return 0; // No permissions and user is external
14113 }
14114 if (!$menuentry['perms'] && getDolGlobalString('MAIN_MENU_HIDE_UNAUTHORIZED')) {
14115 return 0; // No permissions and option to hide when not allowed, even for internal user, is on
14116 }
14117 if (!$menuentry['perms']) {
14118 return 2; // No permissions and user is external
14119 }
14120 return 1;
14121}
14122
14130function roundUpToNextMultiple($n, $x = 5)
14131{
14132 $result = (ceil($n) % $x === 0) ? ceil($n) : (round(($n + $x / 2) / $x) * $x);
14133 return (int) $result;
14134}
14135
14147function dolGetBadge($label, $html = '', $type = 'primary', $mode = '', $url = '', $params = array())
14148{
14149 $csstouse = 'badge';
14150 $csstouse .= (!empty($mode) ? ' badge-' . $mode : '');
14151 $csstouse .= (!empty($type) ? ' badge-' . $type : '');
14152 $csstouse .= (empty($params['css']) ? '' : ' ' . $params['css']);
14153
14154 $attr = array(
14155 'class' => $csstouse
14156 );
14157
14158 if (empty($html)) {
14159 $html = $label;
14160 }
14161
14162 if (!empty($url)) {
14163 $attr['href'] = $url;
14164 }
14165
14166 if ($mode === 'dot') {
14167 $attr['class'] .= ' classfortooltip';
14168 $attr['title'] = $html;
14169 $attr['aria-label'] = $label;
14170 $html = '';
14171 }
14172
14173 // Override attr
14174 if (!empty($params['attr']) && is_array($params['attr'])) {
14175 foreach ($params['attr'] as $key => $value) {
14176 if ($key == 'class') {
14177 $attr['class'] .= ' ' . $value;
14178 } elseif ($key == 'classOverride') {
14179 $attr['class'] = $value;
14180 } else {
14181 $attr[$key] = $value;
14182 }
14183 }
14184 }
14185
14186 // TODO: add hook
14187
14188 // escape all attribute
14189 $attr = array_map('dolPrintHTMLForAttribute', $attr);
14190
14191 $TCompiledAttr = array();
14192 foreach ($attr as $key => $value) {
14193 $TCompiledAttr[] = $key . '="' . $value . '"';
14194 }
14195
14196 $compiledAttributes = !empty($TCompiledAttr) ? implode(' ', $TCompiledAttr) : '';
14197
14198 $tag = !empty($url) ? 'a' : 'span';
14199
14200 return '<' . $tag . ' ' . $compiledAttributes . '>' . $html . '</' . $tag . '>';
14201}
14202
14203
14216function dolGetStatus($statusLabel = '', $statusLabelShort = '', $html = '', $statusType = 'status0', $displayMode = 0, $url = '', $params = array())
14217{
14218 global $conf;
14219
14220 $return = '';
14221 $dolGetBadgeParams = array();
14222
14223 if (!empty($params['badgeParams'])) {
14224 $dolGetBadgeParams = $params['badgeParams'];
14225 }
14226
14227 // TODO : add a hook
14228 if ($displayMode == 0) {
14229 $return = !empty($html) ? $html : (empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort));
14230 } elseif ($displayMode == 1) {
14231 $return = !empty($html) ? $html : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
14232 } elseif (getDolGlobalString('MAIN_STATUS_USES_IMAGES')) {
14233 // Use status with images (for backward compatibility)
14234 $return = '';
14235 $htmlLabel = (in_array($displayMode, array(1, 2, 5)) ? '<span class="hideonsmartphone">' : '') . (!empty($html) ? $html : $statusLabel) . (in_array($displayMode, array(1, 2, 5)) ? '</span>' : '');
14236 $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>' : '');
14237
14238 // For small screen, we always use the short label instead of long label.
14239 if (!empty($conf->dol_optimize_smallscreen)) {
14240 if ($displayMode == 0) {
14241 $displayMode = 1;
14242 } elseif ($displayMode == 4) {
14243 $displayMode = 2;
14244 } elseif ($displayMode == 6) {
14245 $displayMode = 5;
14246 }
14247 }
14248
14249 // For backward compatibility. Image's filename are still in French, so we use this array to convert
14250 $statusImg = array(
14251 'status0' => 'statut0',
14252 'status1' => 'statut1',
14253 'status2' => 'statut2',
14254 'status3' => 'statut3',
14255 'status4' => 'statut4',
14256 'status5' => 'statut5',
14257 'status6' => 'statut6',
14258 'status7' => 'statut7',
14259 'status8' => 'statut8',
14260 'status9' => 'statut9'
14261 );
14262
14263 if (!empty($statusImg[$statusType])) {
14264 $htmlImg = img_picto($statusLabel, $statusImg[$statusType]);
14265 } else {
14266 $htmlImg = img_picto($statusLabel, $statusType);
14267 }
14268
14269 if ($displayMode === 2) {
14270 $return = $htmlImg . ' ' . $htmlLabelShort;
14271 } elseif ($displayMode === 3) {
14272 $return = $htmlImg;
14273 } elseif ($displayMode === 4) {
14274 $return = $htmlImg . ' ' . $htmlLabel;
14275 } elseif ($displayMode === 5) {
14276 $return = $htmlLabelShort . ' ' . $htmlImg;
14277 } else { // $displayMode >= 6
14278 $return = $htmlLabel . ' ' . $htmlImg;
14279 }
14280 } elseif (!getDolGlobalString('MAIN_STATUS_USES_IMAGES') && !empty($displayMode)) {
14281 // Use new badge
14282 $statusLabelShort = (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
14283
14284 $dolGetBadgeParams['attr']['class'] = 'badge-status';
14285 if (empty($dolGetBadgeParams['attr']['title'])) {
14286 $dolGetBadgeParams['attr']['title'] = empty($params['tooltip']) ? $statusLabel : ($params['tooltip'] != 'no' ? $params['tooltip'] : '');
14287 } else { // If a title was forced from $params['badgeParams']['attr']['title'], we set the class to get it as a tooltip.
14288 $dolGetBadgeParams['attr']['class'] .= ' classfortooltip';
14289 // And if we use tooltip, we can output title in HTML @phan-suppress-next-line PhanTypeInvalidDimOffset
14290 $dolGetBadgeParams['attr']['title'] = dol_htmlentitiesbr((string) $dolGetBadgeParams['attr']['title'], 1);
14291 }
14292
14293 if ($displayMode == 3) {
14294 $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), '', $statusType, 'dot', $url, $dolGetBadgeParams);
14295 } elseif ($displayMode === 5) {
14296 $return = dolGetBadge($statusLabelShort, $html, $statusType, '', $url, $dolGetBadgeParams);
14297 } else {
14298 $return = dolGetBadge(((empty($conf->dol_optimize_smallscreen) && $displayMode != 2) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), $html, $statusType, '', $url, $dolGetBadgeParams);
14299 }
14300 }
14301
14302 return $return;
14303}
14304
14305
14341function dolGetButtonAction($label, $text = '', $actionType = 'default', $url = '', $id = '', $userRight = 1, $params = array())
14342{
14343 global $hookmanager, $action, $object, $langs;
14344
14345 // If $url is an array, we must build a dropdown button or recursively iterate over each value
14346 if (is_array($url)) {
14347 // Loop on $url array to remove entries of disabled modules
14348 foreach ($url as $key => $subbutton) {
14349 if (isset($subbutton['enabled']) && empty($subbutton['enabled'])) {
14350 unset($url[$key]);
14351 }
14352 }
14353
14354 $out = '';
14355
14356 if (array_key_exists('areDropdownButtons', $params) && $params["areDropdownButtons"] === false) { // @phan-suppress-current-line PhanTypeInvalidDimOffset
14357 foreach ($url as $button) {
14358 if (!empty($button['lang'])) {
14359 $langs->load($button['lang']);
14360 }
14361 $label = $langs->trans($button['label']);
14362 $text = $button['text'] ?? '';
14363 $actionType = $button['actionType'] ?? '';
14364 $tmpUrl = DOL_URL_ROOT . $button['url'] . (empty($params['backtopage']) ? '' : '&amp;backtopage=' . urlencode($params['backtopage']));
14365 $id = $button['id'] ?? '';
14366 $userRight = $button['perm'] ?? 1;
14367 $button['params'] = $button['params'] ?? []; // @phan-suppress-current-line PhanPluginDuplicateExpressionAssignmentOperation
14368
14369 $out .= dolGetButtonAction($label, $text, $actionType, $tmpUrl, $id, $userRight, $button['params']);
14370 }
14371 return $out;
14372 }
14373
14374 if (count($url) > 1) {
14375 $out .= '<div class="dropdown inline-block dropdown-holder">';
14376 $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>';
14377 $out .= '<div class="dropdown-content">';
14378 foreach ($url as $subbutton) {
14379 if (!empty($subbutton['lang'])) {
14380 $langs->load($subbutton['lang']);
14381 }
14382
14383 if (!empty($subbutton['urlraw'])) {
14384 $tmpurl = $subbutton['urlraw']; // Use raw url, no url completion, use only what developer send
14385 } else {
14386 $tmpurl = !empty($subbutton['urlroot']) ? $subbutton['urlroot'] : $subbutton['url'];
14387 $tmpurl = dolCompletUrlForDropdownButton($tmpurl, $params, empty($subbutton['urlroot']));
14388 }
14389
14390 $subbuttonparam = array();
14391 if (!empty($subbutton['attr'])) {
14392 $subbuttonparam['attr'] = $subbutton['attr'];
14393 }
14394 $subbuttonparam['isDropDown'] = (empty($params['isDropDown']) ? ($subbutton['isDropDown'] ?? false) : $params['isDropDown']);
14395
14396 $out .= dolGetButtonAction('', $langs->trans($subbutton['label']), 'default', $tmpurl, $subbutton['id'] ?? '', $subbutton['perm'], $subbuttonparam);
14397 }
14398 $out .= "</div>";
14399 $out .= "</div>";
14400 } else {
14401 foreach ($url as $subbutton) { // Should loop on 1 record only
14402 if (!empty($subbutton['lang'])) {
14403 $langs->load($subbutton['lang']);
14404 }
14405
14406 if (!empty($subbutton['urlraw'])) {
14407 $tmpurl = $subbutton['urlraw']; // Use raw url, no url completion, use only what developer send
14408 } else {
14409 $tmpurl = !empty($subbutton['urlroot']) ? $subbutton['urlroot'] : $subbutton['url'];
14410 $tmpurl = dolCompletUrlForDropdownButton($tmpurl, $params, empty($subbutton['urlroot']));
14411 }
14412
14413 $label = $langs->trans($subbutton['label']);
14414 $text = $subbutton['text'] ?? '';
14415 if (empty($text)) {
14416 $text = $label;
14417 $label = '';
14418 }
14419
14420 $out .= dolGetButtonAction($label, $text, 'default', $tmpurl, '', $subbutton['perm'], $params);
14421 }
14422 }
14423
14424 return $out;
14425 }
14426
14427 // Here, $url is a simple link
14428 if (!empty($params['isDropdown']) || !empty($params['isDropDown'])) { // Use the dropdown-item style (not for action button)
14429 $class = "dropdown-item";
14430 } else {
14431 $class = 'butAction';
14432 if ($actionType == 'edit') {
14433 $class = 'butAction butActionEdit';
14434 } elseif ($actionType == 'email') {
14435 $class = 'butAction butActionEmail';
14436 } elseif ($actionType == 'clone') {
14437 $class = 'butAction butActionClone';
14438 } elseif ($actionType == 'danger' || $actionType == 'delete') {
14439 $class = 'butAction butActionDelete';
14440 if (!empty($url) && strpos($url, 'token=') === false) {
14441 $url .= '&token=' . newToken();
14442 }
14443 }
14444 }
14445 $attr = array(
14446 'class' => $class,
14447 'href' => empty($url) ? '' : $url,
14448 'title' => $label
14449 );
14450
14451 if (empty($text)) {
14452 $text = $label;
14453 $attr['title'] = ''; // if html not set, using label on title is redundant
14454 } else {
14455 $attr['title'] = $label;
14456 $attr['aria-label'] = $label;
14457 }
14458
14459 if (empty($userRight) || $userRight < 0) {
14460 $attr['class'] = 'butActionRefused';
14461 $attr['href'] = '';
14462 $attr['title'] = (($label && $text && $label != $text) ? $label : '');
14463 $attr['title'] = ($attr['title'] ? $attr['title'] . (empty($userRight) ? '<br>' : '') : '');
14464 $attr['title'] .= ((empty($userRight) && empty($label)) ? $langs->trans('NotEnoughPermissions') : '');
14465 }
14466
14467 if (!empty($id)) {
14468 $attr['id'] = $id;
14469 }
14470
14471 // Override attr
14472 if (!empty($params['attr']) && is_array($params['attr'])) {
14473 foreach ($params['attr'] as $key => $value) {
14474 if ($key == 'class') {
14475 $attr['class'] .= ' ' . $value;
14476 } elseif ($key == 'classOverride') {
14477 $attr['class'] = $value;
14478 } else {
14479 $attr[$key] = $value;
14480 }
14481 }
14482 }
14483
14484 // automatic add tooltip when title is detected
14485 if (!empty($attr['title']) && !empty($attr['class']) && strpos($attr['class'], 'classfortooltip') === false) {
14486 $attr['class'] .= ' classfortooltip';
14487 }
14488
14489 // Js Confirm button
14490 if ($userRight && !empty($params['confirm'])) {
14491 if (!is_array($params['confirm'])) {
14492 $params['confirm'] = array();
14493 }
14494
14495 if (empty($params['confirm']['url'])) {
14496 $params['confirm']['url'] = $url . (strpos($url, '?') > 0 ? '&' : '?') . 'confirm=yes';
14497 }
14498
14499 // for js disabled compatibility set $url as call to confirm action and $params['confirm']['url'] to confirmed action
14500 $attr['data-confirm-url'] = $params['confirm']['url'];
14501 $attr['data-confirm-title'] = !empty($params['confirm']['title']) ? $params['confirm']['title'] : $langs->trans('ConfirmBtnCommonTitle', $label);
14502 $attr['data-confirm-content'] = !empty($params['confirm']['content']) ? $params['confirm']['content'] : $langs->trans('ConfirmBtnCommonContent', $label);
14503 $attr['data-confirm-content'] = preg_replace("/\r|\n/", "", $attr['data-confirm-content']);
14504 $attr['data-confirm-action-btn-label'] = !empty($params['confirm']['action-btn-label']) ? $params['confirm']['action-btn-label'] : $langs->trans('Confirm');
14505 $attr['data-confirm-cancel-btn-label'] = !empty($params['confirm']['cancel-btn-label']) ? $params['confirm']['cancel-btn-label'] : $langs->trans('CloseDialog');
14506 $attr['data-confirm-modal'] = !empty($params['confirm']['modal']) ? $params['confirm']['modal'] : true;
14507
14508 $attr['class'] .= ' butActionConfirm';
14509 }
14510
14511 if (isset($attr['href']) && empty($attr['href'])) {
14512 unset($attr['href']);
14513 }
14514
14515 // TODO replace $TCompiledAttr generation by commonHtmlAttributeBuilder given below
14516 $TCompiledAttr = array();
14517 foreach ($attr as $key => $value) {
14518 if (!empty($params['use_unsecured_unescapedattr']) && is_array($params['use_unsecured_unescapedattr']) && in_array($key, $params['use_unsecured_unescapedattr'])) {
14519 // Not recommended
14520 $value = dol_htmlentities($value, ENT_QUOTES | ENT_SUBSTITUTE);
14521 } elseif (in_array($key, ['href', 'data-confirm-url'])) {
14522 $value = dolPrintHTMLForAttributeUrl($value);
14523 } else {
14524 $value = dolPrintHTMLForAttribute($value);
14525 }
14526
14527 $TCompiledAttr[] = $key . '="' . $value . '"'; // $value has been escaped by the dolPrintHTMLForAttribute... just before
14528 }
14529 // TODO replace $TCompiledAttr generation by uncomment line below and remove old code
14530 // $TCompiledAttr = commonHtmlAttributeBuilder($attr,$params['use_unsecured_unescapedattr'] ?? []);
14531 $compiledAttributes = empty($TCompiledAttr) ? '' : implode(' ', $TCompiledAttr);
14532
14533 $tag = !empty($attr['href']) ? 'a' : 'span';
14534
14535 $parameters = array(
14536 'TCompiledAttr' => $TCompiledAttr, // array
14537 'compiledAttributes' => $compiledAttributes, // string
14538 'attr' => $attr,
14539 'tag' => $tag,
14540 'label' => $label,
14541 'html' => $text,
14542 'actionType' => $actionType,
14543 'url' => $url,
14544 'id' => $id,
14545 'userRight' => $userRight,
14546 'params' => $params
14547 );
14548
14549 $reshook = $hookmanager->executeHooks('dolGetButtonAction', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
14550 if ($reshook < 0) {
14551 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
14552 }
14553
14554 if (empty($reshook)) {
14555 if (dol_textishtml($text)) { // If content already HTML encoded
14556 return '<' . $tag . ' ' . $compiledAttributes . '><span class="textbutton">' . $text . '</span></' . $tag . '>';
14557 } else {
14558 return '<' . $tag . ' ' . $compiledAttributes . '><span class="textbutton">' . dol_escape_htmltag($text) . '</span></' . $tag . '>';
14559 }
14560 } else {
14561 return $hookmanager->resPrint;
14562 }
14563}
14564
14600function commonHtmlAttributeBuilder($attr, array $unescapedAttr = [])
14601{
14602 $TCompiledAttr = array();
14603 if (empty($attr)) {
14604 return [];
14605 }
14606
14607 foreach ($attr as $key => $value) {
14608 // special boolean attributes case
14609 if (in_array($key, getListOfHtmlBooleanAttributes())) {
14610 if ($value) {
14611 $TCompiledAttr[$key] = $key;
14612 }
14613 continue;
14614 }
14615
14616 if (!empty($unescapedAttr) && in_array($key, $unescapedAttr)) {
14617 // Not recommended
14618 $value = dol_htmlentities((string) $value, ENT_QUOTES | ENT_SUBSTITUTE);
14619 } elseif ($key == 'href') {
14620 $value = dolPrintHTMLForAttributeUrl((string) $value);
14621 } else {
14622 $value = dolPrintHTMLForAttribute((string) $value);
14623 }
14624
14625 $TCompiledAttr[$key] = $key . '="' . $value . '"'; // $value has been escaped by the dolPrintHTMLForAttribute... just before
14626 }
14627
14628 return $TCompiledAttr;
14629}
14630
14645function getListOfHtmlBooleanAttributes(): array
14646{
14647 return [
14648 // Input / Form
14649 'checked',
14650 'disabled',
14651 'readonly',
14652 'required',
14653 'autofocus',
14654 'multiple',
14655
14656 // Option
14657 'selected',
14658
14659 // Form / General
14660 'novalidate',
14661 'formnovalidate',
14662
14663 // Media
14664 'autoplay',
14665 'controls',
14666 'loop',
14667 'muted',
14668 'playsinline',
14669
14670 // Other elements
14671 'hidden',
14672 'open',
14673 'ismap',
14674 'reversed',
14675 'allowfullscreen',
14676 'itemscope',
14677 'nomodule',
14678 'defer',
14679 'async',
14680 'default',
14681 'inert',
14682 ];
14683}
14684
14685
14694function dolCompletUrlForDropdownButton(string $url, array $params, bool $addDolUrlRoot = true)
14695{
14696 if (empty($url)) {
14697 return '';
14698 }
14699
14700 $parsedUrl = parse_url($url);
14701 if ((isset($parsedUrl['scheme']) && in_array($parsedUrl['scheme'], ['javascript', 'mailto', 'tel'])) || strpos($url, '#') === 0) {
14702 return $url;
14703 }
14704
14705 if (!empty($parsedUrl['query'])) {
14706 // Use parse_str() function to parse the string passed via URL
14707 parse_str($parsedUrl['query'], $urlQuery);
14708 if (!isset($urlQuery['backtopage']) && isset($params['backtopage'])) {
14709 $url .= '&amp;backtopage=' . urlencode($params['backtopage']);
14710 }
14711 }
14712
14713 if (!isset($parsedUrl['scheme']) && $addDolUrlRoot) {
14714 $url = DOL_URL_ROOT . $url;
14715 }
14716
14717 return $url;
14718}
14719
14720
14727function dolGetButtonTitleSeparator($moreClass = "")
14728{
14729 return '<span class="button-title-separator ' . $moreClass . '" ></span>';
14730}
14731
14738function getFieldErrorIcon($fieldValidationErrorMsg)
14739{
14740 $out = '';
14741 if (!empty($fieldValidationErrorMsg)) {
14742 $out .= '<span class="field-error-icon classfortooltip" title="' . dol_escape_htmltag($fieldValidationErrorMsg, 1) . '" role="alert" >'; // role alert is used for accessibility
14743 $out .= '<span class="fa fa-exclamation-circle" aria-hidden="true" ></span>'; // For accessibility icon is separated and aria-hidden
14744 $out .= '</span>';
14745 }
14746
14747 return $out;
14748}
14749
14762function dolGetButtonTitle($label, $helpText = '', $iconClass = 'fa fa-file', $url = '', $id = '', $status = 1, $params = array())
14763{
14764 global $langs, $user;
14765
14766 // Actually this conf is used in css too for external module compatibility and smooth transition to this function
14767 if (getDolGlobalString('MAIN_BUTTON_HIDE_UNAUTHORIZED') && (!$user->admin) && $status <= 0) {
14768 return '';
14769 }
14770 // Fix old picto fa-th-list to use fa-grid-vertical instead
14771 if ($iconClass == 'fa fa-th-list imgforviewmode') {
14772 $iconClass = ' fa fa-grip-horizontal imgforviewmode';
14773 }
14774
14775 $class = 'btnTitle';
14776 if (in_array($iconClass, array('fa fa-plus-circle', 'fa fa-plus-circle size15x', 'fa fa-comment-dots', 'fa fa-paper-plane'))) {
14777 $class .= ' btnTitlePlus';
14778 }
14779 $useclassfortooltip = 1;
14780
14781 if (!empty($params['morecss'])) {
14782 $class .= ' ' . $params['morecss'];
14783 }
14784
14785 $attr = array(
14786 'class' => $class,
14787 'href' => empty($url) ? '' : $url
14788 );
14789
14790 if (!empty($helpText)) {
14791 $attr['title'] = $helpText;
14792 } elseif ($label) { // empty($attr['title']) &&
14793 $attr['title'] = $label;
14794 $useclassfortooltip = 0;
14795 }
14796
14797 if ($status == 2) {
14798 $attr['class'] .= ' btnTitleSelected';
14799 } elseif ($status <= 0) {
14800 $attr['class'] .= ' refused';
14801
14802 $attr['href'] = '';
14803
14804 if ($status == -1) { // disable
14805 $attr['title'] = $langs->transnoentitiesnoconv("FeatureDisabled");
14806 } elseif ($status == 0) { // Not enough permissions
14807 $attr['title'] = $langs->transnoentitiesnoconv("NotEnoughPermissions");
14808 }
14809 }
14810
14811 if (!empty($attr['title']) && $useclassfortooltip) {
14812 $attr['class'] .= ' classfortooltip';
14813 }
14814
14815 if (!empty($id)) {
14816 $attr['id'] = $id;
14817 }
14818
14819 // Override attr
14820 if (!empty($params['attr']) && is_array($params['attr'])) {
14821 foreach ($params['attr'] as $key => $value) {
14822 if ($key == 'class') {
14823 $attr['class'] .= ' ' . $value;
14824 } elseif ($key == 'classOverride') {
14825 $attr['class'] = $value;
14826 } else {
14827 $attr[$key] = $value;
14828 }
14829 }
14830 }
14831
14832 if (isset($attr['href']) && empty($attr['href'])) {
14833 unset($attr['href']);
14834 }
14835
14836 // TODO : add a hook
14837
14838 // Generate attributes with escapement
14839 $TCompiledAttr = array();
14840 foreach ($attr as $key => $value) {
14841 $TCompiledAttr[] = $key . '="' . dol_escape_htmltag($value) . '"'; // Do not use dolPrintHTMLForAttribute() here, we must accept "javascript:string"
14842 }
14843
14844 $compiledAttributes = (empty($TCompiledAttr) ? '' : implode(' ', $TCompiledAttr));
14845
14846 $tag = (empty($attr['href']) ? 'span' : 'a');
14847
14848 $button = '<' . $tag . ' ' . $compiledAttributes . '>';
14849 $button .= '<span class="' . $iconClass . ' valignmiddle btnTitle-icon"></span>';
14850 if (!empty($params['forcenohideoftext'])) {
14851 $button .= '<span class="valignmiddle text-plus-circle btnTitle-label' . (empty($params['forcenohideoftext']) ? ' hideonsmartphone' : '') . '">' . $label . '</span>';
14852 }
14853 $button .= '</' . $tag . '>';
14854
14855 return $button;
14856}
14857
14867function getElementProperties($elementType)
14868{
14869 global $conf, $db, $hookmanager;
14870
14871 $regs = array();
14872
14873 //$element_type='facture';
14874
14875 $classfile = $classname = $classpath = $subdir = $dir_output = $dir_temp = $parent_element = '';
14876
14877 // Parse element/subelement
14878 $module = $elementType;
14879 $element = $elementType;
14880 $subelement = $elementType;
14881 $table_element = $elementType;
14882
14883 // If we ask a resource form external module (instead of default path)
14884 if (preg_match('/^([^@]+)@([^@]+)$/i', $elementType, $regs)) { // 'myobject@mymodule'
14885 $element = $subelement = $regs[1];
14886 $module = $regs[2];
14887 }
14888
14889 // If we ask a resource for a string with an element and a subelement
14890 // Example 'project_task'
14891 if (preg_match('/^([^_]+)_([^_]+)/i', $element, $regs)) { // 'myobject_mysubobject' with myobject=mymodule
14892 $module = $element = $regs[1];
14893 $subelement = $regs[2];
14894 }
14895
14896 // Object lines will use parent classpath and module ref
14897 if (substr($elementType, -3) == 'det') {
14898 $module = preg_replace('/det$/', '', $element);
14899 $subelement = preg_replace('/det$/', '', $subelement);
14900 $classpath = $module . '/class';
14901 $classfile = $module;
14902 $classname = preg_replace('/det$/', 'Line', $element);
14903 if (in_array($module, array('expedition', 'propale', 'facture', 'contrat', 'fichinter', 'supplier_order', 'commandefournisseur'))) {
14904 $classname = preg_replace('/det$/', 'Ligne', $element);
14905 }
14906 }
14907 // For compatibility and to work with non standard path
14908 if ($elementType == "action" || $elementType == "actioncomm") {
14909 $classpath = 'comm/action/class';
14910 $subelement = 'Actioncomm';
14911 $module = 'agenda';
14912 $table_element = 'actioncomm';
14913 } elseif ($elementType == 'cronjob') {
14914 $classpath = 'cron/class';
14915 $module = 'cron';
14916 $table_element = 'cron';
14917 } elseif ($elementType == 'adherent_type') {
14918 $classpath = 'adherents/class';
14919 $classfile = 'adherent_type';
14920 $module = 'adherent';
14921 $subelement = 'adherent_type';
14922 $classname = 'AdherentType';
14923 $table_element = 'adherent_type';
14924 } elseif ($elementType == 'bank_account') {
14925 $classpath = 'compta/bank/class';
14926 $module = 'bank'; // We need $conf->bank->dir_output and not $conf->banque->dir_output
14927 $classfile = 'account';
14928 $classname = 'Account';
14929 } elseif ($elementType == 'bank_line') {
14930 $classpath = 'compta/bank/class';
14931 $module = 'bank'; // We need $conf->bank->dir_output and not $conf->banque->dir_output
14932 $classfile = 'account';
14933 $classname = 'AccountLine';
14934 } elseif ($elementType == 'category') {
14935 $classpath = 'categories/class';
14936 $module = 'categorie';
14937 $subelement = 'categorie';
14938 $table_element = 'categorie';
14939 } elseif ($elementType == 'contact') {
14940 $classpath = 'contact/class';
14941 $classfile = 'contact';
14942 $module = 'societe';
14943 $subelement = 'contact';
14944 $table_element = 'socpeople';
14945 } elseif ($elementType == 'inventory') {
14946 $module = 'product';
14947 $classpath = 'product/inventory/class';
14948 } elseif ($elementType == 'inventoryline') {
14949 $module = 'product';
14950 $classpath = 'product/inventory/class';
14951 $table_element = 'inventorydet';
14952 $parent_element = 'inventory';
14953 } elseif ($elementType == 'stock' || $elementType == 'entrepot' || $elementType == 'warehouse') {
14954 $module = 'stock';
14955 $classpath = 'product/stock/class';
14956 $classfile = 'entrepot';
14957 $classname = 'Entrepot';
14958 $table_element = 'entrepot';
14959 } elseif ($elementType == 'project') {
14960 $classpath = 'projet/class';
14961 $module = 'projet';
14962 $table_element = 'projet';
14963 } elseif ($elementType == 'project_task') {
14964 $classpath = 'projet/class';
14965 $module = 'projet';
14966 $subelement = 'task';
14967 $table_element = 'projet_task';
14968 } elseif ($elementType == 'facture' || $elementType == 'invoice') {
14969 $classpath = 'compta/facture/class';
14970 $module = 'facture';
14971 $subelement = 'facture';
14972 $table_element = 'facture';
14973 } elseif ($elementType == 'facturedet') {
14974 $classpath = 'compta/facture/class';
14975 $classfile = 'facture';
14976 $classname = 'FactureLigne';
14977 $module = 'facture';
14978 $table_element = 'facturedet';
14979 $parent_element = 'facture';
14980 } elseif ($elementType == 'facturerec'|| $elementType == 'facture_rec') {
14981 $classpath = 'compta/facture/class';
14982 $classfile = 'facture-rec';
14983 $module = 'facture';
14984 $classname = 'FactureRec';
14985 } elseif ($elementType == 'commande' || $elementType == 'order') {
14986 $classpath = 'commande/class';
14987 $module = 'commande';
14988 $subelement = 'commande';
14989 $table_element = 'commande';
14990 } elseif ($elementType == 'commandedet') {
14991 $classpath = 'commande/class';
14992 $classfile = 'commande';
14993 $classname = 'OrderLine';
14994 $module = 'commande';
14995 $table_element = 'commandedet';
14996 $parent_element = 'commande';
14997 } elseif ($elementType == 'propal') {
14998 $classpath = 'comm/propal/class';
14999 $table_element = 'propal';
15000 } elseif ($elementType == 'propaldet') {
15001 $classpath = 'comm/propal/class';
15002 $classfile = 'propal';
15003 $subelement = 'propaleligne';
15004 $module = 'propal';
15005 $table_element = 'propaldet';
15006 $parent_element = 'propal';
15007 } elseif ($elementType == 'shipping') {
15008 $classpath = 'expedition/class';
15009 $classfile = 'expedition';
15010 $classname = 'Expedition';
15011 $module = 'expedition';
15012 $table_element = 'expedition';
15013 } elseif ($elementType == 'expeditiondet' || $elementType == 'shippingdet') {
15014 $classpath = 'expedition/class';
15015 $classfile = 'expedition';
15016 $classname = 'ExpeditionLigne';
15017 $module = 'expedition';
15018 $table_element = 'expeditiondet';
15019 $parent_element = 'expedition';
15020 } elseif ($elementType == 'delivery_note') {
15021 $classpath = 'delivery/class';
15022 $subelement = 'delivery';
15023 $module = 'expedition';
15024 } elseif ($elementType == 'delivery') {
15025 $classpath = 'delivery/class';
15026 $subelement = 'delivery';
15027 $module = 'expedition';
15028 } elseif ($elementType == 'deliverydet') {
15029 // @todo
15030 } elseif ($elementType == 'supplier_proposal') {
15031 $classpath = 'supplier_proposal/class';
15032 $module = 'supplier_proposal';
15033 $element = 'supplierproposal';
15034 $classfile = 'supplier_proposal';
15035 $subelement = 'supplierproposal';
15036 } elseif ($elementType == 'supplier_proposaldet') {
15037 $classpath = 'supplier_proposal/class';
15038 $module = 'supplier_proposal';
15039 $classfile = 'supplier_proposal';
15040 $classname = 'SupplierProposalLine';
15041 $table_element = 'supplier_proposaldet';
15042 $parent_element = 'supplier_proposal';
15043 } elseif ($elementType == 'contract') {
15044 $classpath = 'contrat/class';
15045 $module = 'contrat';
15046 $subelement = 'contrat';
15047 $table_element = 'contract';
15048 } elseif ($elementType == 'contratdet') {
15049 $classpath = 'contrat/class';
15050 $module = 'contrat';
15051 $table_element = 'contratdet';
15052 $parent_element = 'contrat';
15053 } elseif ($elementType == 'mailing') {
15054 $classpath = 'comm/mailing/class';
15055 $module = 'mailing';
15056 $classfile = 'mailing';
15057 $classname = 'Mailing';
15058 $subelement = '';
15059 } elseif ($elementType == 'member' || $elementType == 'adherent') {
15060 $classpath = 'adherents/class';
15061 $module = 'adherent';
15062 $subelement = 'adherent';
15063 $table_element = 'adherent';
15064 } elseif ($elementType == 'subscription') {
15065 $classpath = 'adherents/class';
15066 $classfile = 'subscription';
15067 $module = 'adherent';
15068 $subelement = 'subscription';
15069 $classname = 'Subscription';
15070 $table_element = 'subscription';
15071 } elseif ($elementType == 'usergroup') {
15072 $classpath = 'user/class';
15073 $module = 'user';
15074 } elseif ($elementType == 'mo' || $elementType == 'mrp') {
15075 $classpath = 'mrp/class';
15076 $classfile = 'mo';
15077 $classname = 'Mo';
15078 $module = 'mrp';
15079 $subelement = '';
15080 $table_element = 'mrp_mo';
15081 } elseif ($elementType == 'mrp_production') {
15082 $classpath = 'mrp/class';
15083 $classfile = 'mo';
15084 $classname = 'MoLine';
15085 $module = 'mrp';
15086 $subelement = '';
15087 $table_element = 'mrp_production';
15088 $parent_element = 'mo';
15089 } elseif ($elementType == 'cabinetmed_cons') {
15090 $classpath = 'cabinetmed/class';
15091 $module = 'cabinetmed';
15092 $subelement = 'cabinetmedcons';
15093 $table_element = 'cabinetmedcons';
15094 } elseif ($elementType == 'fichinter') {
15095 $classpath = 'fichinter/class';
15096 $module = 'ficheinter';
15097 $subelement = 'fichinter';
15098 $table_element = 'fichinter';
15099 } elseif ($elementType == 'dolresource' || $elementType == 'resource') {
15100 $classpath = 'resource/class';
15101 $module = 'resource';
15102 $subelement = 'dolresource';
15103 $table_element = 'resource';
15104 } elseif ($elementType == 'opensurvey_sondage') {
15105 $classpath = 'opensurvey/class';
15106 $module = 'opensurvey';
15107 $subelement = 'opensurveysondage';
15108 } elseif ($elementType == 'order_supplier' || $elementType == 'supplier_order' || $elementType == 'commande_fournisseur' || $elementType == 'commandefournisseur') {
15109 $classpath = 'fourn/class';
15110 $module = 'fournisseur';
15111 $classfile = 'fournisseur.commande';
15112 $element = 'order_supplier';
15113 $subelement = '';
15114 $classname = 'CommandeFournisseur';
15115 $table_element = 'commande_fournisseur';
15116 } elseif ($elementType == 'commande_fournisseurdet') {
15117 $classpath = 'fourn/class';
15118 $module = 'fournisseur';
15119 $classfile = 'fournisseur.commande';
15120 $element = 'commande_fournisseurdet';
15121 $subelement = '';
15122 $classname = 'CommandeFournisseurLigne';
15123 $table_element = 'commande_fournisseurdet';
15124 $parent_element = 'commande_fournisseur';
15125 } elseif ($elementType == 'invoice_supplier' || $elementType == 'supplier_invoice' || $elementType == 'facture_fourn') {
15126 $classpath = 'fourn/class';
15127 $module = 'fournisseur';
15128 $classfile = 'fournisseur.facture';
15129 $element = 'invoice_supplier';
15130 $subelement = '';
15131 $classname = 'FactureFournisseur';
15132 $table_element = 'facture_fourn';
15133 } elseif ($elementType == 'facture_fourn_det') {
15134 $classpath = 'fourn/class';
15135 $module = 'fournisseur';
15136 $classfile = 'fournisseur.facture';
15137 $element = 'facture_fourn_det';
15138 $subelement = '';
15139 $classname = 'SupplierInvoiceLine';
15140 $table_element = 'facture_fourn_det';
15141 $parent_element = 'invoice_supplier';
15142 } elseif ($elementType == "service") {
15143 $classpath = 'product/class';
15144 $subelement = 'product';
15145 $table_element = 'product';
15146 } elseif ($elementType == 'product_attribute') {
15147 $module = 'variants';
15148 $element = 'product_attribute';
15149 $subelement = 'product_attribute';
15150 $classpath = 'variants/class';
15151 $classfile = 'ProductAttribute';
15152 $classname = 'ProductAttribute';
15153 $table_element = 'product_attribute';
15154 } elseif ($elementType == 'product_attribute_value') {
15155 $module = 'variants';
15156 $element = 'product_attribute_value';
15157 $subelement = 'product_attribute_value';
15158 $classpath = 'variants/class';
15159 $classfile = 'ProductAttributeValue';
15160 $classname = 'ProductAttributeValue';
15161 $table_element = 'product_attribute_value';
15162 $parent_element = 'product_attribute';
15163 } elseif ($elementType == 'salary') {
15164 $classpath = 'salaries/class';
15165 $module = 'salaries';
15166 } elseif ($elementType == 'payment_salary') {
15167 $classpath = 'salaries/class';
15168 $classfile = 'paymentsalary';
15169 $classname = 'PaymentSalary';
15170 $module = 'salaries';
15171 } elseif ($elementType == 'productlot') {
15172 $module = 'productbatch';
15173 $classpath = 'product/stock/class';
15174 $classfile = 'productlot';
15175 $classname = 'Productlot';
15176 $element = 'productlot';
15177 $subelement = '';
15178 $table_element = 'product_lot';
15179 } elseif ($elementType == 'societeaccount') {
15180 $classpath = 'societe/class';
15181 $classfile = 'societeaccount';
15182 $classname = 'SocieteAccount';
15183 $module = 'societe';
15184 } elseif ($elementType == 'websitepage' || $elementType == 'website_page') {
15185 $classpath = 'website/class';
15186 $classfile = 'websitepage';
15187 $classname = 'Websitepage';
15188 $module = 'website';
15189 $subelement = 'websitepage';
15190 $table_element = 'website_page';
15191 } elseif ($elementType == 'fiscalyear') {
15192 $classpath = 'core/class';
15193 $module = 'accounting';
15194 $subelement = 'fiscalyear';
15195 } elseif ($elementType == 'chargesociales') {
15196 $classpath = 'compta/sociales/class';
15197 $module = 'tax';
15198 $table_element = 'chargesociales';
15199 } elseif ($elementType == 'tva') {
15200 $classpath = 'compta/tva/class';
15201 $module = 'tax';
15202 $subdir = '/vat';
15203 $table_element = 'tva';
15204 } elseif ($elementType == 'emailsenderprofile') {
15205 $module = '';
15206 $classpath = 'core/class';
15207 $classfile = 'emailsenderprofile';
15208 $classname = 'EmailSenderProfile';
15209 $table_element = 'c_email_senderprofile';
15210 $subelement = '';
15211 } elseif ($elementType == 'conferenceorboothattendee') {
15212 $classpath = 'eventorganization/class';
15213 $classfile = 'conferenceorboothattendee';
15214 $classname = 'ConferenceOrBoothAttendee';
15215 $module = 'eventorganization';
15216 } elseif ($elementType == 'conferenceorbooth') {
15217 $classpath = 'eventorganization/class';
15218 $classfile = 'conferenceorbooth';
15219 $classname = 'ConferenceOrBooth';
15220 $module = 'eventorganization';
15221 } elseif ($elementType == 'ccountry') {
15222 $module = '';
15223 $classpath = 'core/class';
15224 $classfile = 'ccountry';
15225 $classname = 'Ccountry';
15226 $table_element = 'c_country';
15227 $subelement = '';
15228 } elseif ($elementType == 'ecmfiles') {
15229 $module = 'ecm';
15230 $classpath = 'ecm/class';
15231 $classfile = 'ecmfiles';
15232 $classname = 'Ecmfiles';
15233 $table_element = 'ecmfiles';
15234 $subelement = '';
15235 } elseif ($elementType == 'knowledgerecord' || $elementType == 'knowledgemanagement') {
15236 $module = 'knowledgemanagement';
15237 $classpath = 'knowledgemanagement/class';
15238 $classfile = 'knowledgerecord';
15239 $classname = 'KnowledgeRecord';
15240 $table_element = 'knowledgemanagement_knowledgerecord';
15241 $subelement = '';
15242 } elseif ($elementType == 'customer') {
15243 $module = 'societe';
15244 $classpath = 'societe/class';
15245 $classfile = 'client';
15246 $classname = 'Client';
15247 $table_element = 'societe';
15248 $subelement = '';
15249 } elseif ($elementType == 'fournisseur' || $elementType == 'supplier') {
15250 $module = 'societe';
15251 $classpath = 'fourn/class';
15252 $classfile = 'fournisseur';
15253 $classname = 'Fournisseur';
15254 $table_element = 'societe';
15255 $subelement = '';
15256 } elseif ($elementType == 'recruitmentcandidature') {
15257 $module = 'recruitment';
15258 $classfile = 'recruitmentcandidature';
15259 $classpath = 'recruitment/class';
15260 $classname = 'RecruitmentCandidature';
15261 $subelement = 'recruitmentcandidature';
15262 $subdir = '/recruitmentcandidature';
15263 } elseif ($elementType == 'recruitmentjobposition') {
15264 $module = 'recruitment';
15265 $classfile = 'recruitmentjobposition';
15266 $classpath = 'recruitment/class';
15267 $classname = 'RecruitmentJobPosition';
15268 $subelement = 'recruitmentjobposition';
15269 $subdir = '/recruitmentjobposition';
15270 }
15271
15272
15273 if (empty($classfile)) {
15274 $classfile = strtolower($subelement);
15275 }
15276 if (empty($classname)) {
15277 $classname = ucfirst($subelement);
15278 }
15279 if (empty($classpath)) {
15280 $classpath = $module . '/class';
15281 }
15282
15283 //print 'getElementProperties subdir='.$subdir;
15284
15285 // Set dir_output
15286 if ($module && isset($conf->$module)) { // The generic case
15287 if (!empty($conf->$module->multidir_output[$conf->entity])) {
15288 $dir_output = $conf->$module->multidir_output[$conf->entity];
15289 } elseif (!empty($conf->$module->output[$conf->entity])) {
15290 $dir_output = $conf->$module->output[$conf->entity];
15291 } elseif (!empty($conf->$module->dir_output)) {
15292 $dir_output = $conf->$module->dir_output;
15293 }
15294 if (!empty($conf->$module->multidir_temp[$conf->entity])) {
15295 $dir_temp = $conf->$module->multidir_temp[$conf->entity];
15296 } elseif (!empty($conf->$module->temp[$conf->entity])) {
15297 $dir_temp = $conf->$module->temp[$conf->entity];
15298 } elseif (!empty($conf->$module->dir_temp)) {
15299 $dir_temp = $conf->$module->dir_temp;
15300 }
15301 }
15302
15303 // Overwrite value for special cases
15304 if ($element == 'order_supplier' && isModEnabled('fournisseur')) {
15305 $dir_output = $conf->fournisseur->commande->dir_output;
15306 $dir_temp = $conf->fournisseur->commande->dir_temp;
15307 } elseif ($element == 'invoice_supplier' && isModEnabled('fournisseur')) {
15308 $dir_output = $conf->fournisseur->facture->dir_output;
15309 $dir_temp = $conf->fournisseur->facture->dir_temp;
15310 }
15311 $dir_output .= $subdir;
15312 $dir_temp .= $subdir;
15313
15314 $elementProperties = array(
15315 'module' => $module,
15316 'element' => $element,
15317 'table_element' => $table_element,
15318 'subelement' => $subelement,
15319 'classpath' => $classpath,
15320 'classfile' => $classfile,
15321 'classname' => $classname,
15322 'dir_output' => $dir_output,
15323 'dir_temp' => $dir_temp,
15324 'parent_element' => $parent_element,
15325 );
15326
15327
15328 // Add hook
15329 if (!is_object($hookmanager)) {
15330 include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
15331 $hookmanager = new HookManager($db);
15332 }
15333 $hookmanager->initHooks(array('elementproperties'));
15334
15335
15336 // Hook params
15337 $parameters = array(
15338 'elementType' => $elementType,
15339 'elementProperties' => $elementProperties
15340 );
15341
15342 $reshook = $hookmanager->executeHooks('getElementProperties', $parameters);
15343
15344 if ($reshook) {
15345 $elementProperties = $hookmanager->resArray;
15346 } elseif (!empty($hookmanager->resArray) && is_array($hookmanager->resArray)) { // resArray is always an array but for sécurity against misconfigured external modules
15347 $elementProperties = array_replace($elementProperties, $hookmanager->resArray);
15348 }
15349
15350 // context of elementproperties doesn't need to exist out of this function so delete it to avoid elementproperties context is equal to all
15351 if (($key = array_search('elementproperties', $hookmanager->contextarray)) !== false) {
15352 unset($hookmanager->contextarray[$key]);
15353 }
15354
15355 return $elementProperties;
15356}
15357
15370function fetchObjectByElement($element_id, $element_type, $element_ref = '', $useCache = 0, $maxCacheByType = 10)
15371{
15372 global $db, $conf;
15373
15374 $ret = 0;
15375
15376 $element_prop = getElementProperties($element_type);
15377
15378 if ($element_prop['module'] == 'product' || $element_prop['module'] == 'service') {
15379 // For example, for an extrafield 'product' (shared for both product and service) that is a link to an object,
15380 // this is called with $element_type = 'product' when we need element properties of a service, we must return a product. If we create the
15381 // extrafield for a service, it is not supported and not found when editing the product/service card. So we must keep 'product' for extrafields
15382 // of service and we will return properties of a product.
15383 $ismodenabled = (isModEnabled('product') || isModEnabled('service'));
15384 } elseif ($element_prop['module'] == 'societeaccount') {
15385 $ismodenabled = isModEnabled('website') || isModEnabled('webportal');
15386 } else {
15387 $ismodenabled = isModEnabled($element_prop['module']);
15388 }
15389 //var_dump('element_type='.$element_type);
15390 //var_dump($element_prop);
15391 //var_dump($element_prop['module'].' '.$ismodenabled);
15392 if (is_array($element_prop) && (empty($element_prop['module']) || $ismodenabled)) {
15393 if ($useCache === 1 && $element_id > 0
15394 && !empty($conf->cache['fetchObjectByElement'][$element_type])
15395 && !empty($conf->cache['fetchObjectByElement'][$element_type][$element_id])
15396 && is_object($conf->cache['fetchObjectByElement'][$element_type][$element_id])
15397 ) {
15398 return $conf->cache['fetchObjectByElement'][$element_type][$element_id];
15399 }
15400
15401 dol_include_once('/' . $element_prop['classpath'] . '/' . $element_prop['classfile'] . '.class.php');
15402
15403 if (class_exists($element_prop['classname'])) {
15404 $className = $element_prop['classname'];
15405 $objecttmp = new $className($db);
15406 '@phan-var-force CommonObject $objecttmp';
15409 if ($element_id > 0 || !empty($element_ref)) {
15410 $ret = $objecttmp->fetch($element_id, $element_ref);
15411 if ($ret > 0) {
15412 if (empty($objecttmp->module)) {
15413 $objecttmp->module = $element_prop['module'];
15414 }
15415
15416 if ($useCache > 0) {
15417 if (!isset($conf->cache['fetchObjectByElement'][$element_type])) {
15418 $conf->cache['fetchObjectByElement'][$element_type] = [];
15419 }
15420
15421 // Manage cache limit
15422 if (! empty($conf->cache['fetchObjectByElement'][$element_type]) && is_array($conf->cache['fetchObjectByElement'][$element_type]) && count($conf->cache['fetchObjectByElement'][$element_type]) >= $maxCacheByType) {
15423 array_shift($conf->cache['fetchObjectByElement'][$element_type]);
15424 }
15425
15426 $conf->cache['fetchObjectByElement'][$element_type][$element_id] = $objecttmp;
15427 }
15428
15429 return $objecttmp;
15430 }
15431 } else {
15432 return $objecttmp; // returned an object without fetch
15433 }
15434 } else {
15435 dol_syslog($element_prop['classname'] . ' doesn\'t exists in /' . $element_prop['classpath'] . '/' . $element_prop['classfile'] . '.class.php');
15436 return -1;
15437 }
15438 }
15439
15440 return $ret;
15441}
15442
15448function getExecutableContent()
15449{
15450 $arrayofregexextension = array(
15451 'htm',
15452 'html',
15453 'shtml',
15454 'js',
15455 'phar',
15456 'php',
15457 'php3',
15458 'php4',
15459 'php5',
15460 'phtml',
15461 'pht',
15462 'pl',
15463 'py',
15464 'cgi',
15465 'ksh',
15466 'sh',
15467 'shtml',
15468 'bash',
15469 'bat',
15470 'cmd',
15471 'wpk',
15472 'exe',
15473 'dmg',
15474 'appimage'
15475 );
15476
15477 return $arrayofregexextension;
15478}
15479
15486function isAFileWithExecutableContent($filename)
15487{
15488 $arrayofregexextension = getExecutableContent();
15489
15490 foreach ($arrayofregexextension as $fileextension) {
15491 if (preg_match('/\.' . preg_quote($fileextension, '/') . '$/i', $filename)) {
15492 return true;
15493 }
15494 }
15495
15496 return false;
15497}
15498
15506function newToken()
15507{
15508 return empty($_SESSION['newtoken']) ? '' : $_SESSION['newtoken'];
15509}
15510
15518function currentToken()
15519{
15520 return isset($_SESSION['token']) ? $_SESSION['token'] : '';
15521}
15522
15528function getNonce()
15529{
15530 global $conf;
15531
15532 if (empty($conf->cache['nonce'])) {
15533 include_once DOL_DOCUMENT_ROOT . '/core/lib/security.lib.php';
15534 $conf->cache['nonce'] = dolGetRandomBytes(8);
15535 }
15536
15537 return $conf->cache['nonce'];
15538}
15539
15540
15554function startSimpleTable($header, $link = "", $arguments = "", $emptyColumns = 0, $number = -1, $pictofulllist = '')
15555{
15556 global $langs;
15557
15558 print '<div class="div-table-responsive-no-min">';
15559 print '<table class="noborder centpercent">';
15560 print '<tr class="liste_titre">';
15561
15562 print ($emptyColumns < 1) ? '<th>' : '<th colspan="' . ($emptyColumns + 1) . '">';
15563
15564 print '<span class="valignmiddle">' . $langs->trans($header) . '</span>';
15565
15566 if (!empty($link)) {
15567 if (!empty($arguments)) {
15568 print '<a href="' . DOL_URL_ROOT . '/' . $link . '?' . $arguments . '">';
15569 } else {
15570 print '<a href="' . DOL_URL_ROOT . '/' . $link . '">';
15571 }
15572 }
15573
15574 if ($number > -1) {
15575 print '<span class="badge marginleftonlyshort">' . $number . '</span>';
15576 } elseif (!empty($link)) {
15577 print '<span class="badge marginleftonlyshort">...</span>';
15578 }
15579
15580 if (!empty($link)) {
15581 print '</a>';
15582 }
15583
15584 print '</th>';
15585
15586 if ($number < 0 && !empty($link)) {
15587 print '<th class="right">';
15588 print '</th>';
15589 }
15590
15591 print '</tr>';
15592}
15593
15602function finishSimpleTable($addLineBreak = false)
15603{
15604 print '</table>';
15605 print '</div>';
15606
15607 if ($addLineBreak) {
15608 print '<br>';
15609 }
15610}
15611
15623function addSummaryTableLine($tableColumnCount, $num, $nbofloop = 0, $total = 0, $noneWord = "None", $extraRightColumn = false)
15624{
15625 global $langs;
15626
15627 if ($num === 0) {
15628 print '<tr class="oddeven">';
15629 print '<td colspan="' . $tableColumnCount . '"><span class="opacitymedium">' . $langs->trans($noneWord) . '</span></td>';
15630 print '</tr>';
15631 return;
15632 }
15633
15634 if ($nbofloop === 0) {
15635 // don't show a summary line
15636 return;
15637 }
15638
15639 /* Case already handled above, commented to satisfy phpstan.
15640 if ($num === 0) {
15641 $colspan = $tableColumnCount;
15642 } else
15643 */
15644 if ($num > $nbofloop) {
15645 $colspan = $tableColumnCount;
15646 } else {
15647 $colspan = $tableColumnCount - 1;
15648 }
15649
15650 if ($extraRightColumn) {
15651 $colspan--;
15652 }
15653
15654 print '<tr class="liste_total">';
15655
15656 if ($nbofloop > 0 && $num > $nbofloop) {
15657 print '<td colspan="' . $colspan . '" class="right">' . $langs->trans("XMoreLines", ($num - $nbofloop)) . '</td>';
15658 } else {
15659 print '<td colspan="' . $colspan . '" class="right"> ' . $langs->trans("Total") . '</td>';
15660 print '<td class="right centpercent">' . price($total) . '</td>';
15661 }
15662
15663 if ($extraRightColumn) {
15664 print '<td></td>';
15665 }
15666
15667 print '</tr>';
15668}
15669
15678function readfileLowMemory($fullpath_original_file_osencoded, $method = -1)
15679{
15680 if ($method == -1) {
15681 $method = 0;
15682 if (getDolGlobalString('MAIN_FORCE_READFILE_WITH_FREAD')) {
15683 $method = 1;
15684 }
15685 if (getDolGlobalString('MAIN_FORCE_READFILE_WITH_STREAM_COPY')) {
15686 $method = 2;
15687 }
15688 }
15689
15690 // Be sure we don't have output buffering enabled to have readfile working correctly
15691 while (ob_get_level()) {
15692 ob_end_flush();
15693 }
15694
15695 // Solution 0
15696 if ($method == 0) {
15697 readfile($fullpath_original_file_osencoded);
15698 } elseif ($method == 1) {
15699 // Solution 1
15700 $handle = fopen($fullpath_original_file_osencoded, "rb");
15701 while (!feof($handle)) {
15702 print fread($handle, 8192);
15703 }
15704 fclose($handle);
15705 } elseif ($method == 2) {
15706 // Solution 2
15707 $handle1 = fopen($fullpath_original_file_osencoded, "rb");
15708 $handle2 = fopen("php://output", "wb");
15709 stream_copy_to_stream($handle1, $handle2);
15710 fclose($handle1);
15711 fclose($handle2);
15712 }
15713}
15714
15724function showValueWithClipboardCPButton($valuetocopy, $showonlyonhover = 1, $texttoshow = '')
15725{
15726 global $langs;
15727
15728 $tag = 'span'; // Using div (like any style of type 'block') does not work when using the js copy code.
15729
15730 $result = '<span class="clipboardCP' . ($showonlyonhover ? ' clipboardCPShowOnHover valignmiddle' : '') . '">';
15731 if ($texttoshow === 'none') {
15732 $result .= '<' . $tag . ' class="clipboardCPValue hidewithsize">' . dol_escape_htmltag($valuetocopy, 1, 1) . '</' . $tag . '>';
15733 $result .= '<span class="clipboardCPValueToPrint"></span>';
15734 } elseif ($texttoshow) {
15735 $result .= '<' . $tag . ' class="clipboardCPValue hidewithsize">' . dol_escape_htmltag($valuetocopy, 1, 1) . '</' . $tag . '>';
15736 $result .= '<span class="clipboardCPValueToPrint">' . dol_escape_htmltag($texttoshow, 1, 1) . '</span>';
15737 } else {
15738 $result .= '<' . $tag . ' class="clipboardCPValue">' . dol_escape_htmltag($valuetocopy, 1, 1) . '</' . $tag . '>';
15739 }
15740 $result .= '<span class="clipboardCPButton far fa-clipboard opacitymedium paddingleft pictomodule" title="' . dolPrintHTML($langs->trans("ClickToCopyToClipboard")) . '"></span>';
15741 $result .= img_picto('', 'tick', 'class="clipboardCPTick hidden paddingleft pictomodule"');
15742 $result .= '<span class="clipboardCPText"></span>';
15743 $result .= '</span>';
15744
15745 return $result;
15746}
15747
15748
15756function jsonOrUnserialize($stringtodecode, $assoc = true)
15757{
15758 $result = json_decode($stringtodecode, $assoc);
15759 if ($result === null) {
15760 $result = unserialize($stringtodecode, ['allowed_classes' => false]); // For backward compatibility. Is no more used in recent versions.
15761 }
15762
15763 return $result;
15764}
15765
15766
15783function forgeSQLFromUniversalSearchCriteria($filter, &$errorstr = '', $noand = 0, $nopar = 0, $noerror = 0)
15784{
15785 global $db, $user;
15786
15787 if (is_null($filter) || !is_string($filter) || $filter === '') {
15788 return '';
15789 }
15790 if (!preg_match('/^\‍(.*\‍)$/', $filter)) { // If $filter does not start and end with ()
15791 $filter = '(' . $filter . ')';
15792 }
15793
15794 $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'
15795 $firstandlastparenthesis = 0;
15796
15797 if (!dolCheckFilters($filter, $errorstr, $firstandlastparenthesis)) {
15798 if ($noerror) {
15799 return '1 = 2';
15800 } else {
15801 return 'Filter syntax error - ' . $errorstr; // Bad balance of parenthesis, we return an error message or force a SQL not found
15802 }
15803 }
15804
15805 // Test the filter syntax
15806 $t = preg_replace_callback('/' . $regexstring . '/i', 'dolForgeDummyCriteriaCallback', $filter);
15807 $t = str_ireplace(array('and', 'or', ' '), '', $t); // Remove the only strings allowed between each () criteria
15808 // If the string result contains something else than '()', the syntax was wrong
15809
15810 if (preg_match('/[^\‍(\‍)]/', $t)) {
15811 $tmperrorstr = 'Bad syntax of the search string';
15812 $errorstr = 'Bad syntax of the search string: ' . $filter;
15813 if ($noerror) {
15814 return '1 = 2';
15815 } else {
15816 dol_syslog("forgeSQLFromUniversalSearchCriteria Filter error - " . $errorstr, LOG_WARNING);
15817 return 'Filter error - ' . $tmperrorstr; // Bad syntax of the search string, we return an error message or force a SQL not found
15818 }
15819 }
15820
15821 $ret = ($noand ? "" : " AND ") . ($nopar ? "" : '(') . preg_replace_callback('/' . $regexstring . '/i', 'dolForgeSQLCriteriaCallback', $filter) . ($nopar ? "" : ')');
15822
15823 if (is_object($db)) {
15824 $ret = str_replace('__NOW__', "'" . $db->idate(dol_now()) . "'", $ret);
15825 }
15826 if (is_object($user)) {
15827 $ret = str_replace('__USER_ID__', (string) $user->id, $ret);
15828 }
15829
15830 return $ret;
15831}
15832
15840function dolForgeExplodeAnd($sqlfilters)
15841{
15842 $arrayofandtags = array();
15843 $nbofchars = dol_strlen($sqlfilters);
15844
15845 $error = '';
15846 $parenthesislevel = 0;
15847 $result = dolCheckFilters($sqlfilters, $error, $parenthesislevel);
15848 if (!$result) {
15849 return array();
15850 }
15851 if ($parenthesislevel >= 1) {
15852 $sqlfilters = preg_replace('/^\‍(/', '', preg_replace('/\‍)$/', '', $sqlfilters));
15853 }
15854
15855 $i = 0;
15856 $s = '';
15857 $countparenthesis = 0;
15858 while ($i < $nbofchars) {
15859 $char = dol_substr($sqlfilters, $i, 1);
15860
15861 if ($char == '(') {
15862 $countparenthesis++;
15863 } elseif ($char == ')') {
15864 $countparenthesis--;
15865 }
15866
15867 if ($countparenthesis == 0) {
15868 $char2 = dol_substr($sqlfilters, $i + 1, 1);
15869 $char3 = dol_substr($sqlfilters, $i + 2, 1);
15870 if ($char == 'A' && $char2 == 'N' && $char3 == 'D') {
15871 // We found a AND
15872 $s = trim($s);
15873 if (!preg_match('/^\‍(.*\‍)$/', $s)) {
15874 $s = '(' . $s . ')';
15875 }
15876 $arrayofandtags[] = $s;
15877 $s = '';
15878 $i += 2;
15879 } else {
15880 $s .= $char;
15881 }
15882 } else {
15883 $s .= $char;
15884 }
15885 $i++;
15886 }
15887 if ($s) {
15888 $s = trim($s);
15889 if (!preg_match('/^\‍(.*\‍)$/', $s)) {
15890 $s = '(' . $s . ')';
15891 }
15892 $arrayofandtags[] = $s;
15893 }
15894
15895 return $arrayofandtags;
15896}
15897
15907function dolCheckFilters($sqlfilters, &$error = '', &$parenthesislevel = 0)
15908{
15909 //$regexstring='\‍(([^:\'\‍(\‍)]+:[^:\'\‍(\‍)]+:[^:\‍(\‍)]+)\‍)';
15910 //$tmp=preg_replace_all('/'.$regexstring.'/', '', $sqlfilters);
15911 $tmp = $sqlfilters;
15912
15913 $nb = dol_strlen($tmp);
15914 $counter = 0;
15915 $parenthesislevel = 0;
15916
15917 $error = '';
15918
15919 $i = 0;
15920 while ($i < $nb) {
15921 $char = dol_substr($tmp, $i, 1);
15922
15923 if ($char == '(') {
15924 if ($i == $parenthesislevel && $parenthesislevel == $counter) {
15925 // We open a parenthesis and it is the first char
15926 $parenthesislevel++;
15927 }
15928 $counter++;
15929 } elseif ($char == ')') {
15930 $nbcharremaining = ($nb - $i - 1);
15931 if ($nbcharremaining >= $counter) {
15932 $parenthesislevel = min($parenthesislevel, $counter - 1);
15933 }
15934 if ($parenthesislevel > $counter && $nbcharremaining >= $counter) {
15935 $parenthesislevel = $counter;
15936 }
15937 $counter--;
15938 }
15939
15940 if ($counter < 0) {
15941 $error = "Wrong balance of parenthesis in sqlfilters=" . $sqlfilters;
15942 $parenthesislevel = 0;
15943 dol_syslog($error, LOG_WARNING);
15944 return false;
15945 }
15946
15947 $i++;
15948 }
15949
15950 if ($counter > 0) {
15951 $error = "Wrong balance of parenthesis in sqlfilters=" . $sqlfilters;
15952 $parenthesislevel = 0;
15953 dol_syslog($error, LOG_WARNING);
15954 return false;
15955 }
15956
15957 return true;
15958}
15959
15967function dolForgeDummyCriteriaCallback($matches)
15968{
15969 //dol_syslog("Convert matches ".$matches[1]);
15970 if (empty($matches[1])) {
15971 return '';
15972 }
15973 $tmp = explode(':', $matches[1]);
15974 if (count($tmp) < 3) {
15975 return '';
15976 }
15977
15978 return '()'; // An empty criteria
15979}
15980
15989function dolForgeSQLCriteriaCallback($matches)
15990{
15991 global $db;
15992
15993 //dol_syslog("Convert matches ".$matches[1]);
15994 if (empty($matches[1])) {
15995 return '';
15996 }
15997 $tmp = explode(':', $matches[1], 3);
15998 if (count($tmp) < 3) {
15999 return '';
16000 }
16001
16002 $operand = preg_replace('/[^a-z0-9\._]/i', '', trim($tmp[0]));
16003
16004 $operator = strtoupper(preg_replace('/[^a-z<>!=]/i', '', trim($tmp[1])));
16005
16006 $realOperator = [
16007 'NOTLIKE' => 'NOT LIKE',
16008 'ISNOT' => 'IS NOT',
16009 'NOTIN' => 'NOT IN',
16010 '!=' => '<>',
16011 ];
16012
16013 if (array_key_exists($operator, $realOperator)) {
16014 $operator = $realOperator[$operator];
16015 }
16016
16017 $tmpescaped = $tmp[2];
16018
16019 //print "Case: ".$operator." ".$operand." ".$tmpescaped."\n";
16020
16021 $regbis = array();
16022
16023 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)
16024 //if (!preg_match('/^\‍(.*\‍)$/', $tmpescaped)) {
16025 $tmpescaped2 = '(';
16026 // Explode and sanitize each element in list
16027 $tmpelemarray = explode(',', $tmpescaped);
16028 foreach ($tmpelemarray as $tmpkey => $tmpelem) {
16029 $reg = array();
16030 $tmpelem = trim($tmpelem);
16031 if (preg_match('/^\'(.*)\'$/', $tmpelem, $reg)) {
16032 $tmpelemarray[$tmpkey] = "'" . $db->escape($db->sanitize($reg[1], 2, 1, 1, 1)) . "'";
16033 $tmpelemarray[$tmpkey] = "'".$db->escape($db->sanitize($reg[1], 2, 1, 1, 1))."'";
16034 } elseif (preg_match('/^[0-9]+$/', (string) $tmpelem)) { // if only 0-9 chars, no .
16035 $tmpelemarray[$tmpkey] = (int) $tmpelem;
16036 } elseif (is_numeric((string) $tmpelem)) { // it can be a float with a .
16037 $tmpelemarray[$tmpkey] = (float) $tmpelem;
16038 } elseif (!getDolGlobalString("MAIN_DISALLOW_UNSECURED_SELECT_INTO_EXTRAFIELDS_FILTER")) {
16039 $tmpelemarray[$tmpkey] = preg_replace('/[^a-z0-9_<>=!\s]/i', '', $tmpelem); // it can be a full subrequest
16040 } else {
16041 $tmpelemarray[$tmpkey] = preg_replace('/[^a-z0-9_]/i', '', $tmpelem); // it can be a name of field or a substitution variable like '__NOW__'
16042 }
16043 }
16044 $tmpescaped2 .= implode(',', $tmpelemarray);
16045 $tmpescaped2 .= ')';
16046
16047 $tmpescaped = $tmpescaped2;
16048 } elseif ($operator == 'LIKE' || $operator == 'NOT LIKE') {
16049 if (preg_match('/^\'([^\']*)\'$/', $tmpescaped, $regbis)) {
16050 $tmpescaped = $regbis[1];
16051 }
16052 //$tmpescaped = "'".$db->escape($db->escapeforlike($regbis[1]))."'";
16053 $tmpescaped = "'" . $db->escape($tmpescaped) . "'"; // We do not escape the _ and % so the LIKE will work as expected
16054 } elseif (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) {
16055 // TODO Retrieve type of field for $operand field name.
16056 // So we can complete format. For example we could complete a year with month and day.
16057 $tmpescaped = "'" . $db->escape($regbis[1]) . "'";
16058 } else {
16059 if (strtoupper($tmpescaped) == 'NULL') {
16060 $tmpescaped = 'NULL';
16061 } elseif (preg_match('/^[0-9]+$/', (string) $tmpescaped)) { // if only 0-9 chars, no .
16062 $tmpescaped = (int) $tmpescaped;
16063 } elseif (is_numeric((string) $tmpescaped)) { // it can be a float with a .
16064 $tmpescaped = (float) $tmpescaped;
16065 } else {
16066 $tmpescaped = preg_replace('/[^a-z0-9_]/i', '', $tmpescaped); // it can be a name of field or a substitution variable like '__NOW__'
16067 }
16068 }
16069
16070 return '(' . $db->escape($operand) . ' ' . strtoupper($operator) . ' ' . $tmpescaped . ')';
16071}
16072
16073
16083function getTimelineIcon($actionstatic, &$histo, $key)
16084{
16085 global $langs;
16086
16087 $out = '<!-- timeline icon -->' . "\n";
16088 $iconClass = 'fa fa-comments';
16089 $img_picto = '';
16090 $colorClass = '';
16091 $pictoTitle = '';
16092
16093 if ($histo[$key]['percent'] == -1) {
16094 $colorClass = 'timeline-icon-not-applicble';
16095 $pictoTitle = $langs->trans('StatusNotApplicable');
16096 } elseif ($histo[$key]['percent'] == 0) {
16097 $colorClass = 'timeline-icon-todo';
16098 $pictoTitle = $langs->trans('StatusActionToDo') . ' (0%)';
16099 } elseif ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100) {
16100 $colorClass = 'timeline-icon-in-progress';
16101 $pictoTitle = $langs->trans('StatusActionInProcess') . ' (' . $histo[$key]['percent'] . '%)';
16102 } elseif ($histo[$key]['percent'] >= 100) {
16103 $colorClass = 'timeline-icon-done';
16104 $pictoTitle = $langs->trans('StatusActionDone') . ' (100%)';
16105 }
16106
16107 if ($actionstatic->code == 'AC_TICKET_CREATE') {
16108 $iconClass = 'fa fa-ticket';
16109 } elseif ($actionstatic->code == 'AC_TICKET_MODIFY') {
16110 $iconClass = 'fa fa-pencilxxx';
16111 } elseif (preg_match('/^TICKET_MSG/', $actionstatic->code)) {
16112 $iconClass = 'fa fa-comments';
16113 } elseif (preg_match('/^TICKET_MSG_PRIVATE/', $actionstatic->code)) {
16114 $iconClass = 'fa fa-mask';
16115 } elseif (getDolGlobalString('AGENDA_USE_EVENT_TYPE')) {
16116 if ($actionstatic->type_picto) {
16117 $img_picto = img_picto('', $actionstatic->type_picto);
16118 } else {
16119 if ($actionstatic->type_code == 'AC_RDV') {
16120 $iconClass = 'fa fa-handshake';
16121 } elseif ($actionstatic->type_code == 'AC_TEL') {
16122 $iconClass = 'fa fa-phone';
16123 } elseif ($actionstatic->type_code == 'AC_FAX') {
16124 $iconClass = 'fa fa-fax';
16125 } elseif ($actionstatic->type_code == 'AC_EMAIL') {
16126 $iconClass = 'fa fa-envelope';
16127 } elseif ($actionstatic->type_code == 'AC_INT') {
16128 $iconClass = 'fa fa-shipping-fast';
16129 } elseif ($actionstatic->type_code == 'AC_OTH_AUTO') {
16130 $iconClass = 'fa fa-robot';
16131 } elseif (!preg_match('/_AUTO/', $actionstatic->type_code)) {
16132 $iconClass = 'fa fa-robot';
16133 }
16134 }
16135 }
16136
16137 $out .= '<i class="' . $iconClass . ' ' . $colorClass . '" title="' . $pictoTitle . '">' . $img_picto . '</i>' . "\n";
16138 return $out;
16139}
16140
16148{
16149 global $db;
16150
16151 $documents = array();
16152
16153 $sql = 'SELECT ecm.rowid as id, ecm.src_object_type, ecm.src_object_id, ecm.filepath, ecm.filename, ecm.agenda_id';
16154 $sql .= ' FROM ' . MAIN_DB_PREFIX . 'ecm_files ecm';
16155 $sql .= " WHERE ecm.filepath = 'agenda/" . ((int) $object->id) . "'";
16156 //$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
16157 $sql .= ' OR ecm.agenda_id = ' . (int) $object->id;
16158 $sql .= ' ORDER BY ecm.position ASC';
16159
16160 $resql = $db->query($sql);
16161 if ($resql) {
16162 if ($db->num_rows($resql)) {
16163 while ($obj = $db->fetch_object($resql)) {
16164 $documents[$obj->id] = $obj;
16165 }
16166 }
16167 }
16168
16169 return $documents;
16170}
16171
16172
16190function show_actions_messaging($conf, $langs, $db, $filterobj, $objcon = null, $noprint = 0, $actioncode = '', $donetodo = 'done', $filters = array(), $sortfield = 'a.datep,a.id', $sortorder = 'DESC')
16191{
16192 global $user, $conf;
16193 global $form;
16194
16195 global $param, $massactionbutton;
16196
16197 require_once DOL_DOCUMENT_ROOT . '/comm/action/class/actioncomm.class.php';
16198
16199 // Check parameters
16200 if (!is_object($filterobj) && !is_object($objcon)) {
16201 dol_print_error(null, 'BadParameter');
16202 }
16203
16204 $histo = array();
16205 '@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';
16206
16207 $numaction = 0;
16208 $now = dol_now();
16209
16210 $sortfield_list = explode(',', $sortfield);
16211 $sortfield_label_list = array('a.id' => 'id', 'a.datep' => 'dp', 'a.percent' => 'percent');
16212 $sortfield_new_list = array();
16213 foreach ($sortfield_list as $sortfield_value) {
16214 $sortfield_new_list[] = $sortfield_label_list[trim($sortfield_value)];
16215 }
16216 $sortfield_new = implode(',', $sortfield_new_list);
16217
16218 $sql = null;
16219 $sql2 = null;
16220
16221 if (isModEnabled('agenda')) {
16222 // Search histo on actioncomm
16223 if (is_object($objcon) && $objcon->id > 0) {
16224 $sql = "SELECT DISTINCT a.id, a.label as label,";
16225 } else {
16226 $sql = "SELECT a.id, a.label as label,";
16227 }
16228 $sql .= " a.datep as dp,";
16229 $sql .= " a.note as message,";
16230 $sql .= " a.datep2 as dp2,";
16231 $sql .= " a.percent as percent, 'action' as type,";
16232 $sql .= " a.fk_element, a.elementtype,";
16233 $sql .= " a.fk_contact,";
16234 $sql .= " a.email_from as msg_from,";
16235 $sql .= " c.code as acode, c.libelle as alabel, c.picto as apicto,";
16236 $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";
16237 if (is_object($filterobj) && get_class($filterobj) == 'Societe') {
16238 $sql .= ", sp.lastname, sp.firstname";
16239 } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
16240 $sql .= ", m.lastname, m.firstname";
16241 } elseif (is_object($filterobj) && in_array(get_class($filterobj), array('Commande', 'CommandeFournisseur', 'Product', 'Ticket', 'BOM', 'Contrat', 'Facture', 'FactureFournisseur', 'Propal', 'Expedition'))) {
16242 $sql .= ", o.ref";
16243 } else {
16244 if (is_object($filterobj) && !empty($filterobj->table_element) && !empty($filterobj->element) && !empty($filterobj->id) && array_key_exists('ref', $filterobj->fields)) {
16245 $sql .= ", o.ref";
16246 }
16247 }
16248 $sql .= " FROM " . MAIN_DB_PREFIX . "actioncomm as a";
16249 $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "user as u on u.rowid = a.fk_user_action";
16250 $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_actioncomm as c ON a.fk_action = c.id";
16251
16252 $force_filter_contact = $filterobj instanceof User;
16253
16254 if (is_object($objcon) && $objcon->id > 0) {
16255 $force_filter_contact = true;
16256 $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "actioncomm_resources as r ON a.id = r.fk_actioncomm";
16257 $sql .= " AND r.element_type = '" . $db->escape($objcon->table_element) . "' AND r.fk_element = " . ((int) $objcon->id);
16258 }
16259
16260 if ((is_object($filterobj) && get_class($filterobj) == 'Societe') || (is_object($filterobj) && get_class($filterobj) == 'Contact')) {
16261 $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "socpeople as sp ON a.fk_contact = sp.rowid";
16262 } elseif (is_object($filterobj) && get_class($filterobj) == 'Dolresource') {
16263 $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "element_resources as er";
16264 $sql .= " ON er.resource_type = 'dolresource'";
16265 $sql .= " AND er.element_id = a.id";
16266 $sql .= " AND er.resource_id = " . ((int) $filterobj->id);
16267 } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
16268 $sql .= ", " . MAIN_DB_PREFIX . "adherent as m";
16269 } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
16270 $sql .= ", " . MAIN_DB_PREFIX . "commande_fournisseur as o";
16271 } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
16272 $sql .= ", " . MAIN_DB_PREFIX . "product as o";
16273 } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
16274 $sql .= ", " . MAIN_DB_PREFIX . "ticket as o";
16275 } elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') {
16276 $sql .= ", " . MAIN_DB_PREFIX . "bom_bom as o";
16277 } elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') {
16278 $sql .= ", " . MAIN_DB_PREFIX . "contrat as o";
16279 } elseif (is_object($filterobj) && get_class($filterobj) == 'Facture') {
16280 $sql .= ", " . MAIN_DB_PREFIX . "facture as o";
16281 } elseif (is_object($filterobj) && get_class($filterobj) == 'FactureFournisseur') {
16282 $sql .= ", " . MAIN_DB_PREFIX . "facture_fourn as o";
16283 } elseif (is_object($filterobj) && get_class($filterobj) == 'Commande') {
16284 $sql .= ", " . MAIN_DB_PREFIX . "commande as o";
16285 } elseif (is_object($filterobj) && get_class($filterobj) == 'Expedition') {
16286 $sql .= ", " . MAIN_DB_PREFIX . "expedition as o";
16287 } elseif (is_object($filterobj) && get_class($filterobj) == 'Propal') {
16288 $sql .= ", " . MAIN_DB_PREFIX . "propal as o";
16289 } else {
16290 if (is_object($filterobj) && !empty($filterobj->table_element) && !empty($filterobj->element) && !empty($filterobj->id) && array_key_exists('ref', $filterobj->fields)) {
16291 $sql .= ", " . MAIN_DB_PREFIX . $filterobj->table_element . " as o";
16292 }
16293 }
16294 $sql .= " WHERE a.entity IN (" . getEntity('agenda') . ")";
16295 if (!$force_filter_contact) {
16296 if (is_object($filterobj) && in_array(get_class($filterobj), array('Societe', 'Client', 'Fournisseur')) && $filterobj->id) {
16297 $sql .= " AND a.fk_soc = " . ((int) $filterobj->id);
16298 } elseif (is_object($filterobj) && get_class($filterobj) == 'Project' && $filterobj->id) {
16299 $sql .= " AND a.fk_project = o.rowid AND a.fk_project = " . ((int) $filterobj->id);
16300 } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
16301 $sql .= " AND a.fk_element = m.rowid AND a.elementtype = 'member'";
16302 if ($filterobj->id) {
16303 $sql .= " AND a.fk_element = " . ((int) $filterobj->id);
16304 }
16305 } elseif (is_object($filterobj) && get_class($filterobj) == 'Commande') {
16306 $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'order'";
16307 if ($filterobj->id) {
16308 $sql .= " AND a.fk_element = " . ((int) $filterobj->id);
16309 }
16310 } elseif (is_object($filterobj) && get_class($filterobj) == 'Expedition') {
16311 $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'shipping'";
16312 if ($filterobj->id) {
16313 $sql .= " AND a.fk_element = " . ((int) $filterobj->id);
16314 }
16315 } elseif (is_object($filterobj) && get_class($filterobj) == 'Propal') {
16316 $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'propal'";
16317 if ($filterobj->id) {
16318 $sql .= " AND a.fk_element = " . ((int) $filterobj->id);
16319 }
16320 } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
16321 $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'order_supplier'";
16322 if ($filterobj->id) {
16323 $sql .= " AND a.fk_element = " . ((int) $filterobj->id);
16324 }
16325 } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
16326 $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'product'";
16327 if ($filterobj->id) {
16328 $sql .= " AND a.fk_element = " . ((int) $filterobj->id);
16329 }
16330 } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
16331 $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'ticket'";
16332 if ($filterobj->id) {
16333 $sql .= " AND a.fk_element = " . ((int) $filterobj->id);
16334 }
16335 } elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') {
16336 $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'bom'";
16337 if ($filterobj->id) {
16338 $sql .= " AND a.fk_element = " . ((int) $filterobj->id);
16339 }
16340 } elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') {
16341 $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'contract'";
16342 if ($filterobj->id) {
16343 $sql .= " AND a.fk_element = " . ((int) $filterobj->id);
16344 }
16345 } elseif (is_object($filterobj) && get_class($filterobj) == 'Contact' && $filterobj->id) {
16346 $sql .= " AND a.fk_contact = sp.rowid";
16347 if ($filterobj->id) {
16348 $sql .= " AND a.fk_contact = " . ((int) $filterobj->id);
16349 }
16350 } elseif (is_object($filterobj) && get_class($filterobj) == 'Facture') {
16351 $sql .= " AND a.fk_element = o.rowid";
16352 if ($filterobj->id) {
16353 $sql .= " AND a.fk_element = " . ((int) $filterobj->id) . " AND a.elementtype = 'invoice'";
16354 }
16355 } elseif (is_object($filterobj) && get_class($filterobj) == 'FactureFournisseur') {
16356 $sql .= " AND a.fk_element = o.rowid";
16357 if ($filterobj->id) {
16358 $sql .= " AND a.fk_element = " . ((int) $filterobj->id) . " AND a.elementtype = 'invoice_supplier'";
16359 }
16360 } else {
16361 if (is_object($filterobj) && !empty($filterobj->element) && !empty($filterobj->id) && array_key_exists('ref', $filterobj->fields)) {
16362 $sql .= " AND a.fk_element = o.rowid";
16363 $sql .= " AND a.elementtype = '" . $db->escape($filterobj->element) . "'";
16364 if ($filterobj->id) {
16365 $sql .= " AND a.fk_element = " . ((int) $filterobj->id);
16366 }
16367 }
16368 }
16369 } else {
16370 $sql .= " AND u.rowid = " . ((int) $filterobj->id);
16371 }
16372
16373 // Condition on actioncode
16374 if (!empty($actioncode) && $actioncode != '-1') {
16375 if (!getDolGlobalString('AGENDA_USE_EVENT_TYPE')) {
16376 if ($actioncode == 'AC_NON_AUTO') {
16377 $sql .= " AND c.type != 'systemauto'";
16378 } elseif ($actioncode == 'AC_ALL_AUTO') {
16379 $sql .= " AND c.type = 'systemauto'";
16380 } else {
16381 if ($actioncode == 'AC_OTH') {
16382 $sql .= " AND c.type != 'systemauto'";
16383 } elseif ($actioncode == 'AC_OTH_AUTO') {
16384 $sql .= " AND c.type = 'systemauto'";
16385 }
16386 }
16387 } else {
16388 if ($actioncode == 'AC_NON_AUTO') {
16389 $sql .= " AND c.type != 'systemauto'";
16390 } elseif ($actioncode == 'AC_ALL_AUTO') {
16391 $sql .= " AND c.type = 'systemauto'";
16392 } else {
16393 $sql .= " AND c.code = '" . $db->escape($actioncode) . "'";
16394 }
16395 }
16396 }
16397 if ($donetodo == 'todo') {
16398 $sql .= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '" . $db->idate($now) . "'))";
16399 } elseif ($donetodo == 'done') {
16400 $sql .= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '" . $db->idate($now) . "'))";
16401 }
16402 if (is_array($filters) && $filters['search_agenda_label']) {
16403 $sql .= natural_search('a.label', $filters['search_agenda_label']);
16404 }
16405 }
16406
16407 // Add also event from emailings. TODO This should be replaced by an automatic event ? May be it's too much for very large emailing.
16408 if (
16409 isModEnabled('mailing') && !empty($objcon->email)
16410 && (empty($actioncode) || $actioncode == 'AC_OTH_AUTO' || $actioncode == 'AC_EMAILING')
16411 ) {
16412 $langs->load("mails");
16413
16414 $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";
16415 $sql2 .= ", null as fk_element, '' as elementtype, null as contact_id";
16416 $sql2 .= ", 'AC_EMAILING' as acode, '' as alabel, '' as apicto";
16417 $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
16418 if (is_object($filterobj) && get_class($filterobj) == 'Societe') {
16419 $sql2 .= ", '' as lastname, '' as firstname";
16420 } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
16421 $sql2 .= ", '' as lastname, '' as firstname";
16422 } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
16423 $sql2 .= ", '' as ref";
16424 } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
16425 $sql2 .= ", '' as ref";
16426 } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
16427 $sql2 .= ", '' as ref";
16428 }
16429 $sql2 .= " FROM " . MAIN_DB_PREFIX . "mailing as m, " . MAIN_DB_PREFIX . "mailing_cibles as mc, " . MAIN_DB_PREFIX . "user as u";
16430 $sql2 .= " WHERE mc.email = '" . $db->escape($objcon->email) . "'"; // Search is done on email.
16431 $sql2 .= " AND mc.statut = 1";
16432 $sql2 .= " AND u.rowid = m.fk_user_valid";
16433 $sql2 .= " AND mc.fk_mailing=m.rowid";
16434 }
16435
16436 $num = 0;
16437 $MAXWITHOUTPAGINATION = getDolGlobalInt('AGENDA_MAX_EVENTS_ON_PAGE_WITHOUT_PAGINATION', 100);
16438
16439 if ($sql || $sql2) { // May not be defined if module Agenda is not enabled and mailing module disabled too
16440 if (!empty($sql) && !empty($sql2)) {
16441 $sql = $sql . " UNION " . $sql2;
16442 } elseif (empty($sql) && !empty($sql2)) {
16443 $sql = $sql2;
16444 }
16445
16446 //TODO Add navigation with this limits...
16447 $offset = 0;
16448 $limit = $MAXWITHOUTPAGINATION;
16449
16450 // Complete request and execute it with limit
16451 $sql .= $db->order($sortfield_new, $sortorder);
16452 if ($limit) {
16453 $sql .= $db->plimit($limit + 1, $offset);
16454 }
16455
16456 dol_syslog("function.lib::show_actions_messaging", LOG_DEBUG);
16457
16458 $resql = $db->query($sql);
16459 if ($resql) {
16460 $i = 0;
16461 $num = $db->num_rows($resql);
16462
16463 $imaxinloop = ($limit ? min($num, $limit) : $num);
16464 while ($i < $imaxinloop) {
16465 $obj = $db->fetch_object($resql);
16466
16467 if ($obj->type == 'action') {
16468 $contactaction = new ActionComm($db);
16469 $contactaction->id = $obj->id;
16470 $result = $contactaction->fetchResources();
16471 if ($result < 0) {
16472 dol_print_error($db);
16473 setEventMessage("actions.lib::show_actions_messaging Error fetch resource", 'errors');
16474 }
16475
16476 //if ($donetodo == 'todo') $sql.= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))";
16477 //elseif ($donetodo == 'done') $sql.= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))";
16478 $tododone = '';
16479 if (($obj->percent >= 0 and $obj->percent < 100) || ($obj->percent == -1 && $obj->dp > $now)) {
16480 $tododone = 'todo';
16481 }
16482
16483 $histo[$numaction] = array(
16484 'type' => $obj->type,
16485 'tododone' => $tododone,
16486 'id' => $obj->id,
16487 'datestart' => $db->jdate($obj->dp),
16488 'dateend' => $db->jdate($obj->dp2),
16489 'note' => $obj->label,
16490 'message' => $obj->message,
16491 'percent' => $obj->percent,
16492
16493 'userid' => $obj->user_id,
16494 'login' => $obj->user_login,
16495 'userfirstname' => $obj->user_firstname,
16496 'userlastname' => $obj->user_lastname,
16497 'userphoto' => $obj->user_photo,
16498 'msg_from' => $obj->msg_from,
16499
16500 'contact_id' => $obj->fk_contact,
16501 'socpeopleassigned' => $contactaction->socpeopleassigned,
16502 'lastname' => (empty($obj->lastname) ? '' : $obj->lastname),
16503 'firstname' => (empty($obj->firstname) ? '' : $obj->firstname),
16504 'fk_element' => $obj->fk_element,
16505 'elementtype' => $obj->elementtype,
16506 // Type of event
16507 'acode' => $obj->acode,
16508 'alabel' => $obj->alabel,
16509 'libelle' => $obj->alabel, // deprecated
16510 'apicto' => $obj->apicto
16511 );
16512 } else {
16513 $histo[$numaction] = array(
16514 'type' => $obj->type,
16515 'tododone' => 'done',
16516 'id' => $obj->id,
16517 'datestart' => $db->jdate($obj->dp),
16518 'dateend' => $db->jdate($obj->dp2),
16519 'note' => $obj->label,
16520 'message' => $obj->message,
16521 'percent' => $obj->percent,
16522 'acode' => $obj->acode,
16523
16524 'userid' => $obj->user_id,
16525 'login' => $obj->user_login,
16526 'userfirstname' => $obj->user_firstname,
16527 'userlastname' => $obj->user_lastname,
16528 'userphoto' => $obj->user_photo
16529 );
16530 }
16531
16532 $numaction++;
16533 $i++;
16534 }
16535 } else {
16536 dol_print_error($db);
16537 }
16538 }
16539
16540 // Set $out to show events
16541 $out = '';
16542
16543 if (!isModEnabled('agenda')) {
16544 $langs->loadLangs(array("admin", "errors"));
16545 $out = info_admin($langs->trans("WarningModuleXDisabledSoYouMayMissEventHere", $langs->transnoentitiesnoconv("Module2400Name")), 0, 0, 'warning');
16546 }
16547
16548 if (isModEnabled('agenda') || (isModEnabled('mailing') && !empty($objcon->email))) {
16549 $delay_warning = getDolGlobalInt('MAIN_DELAY_ACTIONS_TODO') * 24 * 60 * 60;
16550
16551 require_once DOL_DOCUMENT_ROOT . '/comm/action/class/actioncomm.class.php';
16552 include_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php';
16553 require_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php';
16554 require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
16555
16556 $formactions = new FormActions($db);
16557
16558 $actionstatic = new ActionComm($db);
16559 $userstatic = new User($db);
16560 $contactstatic = new Contact($db);
16561 $userGetNomUrlCache = array();
16562 $contactGetNomUrlCache = array();
16563
16564 $out .= '<div class="filters-container" >';
16565 $out .= '<form name="listactionsfilter" class="listactionsfilter" action="' . $_SERVER["PHP_SELF"] . '" method="POST">';
16566 $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
16567
16568 if (
16569 $objcon && get_class($objcon) == 'Contact' &&
16570 (is_null($filterobj) || get_class($filterobj) == 'Societe')
16571 ) {
16572 $out .= '<input type="hidden" name="id" value="' . $objcon->id . '" />';
16573 } else {
16574 $out .= '<input type="hidden" name="id" value="' . $filterobj->id . '" />';
16575 }
16576 if (($filterobj && get_class($filterobj) == 'Societe')) {
16577 $out .= '<input type="hidden" name="socid" value="' . $filterobj->id . '" />';
16578 } else {
16579 $out .= '<input type="hidden" name="userid" value="' . $filterobj->id . '" />';
16580 }
16581
16582 $out .= "\n";
16583
16584 $out .= '<div class="div-table-responsive-no-min">';
16585 $out .= '<table class="noborder borderbottom centpercent">';
16586
16587 $out .= '<tr class="liste_titre">';
16588
16589 // Action column
16590 if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
16591 $out .= '<th class="liste_titre width50 middle">';
16592 $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1);
16593 $out .= $searchpicto;
16594 $out .= '</th>';
16595 }
16596
16597 // Date
16598 $out .= getTitleFieldOfList('Date', 0, $_SERVER["PHP_SELF"], 'a.datep', '', $param, '', $sortfield, $sortorder, 'nowraponall nopaddingleftimp ') . "\n";
16599
16600 $out .= '<th class="liste_titre hideonsmartphone"><strong class="hideonsmartphone">' . $langs->trans("Search") . ' : </strong></th>';
16601 if ($donetodo) {
16602 $out .= '<th class="liste_titre"></th>';
16603 }
16604 // Type of event
16605 $out .= '<th class="liste_titre">';
16606 $out .= '<span class="fas fa-square inline-block fawidth30 hideonsmartphone" style="color: #ddd;" title="' . $langs->trans("ActionType") . '"></span>';
16607 $out .= $formactions->select_type_actions($actioncode, "actioncode", '', getDolGlobalString('AGENDA_USE_EVENT_TYPE') ? -1 : 1, 0, 0, 1, 'selecttype minwidth100', $langs->trans("Type"));
16608 $out .= '</th>';
16609 // Label
16610 $out .= '<th class="liste_titre maxwidth100onsmartphone">';
16611 $out .= '<input type="text" class="maxwidth100onsmartphone" name="search_agenda_label" value="' . $filters['search_agenda_label'] . '" placeholder="' . $langs->trans("Label") . '">';
16612 $out .= '</th>';
16613
16614 // Action column
16615 if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
16616 $out .= '<th class="liste_titre width50 middle">';
16617 $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1);
16618 $out .= $searchpicto;
16619 $out .= '</th>';
16620 }
16621
16622 $out .= '</tr>';
16623
16624 $out .= '</table>';
16625
16626 $out .= '</form>';
16627 $out .= '</div>';
16628
16629 $out .= "\n";
16630
16631 $out .= '<ul class="timeline">';
16632
16633 if ($donetodo) {
16634 $tmp = '';
16635 if ($filterobj instanceof Societe) {
16636 $tmp .= '<a href="' . DOL_URL_ROOT . '/comm/action/list.php?mode=show_list&socid=' . $filterobj->id . '&status=done">';
16637 }
16638 if ($filterobj instanceof User) {
16639 $tmp .= '<a href="' . DOL_URL_ROOT . '/comm/action/list.php?mode=show_list&socid=' . $filterobj->id . '&status=done">';
16640 }
16641 $tmp .= ($donetodo != 'done' ? $langs->trans("ActionsToDoShort") : '');
16642 $tmp .= ($donetodo != 'done' && $donetodo != 'todo' ? ' / ' : '');
16643 $tmp .= ($donetodo != 'todo' ? $langs->trans("ActionsDoneShort") : '');
16644 //$out.=$langs->trans("ActionsToDoShort").' / '.$langs->trans("ActionsDoneShort");
16645 if ($filterobj instanceof Societe) {
16646 $tmp .= '</a>';
16647 }
16648 if ($filterobj instanceof User) {
16649 $tmp .= '</a>';
16650 }
16651 $out .= getTitleFieldOfList($tmp);
16652 }
16653
16654 require_once DOL_DOCUMENT_ROOT . '/comm/action/class/cactioncomm.class.php';
16655 $caction = new CActionComm($db);
16656 $arraylist = $caction->liste_array(1, 'code', '', (!getDolGlobalString('AGENDA_USE_EVENT_TYPE') ? 1 : 0), '', 1);
16657
16658 $actualCycleDate = false;
16659
16660 // Loop on each event to show it
16661 foreach ($histo as $key => $value) {
16662 $actionstatic->fetch($histo[$key]['id']); // TODO Do we need this, we already have a lot of data of line into $histo
16663
16664 $actionstatic->type_picto = $histo[$key]['apicto'];
16665 $actionstatic->type_code = $histo[$key]['acode'];
16666
16667 $labeltype = $actionstatic->type_code;
16668 if (!getDolGlobalString('AGENDA_USE_EVENT_TYPE') && empty($arraylist[$labeltype])) {
16669 $labeltype = 'AC_OTH';
16670 }
16671 if (!empty($actionstatic->code) && preg_match('/^TICKET_MSG/', $actionstatic->code)) {
16672 $labeltype = $langs->trans("Message");
16673 } else {
16674 if (!empty($arraylist[$labeltype])) {
16675 $labeltype = $arraylist[$labeltype];
16676 }
16677 if ($actionstatic->type_code == 'AC_OTH_AUTO' && ($actionstatic->type_code != $actionstatic->code) && $labeltype && !empty($arraylist[$actionstatic->code])) {
16678 $labeltype .= ' - ' . $arraylist[$actionstatic->code]; // Use code in priority on type_code
16679 }
16680 }
16681
16682 $url = DOL_URL_ROOT . '/comm/action/card.php?id=' . $histo[$key]['id'];
16683
16684 $tmpa = dol_getdate($histo[$key]['datestart'], false);
16685
16686 if (isset($tmpa['year']) && isset($tmpa['yday']) && $actualCycleDate !== $tmpa['year'] . '-' . $tmpa['yday']) {
16687 $actualCycleDate = $tmpa['year'] . '-' . $tmpa['yday'];
16688 $out .= '<!-- timeline time label -->';
16689 $out .= '<li class="time-label">';
16690 $out .= '<span class="timeline-badge-date">';
16691 $out .= dol_print_date($histo[$key]['datestart'], 'daytext', 'tzuserrel', $langs);
16692 $out .= '</span>';
16693 $out .= '</li>';
16694 $out .= '<!-- /.timeline-label -->';
16695 }
16696
16697
16698 $out .= '<!-- timeline item -->' . "\n";
16699 $out .= '<li class="timeline-code-' . (!empty($actionstatic->code) ? strtolower($actionstatic->code) : "none") . '">';
16700
16701 //$timelineicon = getTimelineIcon($actionstatic, $histo, $key);
16702 $typeicon = $actionstatic->getTypePicto('pictofixedwidth timeline-icon-not-applicble', $labeltype);
16703 //$out .= $timelineicon;
16704 //var_dump($timelineicon);
16705 $out .= $typeicon;
16706
16707 $out .= '<div class="timeline-item">' . "\n";
16708
16709 $out .= '<span class="time timeline-header-action2">';
16710
16711 if (isset($histo[$key]['type']) && $histo[$key]['type'] == 'mailing') {
16712 $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") . ' ';
16713 $out .= $histo[$key]['id'];
16714 $out .= '</a> ';
16715 } else {
16716 $out .= $actionstatic->getNomUrl(1, -1, 'valignmiddle') . ' ';
16717 }
16718
16719 if (
16720 $user->hasRight('agenda', 'allactions', 'create') ||
16721 (($actionstatic->authorid == $user->id || $actionstatic->userownerid == $user->id) && $user->hasRight('agenda', 'myactions', 'create'))
16722 ) {
16723 $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) . '">';
16724 //$out .= '<i class="fa fa-pencil" title="'.$langs->trans("Modify").'" ></i>';
16725 $out .= img_picto($langs->trans("Modify"), 'edit', 'class="edita"');
16726 $out .= '</a>';
16727 }
16728
16729 $out .= '</span>';
16730
16731 // Date
16732 $out .= '<span class="time"><i class="fa fa-clock valignmiddle"></i> ';
16733 $out .= '<span class="valignmiddle marginrightonly">';
16734 $out .= dol_print_date($histo[$key]['datestart'], 'day', 'tzuserrel');
16735 //$out .= '</span>';
16736 //$out .= '<span class="valignmiddle">'.
16737 $out .= ' '.dol_print_date($histo[$key]['datestart'], 'hour', 'tzuserrel', null, false, 'opacitymedium');
16738 //$out .= '</span>';
16739 if ($histo[$key]['dateend'] && $histo[$key]['dateend'] != $histo[$key]['datestart']) {
16740 $tmpa = dol_getdate($histo[$key]['datestart'], true);
16741 $tmpb = dol_getdate($histo[$key]['dateend'], true);
16742 if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year']) {
16743 $out .= ' - ' . dol_print_date($histo[$key]['dateend'], 'hour', 'tzuserrel', null, false, 1);
16744 } else {
16745 $out .= ' - ' . dol_print_date($histo[$key]['dateend'], 'day', 'tzuserrel');
16746 //$out .= '<span class="valignmiddle marginrightonly">';
16747 $out .= ' '.dol_print_date($histo[$key]['dateend'], 'hour', 'tzuserrel', null, false, 'opacitymedium');
16748 //$out .= '</span>';
16749 }
16750 }
16751 $late = 0;
16752 if ($histo[$key]['percent'] == 0 && $histo[$key]['datestart'] && $histo[$key]['datestart'] < ($now - $delay_warning)) {
16753 $late = 1;
16754 }
16755 if ($histo[$key]['percent'] == 0 && !$histo[$key]['datestart'] && $histo[$key]['dateend'] && $histo[$key]['datestart'] < ($now - $delay_warning)) {
16756 $late = 1;
16757 }
16758 if ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100 && $histo[$key]['dateend'] && $histo[$key]['dateend'] < ($now - $delay_warning)) {
16759 $late = 1;
16760 }
16761 if ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100 && !$histo[$key]['dateend'] && $histo[$key]['datestart'] && $histo[$key]['datestart'] < ($now - $delay_warning)) {
16762 $late = 1;
16763 }
16764 if ($late) {
16765 $out .= img_warning($langs->trans("Late")) . ' ';
16766 }
16767 $out .= "</span></span>\n";
16768
16769 $out .= '<span class="time">';
16770 $out .= $actionstatic->getLibStatut(2);
16771 $out .= '</span>';
16772
16773 // Ref
16774 $out .= '<h3 class="timeline-header">';
16775
16776 // Author of event
16777 $out .= '<div class="messaging-author inline-block tdoverflowmax150 valignmiddle marginrightonly">';
16778 if ($histo[$key]['userid'] > 0) {
16779 if (!isset($userGetNomUrlCache[$histo[$key]['userid']])) { // is in cache ?
16780 $userstatic->fetch($histo[$key]['userid']);
16781 $userGetNomUrlCache[$histo[$key]['userid']] = $userstatic->getNomUrl(-1, '', 0, 0, 16, 0, 'firstelselast', '');
16782 }
16783 $out .= $userGetNomUrlCache[$histo[$key]['userid']];
16784 } elseif (!empty($histo[$key]['msg_from']) && $actionstatic->code == 'TICKET_MSG') {
16785 if (!isset($contactGetNomUrlCache[$histo[$key]['msg_from']])) {
16786 if ($contactstatic->fetch(0, null, '', $histo[$key]['msg_from']) > 0) {
16787 $contactGetNomUrlCache[$histo[$key]['msg_from']] = $contactstatic->getNomUrl(-1, '', 16);
16788 } else {
16789 $contactGetNomUrlCache[$histo[$key]['msg_from']] = $histo[$key]['msg_from'];
16790 }
16791 }
16792 $out .= $contactGetNomUrlCache[$histo[$key]['msg_from']];
16793 } else {
16794 $out .= '<img class="photomemberphoto userphoto" alt="" src="/public/theme/common/user_anonymous.png">'.$langs->trans("Anonymous");
16795 }
16796 $out .= '</div>';
16797
16798 // Title
16799 $out .= ' <div class="messaging-title inline-block">';
16800 //$out .= $actionstatic->getTypePicto(); // The type of event is already into the timeline on left.
16801 if (empty($conf->dol_optimize_smallscreen) && $actionstatic->type_code != 'AC_OTH_AUTO') {
16802 $out .= $labeltype . ' - ';
16803 }
16804
16805 $libelle = '';
16806
16807 if (!empty($actionstatic->code) && preg_match('/^TICKET_MSG_PRIVATE/', $actionstatic->code)) {
16808 $out .= $langs->trans('TicketNewMessage').' <em>('.$langs->trans('Private').')</em>';
16809 } elseif (!empty($actionstatic->code) && preg_match('/^TICKET_MSG/', $actionstatic->code)) {
16810 $out .= $langs->trans('TicketNewMessage');
16811 } elseif (isset($histo[$key]['type'])) {
16812 if ($histo[$key]['type'] == 'action') {
16813 $transcode = $langs->transnoentitiesnoconv("Action" . $histo[$key]['acode']);
16814 $libelle = ($transcode != "Action" . $histo[$key]['acode'] ? $transcode : $histo[$key]['alabel']);
16815 $libelle = $histo[$key]['note'];
16816 $actionstatic->id = $histo[$key]['id'];
16817 if ($libelle != $labeltype) {
16818 $out .= dol_escape_htmltag(dol_trunc($libelle, 120));
16819 }
16820 } elseif ($histo[$key]['type'] == 'mailing') {
16821 $out .= '<a href="' . DOL_URL_ROOT . '/comm/mailing/card.php?id=' . $histo[$key]['id'] . '">' . img_object($langs->trans("ShowEMailing"), "email") . ' ';
16822 $transcode = $langs->transnoentitiesnoconv("Action" . $histo[$key]['acode']);
16823 $libelle = ($transcode != "Action" . $histo[$key]['acode'] ? $transcode : 'Send mass mailing');
16824 $out .= dol_escape_htmltag(dol_trunc($libelle, 120));
16825 } else {
16826 $libelle .= $histo[$key]['note'];
16827 $out .= dol_escape_htmltag(dol_trunc($libelle, 120));
16828 }
16829 }
16830 $out = preg_replace('/ - $/', '', $out); // Remove ending ' - '
16831
16832 if (isset($histo[$key]['elementtype']) && !empty($histo[$key]['fk_element'])) {
16833 if (isset($conf->cache['elementlinkcache'][$histo[$key]['elementtype']]) && isset($conf->cache['elementlinkcache'][$histo[$key]['elementtype']][$histo[$key]['fk_element']])) {
16834 $link = $conf->cache['elementlinkcache'][$histo[$key]['elementtype']][$histo[$key]['fk_element']];
16835 } else {
16836 if (!isset($conf->cache['elementlinkcache'][$histo[$key]['elementtype']])) {
16837 $conf->cache['elementlinkcache'][$histo[$key]['elementtype']] = array();
16838 }
16839 $link = dolGetElementUrl($histo[$key]['fk_element'], $histo[$key]['elementtype'], 1);
16840 $conf->cache['elementlinkcache'][$histo[$key]['elementtype']][$histo[$key]['fk_element']] = $link;
16841 }
16842 if ($link) {
16843 $out .= ' - ' . $link;
16844 }
16845 }
16846
16847 $out .= '</div>';
16848
16849 $out .= '</h3>';
16850
16851 // Message
16852 if (
16853 !empty($histo[$key]['message'] && $histo[$key]['message'] != $libelle)
16854 && $actionstatic->code != 'AC_TICKET_CREATE'
16855 && $actionstatic->code != 'AC_TICKET_MODIFY'
16856 ) {
16857 $out .= '<div class="timeline-body wordbreak small">';
16858 $truncateLines = getDolGlobalInt('MAIN_TRUNCATE_TIMELINE_MESSAGE', 3);
16859 $newmess = dol_htmlentitiesbr($histo[$key]['message']);
16860 $truncatedText = dolGetFirstLineOfText($newmess, $truncateLines);
16861 // dolGetFirstLineOfText() cuts on <br> without caring about tag balance, so a message wrapped in
16862 // a block tag leaves the excerpt with an unclosed tag. The browser then nests the read more link
16863 // and the full text inside the excerpt, and hiding the excerpt hides the whole message (#39035).
16864 $truncatedText = dolCloseUnclosedHtmlTags($truncatedText);
16865 if ($truncateLines > 0 && strlen($newmess) > strlen($truncatedText)) {
16866 $out .= '<div class="readmore-block --closed" >';
16867 $out .= ' <div class="readmore-block__excerpt">';
16868 $out .= dolPrintHTML($truncatedText);
16869 $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>';
16870 $out .= ' </div>';
16871 $out .= ' <div class="readmore-block__full-text" >';
16872 $out .= dolPrintHTML($newmess);
16873 $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>';
16874 $out .= ' </div>';
16875 $out .= '</div>';
16876 } else {
16877 $out .= dolPrintHTML($newmess);
16878 }
16879
16880 $out .= '</div>';
16881 }
16882
16883 // Timeline footer
16884 $footer = '';
16885
16886 // Contact for this action
16887 if (isset($histo[$key]['socpeopleassigned']) && is_array($histo[$key]['socpeopleassigned']) && count($histo[$key]['socpeopleassigned']) > 0) {
16888 $contactList = '';
16889 foreach ($histo[$key]['socpeopleassigned'] as $cid => $Tab) {
16890 if (empty($conf->cache['contact'][$cid])) {
16891 $contact = new Contact($db);
16892 $contact->fetch($cid);
16893 $conf->cache['contact'][$cid] = $contact;
16894 } else {
16895 $contact = $conf->cache['contact'][$cid];
16896 }
16897
16898 if ($contact) {
16899 $contactList .= !empty($contactList) ? ', ' : '';
16900 $contactList .= $contact->getNomUrl(1);
16901 if (isset($histo[$key]['acode']) && $histo[$key]['acode'] == 'AC_TEL') {
16902 if (!empty($contact->phone_pro)) {
16903 $contactList .= '(' . dol_print_phone($contact->phone_pro) . ')';
16904 }
16905 }
16906 }
16907 }
16908
16909 $footer .= $langs->trans('ActionOnContact') . ' : ' . $contactList;
16910 } elseif (empty($objcon->id) && isset($histo[$key]['contact_id']) && $histo[$key]['contact_id'] > 0) {
16911 if (empty($conf->cache['contact'][$histo[$key]['contact_id']])) {
16912 $contact = new Contact($db);
16913 $result = $contact->fetch($histo[$key]['contact_id']);
16914 $conf->cache['contact'][$histo[$key]['contact_id']] = $contact;
16915 } else {
16916 $contact = $conf->cache['contact'][$histo[$key]['contact_id']];
16917 $result = ($contact instanceof Contact) ? $contact->id : 0;
16918 }
16919
16920 if ($result > 0) {
16921 $footer .= $contact->getNomUrl(1);
16922 if (isset($histo[$key]['acode']) && $histo[$key]['acode'] == 'AC_TEL') {
16923 if (!empty($contact->phone_pro)) {
16924 $footer .= '(' . dol_print_phone($contact->phone_pro) . ')';
16925 }
16926 }
16927 }
16928 }
16929
16930 $documents = getActionCommEcmList($actionstatic);
16931 if (!empty($documents)) {
16932 $footer .= '<div class="timeline-documents-container">';
16933 foreach ($documents as $doc) {
16934 $footer .= '<span id="document_' . $doc->id . '" class="timeline-documents" ';
16935 $footer .= ' data-id="' . $doc->id . '" ';
16936 $footer .= ' data-path="' . $doc->filepath . '"';
16937 $footer .= ' data-filename="' . dol_escape_htmltag($doc->filename) . '" ';
16938 $footer .= '>';
16939
16940 $filePath = DOL_DATA_ROOT . '/' . $doc->filepath . '/' . $doc->filename;
16941 $mime = dol_mimetype($filePath);
16942 if (empty($doc->agenda_id)) {
16943 $dir_ref = $actionstatic->id;
16944 $modulepart = 'actions';
16945 } else {
16946 $split_dir = explode('/', $doc->filepath);
16947 $modulepart = array_shift($split_dir);
16948 $dir_ref = implode('/', $split_dir);
16949 }
16950
16951 $file = $dir_ref . '/' . $doc->filename;
16952 $thumb = $dir_ref . '/thumbs/' . substr($doc->filename, 0, strrpos($doc->filename, '.')) . '_mini' . substr($doc->filename, strrpos($doc->filename, '.'));
16953 $doclink = dol_buildpath('document.php', 1) . '?modulepart=' . $modulepart . '&attachment=0&file=' . urlencode($file) . '&entity=' . $conf->entity;
16954 $viewlink = dol_buildpath('viewimage.php', 1) . '?modulepart=' . $modulepart . '&file=' . urlencode($thumb) . '&entity=' . $conf->entity;
16955
16956
16957
16958 $mimeAttr = ' mime="' . $mime . '" ';
16959 $class = '';
16960 if (in_array($mime, array('image/png', 'image/jpeg', 'application/pdf'))) {
16961 $class .= ' documentpreview';
16962 }
16963
16964 $footer .= '<a href="' . $doclink . '" class="btn-link ' . $class . '" target="_blank" rel="noopener noreferrer" ' . $mimeAttr . ' >';
16965 $footer .= img_mime($filePath) . ' ' . $doc->filename;
16966 $footer .= '</a>';
16967
16968 $footer .= '</span>';
16969 }
16970 $footer .= '</div>';
16971 }
16972
16973 if (!empty($footer)) {
16974 $out .= '<div class="timeline-footer">' . $footer . '</div>';
16975 }
16976
16977 $out .= '</div>' . "\n"; // end timeline-item
16978
16979 $out .= '</li>';
16980 $out .= '<!-- END timeline item -->';
16981 }
16982
16983 $out .= "</ul>\n";
16984
16985 // Code to manage the click on button data-read-more-action to show full description of an event
16986 $out .= '<script>
16987 jQuery(document).ready(function () {
16988 $(document).on("click", "[data-read-more-action]", function(e){
16989 console.log("We click on data-read-more-action");
16990 let readMoreBloc = $(this).closest(".readmore-block");
16991 if(readMoreBloc.length > 0){
16992 e.preventDefault();
16993 if($(this).attr("data-read-more-action") == "close"){
16994 readMoreBloc.addClass("--closed").removeClass("--open");
16995 $("html, body").animate({
16996 scrollTop: readMoreBloc.offset().top - 200
16997 }, 100);
16998 }else{
16999 readMoreBloc.addClass("--open").removeClass("--closed");
17000 }
17001 }
17002 });
17003 });
17004 </script>';
17005
17006
17007 if (empty($histo)) {
17008 $out .= '<span class="opacitymedium">' . $langs->trans("NoRecordFound") . '</span>';
17009 }
17010
17011 if ($num > $MAXWITHOUTPAGINATION) {
17012 $langs->load("errors");
17013 $colspan = 9;
17014 $out .= '<center><span class="opacitymedium">...' . $langs->trans("WarningTooManyDataPleaseUseMoreFilters", $MAXWITHOUTPAGINATION) . '...</span></center>';
17015 }
17016 }
17017
17018 if ($noprint) {
17019 return $out;
17020 } else {
17021 print $out;
17022 return null;
17023 }
17024}
17025
17037function buildParamDate($prefix, $timestamp = null, $hourTime = '', $gm = 'auto')
17038{
17039 if ($timestamp === null) {
17040 $timestamp = GETPOSTDATE($prefix, $hourTime, $gm);
17041 }
17042 $TParam = array(
17043 $prefix . 'day' => intval(dol_print_date($timestamp, '%d')),
17044 $prefix . 'month' => intval(dol_print_date($timestamp, '%m')),
17045 $prefix . 'year' => intval(dol_print_date($timestamp, '%Y')),
17046 );
17047 if ($hourTime === 'getpost' || ($timestamp !== null && dol_print_date($timestamp, '%H:%M:%S') !== '00:00:00')) {
17048 $TParam = array_merge($TParam, array(
17049 $prefix . 'hour' => intval(dol_print_date($timestamp, '%H')),
17050 $prefix . 'min' => intval(dol_print_date($timestamp, '%M')),
17051 $prefix . 'sec' => intval(dol_print_date($timestamp, '%S'))
17052 ));
17053 }
17054
17055 return '&' . http_build_query($TParam);
17056}
17057
17076function recordNotFound($message = '', $printheader = 1, $printfooter = 1, $showonlymessage = 0, $params = null)
17077{
17078 global $conf, $db, $langs, $hookmanager;
17079 global $action, $object;
17080
17081 if (!is_object($langs)) {
17082 include_once DOL_DOCUMENT_ROOT . '/core/class/translate.class.php';
17083 $langs = new Translate('', $conf);
17084 $langs->setDefaultLang();
17085 }
17086
17087 $langs->load("errors");
17088
17089 if ($printheader) {
17090 if (function_exists("llxHeader")) {
17091 llxHeader('');
17092 } elseif (function_exists("llxHeaderVierge")) {
17093 llxHeaderVierge('');
17094 }
17095 }
17096
17097 print '<div class="error">';
17098 if (empty($message)) {
17099 print $langs->trans("ErrorRecordNotFound");
17100 } else {
17101 print $langs->trans($message);
17102 }
17103 print '</div>';
17104 print '<br>';
17105
17106 if (empty($showonlymessage)) {
17107 if (empty($hookmanager)) {
17108 include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
17109 $hookmanager = new HookManager($db);
17110 // Initialize a technical object to manage hooks of page. Note that conf->hooks_modules contains an array of hook context
17111 $hookmanager->initHooks(array('main'));
17112 }
17113
17114 $parameters = array('message' => $message, 'params' => $params);
17115 $reshook = $hookmanager->executeHooks('getErrorRecordNotFound', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
17116 print $hookmanager->resPrint;
17117 }
17118
17119 if ($printfooter && function_exists("llxFooter")) {
17120 llxFooter();
17121 if (is_object($db)) {
17122 $db->close();
17123 }
17124 }
17125 exit(0);
17126}
17127
17156function array_merge_recursive_distinct(array $array1, array $array2): array
17157{
17158 $merged = $array1;
17159
17160 foreach ($array2 as $key => $value) {
17161 if (is_array($value) && isset($merged[$key]) && is_array($merged[$key])) {
17162 $merged[$key] = array_merge_recursive_distinct($merged[$key], $value);
17163 } else {
17164 $merged[$key] = $value;
17165 }
17166 }
17167
17168 return $merged;
17169}
17170
17177function getObjectSocId($obj)
17178{
17179 if (!empty($obj->socid)) {
17180 return (int) $obj->socid;
17181 } elseif (!empty($obj->soc_id)) {
17182 return (int) $obj->soc_id;
17183 } elseif (!empty($obj->societe_id)) {
17184 return (int) $obj->societe_id;
17185 }
17186 return null;
17187}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
global $dolibarr_main_url_root
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='', $readonly=0)
On/off button to change a property status of an object This uses the ajax service objectonoff....
Definition ajax.lib.php:793
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.
static getValidAddress($address, $format, $encode=0, $maxnumberofemail=0)
Return a formatted address string for SMTP protocol.
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...)
isACompany()
Check if third party is a company (Business) or an end user (Consumer)
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)
global $mysoc
dol_get_prev_month($month, $year)
Return previous month.
Definition date.lib.php:537
dol_get_next_day($day, $month, $year)
Return next day.
Definition date.lib.php:522
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:506
dol_get_next_month($month, $year)
Return next month.
Definition date.lib.php:556
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:64
dol_is_dir($folder)
Test if filename is a directory.
dolGetElementUrl($objectid, $objecttype, $withpicto=0, $option='')
Return link url to an object.
isValidMailDomain($mail)
Return true if email has a domain name that can be resolved to MX type.
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_now($mode='gmt')
Return date for now.
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...
dol_print_email($email, $contactid=0, $socid=0, $addlink=0, $max=0, $showinvalid=2, $withpicto=0, $morecss='paddingrightonly')
Show EMail link formatted for HTML output.
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.
dol_getmypid()
Return getmypid() or random PID when function is disabled Some web hosts disable this php function fo...
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.
img_credit_card($brand, $morecss='fa-2x inline-block valignmiddle')
Return image of a credit card according to its brand name.
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.
dol_print_phone($phone, $countrycode='', $contactid=0, $socid=0, $addlink='', $separ="&nbsp;", $withpicto='', $titlealt='', $adddivfloat=0, $morecss='paddingright')
Format phone numbers according to country.
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.
dolBuildUrl($url, $params=[], $addtoken=false)
Return path of url.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
getObjectSocId($obj)
Get the socid of an object, supporting legacy attribute names.
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.
getDolEntity()
Return the current entity.
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.
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-...
dol_sanitizePathName($str, $newstr='_', $unaccent=0, $allowdash=0)
Clean a string to use it as a path name.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
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.
getDolOptimizeSmallScreen()
Return if render must be optimized for small screen.
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.
jsonOrUnserialize($stringtodecode, $assoc=true)
Decode an encoded string.
dol_print_socialnetworks($value, $contactid, $socid, $type, $dictsocialnetworks=array())
Show social network link.
dolChmod($filepath, $newmask='')
Change mod of a file.
dol_fiche_head($links=array(), $active='0', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='')
Show tab header of a card.
natural_search($fields, $value, $mode=0, $nofirstand=0, $sqltoadd='')
Generate natural SQL search string for a criteria (this criteria can be tested on one or several fiel...
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_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)
GETPOSTFLOAT($paramname, $rounding='', $option=2)
Return the value of a $_GET or $_POST supervariable, converted into float.
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.
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_clone_in_array($srcobject, $startlevel=0)
Create a clone of instance of object into a full array, using recursive call.
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 ...
getDolCurrency()
Return the main currency ('EUR', 'USD', ...)
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.
getDolDefaultContextPage($s)
Return the default context page string.
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.
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)
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.
getDolDBType()
Return the current entity.
print_titre($title)
Show a title.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_clone($srcobject, $native=2)
Create a clone of instance of object (new instance with same value for each properties) With native =...
dol_string_nounprintableascii($str, $removetabcrlf=1)
Clean a string from all non printable ASCII chars (0x00-0x1F and 0x7F).
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
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).
dolCloseUnclosedHtmlTags($text)
Close the HTML tags left open in a truncated HTML string.
get_product_localtax_for_country($idprod, $local, $thirdpartytouseforcountry)
Return localtax vat rate of a product in a particular country or default country vat if product is un...
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.
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='', $morecssonpicto='widthpictotitle')
Load a title with picto.
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 start with $regextext.
dolSlugify($stringtoslugify)
Returns text slugified (lowercase and no special char, separator is "-").
dol_concat($text1, $text2)
Concat 2 strings.
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...
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.
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.
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.
isModEnabled($module)
Is Dolibarr module enabled.
array_merge_recursive_distinct(array $array1, array $array2)
Recursively merges two arrays while preserving keys and replacing existing values.
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 rate, when selling a product with vat $vatrate,...
dol_eval_standard($s, $hideerrors=1, $onlysimplestring='1')
Replace eval function to add more security.
get_product_vat_for_country($idprod, $thirdpartytouseforcountry, $idprodfournprice=0)
Return vat rate of a product in a particular country, or default country vat if product is unknown.
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.
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.
multi select button
0 = Do not include form tag and submit button -1 = Do not include form tag but include submit button
treeview li table
No Email.
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.
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.
measuringUnitString($unitid, $measuring_style='', $unitscale=null, $use_short_label=0, $outputlangs=null)
Return translation label of a unit key.
if(preg_match('/(crypted|dolcrypt):/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition repair.php:132
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:135
realCharForNumericEntities($matches)
Return the real char for a numeric entities.
Definition waf.inc.php:66