dolibarr 24.0.3
functions.lib.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2000-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2003 Jean-Louis Bergamo <jlb@j1b.org>
4 * Copyright (C) 2004-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-2026 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-2026 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 * Copyright (C) 2026 Pierre Ardoin <developpeur@lesmetiersdubatiment.fr>
31 *
32 * This program is free software; you can redistribute it and/or modify
33 * it under the terms of the GNU General Public License as published by
34 * the Free Software Foundation; either version 3 of the License, or
35 * (at your option) any later version.
36 *
37 * This program is distributed in the hope that it will be useful,
38 * but WITHOUT ANY WARRANTY; without even the implied warranty of
39 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
40 * GNU General Public License for more details.
41 *
42 * You should have received a copy of the GNU General Public License
43 * along with this program. If not, see <https://www.gnu.org/licenses/>.
44 * or see https://www.gnu.org/
45 */
46
53//include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
54
55// Function for better PHP x compatibility
56if (!function_exists('utf8_encode')) {
64 function utf8_encode($elements)
65 {
66 return mb_convert_encoding($elements, 'UTF-8', 'ISO-8859-1');
67 }
68}
69
70if (!function_exists('utf8_decode')) {
78 function utf8_decode($elements)
79 {
80 return mb_convert_encoding($elements, 'ISO-8859-1', 'UTF-8');
81 }
82}
83if (!function_exists('str_starts_with')) {
92 function str_starts_with($haystack, $needle)
93 {
94 return (string) $needle !== '' && strncmp($haystack, $needle, strlen($needle)) === 0;
95 }
96}
97if (!function_exists('str_ends_with')) {
106 function str_ends_with($haystack, $needle)
107 {
108 return $needle !== '' && substr($haystack, -strlen($needle)) === (string) $needle;
109 }
110}
111if (!function_exists('str_contains')) {
120 function str_contains($haystack, $needle)
121 {
122 return $needle !== '' && mb_strpos($haystack, $needle) !== false;
123 }
124}
125
126
134function formatLogObject($data)
135{
136 if (getDolGlobalInt("MAIN_LOG_ON_ONE_LINE")) {
137 return json_encode($data);
138 }
139
140 return var_export($data, true);
141}
142
143
155function getMultidirOutput($object, $module = '', $forobject = 0, $mode = 'output')
156{
157 global $conf;
158
159 $subdirectory = '';
160 if (!is_object($object) && empty($module)) {
161 return null;
162 }
163 if (empty($module) && !empty($object->element)) {
164 $module = $object->element;
165 }
166
167 // Special case for backward compatibility
168 switch ($module) {
169 case 'fichinter':
170 $module = 'ficheinter';
171 break;
172 case 'invoice_supplier':
173 $module = 'supplier_invoice';
174 break;
175 case 'order_supplier':
176 $module = 'supplier_order';
177 break;
178 case 'recruitmentjobposition':
179 $module = 'recruitment';
180 $subdirectory = '/recruitmentjobposition';
181 break;
182 case 'recruitmentcandidature':
183 $module = 'recruitment';
184 $subdirectory = '/recruitmentcandidature';
185 break;
186 case 'knowledgerecord':
187 $module = 'knowledgemanagement';
188 $subdirectory = '/knowledgerecord';
189 break;
190 case 'commande_fournisseur':
191 $module = 'fournisseur';
192 $subdirectory = '/commande';
193 break;
194 case 'expedition':
195 case 'shipment':
196 case 'shipping':
197 $module = 'expedition';
198 $subdirectory = '/sending';
199 break;
200 case 'company':
201 $module = 'societe';
202 break;
203 case 'service':
204 case 'produit':
205 $module = 'product';
206 break;
207 case 'project_task':
208 $module = 'projet';
209
210 // Fetch the project to build the correct path
211 $object->fetchProject();
212
213 $subdirectory = '/'.$object->project->ref;
214 break;
215 case 'action':
216 case 'actioncomm':
217 case 'event':
218 $module = 'agenda';
219 break;
220 default:
221 break;
222 }
223
224 // Get the relative path of directory
225 if ($mode == 'output' || $mode == 'outputrel' || $mode == 'version') {
226 if (isset($conf->$module) && property_exists($conf->$module, 'multidir_output')) {
227 $s = '';
228 if ($mode != 'outputrel') {
229 // An entity with no declared directory returned an undefined index, so an empty path that
230 // made the caller read or write a relative path under the web root. Answer the error instead.
231 $entity = (int) (empty($object->entity) ? $conf->entity : $object->entity);
232 if (!isset($conf->$module->multidir_output[$entity])) {
233 return 'error-diroutput-not-defined-for-this-entity-and-object='.$module;
234 }
235 $s = $conf->$module->multidir_output[$entity] . $subdirectory;
236 }
237 if ($forobject && $object->id > 0) {
238 $s .= ($mode != 'outputrel' ? '/' : '') . get_exdir(0, 0, 0, 0, $object);
239 }
240 return dol_sanitizePathName($s);
241 } elseif (isset($conf->$module) && property_exists($conf->$module, 'dir_output')) {
242 $s = '';
243 if ($mode != 'outputrel') {
244 $s = $conf->$module->dir_output . $subdirectory;
245 }
246 if ($forobject && $object->id > 0) {
247 $s .= ($mode != 'outputrel' ? '/' : '') . get_exdir(0, 0, 0, 0, $object);
248 }
249 return dol_sanitizePathName($s);
250 } else {
251 return 'error-diroutput-not-defined-for-this-entity-and-object='.$module;
252 }
253 } elseif ($mode == 'temp') {
254 if (isset($conf->$module) && property_exists($conf->$module, 'multidir_temp')) {
255 // Same guard as the 'output' mode above, see the comment there
256 $entity = (int) (empty($object->entity) ? $conf->entity : $object->entity);
257 if (!isset($conf->$module->multidir_temp[$entity])) {
258 return 'error-dirtemp-not-defined-for-this-entity-and-object='.$module;
259 }
260 return dol_sanitizePathName($conf->$module->multidir_temp[$entity]);
261 } elseif (isset($conf->$module) && property_exists($conf->$module, 'dir_temp')) {
262 return dol_sanitizePathName($conf->$module->dir_temp);
263 } else {
264 return 'error-dirtemp-not-defined-for-this-entity-and-object='.$module;
265 }
266 } else {
267 return 'error-bad-value-for-mode';
268 }
269}
270
280function getMultidirTemp($object, $module = '', $forobject = 0)
281{
282 return getMultidirOutput($object, $module, $forobject, 'temp');
283}
284
294function getMultidirVersion($object, $module = '', $forobject = 0)
295{
296 return getMultidirOutput($object, $module, $forobject, 'version');
297}
298
299
308function getDolGlobalString($key, $default = '')
309{
310 global $conf;
311 return (string) (isset($conf->global->$key) ? $conf->global->$key : $default);
312}
313
320{
321 global $dolibarr_login_badcharunauthorized;
322
323 if (isset($dolibarr_login_badcharunauthorized)) {
324 if ($dolibarr_login_badcharunauthorized === 'MAIN_LOGIN_BADCHARUNAUTHORIZED') {
325 return getDolGlobalString('MAIN_LOGIN_BADCHARUNAUTHORIZED', ',@<>"\'');
326 }
327
328 return (string) $dolibarr_login_badcharunauthorized;
329 }
330
331 return ',@<>"\'';
332}
333
343function getDolGlobalInt($key, $default = 0)
344{
345 global $conf;
346 return (int) (isset($conf->global->$key) ? $conf->global->$key : $default);
347}
348
358function getDolGlobalFloat($key, $default = 0)
359{
360 global $conf;
361 return (float) (isset($conf->global->$key) ? $conf->global->$key : $default);
362}
363
372function getDolGlobalBool($key, $default = false)
373{
374 global $conf;
375 return (bool) ($conf->global->$key ?? $default);
376}
377
384{
385 global $conf;
386 return (string) $conf->currency;
387}
388
395{
396 global $conf;
397 return (string) $conf->dol_optimize_smallscreen;
398}
399
405function getDolEntity()
406{
407 global $conf;
408 return (int) $conf->entity;
409}
410
416function getDolDBType()
417{
418 global $conf;
419 return $conf->db->type;
420}
421
429{
430 return str_replace('_', '', basename(dirname($s)).basename($s, '.php'));
431}
432
442function getDolUserString($key, $default = '', $tmpuser = null)
443{
444 if (empty($tmpuser)) {
445 global $user;
446 $tmpuser = $user;
447 }
448
449 return (string) (isset($tmpuser->conf->$key) ? $tmpuser->conf->$key : $default);
450}
451
460function getDolUserInt($key, $default = 0, $tmpuser = null)
461{
462 if (empty($tmpuser)) {
463 global $user;
464 $tmpuser = $user;
465 }
466
467 return (int) (isset($tmpuser->conf->$key) ? $tmpuser->conf->$key : $default);
468}
469
470
479define(
480 'MODULE_MAPPING',
481 array(
482 // Map deprecated names to new names
483 'adherent' => 'member', // Has new directory
484 'member_type' => 'adherent_type', // No directory, but file called adherent_type
485 'banque' => 'bank', // Has new directory
486 'contrat' => 'contract', // Has new directory
487 'entrepot' => 'stock', // Has new directory
488 'projet' => 'project', // Has new directory
489 'categorie' => 'category', // Has old directory
490 'commande' => 'order', // Has old directory
491 'expedition' => 'shipping', // Has old directory
492 'facture' => 'invoice', // Has old directory
493 'fichinter' => 'intervention', // Has old directory
494 'ficheinter' => 'intervention', // Backup for 'fichinter'
495 'propale' => 'propal', // Has old directory
496 'societe' => 'thirdparty', // Has old directory
497 'socpeople' => 'contact', // Has old directory
498 'fournisseur' => 'supplier', // Has old directory
499
500 'actioncomm' => 'agenda', // NO module directory (public dir agenda)
501 'product_price' => 'productprice', // NO directory
502 'product_fournisseur_price' => 'productsupplierprice', // NO directory
503 )
504);
505
512function isModEnabled($module)
513{
514 global $conf;
515
516 // Fix old names (map to new names)
517 $arrayconv = MODULE_MAPPING;
518 $arrayconvbis = array_flip(MODULE_MAPPING);
519
520 if (!getDolGlobalString('MAIN_USE_NEW_SUPPLIERMOD')) {
521 // Special cases: both use the same module.
522 $arrayconv['supplier_order'] = 'fournisseur';
523 $arrayconv['supplier_invoice'] = 'fournisseur';
524 }
525
526 $module_alt = $module;
527 if (!empty($arrayconv[$module])) {
528 $module_alt = $arrayconv[$module];
529 }
530 $module_bis = $module;
531 if (!empty($arrayconvbis[$module])) {
532 $module_bis = $arrayconvbis[$module];
533 }
534
535 return !empty($conf->modules[$module]) || !empty($conf->modules[$module_alt]) || !empty($conf->modules[$module_bis]);
536}
537
548function getWarningDelay($module, $parmlevel1, $parmlevel2 = '')
549{
550 global $conf;
551
552 // For compatibility with bad naming on module
553 $moduletomoduletouse = array(
554 'invoice' => 'facture',
555 );
556 $moduleParmsMapping = array(
557 'product' => 'produit',
558 );
559
560 if (!empty($moduletomoduletouse[$module])) {
561 $module = $moduletomoduletouse[$module];
562 }
563
564 $warningDelayPath = $parmlevel1;
565 if (!empty($moduleParmsMapping[$warningDelayPath])) {
566 $warningDelayPath = $moduleParmsMapping[$warningDelayPath];
567 }
568
569 if ($parmlevel2) {
570 if (!empty($conf->$module) && !empty($conf->$module->$warningDelayPath) && !empty($conf->$module->$warningDelayPath->$parmlevel2) && !empty($conf->$module->$warningDelayPath->$parmlevel2->warning_delay)) {
571 return (int) $conf->$module->$warningDelayPath->$parmlevel2->warning_delay;
572 }
573 } else {
574 if (!empty($conf->$module) && !empty($conf->$module->$warningDelayPath) && !empty($conf->$module->$warningDelayPath->warning_delay)) {
575 return (int) $conf->$module->$warningDelayPath->warning_delay;
576 }
577 }
578
579 return 0;
580}
581
588function isDolTms($timestamp)
589{
590 if ($timestamp === '') {
591 dol_syslog('Using empty string for a timestamp is deprecated, prefer use of null when calling page ' . $_SERVER["PHP_SELF"] . getCallerInfoString(), LOG_DEBUG);
592 return false;
593 }
594 if (is_null($timestamp) || !is_numeric($timestamp)) {
595 return false;
596 }
597
598 return true;
599}
600
612function getDoliDBInstance($type, $host, $user, $pass, $name, $port)
613{
614 require_once DOL_DOCUMENT_ROOT . "/core/db/" . $type . '.class.php';
615
616 $class = 'DoliDB' . ucfirst($type);
617 $db = new $class($type, $host, $user, $pass, $name, $port);
618 return $db;
619}
620
638function getEntity($element, $shared = 1, $currentobject = null)
639{
640 global $conf, $mc, $hookmanager, $object, $action, $db;
641
642 if (!is_object($hookmanager)) {
643 include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
644 $hookmanager = new HookManager($db);
645 }
646
647 // fix different element names (France to English)
648 switch ($element) {
649 case 'projet':
650 $element = 'project';
651 break;
652 case 'contrat':
653 $element = 'contract';
654 break; // "/contrat/class/contrat.class.php"
655 case 'order_supplier':
656 $element = 'supplier_order';
657 break; // "/fourn/class/fournisseur.commande.class.php"
658 case 'invoice_supplier':
659 $element = 'supplier_invoice';
660 break; // "/fourn/class/fournisseur.facture.class.php"
661 }
662
663 if (is_object($mc)) {
664 $out = $mc->getEntity($element, $shared, $currentobject);
665 } else {
666 $out = '';
667 $addzero = array('user', 'usergroup', 'cronjob', 'c_email_templates', 'email_template', 'default_values', 'overwrite_trans', 'extrafields');
668 if (getDolGlobalString('HOLIDAY_ALLOW_ZERO_IN_DIC')) { // this constant break the dictionary admin without Multicompany
669 $addzero[] = 'c_holiday_types';
670 }
671 if (in_array($element, $addzero)) {
672 $out .= '0,';
673 }
674 $out .= ((int) $conf->entity);
675 }
676
677 // Manipulate entities to query on the fly
678 $parameters = array(
679 'element' => $element,
680 'shared' => $shared,
681 'object' => $object,
682 'currentobject' => $currentobject,
683 'out' => $out
684 );
685 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable
686 $reshook = $hookmanager->executeHooks('hookGetEntity', $parameters, $currentobject, $action); // Note that $action and $object may have been modified by some hooks
687
688 if (is_numeric($reshook)) {
689 if ($reshook == 0 && !empty($hookmanager->resPrint)) {
690 $out .= ',' . $hookmanager->resPrint; // add
691 } elseif ($reshook == 1) {
692 $out = $hookmanager->resPrint; // replace
693 }
694 }
695
696 return $out;
697}
698
705function setEntity($currentobject)
706{
707 global $conf, $mc;
708
709 if (is_object($mc) && method_exists($mc, 'setEntity')) {
710 return $mc->setEntity($currentobject);
711 } else {
712 return ((is_object($currentobject) && $currentobject->id > 0 && ((int) $currentobject->entity) > 0) ? (int) $currentobject->entity : $conf->entity);
713 }
714}
715
722function isASecretKey($keyname)
723{
724 return preg_match('/(_pass|password|_pw|_key|securekey|serverkey|secret\d?|p12key|exportkey|_PW_[a-z]+|token)$/i', $keyname);
725}
726
727
734function num2Alpha($n)
735{
736 $r = '';
737 for ($r = ""; $n >= 0; $n = intval($n / 26) - 1) {
738 $r = chr($n % 26 + 0x41) . $r;
739 }
740 return $r;
741}
742
743
760function getBrowserInfo($user_agent)
761{
762 include_once DOL_DOCUMENT_ROOT . '/includes/mobiledetect/mobiledetectlib/Mobile_Detect.php';
763
764 $name = 'unknown';
765 $version = '';
766 $os = 'unknown';
767 $phone = '';
768
769 $user_agent = substr($user_agent, 0, 512); // Avoid to process too large user agent
770
771 // @phan-suppress-next-line PhanTypeMismatchArgumentProbablyReal Bad definition of Mobile_Detect function
772 $detectmobile = new Mobile_Detect(null, $user_agent);
773 $tablet = $detectmobile->isTablet();
774
775 if ($detectmobile->isMobile()) {
776 $phone = 'unknown';
777
778 // If phone/smartphone, we set phone os name.
779 if ($detectmobile->is('AndroidOS')) {
780 $os = $phone = 'android';
781 } elseif ($detectmobile->is('BlackBerryOS')) {
782 $os = $phone = 'blackberry';
783 } elseif ($detectmobile->is('iOS')) {
784 $os = 'ios';
785 $phone = 'iphone';
786 } elseif ($detectmobile->is('PalmOS')) {
787 $os = $phone = 'palm';
788 } elseif ($detectmobile->is('SymbianOS')) {
789 $os = 'symbian';
790 } elseif ($detectmobile->is('webOS')) {
791 $os = 'webos';
792 } elseif ($detectmobile->is('MaemoOS')) {
793 $os = 'maemo';
794 } elseif ($detectmobile->is('WindowsMobileOS') || $detectmobile->is('WindowsPhoneOS')) {
795 $os = 'windows';
796 }
797 }
798
799 // OS
800 if (preg_match('/linux/i', $user_agent)) {
801 $os = 'linux';
802 } elseif (preg_match('/macintosh/i', $user_agent)) {
803 $os = 'macintosh';
804 } elseif (preg_match('/windows/i', $user_agent)) {
805 $os = 'windows';
806 }
807
808 // Name
809 $reg = array();
810 if (preg_match('/firefox(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
811 $name = 'firefox';
812 $version = empty($reg[2]) ? '' : $reg[2];
813 } elseif (preg_match('/edge(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
814 $name = 'edge';
815 $version = empty($reg[2]) ? '' : $reg[2];
816 } elseif (preg_match('/chrome(\/|\s)([\d\.]+)/i', $user_agent, $reg)) {
817 $name = 'chrome';
818 $version = empty($reg[2]) ? '' : $reg[2];
819 } elseif (preg_match('/chrome/i', $user_agent, $reg)) {
820 // we can have 'chrome (Mozilla...) chrome x.y' in one string
821 $name = 'chrome';
822 } elseif (preg_match('/iceweasel/i', $user_agent)) {
823 $name = 'iceweasel';
824 } elseif (preg_match('/epiphany/i', $user_agent)) {
825 $name = 'epiphany';
826 } elseif (preg_match('/safari(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
827 $name = 'safari';
828 $version = empty($reg[2]) ? '' : $reg[2];
829 } elseif (preg_match('/opera(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
830 // Safari is often present in string for mobile but its not.
831 $name = 'opera';
832 $version = empty($reg[2]) ? '' : $reg[2];
833 } elseif (preg_match('/(MSIE\s([0-9]+\.[0-9]))|.*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
834 $name = 'ie';
835 $version = end($reg);
836 } elseif (preg_match('/(Windows NT\s([0-9]+\.[0-9])).*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
837 // MS products at end
838 $name = 'ie';
839 $version = end($reg);
840 } elseif (preg_match('/l[iy]n(x|ks)(\‍(|\/|\s)*([\d\.]+)/i', $user_agent, $reg)) {
841 // MS products at end
842 $name = 'textbrowser';
843 $version = empty($reg[3]) ? '' : $reg[3];
844 } elseif (preg_match('/w3m\/([\d\.]+)/i', $user_agent, $reg)) {
845 // MS products at end
846 $name = 'textbrowser';
847 $version = empty($reg[1]) ? '' : $reg[1];
848 }
849
850 if ($tablet) {
851 $layout = 'tablet';
852 } elseif ($phone) {
853 $layout = 'phone';
854 } else {
855 $layout = 'classic';
856 }
857
858 return array(
859 'browsername' => $name,
860 'browserversion' => $version,
861 'browseros' => $os,
862 'browserua' => $user_agent,
863 'layout' => $layout, // tablet, phone, classic
864 'phone' => $phone, // deprecated
865 'tablet' => $tablet // deprecated
866 );
867}
868
874function dol_shutdown()
875{
876 global $db;
877 $disconnectdone = false;
878 $depth = 0;
879 if (is_object($db) && !empty($db->connected)) {
880 $depth = $db->transaction_opened;
881 $disconnectdone = $db->close();
882 }
883 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));
884}
885
895function GETPOSTISSET($paramname)
896{
897 $isset = false;
898
899 $relativepathstring = $_SERVER["PHP_SELF"];
900 // Clean $relativepathstring
901 if (constant('DOL_URL_ROOT')) {
902 $relativepathstring = preg_replace('/^' . preg_quote(constant('DOL_URL_ROOT'), '/') . '/', '', $relativepathstring);
903 }
904 $relativepathstring = ltrim($relativepathstring, '/');
905 $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
906
907 // Code for search criteria persistence.
908 // Retrieve values if restore_lastsearch_values
909 if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
910 if (!empty($_SESSION['lastsearch_values_' . $relativepathstring])) { // If there is saved values
911 $tmp = json_decode($_SESSION['lastsearch_values_' . $relativepathstring], true);
912 if (is_array($tmp)) {
913 foreach ($tmp as $key => $val) {
914 if ($key == $paramname) { // We are on the requested parameter
915 $isset = true;
916 break;
917 }
918 }
919 }
920 }
921 // If there is saved contextpage, limit, page or mode
922 if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_' . $relativepathstring])) {
923 $isset = true;
924 } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_' . $relativepathstring])) {
925 $isset = true;
926 } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_' . $relativepathstring])) {
927 $isset = true;
928 } elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_' . $relativepathstring])) {
929 $isset = true;
930 }
931 } else {
932 $isset = (isset($_POST[$paramname]) || isset($_GET[$paramname])); // We must keep $_POST and $_GET here
933 }
934
935 return $isset;
936}
937
946function GETPOSTISARRAY($paramname, $method = 0)
947{
948 // for $method test need return the same $val as GETPOST
949 if (empty($method)) {
950 $val = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
951 } elseif ($method == 1) {
952 $val = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
953 } elseif ($method == 2) {
954 $val = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
955 } elseif ($method == 3) {
956 $val = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
957 } else {
958 $val = 'BadFirstParameterForGETPOST';
959 }
960
961 return is_array($val);
962}
963
964
975function GETPOSTINT($paramname, $method = 0, $nodefault = 0)
976{
977 return (int) GETPOST($paramname, 'int', $method, null, null, 0, $nodefault);
978}
979
993function GETPOSTFLOAT($paramname, $rounding = '', $option = 2)
994{
995 // 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.)
996 return (float) price2num(GETPOST($paramname), $rounding, $option);
997}
998
1014function GETPOSTDATE($prefix, $hourTime = '', $gm = 'auto', $saverestore = '')
1015{
1016 $m = array();
1017 if ($hourTime === 'getpost' || $hourTime === 'getpostend') {
1018 $hour = (GETPOSTISSET($prefix . 'hour') && GETPOSTINT($prefix . 'hour') >= 0) ? GETPOSTINT($prefix . 'hour') : ($hourTime === 'getpostend' ? 23 : 0);
1019 $minute = (GETPOSTISSET($prefix . 'min') && GETPOSTINT($prefix . 'min') >= 0) ? GETPOSTINT($prefix . 'min') : ($hourTime === 'getpostend' ? 59 : 0);
1020 $second = (GETPOSTISSET($prefix . 'sec') && GETPOSTINT($prefix . 'sec') >= 0) ? GETPOSTINT($prefix . 'sec') : ($hourTime === 'getpostend' ? 59 : 0);
1021 } elseif (preg_match('/^(\d\d):(\d\d):(\d\d)$/', $hourTime, $m)) {
1022 $hour = intval($m[1]);
1023 $minute = intval($m[2]);
1024 $second = intval($m[3]);
1025 } elseif ($hourTime === 'end') {
1026 $hour = 23;
1027 $minute = 59;
1028 $second = 59;
1029 } else {
1030 $hour = $minute = $second = 0;
1031 }
1032
1033 if (
1034 $saverestore
1035 && !GETPOSTISSET($prefix . 'day')
1036 && !GETPOSTISSET($prefix . 'month')
1037 && !GETPOSTISSET($prefix . 'year')
1038 && isset($_SESSION['DOLDATE_' . $saverestore . '_day'])
1039 && isset($_SESSION['DOLDATE_' . $saverestore . '_month'])
1040 && isset($_SESSION['DOLDATE_' . $saverestore . '_year'])
1041 ) {
1042 $day = $_SESSION['DOLDATE_' . $saverestore . '_day'];
1043 $month = $_SESSION['DOLDATE_' . $saverestore . '_month'];
1044 $year = $_SESSION['DOLDATE_' . $saverestore . '_year'];
1045 } else {
1046 $month = GETPOSTINT($prefix . 'month');
1047 $day = GETPOSTINT($prefix . 'day');
1048 $year = GETPOSTINT($prefix . 'year');
1049 }
1050
1051 // normalize out of range values
1052 $hour = (int) min($hour, 23);
1053 $minute = (int) min($minute, 59);
1054 $second = (int) min($second, 59);
1055
1056 if ($saverestore) {
1057 $_SESSION['DOLDATE_' . $saverestore . '_day'] = $day;
1058 $_SESSION['DOLDATE_' . $saverestore . '_month'] = $month;
1059 $_SESSION['DOLDATE_' . $saverestore . '_year'] = $year;
1060 }
1061
1062 //print "$hour, $minute, $second, $month, $day, $year, $gm<br>";
1063 return dol_mktime($hour, $minute, $second, $month, $day, $year, $gm);
1064}
1065
1107function GETPOST($paramname, $check = 'alphanohtml', $method = 0, $filter = null, $options = null, $noreplace = 0, $nodefault = 0)
1108{
1109 global $langs, $mysoc, $user, $conf;
1110
1111 if (empty($paramname)) { // Explicit test for null for phan.
1112 return 'BadFirstParameterForGETPOST';
1113 }
1114 if (empty($check)) {
1115 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);
1116 // Enable this line to know who call the GETPOST with '' $check parameter.
1117 //var_dump(getCallerInfoString());
1118 }
1119 if (in_array($paramname, array('sortfield', 'sortorder'))) { // Force the $check to a more appropriated value
1120 $check = 'aZ09comma';
1121 }
1122
1123 if (empty($method)) {
1124 $out = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
1125 } elseif ($method == 1) {
1126 $out = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
1127 } elseif ($method == 2) {
1128 $out = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
1129 } elseif ($method == 3) {
1130 $out = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
1131 } else {
1132 return 'BadThirdParameterForGETPOST';
1133 }
1134
1135 $relativepathstring = ''; // For static analysis - looks possibly undefined if not set.
1136
1137 if (empty($method) || $method == 3 || $method == 4) {
1138 $relativepathstring = (empty($_SERVER["PHP_SELF"]) ? '' : $_SERVER["PHP_SELF"]);
1139 // Clean $relativepathstring
1140 if (constant('DOL_URL_ROOT')) {
1141 $relativepathstring = preg_replace('/^' . preg_quote(constant('DOL_URL_ROOT'), '/') . '/', '', $relativepathstring);
1142 }
1143 $relativepathstring = ltrim($relativepathstring, '/');
1144 $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
1145
1146 // Code for search criteria persistence.
1147 // Retrieve saved values if restore_lastsearch_values is set
1148 if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
1149 if (!empty($_SESSION['lastsearch_values_' . $relativepathstring])) { // If there is saved values
1150 $tmp = json_decode($_SESSION['lastsearch_values_' . $relativepathstring], true);
1151 if (is_array($tmp)) {
1152 foreach ($tmp as $key => $val) {
1153 if ($key == $paramname) { // We are on the requested parameter
1154 $out = $val;
1155 break;
1156 }
1157 }
1158 }
1159 }
1160 // If there is saved contextpage, page or limit
1161 if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_' . $relativepathstring])) {
1162 $out = $_SESSION['lastsearch_contextpage_' . $relativepathstring];
1163 } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_' . $relativepathstring])) {
1164 $out = $_SESSION['lastsearch_limit_' . $relativepathstring];
1165 } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_' . $relativepathstring])) {
1166 $out = $_SESSION['lastsearch_page_' . $relativepathstring];
1167 } elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_' . $relativepathstring])) {
1168 $out = $_SESSION['lastsearch_mode_' . $relativepathstring];
1169 }
1170 } elseif (!isset($_GET['sortfield'])) {
1171 // Else, retrieve default values if we are not doing a sort
1172 // 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
1173 if (!empty($_GET['action']) && $_GET['action'] == 'create' && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
1174 // Search default value from $object->field
1175 global $object;
1176 '@phan-var-force CommonObject $object'; // Suppose it's a CommonObject for analysis, but other objects have the $fields field as well
1177 if (is_object($object) && isset($object->fields[$paramname]['default'])) {
1178 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
1179 $out = $object->fields[$paramname]['default'];
1180 }
1181 }
1182 if (getDolGlobalString('MAIN_ENABLE_DEFAULT_VALUES')) {
1183 if (!empty($_GET['action']) && (preg_match('/^create/', $_GET['action']) || preg_match('/^presend/', $_GET['action'])) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
1184 // Now search in setup to overwrite default values
1185 if (!empty($user->default_values)) { // $user->default_values defined from menu 'Setup - Default values'
1186 if (isset($user->default_values[$relativepathstring]['createform'])) {
1187 foreach ($user->default_values[$relativepathstring]['createform'] as $defkey => $defval) {
1188 $qualified = 0;
1189 if ($defkey != '_noquery_') {
1190 $tmpqueryarraytohave = explode('&', $defkey);
1191 $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
1192 $foundintru = 0;
1193 foreach ($tmpqueryarraytohave as $tmpquerytohave) {
1194 if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
1195 $foundintru = 1;
1196 }
1197 }
1198 if (!$foundintru) {
1199 $qualified = 1;
1200 }
1201 } else {
1202 $qualified = 1;
1203 }
1204
1205 if ($qualified) {
1206 if (isset($user->default_values[$relativepathstring]['createform'][$defkey][$paramname])) {
1207 $out = $user->default_values[$relativepathstring]['createform'][$defkey][$paramname];
1208 break;
1209 }
1210 }
1211 }
1212 }
1213 }
1214 } elseif (!empty($paramname) && !isset($_GET[$paramname]) && !isset($_POST[$paramname]) && empty($nodefault)) {
1215 // Management of default search_filters and sort order
1216 if (!empty($user->default_values)) {
1217 // $user->default_values defined from menu 'Setup - Default values'
1218 //var_dump($user->default_values[$relativepathstring]);
1219 if ($paramname == 'sortfield' || $paramname == 'sortorder') {
1220 // Sorted on which fields ? ASC or DESC ?
1221 if (isset($user->default_values[$relativepathstring]['sortorder'])) {
1222 // Even if paramname is sortfield, data are stored into ['sortorder...']
1223 foreach ($user->default_values[$relativepathstring]['sortorder'] as $defkey => $defval) {
1224 $qualified = 0;
1225 if ($defkey != '_noquery_') {
1226 $tmpqueryarraytohave = explode('&', $defkey);
1227 $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
1228 $foundintru = 0;
1229 foreach ($tmpqueryarraytohave as $tmpquerytohave) {
1230 if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
1231 $foundintru = 1;
1232 }
1233 }
1234 if (!$foundintru) {
1235 $qualified = 1;
1236 }
1237 } else {
1238 $qualified = 1;
1239 }
1240
1241 if ($qualified) {
1242 $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
1243 foreach ($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val) {
1244 if ($out) {
1245 $out .= ', ';
1246 }
1247 if ($paramname == 'sortfield') {
1248 $out .= dol_string_nospecial($key, '', $forbidden_chars_to_replace);
1249 }
1250 if ($paramname == 'sortorder') {
1251 $out .= dol_string_nospecial($val, '', $forbidden_chars_to_replace);
1252 }
1253 }
1254 //break; // No break for sortfield and sortorder so we can cumulate fields (is it really useful ?)
1255 }
1256 }
1257 }
1258 } elseif (isset($user->default_values[$relativepathstring]['filters'])) {
1259 foreach ($user->default_values[$relativepathstring]['filters'] as $defkey => $defval) { // $defkey is a querystring like 'a=b&c=d', $defval is key of user
1260 if (!empty($_GET['disabledefaultvalues'])) { // If set of default values has been disabled by a request parameter
1261 continue;
1262 }
1263 $qualified = 0;
1264 if ($defkey != '_noquery_') {
1265 $tmpqueryarraytohave = explode('&', $defkey);
1266 $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
1267 $foundintru = 0;
1268 foreach ($tmpqueryarraytohave as $tmpquerytohave) {
1269 if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
1270 $foundintru = 1;
1271 }
1272 }
1273 if (!$foundintru) {
1274 $qualified = 1;
1275 }
1276 } else {
1277 $qualified = 1;
1278 }
1279
1280 if ($qualified && isset($user->default_values[$relativepathstring]['filters'][$defkey][$paramname])) {
1281 // We must keep $_POST and $_GET here
1282 if (isset($_POST['search_all']) || isset($_GET['search_all'])) {
1283 // We made a search from quick search menu, do we still use default filter ?
1284 if (!getDolGlobalString('MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH')) {
1285 $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
1286 $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
1287 }
1288 } else {
1289 $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
1290 $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
1291 }
1292 break;
1293 }
1294 }
1295 }
1296 }
1297 }
1298 }
1299 }
1300 }
1301
1302 // Replace 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)
1303 // Example of variables: __DAY__, __MONTH__, __YEAR__, __MYCOMPANY_COUNTRY_ID__, __USER_ID__, ...
1304 // 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.
1305 '@phan-var-force string $paramname';
1306 if (!is_array($out) && empty($_POST[$paramname]) && empty($noreplace)) {
1307 if (preg_match('/__([A-Z0-9]+(?:_[A-Z0-9]+){0,3})__/i', $out)) { // If there is at least one substitution key, we try to replace all known substitution keys
1308 $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $user, array('mycompany', 'date', 'system', 'user'));
1309 complete_substitutions_array($substitutionarray, $langs, $user);
1310
1311 $out = make_substitutions($out, $substitutionarray, $langs);
1312 }
1313 }
1314
1315 // Check type of variable and make sanitization according to this
1316 if (preg_match('/^array/', $check)) { // If 'array' or 'array:restricthtml' or 'array:aZ09' or 'array:int'
1317 $tmpcheck = 'alphanohtml';
1318 if ($out === null || $out === '') {
1319 $out = array();
1320 } elseif (!is_array($out)) {
1321 $out = explode(',', $out);
1322 } else {
1323 $tmparray = explode(':', $check);
1324 if (!empty($tmparray[1])) {
1325 $tmpcheck = $tmparray[1];
1326 }
1327 }
1328 foreach ($out as $outkey => $outval) {
1329 $out[$outkey] = sanitizeVal($outval, $tmpcheck, $filter, $options);
1330 }
1331 } else {
1332 // If field name is 'search_xxx' then we force the add of space after each < and > (when following char is numeric) because it means
1333 // 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
1334 if (strpos($paramname, 'search_') === 0) {
1335 $out = preg_replace('/([<>])([-+]?\d)/', '\1 \2', $out);
1336 }
1337
1338 // @phan-suppress-next-line UnknownSanitizeType
1339 $out = sanitizeVal($out, $check, $filter, $options);
1340 }
1341
1342 // Sanitizing for special parameters.
1343 // 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.
1344 // @TODO Merge backtopage with backtourl
1345 // @TODO Rename backtolist into backtopagelist
1346 // @TODO Merge urlfrom into backtourl
1347 if (preg_match('/^backto/i', $paramname) || preg_match('/^urlfrom/i', $paramname)) {
1348 $out = str_replace('\\', '/', $out); // Can be before the loop because only 1 char is replaced. No risk to get it after other replacements.
1349 $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.
1350 do {
1351 $oldstringtoclean = $out;
1352 $out = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $out);
1353 $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'
1354 $out = preg_replace(array('/^[a-z]*\/\s*\/+/i'), '', $out); // We remove schema*// to remove external URL
1355 } while ($oldstringtoclean != $out);
1356 }
1357
1358 // Code for search criteria persistence.
1359 // Save data into session if key start with 'search_'
1360 if (empty($method) || $method == 3 || $method == 4) {
1361 if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder', 'sortfield'))) {
1362 //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]);
1363
1364 // We save search key only if $out not empty that means:
1365 // - posted value not empty, or
1366 // - 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).
1367
1368 if ($out != '' && isset($user)) { // $out = '0' or 'abc', it is a search criteria to keep
1369 $user->lastsearch_values_tmp[$relativepathstring][$paramname] = $out;
1370 }
1371 }
1372 }
1373
1374 if ($paramname == 'hashp' && $out == 'shared') {
1375 $out = ''; // We refuse to have hashp=shared as a parameter
1376 }
1377
1378 return $out;
1379}
1380
1390function sanitizeVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
1391{
1392 // TODO : use class "Validate" to perform tests (and add missing tests) if needed for factorize
1393 // Check is done after replacement
1394 if ($out === null) {
1395 $out = '';
1396 }
1397 switch ($check) {
1398 case 'none':
1399 case 'password':
1400 break;
1401 case 'int': // Check param is a numeric value (integer but also float or hexadecimal)
1402 if (!is_numeric($out)) {
1403 $out = '';
1404 }
1405 break;
1406 case 'intcomma':
1407 if (is_array($out)) {
1408 $out = implode(',', $out);
1409 }
1410 if (preg_match('/[^0-9,-]+/i', $out)) {
1411 $out = '';
1412 }
1413 break;
1414 case 'san_alpha':
1415 dol_syslog("Use of parameter value 'san_alpha' in GETPOST is deprecated. Use 'alphanohtml', 'aZ09comma', ...", LOG_WARNING);
1416 $out = filter_var($out, FILTER_SANITIZE_STRING);
1417 break;
1418 case 'email':
1419 $out = filter_var($out, FILTER_SANITIZE_EMAIL);
1420 break;
1421 case 'url':
1422 //$out = filter_var($out, FILTER_SANITIZE_URL); // Not reliable, replaced with FILTER_VALIDATE_URL
1423 $out = preg_replace('/[^:\/\[\]a-z0-9@\$\'\*\~\.\-_,;\?\!=%&+#]+/i', '', $out);
1424 // TODO Allow ( ) but only into password of https://login:password@domain...
1425 break;
1426 case 'aZ':
1427 if (!is_array($out)) {
1428 $out = trim($out);
1429 if (preg_match('/[^a-z]+/i', $out)) {
1430 $out = '';
1431 }
1432 }
1433 break;
1434 case 'aZ09':
1435 if (!is_array($out)) {
1436 $out = trim($out);
1437 if (preg_match('/[^a-z0-9_\-\.]+/i', $out)) {
1438 $out = '';
1439 }
1440 }
1441 break;
1442 case 'aZ09arobase': // great to sanitize $objecttype parameter
1443 if (!is_array($out)) {
1444 $out = trim($out);
1445 if (preg_match('/[^a-z0-9_\-\.@]+/i', $out)) {
1446 $out = '';
1447 }
1448 }
1449 break;
1450 case 'aZ09comma': // great to sanitize $sortfield or $sortorder params that can be 't.abc,t.def_gh'
1451 if (!is_array($out)) {
1452 $out = trim($out);
1453 if (preg_match('/[^a-z0-9_\-\.,]+/i', $out)) {
1454 $out = '';
1455 }
1456 }
1457 break;
1458 case 'alpha': // No html and no ../ and "
1459 case 'alphanohtml': // Recommended for most scalar parameters and search parameters. Not valid for json string.
1460 if (!is_array($out)) {
1461 $out = trim($out);
1462 do {
1463 $oldstringtoclean = $out;
1464 // Remove html tags
1465 $out = dol_string_nohtmltag($out, 0);
1466 // 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).
1467 $out = preg_replace('/\\\‍([0-9xu])/', '/\1', $out);
1468 // Remove also other dangerous string sequences
1469 // '../' or '..\' is dangerous because it allows dir transversals
1470 // '&#38', '&#0000038', '&#x26'... is a the char '&' alone but there is no reason to accept such way to encode input char
1471 // '"' = '&#34' = '&#0000034' = '&#x22' is dangerous because param in url can close the href= or src= and add javascript functions.
1472 // '&#47', '&#0000047', '&#x2F' is the char '/' but there is no reason to accept such way to encode this input char
1473 // '&#92' = '&#0000092' = '&#x5C' is the char '\' but there is no reason to accept such way to encode this input char
1474 $out = str_ireplace(array('../', '..\\', '&#38', '&#0000038', '&#x26', '&quot', '"', '&#34', '&#0000034', '&#x22', '&#47', '&#0000047', '&#x2F', '&#92', '&#0000092', '&#x5C'), '', $out);
1475 } while ($oldstringtoclean != $out);
1476 // keep lines feed
1477 }
1478 break;
1479 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'
1480 if (!is_array($out)) {
1481 $out = trim($out);
1482 do {
1483 $oldstringtoclean = $out;
1484 // Decode html entities
1485 $out = dol_html_entity_decode($out, ENT_COMPAT | ENT_HTML5, 'UTF-8');
1486 // 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).
1487 $out = preg_replace('/\\\‍([0-9xu])/', '/\1', $out);
1488 // Remove also other dangerous string sequences
1489 // '../' or '..\' is dangerous because it allows dir transversals
1490 // '&#38', '&#0000038', '&#x26'... is a the char '&' alone but there is no reason to accept such way to encode input char
1491 // '"' = '&#34' = '&#0000034' = '&#x22' is dangerous because param in url can close the href= or src= and add javascript functions.
1492 // '&#47', '&#0000047', '&#x2F' is the char '/' but there is no reason to accept such way to encode this input char
1493 // '&#92' = '&#0000092' = '&#x5C' is the char '\' but there is no reason to accept such way to encode this input char
1494 $out = str_ireplace(array('../', '..\\', '&#38', '&#0000038', '&#x26', '&quot', '"', '&#34', '&#0000034', '&#x22', '&#47', '&#0000047', '&#x2F', '&#92', '&#0000092', '&#x5C'), '', $out);
1495 } while ($oldstringtoclean != $out);
1496 }
1497 break;
1498 case 'nohtml': // No html. Valid for JSON strings.
1499 $out = dol_string_nohtmltag($out, 0);
1500 break;
1501 case 'restricthtmlnolink':
1502 case 'restricthtml': // Recommended for most html textarea
1503 case 'restricthtmlallowclass':
1504 case 'restricthtmlallowiframe':
1505 case 'restricthtmlallowlinkscript': // Allow link and script tag for head section.
1506 case 'restricthtmlallowunvalid':
1507 $out = dol_htmlwithnojs($out, 1, $check);
1508 break;
1509 case 'custom':
1510 if (!empty($out)) {
1511 if (empty($filter)) {
1512 return 'BadParameterForGETPOST - Param 3 of sanitizeVal()';
1513 }
1514 if (is_null($options)) {
1515 $options = 0;
1516 }
1517 $out = filter_var($out, $filter, $options);
1518 }
1519 break;
1520 default:
1521 dol_syslog("Error, you call sanitizeVal() with a bad value for the check type. Data will be sanitized with alphanohtml.", LOG_ERR);
1522 $out = GETPOST($out, 'alphanohtml');
1523 break;
1524 }
1525
1526 return $out;
1527}
1528
1537function dolSetCookie(string $cookiename, string $cookievalue, int $expire = -1)
1538{
1539 include_once DOL_DOCUMENT_ROOT.'/blockedlog/lib/securitycore.lib.php';
1540
1541 global $dolibarr_main_force_https;
1542
1543 if ($expire == -1) {
1544 $expire = (time() + (86400 * 354)); // keep cookie 1 year.
1545 }
1546
1547 if (PHP_VERSION_ID < 70300) {
1548 setcookie($cookiename, empty($cookievalue) ? '' : $cookievalue, empty($cookievalue) ? 0 : $expire, '/', '', !(empty($dolibarr_main_force_https) && isHTTPS() === false), true); // add tag httponly
1549 } else {
1550 // Only available for php >= 7.3
1551 $cookieparams = array(
1552 'expires' => empty($cookievalue) ? 0 : $expire,
1553 'path' => '/',
1554 //'domain' => '.mywebsite.com', // the dot at the beginning allows compatibility with subdomains
1555 'secure' => !(empty($dolibarr_main_force_https) && isHTTPS() === false),
1556 'httponly' => true,
1557 'samesite' => 'Lax' // None || Lax || Strict
1558 );
1559 setcookie($cookiename, empty($cookievalue) ? '' : $cookievalue, $cookieparams);
1560 }
1561 if (empty($cookievalue)) {
1562 unset($_COOKIE[$cookiename]);
1563 }
1564}
1565
1566if (!function_exists('dol_getprefix')) {
1577 function dol_getprefix($mode = '')
1578 {
1579 // If prefix is for email (we need to have $conf already loaded for this case)
1580 if ($mode == 'email') {
1581 global $conf;
1582
1583 if (getDolGlobalString('MAIL_PREFIX_FOR_EMAIL_ID')) { // If MAIL_PREFIX_FOR_EMAIL_ID is set
1584 if (getDolGlobalString('MAIL_PREFIX_FOR_EMAIL_ID') != 'SERVER_NAME') {
1585 return getDolGlobalString('MAIL_PREFIX_FOR_EMAIL_ID');
1586 } elseif (isset($_SERVER["SERVER_NAME"])) { // If MAIL_PREFIX_FOR_EMAIL_ID is set to 'SERVER_NAME'
1587 return $_SERVER["SERVER_NAME"];
1588 }
1589 }
1590
1591 // The recommended value if MAIL_PREFIX_FOR_EMAIL_ID is not defined (may be not defined for old versions)
1592 if (!empty($conf->file->instance_unique_id)) {
1593 return sha1('dolibarr' . $conf->file->instance_unique_id);
1594 }
1595
1596 // For backward compatibility when instance_unique_id is not set
1597 return sha1(DOL_DOCUMENT_ROOT . DOL_URL_ROOT);
1598 }
1599
1600 // If prefix is for session (no need to have $conf loaded)
1601 global $dolibarr_main_instance_unique_id, $dolibarr_main_cookie_cryptkey; // This is loaded by filefunc.inc.php
1602 $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
1603
1604 // The recommended value (may be not defined for old versions)
1605 if (!empty($tmp_instance_unique_id)) {
1606 return sha1('dolibarr' . $tmp_instance_unique_id);
1607 }
1608
1609 // For backward compatibility when instance_unique_id is not set
1610 if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"])) {
1611 return sha1($_SERVER["SERVER_NAME"] . $_SERVER["DOCUMENT_ROOT"] . DOL_DOCUMENT_ROOT . DOL_URL_ROOT);
1612 } else {
1613 return sha1(DOL_DOCUMENT_ROOT . DOL_URL_ROOT);
1614 }
1615 }
1616}
1617
1628function dol_include_once($relpath, $classname = '')
1629{
1630 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']
1631
1632 if (strpos($relpath, '..') !== false) {
1633 // Found a not valid path
1634 dol_syslog('functions::dol_include_once Tried to load a file with a path including a forbidden sequence ".." : ' . $relpath, LOG_WARNING);
1635 return false;
1636 }
1637 if (!preg_match('/\.php$/', $relpath)) {
1638 // Found a not valid path
1639 dol_syslog('functions::dol_include_once Tried to load a file that is not a PHP file : ' . $relpath, LOG_WARNING);
1640 return false;
1641 }
1642
1643 $fullpath = dol_buildpath($relpath);
1644
1645 if (!file_exists($fullpath)) {
1646 dol_syslog('functions::dol_include_once Tried to load unexisting file: ' . $relpath, LOG_WARNING);
1647 return false;
1648 }
1649 if (!empty($classname) && !class_exists($classname)) {
1650 return include $fullpath;
1651 } else {
1652 return include_once $fullpath;
1653 }
1654}
1655
1656
1670function dol_buildpath($path, $type = 0, $returnemptyifnotfound = 0)
1671{
1672 global $conf;
1673
1674 $path = preg_replace('/^\//', '', $path);
1675
1676 if (empty($type)) { // For a filesystem path
1677 $res = DOL_DOCUMENT_ROOT . '/' . $path; // Standard default path
1678 if (is_array($conf->file->dol_document_root)) {
1679 foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array("main"=>"/home/main/htdocs", "alt0"=>"/home/dirmod/htdocs", ...)
1680 if ($key == 'main') {
1681 continue;
1682 }
1683 // if (@file_exists($dirroot.'/'.$path)) {
1684 if (@file_exists($dirroot . '/' . $path)) { // avoid [php:warn]
1685 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/...'
1686 continue;
1687 }
1688 $res = $dirroot . '/' . $path;
1689 return $res;
1690 }
1691 }
1692 }
1693 if ($returnemptyifnotfound) {
1694 // Not found into alternate dir
1695 if ($returnemptyifnotfound == 1 || !file_exists($res)) {
1696 return '';
1697 }
1698 }
1699 } else {
1700 // For an url path
1701 // We try to get local path of file on filesystem from url
1702 // Note that trying to know if a file on disk exist by forging path on disk from url
1703 // works only for some web server and some setup. This is bugged when
1704 // using proxy, rewriting, virtual path, etc...
1705 $res = '';
1706 if ($type == 1) {
1707 $res = DOL_URL_ROOT . '/' . $path; // Standard value
1708 }
1709 if ($type == 2) {
1710 $res = DOL_MAIN_URL_ROOT . '/' . $path; // Standard value
1711 }
1712 if ($type == 3) {
1713 $res = DOL_URL_ROOT . '/' . $path;
1714 }
1715
1716 foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
1717 if ($key == 'main') {
1718 if ($type == 3) {
1719 /*global $dolibarr_main_url_root;*/
1720
1721 // Define $urlwithroot
1722 $urlwithouturlroot = preg_replace('/' . preg_quote(DOL_URL_ROOT, '/') . '$/i', '', trim($conf->file->dol_main_url_root));
1723 $urlwithroot = $urlwithouturlroot . DOL_URL_ROOT; // This is to use external domain name found into config file
1724 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
1725
1726 $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : $urlwithroot) . '/' . $path; // Test on start with http is for old conf syntax
1727 }
1728 continue;
1729 }
1730 $regs = array();
1731 preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i', $path, $regs); // Take part before '?'
1732 if (!empty($regs[1])) {
1733 //print $key.'-'.$dirroot.'/'.$path.'-'.$conf->file->dol_url_root[$type].'<br>'."\n";
1734 //if (file_exists($dirroot.'/'.$regs[1])) {
1735 if (@file_exists($dirroot . '/' . $regs[1])) { // avoid [php:warn]
1736 if ($type == 1) {
1737 $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_URL_ROOT) . $conf->file->dol_url_root[$key] . '/' . $path;
1738 } elseif ($type == 2) {
1739 $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_MAIN_URL_ROOT) . $conf->file->dol_url_root[$key] . '/' . $path;
1740 } elseif ($type == 3) {
1741 /*global $dolibarr_main_url_root;*/
1742
1743 // Define $urlwithroot
1744 $urlwithouturlroot = preg_replace('/' . preg_quote(DOL_URL_ROOT, '/') . '$/i', '', trim($conf->file->dol_main_url_root));
1745 $urlwithroot = $urlwithouturlroot . DOL_URL_ROOT; // This is to use external domain name found into config file
1746 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
1747
1748 $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
1749 }
1750 break;
1751 }
1752 }
1753 }
1754 }
1755
1756 return $res;
1757}
1758
1768function dolBuildUrl($url, $params = [], $addtoken = false, $anchor = '')
1769{
1770 global $db, $hookmanager;
1771
1772 if (!is_object($hookmanager)) {
1773 include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
1774 $hookmanager = new HookManager($db);
1775 }
1776 if ((!isset($params['mainmenu']) || empty($params['mainmenu'])) && GETPOSTISSET('mainmenu')) {
1777 $params = array_merge($params, ['mainmenu' => (GETPOST('mainmenu', 'restricthtml'))]);
1778 }
1779 if ((!isset($params['leftmenu'])/* || empty($params['leftmenu']) */) && GETPOSTISSET('leftmenu')) { // do not fill leftmenu if we have leftmenu=
1780 $params = array_merge($params, ['leftmenu' => (GETPOST('leftmenu', 'restricthtml'))]);
1781 }
1782 $parameters = [
1783 'path' => &$url,
1784 'params' => &$params,
1785 'addtoken' => &$addtoken,
1786 ];
1787 $hookmanager->executeHooks('buildurl', $parameters);
1788 if ($addtoken) {
1789 $params = array_merge($params, ['token' => newToken()]);
1790 }
1791 if ($params) {
1792 $url .= '?' . http_build_query($params);
1793 }
1794 if ($anchor) {
1795 $url .= '#' . preg_replace('/[^a-z]/i', '', $anchor);
1796 }
1797
1798 return $url;
1799}
1800
1811function dol_get_object_properties($obj, $properties = [])
1812{
1813 // Get real properties using get_object_vars() if $properties is empty
1814 if (empty($properties)) {
1815 return get_object_vars($obj);
1816 }
1817
1818 $existingProperties = [];
1819 $realProperties = get_object_vars($obj);
1820
1821 // Get the real or magic property values
1822 foreach ($properties as $property) {
1823 if (array_key_exists($property, $realProperties)) {
1824 // Real property, add the value
1825 $existingProperties[$property] = $obj->{$property};
1826 } elseif (property_exists($obj, $property)) {
1827 // Magic property
1828 $existingProperties[$property] = $obj->{$property};
1829 }
1830 }
1831
1832 return $existingProperties;
1833}
1834
1835
1853function dol_clone($srcobject, $native = 2)
1854{
1855 if ($native == 0) {
1856 // deprecated method, use the method with native = 2 instead
1857 dol_syslog("Warning, call to dol_clone() with the deprecated parameter native=0, use 2 instead", LOG_WARNING);
1858
1859 $tmpsavdb = null;
1860 if (isset($srcobject->db) && isset($srcobject->db->db) && is_object($srcobject->db->db) && get_class($srcobject->db->db) == 'PgSql\Connection') {
1861 $tmpsavdb = $srcobject->db;
1862 unset($srcobject->db); // Such property can not be serialized with pgsl (when object->db->db = 'PgSql\Connection')
1863 }
1864
1865 $myclone = unserialize(serialize($srcobject)); // serialize then unserialize is a hack to be sure to have a new object for all fields
1866
1867 if (!empty($tmpsavdb)) {
1868 $srcobject->db = $tmpsavdb;
1869 }
1870 } elseif ($native == 2) {
1871 // recommended method to have a full secured isolated cloned object
1872 $myclone = new stdClass();
1873 $tmparray = get_object_vars($srcobject); // return only public properties
1874
1875 if (is_array($tmparray)) {
1876 foreach ($tmparray as $propertykey => $propertyval) {
1877 if (is_scalar($propertyval) || is_array($propertyval)) {
1878 $myclone->$propertykey = $propertyval;
1879 }
1880 }
1881 }
1882 } else {
1883 $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)
1884 }
1885
1886 return $myclone;
1887}
1888
1889
1898function dol_clone_in_array($srcobject, $startlevel = 0)
1899{
1900 if (is_object($srcobject)) {
1901 $srcobject = get_object_vars($srcobject); // exclude private/protected properties
1902 }
1903
1904 if (is_array($srcobject)) {
1905 $result = [];
1906 foreach ($srcobject as $key => $value) {
1907 if (in_array($key, array('db', 'fields', 'error', 'errorhidden', 'errors', 'oldcopy', 'linkedObjects', 'linked_objects'))) {
1908 continue;
1909 }
1910 $result[$key] = dol_clone_in_array($value, $startlevel + 1);
1911 }
1912 return $result;
1913 }
1914
1915 return $srcobject;
1916}
1917
1918
1928function dol_size($size, $type = '')
1929{
1930 global $conf;
1931 if (empty($conf->dol_optimize_smallscreen)) {
1932 return $size;
1933 }
1934 if ($type == 'width' && $size > 250) {
1935 return 250;
1936 } else {
1937 return 10;
1938 }
1939}
1940
1941
1955function dol_sanitizeFileName($str, $newstr = '_', $unaccent = 1, $includequotes = 0, $allowdash = 0)
1956{
1957 $str = (string) $str;
1958
1959 // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
1960 // Char '>' '<' '|' '$' and ';' are special chars for shells.
1961 // Char '/' and '\' are file delimiters.
1962 // 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
1963 $filesystem_forbidden_chars = array('<', '>', '/', '\\', '?', '*', '|', '"', ':', '°', '$', ';', '`');
1964 if ($includequotes) {
1965 $filesystem_forbidden_chars[] = "'";
1966 }
1967 $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
1968 $tmp = preg_replace('/\-\-+/', '_', $tmp);
1969 if (empty($allowdash)) {
1970 $tmp = preg_replace('/\s+\-([^\s])/', ' _$1', $tmp);
1971 $tmp = preg_replace('/\s+\-$/', '', $tmp);
1972 }
1973 $tmp = str_replace('..', '', $tmp);
1974 $tmp = str_replace('~', $newstr, $tmp);
1975 $tmp = preg_replace('/\s{2,}/', ' ', $tmp);
1976
1977 return $tmp;
1978}
1979
1980
1993function dol_sanitizePathName($str, $newstr = '_', $unaccent = 0, $allowdash = 0)
1994{
1995 // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
1996 // Char '>' '<' '|' '$' ';' and '`' are special chars for shells.
1997 // Char '?' and '*' are for wild card chars.
1998 // Char '"' is dangerous.
1999 // Char '°' is just not expected.
2000 // 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
2001 // Chars '--' and '~' can be used for path transversal
2002 $filesystem_forbidden_chars = array('<', '>', '?', '*', '|', '"', '°', '$', ';', '`');
2003
2004 $tmp = $str;
2005 if ($unaccent) {
2006 $tmp = dol_string_unaccent($tmp);
2007 }
2008 $tmp = dol_string_nospecial($tmp, $newstr, $filesystem_forbidden_chars);
2009 $tmp = preg_replace('/\-\-+/', $newstr, $tmp);
2010 if (empty($allowdash)) {
2011 $tmp = preg_replace('/\s+\-([^\s])/', ' '.$newstr.'$1', $tmp);
2012 $tmp = preg_replace('/\s+\-$/', '', $tmp);
2013 }
2014 $tmp = str_replace('..', $newstr, $tmp);
2015 $tmp = str_replace('~', $newstr, $tmp);
2016 $tmp = preg_replace('/\s{2,}/', ' ', $tmp);
2017
2018 return $tmp;
2019}
2020
2028function dol_sanitizeUrl($stringtoclean, $type = 1)
2029{
2030 // 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)
2031 // We should use dol_string_nounprintableascii but function may not be yet loaded/available
2032 $stringtoclean = preg_replace('/[\x00-\x1F\x7F]/u', '', $stringtoclean); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
2033 // We clean html comments because some hacks try to obfuscate evil strings by inserting HTML comments. Example: on<!-- -->error=alert(1)
2034 $stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
2035
2036 $stringtoclean = str_replace('\\', '/', $stringtoclean);
2037 if ($type == 1) {
2038 // removing : should disable links to external url like http:aaa)
2039 // removing ';' should disable "named" html entities encode into an url (we should not have this into an url)
2040 $stringtoclean = str_replace(array(':', ';', '@'), '', $stringtoclean);
2041 }
2042
2043 do {
2044 $oldstringtoclean = $stringtoclean;
2045 // removing '&colon' should disable links to external url like http:aaa)
2046 // removing '&#' should disable "numeric" html entities encode into an url (we should not have this into an url)
2047 $stringtoclean = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $stringtoclean);
2048 } while ($oldstringtoclean != $stringtoclean);
2049
2050 if ($type == 1) {
2051 // removing '//' should disable links to external url like //aaa or http//)
2052 $stringtoclean = preg_replace(array('/^[a-z]*\/\/+/i'), '', $stringtoclean);
2053 }
2054
2055 return $stringtoclean;
2056}
2057
2064function dol_sanitizeEmail($stringtoclean)
2065{
2066 do {
2067 $oldstringtoclean = $stringtoclean;
2068 $stringtoclean = str_ireplace(array('"', ':', '[', ']', "\n", "\r", '\\', '\/'), '', $stringtoclean);
2069 } while ($oldstringtoclean != $stringtoclean);
2070
2071 return $stringtoclean;
2072}
2073
2082function dol_sanitizeKeyCode($str)
2083{
2084 return preg_replace('/[^\w]+/', '', $str);
2085}
2086
2087
2096function dol_string_unaccent($str)
2097{
2098 if (is_null($str)) {
2099 return '';
2100 }
2101
2102 if (utf8_check($str)) {
2103 if (extension_loaded('intl') && getDolGlobalString('MAIN_UNACCENT_USE_TRANSLITERATOR')) {
2104 $transliterator = Transliterator::createFromRules(':: Any-Latin; :: Latin-ASCII; :: NFD; :: [:Nonspacing Mark:] Remove; :: NFC;', Transliterator::FORWARD);
2105 return $transliterator->transliterate($str);
2106 }
2107 // See http://www.utf8-chartable.de/
2108 $string = rawurlencode($str);
2109 $replacements = array(
2110 '%C3%80' => 'A', '%C3%81' => 'A', '%C3%82' => 'A', '%C3%83' => 'A', '%C3%84' => 'A', '%C3%85' => 'A',
2111 '%C3%87' => 'C',
2112 '%C3%88' => 'E', '%C3%89' => 'E', '%C3%8A' => 'E', '%C3%8B' => 'E',
2113 '%C3%8C' => 'I', '%C3%8D' => 'I', '%C3%8E' => 'I', '%C3%8F' => 'I',
2114 '%C3%91' => 'N',
2115 '%C3%92' => 'O', '%C3%93' => 'O', '%C3%94' => 'O', '%C3%95' => 'O', '%C3%96' => 'O', '%C5%90' => 'O',
2116 '%C5%A0' => 'S',
2117 '%C3%99' => 'U', '%C3%9A' => 'U', '%C3%9B' => 'U', '%C3%9C' => 'U', '%C5%B0' => 'U',
2118 '%C3%9D' => 'Y', '%C5%B8' => 'y',
2119 '%C3%A0' => 'a', '%C3%A1' => 'a', '%C3%A2' => 'a', '%C3%A3' => 'a', '%C3%A4' => 'a', '%C3%A5' => 'a',
2120 '%C3%A7' => 'c',
2121 '%C3%A8' => 'e', '%C3%A9' => 'e', '%C3%AA' => 'e', '%C3%AB' => 'e',
2122 '%C3%AC' => 'i', '%C3%AD' => 'i', '%C3%AE' => 'i', '%C3%AF' => 'i',
2123 '%C3%B1' => 'n',
2124 '%C3%B2' => 'o', '%C3%B3' => 'o', '%C3%B4' => 'o', '%C3%B5' => 'o', '%C3%B6' => 'o', '%C5%91' => 'o',
2125 '%C5%A1' => 's',
2126 '%C3%B9' => 'u', '%C3%BA' => 'u', '%C3%BB' => 'u', '%C3%BC' => 'u', '%C5%B1' => 'u',
2127 '%C3%BD' => 'y', '%C3%BF' => 'y',
2128 '%CC%80' => '',
2129 '%CC%81' => '',
2130 '%CC%82' => '',
2131 '%CC%83' => '',
2132 '%CC%84' => '',
2133 '%CC%85' => '',
2134 '%CC%86' => '',
2135 '%CC%87' => '',
2136 '%CC%88' => '',
2137 '%CC%89' => '',
2138 '%CC%8A' => '',
2139 '%CC%8B' => '',
2140 '%CC%8C' => '',
2141 '%CC%8D' => '',
2142 '%CC%8E' => '',
2143 '%CC%8F' => '',
2144 '%CC%90' => '',
2145 '%CC%91' => '',
2146 '%CC%A7' => ''
2147 );
2148 $string = strtr($string, $replacements);
2149 return rawurldecode($string);
2150 } else {
2151 // See http://www.ascii-code.com/
2152 $string = strtr(
2153 $str,
2154 "\xC0\xC1\xC2\xC3\xC4\xC5\xC7
2155 \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
2156 \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
2157 \xE0\xE1\xE2\xE3\xE4\xE5\xE7\xE8\xE9\xEA\xEB
2158 \xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
2159 \xF9\xFA\xFB\xFC\xFD\xFF",
2160 "AAAAAAC
2161 EEEEIIIIDN
2162 OOOOOUUUY
2163 aaaaaaceeee
2164 iiiidnooooo
2165 uuuuyy"
2166 );
2167 $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"));
2168 return $string;
2169 }
2170}
2171
2185function dol_string_nospecial($str, $newstr = '_', $badcharstoreplace = '', $badcharstoremove = '', $keepspaces = 0)
2186{
2187 $forbidden_chars_to_replace = array("'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°', '$', ';'); // more complete than dol_sanitizeFileName
2188 if (empty($keepspaces)) {
2189 $forbidden_chars_to_replace[] = " ";
2190 }
2191 $forbidden_chars_to_remove = array();
2192 //$forbidden_chars_to_remove=array("(",")");
2193
2194 if (is_array($badcharstoreplace)) {
2195 $forbidden_chars_to_replace = $badcharstoreplace;
2196 }
2197 if (is_array($badcharstoremove)) {
2198 $forbidden_chars_to_remove = $badcharstoremove;
2199 }
2200
2201 // @phan-suppress-next-line PhanPluginSuspiciousParamOrderInternal
2202 return str_replace($forbidden_chars_to_replace, $newstr, str_replace($forbidden_chars_to_remove, "", $str));
2203}
2204
2205
2219function dol_string_nounprintableascii($str, $removetabcrlf = 1)
2220{
2221 if ($removetabcrlf) {
2222 return preg_replace('/[\x00-\x1F\x7F]/u', '', $str); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
2223 } else {
2224 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
2225 }
2226}
2227
2234function dolSlugify($stringtoslugify)
2235{
2236 $slug = dol_string_unaccent($stringtoslugify);
2237
2238 // Convert special characters to their ASCII equivalents
2239 if (function_exists('iconv')) {
2240 $slug = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $slug);
2241 }
2242
2243 // Convert to lowercase
2244 $slug = strtolower($slug);
2245
2246 // Replace non-alphanumeric characters with hyphens
2247 $slug = preg_replace('/[^a-z0-9]+/', '-', $slug);
2248
2249 // Remove leading and trailing hyphens
2250 $slug = trim($slug, '-');
2251
2252 return $slug;
2253}
2254
2263function dol_escape_js($stringtoescape, $mode = 0, $noescapebackslashn = 0)
2264{
2265 if (is_null($stringtoescape)) {
2266 return '';
2267 }
2268
2269 // escape quotes and backslashes, newlines, etc.
2270 $substitjs = array("&#039;" => "\\'", "\r" => '\\r');
2271 //$substitjs['</']='<\/'; // We removed this. Should be useless.
2272 if (empty($noescapebackslashn)) {
2273 $substitjs["\n"] = '\\n';
2274 $substitjs['\\'] = '\\\\';
2275 }
2276 if (empty($mode)) {
2277 $substitjs["'"] = "\\'";
2278 $substitjs['"'] = "\\'";
2279 } elseif ($mode == 1) {
2280 $substitjs["'"] = "\\'";
2281 } elseif ($mode == 2) {
2282 $substitjs['"'] = '\\"';
2283 } elseif ($mode == 3) {
2284 $substitjs["'"] = "\\'";
2285 $substitjs['"'] = "\\\"";
2286 }
2287 return strtr((string) $stringtoescape, $substitjs);
2288}
2289
2299function dol_escape_uri($stringtoescape)
2300{
2301 return rawurlencode($stringtoescape);
2302}
2303
2310function dol_escape_json($stringtoescape)
2311{
2312 return str_replace('"', '\"', $stringtoescape);
2313}
2314
2322function dol_escape_php($stringtoescape, $stringforquotes = 2)
2323{
2324 if (is_null($stringtoescape)) {
2325 return '';
2326 }
2327
2328 if ($stringforquotes == 2) {
2329 return str_replace('"', "'", $stringtoescape);
2330 } elseif ($stringforquotes == 1) {
2331 // We remove the \ char.
2332 // If we allow the \ char, we can have $stringtoescape =
2333 // abc\';phpcodedanger; so the escapement will become
2334 // abc\\';phpcodedanger; and injecting this into
2335 // $a='...' will give $ac='abc\\';phpcodedanger;
2336 $stringtoescape = str_replace('\\', '', $stringtoescape);
2337 return str_replace("'", "\'", str_replace('"', "'", $stringtoescape));
2338 }
2339
2340 return 'Bad parameter for stringforquotes in dol_escape_php';
2341}
2342
2349function dol_escape_all($stringtoescape)
2350{
2351 return preg_replace('/[^a-z0-9_]/i', '', $stringtoescape);
2352}
2353
2360function dol_escape_xml($stringtoescape)
2361{
2362 $stringtoescape = (string) preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', '', (string) $stringtoescape); // Characters not allowed in XML 1.0
2363
2364 return htmlspecialchars($stringtoescape, ENT_XML1 | ENT_QUOTES, 'UTF-8');
2365}
2366
2376function dolPrintLabel($s, $escapeonlyhtmltags = 0)
2377{
2378 return dol_escape_htmltag(dol_string_nohtmltag($s, 1, 'UTF-8', 0, 0), 0, 0, '', $escapeonlyhtmltags, 1);
2379}
2380
2389function dolPrintText($s)
2390{
2391 return dol_escape_htmltag(dol_string_nohtmltag($s, 2, 'UTF-8', 0, 0), 0, 1, '', 0, 1);
2392}
2393
2405function dolPrintHTML($s, $allowiframe = 0, $moreallowedtags = array())
2406{
2407 // If text is already HTML, we want to escape only dangerous chars else we want to escape all content.
2408 //$isAlreadyHTML = dol_textishtml($s);
2409
2410 // dol_htmlentitiesbr encode all chars except "'" if string is not already HTML, but
2411 // encode only special char like accented chars but not &, <, >, ", ' if already HTML.
2412 $stringWithEntitesForSpecialChar = dol_htmlentitiesbr((string) $s);
2413
2414 $allowedtags = 'common';
2415 if (!empty($moreallowedtags)) {
2416 $allowedtags .= ','.implode(',', $moreallowedtags);
2417 }
2418 return dol_escape_htmltag(dol_htmlwithnojs(dol_string_onlythesehtmltags($stringWithEntitesForSpecialChar, 1, 1, 1, $allowiframe, $allowedtags)), 1, 1, $allowedtags, 0, 1);
2419}
2420
2431function dolPrintHTMLForAttribute($s, $escapeonlyhtmltags = 0, $allowothertags = array())
2432{
2433 $allowedtags = array('br', 'b', 'font', 'hr', 'span');
2434 if (!empty($allowothertags) && is_array($allowothertags)) {
2435 $allowedtags = array_merge($allowedtags, $allowothertags);
2436 }
2437 // The dol_htmlentitiesbr will convert simple text into html, including switching accent into HTML entities
2438 // The dol_escape_htmltag will escape html tags.
2439 if ($escapeonlyhtmltags) {
2440 return dol_escape_htmltag(dol_string_onlythesehtmltags($s, 1, 0, 0, 0, $allowedtags), 1, -1, '', 1, 1);
2441 } else {
2442 return dol_escape_htmltag(dol_string_onlythesehtmltags(dol_htmlentitiesbr($s), 1, 0, 0, 0, $allowedtags), 1, -1, '', 0, 1);
2443 }
2444}
2445
2454function dolPrintHTMLForAttributeUrl($s)
2455{
2456 // 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)
2457 // The dol_escape_htmltag will escape html chars.
2458 $escapeonlyhtmltags = 1;
2459 return dol_escape_htmltag(dol_string_onlythesehtmltags($s, 1, 1, 1, 0, array()), 0, 0, '', $escapeonlyhtmltags, 1);
2460}
2461
2471function dolPrintHTMLForTextArea($s, $allowiframe = 0)
2472{
2473 return dol_escape_htmltag(dol_htmlwithnojs(dol_string_onlythesehtmltags(dol_htmlentitiesbr($s), 1, 1, 1, $allowiframe)), 1, 1, '', 0, 1);
2474}
2475
2482function dolPrintPassword($s)
2483{
2484 return htmlspecialchars($s, ENT_HTML5, 'UTF-8');
2485}
2486
2487
2504function dol_escape_htmltag($stringtoescape, $keepb = 0, $keepn = 0, $noescapetags = '', $escapeonlyhtmltags = 0, $cleanalsojavascript = 0)
2505{
2506 $reg = array();
2507 if (preg_match('/^common([a-z,]*)/', $noescapetags, $reg)) {
2508 $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';
2509 // Add also html5 tags
2510 $noescapetags .= ',header,footer,nav,section,menu,menuitem';
2511 if (!empty($reg[1])) {
2512 $noescapetags .= $reg[1];
2513 }
2514 }
2515 if ($cleanalsojavascript) {
2516 $stringtoescape = dol_string_onlythesehtmltags($stringtoescape, 0, 0, $cleanalsojavascript, 0, array(), 0);
2517 }
2518
2519 // escape quotes and backslashes, newlines, etc.
2520 if ($escapeonlyhtmltags) {
2521 $tmp = htmlspecialchars_decode((string) $stringtoescape, ENT_COMPAT);
2522 } else {
2523 // We make a manipulation by calling the html_entity_decode() to convert content into NON HTML UTF8 string.
2524 // Because content can be or not already HTML.
2525 // For example, this decode &egrave; into its UTF-8 char so string is UTF8 (but numbers entities like &#39; is not decoded).
2526 // In a future, we should not need this
2527
2528 $tmp = (string) $stringtoescape;
2529
2530 // We protect the 6 special entities that we don't want to decode.
2531 $tmp = str_ireplace('&lt', '__DONOTDECODELT', $tmp);
2532 $tmp = str_ireplace('&gt', '__DONOTDECODEGT', $tmp);
2533 $tmp = str_ireplace('&amp', '__DONOTDECODEAMP', $tmp);
2534 $tmp = str_ireplace('&quot', '__DONOTDECODEQUOT', $tmp);
2535 $tmp = str_ireplace('&apos', '__DONOTDECODEAPOS', $tmp);
2536 $tmp = str_ireplace('&#39', '__DONOTDECODE39', $tmp);
2537
2538 $tmp = html_entity_decode((string) $tmp, ENT_COMPAT, 'UTF-8'); // Convert entities into UTF8
2539
2540 // We restore the 6 special entities that we don't want to have been decoded by previous command
2541 $tmp = str_ireplace('__DONOTDECODELT', '&lt', $tmp);
2542 $tmp = str_ireplace('__DONOTDECODEGT', '&gt', $tmp);
2543 $tmp = str_ireplace('__DONOTDECODEAMP', '&amp', $tmp);
2544 $tmp = str_ireplace('__DONOTDECODEQUOT', '&quot', $tmp);
2545 $tmp = str_ireplace('__DONOTDECODEAPOS', '&apos', $tmp);
2546 $tmp = str_ireplace('__DONOTDECODE39', '&#39', $tmp);
2547
2548 $tmp = str_ireplace('&#39;', '__SIMPLEQUOTE__', $tmp); // HTML 4
2549 }
2550 if (!$keepb) {
2551 $tmp = strtr($tmp, array("<b>" => '', '</b>' => '', '<strong>' => '', '</strong>' => ''));
2552 }
2553 if (!$keepn) {
2554 $tmp = strtr($tmp, array("\r" => '\\r', "\n" => '\\n'));
2555 } elseif ($keepn == -1) {
2556 $tmp = strtr($tmp, array("\r" => '', "\n" => ''));
2557 }
2558
2559 if ($escapeonlyhtmltags) {
2560 $tmp = htmlspecialchars($tmp, ENT_COMPAT, 'UTF-8');
2561 return $tmp;
2562 } else {
2563 // Now we protect all the tags we want to keep
2564 $tmparrayoftags = array();
2565 if ($noescapetags) {
2566 $tmparrayoftags = explode(',', $noescapetags);
2567 }
2568
2569 if (count($tmparrayoftags)) {
2570 // Now we will protect tags (defined into $tmparrayoftags) that we want to keep untouched
2571
2572 $reg = array();
2573 // Remove reserved keywords. They are forbidden in a source string
2574 $tmp = str_ireplace(array('__DOUBLEQUOTE', '__BEGINTAGTOREPLACE', '__ENDTAGTOREPLACE', '__BEGINENDTAGTOREPLACE'), '', $tmp);
2575
2576 foreach ($tmparrayoftags as $tagtoreplace) {
2577 // For case of tag without attributes '<abc>', '</abc>', '<abc />', we protect them to avoid transformation by htmlentities() later
2578 $tmp = preg_replace('/<' . preg_quote($tagtoreplace, '/') . '>/', '__BEGINTAGTOREPLACE' . $tagtoreplace . '__', $tmp);
2579 $tmp = str_ireplace('</' . $tagtoreplace . '>', '__ENDTAGTOREPLACE' . $tagtoreplace . '__', $tmp);
2580 $tmp = preg_replace('/<' . preg_quote($tagtoreplace, '/') . ' \/>/', '__BEGINENDTAGTOREPLACE' . $tagtoreplace . '__', $tmp);
2581
2582 // For case of tag with attributes.
2583 // All the occurrences are protected in a single pass: the replacement string contains no '<', so it
2584 // can never build a new tag to protect (a loop replacing one distinct attribute string per round was
2585 // rescanning the whole content for each of them, so the cost was quadratic on large contents).
2586 $tmp = preg_replace_callback(
2587 '/<'.preg_quote($tagtoreplace, '/').'(\s+)([^>]+)>/',
2592 static function ($reg) use ($tagtoreplace) {
2593 // We want to protect the attribute part ... in '<xxx ...>' to avoid transformation by htmlentities() later
2594 $tmpattributes = str_ireplace(array('[', ']'), '_', $reg[2]); // We must never have [ ] inside the attribute string
2595 $tmpattributes = str_ireplace('"', '__DOUBLEQUOTE__', $tmpattributes);
2596 $tmpattributes = preg_replace('/[^a-z0-9_%,\/\?\;\s=&\.\-@:\.#\+]/i', '', $tmpattributes);
2597 //$tmpattributes = preg_replace("/float:\s*(left|right)/", "", $tmpattributes); // Disabled: we must not remove content
2598 return '__BEGINTAGTOREPLACE'.$tagtoreplace.'['.$tmpattributes.']__';
2599 },
2600 $tmp
2601 ) ?? $tmp;
2602 }
2603
2604 $tmp = str_ireplace('&amp', '__ANDNOSEMICOLON__', $tmp);
2605 $tmp = str_ireplace('&quot', '__DOUBLEQUOTENOSEMICOLON__', $tmp);
2606 $tmp = str_ireplace('&lt', '__LESSTHAN__', $tmp);
2607 $tmp = str_ireplace('&gt', '__GREATERTHAN__', $tmp);
2608 }
2609
2610 // Warning: htmlentities encode all special chars that remains (except "'" with ENT_COMPAT).
2611 $result = htmlentities($tmp, ENT_COMPAT, 'UTF-8');
2612
2613 //print $result;
2614
2615 if (count($tmparrayoftags)) {
2616 // Restore protected tags
2617 foreach ($tmparrayoftags as $tagtoreplace) {
2618 $result = str_ireplace('__BEGINTAGTOREPLACE' . $tagtoreplace . '__', '<' . $tagtoreplace . '>', $result);
2619 $result = preg_replace('/__BEGINTAGTOREPLACE' . $tagtoreplace . '\[([^\]]*)\]__/', '<' . $tagtoreplace . ' \1>', $result);
2620 $result = str_ireplace('__ENDTAGTOREPLACE' . $tagtoreplace . '__', '</' . $tagtoreplace . '>', $result);
2621 $result = str_ireplace('__BEGINENDTAGTOREPLACE' . $tagtoreplace . '__', '<' . $tagtoreplace . ' />', $result);
2622 $result = preg_replace('/__BEGINENDTAGTOREPLACE' . $tagtoreplace . '\[([^\]]*)\]__/', '<' . $tagtoreplace . ' \1 />', $result);
2623 }
2624
2625 $result = str_ireplace('__DOUBLEQUOTE__', '"', $result);
2626
2627 $result = str_ireplace('__ANDNOSEMICOLON__', '&amp', $result);
2628 $result = str_ireplace('__DOUBLEQUOTENOSEMICOLON__', '&quot', $result);
2629 $result = str_ireplace('__LESSTHAN__', '&lt', $result);
2630 $result = str_ireplace('__GREATERTHAN__', '&gt', $result);
2631 }
2632
2633 $result = str_ireplace('__SIMPLEQUOTE__', '&#39;', $result);
2634
2635 //$result="\n\n\n".var_export($tmp, true)."\n\n\n".var_export($result, true);
2636
2637 return $result;
2638 }
2639}
2640
2648function dol_strtolower($string, $encoding = "UTF-8")
2649{
2650 if (function_exists('mb_strtolower')) {
2651 return mb_strtolower($string, $encoding);
2652 } else {
2653 return strtolower($string);
2654 }
2655}
2656
2665function dol_strtoupper($string, $encoding = "UTF-8")
2666{
2667 if (function_exists('mb_strtoupper')) {
2668 return mb_strtoupper($string, $encoding);
2669 } else {
2670 return strtoupper($string);
2671 }
2672}
2673
2682function dol_ucfirst($string, $encoding = "UTF-8")
2683{
2684 if (function_exists('mb_substr')) {
2685 return mb_strtoupper(mb_substr($string, 0, 1, $encoding), $encoding) . mb_substr($string, 1, null, $encoding);
2686 } else {
2687 return ucfirst($string);
2688 }
2689}
2690
2699function dol_ucwords($string, $encoding = "UTF-8")
2700{
2701 if (function_exists('mb_convert_case')) {
2702 return mb_convert_case($string, MB_CASE_TITLE, $encoding);
2703 } else {
2704 return ucwords($string);
2705 }
2706}
2707
2708
2714function getCallerInfoString()
2715{
2716 $backtrace = debug_backtrace();
2717 $msg = "";
2718 if (count($backtrace) >= 1) {
2719 $pos = 1;
2720 if (count($backtrace) == 1) {
2721 $pos = 0;
2722 }
2723 $trace = $backtrace[$pos];
2724 if (isset($trace['file'], $trace['line'])) {
2725 $msg = " From {$trace['file']}:{$trace['line']}.";
2726 }
2727 }
2728 return $msg;
2729}
2730
2753function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename = '', $restricttologhandler = '', $logcontext = null)
2754{
2755 global $conf, $user, $debugbar;
2756
2757 // If syslog module enabled
2758 if (!isModEnabled('syslog')) {
2759 return;
2760 }
2761
2762 // Check if we are into execution of code of a website
2763 if (defined('USEEXTERNALSERVER') && !defined('USEDOLIBARRSERVER') && !defined('USEDOLIBARREDITOR')) {
2764 global $website, $websitekey;
2765 if (is_object($website) && !empty($website->ref)) {
2766 $suffixinfilename .= '_website_' . $website->ref;
2767 } elseif (!empty($websitekey)) {
2768 $suffixinfilename .= '_website_' . $websitekey;
2769 }
2770 }
2771
2772 // Check if we have a forced suffix
2773 if (defined('USESUFFIXINLOG')) {
2774 $suffixinfilename .= constant('USESUFFIXINLOG');
2775 }
2776
2777 if ($ident < 0) {
2778 foreach ($conf->loghandlers as $loghandlerinstance) {
2779 $loghandlerinstance->setIdent($ident);
2780 }
2781 }
2782
2783 if (!empty($message)) {
2784 // Test log level
2785 // @phan-suppress-next-line PhanPluginDuplicateArrayKey
2786 $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');
2787
2788 if (!array_key_exists($level, $logLevels)) {
2789 dol_syslog('Error Bad Log Level ' . $level, LOG_ERR);
2790 $level = LOG_ERR;
2791 }
2792 if ($level > getDolGlobalInt('SYSLOG_LEVEL')) {
2793 return;
2794 }
2795
2796 if (!getDolGlobalString('MAIN_SHOW_PASSWORD_INTO_LOG')) {
2797 $message = preg_replace('/password=\'[^\']*\'/', 'password=\'hidden\'', $message); // protection to avoid to have value of password in log
2798 }
2799
2800 // If adding log inside HTML page is required
2801 if ((!empty($_REQUEST['logtohtml']) && getDolGlobalString('MAIN_ENABLE_LOG_TO_HTML'))
2802 || (is_object($user) && $user->hasRight('debugbar', 'read') && is_object($debugbar))
2803 ) {
2804 $ospid = sprintf("%7s", dol_trunc((string) getmypid(), 7, 'right', 'UTF-8', 1));
2805 $osuser = " " . sprintf("%6s", dol_trunc(function_exists('posix_getuid') ? posix_getuid() : '', 6, 'right', 'UTF-8', 1));
2806
2807 $conf->logbuffer[] = dol_print_date(time(), "%Y-%m-%d %H:%M:%S") . " " . sprintf("%-7s", $logLevels[$level]) . " " . $ospid . " " . $osuser . " " . $message;
2808 }
2809
2810 //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output
2811 // If html log tag enabled and url parameter log defined, we show output log on HTML comments
2812 if (getDolGlobalString('MAIN_ENABLE_LOG_INLINE_HTML') && GETPOSTINT("log")) {
2813 print "\n\n<!-- Log start\n";
2814 print dol_escape_htmltag($message) . "\n";
2815 print "Log end -->\n";
2816 }
2817
2818 $data = array(
2819 'message' => $message,
2820 'script' => (isset($_SERVER['PHP_SELF']) ? basename($_SERVER['PHP_SELF'], '.php') : ''),
2821 'level' => $level,
2822 'user' => ((is_object($user) && $user->id) ? $user->login : ''),
2823 'ip' => '',
2824 'osuser' => function_exists('posix_getuid') ? (string) posix_getuid() : '',
2825 'ospid' => (string) getmypid() // on linux, max value is defined into cat /proc/sys/kernel/pid_max
2826 );
2827
2828 // For log, we want the reliable IP first.
2829 $remoteip = getUserRemoteIP(1); // Get ip when page run on a web server
2830 if (!empty($remoteip)) {
2831 $data['ip'] = $remoteip;
2832 // This is when server run behind a reverse proxy
2833 // A HTTP_X_FORWARDED_FOR as format "ip real of user, ip of proxy1, ip of proxy2, ..."
2834 // $data['ip'] is last
2835 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
2836 $tmpips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
2837 $data['ip'] = '';
2838 $foundremoteip = 0;
2839 $j = 0;
2840 foreach ($tmpips as $tmpip) {
2841 $tmpip = trim($tmpip);
2842 if (strtolower($tmpip) == strtolower($remoteip)) {
2843 $foundremoteip = 1;
2844 }
2845 if (empty($data['ip'])) {
2846 $data['ip'] = $tmpip;
2847 } else {
2848 $j++;
2849 $data['ip'] .= (($j == 1) ? ' [via ' : ',') . $tmpip;
2850 }
2851 }
2852 if (!$foundremoteip) {
2853 $j++;
2854 $data['ip'] .= (($j == 1) ? ' [via ' : ',') . $remoteip;
2855 }
2856 $data['ip'] .= (($j > 0) ? ']' : '');
2857 } elseif (!empty($_SERVER['HTTP_CLIENT_IP'])) {
2858 $tmpips = explode(',', $_SERVER['HTTP_CLIENT_IP']);
2859 $data['ip'] = '';
2860 $foundremoteip = 0;
2861 $j = 0;
2862 foreach ($tmpips as $tmpip) {
2863 $tmpip = trim($tmpip);
2864 if (strtolower($tmpip) == strtolower($remoteip)) {
2865 $foundremoteip = 1;
2866 }
2867 if (empty($data['ip'])) {
2868 $data['ip'] = $tmpip;
2869 } else {
2870 $j++;
2871 $data['ip'] .= (($j == 1) ? ' [via ' : ',') . $tmpip;
2872 }
2873 }
2874 if (!$foundremoteip) {
2875 $j++;
2876 $data['ip'] .= (($j == 1) ? ' [via ' : ',') . $remoteip;
2877 }
2878 $data['ip'] .= (($j > 0) ? ']' : '');
2879 }
2880 } elseif (!empty($_SERVER['SERVER_ADDR'])) {
2881 // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
2882 $data['ip'] = (string) $_SERVER['SERVER_ADDR'];
2883 } elseif (!empty($_SERVER['COMPUTERNAME'])) {
2884 // 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).
2885 $data['ip'] = (string) $_SERVER['COMPUTERNAME'];
2886 } else {
2887 $data['ip'] = '???';
2888 }
2889
2890 if (!empty($_SERVER['USERNAME'])) {
2891 // 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).
2892 $data['osuser'] = (string) $_SERVER['USERNAME'];
2893 } elseif (!empty($_SERVER['LOGNAME'])) {
2894 // 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).
2895 $data['osuser'] = (string) $_SERVER['LOGNAME'];
2896 }
2897
2898 // Loop on each log handler and send output
2899 foreach ($conf->loghandlers as $loghandlerinstance) {
2900 if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler) {
2901 continue;
2902 }
2903 $loghandlerinstance->export($data, $suffixinfilename);
2904 }
2905 unset($data);
2906 }
2907
2908 if ($ident > 0) {
2909 foreach ($conf->loghandlers as $loghandlerinstance) {
2910 $loghandlerinstance->setIdent($ident);
2911 }
2912 }
2913}
2914
2926function dolButtonToOpenExportDialog($name, $label, $buttonstring, $exportSiteName, $overwriteGitUrl, $website)
2927{
2928 global $langs, $db;
2929
2930 $form = new Form($db);
2931
2932 $templatenameforexport = $website->name_template; // Example 'website_template-corporate'
2933 if (empty($templatenameforexport)) {
2934 $templatenameforexport = 'website_' . $website->ref;
2935 }
2936
2937 $out = '';
2938 $out .= '<input type="button" class="cursorpointer button bordertransp" id="open-dialog-' . $name . '" value="' . dol_escape_htmltag($buttonstring) . '"/>';
2939
2940 // for generate popup
2941 $out .= '<script nonce="' . getNonce() . '" type="text/javascript">';
2942 $out .= 'jQuery(document).ready(function () {';
2943 $out .= ' jQuery("#open-dialog-' . $name . '").click(function () {';
2944 $out .= ' var dialogHtml = \'';
2945
2946 $dialogcontent = ' <div id="custom-dialog-' . $name . '">';
2947 $dialogcontent .= ' <div style="margin-top: 20px;">';
2948 $dialogcontent .= ' <label for="export-site-' . $name . '"><strong>' . $langs->trans("ExportSiteLabel") . '...</label><br>';
2949 $dialogcontent .= ' <button class="button smallpaddingimp" id="export-site-' . $name . '">' . dol_escape_htmltag($langs->trans("DownloadZip")) . '</button>';
2950 $dialogcontent .= ' </div>';
2951 $dialogcontent .= ' <br>';
2952 $dialogcontent .= ' <div style="margin-top: 20px;">';
2953 $dialogcontent .= ' <strong>' . $langs->trans("ExportSiteGitLabel") . ' ' . $form->textwithpicto('', $langs->trans("SourceFiles"), 1, 'help', '', 0, 3, '') . '</strong><br>';
2954 $dialogcontent .= ' <form action="' . dol_escape_htmltag($overwriteGitUrl) . '" method="POST">';
2955 $dialogcontent .= ' <input type="hidden" name="action" value="overwritesite">';
2956 $dialogcontent .= ' <input type="hidden" name="token" value="' . newToken() . '">';
2957 $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>';
2958 $dialogcontent .= ' <button type="submit" class="button smallpaddingimp" id="overwrite-git-' . $name . '">' . dol_escape_htmltag($langs->trans("ExportIntoGIT")) . '</button>';
2959 $dialogcontent .= ' </form>';
2960 $dialogcontent .= ' </div>';
2961 $dialogcontent .= ' </div>';
2962
2963 $out .= dol_escape_js($dialogcontent);
2964
2965 $out .= '\';';
2966
2967
2968 // Add the content of the dialog to the body of the page
2969 $out .= ' var $dialog = jQuery("#custom-dialog-' . $name . '");';
2970 $out .= ' if ($dialog.length > 0) {
2971 $dialog.remove();
2972 }
2973 jQuery("body").append(dialogHtml);';
2974
2975 // Configuration of popup
2976 $out .= ' jQuery("#custom-dialog-' . $name . '").dialog({';
2977 $out .= ' autoOpen: false,';
2978 $out .= ' modal: true,';
2979 $out .= ' height: 290,';
2980 $out .= ' width: "40%",';
2981 $out .= ' title: "' . dol_escape_js($label) . '",';
2982 $out .= ' });';
2983
2984 // Simulate a click on the original "submit" input to export the site.
2985 $out .= ' jQuery("#export-site-' . $name . '").click(function () {';
2986 $out .= ' console.log("Clic on exportsite.");';
2987 $out .= ' var target = jQuery("input[name=\'' . dol_escape_js($exportSiteName) . '\']");';
2988 $out .= ' console.log("element founded:", target.length > 0);';
2989 $out .= ' if (target.length > 0) { target.click(); }';
2990 $out .= ' jQuery("#custom-dialog-' . $name . '").dialog("close");';
2991 $out .= ' });';
2992
2993 // open popup
2994 $out .= ' jQuery("#custom-dialog-' . $name . '").dialog("open");';
2995 $out .= ' return false;';
2996 $out .= ' });';
2997 $out .= '});';
2998 $out .= '</script>';
2999
3000 return $out;
3001}
3002
3003
3020function dolButtonToOpenUrlInDialogPopup($name, $label, $buttonstring, $url, $disabled = '', $morecss = 'classlink button bordertransp', $jsonopen = '', $jsonclose = '', $accesskey = '')
3021{
3022 global $conf;
3023
3024 if (strpos($url, '?') > 0) {
3025 $url .= '&dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup=' . urlencode($name);
3026 } else {
3027 $url .= '?dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup=' . urlencode($name);
3028 }
3029
3030 if (preg_match('/^https/i', $url)) {
3031 $urltoopen = $url;
3032 } else {
3033 $urltoopen = DOL_URL_ROOT . $url;
3034 }
3035
3036 $out = '';
3037
3038 //print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("MediaFiles")).'" name="file_manager">';
3039 $out .= '<!-- a link for button to open url into a dialog popup -->';
3040 $out .= '<a ' . ($accesskey ? ' accesskey="' . $accesskey . '"' : '') . ' class="cursorpointer reposition button_' . $name . ($morecss ? ' ' . $morecss : '') . '"' . $disabled . ' title="' . dol_escape_htmltag($label) . '"';
3041 if (empty($conf->use_javascript_ajax)) {
3042 $out .= ' href="' . $urltoopen . '" target="_blank"';
3043 } elseif ($jsonopen) {
3044 $out .= ' href="#" onclick="' . $jsonopen . '"';
3045 } else {
3046 $out .= ' href="#"';
3047 }
3048 $out .= '>' . $buttonstring . '</a>';
3049
3050 if (!empty($conf->use_javascript_ajax)) {
3051 // Add code to open url using the popup.
3052 $out .= '<!-- code to open popup and variables to retrieve returned variables -->';
3053 $out .= '<div id="idfordialog' . $name . '" class="hidden">' . (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER') < 2 ? 'div for dialog' : '') . '</div>';
3054
3055 $out .= '<!-- Add js code to open dialog popup on dialog -->';
3056 $out .= '<script nonce="' . getNonce() . '" type="text/javascript">
3057 jQuery(document).ready(function () {
3058 jQuery(".button_' . $name . '").click(function () {
3059 console.log(\'Open popup with jQuery(...).dialog() on URL ' . dol_escape_js($urltoopen) . '\');
3060 var $tmpdialog = $(\'#idfordialog' . $name . '\');
3061 $tmpdialog.html(\'<iframe class="iframedialog" id="iframedialog' . $name . '" style="border: 0px;" src="' . $urltoopen . '" width="100%" height="98%"></iframe>\');
3062 $tmpdialog.dialog({
3063 autoOpen: false,
3064 modal: true,
3065 height: (window.innerHeight - 150),
3066 width: \'80%\',
3067 title: \'' . dol_escape_js($label) . '\',
3068 open: function (event, ui) {
3069 console.log("open popup name=' . $name . '");
3070 },
3071 close: function (event, ui) {
3072 console.log("Popup is closed, run jsonclose = ' . $jsonclose . '");
3073 ' . (empty($jsonclose) || preg_match('/^TODO/', $jsonclose) ? '' : $jsonclose . ';') . '
3074 }
3075 });
3076
3077 $tmpdialog.dialog(\'open\');
3078 return false;
3079 });
3080 });
3081 </script>';
3082 }
3083 return $out;
3084}
3085
3102function dol_fiche_head($links = array(), $active = '0', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
3103{
3104 print dol_get_fiche_head($links, $active, $title, $notab, $picto, $pictoisfullpath, $morehtmlright, $morecss, $limittoshow, $moretabssuffix);
3105}
3106
3124function dol_get_fiche_head($links = array(), $active = '', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '', $dragdropfile = 0, $morecssdiv = '')
3125{
3126 global $conf, $langs, $hookmanager;
3127
3128 // Show title
3129 $showtitle = 1;
3130 if (!empty($conf->dol_optimize_smallscreen)) {
3131 $showtitle = 0;
3132 }
3133
3134 $out = "\n" . '<!-- dol_fiche_head - dol_get_fiche_head -->';
3135
3136 if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
3137 $out .= '<div class="tabs' . ($picto ? '' : ' nopaddingleft') . '" data-role="controlgroup" data-type="horizontal">' . "\n";
3138 }
3139
3140 // Show right part
3141 if ($morehtmlright) {
3142 $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.
3143 }
3144
3145 // Show tabs
3146
3147 // Define max of key (max may be higher than sizeof because of hole due to module disabling some tabs).
3148 $maxkey = -1;
3149 if (is_array($links) && !empty($links)) {
3150 $keys = array_keys($links);
3151 if (count($keys)) {
3152 $maxkey = max($keys);
3153 }
3154 }
3155
3156 // if =0 we don't use the feature
3157 if (empty($limittoshow)) {
3158 $limittoshow = getDolGlobalInt('MAIN_MAXTABS_IN_CARD', 99);
3159 }
3160 if (!empty($conf->dol_optimize_smallscreen)) { // If on smartphone, we limit to 1 tab to show
3161 $limittoshow = 1;
3162 }
3163
3164 $displaytab = 0;
3165 $nbintab = 0;
3166 $popuptab = 0;
3167 $outmore = '';
3168 for ($i = 0; $i <= $maxkey; $i++) {
3169 if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
3170 // If active tab is already present
3171 if ($i >= $limittoshow) {
3172 $limittoshow--;
3173 }
3174 }
3175 }
3176
3177 for ($i = 0; $i <= $maxkey; $i++) {
3178 if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
3179 $isactive = true;
3180 } else {
3181 $isactive = false;
3182 }
3183
3184 if ($i < $limittoshow || $isactive) {
3185 // Output entry with a visible tab
3186 $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])) . ' -->';
3187
3188 if (isset($links[$i][2]) && $links[$i][2] == 'image') {
3189 if (!empty($links[$i][0])) {
3190 $out .= '<a class="tabimage' . ($morecss ? ' ' . $morecss : '') . '" href="' . $links[$i][0] . '">' . $links[$i][1] . '</a>' . "\n";
3191 } else {
3192 $out .= '<span class="tabspan">' . $links[$i][1] . '</span>' . "\n";
3193 }
3194 } elseif (!empty($links[$i][1])) {
3195 //print "x $i $active ".$links[$i][2]." z";
3196 $out .= '<div class="tab tab' . ($isactive ? 'active' : 'unactive') . '" style="margin: 0 !important">';
3197
3198 if (!empty($links[$i][0])) {
3199 $titletoshow = preg_replace('/<.*$/', '', $links[$i][1]);
3200 $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) . '">';
3201 }
3202
3203 if ($displaytab == 0 && $picto) {
3204 $out .= img_picto($title, $picto, '', $pictoisfullpath, 0, 0, '', 'imgTabTitle paddingright marginrightonlyshort');
3205 }
3206
3207 $out .= $links[$i][1];
3208 if (!empty($links[$i][0])) {
3209 $out .= '</a>' . "\n";
3210 }
3211 $out .= empty($links[$i][4]) ? '' : $links[$i][4];
3212 $out .= '</div>';
3213 }
3214
3215 $out .= '</div>';
3216 } else {
3217 // Add entry into the combo popup with the other tabs
3218 if (!$popuptab) {
3219 $popuptab = 1;
3220 $outmore .= '<div class="popuptabset wordwrap">'; // The css used to hide/show popup
3221 }
3222 $outmore_content = '';
3223
3224 if (isset($links[$i][2]) && $links[$i][2] == 'image') {
3225 if (!empty($links[$i][0])) {
3226 $outmore_content .= '<a class="tabimage' . ($morecss ? ' ' . $morecss : '') . '" href="' . $links[$i][0] . '">' . $links[$i][1] . '</a>' . "\n";
3227 } else {
3228 $outmore_content .= '<span class="tabspan">' . $links[$i][1] . '</span>' . "\n";
3229 }
3230 } elseif (!empty($links[$i][1])) {
3231 $outmore_content .= '<a' . (!empty($links[$i][2]) ? ' id="' . $links[$i][2] . '"' : '') . ' class="wordwrap inline-block' . ($morecss ? ' ' . $morecss : '') . '" href="' . $links[$i][0] . '">';
3232 $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.
3233 $outmore_content .= '</a>' . "\n";
3234 }
3235 if ($outmore_content !== '') {
3236 $outmore .= '<div class="popuptab wordwrap" style="display:inherit;">' . $outmore_content . '</div>';
3237 }
3238
3239 $nbintab++;
3240 }
3241
3242 $displaytab = $i + 1;
3243 }
3244 if ($popuptab) {
3245 $outmore .= '</div>';
3246 }
3247
3248 if ($popuptab) { // If there is some tabs not shown
3249 $left = ($langs->trans("DIRECTION") == 'rtl' ? 'right' : 'left');
3250 $right = ($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right');
3251 $widthofpopup = 240;
3252
3253 $tabsname = $moretabssuffix;
3254 if (empty($tabsname)) {
3255 $tabsname = str_replace("@", "", $picto);
3256 }
3257 $out .= '<div id="moretabs' . $tabsname . '" class="inline-block tabsElem valignmiddle">';
3258 if (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER') < 2) {
3259 $out .= '<div class="tab valignmiddle"><a href="#" class="tab moretab inline-block tabunactive valignmiddle"><span class="fa fa-angle-down"></span> <span class="opacitymedium">+' . $nbintab . '</span></a></div>'; // Do not use "reposition" class in the "More".
3260 }
3261 $out .= '<div id="moretabsList' . $tabsname . '" style="width: ' . $widthofpopup . 'px; position: absolute; ' . $left . ': -999em; text-align: ' . $left . '; margin:0px; padding:2px; z-index:10;">';
3262 $out .= $outmore;
3263 $out .= '</div>';
3264 $out .= '<div></div>';
3265 $out .= "</div>\n";
3266
3267 $out .= '<script nonce="' . getNonce() . '">';
3268 $out .= "$('#moretabs" . $tabsname . "').mouseenter( function() {
3269 var x = this.offsetLeft, y = this.offsetTop;
3270 console.log('mouseenter " . $left . " x='+x+' y='+y+' window.innerWidth='+window.innerWidth);
3271 if ((window.innerWidth - x) < " . ($widthofpopup + 10) . ") {
3272 $('#moretabsList" . $tabsname . "').css('" . $right . "','8px');
3273 }
3274 $('#moretabsList" . $tabsname . "').css('" . $left . "','auto');
3275 });
3276 ";
3277 $out .= "$('#moretabs" . $tabsname . "').mouseleave( function() { console.log('mouseleave " . $left . "'); $('#moretabsList" . $tabsname . "').css('" . $left . "','-999em');});";
3278 $out .= "</script>";
3279 }
3280
3281 if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
3282 $out .= "</div>\n";
3283 }
3284
3285 if (!$notab || $notab == -1 || $notab == -2 || $notab == -3 || $notab == -4) {
3286 $out .= "\n" . '<div id="dragDropAreaTabBar" class="tabBar' . ($notab == -1 ? '' : ($notab == -2 ? ' tabBarNoTop' : ((($notab == -3 || $notab == -4) ? ' noborderbottom' : '') . ($notab == -4 ? '' : ' tabBarWithBottom'))));
3287 $out .= ($morecssdiv ? ' ' . $morecssdiv : '');
3288 $out .= '">' . "\n";
3289 }
3290 if (!empty($dragdropfile)) {
3291 // Add the js code to manage the drag and drop
3292 include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
3293 $out .= dragAndDropFileUpload("dragDropAreaTabBar");
3294 }
3295 $parameters = array('tabname' => $active, 'out' => $out);
3296 $reshook = $hookmanager->executeHooks('printTabsHead', $parameters); // This hook usage is called just before output the head of tabs. Take also a look at "completeTabsHead"
3297 if ($reshook > 0) {
3298 $out = $hookmanager->resPrint;
3299 }
3300
3301 return $out;
3302}
3303
3311function dol_fiche_end($notab = 0)
3312{
3313 print dol_get_fiche_end($notab);
3314}
3315
3322function dol_get_fiche_end($notab = 0)
3323{
3324 if (!$notab || $notab == -1) {
3325 return "\n</div>\n";
3326 } else {
3327 return '';
3328 }
3329}
3330
3350function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $onlybanner = 0, $morehtmlright = '')
3351{
3352 global $conf, $form, $user, $langs, $hookmanager, $action;
3353
3354 $error = 0;
3355
3356 $maxvisiblephotos = 1;
3357 $showimage = 1;
3358 $entity = (empty($object->entity) ? $conf->entity : $object->entity);
3359 // @phan-suppress-next-line PhanUndeclaredMethod
3360 $showbarcode = !isModEnabled('barcode') ? 0 : (empty($object->barcode) ? 0 : 1);
3361 if (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !$user->hasRight('barcode', 'lire_advance')) {
3362 $showbarcode = 0;
3363 }
3364 $modulepart = 'unknown';
3365
3366 if (in_array($object->element, ['societe', 'contact', 'product', 'ticket', 'bom'])) {
3367 $modulepart = $object->element;
3368 } elseif ($object->element == 'member') {
3369 $modulepart = 'memberphoto';
3370 } elseif ($object->element == 'user') {
3371 $modulepart = 'userphoto';
3372 }
3373
3374 if (class_exists("Imagick")) {
3375 if ($object->element == 'expensereport' || $object->element == 'propal' || $object->element == 'commande' || $object->element == 'facture' || $object->element == 'supplier_proposal') {
3376 $modulepart = $object->element;
3377 } elseif ($object->element == 'fichinter' || $object->element == 'intervention') {
3378 $modulepart = 'ficheinter';
3379 } elseif ($object->element == 'contrat' || $object->element == 'contract') {
3380 $modulepart = 'contract';
3381 } elseif ($object->element == 'order_supplier') {
3382 $modulepart = 'supplier_order';
3383 } elseif ($object->element == 'invoice_supplier') {
3384 $modulepart = 'supplier_invoice';
3385 }
3386 }
3387
3388 if ($object->element == 'product') {
3390 '@phan-var-force Product $object';
3391 $width = 80;
3392 $cssclass = 'photowithmargin photoref';
3393 $showimage = $object->is_photo_available($conf->product->multidir_output[$entity]);
3394 $maxvisiblephotos = getDolGlobalInt('PRODUCT_MAX_VISIBLE_PHOTO', 5);
3395 if ($conf->browser->layout == 'phone') {
3396 $maxvisiblephotos = 1;
3397 }
3398 $useLinkPathPhoto = getDolGlobalInt('PRODUCT_USE_LINK_PATH_FOR_PHOTO');
3399 if ($showimage || $useLinkPathPhoto) {
3400 $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>';
3401 } else {
3402 if (getDolGlobalString('PRODUCT_NODISPLAYIFNOPHOTO')) {
3403 $nophoto = '';
3404 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
3405 } else { // Show no photo link
3406 $nophoto = '/public/theme/common/nophoto.png';
3407 $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>';
3408 }
3409 }
3410 } elseif ($object->element == 'category') {
3412 '@phan-var-force Categorie $object';
3413 $width = 80;
3414 $cssclass = 'photowithmargin photoref';
3415 $showimage = $object->isAnyPhotoAvailable($conf->categorie->multidir_output[$entity]);
3416 $maxvisiblephotos = getDolGlobalInt('CATEGORY_MAX_VISIBLE_PHOTO', 5);
3417 if ($conf->browser->layout == 'phone') {
3418 $maxvisiblephotos = 1;
3419 }
3420 if ($showimage) {
3421 $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>';
3422 } else {
3423 if (getDolGlobalString('CATEGORY_NODISPLAYIFNOPHOTO')) {
3424 $nophoto = '';
3425 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
3426 } else { // Show no photo link
3427 $nophoto = '/public/theme/common/nophoto.png';
3428 $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>';
3429 }
3430 }
3431 } elseif ($object->element == 'bom') {
3433 '@phan-var-force Bom $object';
3434 $width = 80;
3435 $cssclass = 'photowithmargin photoref';
3436 $showimage = $object->is_photo_available($conf->bom->multidir_output[$entity]);
3437 $maxvisiblephotos = getDolGlobalInt('BOM_MAX_VISIBLE_PHOTO', 5);
3438 if ($conf->browser->layout == 'phone') {
3439 $maxvisiblephotos = 1;
3440 }
3441 if ($showimage) {
3442 $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>';
3443 } else {
3444 if (getDolGlobalString('BOM_NODISPLAYIFNOPHOTO')) {
3445 $nophoto = '';
3446 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
3447 } else { // Show no photo link
3448 $nophoto = '/public/theme/common/nophoto.png';
3449 $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>';
3450 }
3451 }
3452 } elseif ($object->element == 'ticket') {
3453 $width = 80;
3454 $cssclass = 'photoref';
3456 '@phan-var-force Ticket $object';
3457 $showimage = $object->is_photo_available($conf->ticket->multidir_output[$entity] . '/' . $object->ref);
3458 $maxvisiblephotos = getDolGlobalInt('TICKET_MAX_VISIBLE_PHOTO', 2);
3459 if ($conf->browser->layout == 'phone') {
3460 $maxvisiblephotos = 1;
3461 }
3462
3463 if ($showimage) {
3464 $showphoto = $object->show_photos('ticket', $conf->ticket->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0);
3465 if ($object->nbphoto > 0) {
3466 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">' . $showphoto . '</div>';
3467 } else {
3468 $showimage = 0;
3469 }
3470 }
3471 if (!$showimage) {
3472 if (getDolGlobalString('TICKET_NODISPLAYIFNOPHOTO')) {
3473 $nophoto = '';
3474 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
3475 } else { // Show no photo link
3476 $nophoto = img_picto('No photo', 'object_ticket');
3477 $morehtmlleft .= '<!-- No photo to show -->';
3478 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
3479 $morehtmlleft .= $nophoto;
3480 $morehtmlleft .= '</div></div>';
3481 }
3482 }
3483 } else {
3484 // $modulepart may have been set previously if Imagick class exists (see before).
3485 if ($modulepart != 'unknown' || method_exists($object, 'getDataToShowPhoto')) {
3486 $phototoshow = '';
3487 // Check if a preview file is available
3488 if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice', 'expensereport')) && class_exists("Imagick")) {
3489 $objectref = dol_sanitizeFileName($object->ref);
3490 $dir_output = (empty($conf->$modulepart->multidir_output[$entity]) ? $conf->$modulepart->dir_output : $conf->$modulepart->multidir_output[$entity]) . "/";
3491 if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice'))) {
3492 $subdir = get_exdir($object->id, 2, 0, 1, $object, $modulepart);
3493 $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
3494 } else {
3495 $subdir = get_exdir($object->id, 0, 0, 1, $object, $modulepart);
3496 }
3497 if (empty($subdir)) {
3498 $subdir = 'errorgettingsubdirofobject'; // Protection to avoid to return empty path
3499 }
3500
3501 $filepath = $dir_output . $subdir . "/";
3502
3503 $filepdf = $filepath . $objectref . ".pdf";
3504 $relativepath = $subdir . '/' . $objectref . '.pdf';
3505
3506 // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png")
3507 $fileimage = $filepdf . '_preview.png';
3508 $relativepathimage = $relativepath . '_preview.png';
3509
3510 $pdfexists = file_exists($filepdf);
3511
3512 // If PDF file exists
3513 if ($pdfexists) {
3514 // Conversion du PDF en image png si fichier png non existent
3515 if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf))) {
3516 if (!getDolGlobalString('MAIN_DISABLE_PDF_THUMBS')) { // If you experience trouble with pdf thumb generation and imagick, you can disable here.
3517 include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
3518 $ret = dol_convert_file($filepdf, 'png', $fileimage, '0'); // Convert first page of PDF into a file _preview.png
3519 if ($ret < 0) {
3520 $error++;
3521 }
3522 }
3523 }
3524 }
3525
3526 if ($pdfexists && !$error) {
3527 $heightforphotref = 80;
3528 if (!empty($conf->dol_optimize_smallscreen)) {
3529 $heightforphotref = 60;
3530 }
3531 // If the preview file is found
3532 if (file_exists($fileimage)) {
3533 $phototoshow = '<div class="photoref">';
3534 $phototoshow .= '<img height="' . $heightforphotref . '" class="photo photowithborder" src="' . DOL_URL_ROOT . '/viewimage.php?modulepart=apercu' . $modulepart . '&amp;file=' . urlencode($relativepathimage) . '">';
3535 $phototoshow .= '</div>';
3536 }
3537 }
3538 } elseif (!$phototoshow) { // example if modulepart = 'societe' or 'photo' or 'memberphoto'
3539 $phototoshow .= $form->showphoto($modulepart, $object, 0, 0, 0, 'photowithmargin photoref', 'small', 1, 0);
3540 }
3541
3542 if ($phototoshow) {
3543 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">';
3544 $morehtmlleft .= $phototoshow;
3545 $morehtmlleft .= '</div>';
3546 }
3547 }
3548
3549 if (empty($phototoshow)) { // Show No photo link (picto of object)
3550 if ($object->element == 'action') {
3551 $width = 80;
3552 $cssclass = 'photorefcenter';
3553 $nophoto = img_picto('No photo', 'title_agenda');
3554 } else {
3555 $width = 14;
3556 $cssclass = 'photorefcenter';
3557 $picto = $object->picto; // @phan-suppress-current-line PhanUndeclaredProperty
3558 $prefix = 'object_';
3559 if ($object->element == 'project' && !$object->public) { // @phan-suppress-current-line PhanUndeclaredProperty
3560 $picto = 'project'; // instead of projectpub
3561 }
3562 if (strpos($picto, 'fontawesome_') !== false) {
3563 $prefix = '';
3564 }
3565 $nophoto = img_picto('No photo', $prefix . $picto);
3566 }
3567 $morehtmlleft .= '<!-- No photo to show -->';
3568 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
3569 $morehtmlleft .= $nophoto;
3570 $morehtmlleft .= '</div></div>';
3571 }
3572 }
3573
3574 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)) {
3575 $morehtmlref .= '<div style="clear: both;"></div>';
3576 $morehtmlref .= '<div class="smallimp refidno opacitymedium banner-object-technical-id">';
3577 $morehtmlref .= $langs->trans("TechnicalID") . ': ' . ((int) $object->id);
3578 $morehtmlref .= '</div>';
3579 }
3580
3581
3582 // Show barcode
3583 if ($showbarcode) {
3584 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">' . $form->showbarcode($object, 100, 'photoref valignmiddle') . '</div>';
3585 }
3586
3587 if ($object->element == 'societe') {
3589 if (!empty($conf->use_javascript_ajax) && $user->hasRight('societe', 'creer') && getDolGlobalString('MAIN_DIRECT_STATUS_UPDATE')) {
3590 $morehtmlstatus .= ajax_object_onoff($object, 'status', 'status', 'InActivity', 'ActivityCeased');
3591 } else {
3592 $morehtmlstatus .= $object->getLibStatut(6);
3593 }
3594 } elseif ($object->element == 'product') {
3596 //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Sell").') ';
3597 if (!empty($conf->use_javascript_ajax) && $user->hasRight('produit', 'creer') && getDolGlobalString('MAIN_DIRECT_STATUS_UPDATE')) {
3598 $morehtmlstatus .= ajax_object_onoff($object, 'status', 'status', 'ProductStatusOnSell', 'ProductStatusNotOnSell');
3599 } else {
3600 $morehtmlstatus .= '<span class="statusrefsell">' . $object->getLibStatut(6, 0) . '</span>';
3601 }
3602 $morehtmlstatus .= ' &nbsp; ';
3603 //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Buy").') ';
3604 if (!empty($conf->use_javascript_ajax) && $user->hasRight('produit', 'creer') && getDolGlobalString('MAIN_DIRECT_STATUS_UPDATE')) {
3605 $morehtmlstatus .= ajax_object_onoff($object, 'status_buy', 'status_buy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy');
3606 } else {
3607 $morehtmlstatus .= '<span class="statusrefbuy">' . $object->getLibStatut(6, 1) . '</span>';
3608 }
3609 } elseif (in_array($object->element, array('salary'))) {
3611 '@phan-var-force Salary $object';
3612 $tmptxt = $object->getLibStatut(6, $object->alreadypaid);
3613 if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
3614 $tmptxt = $object->getLibStatut(5, $object->alreadypaid);
3615 }
3616 $morehtmlstatus .= $tmptxt;
3617 } elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier'))) {
3619 '@phan-var-force Facture|FactureFournisseur|CommonInvoice $object';
3620 if (!isset($object->alreadypaid)) {
3621 $object->totalpaid = $object->getSommePaiement(0);
3622 $object->totalcreditnotes = $object->getSumCreditNotesUsed(0);
3623 $object->totaldeposits = $object->getSumDepositsUsed(0);
3624 $object->alreadypaid = $object->totalpaid + $object->totalcreditnotes + $object->totaldeposits;
3625 }
3626 $tmptxt = $object->getLibStatut(6, (float) $object->alreadypaid);
3627 if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
3628 $tmptxt = $object->getLibStatut(5, (float) $object->alreadypaid);
3629 }
3630 $morehtmlstatus .= $tmptxt;
3631 } elseif (in_array($object->element, array('chargesociales', 'loan', 'tva'))) { // TODO Move this to use ->alreadypaid like for invoices
3633 '@phan-var-force ChargeSociales|Loan|Tva $object';
3634 $tmptxt = $object->getLibStatut(6, $object->totalpaid);
3635 if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
3636 $tmptxt = $object->getLibStatut(5, $object->totalpaid);
3637 }
3638 $morehtmlstatus .= $tmptxt;
3639 } elseif ($object->element == 'contrat' || $object->element == 'contract') {
3641 if ($object->status == 0) {
3642 $morehtmlstatus .= $object->getLibStatut(5);
3643 } else {
3644 $morehtmlstatus .= $object->getLibStatut(4);
3645 }
3646 } elseif ($object->element == 'facturerec') {
3648 '@phan-var-force FactureRec $object';
3649 if ($object->frequency == 0) {
3650 $morehtmlstatus .= $object->getLibStatut(2);
3651 } else {
3652 $morehtmlstatus .= $object->getLibStatut(5);
3653 }
3654 } elseif ($object->element == 'project_task') {
3656 $tmptxt = $object->getLibStatut(4);
3657 $morehtmlstatus .= $tmptxt;
3658 } elseif (method_exists($object, 'getLibStatut')) { // Generic case for status
3659 $tmptxt = $object->getLibStatut(6);
3660 if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
3661 $tmptxt = $object->getLibStatut(5);
3662 }
3663 $morehtmlstatus .= $tmptxt;
3664 }
3665
3666 // Say if object was dispatched/transferred "into accountancy"
3667 if (isModEnabled('accounting') && in_array($object->element, array('bank', 'paiementcharge', 'facture', 'invoice', 'invoice_supplier', 'expensereport', 'payment_various'))) {
3668 // Note: For 'chargesociales', 'salaries'... this is the payments that are dispatched (so element = 'bank')
3669 if (method_exists($object, 'getVentilExportCompta')) {
3670 $accounted = $object->getVentilExportCompta(1);
3671 $langs->load("accountancy");
3672 $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>';
3673 }
3674 }
3675
3676 // Add alias for thirdparty
3677 if (!empty($object->name_alias)) {
3679 '@phan-var-force Societe $object';
3680 $morehtmlref .= '<div class="refidno opacitymedium banner-object-name-alias">' . dol_escape_htmltag($object->name_alias) . '</div>';
3681 }
3682
3683 // Add label
3684 if (in_array($object->element, array('product', 'bank_account', 'project_task'))) {
3686 if (!empty($object->label)) {
3687 $morehtmlref .= '<div class="refidno banner-object-label">' . $object->label . '</div>';
3688 }
3689 }
3690 // Show address and email
3691 if (method_exists($object, 'getBannerAddress') && !in_array($object->element, array('product', 'bookmark', 'ecm_directories', 'ecm_files'))) {
3692 $moreaddress = $object->getBannerAddress('refaddress', $object); // address, email, url, social networks
3693 if ($moreaddress) {
3694 $morehtmlref .= '<div class="refidno refaddress">';
3695 $morehtmlref .= $moreaddress;
3696 $morehtmlref .= '</div>';
3697 }
3698 }
3699
3700 $parameters = array('morehtmlref' => &$morehtmlref, 'moreparam' => &$moreparam, 'morehtmlleft' => &$morehtmlleft, 'morehtmlstatus' => &$morehtmlstatus, 'morehtmlright' => &$morehtmlright);
3701 $reshook = $hookmanager->executeHooks('formDolBanner', $parameters, $object, $action);
3702 if ($reshook < 0) {
3703 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
3704 } elseif (empty($reshook)) {
3705 $morehtmlref .= $hookmanager->resPrint;
3706 } elseif ($reshook > 0) {
3707 $morehtmlref = $hookmanager->resPrint;
3708 }
3709
3710 // $morehtml is the right part (link "Back to list")
3711 // $morehtmlref is the part after the ref
3712 // $morehtmlleft is the picto or photo of banner
3713 // $morehtmlstatus is part under the status
3714 // $morehtmlright is part of htmlright
3715
3716 print '<div class="' . ($onlybanner ? 'arearefnobottom ' : 'arearef ') . 'heightref valignmiddle centpercent object-banner-tab-container" data-module-part="'.dolPrintHTMLForAttribute($modulepart).'">';
3717 print $form->showrefnav($object, $paramid, $morehtml, $shownav, $fieldid, $fieldref, $morehtmlref, $moreparam, $nodbprefix, $morehtmlleft, $morehtmlstatus, $morehtmlright);
3718 print '</div>';
3719 print '<div class="underrefbanner clearboth"></div>';
3720}
3721
3731function fieldLabel($langkey, $fieldkey, $fieldrequired = 0)
3732{
3733 global $langs;
3734 $ret = '';
3735 if ($fieldrequired) {
3736 $ret .= '<span class="fieldrequired">';
3737 }
3738 $ret .= '<label for="' . $fieldkey . '">';
3739 $ret .= $langs->trans($langkey);
3740 $ret .= '</label>';
3741 if ($fieldrequired) {
3742 $ret .= '</span>';
3743 }
3744 return $ret;
3745}
3746
3760function dol_format_address($object, $withcountry = 0, $sep = "\n", $outputlangs = null, $mode = 0, $extralangcode = '')
3761{
3762 global $langs, $hookmanager;
3763
3764 $ret = '';
3765 $countriesusingstate = array('AU', 'CA', 'US', 'IN', 'GB', 'ES', 'UK', 'TR', 'CN'); // See also MAIN_FORCE_STATE_INTO_ADDRESS
3766
3767 // See format of addresses on https://en.wikipedia.org/wiki/Address
3768 // Address
3769 if (empty($mode)) {
3770 $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)));
3771 }
3772 // Zip/Town/State
3773 if (isset($object->country_code) && in_array($object->country_code, array('AU', 'CA', 'US', 'CN')) || getDolGlobalString('MAIN_FORCE_STATE_INTO_ADDRESS')) {
3774 // US: title firstname name \n address lines \n town, state, zip \n country
3775 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
3776 $ret .= (($ret && $town) ? $sep : '') . $town;
3777
3778 if (!empty($object->state)) {
3779 $ret .= ($ret ? ($town ? ", " : $sep) : '') . $object->state;
3780 }
3781 if (!empty($object->zip)) {
3782 $ret .= ($ret ? (($town || $object->state) ? ", " : $sep) : '') . $object->zip;
3783 }
3784 } elseif (isset($object->country_code) && in_array($object->country_code, array('GB', 'UK'))) {
3785 // UK: title firstname name \n address lines \n town state \n zip \n country
3786 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
3787 $ret .= ($ret ? $sep : '') . $town;
3788 if (!empty($object->state)) {
3789 $ret .= ($ret ? ", " : '') . $object->state;
3790 }
3791 if (!empty($object->zip)) {
3792 $ret .= ($ret ? $sep : '') . $object->zip;
3793 }
3794 } elseif (isset($object->country_code) && in_array($object->country_code, array('ES', 'TR'))) {
3795 // ES: title firstname name \n address lines \n zip town \n state \n country
3796 $ret .= ($ret ? $sep : '') . $object->zip;
3797 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
3798 $ret .= ($town ? (($object->zip ? ' ' : '') . $town) : '');
3799 if (!empty($object->state)) {
3800 $ret .= $sep . $object->state;
3801 }
3802 } elseif (isset($object->country_code) && in_array($object->country_code, array('JP'))) {
3803 // JP: In romaji, title firstname name\n address lines \n [state,] town zip \n country
3804 // See https://www.sljfaq.org/afaq/addresses.html
3805 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
3806 $ret .= ($ret ? $sep : '') . ($object->state ? $object->state . ', ' : '') . $town . ($object->zip ? ' ' : '') . $object->zip;
3807 } elseif (isset($object->country_code) && in_array($object->country_code, array('IT'))) {
3808 // IT: title firstname name\n address lines \n zip town state_code \n country
3809 $ret .= ($ret ? $sep : '') . $object->zip;
3810 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
3811 $ret .= ($town ? (($object->zip ? ' ' : '') . $town) : '');
3812 $ret .= (empty($object->state_code) ? '' : (' ' . $object->state_code));
3813 } else {
3814 // Other: title firstname name \n address lines \n zip town[, state] \n country
3815 $town = (($extralangcode && !empty($object->array_languages['address'][$extralangcode])) ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
3816 $ret .= !empty($object->zip) ? (($ret ? $sep : '') . $object->zip) : '';
3817 $ret .= ($town ? (($object->zip ? ' ' : ($ret ? $sep : '')) . $town) : '');
3818 if (!empty($object->state) && in_array($object->country_code, $countriesusingstate)) {
3819 $ret .= ($ret ? ", " : '') . $object->state;
3820 }
3821 }
3822
3823 if (!is_object($outputlangs)) {
3824 $outputlangs = $langs;
3825 }
3826 if ($withcountry) {
3827 $langs->load("dict");
3828 $ret .= (empty($object->country_code) ? '' : ($ret ? $sep : '') . $outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country" . $object->country_code)));
3829 }
3830 if ($hookmanager) {
3831 $parameters = array('withcountry' => $withcountry, 'sep' => $sep, 'outputlangs' => $outputlangs, 'mode' => $mode, 'extralangcode' => $extralangcode);
3832 $reshook = $hookmanager->executeHooks('formatAddress', $parameters, $object);
3833 if ($reshook > 0) {
3834 $ret = '';
3835 }
3836 $ret .= $hookmanager->resPrint;
3837 }
3838
3839 return $ret;
3840}
3841
3842
3843
3853function dol_strftime($fmt, $ts = false, $is_gmt = false)
3854{
3855 if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
3856 return dol_print_date($ts, $fmt, $is_gmt);
3857 } else {
3858 return 'Error date outside supported range';
3859 }
3860}
3861
3884function dol_print_date($time, $format = '', $tzoutput = 'auto', $outputlangs = null, $encodetooutput = false, $decorate = 0)
3885{
3886 global $conf, $langs;
3887
3888 // If date undefined or "", we return ""
3889 if (dol_strlen((string) $time) == 0) {
3890 return ''; // $time=0 allowed (it means 01/01/1970 00:00:00)
3891 }
3892
3893 if ($tzoutput === 'auto') {
3894 $tzoutput = (empty($conf) ? 'tzserver' : (isset($conf->tzuserinputkey) ? $conf->tzuserinputkey : 'tzserver'));
3895 }
3896
3897 // Clean parameters
3898 $to_gmt = false; // false if we want date in server timezone, true if we want to add offset
3899 $offsettz = $offsetdst = 0;
3900 if ($tzoutput) {
3901 $to_gmt = true; // For backward compatibility
3902 if (is_string($tzoutput)) {
3903 if ($tzoutput == 'tzserver') {
3904 $to_gmt = false;
3905 $offsettzstring = @date_default_timezone_get(); // Example 'Europe/Berlin' or 'Indian/Reunion'
3906 // @phan-suppress-next-line PhanPluginRedundantAssignment
3907 $offsettz = 0; // Timezone offset with server timezone (because to_gmt is false), so 0
3908 // @phan-suppress-next-line PhanPluginRedundantAssignment
3909 $offsetdst = 0; // Dst offset with server timezone (because to_gmt is false), so 0
3910 } elseif ($tzoutput == 'tzuser' || $tzoutput == 'tzuserrel') {
3911 $to_gmt = true;
3912 // if no session (by example in cron) may use MAIN_DOLIBARR_USER_TIMEZONE instead UTC
3913 $offsettzstring = (empty($_SESSION['dol_tz_string']) ? getDolGlobalString('MAIN_DOLIBARR_USER_TIMEZONE', 'UTC') : $_SESSION['dol_tz_string']); // Example 'Europe/Berlin' or 'Indian/Reunion'
3914
3915 if (class_exists('DateTimeZone')) {
3916 try {
3917 $user_date_tz = new DateTimeZone($offsettzstring);
3918 } catch (Exception $e) {
3919 // Bad value for $offsettzstring
3920 dol_syslog("DateInvalidTimeZoneException for timezone string '".$offsettzstring."'. Falling back to UTC.", LOG_ERR);
3921 $user_date_tz = new DateTimeZone('UTC'); // Force valid timezone as UTC
3922 }
3923 $user_dt = new DateTime();
3924 $user_dt->setTimezone($user_date_tz);
3925 $user_dt->setTimestamp($tzoutput == 'tzuser' ? dol_now() : (int) $time);
3926 $offsettz = $user_dt->getOffset(); // should include dst ?
3927 } else { // with old method (The 'tzuser' was processed like the 'tzuserrel')
3928 $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60; // Will not be used anymore
3929 $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60; // Will not be used anymore
3930 }
3931 }
3932 }
3933 }
3934 if (!is_object($outputlangs)) {
3935 $outputlangs = $langs;
3936 }
3937 if (!$format) {
3938 $format = 'daytextshort';
3939 }
3940
3941 // Do we have to reduce the length of date (year on 2 chars) to save space.
3942 // Note: dayinputnoreduce is same than day but no reduction of year length will be done
3943 $reduceformat = (!empty($conf->dol_optimize_smallscreen) && in_array($format, array('day', 'dayhour', 'dayhoursec'))) ? 1 : 0; // Test on original $format param.
3944 $format = preg_replace('/inputnoreduce/', '', $format); // so format 'dayinputnoreduce' is processed like day
3945 $formatwithoutreduce = preg_replace('/reduceformat/', '', $format);
3946 if ($formatwithoutreduce != $format) {
3947 $format = $formatwithoutreduce;
3948 $reduceformat = 1;
3949 } // so format 'dayreduceformat' is processed like day
3950
3951 // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
3952 // TODO Add format daysmallyear and dayhoursmallyear
3953 if ($format == 'day') {
3954 $format = ($outputlangs->trans("FormatDateShort") != "FormatDateShort" ? $outputlangs->trans("FormatDateShort") : $conf->format_date_short);
3955 } elseif ($format == 'hour') {
3956 $format = ($outputlangs->trans("FormatHourShort") != "FormatHourShort" ? $outputlangs->trans("FormatHourShort") : $conf->format_hour_short);
3957 } elseif ($format == 'hoursec') {
3958 $s1 = $outputlangs->trans("FormatDateShort");
3959 $s2 = $outputlangs->trans("FormatDateHourSecShort");
3960 $s3 = trim(preg_replace('/'.preg_quote($s1, '/').'/', '', $s2)); // Try to guess the format for FormatHourSecShort using FormatDateShort and FormatDateHourSecShort
3961 $format = $s3;
3962 //$format = ($outputlangs->trans("FormatHourSecShort") != "FormatHourSecShort" ? $outputlangs->trans("FormatHourSecShort") : ($s3 ? $s3 : $conf->format_hour_sec_short));
3963 } elseif ($format == 'hourduration') {
3964 $format = ($outputlangs->trans("FormatHourShortDuration") != "FormatHourShortDuration" ? $outputlangs->trans("FormatHourShortDuration") : $conf->format_hour_short_duration);
3965 } elseif ($format == 'daytext') {
3966 $format = ($outputlangs->trans("FormatDateText") != "FormatDateText" ? $outputlangs->trans("FormatDateText") : $conf->format_date_text);
3967 } elseif ($format == 'daytextshort') {
3968 $format = ($outputlangs->trans("FormatDateTextShort") != "FormatDateTextShort" ? $outputlangs->trans("FormatDateTextShort") : $conf->format_date_text_short);
3969 } elseif ($format == 'dayhour') {
3970 $format = ($outputlangs->trans("FormatDateHourShort") != "FormatDateHourShort" ? $outputlangs->trans("FormatDateHourShort") : $conf->format_date_hour_short);
3971 } elseif ($format == 'dayhoursec') {
3972 $format = ($outputlangs->trans("FormatDateHourSecShort") != "FormatDateHourSecShort" ? $outputlangs->trans("FormatDateHourSecShort") : $conf->format_date_hour_sec_short);
3973 } elseif ($format == 'dayhourtext') {
3974 $format = ($outputlangs->trans("FormatDateHourText") != "FormatDateHourText" ? $outputlangs->trans("FormatDateHourText") : $conf->format_date_hour_text);
3975 } elseif ($format == 'dayhourtextshort') {
3976 $format = ($outputlangs->trans("FormatDateHourTextShort") != "FormatDateHourTextShort" ? $outputlangs->trans("FormatDateHourTextShort") : $conf->format_date_hour_text_short);
3977 } elseif ($format == 'dayhourlog') {
3978 // Format not sensitive to language
3979 $format = '%Y%m%d%H%M%S';
3980 } elseif ($format == 'dayhourlogsmall') {
3981 // Format not sensitive to language
3982 $format = '%y%m%d%H%M';
3983 } elseif ($format == 'dayhourldap') {
3984 $format = '%Y%m%d%H%M%SZ';
3985 } elseif ($format == 'dayhourxcard') {
3986 $format = '%Y%m%dT%H%M%SZ';
3987 } elseif ($format == 'dayxcard') {
3988 $format = '%Y%m%d';
3989 } elseif ($format == 'dayrfc') {
3990 $format = '%Y-%m-%d'; // DATE_RFC3339
3991 } elseif ($format == 'dayhourrfc') {
3992 $format = '%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339
3993 } elseif ($format == 'standard') {
3994 $format = '%Y-%m-%d %H:%M:%S';
3995 }
3996
3997 if ($reduceformat) {
3998 $format = str_replace('%Y', '%y', $format);
3999 $format = str_replace('yyyy', 'yy', $format);
4000 }
4001
4002 // Clean format
4003 if (preg_match('/%b/i', $format)) { // There is some text to translate
4004 // We inhibit translation to text made by strftime functions. We will use trans instead later.
4005 $format = str_replace('%b', '__b__', $format);
4006 $format = str_replace('%B', '__B__', $format);
4007 }
4008 if (preg_match('/%a/i', $format)) { // There is some text to translate
4009 // We inhibit translation to text made by strftime functions. We will use trans instead later.
4010 $format = str_replace('%a', '__a__', $format);
4011 $format = str_replace('%A', '__A__', $format);
4012 }
4013
4014 // Analyze date
4015 $reg = array();
4016 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
4017 dol_print_error(null, "Functions.lib::dol_print_date function called with a bad value" . getCallerInfoString());
4018 return '';
4019 } 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
4020 // This part of code should not be used anymore.
4021 dol_syslog("Functions.lib::dol_print_date function called with a bad value" . getCallerInfoString(), LOG_WARNING);
4022 // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
4023 $syear = (!empty($reg[1]) ? $reg[1] : '');
4024 $smonth = (!empty($reg[2]) ? $reg[2] : '');
4025 $sday = (!empty($reg[3]) ? $reg[3] : '');
4026 $shour = (!empty($reg[4]) ? $reg[4] : '');
4027 $smin = (!empty($reg[5]) ? $reg[5] : '');
4028 $ssec = (!empty($reg[6]) ? $reg[6] : '');
4029
4030 $time = dol_mktime((int) $shour, (int) $smin, (int) $ssec, (int) $smonth, (int) $sday, (int) $syear, true);
4031
4032 if ($to_gmt) {
4033 $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
4034 } else {
4035 $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
4036 }
4037 $dtts = new DateTime();
4038 $dtts->setTimestamp($time);
4039 $dtts->setTimezone($tzo);
4040 $newformat = str_replace(
4041 array('%Y', '%y', '%m', '%d', '%H', '%I', '%M', '%S', '%p', 'T', 'Z', '__a__', '__A__', '__b__', '__B__'),
4042 array('Y', 'y', 'm', 'd', 'H', 'h', 'i', 's', 'A', '__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
4043 $format
4044 );
4045 $ret = $dtts->format($newformat);
4046 $ret = str_replace(
4047 array('__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
4048 array('T', 'Z', '__a__', '__A__', '__b__', '__B__'),
4049 $ret
4050 );
4051 } else {
4052 // Date is a timestamps
4053 if ($time < 100000000000) { // Protection against bad date values
4054 $dtts = new DateTime();
4055 //var_dump($tzoutput.' '.$offsettzstring.' '.$offsettz.$offsetdst.' x '.$to_gmt);
4056 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
4057 $timetouse = (int) $time + $offsettz + $offsetdst; // TODO We could be able to disable use of offsettz and offsetdst to use only offsettzstring.
4058
4059 $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
4060 $dtts->setTimezone($tzo); // important: must be before the setTimestamp
4061 $dtts->setTimestamp($timetouse);
4062 } else {
4063 $timetouse = (int) $time + $offsettz + $offsetdst; // TODO We could be able to disable use of offsettz and offsetdst to use only offsettzstring.
4064
4065 $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
4066 $dtts->setTimestamp($timetouse); // TODO May be we can invert setTimestamp and setTimezone
4067 $dtts->setTimezone($tzo);
4068 }
4069
4070 $newformat = str_replace(
4071 array('%Y', '%y', '%m', '%d', '%H', '%I', '%M', '%S', '%p', '%w', 'T', 'Z', '__a__', '__A__', '__b__', '__B__'),
4072 array('Y', 'y', 'm', 'd', 'H', 'h', 'i', 's', 'A', 'w', '__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
4073 $format
4074 );
4075
4076 $ret = $dtts->format($newformat);
4077 //var_dump($timetouse, $offsettz, $offsetdst, $tzo, $newformat, $ret);
4078 $ret = str_replace(
4079 array('__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
4080 array('T', 'Z', '__a__', '__A__', '__b__', '__B__'),
4081 $ret
4082 );
4083 } else {
4084 $ret = 'Bad value ' . $time . ' for date';
4085 }
4086 }
4087
4088 if (preg_match('/__b__/i', $format)) {
4089 $timetouse = $time + $offsettz + $offsetdst; // TODO We could be able to disable use of offsettz and offsetdst to use only offsettzstring.
4090
4091 if ($to_gmt) {
4092 $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
4093 } else {
4094 $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
4095 }
4096 $dtts = new DateTime();
4097 $dtts->setTimestamp($timetouse);
4098 $dtts->setTimezone($tzo);
4099 $month = (int) $dtts->format("m");
4100 $month = sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'.
4101 if ($encodetooutput) {
4102 $monthtext = $outputlangs->transnoentities('Month' . $month);
4103 $monthtextshort = $outputlangs->transnoentities('MonthShort' . $month);
4104 } else {
4105 $monthtext = $outputlangs->transnoentitiesnoconv('Month' . $month);
4106 $monthtextshort = $outputlangs->transnoentitiesnoconv('MonthShort' . $month);
4107 }
4108 //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
4109 $ret = str_replace('__b__', $monthtextshort, $ret);
4110 $ret = str_replace('__B__', $monthtext, $ret);
4111 //print 'x'.$outputlangs->charset_output.'-'.$ret.'x';
4112 //return $ret;
4113 }
4114 if (preg_match('/__a__/i', $format)) {
4115 //print "time=$time offsettz=$offsettz offsetdst=$offsetdst offsettzstring=$offsettzstring";
4116 $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
4117
4118 if ($to_gmt) {
4119 $tzo = new DateTimeZone('UTC');
4120 } else {
4121 $tzo = new DateTimeZone(date_default_timezone_get());
4122 }
4123 $dtts = new DateTime();
4124 $dtts->setTimestamp($timetouse);
4125 $dtts->setTimezone($tzo);
4126 $w = $dtts->format("w");
4127 $dayweek = $outputlangs->transnoentitiesnoconv('Day' . $w);
4128
4129 $ret = str_replace('__A__', $dayweek, $ret);
4130 $ret = str_replace('__a__', dol_substr($dayweek, 0, 3), $ret);
4131 }
4132
4133 if ($decorate) {
4134 $ret = preg_replace('/(\d\d:\d\d [AP]M)$/', '<span class="'.($decorate === 1 ? 'opacitymedium' : $decorate).'">\1</span>', $ret);
4135 $ret = preg_replace('/(\d\d:\d\d)$/', '<span class="'.($decorate === 1 ? 'opacitymedium' : $decorate).'">\1</span>', $ret);
4136 }
4137
4138 return $ret;
4139}
4140
4141
4162function dol_getdate($timestamp, $fast = false, $forcetimezone = '')
4163{
4164 if ($timestamp === '') {
4165 return array();
4166 }
4167
4168 $datetimeobj = new DateTime();
4169 $datetimeobj->setTimestamp($timestamp); // Use local PHP server timezone
4170 if ($forcetimezone && $forcetimezone != 'tzserver') {
4171 $datetimeobj->setTimezone(new DateTimeZone($forcetimezone == 'gmt' ? 'UTC' : $forcetimezone)); // (add timezone relative to the date entered)
4172 }
4173 $arrayinfo = array(
4174 'year' => ((int) date_format($datetimeobj, 'Y')),
4175 'mon' => ((int) date_format($datetimeobj, 'm')),
4176 'mday' => ((int) date_format($datetimeobj, 'd')),
4177 'wday' => ((int) date_format($datetimeobj, 'w')),
4178 'yday' => ((int) date_format($datetimeobj, 'z')),
4179 'hours' => ((int) date_format($datetimeobj, 'H')),
4180 'minutes' => ((int) date_format($datetimeobj, 'i')),
4181 'seconds' => ((int) date_format($datetimeobj, 's')),
4182 '0' => $timestamp
4183 );
4184
4185 return $arrayinfo;
4186}
4187
4209function dol_mktime($hour, $minute, $second, $month, $day, $year, $gm = 'auto', $check = 1)
4210{
4211 global $conf;
4212 //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
4213
4214 if ($gm === 'auto') {
4215 $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
4216 }
4217 //print 'gm:'.$gm.' gm === auto:'.($gm === 'auto').'<br>';exit;
4218
4219 // Clean parameters
4220 if ($hour == -1 || empty($hour)) {
4221 $hour = 0;
4222 }
4223 if ($minute == -1 || empty($minute)) {
4224 $minute = 0;
4225 }
4226 if ($second == -1 || empty($second)) {
4227 $second = 0;
4228 }
4229
4230 // Check parameters
4231 if ($check) {
4232 if (!$month || !$day) {
4233 return '';
4234 }
4235 if ($day > 31) {
4236 return '';
4237 }
4238 if ($month > 12) {
4239 return '';
4240 }
4241 if ($hour < 0 || $hour > 24) {
4242 return '';
4243 }
4244 if ($minute < 0 || $minute > 60) {
4245 return '';
4246 }
4247 if ($second < 0 || $second > 60) {
4248 return '';
4249 }
4250 }
4251
4252 if (empty($gm) || ($gm === 'server' || $gm === 'tzserver')) {
4253 $default_timezone = @date_default_timezone_get(); // Example 'Europe/Berlin'
4254 $localtz = new DateTimeZone($default_timezone);
4255 } elseif ($gm === 'user' || $gm === 'tzuser' || $gm === 'tzuserrel') {
4256 // We use dol_tz_string first because it is more reliable.
4257 $default_timezone = (empty($_SESSION["dol_tz_string"]) ? @date_default_timezone_get() : $_SESSION["dol_tz_string"]); // Example 'Europe/Berlin'
4258 try {
4259 $localtz = new DateTimeZone($default_timezone);
4260 } catch (Exception $e) {
4261 dol_syslog("Warning dol_tz_string contains an invalid value " . json_encode($_SESSION["dol_tz_string"] ?? null), LOG_WARNING);
4262 $default_timezone = @date_default_timezone_get();
4263 }
4264 } elseif (strrpos($gm, "tz,") !== false) {
4265 $timezone = (string) str_replace("tz,", "", $gm); // Example 'tz,Europe/Berlin'
4266 try {
4267 $localtz = new DateTimeZone($timezone);
4268 } catch (Exception $e) {
4269 dol_syslog("Warning passed timezone contains an invalid value " . $timezone, LOG_WARNING);
4270 }
4271 }
4272
4273 if (empty($localtz)) {
4274 $localtz = new DateTimeZone('UTC');
4275 }
4276 $dt = new DateTime('now', $localtz);
4277 $dt->setDate((int) $year, (int) $month, (int) $day);
4278 $dt->setTime((int) $hour, (int) $minute, (int) $second);
4279 $date = $dt->getTimestamp(); // should include daylight saving time
4280
4281 return $date;
4282}
4283
4284
4295function dol_now($mode = 'gmt')
4296{
4297 $ret = 0;
4298
4299 if ($mode === 'auto') {
4300 $mode = 'gmt';
4301 }
4302
4303 if ($mode == 'gmt') {
4304 $ret = time(); // Time for now at greenwich.
4305 } elseif ($mode == 'tzserver') { // Time for now with PHP server timezone added
4306 require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
4307 $tzsecond = getServerTimeZoneInt('now'); // Contains tz+dayling saving time
4308 $ret = (int) (dol_now('gmt') + ($tzsecond * 3600));
4309 // } elseif ($mode == 'tzref') {// Time for now with parent company timezone is added
4310 // require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
4311 // $tzsecond=getParentCompanyTimeZoneInt(); // Contains tz+dayling saving time
4312 // $ret=dol_now('gmt')+($tzsecond*3600);
4313 } elseif ($mode == 'tzuser' || $mode == 'tzuserrel') {
4314 // Time for now with user timezone added
4315 // print 'time: '.time();
4316 $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60;
4317 $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60;
4318 $ret = (int) (dol_now('gmt') + ($offsettz + $offsetdst));
4319 }
4320
4321 return $ret;
4322}
4323
4324
4333function dol_print_size($size, $shortvalue = 0, $shortunit = 0)
4334{
4335 global $conf, $langs;
4336 $level = 1024;
4337
4338 if (!empty($conf->dol_optimize_smallscreen)) {
4339 $shortunit = 1;
4340 }
4341
4342 // Set value text
4343 if (empty($shortvalue) || $size < ($level * 10)) {
4344 $ret = $size;
4345 $textunitshort = $langs->trans("b");
4346 $textunitlong = $langs->trans("Bytes");
4347 } else {
4348 $ret = round($size / $level, 0);
4349 $textunitshort = $langs->trans("Kb");
4350 $textunitlong = $langs->trans("KiloBytes");
4351 }
4352 // Use long or short text unit
4353 if (empty($shortunit)) {
4354 $ret .= ' ' . $textunitlong;
4355 } else {
4356 $ret .= ' ' . $textunitshort;
4357 }
4358
4359 return $ret;
4360}
4361
4372function dol_print_url($url, $target = '_blank', $max = 32, $withpicto = 0, $morecss = '')
4373{
4374 global $langs;
4375
4376 if (empty($url)) {
4377 return '';
4378 }
4379
4380 $linkstart = '<a href="';
4381 if (!preg_match('/^http/i', $url)) {
4382 $linkstart .= 'http://';
4383 }
4384 $linkstart .= $url;
4385 $linkstart .= '"';
4386 if ($target) {
4387 $linkstart .= ' target="' . $target . '"';
4388 }
4389 $linkstart .= ' title="' . $langs->trans("URL") . ': ' . $url . '"';
4390 $linkstart .= '>';
4391
4392 $link = '';
4393 if (!preg_match('/^http/i', $url)) {
4394 $link .= 'http://';
4395 }
4396 $link .= dol_trunc($url, $max);
4397
4398 $linkend = '</a>';
4399
4400 if ($morecss == 'float') { // deprecated
4401 return '<div class="nospan' . ($morecss ? ' ' . $morecss : '') . '" style="margin-right: 10px">' . ($withpicto ? img_picto($langs->trans("Url"), 'globe', 'class="paddingrightonly"') : '') . $link . '</div>';
4402 } else {
4403 return $linkstart . '<span class="nospan' . ($morecss ? ' ' . $morecss : '') . '" style="margin-right: 10px">' . ($withpicto ? img_picto('', 'globe', 'class="paddingrightonly"') : '') . $link . '</span>' . $linkend;
4404 }
4405}
4406
4420function dol_print_email($email, $contactid = 0, $socid = 0, $addlink = 0, $max = 0, $showinvalid = 2, $withpicto = 0, $morecss = 'paddingrightonly')
4421{
4422 global $user, $langs, $hookmanager;
4423
4424 //global $conf; $conf->global->AGENDA_ADDACTIONFOREMAIL = 1;
4425 //$showinvalid = 1; $email = 'rrrrr';
4426
4427 $newemail = dol_escape_htmltag($email);
4428
4429 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') && $withpicto) {
4430 $withpicto = 0;
4431 }
4432
4433 if (empty($email)) {
4434 return '&nbsp;';
4435 }
4436
4437 if ($addlink == 1) {
4438 $newemail = '<a class="' . ($morecss ? $morecss : '') . '" style="text-overflow: ellipsis;" href="';
4439 if (!preg_match('/^mailto:/i', $email)) {
4440 $newemail .= 'mailto:';
4441 }
4442 $newemail .= $email;
4443 $newemail .= '" target="_blank">';
4444
4445 $newemail .= ($withpicto ? img_picto($langs->trans("EMail") . ' : ' . $email, (is_numeric($withpicto) ? 'email' : $withpicto), 'class="paddingrightonly"') : '');
4446
4447 if ($max > 0) {
4448 $newemail .= dol_trunc($email, $max);
4449 } else {
4450 $newemail .= $email;
4451 }
4452 $newemail .= '</a>';
4453
4454 if ($showinvalid) {
4455 include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
4456 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
4457 $emailonly = CMailFile::getValidAddress($email, 2);
4458 if (!isValidEmail($emailonly)) {
4459 $langs->load("errors");
4460 $newemail .= img_warning($langs->transnoentitiesnoconv("ErrorBadEMail", $emailonly), '', 'paddingrightonly');
4461 } elseif ($showinvalid == 2 && !isValidMailDomain($emailonly)) {
4462 $langs->load("errors");
4463 $newemail .= img_warning($langs->transnoentitiesnoconv("ErrorBadMXDomain", $emailonly), '', 'paddingrightonly');
4464 }
4465 }
4466
4467 if (($contactid || $socid) && isModEnabled('agenda') && $user->hasRight("agenda", "myactions", "create")) {
4468 $type = 'AC_EMAIL';
4469 $linktoaddaction = '';
4470 if (getDolGlobalString('AGENDA_ADDACTIONFOREMAIL')) {
4471 $linktoaddaction = '<a href="' . DOL_URL_ROOT . '/comm/action/card.php?action=create&backtopage=1&actioncode=' . urlencode($type) . '&contactid=' . ((int) $contactid) . '&socid=' . ((int) $socid) . '">' . img_object($langs->trans("AddAction"), "calendar") . '</a>';
4472 }
4473 if ($linktoaddaction) {
4474 $newemail = '<div>' . $newemail . ' ' . $linktoaddaction . '</div>';
4475 }
4476 }
4477 } elseif ($addlink === 'thirdparty') {
4478 $tmpnewemail = '<a class="' . ($morecss ? $morecss : '') . '" style="text-overflow: ellipsis;" href="' . DOL_URL_ROOT . '/societe/card.php?socid=' . $socid . '&action=presend&mode=init#formmailbeforetitle">';
4479 $tmpnewemail .= ($withpicto ? img_picto($langs->trans("EMail") . ' : ' . $email, (is_numeric($withpicto) ? 'email' : $withpicto), 'class="paddingrightonly"') : '');
4480 if ($withpicto == 1) {
4481 $tmpnewemail .= $newemail;
4482 }
4483 $tmpnewemail .= '</a>';
4484
4485 $newemail = $tmpnewemail;
4486 } else {
4487 $newemail = ($withpicto ? img_picto($langs->trans("EMail") . ' : ' . $email, (is_numeric($withpicto) ? 'email' : $withpicto), 'class="paddingrightonly"') : '') . $newemail;
4488
4489 if ($showinvalid) {
4490 include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
4491 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
4492 $emailonly = CMailFile::getValidAddress($email, 2);
4493 if (!isValidEmail($emailonly)) {
4494 $langs->load("errors");
4495 $newemail .= img_warning($langs->transnoentitiesnoconv("ErrorBadEMail", $email));
4496 } elseif ($showinvalid == 2 && !isValidMailDomain($emailonly)) {
4497 $langs->load("errors");
4498 $newemail .= img_warning($langs->transnoentitiesnoconv("ErrorBadMXDomain", $emailonly));
4499 }
4500 }
4501 }
4502
4503 //$rep = '<div class="nospan" style="margin-right: 10px">';
4504 //$rep = ($withpicto ? img_picto($langs->trans("EMail").' : '.$email, (is_numeric($withpicto) ? 'email' : $withpicto), 'class="paddingrightonly"') : '').$newemail;
4505 //$rep .= '</div>';
4506 $rep = $newemail;
4507 if (getDolGlobalString('MAIN_MAIL_COPY_ON_CLICK')) {
4508 $rep .= showValueWithClipboardCPButton($newemail, 0, 'none');
4509 }
4510
4511 if ($hookmanager) {
4512 $parameters = array('cid' => $contactid, 'socid' => $socid, 'addlink' => $addlink, 'picto' => $withpicto);
4513
4514 $reshook = $hookmanager->executeHooks('printEmail', $parameters, $email);
4515 if ($reshook > 0) {
4516 $rep = '';
4517 }
4518 $rep .= $hookmanager->resPrint;
4519 }
4520
4521 return $rep;
4522}
4523
4524
4540function dolOutputDates($datep, $datef = null, $fullday = 0, $addseconds = 0, $pictotoadd = '', $tzoutput = 'tzuserrel', $reduceformat = 0)
4541{
4542 $tmpa = dol_getdate($datep);
4543 if (empty($datef)) {
4544 $tmpb = $tmpa;
4545 } else {
4546 $tmpb = dol_getdate($datef);
4547 }
4548
4549 $s = '';
4550
4551 if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year']) {
4552 // The same day
4553 $s .= '<div class="center inline-block">';
4554 if ($tmpa['hours'] != $tmpb['hours'] || $tmpa['minutes'] != $tmpb['minutes']) {
4555 // Not the same hour
4556 $s .= dol_print_date($datep, 'day'.($reduceformat ? 'reduceformat' : ''), $tzoutput);
4557 $s .= $pictotoadd;
4558 if (empty($fullday)) {
4559 $s .= '<br><span class="small opacitymedium">';
4560 $s .= dol_print_date($datep, 'hour'.($addseconds ? 'sec' : '').'reduceformat', $tzoutput);
4561 $s .= '-'.dol_print_date($datef, 'hour'.($addseconds ? 'sec' : '').'reduceformat', $tzoutput);
4562 $s .= '</span>';
4563 }
4564 } else {
4565 // The same hour
4566 $s .= dol_print_date($datep, 'day'.($reduceformat ? 'reduceformat' : ''), 'tzuserrel');
4567 $s .= $pictotoadd;
4568 if (empty($fullday)) {
4569 $s .= '<br><span class="small opacitymedium">';
4570 $s .= dol_print_date($datep, 'hour'.($addseconds ? 'sec' : '').'reduceformat', $tzoutput);
4571 $s .= '</span>';
4572 }
4573 }
4574 $s .= '</div>';
4575 } else {
4576 // Not the same day
4577 $s .= '<div class="center inline-block dateborderright">';
4578 $s .= dol_print_date($datep, 'day'.($reduceformat ? 'reduceformat' : ''), $tzoutput);
4579 if (empty($fullday)) {
4580 $s .= '<br><span class="small opacitymedium">';
4581 $s .= dol_print_date($datep, 'hour'.($addseconds ? 'sec' : '').'reduceformat', $tzoutput);
4582 $s .= '</span>';
4583 }
4584 $s .= '</div>';
4585 $s .= '<div class="center inline-block dateborderleft">';
4586 $s .= dol_print_date($datef, 'day'.($reduceformat ? 'reduceformat' : ''), 'tzuserrel');
4587 $s .= $pictotoadd;
4588 if (empty($fullday)) {
4589 $s .= '<br><span class="small opacitymedium">';
4590 $s .= dol_print_date($datef, 'hour'.($addseconds ? 'sec' : '').'reduceformat', $tzoutput);
4591 $s .= '</span>';
4592 }
4593 $s .= '</div>';
4594 }
4595
4596 return $s;
4597}
4598
4599
4605function getArrayOfSocialNetworks()
4606{
4607 global $db;
4608
4609 $socialnetworks = array();
4610 // Enable caching of array
4611 require_once DOL_DOCUMENT_ROOT . '/core/lib/memory.lib.php';
4612 $cachekey = dol_sanitizeKeyCode(str_replace(',', '_', 'socialnetworks_'.getEntity('c_socialnetworks')));
4613 $dataretrieved = dol_getcache($cachekey);
4614
4615 if (!is_null($dataretrieved)) {
4616 $socialnetworks = $dataretrieved;
4617 } else {
4618 $sql = "SELECT rowid, code, label, url, icon, active FROM " . MAIN_DB_PREFIX . "c_socialnetworks";
4619 $sql .= " WHERE entity IN (" . getEntity('c_socialnetworks').")";
4620
4621 $resql = $db->query($sql);
4622 if ($resql) {
4623 while ($obj = $db->fetch_object($resql)) {
4624 $socialnetworks[$obj->code] = array(
4625 'rowid' => $obj->rowid,
4626 'label' => $obj->label,
4627 'url' => $obj->url,
4628 'icon' => $obj->icon,
4629 'active' => $obj->active,
4630 );
4631 }
4632 }
4633 dol_setcache($cachekey, $socialnetworks); // If setting cache fails, this is not a problem, so we do not test result.
4634 }
4635
4636 return (is_array($socialnetworks) ? $socialnetworks : array());
4637}
4638
4649function dol_print_socialnetworks($value, $contactid, $socid, $type, $dictsocialnetworks = array())
4650{
4651 global $hookmanager, $langs, $user;
4652
4653 $htmllink = $value;
4654
4655 if (empty($value)) {
4656 return '&nbsp;';
4657 }
4658
4659 if (!empty($type)) {
4660 $htmllink = '<div class="divsocialnetwork inline-block valignmiddle">';
4661 // Use dictionary definition for picto $dictsocialnetworks[$type]['icon']
4662 $htmllink .= '<span class="fab pictofixedwidth ' . ($dictsocialnetworks[$type]['icon'] ? $dictsocialnetworks[$type]['icon'] : 'fa-link') . '"></span>';
4663 if ($type == 'skype') {
4664 $htmllink .= dol_escape_htmltag($value);
4665 $htmllink .= '&nbsp; <a href="skype:';
4666 $htmllink .= dol_string_nospecial($value, '_', '', array('@'));
4667 $htmllink .= '?call" alt="' . $langs->trans("Call") . '&nbsp;' . $value . '" title="' . dol_escape_htmltag($langs->trans("Call") . ' ' . $value) . '">';
4668 $htmllink .= '<img src="' . DOL_URL_ROOT . '/theme/common/skype_callbutton.png" border="0">';
4669 $htmllink .= '</a><a href="skype:';
4670 $htmllink .= dol_string_nospecial($value, '_', '', array('@'));
4671 $htmllink .= '?chat" alt="' . $langs->trans("Chat") . '&nbsp;' . $value . '" title="' . dol_escape_htmltag($langs->trans("Chat") . ' ' . $value) . '">';
4672 $htmllink .= '<img class="paddingleft" src="' . DOL_URL_ROOT . '/theme/common/skype_chatbutton.png" border="0">';
4673 $htmllink .= '</a>';
4674 if (($contactid || $socid) && isModEnabled('agenda') && $user->hasRight('agenda', 'myactions', 'create')) {
4675 $addlink = 'AC_SKYPE';
4676 $link = '';
4677 if (getDolGlobalString('AGENDA_ADDACTIONFORSKYPE')) {
4678 $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>';
4679 }
4680 $htmllink .= ($link ? ' ' . $link : '');
4681 }
4682 } else {
4683 if (!empty($dictsocialnetworks[$type]['url'])) {
4684 $tmpvirginurl = preg_replace('/\/?{socialid}/', '', $dictsocialnetworks[$type]['url']);
4685 if ($tmpvirginurl) {
4686 $value = preg_replace('/^www\.' . preg_quote($tmpvirginurl, '/') . '\/?/', '', $value);
4687 $value = preg_replace('/^' . preg_quote($tmpvirginurl, '/') . '\/?/', '', $value);
4688
4689 $tmpvirginurl3 = preg_replace('/^https:\/\//i', 'https://www.', $tmpvirginurl);
4690 if ($tmpvirginurl3) {
4691 $value = preg_replace('/^www\.' . preg_quote($tmpvirginurl3, '/') . '\/?/', '', $value);
4692 $value = preg_replace('/^' . preg_quote($tmpvirginurl3, '/') . '\/?/', '', $value);
4693 }
4694
4695 $tmpvirginurl2 = preg_replace('/^https?:\/\//i', '', $tmpvirginurl);
4696 if ($tmpvirginurl2) {
4697 $value = preg_replace('/^www\.' . preg_quote($tmpvirginurl2, '/') . '\/?/', '', $value);
4698 $value = preg_replace('/^' . preg_quote($tmpvirginurl2, '/') . '\/?/', '', $value);
4699 }
4700 }
4701 if (preg_match('/^https?:\/\//i', $value)) {
4702 $link = $value;
4703 } else {
4704 $link = str_replace('{socialid}', $value, $dictsocialnetworks[$type]['url']);
4705 }
4706 $valuetoshow = $value;
4707 $valuetoshow = preg_replace('/https:\/\/www\.(twitter|x|linkedin)\.com\/?/', '', $valuetoshow);
4708 if (preg_match('/^https?:\/\//i', $link)) {
4709 $htmllink .= '<a href="' . dol_sanitizeUrl($link, 0) . '" target="_blank" rel="noopener noreferrer">' . dol_escape_htmltag($valuetoshow) . '</a>';
4710 } else {
4711 $htmllink .= '<a href="' . dol_sanitizeUrl($link, 1) . '" target="_blank" rel="noopener noreferrer">' . dol_escape_htmltag($valuetoshow) . '</a>';
4712 }
4713 } else {
4714 $htmllink .= dol_escape_htmltag($value);
4715 }
4716 }
4717 $htmllink .= '</div>';
4718 } else {
4719 $langs->load("errors");
4720 $htmllink .= img_warning($langs->trans("ErrorBadSocialNetworkValue", $value));
4721 }
4722
4723 if ($hookmanager) {
4724 $parameters = array(
4725 'value' => $value,
4726 'cid' => $contactid,
4727 'socid' => $socid,
4728 'type' => $type,
4729 'dictsocialnetworks' => $dictsocialnetworks,
4730 );
4731
4732 $reshook = $hookmanager->executeHooks('printSocialNetworks', $parameters);
4733 if ($reshook > 0) {
4734 $htmllink = '';
4735 }
4736 $htmllink .= $hookmanager->resPrint;
4737 }
4738
4739 return $htmllink;
4740}
4741
4751function dol_print_profids($profID, $profIDtype, $countrycode = '', $addcpButton = 1)
4752{
4753 global $mysoc;
4754
4755 if (empty($profID) || empty($profIDtype)) {
4756 return '';
4757 }
4758 if (empty($countrycode)) {
4759 $countrycode = (is_object($mysoc) ? $mysoc->country_code : '');
4760 }
4761 $newProfID = $profID;
4762 $id = substr($profIDtype, -1);
4763 $ret = '';
4764 if (strtoupper($countrycode) == 'FR') {
4765 // France
4766 // (see https://www.economie.gouv.fr/entreprises/numeros-identification-entreprise)
4767
4768 if ($id == 1 && dol_strlen($newProfID) == 9) {
4769 // SIREN (ex: 123 123 123)
4770 $newProfID = substr($newProfID, 0, 3) . ' ' . substr($newProfID, 3, 3) . ' ' . substr($newProfID, 6, 3);
4771 }
4772 if ($id == 2 && dol_strlen($newProfID) == 14) {
4773 // SIRET (ex: 123 123 123 12345)
4774 $newProfID = substr($newProfID, 0, 3) . ' ' . substr($newProfID, 3, 3) . ' ' . substr($newProfID, 6, 3) . ' ' . substr($newProfID, 9, 5);
4775 }
4776 if ($id == 3 && dol_strlen($newProfID) == 5) {
4777 // NAF/APE (ex: 69.20Z)
4778 $newProfID = substr($newProfID, 0, 2) . '.' . substr($newProfID, 2, 3);
4779 }
4780 if ($profIDtype === 'VAT' && dol_strlen($newProfID) == 13) {
4781 // TVA intracommunautaire (ex: FR12 123 123 123)
4782 $newProfID = substr($newProfID, 0, 4) . ' ' . substr($newProfID, 4, 3) . ' ' . substr($newProfID, 7, 3) . ' ' . substr($newProfID, 10, 3);
4783 }
4784 }
4785 if (!empty($addcpButton)) {
4786 $ret = showValueWithClipboardCPButton(dol_escape_htmltag($profID), ($addcpButton == 1 ? 1 : 0), $newProfID);
4787 } else {
4788 $ret = $newProfID;
4789 }
4790 return $ret;
4791}
4792
4808function dol_print_phone($phone, $countrycode = '', $contactid = 0, $socid = 0, $addlink = '', $separ = "&nbsp;", $withpicto = '', $titlealt = '', $adddivfloat = 0, $morecss = 'paddingright')
4809{
4810 global $conf, $user, $langs, $mysoc, $hookmanager;
4811
4812 // Clean phone parameter
4813 $phone = is_null($phone) ? '' : preg_replace("/[\s.-]/", "", trim($phone));
4814 if (empty($phone)) {
4815 return '';
4816 }
4817 if (getDolGlobalString('MAIN_PHONE_SEPAR')) {
4818 $separ = getDolGlobalString('MAIN_PHONE_SEPAR');
4819 }
4820 if (empty($countrycode) && is_object($mysoc)) {
4821 $countrycode = $mysoc->country_code;
4822 }
4823
4824 // Short format for small screens
4825 if (!empty($conf->dol_optimize_smallscreen) && $separ != 'hidenum') {
4826 $separ = '';
4827 }
4828
4829 $newphone = $phone;
4830 $newphonewa = $phone;
4831 if (strtoupper($countrycode) == "FR") {
4832 // France
4833 if (dol_strlen($phone) == 10) {
4834 $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);
4835 } elseif (dol_strlen($phone) == 7) {
4836 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 2) . $separ . substr($newphone, 5, 2);
4837 } elseif (dol_strlen($phone) == 9) {
4838 $newphone = substr($newphone, 0, 2) . $separ . substr($newphone, 2, 3) . $separ . substr($newphone, 5, 2) . $separ . substr($newphone, 7, 2);
4839 } elseif (dol_strlen($phone) == 11) {
4840 $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);
4841 } elseif (dol_strlen($phone) == 12) {
4842 $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);
4843 } elseif (dol_strlen($phone) == 13) {
4844 $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);
4845 }
4846 } elseif (strtoupper($countrycode) == "CA") {
4847 if (dol_strlen($phone) == 10) {
4848 $newphone = ($separ != '' ? '(' : '') . substr($newphone, 0, 3) . ($separ != '' ? ')' : '') . $separ . substr($newphone, 3, 3) . ($separ != '' ? '-' : '') . substr($newphone, 6, 4);
4849 }
4850 } elseif (strtoupper($countrycode) == "PT") { //Portugal
4851 if (dol_strlen($phone) == 13) { //ex: +351_ABC_DEF_GHI
4852 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 3) . $separ . substr($newphone, 10, 3);
4853 }
4854 } elseif (strtoupper($countrycode) == "SR") { //Suriname
4855 if (dol_strlen($phone) == 10) { //ex: +597_ABC_DEF
4856 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 3);
4857 } elseif (dol_strlen($phone) == 11) { //ex: +597_ABC_DEFG
4858 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 4);
4859 }
4860 } elseif (strtoupper($countrycode) == "DE") { //Deutschland
4861 if (dol_strlen($phone) == 14) { //ex: +49_ABCD_EFGH_IJK
4862 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 4) . $separ . substr($newphone, 7, 4) . $separ . substr($newphone, 11, 3);
4863 } elseif (dol_strlen($phone) == 13) { //ex: +49_ABC_DEFG_HIJ
4864 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 4) . $separ . substr($newphone, 10, 3);
4865 }
4866 } elseif (strtoupper($countrycode) == "ES") { //Spain
4867 if (dol_strlen($phone) == 12) { //ex: +34_ABC_DEF_GHI
4868 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 3) . $separ . substr($newphone, 9, 3);
4869 }
4870 } elseif (strtoupper($countrycode) == "BF") { // Burkina Faso
4871 if (dol_strlen($phone) == 12) { //ex : +22 A BC_DE_FG_HI
4872 $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);
4873 }
4874 } elseif (strtoupper($countrycode) == "RO") { // Roumanie
4875 if (dol_strlen($phone) == 12) { //ex : +40 AB_CDE_FG_HI
4876 $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);
4877 }
4878 } elseif (strtoupper($countrycode) == "TR") { //Turquie
4879 if (dol_strlen($phone) == 13) { //ex : +90 ABC_DEF_GHIJ
4880 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 3) . $separ . substr($newphone, 9, 4);
4881 }
4882 } elseif (strtoupper($countrycode) == "US") { //Etat-Unis
4883 if (dol_strlen($phone) == 12) { //ex: +1 ABC_DEF_GHIJ
4884 $newphone = substr($newphone, 0, 2) . $separ . substr($newphone, 2, 3) . $separ . substr($newphone, 5, 3) . $separ . substr($newphone, 8, 4);
4885 }
4886 } elseif (strtoupper($countrycode) == "MX") { //Mexique
4887 if (dol_strlen($phone) == 12) { //ex: +52 ABCD_EFG_HI
4888 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 4) . $separ . substr($newphone, 7, 3) . $separ . substr($newphone, 10, 2);
4889 } elseif (dol_strlen($phone) == 11) { //ex: +52 AB_CD_EF_GH
4890 $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);
4891 } elseif (dol_strlen($phone) == 13) { //ex: +52 ABC_DEF_GHIJ
4892 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 3) . $separ . substr($newphone, 9, 4);
4893 }
4894 } elseif (strtoupper($countrycode) == "ML") { //Mali
4895 if (dol_strlen($phone) == 12) { //ex: +223 AB_CD_EF_GH
4896 $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);
4897 }
4898 } elseif (strtoupper($countrycode) == "TH") { //Thailand
4899 if (dol_strlen($phone) == 11) { //ex: +66_ABC_DE_FGH
4900 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 2) . $separ . substr($newphone, 8, 3);
4901 } elseif (dol_strlen($phone) == 12) { //ex: +66_A_BCD_EF_GHI
4902 $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);
4903 }
4904 } elseif (strtoupper($countrycode) == "MU") {
4905 //Maurice
4906 if (dol_strlen($phone) == 11) { //ex: +230_ABC_DE_FG
4907 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 2) . $separ . substr($newphone, 9, 2);
4908 } elseif (dol_strlen($phone) == 12) { //ex: +230_ABCD_EF_GH
4909 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 4) . $separ . substr($newphone, 8, 2) . $separ . substr($newphone, 10, 2);
4910 }
4911 } elseif (strtoupper($countrycode) == "ZA") { //Afrique du sud
4912 if (dol_strlen($phone) == 12) { //ex: +27_AB_CDE_FG_HI
4913 $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);
4914 }
4915 } elseif (strtoupper($countrycode) == "SY") { //Syrie
4916 if (dol_strlen($phone) == 12) { //ex: +963_AB_CD_EF_GH
4917 $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);
4918 } elseif (dol_strlen($phone) == 13) { //ex: +963_AB_CD_EF_GHI
4919 $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);
4920 }
4921 } elseif (strtoupper($countrycode) == "AE") { //Emirats Arabes Unis
4922 if (dol_strlen($phone) == 12) { //ex: +971_ABC_DEF_GH
4923 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 3) . $separ . substr($newphone, 10, 2);
4924 } elseif (dol_strlen($phone) == 13) { //ex: +971_ABC_DEF_GHI
4925 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 3) . $separ . substr($newphone, 10, 3);
4926 } elseif (dol_strlen($phone) == 14) { //ex: +971_ABC_DEF_GHIK
4927 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 3) . $separ . substr($newphone, 10, 4);
4928 }
4929 } elseif (strtoupper($countrycode) == "DZ") { //Algeria
4930 if (dol_strlen($phone) == 13) { //ex: +213_ABC_DEF_GHI
4931 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 3) . $separ . substr($newphone, 10, 3);
4932 }
4933 } elseif (strtoupper($countrycode) == "BE") { //Belgique
4934 if (dol_strlen($phone) == 11) { //ex: +32_ABC_DE_FGH
4935 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 2) . $separ . substr($newphone, 8, 3);
4936 } elseif (dol_strlen($phone) == 12) { //ex: +32_ABC_DEF_GHI
4937 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 3) . $separ . substr($newphone, 9, 3);
4938 }
4939 } elseif (strtoupper($countrycode) == "PF") { //French Polynesia
4940 if (dol_strlen($phone) == 12) { //ex: +689_AB_CD_EF_GH
4941 $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);
4942 }
4943 } elseif (strtoupper($countrycode) == "CO") { //Colombie
4944 if (dol_strlen($phone) == 13) { //ex: +57_ABC_DEF_GH_IJ
4945 $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);
4946 }
4947 } elseif (strtoupper($countrycode) == "JO") { //Jordanie
4948 if (dol_strlen($phone) == 12) { //ex: +962_A_BCD_EF_GH
4949 $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);
4950 }
4951 } elseif (strtoupper($countrycode) == "JM") { //Jamaica
4952 if (dol_strlen($newphone) == 12) { //ex: +1867_ABC_DEFG
4953 $newphone = substr($newphone, 0, 5) . $separ . substr($newphone, 5, 3) . $separ . substr($newphone, 8, 4);
4954 }
4955 } elseif (strtoupper($countrycode) == "MG") { //Madagascar
4956 if (dol_strlen($phone) == 13) { //ex: +261_AB_CD_EFG_HI
4957 $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);
4958 }
4959 } elseif (strtoupper($countrycode) == "GB") { //Royaume uni
4960 if (dol_strlen($phone) == 13) { //ex: +44_ABCD_EFG_HIJ
4961 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 4) . $separ . substr($newphone, 7, 3) . $separ . substr($newphone, 10, 3);
4962 }
4963 } elseif (strtoupper($countrycode) == "CH") { //Suisse
4964 if (dol_strlen($phone) == 12) { //ex: +41_AB_CDE_FG_HI
4965 $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);
4966 } elseif (dol_strlen($phone) == 15) { // +41_AB_CDE_FGH_IJKL
4967 $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);
4968 }
4969 } elseif (strtoupper($countrycode) == "TN") { //Tunisie
4970 if (dol_strlen($phone) == 12) { //ex: +216_AB_CDE_FGH
4971 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 2) . $separ . substr($newphone, 6, 3) . $separ . substr($newphone, 9, 3);
4972 }
4973 } elseif (strtoupper($countrycode) == "GF") { //Guyane francaise
4974 if (dol_strlen($phone) == 13) { //ex: +594_ABC_DE_FG_HI (ABC=594 de nouveau)
4975 $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);
4976 }
4977 } elseif (strtoupper($countrycode) == "GP") { //Guadeloupe
4978 if (dol_strlen($phone) == 13) { //ex: +590_ABC_DE_FG_HI (ABC=590 de nouveau)
4979 $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);
4980 }
4981 } elseif (strtoupper($countrycode) == "MQ") { //Martinique
4982 if (dol_strlen($phone) == 13) { //ex: +596_ABC_DE_FG_HI (ABC=596 de nouveau)
4983 $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);
4984 }
4985 } elseif (strtoupper($countrycode) == "IT") { //Italie
4986 if (dol_strlen($phone) == 12) { //ex: +39_ABC_DEF_GHI
4987 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 3) . $separ . substr($newphone, 9, 3);
4988 } elseif (dol_strlen($phone) == 13) { //ex: +39_ABC_DEF_GH_IJ
4989 $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);
4990 }
4991 } elseif (strtoupper($countrycode) == "AU") {
4992 //Australie
4993 if (dol_strlen($phone) == 12) {
4994 //ex: +61_A_BCDE_FGHI
4995 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 1) . $separ . substr($newphone, 4, 4) . $separ . substr($newphone, 8, 4);
4996 }
4997 } elseif (strtoupper($countrycode) == "LU") {
4998 // Luxembourg
4999 if (dol_strlen($phone) == 10) { // fix 6 digits +352_AA_BB_CC
5000 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 2) . $separ . substr($newphone, 6, 2) . $separ . substr($newphone, 8, 2);
5001 } elseif (dol_strlen($phone) == 11) { // fix 7 digits +352_AA_BB_CC_D
5002 $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);
5003 } elseif (dol_strlen($phone) == 12) { // fix 8 digits +352_AA_BB_CC_DD
5004 $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);
5005 } elseif (dol_strlen($phone) == 13) { // mobile +352_AAA_BB_CC_DD
5006 $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);
5007 }
5008 } elseif (strtoupper($countrycode) == "PE") {
5009 // Peru
5010 if (dol_strlen($phone) == 7) { // fix 7 numbers without code AAA_BBBB
5011 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 4);
5012 } elseif (dol_strlen($phone) == 9) { // mobile add code and fix 9 numbers +51_AAA_BBB_CCC
5013 $newphonewa = '+51' . $newphone;
5014 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 3);
5015 } elseif (dol_strlen($phone) == 11) { // fix 11 numbers +511_AAA_BBBB
5016 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 4);
5017 } elseif (dol_strlen($phone) == 12) { // mobile +51_AAA_BBB_CCC
5018 $newphonewa = $newphone;
5019 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 3) . $separ . substr($newphone, 9, 3);
5020 }
5021 } elseif (strtoupper($countrycode) == "IN") { //India
5022 if (dol_strlen($phone) == 13) {
5023 if ($withpicto == 'phone') { //ex: +91_AB_CDEF_GHIJ
5024 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 2) . $separ . substr($newphone, 5, 4) . $separ . substr($newphone, 9, 4);
5025 } else { //ex: +91_ABCDE_FGHIJ
5026 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 5) . $separ . substr($newphone, 8, 5);
5027 }
5028 }
5029 }
5030
5031 $newphoneastart = $newphoneaend = '';
5032 if (!empty($addlink)) { // Link on phone number (+ link to add action if conf->global->AGENDA_ADDACTIONFORPHONE set)
5033 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
5034 // Keep the leading '+' of international numbers: it is allowed in a tel: URI (RFC 3966) and many
5035 // softphones/CTI handlers do not decode '%2B', so they drop the '%' and dial a wrong leading '2'.
5036 // Spaces were removed above, so a '+' produced here can only come from a real '+'.
5037 $newphoneastart = '<a href="tel:' . str_replace('%2B', '+', urlencode($phone)) . '">';
5038 $newphoneaend .= '</a>';
5039 } elseif (isModEnabled('clicktodial') && $addlink == 'AC_TEL') { // If click to dial, we use click to dial url
5040 if (empty($user->clicktodial_loaded)) {
5041 $user->fetch_clicktodial();
5042 }
5043
5044 // Define urlmask
5045 $urlmask = getDolGlobalString('CLICKTODIAL_URL', 'ErrorClickToDialModuleNotConfigured');
5046 if (!empty($user->clicktodial_url)) {
5047 $urlmask = $user->clicktodial_url;
5048 }
5049
5050 $clicktodial_poste = (!empty($user->clicktodial_poste) ? urlencode($user->clicktodial_poste) : '');
5051 $clicktodial_login = (!empty($user->clicktodial_login) ? urlencode($user->clicktodial_login) : '');
5052 $clicktodial_password = (!empty($user->clicktodial_password) ? urlencode($user->clicktodial_password) : '');
5053 // This line is for backward compatibility @phan-suppress-next-line PhanPluginPrintfVariableFormatString
5054 $url = sprintf($urlmask, urlencode($phone), $clicktodial_poste, $clicktodial_login, $clicktodial_password);
5055 // Those lines are for substitution
5056 $substitarray = array(
5057 '__PHONEFROM__' => $clicktodial_poste,
5058 '__PHONETO__' => urlencode($phone),
5059 '__LOGIN__' => $clicktodial_login,
5060 '__PASS__' => $clicktodial_password
5061 );
5062 $url = make_substitutions($url, $substitarray);
5063 if (!getDolGlobalString('CLICKTODIAL_DO_NOT_USE_AJAX_CALL')) {
5064 // Default and recommended: New method using ajax without submitting a page making a javascript history.go(-1) back
5065 $newphoneastart = '<a href="' . $url . '" class="cssforclicktodial">'; // Call of ajax is handled by the lib_foot.js.php on class 'cssforclicktodial'
5066 $newphoneaend = '</a>';
5067 } else {
5068 // Old method
5069 $newphoneastart = '<a href="' . $url . '"';
5070 if (getDolGlobalString('CLICKTODIAL_FORCENEWTARGET')) {
5071 $newphoneastart .= ' target="_blank" rel="noopener noreferrer"';
5072 }
5073 $newphoneastart .= '>';
5074 $newphoneaend .= '</a>';
5075 }
5076 }
5077
5078 //if (($contactid || $socid) && isModEnabled('agenda') && $user->hasRight('agenda', 'myactions', 'create'))
5079 if (isModEnabled('agenda') && $user->hasRight("agenda", "myactions", "create")) {
5080 $type = 'AC_TEL';
5081 $addlinktoagenda = '';
5082 if ($addlink == 'AC_FAX') {
5083 $type = 'AC_FAX';
5084 }
5085 if (getDolGlobalString('AGENDA_ADDACTIONFORPHONE')) {
5086 $addlinktoagenda = '<a href="' . DOL_URL_ROOT . '/comm/action/card.php?action=create&backtopage=' . urlencode($_SERVER['REQUEST_URI']) . '&actioncode=' . $type . ($contactid ? '&contactid=' . $contactid : '') . ($socid ? '&socid=' . $socid : '') . '">' . img_object($langs->trans("AddAction"), "calendar") . '</a>';
5087 }
5088 if ($addlinktoagenda) {
5089 $newphone = '<span>' . $newphone . ' ' . $addlinktoagenda . '</span>';
5090 }
5091 }
5092 }
5093
5094 if (getDolGlobalString('CONTACT_PHONEMOBILE_SHOW_LINK_TO_WHATSAPP') && $withpicto == 'mobile') {
5095 // Link to Whatsapp
5096 $newphone .= ' <a href="https://wa.me/' . $newphonewa . '" target="_blank"'; // Use api to whatasapp contacts
5097 $newphone .= '><span class="paddingright fab fa-whatsapp" style="color:#25D366;" title="WhatsApp"></span></a>';
5098 }
5099
5100 if (empty($titlealt) && isset($langs)) {
5101 $titlealt = ($withpicto == 'fax' ? $langs->trans("Fax") : $langs->trans("Phone"));
5102 }
5103 $rep = '';
5104
5105 if ($hookmanager) {
5106 $parameters = array('countrycode' => $countrycode, 'cid' => $contactid, 'socid' => $socid, 'titlealt' => $titlealt, 'picto' => $withpicto);
5107 $reshook = $hookmanager->executeHooks('printPhone', $parameters, $phone);
5108 $rep .= $hookmanager->resPrint;
5109 }
5110 if (empty($reshook)) {
5111 $picto = '';
5112 if ($withpicto) {
5113 if ($withpicto == 'fax') {
5114 $picto = 'phoning_fax';
5115 } elseif ($withpicto == 'phone') {
5116 $picto = 'phone';
5117 } elseif ($withpicto == 'mobile') {
5118 $picto = 'phoning_mobile';
5119 } else {
5120 $picto = '';
5121 }
5122 }
5123 if ($adddivfloat == 1) {
5124 $rep .= '<div class="nospan float' . ($morecss ? ' ' . $morecss : '') . '">';
5125 } elseif (empty($adddivfloat)) {
5126 $rep .= '<span' . ($morecss ? ' class="' . $morecss . '"' : '') . '>';
5127 }
5128
5129 $rep .= $newphoneastart;
5130 $rep .= ($withpicto ? img_picto($titlealt, $picto) : '');
5131 if ($separ != 'hidenum') {
5132 $rep .= ($withpicto ? ' ' : '') . $newphone;
5133 }
5134 $rep .= $newphoneaend;
5135
5136 if ($adddivfloat == 1) {
5137 $rep .= '</div>';
5138 } elseif (empty($adddivfloat)) {
5139 $rep .= '</span>';
5140 }
5141 }
5142
5143 return $rep;
5144}
5145
5154function dol_print_ip($ip, $mode = 0, $showname = 0)
5155{
5156 global $conf;
5157
5158 $ret = '';
5159 if (!isset($conf->cache['resolveips'])) {
5160 $conf->cache['resolveips'] = array();
5161 }
5162
5163 if ($mode != 2) {
5164 $countrycode = dolGetCountryCodeFromIp($ip);
5165 if ($countrycode) { // If success, countrycode is us, fr, ...
5166 if (file_exists(DOL_DOCUMENT_ROOT . '/theme/common/flags/' . $countrycode . '.png')) {
5167 $ret .= picto_from_langcode($countrycode);
5168 } else {
5169 $ret .= '(' . $countrycode . ')';
5170 }
5171 $ret .= '&nbsp;';
5172 } else {
5173 // Nothing
5174 }
5175 }
5176
5177 if (in_array($mode, [0, 2])) {
5178 $domain = '';
5179 if ($showname) {
5180 if (!array_key_exists($ip, $conf->cache['resolveips'])) {
5181 $domain = gethostbyaddr($ip);
5182 $conf->cache['resolveips'][$ip] = $domain; // false or domain
5183 } else {
5184 $domain = $conf->cache['resolveips'][$ip];
5185 }
5186 }
5187 if ($domain) {
5188 $ret .= $domain;
5189 } else {
5190 $ret .= $ip;
5191 }
5192 }
5193
5194 return $ret;
5195}
5196
5209function getUserRemoteIP($trusted = 0)
5210{
5211 if ($trusted) { // Return only IP we can rely on (not spoofable by the client)
5212 $ip = (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']); // value may be the IP of a proxy
5213 // 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)
5214 // This can happen if the proxy were added in the list of trusted proxy.
5215 return $ip;
5216 }
5217
5218 // Try to guess the real IP of client (but this may not be reliable)
5219 if (empty($_SERVER['HTTP_X_FORWARDED_FOR']) || preg_match('/[^0-9\.\:,\[\]\s]/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {
5220 if (empty($_SERVER['HTTP_CLIENT_IP']) || preg_match('/[^0-9\.\:,\[\]\s]/', $_SERVER['HTTP_CLIENT_IP'])) {
5221 if (empty($_SERVER["HTTP_CF_CONNECTING_IP"])) {
5222 $ip = (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']); // value may be the IP of the proxy and not the client
5223 } else {
5224 $ip = $_SERVER["HTTP_CF_CONNECTING_IP"]; // value here may have been forged by client
5225 }
5226 } else {
5227 $ip = preg_replace('/,.*$/', '', $_SERVER['HTTP_CLIENT_IP']); // value is clean here but may have been forged by proxy
5228 }
5229 } else {
5230 $ip = preg_replace('/,.*$/', '', $_SERVER['HTTP_X_FORWARDED_FOR']); // value is clean here but may have been forged by proxy
5231 }
5232 return $ip;
5233}
5234
5241function dolGetCountryCodeFromIp($ip)
5242{
5243 $countrycode = '';
5244
5245 if (isModEnabled('geoipmaxmind')) {
5246 if (getDolGlobalString('GEOIP_VERSION') == 'php') {
5247 $datafile = getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE');
5248 } else {
5249 $diroffile = getMultidirOutput(null, 'geoipmaxmind');
5250 $datafile = $diroffile . '/' . getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE_EMBEDDED');
5251 }
5252 //$ip='24.24.24.24';
5253 //$datafile='/usr/share/GeoIP/GeoIP.dat'; Note that this must be downloaded datafile (not same than datafile provided with ubuntu packages)
5254 if ($datafile) {
5255 try {
5256 include_once DOL_DOCUMENT_ROOT . '/core/class/dolgeoip.class.php';
5257 $geoip = new DolGeoIP('country', $datafile);
5258 //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
5259 $countrycode = $geoip->getCountryCodeFromIP($ip);
5260 } catch (Exception $e) {
5261 //print 'Error with GeoIP database: '.$e->getMessage();
5262 }
5263 }
5264 }
5265
5266 return $countrycode;
5267}
5268
5269
5276function dol_user_country()
5277{
5278 global $conf, $langs, $user;
5279
5280 //$ret=$user->xxx;
5281 $ret = '';
5282 if (isModEnabled('geoipmaxmind')) {
5283 $ip = getUserRemoteIP();
5284 $datafile = getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE');
5285 //$ip='24.24.24.24';
5286 //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';
5287 include_once DOL_DOCUMENT_ROOT . '/core/class/dolgeoip.class.php';
5288 $geoip = new DolGeoIP('country', $datafile);
5289 $countrycode = $geoip->getCountryCodeFromIP($ip);
5290 $ret = $countrycode;
5291 }
5292 return $ret;
5293}
5294
5307function dol_print_address($address, $htmlid, $element, $id, $noprint = 0, $charfornl = '')
5308{
5309 global $hookmanager;
5310
5311 $out = '';
5312
5313 if ($address) {
5314 if ($hookmanager) {
5315 $parameters = array('element' => $element, 'id' => $id);
5316 $reshook = $hookmanager->executeHooks('printAddress', $parameters, $address);
5317 $out .= $hookmanager->resPrint;
5318 }
5319 if (empty($reshook)) {
5320 if (empty($charfornl)) {
5321 $out .= nl2br((string) $address);
5322 } else {
5323 $out .= preg_replace('/[\r\n]+/', $charfornl, (string) $address);
5324 }
5325
5326 // TODO Remove this block, we can add this using the hook now
5327 $showgmap = $showomap = 0;
5328 if (($element == 'thirdparty' || $element == 'societe') && isModEnabled('google') && getDolGlobalString('GOOGLE_ENABLE_GMAPS')) {
5329 $showgmap = 1;
5330 }
5331 if ($element == 'contact' && isModEnabled('google') && getDolGlobalString('GOOGLE_ENABLE_GMAPS_CONTACTS')) {
5332 $showgmap = 1;
5333 }
5334 if ($element == 'member' && isModEnabled('google') && getDolGlobalString('GOOGLE_ENABLE_GMAPS_MEMBERS')) {
5335 $showgmap = 1;
5336 }
5337 if ($element == 'user' && isModEnabled('google') && getDolGlobalString('GOOGLE_ENABLE_GMAPS_USERS')) {
5338 $showgmap = 1;
5339 }
5340 if (($element == 'thirdparty' || $element == 'societe') && isModEnabled('openstreetmap') && getDolGlobalString('OPENSTREETMAP_ENABLE_MAPS')) {
5341 $showomap = 1;
5342 }
5343 if ($element == 'contact' && isModEnabled('openstreetmap') && getDolGlobalString('OPENSTREETMAP_ENABLE_MAPS_CONTACTS')) {
5344 $showomap = 1;
5345 }
5346 if ($element == 'member' && isModEnabled('openstreetmap') && getDolGlobalString('OPENSTREETMAP_ENABLE_MAPS_MEMBERS')) {
5347 $showomap = 1;
5348 }
5349 if ($element == 'user' && isModEnabled('openstreetmap') && getDolGlobalString('OPENSTREETMAP_ENABLE_MAPS_USERS')) {
5350 $showomap = 1;
5351 }
5352 if ($showgmap) {
5353 $url = dol_buildpath('/google/gmaps.php?mode=' . $element . '&id=' . $id, 1);
5354 $out .= ' <a href="' . $url . '" target="_gmaps"><img id="' . $htmlid . '" class="valigntextbottom" src="' . DOL_URL_ROOT . '/theme/common/gmap.png"></a>';
5355 }
5356 if ($showomap) {
5357 $url = dol_buildpath('/openstreetmap/maps.php?mode=' . $element . '&id=' . $id, 1);
5358 $out .= ' <a href="' . $url . '" target="_gmaps"><img id="' . $htmlid . '_openstreetmap" class="valigntextbottom" src="' . DOL_URL_ROOT . '/theme/common/gmap.png"></a>';
5359 }
5360 }
5361 }
5362 if ($noprint) {
5363 return $out;
5364 } else {
5365 print $out;
5366 return null;
5367 }
5368}
5369
5370
5380function isValidEmail($address, $acceptsupervisorkey = 0, $acceptuserkey = 0)
5381{
5382 if ($acceptsupervisorkey && $address == '__SUPERVISOREMAIL__') {
5383 return true;
5384 }
5385 if ($acceptuserkey && $address == '__USER_EMAIL__') {
5386 return true;
5387 }
5388 if (filter_var($address, FILTER_VALIDATE_EMAIL)) {
5389 return true;
5390 }
5391
5392 return false;
5393}
5394
5404function isValidMXRecord($domain)
5405{
5406 if (function_exists('idn_to_ascii') && function_exists('checkdnsrr')) {
5407 if (!checkdnsrr(idn_to_ascii($domain), 'MX')) {
5408 return 0;
5409 }
5410 if (function_exists('getmxrr')) {
5411 $mxhosts = array();
5412 $weight = array();
5413 getmxrr(idn_to_ascii($domain), $mxhosts, $weight);
5414 if (count($mxhosts) > 1) {
5415 return 1;
5416 }
5417 if (count($mxhosts) == 1 && !in_array((string) $mxhosts[0], array('', '.'))) {
5418 return 1;
5419 }
5420
5421 return 0;
5422 }
5423 }
5424
5425 // function idn_to_ascii or checkdnsrr or getmxrr does not exists
5426 return -1;
5427}
5428
5436function isValidPhone($phone)
5437{
5438 return true;
5439}
5440
5441
5451function dolGetFirstLetters($s, $nbofchar = 1)
5452{
5453 $ret = '';
5454 $tmparray = explode(' ', $s);
5455 foreach ($tmparray as $tmps) {
5456 $ret .= dol_substr($tmps, 0, $nbofchar);
5457 }
5458
5459 return $ret;
5460}
5461
5462
5470function dol_strlen($string, $stringencoding = 'UTF-8')
5471{
5472 if (is_null($string)) {
5473 return 0;
5474 }
5475
5476 if (function_exists('mb_strlen')) {
5477 return mb_strlen($string, $stringencoding);
5478 } else {
5479 return strlen($string);
5480 }
5481}
5482
5493function dol_substr($string, $start, $length = null, $stringencoding = '', $trunconbytes = 0)
5494{
5495 global $langs;
5496
5497 if (empty($stringencoding)) {
5498 $stringencoding = (empty($langs) ? 'UTF-8' : $langs->charset_output);
5499 }
5500
5501 $ret = '';
5502 if (empty($trunconbytes)) {
5503 if (function_exists('mb_substr')) {
5504 $ret = mb_substr($string, $start, $length, $stringencoding);
5505 } else {
5506 $ret = substr($string, $start, $length);
5507 }
5508 } else {
5509 if (function_exists('mb_strcut')) {
5510 $ret = mb_strcut($string, $start, $length, $stringencoding);
5511 } else {
5512 $ret = substr($string, $start, $length);
5513 }
5514 }
5515 return $ret;
5516}
5517
5518
5532function dol_trunc($string, $size = 40, $trunc = 'right', $stringencoding = 'UTF-8', $nodot = 0, $display = 0)
5533{
5534 global $conf;
5535
5536 if (empty($size) || getDolGlobalString('MAIN_DISABLE_TRUNC')) {
5537 return $string;
5538 }
5539
5540 if (empty($stringencoding)) {
5541 $stringencoding = 'UTF-8';
5542 }
5543 // reduce for small screen
5544 if (!empty($conf->dol_optimize_smallscreen) && $conf->dol_optimize_smallscreen == 1 && $display == 1) {
5545 $size = round($size / 3);
5546 }
5547
5548 // We go always here
5549 if ($trunc == 'right') {
5550 $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
5551 if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
5552 // If nodot is 0 and size is 1 chars more, we don't trunc and don't add '...'
5553 return dol_substr($newstring, 0, $size, $stringencoding) . ($nodot ? '' : '…');
5554 } else {
5555 //return 'u'.$size.'-'.$newstring.'-'.dol_strlen($newstring,$stringencoding).'-'.$string;
5556 return $string;
5557 }
5558 } elseif ($trunc == 'middle') {
5559 $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
5560 if (dol_strlen($newstring, $stringencoding) > 2 && dol_strlen($newstring, $stringencoding) > ($size + 1)) {
5561 $size1 = (int) round($size / 2);
5562 $size2 = (int) round($size / 2);
5563 return dol_substr($newstring, 0, $size1, $stringencoding) . '…' . dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size2, $size2, $stringencoding);
5564 } else {
5565 return $string;
5566 }
5567 } elseif ($trunc == 'left') {
5568 $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
5569 if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
5570 // If nodot is 0 and size is 1 chars more, we don't trunc and don't add '...'
5571 return '…' . dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size, $size, $stringencoding);
5572 } else {
5573 return $string;
5574 }
5575 } elseif ($trunc == 'wrap') {
5576 $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
5577 if (dol_strlen($newstring, $stringencoding) > ($size + 1)) {
5578 return dol_substr($newstring, 0, $size, $stringencoding) . "\n" . dol_trunc(dol_substr($newstring, $size, dol_strlen($newstring, $stringencoding) - $size, $stringencoding), $size, $trunc);
5579 } else {
5580 return $string;
5581 }
5582 } else {
5583 return 'BadParam3CallingDolTrunc';
5584 }
5585}
5586
5594function getPictoForType($key, $morecss = '')
5595{
5596 // Set array with type -> picto
5597 $type2picto = array(
5598 'varchar' => 'font',
5599 'text' => 'font',
5600 'html' => 'code',
5601 'int' => 'sort-numeric-down',
5602 'double' => 'sort-numeric-down',
5603 'price' => 'currency',
5604 'pricecy' => 'multicurrency',
5605 'password' => 'key',
5606 'boolean' => 'check-square',
5607 'date' => 'calendar',
5608 'datetime' => 'calendar',
5609 'duration' => 'hourglass',
5610 'phone' => 'phone',
5611 'mail' => 'email',
5612 'url' => 'url',
5613 'ip' => 'country',
5614 'select' => 'list',
5615 'sellist' => 'list',
5616 'stars' => 'fontawesome_star_fas',
5617 'radio' => 'check-circle',
5618 'checkbox' => 'list',
5619 'chkbxlst' => 'list',
5620 'link' => 'link',
5621 'icon' => "question",
5622 'point' => "country",
5623 'multipts' => 'country',
5624 'linestrg' => "country",
5625 'polygon' => "country",
5626 'separate' => 'minus'
5627 );
5628
5629 if (!empty($type2picto[$key])) {
5630 return img_picto('', $type2picto[$key], 'class="pictofixedwidth' . ($morecss ? ' ' . $morecss : '') . '"');
5631 }
5632
5633 return img_picto('', 'generic', 'class="pictofixedwidth' . ($morecss ? ' ' . $morecss : '') . '"');
5634}
5635
5636
5660function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $srconly = 0, $notitle = 0, $alt = '', $morecss = '', $marginleftonlyshort = 2, $allowothertags = array())
5661{
5662 global $conf;
5663
5664 // We forge fullpathpicto for image to $path/img/$picto. By default, we take DOL_URL_ROOT/theme/$conf->theme/img/$picto
5665 $url = DOL_URL_ROOT;
5666 $theme = isset($conf->theme) ? $conf->theme : null;
5667 $path = 'theme/' . $theme;
5668 if (empty($picto)) {
5669 $picto = 'generic';
5670 }
5671
5672 if ($titlealt) {
5673 $titlealt = str_replace(array('\n', "\n"), ' - ', $titlealt);
5674 }
5675
5676 // Define fullpathpicto to use into src
5677 if ($pictoisfullpath) {
5678 // Clean parameters
5679 if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
5680 $picto .= '.png';
5681 }
5682 $fullpathpicto = $picto;
5683 $reg = array();
5684 if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
5685 $morecss .= ($morecss ? ' ' : '') . $reg[1];
5686 $moreatt = str_replace('class="' . $reg[1] . '"', '', $moreatt);
5687 }
5688 } else {
5689 // $picto can not be null since replaced with 'generic' in that case
5690 // $pictowithouttext = preg_replace('/(\.png|\.gif|\.svg)$/', '', (is_null($picto) ? '' : $picto));
5691 $pictowithouttext = preg_replace('/(\.png|\.gif|\.svg)$/', '', $picto);
5692 $pictowithouttext = str_replace('object_', '', $pictowithouttext);
5693 $pictowithouttext = str_replace('_nocolor', '', $pictowithouttext);
5694
5695 // Fix some values of $pictowithouttext
5696 $pictoconvertkey = array(
5697 'facture' => 'bill',
5698 'shipping' => 'shipment',
5699 'fichinter' => 'intervention',
5700 'agenda' => 'calendar',
5701 'invoice_supplier' => 'supplier_invoice',
5702 'order_supplier' => 'supplier_order');
5703 if (in_array($pictowithouttext, array_keys($pictoconvertkey))) {
5704 $pictowithouttext = $pictoconvertkey[$pictowithouttext];
5705 }
5706
5707 if (strpos($pictowithouttext, 'fontawesome_') === 0 || strpos($pictowithouttext, 'fa-') === 0) {
5708 // This is a font awesome image 'fontawesome_xxx' or 'fa-xxx'
5709 $pictowithouttext = str_replace('fontawesome_', '', $pictowithouttext);
5710 $pictowithouttext = str_replace('fa-', '', $pictowithouttext);
5711
5712 // Compatibility with old fontawesome versions
5713 if ($pictowithouttext == 'file-o') {
5714 $pictowithouttext = 'file';
5715 }
5716
5717 $pictowithouttextarray = explode('_', $pictowithouttext);
5718 $marginleftonlyshort = 0;
5719
5720 if (!empty($pictowithouttextarray[1])) {
5721 // Syntax is 'fontawesome_fakey_faprefix_facolor_fasize' or 'fa-fakey_faprefix_facolor_fasize'
5722 $fakey = 'fa-' . $pictowithouttextarray[0];
5723 $faprefix = empty($pictowithouttextarray[1]) ? 'fas' : $pictowithouttextarray[1];
5724 $facolor = empty($pictowithouttextarray[2]) ? '' : $pictowithouttextarray[2];
5725 $fasize = empty($pictowithouttextarray[3]) ? '' : $pictowithouttextarray[3];
5726 } else {
5727 $fakey = 'fa-' . $pictowithouttext;
5728 $faprefix = 'fas';
5729 $facolor = '';
5730 $fasize = '';
5731 }
5732
5733 // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
5734 // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
5735 $morestyle = '';
5736 $reg = array();
5737 if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
5738 $morecss .= ($morecss ? ' ' : '') . $reg[1];
5739 $moreatt = str_replace('class="' . $reg[1] . '"', '', $moreatt);
5740 }
5741 if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
5742 $morestyle = $reg[1];
5743 $moreatt = str_replace('style="' . $reg[1] . '"', '', $moreatt);
5744 }
5745 $moreatt = trim($moreatt);
5746
5747 $enabledisablehtml = '<span class="' . $faprefix . ' ' . $fakey . ($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
5748 $enabledisablehtml .= ($morecss ? ' ' . $morecss : '') . '" style="' . ($fasize ? ('font-size: ' . $fasize . ';') : '') . ($facolor ? (' color: ' . $facolor . ';') : '') . ($morestyle ? ' ' . $morestyle : '') . '"' . (($notitle || empty($titlealt)) ? '' : ' title="' . dol_escape_htmltag($titlealt) . '"') . ($moreatt ? ' ' . $moreatt : '') . '>';
5749 $enabledisablehtml .= '</span>';
5750
5751 return $enabledisablehtml;
5752 }
5753
5754 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
5755 $fakey = $pictowithouttext;
5756 $facolor = '';
5757 $fasize = '';
5758 $fa = getDolGlobalString('MAIN_FONTAWESOME_ICON_STYLE', 'fas');
5759 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'))) {
5760 $fa = 'far';
5761 }
5762 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'))) {
5763 $fa = 'fab';
5764 }
5765
5766 $arrayconvpictotofa = getImgPictoConv('fa');
5767
5768 if ($pictowithouttext == 'off') {
5769 $fakey = 'fa-square';
5770 $fasize = '1.3em';
5771 } elseif ($pictowithouttext == 'on') {
5772 $fakey = 'fa-check-square';
5773 $fasize = '1.3em';
5774 } elseif ($pictowithouttext == 'listlight') {
5775 $fakey = 'fa-download';
5776 $marginleftonlyshort = 1;
5777 } elseif ($pictowithouttext == 'printer') {
5778 $fakey = 'fa-print';
5779 $fasize = '1.2em';
5780 } elseif ($pictowithouttext == 'note') {
5781 $fakey = 'fa-sticky-note';
5782 $marginleftonlyshort = 1;
5783 } elseif (in_array($pictowithouttext, array('1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'))) {
5784 $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');
5785 $fakey = 'fa-' . $convertarray[$pictowithouttext];
5786 if (preg_match('/selected/', $pictowithouttext)) {
5787 $facolor = '#888';
5788 }
5789 $marginleftonlyshort = 1;
5790 } elseif (!empty($arrayconvpictotofa[$pictowithouttext])) {
5791 $fakey = 'fa-' . $arrayconvpictotofa[$pictowithouttext];
5792 } else {
5793 $fakey = 'fa-' . $pictowithouttext;
5794 }
5795
5796 if (in_array($pictowithouttext, array('dollyrevert', 'member', 'members', 'contract', 'group', 'resource', 'shipment', 'reception'))) {
5797 $morecss .= ' em092';
5798 }
5799 if (in_array($pictowithouttext, array('conferenceorbooth', 'eventorganization', 'holiday', 'info', 'info_black', 'project', 'workstation'))) {
5800 $morecss .= ' em088';
5801 }
5802 if (in_array($pictowithouttext, array('asset', 'intervention', 'payment', 'loan', 'partnership', 'stock', 'technic'))) {
5803 $morecss .= ' em080';
5804 }
5805
5806 // Define $marginleftonlyshort
5807 $arrayconvpictotomarginleftonly = array(
5808 'bank',
5809 'check',
5810 'delete',
5811 'generic',
5812 'grip',
5813 'grip_title',
5814 'jabber',
5815 'grip_title',
5816 'grip',
5817 'listlight',
5818 'note',
5819 'on',
5820 'off',
5821 'playdisabled',
5822 'printer',
5823 'resize',
5824 'sign-out',
5825 'stats',
5826 'switch_on',
5827 'switch_on_grey',
5828 'switch_on_red',
5829 'switch_off',
5830 'switch_off_grey',
5831 'switch_off_red',
5832 'uparrow',
5833 '1uparrow',
5834 '1downarrow',
5835 '1leftarrow',
5836 '1rightarrow',
5837 '1uparrow_selected',
5838 '1downarrow_selected',
5839 '1leftarrow_selected',
5840 '1rightarrow_selected'
5841 );
5842 if (!array_key_exists($pictowithouttext, $arrayconvpictotomarginleftonly)) {
5843 $marginleftonlyshort = 0;
5844 }
5845
5846 // Add CSS
5847 $arrayconvpictotomorcess = array(
5848 'action' => 'infobox-action',
5849 'account' => 'infobox-bank_account',
5850 'accounting_account' => 'infobox-bank_account',
5851 'accountline' => 'infobox-bank_account',
5852 'accountancy' => 'infobox-bank_account',
5853 'admin' => 'opacitymedium',
5854 'asset' => 'infobox-bank_account',
5855 'bank_account' => 'infobox-bank_account',
5856 'bill' => 'infobox-commande',
5857 'billa' => 'infobox-commande',
5858 'billr' => 'infobox-commande',
5859 'billd' => 'infobox-commande',
5860 'bookcal' => 'infobox-portal',
5861 'margin' => 'infobox-bank_account',
5862 'conferenceorbooth' => 'infobox-project',
5863 'cash-register' => 'infobox-portal',
5864 'contract' => 'infobox-contrat',
5865 'check' => 'font-status4',
5866 'conversation' => 'infobox-contrat',
5867 'donation' => 'infobox-commande',
5868 'dolly' => 'infobox-commande',
5869 'dollyrevert' => 'flip infobox-order_supplier',
5870 'ecm' => 'infobox-action',
5871 'eventorganization' => 'infobox-project',
5872 'hrm' => 'infobox-adherent',
5873 'group' => 'infobox-adherent',
5874 'intervention' => 'infobox-contrat',
5875 'incoterm' => 'infobox-supplier_proposal',
5876 'intracommreport' => 'infobox-bank_account',
5877 'currency' => 'infobox-bank_account',
5878 'multicurrency' => 'infobox-bank_account',
5879 'members' => 'infobox-adherent',
5880 'member' => 'infobox-adherent',
5881 'money-bill-alt' => 'infobox-bank_account',
5882 'order' => 'infobox-commande',
5883 'user' => 'infobox-adherent',
5884 'users' => 'infobox-adherent',
5885 'error' => 'pictoerror',
5886 'warning' => 'pictowarning',
5887 'switch_on' => 'font-status4',
5888 'switch_on_warning' => 'font-status4 warning',
5889 'switch_on_red' => 'font-status8',
5890 'switch_off_warning' => 'font-status4 warning',
5891 'switch_off_red' => 'font-status8',
5892 'holiday' => 'infobox-holiday',
5893 'info' => 'opacityhigh',
5894 'info_black' => 'purple',
5895 'invoice' => 'infobox-commande',
5896 'knowledgemanagement' => 'infobox-contrat rotate90',
5897 'loan' => 'infobox-commande',
5898 'payment' => 'infobox-bank_account',
5899 'payment_vat' => 'infobox-bank_account',
5900 'poll' => 'infobox-portal',
5901 'pos' => 'infobox-bank_account',
5902 'project' => 'infobox-project',
5903 'projecttask' => 'infobox-project',
5904 'propal' => 'infobox-propal',
5905 'proposal' => 'infobox-propal',
5906 'private' => 'infobox-project',
5907 'reception' => 'flip infobox-order_supplier',
5908 'recruitmentjobposition' => 'infobox-adherent',
5909 'recruitmentcandidature' => 'infobox-adherent',
5910 'resource' => 'infobox-action',
5911 'salary' => 'infobox-commande',
5912 'shapes' => 'infobox-adherent',
5913 'shipment' => 'infobox-commande',
5914 'store' => 'infobox-portal',
5915 'stripe' => 'infobox-bank_account',
5916 'supplier_invoice' => 'infobox-order_supplier',
5917 'supplier_invoicea' => 'infobox-order_supplier',
5918 'supplier_invoiced' => 'infobox-order_supplier',
5919 'supplier_invoicer' => 'infobox-order_supplier',
5920 'supplier' => 'infobox-order_supplier',
5921 'supplier_order' => 'infobox-order_supplier',
5922 'supplier_proposal' => 'infobox-supplier_proposal',
5923 'ticket' => 'infobox-contrat',
5924 'title_accountancy' => 'infobox-bank_account',
5925 'title_hrm' => 'infobox-holiday',
5926 'expensereport' => 'infobox-expensereport',
5927 'trip' => 'infobox-expensereport',
5928 'title_agenda' => 'infobox-action',
5929 'vat' => 'infobox-bank_account',
5930 'webportal' => 'infobox-portal',
5931 'website' => 'infobox-portal',
5932 //'title_setup'=>'infobox-action', 'tools'=>'infobox-action',
5933 'list-alt' => 'imgforviewmode',
5934 'calendar' => 'imgforviewmode',
5935 'calendarweek' => 'imgforviewmode',
5936 'calendarmonth' => 'imgforviewmode',
5937 'calendarday' => 'imgforviewmode',
5938 'calendarperuser' => 'imgforviewmode',
5939 'calendarpertype' => 'imgforviewmode'
5940 );
5941 if (!empty($arrayconvpictotomorcess[$pictowithouttext]) && strpos($picto, '_nocolor') === false) {
5942 $morecss .= ($morecss ? ' ' : '') . $arrayconvpictotomorcess[$pictowithouttext];
5943 }
5944
5945 // Define $color
5946 $arrayconvpictotocolor = array(
5947 'address' => '#6c6aa8',
5948 'building' => '#6c6aa8',
5949 'bom' => '#a69944',
5950 'clone' => '#999',
5951 'cog' => '#999',
5952 'companies' => '#6c6aa8',
5953 'company' => '#6c6aa8',
5954 'contact' => '#6c6aa8',
5955 'cron' => '#555',
5956 'dynamicprice' => '#a69944',
5957 'edit' => '#444',
5958 'note' => '#999',
5959 'error' => '',
5960 'help' => '#bbb',
5961 'listlight' => '#999',
5962 'language' => '#555',
5963 //'dolly'=>'#a69944', 'dollyrevert'=>'#a69944',
5964 'lock' => '#ddd',
5965 'lot' => '#a69944',
5966 'map-marker-alt' => '#aaa',
5967 'mrp' => '#a69944',
5968 'product' => '#a69944',
5969 'service' => '#a69944',
5970 'inventory' => '#a69944',
5971 'stock' => '#a69944',
5972 'movement' => '#a69944',
5973 'other' => '#ddd',
5974 'world' => '#986c6a',
5975 'partnership' => '#6c6aa8',
5976 'playdisabled' => '#ccc',
5977 'printer' => '#444',
5978 'projectpub' => '#986c6a',
5979 'resize' => '#444',
5980 'rss' => '#cba',
5981 //'shipment'=>'#a69944',
5982 'search-plus' => '#808080',
5983 'security' => '#999',
5984 'square' => '#888',
5985 'stop-circle' => '#888',
5986 'stats' => '#444',
5987 'superadmin' => '#600',
5988 'switch_off' => '#999',
5989 'technic' => '#999',
5990 'tick' => '#282',
5991 'timespent' => '#555',
5992 'uncheck' => '#800',
5993 'uparrow' => '#555',
5994 'user-cog' => '#999',
5995 'country' => '#aaa',
5996 'globe-americas' => '#aaa',
5997 'region' => '#aaa',
5998 'state' => '#aaa',
5999 //'website' => '#304',
6000 'workstation' => '#a69944'
6001 );
6002 if (isset($arrayconvpictotocolor[$pictowithouttext]) && strpos($picto, '_nocolor') === false) {
6003 $facolor = $arrayconvpictotocolor[$pictowithouttext];
6004 }
6005
6006 // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
6007 // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
6008 $morestyle = '';
6009 $reg = array();
6010 if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
6011 $morecss .= ($morecss ? ' ' : '') . $reg[1];
6012 $moreatt = str_replace('class="' . $reg[1] . '"', '', $moreatt);
6013 }
6014 if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
6015 $morestyle = $reg[1];
6016 $moreatt = str_replace('style="' . $reg[1] . '"', '', $moreatt);
6017 }
6018 $moreatt = trim($moreatt);
6019
6020 $enabledisablehtml = '<span class="' . $fa . ' ' . $fakey . ($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
6021 $enabledisablehtml .= ($morecss ? ' ' . $morecss : '') . '" style="' . ($fasize ? ('font-size: ' . $fasize . ';') : '') . ($facolor ? (' color: ' . $facolor . ';') : '') . ($morestyle ? ' ' . $morestyle : '') . '"' . (($notitle || empty($titlealt)) ? '' : ' title="' . dol_escape_htmltag($titlealt) . '"') . ($moreatt ? ' ' . $moreatt : '') . '>';
6022 $enabledisablehtml .= '</span>';
6023
6024 return $enabledisablehtml;
6025 }
6026
6027 if (getDolGlobalString('MAIN_OVERWRITE_THEME_PATH')) {
6028 $path = getDolGlobalString('MAIN_OVERWRITE_THEME_PATH') . '/theme/' . $theme; // If the theme does not have the same name as the module
6029 } elseif (getDolGlobalString('MAIN_OVERWRITE_THEME_RES')) {
6030 $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
6031 } elseif (!empty($conf->modules_parts['theme']) && array_key_exists($theme, $conf->modules_parts['theme'])) {
6032 $path = $theme . '/theme/' . $theme; // If the theme have the same name as the module
6033 }
6034
6035 // If we ask an image into $url/$mymodule/img (instead of default path)
6036 $regs = array();
6037 if (preg_match('/^([^@]+)@([^@]+)$/i', $picto, $regs)) {
6038 $picto = $regs[1];
6039 $path = $regs[2]; // $path is $mymodule
6040 }
6041
6042 // Clean parameters
6043 if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
6044 $picto .= '.png';
6045 }
6046 // If alt path are defined, define url where img file is, according to physical path
6047 // ex: array(["main"]=>"/home/maindir/htdocs", ["alt0"]=>"/home/moddir0/htdocs", ...)
6048 foreach ($conf->file->dol_document_root as $type => $dirroot) {
6049 if ($type == 'main') {
6050 continue;
6051 }
6052 // This consumes a lot of time, that's why enabling alternative dir like "custom" dir should be avoid
6053 if (file_exists($dirroot . '/' . $path . '/img/' . $picto) && !empty($conf->file->dol_url_root)) {
6054 $url = DOL_URL_ROOT . $conf->file->dol_url_root[$type];
6055 break;
6056 }
6057 }
6058
6059 // $url is '' or '/custom', $path is current theme or
6060 $fullpathpicto = $url . '/' . $path . '/img/' . $picto;
6061 }
6062
6063 if ($srconly) {
6064 return $fullpathpicto;
6065 }
6066
6067 // tag title is used for tooltip on <a>, tag alt can be used with very simple text on image for blind people
6068 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
6069}
6070
6078function getImgPictoConv($mode = 'fa')
6079{
6080 global $conf;
6081
6082 if (empty($mode) || $mode == 'fa') {
6083 // Array when the fa picto key is different than the Dolibarr picto key.
6084 $arrayconvpictotofa = array(
6085 'account' => 'university',
6086 'accounting_account' => 'clipboard-list',
6087 'accountline' => 'receipt',
6088 'accountancy' => 'search-dollar',
6089 'action' => 'calendar-alt',
6090 'add' => 'plus-circle',
6091 'address' => 'address-book',
6092 'ai' => 'magic',
6093 'admin' => 'star',
6094 'asset' => 'money-check-alt',
6095 'autofill' => 'fill',
6096 'back' => 'arrow-left',
6097 'bank_account' => 'university',
6098 'bill' => 'file-invoice-dollar',
6099 'billa' => 'file-excel',
6100 'billr' => 'file-invoice-dollar',
6101 'billd' => 'file-medical',
6102 'blockedlog' => 'file-archive',
6103 'bookcal' => 'calendar-check',
6104 'supplier_invoice' => 'file-invoice-dollar',
6105 'supplier_invoicea' => 'file-excel',
6106 'supplier_invoicer' => 'file-invoice-dollar',
6107 'supplier_invoiced' => 'file-medical',
6108 'bom' => 'shapes',
6109 'card' => 'address-card',
6110 'chart' => 'chart-line',
6111 'company' => 'building',
6112 'contact' => 'address-book',
6113 'contract' => 'suitcase',
6114 'collab' => 'people-arrows',
6115 'conversation' => 'comments',
6116 'country' => 'globe-americas',
6117 'cron' => 'business-time',
6118 'cross' => 'times',
6119 'chevron-double-left' => 'angle-double-left',
6120 'chevron-double-right' => 'angle-double-right',
6121 'chevron-double-down' => 'angle-double-down',
6122 'chevron-double-top' => 'angle-double-up',
6123 'donation' => 'gift',
6124 'dynamicprice' => 'hand-holding-usd',
6125 'setup' => 'cog',
6126 'companies' => 'building',
6127 'products' => 'cube',
6128 'commercial' => 'suitcase',
6129 'invoicing' => 'coins',
6130 'accounting' => 'search-dollar',
6131 'category' => 'tag',
6132 'dollyrevert' => 'dolly',
6133 'file-o' => 'file',
6134 'generate' => 'plus-square',
6135 'hrm' => 'user-tie',
6136 'incoterm' => 'truck-loading',
6137 'margin' => 'calculator',
6138 'members' => 'user-friends',
6139 'ticket' => 'ticket-alt',
6140 'globe' => 'external-link-alt',
6141 'lot' => 'barcode',
6142 'email' => 'at',
6143 'establishment' => 'building',
6144 'edit' => 'pencil-alt',
6145 'entity' => 'globe',
6146 'graph' => 'chart-line',
6147 'grip_title' => 'arrows-alt',
6148 'grip' => 'arrows-alt',
6149 'help' => 'question-circle',
6150 'generic' => 'file',
6151 'holiday' => 'umbrella-beach',
6152 'info' => 'info-circle',
6153 'info_black' => 'info-circle',
6154 'inventory' => 'boxes',
6155 'intracommreport' => 'globe-europe',
6156 'jobprofile' => 'cogs',
6157 'knowledgemanagement' => 'ticket-alt',
6158 'label' => 'layer-group',
6159 'layout' => 'columns',
6160 'line' => 'bars',
6161 'loan' => 'money-bill-alt',
6162 'member' => 'user-alt',
6163 'meeting' => 'chalkboard-teacher',
6164 'mrp' => 'cubes',
6165 'next' => 'arrow-alt-circle-right',
6166 'trip' => 'wallet',
6167 'expensereport' => 'wallet',
6168 'group' => 'users',
6169 'movement' => 'people-carry',
6170 'sign-out' => 'sign-out-alt',
6171 'superadmin' => 'star',
6172 'switch_off' => 'toggle-off',
6173 'switch_off_grey' => 'toggle-off',
6174 'switch_off_warning' => 'toggle-off',
6175 'switch_off_red' => 'toggle-off',
6176 'switch_on' => 'toggle-on',
6177 'switch_on_grey' => 'toggle-on',
6178 'switch_on_warning' => 'toggle-on',
6179 'switch_on_red' => 'toggle-on',
6180 'check' => 'check',
6181 'bookmark' => 'star',
6182 'bank' => 'university',
6183 'close_title' => 'times',
6184 'delete' => 'trash',
6185 'filter' => 'filter',
6186 'list-alt' => 'list-alt',
6187 'calendarlist' => 'bars',
6188 'calendar' => 'calendar-alt',
6189 'calendarmonth' => 'calendar-alt',
6190 'calendarweek' => 'calendar-week',
6191 'calendarday' => 'calendar-day',
6192 'calendarperuser' => 'table',
6193 'calendarpertype' => 'table',
6194 'intervention' => 'ambulance',
6195 'invoice' => 'file-invoice-dollar',
6196 'order' => 'file-invoice',
6197 'error' => 'exclamation-triangle',
6198 'warning' => 'exclamation-triangle',
6199 'other' => 'square',
6200 'playdisabled' => 'play',
6201 'pdf' => 'file-pdf',
6202 'poll' => 'check-double',
6203 'pos' => 'cash-register',
6204 'preview' => 'binoculars',
6205 'project' => 'project-diagram',
6206 'projectpub' => 'project-diagram',
6207 'projecttask' => 'tasks',
6208 'propal' => 'file-signature',
6209 'proposal' => 'file-signature',
6210 'partnership' => 'handshake',
6211 'payment' => 'money-check-alt',
6212 'payment_vat' => 'money-check-alt',
6213 'pictoconfirm' => 'check-square',
6214 'phoning' => 'phone',
6215 'phoning_mobile' => 'mobile-alt',
6216 'phoning_fax' => 'fax',
6217 'previous' => 'arrow-alt-circle-left',
6218 'printer' => 'print',
6219 'product' => 'cube',
6220 'puce' => 'angle-right',
6221 'recent' => 'check-square',
6222 'reception' => 'dolly',
6223 'recruitmentjobposition' => 'id-card-alt',
6224 'recruitmentcandidature' => 'id-badge',
6225 'resize' => 'crop',
6226 'supplier_order' => 'dol-order_supplier',
6227 'supplier_proposal' => 'file-signature',
6228 'refresh' => 'redo',
6229 'region' => 'map-marked',
6230 'replacement' => 'exchange-alt',
6231 'resource' => 'laptop-house',
6232 'recurring' => 'history',
6233 'service' => 'concierge-bell',
6234 'skill' => 'shapes',
6235 'state' => 'map-marked-alt',
6236 'security' => 'key',
6237 'salary' => 'wallet',
6238 'shipment' => 'dolly',
6239 'stock' => 'box-open',
6240 'stats' => 'chart-bar',
6241 'split' => 'code-branch',
6242 'status' => 'stop-circle',
6243 'stripe' => 'stripe-s',
6244 'supplier' => 'building',
6245 'technic' => 'cogs',
6246 'tick' => 'check',
6247 'timespent' => 'clock',
6248 'title_setup' => 'tools',
6249 'title_accountancy' => 'money-check-alt',
6250 'title_bank' => 'university',
6251 'title_hrm' => 'umbrella-beach',
6252 'title_agenda' => 'calendar-alt',
6253 'uncheck' => 'times',
6254 'uparrow' => 'share',
6255 'url' => 'external-link-alt',
6256 'vat' => 'money-check-alt',
6257 'vcard' => 'arrow-alt-circle-down',
6258 'jabber' => 'comment',
6259 'website' => 'globe-americas',
6260 'workstation' => 'pallet',
6261 'webhook' => 'bullseye',
6262 'world' => 'globe',
6263 'private' => 'user-lock',
6264 'conferenceorbooth' => 'chalkboard-teacher',
6265 'eventorganization' => 'project-diagram',
6266 'webportal' => 'door-open'
6267 );
6268
6269 if ($conf->currency == 'EUR') {
6270 $arrayconvpictotofa['currency'] = 'euro-sign';
6271 $arrayconvpictotofa['multicurrency'] = 'dollar-sign';
6272 } else {
6273 $arrayconvpictotofa['currency'] = 'dollar-sign';
6274 $arrayconvpictotofa['multicurrency'] = 'euro-sign';
6275 }
6276 } else {
6277 $arrayconvpictotofa = array();
6278 }
6279
6280 return $arrayconvpictotofa;
6281}
6282
6283
6298function img_object($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $srconly = 0, $notitle = 0, $allowothertags = array())
6299{
6300 if (strpos($picto, '^') === 0) {
6301 return img_picto($titlealt, str_replace('^', '', $picto), $moreatt, $pictoisfullpath, $srconly, $notitle, '', '', 2, $allowothertags);
6302 } else {
6303 return img_picto($titlealt, 'object_' . $picto, $moreatt, $pictoisfullpath, $srconly, $notitle, '', '', 2, $allowothertags);
6304 }
6305}
6306
6318function img_weather($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $morecss = '')
6319{
6320 global $conf;
6321
6322 if (is_numeric($picto)) {
6323 //$leveltopicto = array(0=>'weather-clear.png', 1=>'weather-few-clouds.png', 2=>'weather-clouds.png', 3=>'weather-many-clouds.png', 4=>'weather-storm.png');
6324 //$picto = $leveltopicto[$picto];
6325 return '<i class="fa fa-weather-level' . $picto . '"></i>';
6326 } elseif (!preg_match('/(\.png|\.gif)$/i', $picto)) {
6327 $picto .= '.png';
6328 }
6329
6330 $path = DOL_URL_ROOT . '/theme/' . $conf->theme . '/img/weather/' . $picto;
6331
6332 return img_picto($titlealt, $path, $moreatt, 1, 0, 0, '', $morecss);
6333}
6334
6346function img_picto_common($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $notitle = 0)
6347{
6348 global $conf;
6349
6350 if (!preg_match('/(\.png|\.gif)$/i', $picto)) {
6351 $picto .= '.png';
6352 }
6353
6354 if ($pictoisfullpath) {
6355 $path = $picto;
6356 } else {
6357 $path = DOL_URL_ROOT . '/theme/common/' . $picto;
6358
6359 if (getDolGlobalInt('MAIN_MODULE_CAN_OVERWRITE_COMMONICONS')) {
6360 $themepath = DOL_DOCUMENT_ROOT . '/theme/' . $conf->theme . '/img/' . $picto;
6361
6362 if (file_exists($themepath)) {
6363 $path = $themepath;
6364 }
6365 }
6366 }
6367
6368 return img_picto($titlealt, $path, $moreatt, 1, 0, $notitle);
6369}
6370
6384function img_action($titlealt, $numaction, $picto = '', $moreatt = '')
6385{
6386 global $langs;
6387
6388 if (empty($titlealt) || $titlealt == 'default') {
6389 if ($numaction == '-1' || $numaction == 'ST_NO') {
6390 $numaction = -1;
6391 $titlealt = $langs->transnoentitiesnoconv('ChangeDoNotContact');
6392 } elseif ($numaction == '0' || $numaction == 'ST_NEVER') {
6393 $numaction = 0;
6394 $titlealt = $langs->transnoentitiesnoconv('ChangeNeverContacted');
6395 } elseif ($numaction == '1' || $numaction == 'ST_TODO') {
6396 $numaction = 1;
6397 $titlealt = $langs->transnoentitiesnoconv('ChangeToContact');
6398 } elseif ($numaction == '2' || $numaction == 'ST_PEND') {
6399 $numaction = 2;
6400 $titlealt = $langs->transnoentitiesnoconv('ChangeContactInProcess');
6401 } elseif ($numaction == '3' || $numaction == 'ST_DONE') {
6402 $numaction = 3;
6403 $titlealt = $langs->transnoentitiesnoconv('ChangeContactDone');
6404 } else {
6405 $titlealt = $langs->transnoentitiesnoconv('ChangeStatus ' . $numaction);
6406 $numaction = 0;
6407 }
6408 }
6409 if (!is_numeric($numaction)) {
6410 $numaction = 0;
6411 }
6412
6413 return img_picto($titlealt, (empty($picto) ? 'stcomm' . $numaction . '.png' : $picto), $moreatt);
6414}
6415
6423function img_edit_add($titlealt = 'default', $other = '')
6424{
6425 global $langs;
6426
6427 if ($titlealt == 'default') {
6428 $titlealt = $langs->trans('Add');
6429 }
6430
6431 return img_picto($titlealt, 'edit_add.png', $other);
6432}
6440function img_edit_remove($titlealt = 'default', $other = '')
6441{
6442 global $langs;
6443
6444 if ($titlealt == 'default') {
6445 $titlealt = $langs->trans('Remove');
6446 }
6447
6448 return img_picto($titlealt, 'edit_remove.png', $other);
6449}
6450
6459function img_edit($titlealt = 'default', $float = 0, $other = '')
6460{
6461 global $langs;
6462
6463 if ($titlealt == 'default') {
6464 $titlealt = $langs->trans('Modify');
6465 }
6466
6467 return img_picto($titlealt, 'edit', ($float ? 'style="float: ' . ($langs->tab_translate["DIRECTION"] == 'rtl' ? 'left' : 'right') . '"' : "") . ($other ? ' ' . $other : ''));
6468}
6469
6478function img_view($titlealt = 'default', $float = 0, $other = 'class="valignmiddle"')
6479{
6480 global $langs;
6481
6482 if ($titlealt == 'default') {
6483 $titlealt = $langs->trans('View');
6484 }
6485
6486 $moreatt = ($float ? 'style="float: right" ' : '') . $other;
6487
6488 return img_picto($titlealt, 'eye', $moreatt);
6489}
6490
6499function img_delete($titlealt = 'default', $other = 'class="pictodelete"', $morecss = '')
6500{
6501 global $langs;
6502
6503 if ($titlealt == 'default') {
6504 $titlealt = $langs->trans('Delete');
6505 }
6506
6507 return img_picto($titlealt, 'delete', $other, 0, 0, 0, '', $morecss);
6508}
6509
6517function img_printer($titlealt = "default", $other = '')
6518{
6519 global $langs;
6520 if ($titlealt == "default") {
6521 $titlealt = $langs->trans("Print");
6522 }
6523 return img_picto($titlealt, 'printer', $other);
6524}
6525
6533function img_split($titlealt = 'default', $other = 'class="pictosplit"')
6534{
6535 global $langs;
6536
6537 if ($titlealt == 'default') {
6538 $titlealt = $langs->trans('Split');
6539 }
6540
6541 return img_picto($titlealt, 'split', $other);
6542}
6543
6551function img_help($usehelpcursor = 1, $usealttitle = 1)
6552{
6553 global $langs;
6554
6555 if ($usealttitle) {
6556 if (is_string($usealttitle)) {
6557 $usealttitle = dol_escape_htmltag($usealttitle);
6558 } else {
6559 $usealttitle = $langs->trans('Info');
6560 }
6561 }
6562
6563 return img_picto($usealttitle, 'info', 'style="vertical-align: middle;' . ($usehelpcursor == 1 ? ' cursor: help' : ($usehelpcursor == 2 ? ' cursor: pointer' : '')) . '"');
6564}
6565
6572function img_info($titlealt = 'default')
6573{
6574 global $langs;
6575
6576 if ($titlealt == 'default') {
6577 $titlealt = $langs->trans('Informations');
6578 }
6579
6580 return img_picto($titlealt, 'info', 'style="vertical-align: middle;"');
6581}
6582
6591function img_warning($titlealt = 'default', $moreatt = '', $morecss = 'pictowarning')
6592{
6593 global $langs;
6594
6595 if ($titlealt == 'default') {
6596 $titlealt = $langs->trans('Warning');
6597 }
6598
6599 //return '<div class="imglatecoin">'.img_picto($titlealt, 'warning_white.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): '')).'</div>';
6600 return img_picto($titlealt, 'warning', 'class="' . $morecss . '"' . ($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' ' . $moreatt) : ''));
6601}
6602
6609function img_error($titlealt = 'default')
6610{
6611 global $langs;
6612
6613 if ($titlealt == 'default') {
6614 $titlealt = $langs->trans('Error');
6615 }
6616
6617 return img_picto($titlealt, 'error');
6618}
6619
6627function img_next($titlealt = 'default', $moreatt = '')
6628{
6629 global $langs;
6630
6631 if ($titlealt == 'default') {
6632 $titlealt = $langs->trans('Next');
6633 }
6634
6635 //return img_picto($titlealt, 'next.png', $moreatt);
6636 return '<span class="fa fa-chevron-right paddingright paddingleft" title="' . dol_escape_htmltag($titlealt) . '"></span>';
6637}
6638
6646function img_previous($titlealt = 'default', $moreatt = '')
6647{
6648 global $langs;
6649
6650 if ($titlealt == 'default') {
6651 $titlealt = $langs->trans('Previous');
6652 }
6653
6654 //return img_picto($titlealt, 'previous.png', $moreatt);
6655 return '<span class="fa fa-chevron-left paddingright paddingleft" title="' . dol_escape_htmltag($titlealt) . '"></span>';
6656}
6657
6666function img_down($titlealt = 'default', $selected = 0, $moreclass = '')
6667{
6668 global $langs;
6669
6670 if ($titlealt == 'default') {
6671 $titlealt = $langs->trans('Down');
6672 }
6673
6674 return img_picto($titlealt, ($selected ? '1downarrow_selected' : '1downarrow'), 'class="imgdown' . ($moreclass ? " " . $moreclass : "") . '"');
6675}
6676
6685function img_up($titlealt = 'default', $selected = 0, $moreclass = '')
6686{
6687 global $langs;
6688
6689 if ($titlealt == 'default') {
6690 $titlealt = $langs->trans('Up');
6691 }
6692
6693 return img_picto($titlealt, ($selected ? '1uparrow_selected' : '1uparrow'), 'class="imgup' . ($moreclass ? " " . $moreclass : "") . '"');
6694}
6695
6704function img_left($titlealt = 'default', $selected = 0, $moreatt = '')
6705{
6706 global $langs;
6707
6708 if ($titlealt == 'default') {
6709 $titlealt = $langs->trans('Left');
6710 }
6711
6712 return img_picto($titlealt, ($selected ? '1leftarrow_selected' : '1leftarrow'), $moreatt);
6713}
6714
6723function img_right($titlealt = 'default', $selected = 0, $moreatt = '')
6724{
6725 global $langs;
6726
6727 if ($titlealt == 'default') {
6728 $titlealt = $langs->trans('Right');
6729 }
6730
6731 return img_picto($titlealt, ($selected ? '1rightarrow_selected' : '1rightarrow'), $moreatt);
6732}
6733
6741function img_allow($allow, $titlealt = 'default')
6742{
6743 global $langs;
6744
6745 if ($titlealt == 'default') {
6746 $titlealt = $langs->trans('Active');
6747 }
6748
6749 if ($allow == 1) {
6750 return img_picto($titlealt, 'tick');
6751 }
6752
6753 return '-';
6754}
6755
6763function img_credit_card($brand, $morecss = 'fa-2x inline-block valignmiddle')
6764{
6765 if (is_null($morecss)) {
6766 $morecss = 'fa-2x';
6767 }
6768
6769 if ($brand == 'visa' || $brand == 'Visa') {
6770 $brand = 'cc-visa';
6771 } elseif ($brand == 'mastercard' || $brand == 'MasterCard') {
6772 $brand = 'cc-mastercard';
6773 } elseif ($brand == 'amex' || $brand == 'American Express') {
6774 $brand = 'cc-amex';
6775 } elseif ($brand == 'discover' || $brand == 'Discover') {
6776 $brand = 'cc-discover';
6777 } elseif ($brand == 'jcb' || $brand == 'JCB') {
6778 $brand = 'cc-jcb';
6779 } elseif ($brand == 'diners' || $brand == 'Diners club') {
6780 $brand = 'cc-diners-club';
6781 } elseif (!in_array($brand, array('cc-visa', 'cc-mastercard', 'cc-amex', 'cc-discover', 'cc-jcb', 'cc-diners-club'))) {
6782 $brand = 'credit-card';
6783 }
6784
6785 return '<span class="fa fa-' . $brand . ' fa-fw' . ($morecss ? ' ' . $morecss : '') . '"></span>';
6786}
6787
6796function img_mime($file, $titlealt = '', $morecss = '')
6797{
6798 require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
6799
6800 $mimetype = dol_mimetype($file, '', 1);
6801 //$mimeimg = dol_mimetype($file, '', 2);
6802 $mimefa = dol_mimetype($file, '', 4);
6803
6804 if (empty($titlealt)) {
6805 $titlealt = 'Mime type: ' . $mimetype;
6806 }
6807
6808 //return img_picto_common($titlealt, 'mime/'.$mimeimg, 'class="'.$morecss.'"');
6809 return '<i class="fa fa-' . $mimefa . ' ' . (preg_match('/pictofixedwidth/', $morecss) ? '' : 'paddingright ') . ($morecss ? ' ' . $morecss : '') . '"' . ($titlealt ? ' title="' . dolPrintHTMLForAttribute($titlealt) . '"' : '') . '></i>';
6810}
6811
6812
6820function img_search($titlealt = 'default', $other = '')
6821{
6822 global $langs;
6823
6824 if ($titlealt == 'default') {
6825 $titlealt = $langs->trans('Search');
6826 }
6827
6828 $img = img_picto($titlealt, 'search', $other, 0, 1);
6829
6830 $input = '<input type="image" class="liste_titre" name="button_search" src="' . $img . '" ';
6831 $input .= 'value="' . dol_escape_htmltag($titlealt) . '" title="' . dol_escape_htmltag($titlealt) . '" >';
6832
6833 return $input;
6834}
6835
6843function img_searchclear($titlealt = 'default', $other = '')
6844{
6845 global $langs;
6846
6847 if ($titlealt == 'default') {
6848 $titlealt = $langs->trans('Search');
6849 }
6850
6851 $img = img_picto($titlealt, 'searchclear.png', $other, 0, 1);
6852
6853 $input = '<input type="image" class="liste_titre" name="button_removefilter" src="' . $img . '" ';
6854 $input .= 'value="' . dol_escape_htmltag($titlealt) . '" title="' . dol_escape_htmltag($titlealt) . '" >';
6855
6856 return $input;
6857}
6858
6873function info_admin($text, $infoonimgalt = 0, $nodiv = 0, $admin = '1', $morecss = 'hideonsmartphone', $textfordropdown = '', $picto = '', $textonpictotooltip = '', $cssfordropdown = 'info_admin')
6874{
6875 global $conf, $langs;
6876
6877 if ($infoonimgalt) {
6878 $result = img_picto($text, 'info', 'class="' . ($morecss ? ' ' . $morecss : '') . '"');
6879 } else {
6880 if (empty($conf->use_javascript_ajax)) {
6881 $textfordropdown = '';
6882 }
6883
6884 $class = (empty($admin) ? 'undefined' : ((string) $admin == '1' ? 'info' : $admin));
6885 $fa = 'info-circle';
6886 if ($picto == 'warning') {
6887 $fa = 'exclamation-triangle';
6888 }
6889 $result = ($nodiv ? '' : '<div class="wordbreak ' . $class . ($cssfordropdown ? ' ' . $cssfordropdown : '') . ($morecss ? ' ' . $morecss : '') . ($textfordropdown ? ' hidden' : '') . '">');
6890 $result .= img_picto(((string) $admin ? $langs->trans('InfoAdmin') : $langs->trans('Note')).($textonpictotooltip ? ' : '.$textonpictotooltip : ''), $fa);
6891 $result .= ' ';
6892 $result .= dol_escape_htmltag($text, 1, 0, 'div,span,b,br,a');
6893 $result .= ($nodiv ? '' : '</div>');
6894
6895 if ($textfordropdown) {
6896 $tmpresult = '<span class="' . $class . ' '. $cssfordropdown.'text opacitymedium cursorpointer">' . $langs->trans($textfordropdown) . ' ' . img_picto($langs->trans($textfordropdown), '1downarrow') . '</span>';
6897 $tmpresult .= '<script nonce="' . getNonce() . '" type="text/javascript">
6898 jQuery(document).ready(function() {
6899 jQuery(".' . $cssfordropdown . 'text").click(function() {
6900 console.log("toggle text of .'.$cssfordropdown.'");
6901 jQuery(".' . $cssfordropdown . '").toggle().removeClass("hidden");
6902 });
6903 });
6904 </script>';
6905
6906 $result = $tmpresult . $result;
6907 }
6908 }
6909
6910 return $result;
6911}
6912
6913
6925function dol_print_error($db = null, $error = '', $errors = null)
6926{
6927 global $conf, $langs, $user, $argv;
6928 global $dolibarr_main_prod;
6929
6930 $out = '';
6931 $syslog = '';
6932
6933 // If error occurs before the $lang object was loaded
6934 if (!$langs) {
6935 require_once DOL_DOCUMENT_ROOT . '/core/class/translate.class.php';
6936 $langs = new Translate('', $conf);
6937 $langs->load("main");
6938 }
6939
6940 // Load translation files required by the error messages
6941 $langs->loadLangs(array('main', 'errors'));
6942
6943 if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
6944 $out .= $langs->trans("DolibarrHasDetectedError") . ".<br>\n";
6945 if (getDolGlobalInt('MAIN_FEATURES_LEVEL') > 0) {
6946 $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";
6947 }
6948 $out .= $langs->trans("InformationToHelpDiagnose") . ":<br>\n";
6949
6950 $out .= "<b>" . $langs->trans("Date") . ":</b> " . dol_print_date(time(), 'dayhourlog') . "<br>\n";
6951 $out .= "<b>" . $langs->trans("Dolibarr") . ":</b> " . DOL_VERSION . " - https://www.dolibarr.org<br>\n";
6952 if (isset($conf->global->MAIN_FEATURES_LEVEL)) {
6953 $out .= "<b>" . $langs->trans("LevelOfFeature") . ":</b> " . getDolGlobalInt('MAIN_FEATURES_LEVEL') . "<br>\n";
6954 }
6955 if ($user instanceof User) {
6956 $out .= "<b>" . $langs->trans("Login") . ":</b> " . $user->login . "<br>\n";
6957 }
6958 if (function_exists("phpversion")) {
6959 $out .= "<b>" . $langs->trans("PHP") . ":</b> " . phpversion() . "<br>\n";
6960 }
6961 $out .= "<b>" . $langs->trans("Server") . ":</b> " . (isset($_SERVER["SERVER_SOFTWARE"]) ? dol_htmlentities($_SERVER["SERVER_SOFTWARE"], ENT_COMPAT) : '') . "<br>\n";
6962 if (function_exists("php_uname")) {
6963 $out .= "<b>" . $langs->trans("OS") . ":</b> " . php_uname() . "<br>\n";
6964 }
6965 $out .= "<b>" . $langs->trans("UserAgent") . ":</b> " . (isset($_SERVER["HTTP_USER_AGENT"]) ? dol_htmlentities($_SERVER["HTTP_USER_AGENT"], ENT_COMPAT) : '') . "<br>\n";
6966 $out .= "<br>\n";
6967 $out .= "<b>" . $langs->trans("RequestedUrl") . ":</b> " . (isset($_SERVER["REQUEST_URI"]) ? dol_htmlentities($_SERVER["REQUEST_URI"], ENT_COMPAT) : '') . "<br>\n";
6968 $out .= "<b>" . $langs->trans("Referer") . ":</b> " . (isset($_SERVER["HTTP_REFERER"]) ? dol_htmlentities($_SERVER["HTTP_REFERER"], ENT_COMPAT) : '') . "<br>\n";
6969 $out .= "<b>" . $langs->trans("MenuManager") . ":</b> " . (isset($conf->standard_menu) ? dol_htmlentities($conf->standard_menu, ENT_COMPAT) : '') . "<br>\n";
6970 $out .= "<br>\n";
6971 $syslog .= "url=" . (isset($_SERVER["REQUEST_URI"]) ? dol_escape_htmltag($_SERVER["REQUEST_URI"]) : '');
6972 $syslog .= ", query_string=" . (isset($_SERVER["QUERY_STRING"]) ? dol_escape_htmltag($_SERVER["QUERY_STRING"]) : '');
6973 } else { // Mode CLI
6974 $out .= '> ' . $langs->transnoentities("ErrorInternalErrorDetected") . ":\n" . $argv[0] . "\n";
6975 $syslog .= "pid=" . dol_getmypid();
6976 }
6977
6978 if (!empty($conf->modules)) {
6979 $out .= "<b>" . $langs->trans("Modules") . ":</b> " . implode(', ', $conf->modules) . "<br>\n";
6980 }
6981
6982 if (is_object($db)) {
6983 if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
6984 $out .= "<b>" . $langs->trans("DatabaseTypeManager") . ":</b> " . $db->type . "<br>\n";
6985 $lastqueryerror = $db->lastqueryerror();
6986 if (!utf8_check($lastqueryerror)) {
6987 $lastqueryerror = "SQL error string is not a valid UTF8 string. We can't show it.";
6988 }
6989 $out .= "<b>" . $langs->trans("RequestLastAccessInError") . ":</b> " . ($lastqueryerror ? dol_escape_htmltag($lastqueryerror) : $langs->trans("ErrorNoRequestInError")) . "<br>\n";
6990 $out .= "<b>" . $langs->trans("ReturnCodeLastAccessInError") . ":</b> " . ($db->lasterrno() ? dol_escape_htmltag($db->lasterrno()) : $langs->trans("ErrorNoRequestInError")) . "<br>\n";
6991 $out .= "<b>" . $langs->trans("InformationLastAccessInError") . ":</b> " . ($db->lasterror() ? dol_escape_htmltag($db->lasterror()) : $langs->trans("ErrorNoRequestInError")) . "<br>\n";
6992 $out .= "<br>\n";
6993 } else { // Mode CLI
6994 // No dol_escape_htmltag for output, we are in CLI mode
6995 $out .= '> ' . $langs->transnoentities("DatabaseTypeManager") . ":\n" . $db->type . "\n";
6996 $out .= '> ' . $langs->transnoentities("RequestLastAccessInError") . ":\n" . ($db->lastqueryerror() ? $db->lastqueryerror() : $langs->transnoentities("ErrorNoRequestInError")) . "\n";
6997 $out .= '> ' . $langs->transnoentities("ReturnCodeLastAccessInError") . ":\n" . ($db->lasterrno() ? $db->lasterrno() : $langs->transnoentities("ErrorNoRequestInError")) . "\n";
6998 $out .= '> ' . $langs->transnoentities("InformationLastAccessInError") . ":\n" . ($db->lasterror() ? $db->lasterror() : $langs->transnoentities("ErrorNoRequestInError")) . "\n";
6999 }
7000 $syslog .= ", sql=" . $db->lastquery();
7001 $syslog .= ", db_error=" . $db->lasterror();
7002 }
7003
7004 if ($error || $errors) {
7005 // Merge all into $errors array
7006 if (is_array($error) && is_array($errors)) {
7007 $errors = array_merge($error, $errors);
7008 } elseif (is_array($error)) { // deprecated, use second parameters
7009 $errors = $error;
7010 } elseif (is_array($errors) && !empty($error)) {
7011 $errors = array_merge(array($error), $errors);
7012 } elseif (!empty($error)) {
7013 $errors = array_merge(array($error), array($errors));
7014 }
7015
7016 $langs->load("errors");
7017
7018 foreach ($errors as $msg) {
7019 if (empty($msg)) {
7020 continue;
7021 }
7022 if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
7023 $out .= "<b>" . $langs->trans("Message") . ":</b> " . dol_escape_htmltag($msg) . "<br>\n";
7024 } else { // Mode CLI
7025 $out .= '> ' . $langs->transnoentities("Message") . ":\n" . $msg . "\n";
7026 }
7027 $syslog .= ", msg=" . $msg;
7028 }
7029 }
7030 if (empty($dolibarr_main_prod) && $_SERVER['DOCUMENT_ROOT'] && function_exists('xdebug_print_function_stack') && function_exists('xdebug_call_file')) {
7031 xdebug_print_function_stack();
7032 $out .= '<b>XDebug information:</b>' . "<br>\n";
7033 $out .= 'File: ' . xdebug_call_file() . "<br>\n";
7034 $out .= 'Line: ' . xdebug_call_line() . "<br>\n";
7035 $out .= 'Function: ' . xdebug_call_function() . "<br>\n";
7036 $out .= "<br>\n";
7037 }
7038
7039 // Return a http header with error code if possible
7040 if (!headers_sent()) {
7041 if (function_exists('top_httphead')) { // In CLI context, the method does not exists
7042 top_httphead();
7043 }
7044 //http_response_code(500); // If we use 500, message is not output with some command line tools
7045 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
7046 }
7047
7048 if (empty($dolibarr_main_prod)) {
7049 print $out;
7050 } else {
7051 if (empty($langs->defaultlang)) {
7052 $langs->setDefaultLang();
7053 }
7054 $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.
7055 // This should not happen, except if there is a bug somewhere. Enabled and check log in such case.
7056 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";
7057 print $langs->trans("DolibarrHasDetectedError") . '. ';
7058 print $langs->trans("YouCanSetOptionDolibarrMainProdToZero");
7059 if (!defined("MAIN_CORE_ERROR")) {
7060 define("MAIN_CORE_ERROR", 1);
7061 }
7062 }
7063
7064 dol_syslog("Error " . $syslog, LOG_ERR);
7065}
7066
7077function dol_print_error_email($prefixcode, $errormessage = '', $errormessages = array(), $morecss = 'error', $email = '')
7078{
7079 global $langs;
7080
7081 if (empty($email)) {
7082 $email = getDolGlobalString('MAIN_INFO_SOCIETE_MAIL');
7083 }
7084
7085 $langs->load("errors");
7086 $now = dol_now();
7087
7088 print '<br><div class="center login_main_message"><div class="' . $morecss . '">';
7089 print $langs->trans("ErrorContactEMail", $email, $prefixcode . '-' . dol_print_date($now, '%Y%m%d%H%M%S'));
7090 if ($errormessage) {
7091 print '<br><br>' . $errormessage;
7092 }
7093 if (is_array($errormessages) && count($errormessages)) {
7094 foreach ($errormessages as $mesgtoshow) {
7095 print '<br><br>' . $mesgtoshow;
7096 }
7097 }
7098 print '</div></div>';
7099}
7100
7117function print_liste_field_titre($name, $file = "", $field = "", $begin = "", $param = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $tooltip = "", $forcenowrapcolumntitle = 0)
7118{
7119 print getTitleFieldOfList($name, 0, $file, $field, $begin, $param, $moreattrib, $sortfield, $sortorder, $prefix, 0, $tooltip, $forcenowrapcolumntitle);
7120}
7121
7140function getTitleFieldOfList($name, $thead = 0, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $disablesortlink = 0, $tooltip = '', $forcenowrapcolumntitle = 0)
7141{
7142 global $langs, $form;
7143 //print "$name, $file, $field, $begin, $options, $moreattrib, $sortfield, $sortorder<br>\n";
7144
7145 if ($moreattrib == 'class="right"') {
7146 $prefix .= 'right '; // For backward compatibility
7147 }
7148
7149 $tooltip = (string) $tooltip; // In case $tooltip is null
7150
7151 $sortorder = strtoupper((string) $sortorder);
7152 $out = '';
7153 $sortimg = '';
7154
7155 $tag = 'th';
7156 if ($thead == 2) {
7157 $tag = 'div';
7158 }
7159
7160 $tmpsortfield = explode(',', (string) $sortfield);
7161 $sortfield1 = trim($tmpsortfield[0]); // If $sortfield is 'd.datep,d.id', it becomes 'd.datep'
7162 $tmpfield = explode(',', $field);
7163 $field1 = trim($tmpfield[0]); // If $field is 'd.datep,d.id', it becomes 'd.datep'
7164
7165 if (strpos((string) $tooltip, ':') !== false) {
7166 $tmptooltip = explode(':', (string) $tooltip);
7167 } else {
7168 $tmptooltip = array($tooltip);
7169 }
7170
7171 $wrapcolumntitle = (empty($forcenowrapcolumntitle) || (!empty($tmptooltip[2]) && $tmptooltip[2] == '-1'));
7172
7173 if (!getDolGlobalString('MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE') && $wrapcolumntitle) {
7174 $prefix = 'wrapcolumntitle ' . $prefix;
7175 }
7176
7177 //var_dump('field='.$field.' field1='.$field1.' sortfield='.$sortfield.' sortfield1='.$sortfield1);
7178 // If field is used as sort criteria we use a specific css class liste_titre_sel
7179 // Example if (sortfield,field)=("nom","xxx.nom") or (sortfield,field)=("nom","nom")
7180 $liste_titre = 'liste_titre';
7181 if ($field1 && ($sortfield1 == $field1 || $sortfield1 == preg_replace("/^[^\.]+\./", "", $field1))) {
7182 $liste_titre = 'liste_titre_sel';
7183 }
7184
7185 $tagstart = '<' . $tag . ' class="' . $prefix . $liste_titre . '" ' . $moreattrib;
7186 //$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)).'"' : '');
7187 $tagstart .= ($name && !getDolGlobalString('MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE') && $wrapcolumntitle && !dol_textishtml($name)) ? ' title="' . dolPrintHTMLForAttribute($langs->trans($name)) . '"' : '';
7188 $tagstart .= '>';
7189
7190 if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
7191 $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
7192 $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
7193 $options = preg_replace('/&+/i', '&', $options);
7194 if (!preg_match('/^&/', $options)) {
7195 $options = '&' . $options;
7196 }
7197
7198 $sortordertouseinlink = '';
7199 if ($field1 != $sortfield1) { // We are on another field than current sorted field
7200 if (preg_match('/^DESC/i', $sortorder)) {
7201 $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
7202 } else { // We reverse the var $sortordertouseinlink
7203 $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
7204 }
7205 } else { // We are on field that is the first current sorting criteria
7206 if (preg_match('/^ASC/i', $sortorder)) { // We reverse the var $sortordertouseinlink
7207 $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
7208 } else {
7209 $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
7210 }
7211 }
7212 $sortordertouseinlink = preg_replace('/,$/', '', $sortordertouseinlink);
7213 $out .= '<a class="reposition" href="' . dolBuildUrl($file, ['sortfield' => $field, 'sortorder' => $sortordertouseinlink, 'begin' => $begin]) . $options . '"';
7214 //$out .= (getDolGlobalString('MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE') ? '' : ' title="'.dol_escape_htmltag($langs->trans($name)).'"');
7215 $out .= '>';
7216 }
7217 if ($tooltip && $tmptooltip[0]) {
7218 // You can also use 'TranslationString:[keyfortooltiponclick]:[tooltipdirection]' for a tooltip on click or to change tooltip position.
7219 $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]));
7220 } else {
7221 $out .= $langs->trans((string) $name);
7222 }
7223
7224 if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
7225 $out .= '</a>';
7226 }
7227
7228 if (empty($thead) && $field) { // If this is a sort field
7229 $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
7230 $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
7231 $options = preg_replace('/&+/i', '&', $options);
7232 if (!preg_match('/^&/', $options)) {
7233 $options = '&' . $options;
7234 }
7235
7236 if (!$sortorder || ($field1 != $sortfield1)) {
7237 // Nothing
7238 } else {
7239 if (preg_match('/^DESC/', $sortorder)) {
7240 $sortimg .= '<span class="nowrap">' . img_up("Z-A", 0, 'paddingright') . '</span>';
7241 }
7242 if (preg_match('/^ASC/', $sortorder)) {
7243 $sortimg .= '<span class="nowrap">' . img_down("A-Z", 0, 'paddingright') . '</span>';
7244 }
7245 }
7246 }
7247
7248 $tagend = '</' . $tag . '>';
7249
7250 $out = $tagstart . $sortimg . $out . $tagend;
7251
7252 return $out;
7253}
7254
7263function print_titre($title)
7264{
7265 dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);
7266
7267 print '<div class="titre">' . $title . '</div>';
7268}
7269
7281function print_fiche_titre($title, $mesg = '', $picto = 'generic', $pictoisfullpath = 0, $id = '')
7282{
7283 print load_fiche_titre($title, $mesg, $picto, $pictoisfullpath, $id);
7284}
7285
7300function load_fiche_titre($title, $morehtmlright = '', $picto = 'generic', $pictoisfullpath = 0, $id = '', $morecssontable = '', $morehtmlcenter = '', $morecssonpicto = 'widthpictotitle')
7301{
7302 $return = '';
7303
7304 if ($picto == 'setup') {
7305 $picto = 'generic';
7306 }
7307
7308 $return .= "\n";
7309 $return .= '<table ' . ($id ? 'id="' . $id . '" ' : '') . 'class="centpercent notopnoleftnoright table-fiche-title' . ($morecssontable ? ' ' . $morecssontable : '') . '">'; // margin bottom must be same than into print_barre_list
7310 $return .= '<tr class="toptitle">';
7311 if ($picto) {
7312 $return .= '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">' . img_picto('', $picto, 'class="valignmiddle pictotitle'.($morecssonpicto ? ' '.$morecssonpicto : '').'"', $pictoisfullpath) . '</td>';
7313 }
7314 $return .= '<td class="nobordernopadding valignmiddle col-title">';
7315 $return .= '<div class="titre inline-block">';
7316 $return .= '<span class="inline-block valignmiddle print-barre-liste">' . $title . '</span>'; // $title is already HTML sanitized content
7317 $return .= '</div>';
7318 $return .= '</td>';
7319 if (dol_strlen($morehtmlcenter)) {
7320 $return .= '<td class="nobordernopadding center valignmiddle col-center">' . $morehtmlcenter . '</td>';
7321 }
7322 if (dol_strlen($morehtmlright)) {
7323 $return .= '<td class="nobordernopadding titre_right wordbreakimp right valignmiddle col-right">' . $morehtmlright . '</td>';
7324 }
7325 $return .= '</tr></table>' . "\n";
7326
7327 return $return;
7328}
7329
7353function 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 = '')
7354{
7355 global $conf, $langs;
7356
7357 $savlimit = $limit;
7358 $savtotalnboflines = $totalnboflines;
7359 if (is_numeric($totalnboflines)) {
7360 $totalnboflines = abs($totalnboflines);
7361 }
7362
7363 // Detect if there is a subtitle
7364 $subtitle = '';
7365 $tmparray = preg_split('/<br>/i', $title, 2);
7366 if (!empty($tmparray[1])) {
7367 $title = $tmparray[0];
7368 $subtitle = $tmparray[1];
7369 }
7370
7371 $page = (int) $page;
7372
7373 if ($picto == 'setup') {
7374 $picto = 'title_setup';
7375 }
7376 if (($conf->browser->name == 'ie') && $picto == 'generic') {
7377 $picto = 'title.gif';
7378 }
7379 if ($limit < 0) {
7380 $limit = $conf->liste_limit;
7381 }
7382
7383 if ($savlimit != 0 && (($num > $limit) || ($num == -1) || ($limit == 0))) {
7384 $nextpage = 1;
7385 } else {
7386 $nextpage = 0;
7387 }
7388 //print 'totalnboflines='.$totalnboflines.'-savlimit='.$savlimit.'-limit='.$limit.'-num='.$num.'-nextpage='.$nextpage.'-selectlimitsuffix='.$selectlimitsuffix.'-hidenavigation='.$hidenavigation;
7389
7390 print "\n";
7391 print "<!-- Begin print_barre_liste -->\n";
7392 print '<table class="centpercent notopnoleftnoright table-fiche-title' . ($morecss ? ' ' . $morecss : '') . '">';
7393 print '<tr class="toptitle">'; // margin bottom must be same than into load_fiche_tire
7394
7395 // Left
7396
7397 if ($picto && $title) {
7398 print '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">';
7399 print img_picto('', $picto, 'class="valignmiddle pictotitle widthpictotitle"', $pictoisfullpath);
7400 print '</td>';
7401 }
7402
7403 print '<td class="nobordernopadding valignmiddle col-title">';
7404 print '<div class="titre inline-block nowrap">';
7405 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()
7406 if (!empty($title) && $savtotalnboflines >= 0 && (string) $savtotalnboflines != '') {
7407 if (is_numeric($totalnboflines) && (int) $totalnboflines > 0) {
7408 print '<span class="opacitymedium colorblack marginleftonly totalnboflines valignmiddle" title="' . $langs->trans("NbRecordQualified") . '">(' . $totalnboflines . ')</span>';
7409 } else {
7410 print '<span class="opacitymedium colorblack marginleftonly totalnboflines valignmiddle">(' . $totalnboflines . ')</span>';
7411 }
7412 }
7413 print '</div>';
7414 if (!empty($subtitle)) {
7415 print '<br><div class="subtitle inline-block hideonsmartphone">' . $subtitle . '</div>';
7416 }
7417 print '</td>';
7418
7419 // Center
7420 if ($morehtmlcenter && empty($conf->dol_optimize_smallscreen)) {
7421 print '<td class="nobordernopadding center valignmiddle col-center">' . $morehtmlcenter . '</td>';
7422 }
7423
7424 // Right
7425 print '<td class="nobordernopadding valignmiddle right col-right">';
7426 print '<input type="hidden" name="pageplusoneold" value="' . ((int) $page + 1) . '">';
7427 $query = [];
7428 parse_str($options, $query);
7429 if ($sortfield) {
7430 $query += ['sortfield' => $sortfield];
7431 }
7432 if ($sortorder) {
7433 $query += ['sortorder' => $sortorder];
7434 }
7435
7436 $options = '&' . http_build_query($query);
7437 if ($page) {
7438 $query = array_merge($query, ['page' => $page]);
7439 }
7440 // Show navigation bar
7441 $pagelist = '';
7442 if ($savlimit != 0 && ($page > 0 || $num > $limit)) {
7443 if ($totalnboflines) { // If we know total nb of lines
7444 // Define nb of extra page links before and after selected page + ... + first or last
7445 $maxnbofpage = (empty($conf->dol_optimize_smallscreen) ? 4 : 0);
7446
7447 if ($limit > 0) {
7448 $nbpages = ceil($totalnboflines / $limit);
7449 } else {
7450 $nbpages = 1;
7451 }
7452 $cpt = ($page - $maxnbofpage);
7453 if ($cpt < 0) {
7454 $cpt = 0;
7455 }
7456
7457 if ($cpt >= 1) {
7458 if (empty($pagenavastextinput)) {
7459 $query['page'] = 0;
7460 $pagelist .= '<li class="pagination"><a class="reposition" href="' . dolBuildUrl($file, $query) . '">1</a></li>';
7461 if ($cpt > 2) {
7462 $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
7463 } elseif ($cpt == 2) {
7464 $query['page'] = 0;
7465 $pagelist .= '<li class="pagination"><a class="reposition" href="' . dolBuildUrl($file, $query) . '">2</a></li>';
7466 }
7467 }
7468 }
7469
7470 do {
7471 if ($pagenavastextinput) {
7472 if ($cpt == $page) {
7473 $pagelist .= '<li class="pagination pageplusone valignmiddle"><input type="text" class="' . ($totalnboflines > 100 ? 'width40' : 'width25') . ' center pageplusone heightofcombo" name="pageplusone" value="' . ($page + 1) . '"></li>';
7474 $pagelist .= '/';
7475 }
7476 } else {
7477 if ($cpt == $page) {
7478 $pagelist .= '<li class="pagination"><span class="active">' . ($page + 1) . '</span></li>';
7479 } else {
7480 $query['page'] = $cpt;
7481 $pagelist .= '<li class="pagination"><a class="reposition" href="' . dolBuildUrl($file, $query) . '">' . ($cpt + 1) . '</a></li>';
7482 }
7483 }
7484 $cpt++;
7485 } while ($cpt < $nbpages && $cpt <= ($page + $maxnbofpage));
7486
7487 if (empty($pagenavastextinput)) {
7488 if ($cpt < $nbpages) {
7489 if ($cpt < $nbpages - 2) {
7490 $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
7491 } elseif ($cpt == $nbpages - 2) {
7492 $query['page'] = ($nbpages - 2);
7493 $pagelist .= '<li class="pagination"><a class="reposition" href="' . dolBuildUrl($file, $query) . '">' . ($nbpages - 1) . '</a></li>';
7494 }
7495 $query['page'] = ($nbpages - 1);
7496 $pagelist .= '<li class="pagination"><a class="reposition" href="' . dolBuildUrl($file, $query) . '">' . $nbpages . '</a></li>';
7497 }
7498 } else {
7499 $query['page'] = ($nbpages - 1);
7500 $pagelist .= '<li class="pagination paginationlastpage"><a class="reposition" href="' . dolBuildUrl($file, $query) . '">' . $nbpages . '</a></li>';
7501 }
7502 } else {
7503 $pagelist .= '<li class="pagination"><span class="active">' . ($page + 1) . "</li>";
7504 }
7505 }
7506
7507 if ($savlimit || $morehtmlright || $morehtmlrightbeforearrow) {
7508 // Show the combolist to select number of record per page and the navigation arrows.
7509 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
7510 }
7511
7512 // js to autoselect page field on focus
7513 if ($pagenavastextinput) {
7514 print ajax_autoselect('.pageplusone');
7515 }
7516
7517 print '</td>';
7518 print '</tr>';
7519
7520 print "</table>\n";
7521
7522 // Center
7523 if ($morehtmlcenter && !empty($conf->dol_optimize_smallscreen)) {
7524 print '<div class="nobordernopadding marginbottomonly center valignmiddle col-center centpercent">' . $morehtmlcenter . '</div>';
7525 }
7526
7527 print "<!-- End title -->\n\n";
7528}
7529
7546function print_fleche_navigation($page, $file, $options = '', $nextpage = 0, $betweenarrows = '', $afterarrows = '', $limit = -1, $totalnboflines = 0, $selectlimitsuffix = '', $beforearrows = '', $hidenavigation = 0)
7547{
7548 global $conf, $langs;
7549
7550 print '<div class="pagination"><ul>';
7551 if ($beforearrows) {
7552 print '<li class="paginationbeforearrows">';
7553 print $beforearrows;
7554 print '</li>';
7555 }
7556
7557 if (empty($hidenavigation)) {
7558 if ((int) $limit > 0 && (empty($selectlimitsuffix) || !is_numeric($selectlimitsuffix))) {
7559 $pagesizechoices = '10:10,15:15,20:20,25:25,50:50,100:100,250:250,500:500,1000:1000';
7560 $pagesizechoices .= ',5000:5000';
7561 //$pagesizechoices .= ',10000:10000'; // Memory trouble on most browsers
7562 //$pagesizechoices .= ',20000:20000'; // Memory trouble on most browsers
7563 //$pagesizechoices .= ',0:'.$langs->trans("All"); // Not yet supported
7564 //$pagesizechoices .= ',2:2';
7565 if (getDolGlobalString('MAIN_PAGESIZE_CHOICES')) {
7566 $pagesizechoices = getDolGlobalString('MAIN_PAGESIZE_CHOICES');
7567 }
7568
7569 if (getDolGlobalString('MAIN_USE_HTML5_LIMIT_SELECTOR')) {
7570 print '<li class="pagination">';
7571 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 . '">';
7572 print '<datalist id="limitlist">';
7573 } else {
7574 print '<li class="paginationcombolimit valignmiddle">';
7575 print '<select id="limit' . (is_numeric($selectlimitsuffix) ? '' : $selectlimitsuffix) . '" name="'.(is_numeric($selectlimitsuffix) ? 'limit' : $selectlimitsuffix).'" class="flat selectlimit nopadding maxwidth75 center' . (is_numeric($selectlimitsuffix) ? '' : ' ' . $selectlimitsuffix) . '" title="' . dol_escape_htmltag($langs->trans("MaxNbOfRecordPerPage")) . '">';
7576 }
7577 $tmpchoice = explode(',', $pagesizechoices);
7578 $tmpkey = $limit . ':' . $limit;
7579 if (!in_array($tmpkey, $tmpchoice)) {
7580 $tmpchoice[$tmpkey] = $tmpkey;
7581 }
7582 $tmpkey = $conf->liste_limit . ':' . $conf->liste_limit;
7583 if (!in_array($tmpkey, $tmpchoice)) {
7584 $tmpchoice[$tmpkey] = $tmpkey;
7585 }
7586 asort($tmpchoice, SORT_NUMERIC);
7587 foreach ($tmpchoice as $val) {
7588 $selected = '';
7589 $tmp = explode(':', $val);
7590 $key = $tmp[0];
7591 $val = $tmp[1];
7592 if ($key != '' && $val != '') {
7593 if ((int) $key == (int) $limit) {
7594 $selected = ' selected="selected"';
7595 }
7596 print '<option name="' . $key . '"' . $selected . '>' . dol_escape_htmltag($val) . '</option>' . "\n";
7597 }
7598 }
7599 if (getDolGlobalString('MAIN_USE_HTML5_LIMIT_SELECTOR')) {
7600 print '</datalist>';
7601 } else {
7602 print '</select>';
7603 print ajax_combobox("limit" . (is_numeric($selectlimitsuffix) ? '' : $selectlimitsuffix), array(), 0, 0, 'resolve', '-1', 'limit');
7604 //print ajax_combobox("limit");
7605 }
7606
7607 if ($conf->use_javascript_ajax) {
7608 print '<!-- JS CODE TO ENABLE select limit to launch submit of page -->
7609 <script>
7610 jQuery(document).ready(function () {
7611 jQuery(".selectlimit").change(function() {
7612 console.log("We change limit so we submit the form");
7613 $(this).parents(\'form:first\').submit();
7614 });
7615 });
7616 </script>
7617 ';
7618 }
7619 print '</li>';
7620 }
7621 if ($page > 0) {
7622 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>';
7623 }
7624 if ($betweenarrows) {
7625 print '<!--<div class="betweenarrows nowraponall inline-block">-->';
7626 print $betweenarrows;
7627 print '<!--</div>-->';
7628 }
7629 if ($nextpage > 0) {
7630 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>';
7631 }
7632 if ($afterarrows) {
7633 print '<li class="paginationafterarrows">';
7634 print $afterarrows;
7635 print '</li>';
7636 }
7637 }
7638 print '</ul></div>' . "\n";
7639}
7640
7641
7653function vatrate($rate, $addpercent = false, $info_bits = 0, $usestarfornpr = 0, $html = 0)
7654{
7655 $morelabel = '';
7656
7657 if (preg_match('/%/', $rate)) {
7658 $rate = str_replace('%', '', $rate);
7659 $addpercent = true;
7660 }
7661 $reg = array();
7662 if (preg_match('/\‍((.*)\‍)/', $rate, $reg)) {
7663 $morelabel = ' (' . $reg[1] . ')';
7664 $rate = preg_replace('/\s*' . preg_quote($morelabel, '/') . '/', '', $rate);
7665 $morelabel = ' ' . ($html ? '<span class="opacitymedium small">' : '') . '(' . $reg[1] . ')' . ($html ? '</span>' : '');
7666 }
7667 if (preg_match('/\*/', $rate)) {
7668 $rate = str_replace('*', '', $rate);
7669 $info_bits |= 1;
7670 }
7671
7672 // If rate is '9/9/9' we don't change it. If rate is '9.000' we apply price()
7673 if (!preg_match('/\//', $rate)) {
7674 $ret = price($rate, 0, '', 0, 0) . ($addpercent ? '%' : '');
7675 } else {
7676 // TODO Split on / and output with a price2num to have clean numbers without ton of 000.
7677 $ret = $rate . ($addpercent ? '%' : '');
7678 }
7679 if (($info_bits & 1) && $usestarfornpr >= 0) {
7680 $ret .= ' *';
7681 }
7682 $ret .= $morelabel;
7683 return $ret;
7684}
7685
7686
7701function price($amount, $form = 0, $outlangs = '', $trunc = 1, $rounding = -1, $forcerounding = -1, $currency_code = '')
7702{
7703 global $langs, $conf;
7704
7705 // Clean parameters
7706 if (empty($amount)) {
7707 $amount = 0; // To have a numeric value if amount not defined or = ''
7708 }
7709 $amount = (is_numeric($amount) ? $amount : 0); // Check if amount is numeric, for example, an error occurred when amount value = o (letter) instead 0 (number)
7710 if ($rounding == -1) {
7711 $rounding = min(getDolGlobalString('MAIN_MAX_DECIMALS_UNIT'), getDolGlobalString('MAIN_MAX_DECIMALS_TOT'));
7712 }
7713 $nbdecimal = $rounding;
7714
7715 if ($outlangs === 'none') {
7716 // Use international separators
7717 $dec = '.';
7718 $thousand = '';
7719 } else {
7720 // Output separators by default (french)
7721 $dec = ',';
7722 $thousand = ' ';
7723
7724 // If $outlangs not forced, we use use language
7725 if (!($outlangs instanceof Translate)) {
7726 $outlangs = $langs;
7727 }
7728
7729 if ($outlangs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
7730 $dec = $outlangs->transnoentitiesnoconv("SeparatorDecimal");
7731 }
7732 if ($outlangs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
7733 $thousand = $outlangs->transnoentitiesnoconv("SeparatorThousand");
7734 }
7735 if ($thousand == 'None') {
7736 $thousand = '';
7737 } elseif ($thousand == 'Space') {
7738 $thousand = ' ';
7739 }
7740 }
7741 //print "outlangs=".$outlangs->defaultlang." amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
7742
7743 //print "amount=".$amount."-";
7744 $amount = str_replace(',', '.', $amount); // should be useless
7745 //print $amount."-";
7746 $data = explode('.', $amount);
7747 $decpart = isset($data[1]) ? $data[1] : '';
7748 $decpart = preg_replace('/0+$/i', '', $decpart); // Remove 0 at end of decimal part
7749 //print "decpart=".$decpart."<br>";
7750 $end = '';
7751
7752 // We increase nbdecimal if there is more decimal than asked (to not loose information)
7753 if (dol_strlen($decpart) > $nbdecimal) {
7754 $nbdecimal = dol_strlen($decpart);
7755 }
7756
7757 // If nbdecimal is higher than max to show
7758 $nbdecimalmaxshown = (int) str_replace('...', '', getDolGlobalString('MAIN_MAX_DECIMALS_SHOWN'));
7759 if ($trunc && $nbdecimal > $nbdecimalmaxshown) {
7760 $nbdecimal = $nbdecimalmaxshown;
7761 if (preg_match('/\.\.\./i', getDolGlobalString('MAIN_MAX_DECIMALS_SHOWN'))) {
7762 // If output is truncated, we show ...
7763 $end = '...';
7764 }
7765 }
7766
7767 // If force rounding
7768 if ((string) $forcerounding != '-1' && (string) $forcerounding != '') {
7769 if ($forcerounding === 'MU') {
7770 $nbdecimal = getDolGlobalInt('MAIN_MAX_DECIMALS_UNIT');
7771 } elseif ($forcerounding === 'MT') {
7772 $nbdecimal = getDolGlobalInt('MAIN_MAX_DECIMALS_TOT');
7773 } elseif ($forcerounding >= 0) {
7774 $nbdecimal = (int) $forcerounding;
7775 }
7776 }
7777
7778 // Format number
7779 $output = number_format((float) $amount, $nbdecimal, $dec, $thousand);
7780 // Add symbol of currency if requested
7781 $cursymbolbefore = $cursymbolafter = '';
7782 if ($currency_code && is_object($outlangs)) {
7783 if ($currency_code == 'auto') {
7784 $currency_code = $conf->currency;
7785 }
7786
7787 $listofcurrenciesbefore = array('AUD', 'CAD', 'CNY', 'COP', 'CLP', 'GBP', 'HKD', 'MXN', 'PEN', 'USD', 'CRC', 'ZAR');
7788 $listoflanguagesbefore = array('nl_NL');
7789 if (in_array($currency_code, $listofcurrenciesbefore) || in_array($outlangs->defaultlang, $listoflanguagesbefore)) {
7790 $cursymbolbefore .= $outlangs->getCurrencySymbol($currency_code);
7791 } else {
7792 $tmpcur = $outlangs->getCurrencySymbol($currency_code);
7793 $cursymbolafter .= ($tmpcur == $currency_code ? ' ' . $tmpcur : $tmpcur);
7794 }
7795 }
7796 if ($form) {
7797 $output = preg_replace('/\s/', '&nbsp;', $output);
7798 $output = $cursymbolbefore . $output . $end . ($cursymbolafter ? ' <span class="small">'.$cursymbolafter.'</span>' : '');
7799 $output = preg_replace('/\'/', '&#039;', $output);
7800 } else {
7801 $output = $cursymbolbefore . $output . $end . ($cursymbolafter ? ' '.$cursymbolafter : '');
7802 }
7803
7804 return $output;
7805}
7806
7832function price2num($amount, $rounding = '', $option = 0)
7833{
7834 global $langs;
7835
7836 // Clean parameters
7837 if (is_null($amount)) {
7838 $amount = '';
7839 }
7840
7841 // Round PHP function does not allow number like '1,234.56' nor '1.234,56' nor '1 234,56'
7842 // Numbers must be '1234.56'
7843 // Decimal delimiter for PHP and database SQL requests must be '.'
7844 $dec = ',';
7845 $thousand = ' ';
7846 if (is_null($langs)) { // $langs is not defined, we use english values.
7847 $dec = '.';
7848 $thousand = ',';
7849 } else {
7850 if ($langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
7851 $dec = $langs->transnoentitiesnoconv("SeparatorDecimal");
7852 }
7853 if ($langs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
7854 $thousand = $langs->transnoentitiesnoconv("SeparatorThousand");
7855 }
7856 }
7857 if ($thousand == 'None') {
7858 $thousand = '';
7859 } elseif ($thousand == 'Space') {
7860 $thousand = ' ';
7861 }
7862 //print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
7863
7864 // Convert value to universal number format (no thousand separator, '.' as decimal separator)
7865 if ($option != 1) { // If not a PHP number or unknown, we change or clean format
7866 //print "\n".'PP'.$amount.' - '.$dec.' - '.$thousand.' - '.intval($amount).'<br>';
7867 if (!is_numeric($amount)) {
7868 $amount = preg_replace('/[a-zA-Z\/\\\*\‍(\‍)<>\_]/', '', $amount);
7869 }
7870
7871 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
7872 $amount = str_replace($thousand, '', $amount);
7873 }
7874
7875 // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
7876 // to format defined by LC_NUMERIC after a calculation and we want source format to be like defined by Dolibarr setup.
7877 // So if number was already a good number, it is converted into local Dolibarr setup.
7878 if (is_numeric($amount)) {
7879 // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
7880 $temps = sprintf("%10.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
7881 $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
7882 $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
7883 $amount = number_format($amount, $nbofdec, $dec, $thousand);
7884 }
7885 //print "QQ".$amount."<br>\n";
7886
7887 // Now make replaceents (the main goal of function)
7888
7889 if ($thousand != ',' && $thousand != '.') {
7890 // Accept the two types of decimal points french users (i.e., using ' ' for thousands)
7891
7892 // REGEX: Find the integral and decimal parts.
7893 //
7894 // We require that the decimal point only appears once in $amount.
7895 // The regex `/^(?<int>[^,]*,|[^.]*\.)(?<dec>[^.,]*)$/u` can be broken down as follows:
7896 // - `(?<int>[^,]*,|[^.]*\.)` is any accepted sequence up to the last potential decimal point '.' or ',' and named `int`.
7897 // It covers two cases:
7898 // - `[^,]*,`: Any sequence of characters that is not ',' with ',' accepted as the decimal point (from start of string because of earlier `^`);
7899 // - `[^.]*\.`: Any sequence of characters that is not a '.' with '.' accepted as the decimal point (from start of string.
7900 // - `(?<dec>[^.,]*)`: The sequence after the character accepted as the decimal point, not including it.
7901 $matches = array();
7902 if (preg_match('/^(?<int>[^,]*,|[^.]*\.)(?<dec>[^.,]*)$/u', $amount, $matches)) {
7903 $intPart = $matches['int'];
7904 $decPart = $matches['dec'];
7905
7906 // Remove all commas and dots from intPart
7907 $intPart = str_replace(['.', ','], '', $intPart);
7908
7909 // Combine intPart and decPart with a dot
7910 $amount = $intPart . $dec . $decPart;
7911 }
7912 }
7913
7914 $amount = str_replace(' ', '', $amount); // To avoid spaces
7915 $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
7916 $amount = str_replace($dec, '.', $amount);
7917
7918 $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
7919 }
7920 //print ' XX'.$amount.' '.$rounding;
7921
7922 // Now, $amount is a real PHP float number. We make a rounding if required.
7923 if ($rounding) {
7924 $nbofdectoround = '';
7925 if ($rounding == 'MU') {
7926 $nbofdectoround = getDolGlobalInt('MAIN_MAX_DECIMALS_UNIT'); // usually 5
7927 } elseif ($rounding == 'MT') {
7928 $nbofdectoround = getDolGlobalInt('MAIN_MAX_DECIMALS_TOT'); // usually 2 or 3
7929 } elseif ($rounding == 'MS') {
7930 $nbofdectoround = getDolGlobalInt('MAIN_MAX_DECIMALS_STOCK', 5);
7931 } elseif ($rounding == 'CU') {
7932 $nbofdectoround = getDolGlobalInt('MAIN_MAX_DECIMALS_CURRENCY_UNIT', getDolGlobalInt('MAIN_MAX_DECIMALS_UNIT')); // TODO Use param of currency
7933 } elseif ($rounding == 'CT') {
7934 $nbofdectoround = getDolGlobalInt('MAIN_MAX_DECIMALS_CURRENCY_TOT', getDolGlobalInt('MAIN_MAX_DECIMALS_TOT')); // TODO Use param of currency
7935 } elseif (is_numeric($rounding)) {
7936 $nbofdectoround = (int) $rounding;
7937 }
7938
7939 //print " RR".$amount.' - '.$nbofdectoround.'<br>';
7940 if (dol_strlen($nbofdectoround)) {
7941 $amount = round(is_string($amount) ? (float) $amount : $amount, $nbofdectoround); // $nbofdectoround can be 0.
7942 } else {
7943 return 'ErrorBadParameterProvidedToFunction';
7944 }
7945 //print ' SS'.$amount.' - '.$nbofdec.' - '.$dec.' - '.$thousand.' - '.$nbofdectoround.'<br>';
7946
7947 // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
7948 // to format defined by LC_NUMERIC after a calculation and we want source format to be defined by Dolibarr setup.
7949 if (is_numeric($amount)) {
7950 // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
7951 $temps = sprintf("%10.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
7952 $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
7953 $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
7954 $amount = number_format($amount, min($nbofdec, $nbofdectoround), $dec, $thousand); // Convert amount to format with dolibarr dec and thousand
7955 }
7956 //print "TT".$amount.'<br>';
7957
7958 // Always make replace because each math function (like round) replace
7959 // with local values and we want a number that has a SQL string format x.y
7960 if ($thousand != ',' && $thousand != '.') {
7961 $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
7962 }
7963
7964 $amount = str_replace(' ', '', $amount); // To avoid spaces
7965 $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
7966 $amount = str_replace($dec, '.', $amount);
7967
7968 $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
7969 }
7970
7971 return $amount;
7972}
7973
7986function showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round = -1, $forceunitoutput = 'no', $use_short_label = 0)
7987{
7988 require_once DOL_DOCUMENT_ROOT . '/core/lib/product.lib.php';
7989
7990 if (($forceunitoutput == 'no' && $dimension < 1 / 10000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -6)) {
7991 $dimension *= 1000000;
7992 $unit -= 6;
7993 } elseif (($forceunitoutput == 'no' && $dimension < 1 / 10 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -3)) {
7994 $dimension *= 1000;
7995 $unit -= 3;
7996 } elseif (($forceunitoutput == 'no' && $dimension > 100000000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 6)) {
7997 $dimension /= 1000000;
7998 $unit += 6;
7999 } elseif (($forceunitoutput == 'no' && $dimension > 100000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 3)) {
8000 $dimension /= 1000;
8001 $unit += 3;
8002 }
8003 // Special case when we want output unit into pound or ounce
8004 /* TODO
8005 if ($unit < 90 && $type == 'weight' && is_numeric($forceunitoutput) && (($forceunitoutput == 98) || ($forceunitoutput == 99))
8006 {
8007 $dimension = // convert dimension from standard unit into ounce or pound
8008 $unit = $forceunitoutput;
8009 }
8010 if ($unit > 90 && $type == 'weight' && is_numeric($forceunitoutput) && $forceunitoutput < 90)
8011 {
8012 $dimension = // convert dimension from standard unit into ounce or pound
8013 $unit = $forceunitoutput;
8014 }*/
8015
8016 $ret = price($dimension, 0, $outputlangs, 0, 0, $round);
8017 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
8018 $ret .= ' ' . measuringUnitString(0, $type, $unit, $use_short_label, $outputlangs);
8019
8020 return $ret;
8021}
8022
8023
8036function get_localtax($vatrate, $local, $thirdparty_buyer = null, $thirdparty_seller = null, $vatnpr = 0)
8037{
8038 global $db, $conf, $mysoc;
8039
8040 if (empty($thirdparty_seller) || !is_object($thirdparty_seller)) {
8041 $thirdparty_seller = $mysoc;
8042 }
8043
8044 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);
8045
8046 $vatratecleaned = $vatrate;
8047 $reg = array();
8048 if (preg_match('/^(.*)\s*\‍((.*)\‍)$/', (string) $vatrate, $reg)) { // If vat is "xx (yy)"
8049 $vatratecleaned = trim($reg[1]);
8050 $vatratecode = $reg[2];
8051 }
8052
8053 /*if ($thirdparty_buyer->country_code != $thirdparty_seller->country_code)
8054 {
8055 return 0;
8056 }*/
8057
8058 // Some test to guess with no need to make database access
8059 if ($mysoc->country_code == 'ES') { // For spain localtaxes 1 and 2, tax is qualified if buyer use local tax
8060 if ($local == 1) {
8061 if (!$mysoc->localtax1_assuj || (string) $vatratecleaned == "0") {
8062 return 0;
8063 }
8064 if ($thirdparty_seller->id == $mysoc->id) {
8065 if (!$thirdparty_buyer->localtax1_assuj) {
8066 return 0;
8067 }
8068 } else {
8069 if (!$thirdparty_seller->localtax1_assuj) {
8070 return 0;
8071 }
8072 }
8073 }
8074
8075 if ($local == 2) {
8076 //if (! $mysoc->localtax2_assuj || (string) $vatratecleaned == "0") return 0;
8077 if (!$mysoc->localtax2_assuj) {
8078 return 0; // If main vat is 0, IRPF may be different than 0.
8079 }
8080 if ($thirdparty_seller->id == $mysoc->id) {
8081 if (!$thirdparty_buyer->localtax2_assuj) {
8082 return 0;
8083 }
8084 } else {
8085 if (!$thirdparty_seller->localtax2_assuj) {
8086 return 0;
8087 }
8088 }
8089 }
8090 } else {
8091 if ($local == 1 && !$thirdparty_seller->localtax1_assuj) {
8092 return 0;
8093 }
8094 if ($local == 2 && !$thirdparty_seller->localtax2_assuj) {
8095 return 0;
8096 }
8097 }
8098
8099 // For some country MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY is forced to on.
8100 if (in_array($mysoc->country_code, array('ES'))) {
8101 $conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY = 1;
8102 }
8103
8104 // Search local taxes
8105 if (getDolGlobalString('MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY')) {
8106 if ($local == 1) {
8107 if ($thirdparty_seller != $mysoc) {
8108 if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
8109 return $thirdparty_seller->localtax1_value;
8110 }
8111 } else { // i am the seller
8112 if (!isOnlyOneLocalTax($local)) { // TODO If seller is me, why not always returning this, even if there is only one locatax vat.
8113 return getDolGlobalString('MAIN_INFO_VALUE_LOCALTAX1');
8114 }
8115 }
8116 }
8117 if ($local == 2) {
8118 if ($thirdparty_seller != $mysoc) {
8119 if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
8120 // TODO We should also return value defined on thirdparty only if defined
8121 return $thirdparty_seller->localtax2_value;
8122 }
8123 } else { // i am the seller
8124 if (in_array($mysoc->country_code, array('ES'))) {
8125 return $thirdparty_buyer->localtax2_value;
8126 } else {
8127 return getDolGlobalString('MAIN_INFO_VALUE_LOCALTAX2');
8128 }
8129 }
8130 }
8131 }
8132
8133 // By default, search value of local tax on line of common tax
8134 $sql = "SELECT t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
8135 $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t, " . MAIN_DB_PREFIX . "c_country as c";
8136 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '" . $db->escape($thirdparty_seller->country_code) . "'";
8137 $sql .= " AND t.taux = " . ((float) $vatratecleaned) . " AND t.active = 1";
8138 $sql .= " AND t.entity IN (" . getEntity('c_tva') . ")";
8139 if (!empty($vatratecode)) {
8140 $sql .= " AND t.code ='" . $db->escape($vatratecode) . "'"; // If we have the code, we use it in priority
8141 } else {
8142 $sql .= " AND t.recuperableonly = '" . $db->escape((string) $vatnpr) . "'";
8143 }
8144
8145 $resql = $db->query($sql);
8146
8147 if ($resql) {
8148 $obj = $db->fetch_object($resql);
8149 if ($obj) {
8150 if ($local == 1) {
8151 return $obj->localtax1;
8152 } elseif ($local == 2) {
8153 return $obj->localtax2;
8154 }
8155 }
8156 }
8157
8158 return 0;
8159}
8160
8161
8170function isOnlyOneLocalTax($local)
8171{
8172 $tax = get_localtax_by_third($local);
8173
8174 $valors = explode(":", $tax);
8175
8176 if (count($valors) > 1) {
8177 return false;
8178 } else {
8179 return true;
8180 }
8181}
8182
8189function get_localtax_by_third($local)
8190{
8191 global $db, $mysoc;
8192
8193 $sql = " SELECT t.localtax" . ((int) $local) . " as localtax";
8194 $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t INNER JOIN " . MAIN_DB_PREFIX . "c_country as c ON c.rowid = t.fk_pays";
8195 $sql .= " WHERE c.code = '" . $db->escape($mysoc->country_code) . "' AND t.active = 1 AND t.entity IN (" . getEntity('c_tva') . ") AND t.taux = (";
8196 $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";
8197 $sql .= " WHERE c.code = '" . $db->escape($mysoc->country_code) . "' AND t.entity IN (" . getEntity('c_tva') . ") AND tt.active = 1)";
8198 $sql .= " AND t.localtax" . ((int) $local) . "_type <> '0'";
8199 $sql .= " ORDER BY t.rowid DESC";
8200
8201 $resql = $db->query($sql);
8202 if ($resql) {
8203 $obj = $db->fetch_object($resql);
8204 if ($obj) {
8205 return $obj->localtax;
8206 } else {
8207 return '0';
8208 }
8209 }
8210
8211 return 'Error';
8212}
8213
8214
8226function getTaxesFromId($vatrate, $buyer = null, $seller = null, $firstparamisid = 1)
8227{
8228 global $db;
8229
8230 dol_syslog("getTaxesFromId vat id or rate = " . $vatrate);
8231
8232 // Search local taxes
8233 $sql = "SELECT t.rowid, t.code, t.taux as rate, t.recuperableonly as npr, t.accountancy_code_sell, t.accountancy_code_buy,";
8234 $sql .= " t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type";
8235 $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t";
8236 if ($firstparamisid) {
8237 $sql .= " WHERE t.rowid = " . (int) $vatrate;
8238 } else {
8239 $vatratecleaned = $vatrate;
8240 $vatratecode = '';
8241 $reg = array();
8242 if (preg_match('/^(.*)\s*\‍((.*)\‍)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
8243 $vatratecleaned = $reg[1];
8244 $vatratecode = $reg[2];
8245 }
8246
8247 $sql .= ", " . MAIN_DB_PREFIX . "c_country as c";
8248 /*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 ??
8249 else $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";*/
8250 $sql .= " WHERE t.fk_pays = c.rowid";
8251 if (getDolGlobalString('SERVICE_ARE_ECOMMERCE_200238EC')) {
8252 $sql .= " AND c.code = '" . $db->escape($buyer->country_code) . "'";
8253 } else {
8254 $sql .= " AND c.code = '" . $db->escape($seller->country_code) . "'";
8255 }
8256 $sql .= " AND t.taux = " . ((float) $vatratecleaned) . " AND t.active = 1";
8257 $sql .= " AND t.entity IN (" . getEntity('c_tva') . ")";
8258 if ($vatratecode) {
8259 $sql .= " AND t.code = '" . $db->escape($vatratecode) . "'";
8260 }
8261 }
8262
8263 $resql = $db->query($sql);
8264 if ($resql) {
8265 $obj = $db->fetch_object($resql);
8266 if ($obj) {
8267 return array(
8268 'rowid' => $obj->rowid,
8269 'code' => $obj->code,
8270 'rate' => $obj->rate,
8271 'localtax1' => $obj->localtax1,
8272 'localtax1_type' => $obj->localtax1_type,
8273 'localtax2' => $obj->localtax2,
8274 'localtax2_type' => $obj->localtax2_type,
8275 'npr' => $obj->npr,
8276 'accountancy_code_sell' => $obj->accountancy_code_sell,
8277 'accountancy_code_buy' => $obj->accountancy_code_buy
8278 );
8279 } else {
8280 return array();
8281 }
8282 } else {
8284 }
8285
8286 return array();
8287}
8288
8305function getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid = 0)
8306{
8307 global $db, $mysoc;
8308
8309 dol_syslog("getLocalTaxesFromRate vatrate=" . $vatrate . " local=" . $local);
8310
8311 // Search local taxes
8312 $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";
8313 $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t";
8314 if ($firstparamisid) {
8315 $sql .= " WHERE t.rowid = " . (int) $vatrate;
8316 } else {
8317 $vatratecleaned = $vatrate;
8318 $vatratecode = '';
8319 $reg = array();
8320 if (preg_match('/^(.*)\s*\‍((.*)\‍)$/', $vatrate, $reg)) { // If vat is "x.x (yy)"
8321 $vatratecleaned = $reg[1];
8322 $vatratecode = $reg[2];
8323 }
8324
8325 $sql .= ", " . MAIN_DB_PREFIX . "c_country as c";
8326 if (!empty($mysoc) && $mysoc->country_code == 'ES') {
8327 $countrycodetouse = ((empty($buyer) || empty($buyer->country_code)) ? $mysoc->country_code : $buyer->country_code);
8328 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '" . $db->escape($countrycodetouse) . "'"; // local tax in spain use the buyer country ??
8329 } else {
8330 $countrycodetouse = ((empty($seller) || empty($seller->country_code)) ? $mysoc->country_code : $seller->country_code);
8331 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '" . $db->escape($countrycodetouse) . "'";
8332 }
8333 $sql .= " AND t.taux = " . ((float) $vatratecleaned) . " AND t.active = 1";
8334 if ($vatratecode) {
8335 $sql .= " AND t.code = '" . $db->escape($vatratecode) . "'";
8336 }
8337 }
8338
8339 $resql = $db->query($sql);
8340 if ($resql) {
8341 $obj = $db->fetch_object($resql);
8342
8343 if ($obj) {
8344 $vateratestring = $obj->rate . ($obj->code ? ' (' . $obj->code . ')' : '');
8345
8346 if ($local == 1) {
8347 return array($obj->localtax1_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
8348 } elseif ($local == 2) {
8349 return array($obj->localtax2_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
8350 } else {
8351 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);
8352 }
8353 }
8354 }
8355
8356 return array();
8357}
8358
8369function get_product_vat_for_country($idprod, $thirdpartytouseforcountry, $idprodfournprice = 0)
8370{
8371 global $db, $mysoc;
8372
8373 require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
8374
8375 $ret = 0;
8376 $found = 0;
8377
8378 if ($idprod > 0) {
8379 // Load product
8380 $product = new Product($db);
8381 $product->fetch($idprod);
8382
8383 if (($mysoc->country_code == $thirdpartytouseforcountry->country_code)
8384 || (in_array($mysoc->country_code, array('FR', 'MC')) && in_array($thirdpartytouseforcountry->country_code, array('FR', 'MC')))
8385 || (in_array($mysoc->country_code, array('MQ', 'GP')) && in_array($thirdpartytouseforcountry->country_code, array('MQ', 'GP')))
8386 ) {
8387 // If country of thirdparty to consider is ours
8388 if ($idprodfournprice > 0) { // We want vat for product for a "supplier" object
8389 $result = $product->get_buyprice($idprodfournprice, 0, 0, '');
8390 if ($result > 0) {
8391 $ret = $product->vatrate_supplier;
8392 if ($product->default_vat_code_supplier) {
8393 $ret .= ' (' . $product->default_vat_code_supplier . ')';
8394 }
8395 $found = 1;
8396 }
8397 }
8398 if (!$found) {
8399 $ret = $product->tva_tx; // Default sales vat of product
8400 if ($product->default_vat_code) {
8401 $ret .= ' (' . $product->default_vat_code . ')';
8402 }
8403 $found = 1;
8404 }
8405 } else {
8406 // TODO Read default product vat according to product and an other countrycode.
8407 // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
8408 }
8409 }
8410
8411 if (!$found) {
8412 if (!getDolGlobalString('MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS')) {
8413 // 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).
8414 $sql = "SELECT t.taux as vat_rate, t.code as default_vat_code";
8415 $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t, " . MAIN_DB_PREFIX . "c_country as c";
8416 $sql .= " WHERE t.active = 1 AND t.fk_pays = c.rowid AND c.code = '" . $db->escape($thirdpartytouseforcountry->country_code) . "'";
8417 $sql .= " AND t.entity IN (" . getEntity('c_tva') . ")";
8418 $sql .= " ORDER BY t.use_default DESC, t.taux DESC, t.code ASC, t.recuperableonly ASC";
8419 $sql .= $db->plimit(1);
8420
8421 $resql = $db->query($sql);
8422 if ($resql) {
8423 $obj = $db->fetch_object($resql);
8424 if ($obj) {
8425 $ret = $obj->vat_rate;
8426 if ($obj->default_vat_code) {
8427 $ret .= ' (' . $obj->default_vat_code . ')';
8428 }
8429 }
8430 $db->free($resql);
8431 } else {
8433 }
8434 } else {
8435 // Forced value if autodetect fails. MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS can be
8436 // '1.23'
8437 // or '1.23 (CODE)'
8438 $defaulttx = '';
8439 if (getDolGlobalString('MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS') != 'none') {
8440 $defaulttx = getDolGlobalString('MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS');
8441 }
8442 /*if (preg_match('/\‍((.*)\‍)/', $defaulttx, $reg)) {
8443 $defaultcode = $reg[1];
8444 $defaulttx = preg_replace('/\s*\‍(.*\‍)/', '', $defaulttx);
8445 }*/
8446
8447 $ret = $defaulttx;
8448 }
8449 }
8450
8451 dol_syslog("get_product_vat_for_country: ret=" . $ret);
8452
8453 return $ret;
8454}
8455
8465function get_product_localtax_for_country($idprod, $local, $thirdpartytouseforcountry)
8466{
8467 global $db, $mysoc;
8468
8469 if (!class_exists('Product')) {
8470 require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
8471 }
8472
8473 $ret = 0;
8474 $found = 0;
8475
8476 if ($idprod > 0) {
8477 // Load product
8478 $product = new Product($db);
8479 $result = $product->fetch($idprod);
8480
8481 if ($mysoc->country_code == $thirdpartytouseforcountry->country_code) { // If selling country is ours
8482 /* Not defined yet, so we don't use this
8483 if ($local==1) $ret=$product->localtax1_tx;
8484 elseif ($local==2) $ret=$product->localtax2_tx;
8485 $found=1;
8486 */
8487 } else {
8488 // TODO Read default product vat according to product and another countrycode.
8489 // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
8490 }
8491 }
8492
8493 if (!$found) {
8494 // If vat of product for the country not found or not defined, we return higher vat of country.
8495 $sql = "SELECT taux as vat_rate, localtax1, localtax2";
8496 $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t, " . MAIN_DB_PREFIX . "c_country as c";
8497 $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='" . $db->escape($thirdpartytouseforcountry->country_code) . "'";
8498 $sql .= " AND t.entity IN (" . getEntity('c_tva') . ")";
8499 $sql .= " ORDER BY t.taux DESC, t.recuperableonly ASC";
8500 $sql .= $db->plimit(1);
8501
8502 $resql = $db->query($sql);
8503 if ($resql) {
8504 $obj = $db->fetch_object($resql);
8505 if ($obj) {
8506 if ($local == 1) {
8507 $ret = $obj->localtax1;
8508 } elseif ($local == 2) {
8509 $ret = $obj->localtax2;
8510 }
8511 }
8512 } else {
8514 }
8515 }
8516
8517 dol_syslog("get_product_localtax_for_country: ret=" . $ret);
8518 return $ret;
8519}
8520
8539function get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
8540{
8541 global $mysoc, $db, $hookmanager;
8542
8543 require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
8544
8545 // Note: possible values for tva_assuj are 0/1 or franchise/reel
8546 $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;
8547
8548 if (empty($thirdparty_seller->country_code)) {
8549 $thirdparty_seller->country_code = $mysoc->country_code;
8550 }
8551 $seller_country_code = $thirdparty_seller->country_code;
8552 $seller_in_cee = isInEEC($thirdparty_seller);
8553
8554 if (empty($thirdparty_buyer->country_code)) {
8555 $thirdparty_buyer->country_code = $mysoc->country_code;
8556 }
8557 $buyer_country_code = $thirdparty_buyer->country_code;
8558 $buyer_in_cee = isInEEC($thirdparty_buyer);
8559
8560 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'));
8561
8562 $vatvalue = 0;
8563 $vatrule = '';
8564
8565 // 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)
8566 // we use the buyer VAT.
8567 if (getDolGlobalString('SERVICE_ARE_ECOMMERCE_200238EC')) {
8568 if ($seller_in_cee && $buyer_in_cee) {
8569 $isacompany = $thirdparty_buyer->isACompany();
8570 if ($isacompany && !getDolGlobalString('MAIN_USE_VAT_ZERO_FOR_COMPANIES_IN_EEC_EVEN_IF_VAT_ID_UNKNOWN')) {
8571 require_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php';
8572 if (!isValidVATID($thirdparty_buyer)) {
8573 $isacompany = 0;
8574 }
8575 }
8576
8577 if (!$isacompany) {
8578 $vatvalue = get_product_vat_for_country($idprod, $thirdparty_buyer, $idprodfournprice);
8579 $vatrule = 'VATRULE 0';
8580 }
8581 }
8582 }
8583
8584 // If seller does not use VAT, default VAT is 0. End of rule.
8585 if (empty($vatrule) && !$seller_use_vat) {
8586 //print 'VATRULE 1';
8587 // TODO get the VAT Code of exemption asked into setup if country isInEEC (from an array list of possible
8588 // values like VATEX-EU-132-*, VATEX-FR-FRANCHISE, VATEX-EU-AE...
8589 // When we had recorded it, we also added a corresponding entry into table of vat code if it does not exists yet.
8590 // Here we test if entry for the VAT exemption code exists in llx_vat, we can return '0 (VATEX-EU-132-xx)'
8591 // If not, we add it and we return '0 (VATEX-EU-132-xx)'
8592 $vatvalue = 0;
8593 $vatrule = 'VATRULE 1';
8594 }
8595
8596 // 'VATRULE 2' - Force VAT if a buyer department is defined on vat rates dictionary
8597 if (empty($vatrule) && !empty($thirdparty_buyer->state_id)) {
8598 $sql = "SELECT d.rowid, t.taux as vat_default_rate, t.code as vat_default_code ";
8599 $sql .= " FROM " . $db->prefix() . "c_tva as t";
8600 $sql .= " INNER JOIN " . $db->prefix() . "c_departements as d ON t.fk_department_buyer = d.rowid";
8601 $sql .= " WHERE d.rowid = " . ((int) $thirdparty_buyer->state_id);
8602 $sql .= " AND t.active > 0";
8603 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
8604 $sql .= " ORDER BY t.use_default DESC, t.taux DESC, t.code ASC, t.recuperableonly ASC";
8605
8606 $res = $db->query($sql);
8607 if ($res) {
8608 if ($db->num_rows($res)) {
8609 $obj = $db->fetch_object($res);
8610
8611 $vatvalue = $obj->vat_default_rate . ' (' . $obj->vat_default_code . ')';
8612 $vatrule = 'VATRULE 2';
8613 }
8614 $db->free($res);
8615 }
8616 }
8617
8618 // If the (seller country = buyer country) then the default VAT = VAT of the product sold. End of rule.
8619 if (empty($vatrule) && (
8620 ($seller_country_code == $buyer_country_code)
8621 || (in_array($seller_country_code, array('FR', 'MC')) && in_array($buyer_country_code, array('FR', 'MC')))
8622 || (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.
8623 )) { // Warning ->country_code not always defined
8624 //print 'VATRULE 3';
8625 $tmpvat = get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
8626
8627 if ($seller_country_code == 'IN' && getDolGlobalString('MAIN_SALETAX_AUTOSWITCH_I_CS_FOR_INDIA')) {
8628 // Special case for india.
8629 //print 'VATRULE 3b';
8630 $reg = array();
8631 if (preg_match('/\‍(C\+S-(\d+(?:\.\d+)?)\‍)/', $tmpvat, $reg) && $thirdparty_seller->state_id != $thirdparty_buyer->state_id) {
8632 // we must revert the C+S into I (rate of I-xx is xx)
8633 $tmpvat = $reg[1].' (I-'.$reg[1].')';
8634 } elseif (preg_match('/\‍(I-(\d+(?:\.\d+)?)\‍)/', $tmpvat, $reg) && $thirdparty_seller->state_id == $thirdparty_buyer->state_id) {
8635 // we must revert the I into C+S (rate of C+S-xx is 0, xx is shared between localtax1 and localtax2)
8636 $tmpvat = '0 (C+S-'.$reg[1].')';
8637 }
8638 }
8639
8640 $vatvalue = $tmpvat;
8641 $vatrule = 'VATRULE 3b';
8642 }
8643
8644 // 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.
8645 // 'VATRULE 4' - Not supported
8646
8647 // If (seller and buyer in the European Community) and (buyer = individual) then VAT by default = VAT of the product sold. End of rule
8648 // If (seller and buyer in European Community) and (buyer = company) then VAT by default=0. End of rule
8649 if (empty($vatrule) && ($seller_in_cee && $buyer_in_cee)) {
8650 $isacompany = $thirdparty_buyer->isACompany();
8651 if ($isacompany && !getDolGlobalString('MAIN_USE_VAT_ZERO_FOR_COMPANIES_IN_EEC_EVEN_IF_VAT_ID_UNKNOWN')) {
8652 require_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php';
8653 if (!isValidVATID($thirdparty_buyer)) {
8654 $isacompany = 0;
8655 }
8656 }
8657
8658 if (!$isacompany) {
8659 //print 'VATRULE 5';
8660 $vatvalue = get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
8661 $vatrule = 'VATRULE 5';
8662 } else {
8663 //print 'VATRULE 6';
8664 // TODO This is the case of VAT exemption 'VATEX-EU-IC'
8665 // If entry for the VAT exemption code exists in llx_vat, we can return '0 (VATEX-EU-IC)'
8666 // If not, we add it and we return '0 (VATEX-EU-IC)'
8667 $vatvalue = 0;
8668 $vatrule = 'VATRULE 6';
8669 }
8670 }
8671
8672 // 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
8673 // 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
8674 if (empty($vatrule) && getDolGlobalString('MAIN_USE_VAT_OF_PRODUCT_FOR_INDIVIDUAL_CUSTOMER_OUT_OF_EEC') && empty($buyer_in_cee)) {
8675 $isacompany = $thirdparty_buyer->isACompany();
8676 if (!$isacompany) {
8677 $vatvalue = get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
8678 $vatrule = 'VATRULE extra';
8679 //print 'VATRULE extra';
8680 }
8681 }
8682
8683 // Otherwise the VAT proposed by default=0. End of rule.
8684 // Rem: This means that at least one of the 2 is outside the European Community and the country differs
8685 //print 'VATRULE 7';
8686 // TODO This is the case of VAT exemption 'VATEX-EU-G'
8687 // If entry for the VAT exemption code exists in llx_vat, we can return '0 (VATEX-xxx)'
8688 // If not, we add it and we return '0 (VATEX-xxx)'
8689
8690 // Allow an external module to bypass the calculation of prices
8691 $parameters = array('vatvalue' => $vatvalue, 'vatrule' => $vatrule);
8692 $tmpobject = null;
8693 $tmpaction = '';
8694 // @phan-suppress-next-line PhanPluginConstantVariableNull
8695 $reshook = $hookmanager->executeHooks('get_default_tva', $parameters, $tmpobject, $tmpaction); // @phan-suppress-current-line PhanPluginConstantVariableNull
8696 if ($reshook > 0 && !empty($hookmanager->resArray['vatvalue'])) {
8697 $vatvalue = $hookmanager->resArray['vatvalue'];
8698 $vatrule = $hookmanager->resArray['vatrule']; // For information
8699 }
8700
8701 return $vatvalue;
8702}
8703
8704
8715function get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
8716{
8717 global $db;
8718
8719 if ($idprodfournprice > 0) {
8720 if (!class_exists('ProductFournisseur')) {
8721 require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.product.class.php';
8722 }
8723 $prodprice = new ProductFournisseur($db);
8724 $prodprice->fetch_product_fournisseur_price($idprodfournprice);
8725 return $prodprice->fourn_tva_npr;
8726 } elseif ($idprod > 0) {
8727 if (!class_exists('Product')) {
8728 require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
8729 }
8730 $prod = new Product($db);
8731 $prod->fetch($idprod);
8732 return $prod->tva_npr;
8733 }
8734
8735 return 0;
8736}
8737
8751function get_default_localtax($thirdparty_seller, $thirdparty_buyer, $local, $idprod = 0)
8752{
8753 global $mysoc;
8754
8755 if (!is_object($thirdparty_seller)) {
8756 return -1;
8757 }
8758 if (!is_object($thirdparty_buyer)) {
8759 return -1;
8760 }
8761
8762 if (empty($thirdparty_seller->country_code)) {
8763 $thirdparty_seller->country_code = $mysoc->country_code;
8764 }
8765 $seller_country_code = $thirdparty_seller->country_code;
8766 //$seller_in_cee = isInEEC($thirdparty_seller);
8767
8768 if (empty($thirdparty_buyer->country_code)) {
8769 $thirdparty_buyer->country_code = $mysoc->country_code;
8770 }
8771 $buyer_country_code = $thirdparty_buyer->country_code;
8772 //$buyer_in_cee = isInEEC($thirdparty_buyer);
8773
8774 if ($local == 1) { // Localtax 1
8775 if ($mysoc->country_code == 'ES') {
8776 if (is_numeric($thirdparty_buyer->localtax1_assuj) && !$thirdparty_buyer->localtax1_assuj) {
8777 return 0;
8778 }
8779 } else {
8780 // Si vendeur non assujeti a Localtax1, localtax1 par default=0
8781 if (is_numeric($thirdparty_seller->localtax1_assuj) && !$thirdparty_seller->localtax1_assuj) {
8782 return 0;
8783 }
8784 if (!is_numeric($thirdparty_seller->localtax1_assuj) && $thirdparty_seller->localtax1_assuj == 'localtax1off') {
8785 return 0;
8786 }
8787 }
8788 } elseif ($local == 2) { //I Localtax 2
8789 // Si vendeur non assujeti a Localtax2, localtax2 par default=0
8790 if (is_numeric($thirdparty_seller->localtax2_assuj) && !$thirdparty_seller->localtax2_assuj) {
8791 return 0;
8792 }
8793 if (!is_numeric($thirdparty_seller->localtax2_assuj) && $thirdparty_seller->localtax2_assuj == 'localtax2off') {
8794 return 0;
8795 }
8796 }
8797
8798 if ($seller_country_code == $buyer_country_code) {
8799 return get_product_localtax_for_country($idprod, $local, $thirdparty_seller);
8800 }
8801
8802 return 0;
8803}
8804
8813function yn($yesno, $format = 1, $color = 0)
8814{
8815 global $langs;
8816
8817 $result = 'unknown';
8818 $classname = '';
8819 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'
8820 $result = $langs->trans('yes');
8821 if ($format == 1 || $format == 3) {
8822 $result = $langs->trans("Yes");
8823 }
8824 if ($format == 2) {
8825 $result = '<input type="checkbox" value="1" checked disabled>';
8826 }
8827 if ($format == 3) {
8828 $result = '<input type="checkbox" value="1" checked disabled> ' . $result;
8829 }
8830 if ($format == 4 || !is_numeric($format)) {
8831 $result = img_picto(is_numeric($format) ? '' : $format, 'check');
8832 }
8833
8834 $classname = 'ok';
8835 } else {
8836 $result = $langs->trans("no");
8837 if ($format == 1 || $format == 3) {
8838 $result = $langs->trans("No");
8839 }
8840 if ($format == 2) {
8841 $result = '<input type="checkbox" value="0" disabled>';
8842 }
8843 if ($format == 3) {
8844 $result = '<input type="checkbox" value="0" disabled> ' . $result;
8845 }
8846 if ($format == 4 || !is_numeric($format)) {
8847 $result = img_picto(is_numeric($format) ? '' : $format, 'uncheck');
8848 }
8849
8850 if ($color == 2) {
8851 $classname = 'ok';
8852 } else {
8853 $classname = 'error';
8854 }
8855 }
8856 if ($color) {
8857 return '<span class="' . $classname . '">' . $result . '</span>';
8858 }
8859 return $result;
8860}
8861
8880function get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart = '')
8881{
8882 if (empty($modulepart) && is_object($object)) {
8883 if (!empty($object->module)) {
8884 $modulepart = $object->module;
8885 } elseif (!empty($object->element)) {
8886 $modulepart = $object->element;
8887 }
8888 }
8889
8890 $path = '';
8891
8892 // Define $arrayforoldpath that is module path using a hierarchy on more than 1 level.
8893 $arrayforoldpath = array('cheque' => 2, 'category' => 2, 'supplier_invoice' => 2, 'invoice_supplier' => 2, 'mailing' => 2, 'supplier_payment' => 2);
8894 if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
8895 $arrayforoldpath['product'] = 2;
8896 }
8897
8898 if (empty($level) && array_key_exists($modulepart, $arrayforoldpath)) {
8899 $level = $arrayforoldpath[$modulepart];
8900 }
8901 if (!empty($level) && array_key_exists($modulepart, $arrayforoldpath)) {
8902 // This part should be removed once all code is using "get_exdir" to forge path, with parameter $object and $modulepart provided.
8903 if (empty($num) && is_object($object)) {
8904 $num = ((int) $object->id);
8905 }
8906 if (empty($alpha)) {
8907 $num = preg_replace('/([^0-9])/i', '', $num);
8908 } else {
8909 $num = preg_replace('/^.*\-/i', '', $num);
8910 }
8911 $num = substr("000" . $num, -$level);
8912 if ($level == 1) {
8913 $path = substr($num, 0, 1);
8914 }
8915 if ($level == 2) {
8916 $path = substr($num, 1, 1) . '/' . substr($num, 0, 1);
8917 }
8918 if ($level == 3) {
8919 $path = substr($num, 2, 1) . '/' . substr($num, 1, 1) . '/' . substr($num, 0, 1);
8920 }
8921 } else {
8922 // We will enhance here a common way of forging path for document storage.
8923 // In a future, we may distribute directories on several levels depending on setup and object.
8924 // Here, $object->id, $object->ref and $modulepart are required.
8925 if (in_array($modulepart, array('societe', 'thirdparty')) && $object instanceof Societe) {
8926 // 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
8927 $path = dol_sanitizeFileName((string) $object->id);
8928 } else {
8929 $path = dol_sanitizeFileName(empty($object->ref) ? (string) ((is_object($object) && property_exists($object, 'id')) ? ((int) $object->id) : '') : $object->ref);
8930 }
8931 }
8932
8933 if (empty($withoutslash) && !empty($path)) {
8934 $path .= '/';
8935 }
8936
8937 return $path;
8938}
8939
8948function dol_mkdir($dir, $dataroot = '', $newmask = '')
8949{
8950 dol_syslog("functions.lib::dol_mkdir: dir=" . $dir, LOG_INFO);
8951
8952 $dir = dol_sanitizePathName($dir, '_', 0);
8953
8954 $dir_osencoded = dol_osencode($dir);
8955 if (@is_dir($dir_osencoded)) {
8956 return 0;
8957 }
8958
8959 $nberr = 0;
8960 $nbcreated = 0;
8961
8962 $ccdir = '';
8963 if (!empty($dataroot)) {
8964 // Remove data root from loop
8965 $dir = str_replace($dataroot . '/', '', $dir);
8966 $ccdir = $dataroot . '/';
8967 }
8968
8969 $cdir = explode("/", $dir);
8970 $num = count($cdir);
8971 for ($i = 0; $i < $num; $i++) {
8972 if ($i > 0) {
8973 $ccdir .= '/' . $cdir[$i];
8974 } else {
8975 $ccdir .= $cdir[$i];
8976 }
8977 $regs = array();
8978 if (preg_match("/^.:$/", $ccdir, $regs)) {
8979 continue; // If the Windows path is incomplete, continue with next directory
8980 }
8981
8982 // Attention, is_dir() can fail event if the directory exists
8983 // (i.e. according the open_basedir configuration)
8984 if ($ccdir) {
8985 $ccdir_osencoded = dol_osencode($ccdir);
8986 if (!@is_dir($ccdir_osencoded)) {
8987 dol_syslog("functions.lib::dol_mkdir: Directory '" . $ccdir . "' is not found (does not exists or is outside open_basedir PHP setting).", LOG_DEBUG);
8988
8989 umask(0);
8990 $dirmaskdec = octdec((string) $newmask);
8991 if (empty($newmask)) {
8992 $dirmaskdec = octdec(getDolGlobalString('MAIN_UMASK', '0755'));
8993 }
8994 $dirmaskdec |= octdec('0111'); // Set x bit required for directories
8995 if (!@mkdir($ccdir_osencoded, $dirmaskdec)) {
8996 // If the is_dir has returned a false information, we arrive here
8997 dol_syslog("functions.lib::dol_mkdir: Fails to create directory '" . $ccdir . "' (no permission to write into parent or directory already exists).", LOG_WARNING);
8998 $nberr++;
8999 } else {
9000 dol_syslog("functions.lib::dol_mkdir: Directory '" . $ccdir . "' created", LOG_DEBUG);
9001 $nberr = 0; // At this point in the code, the previous failures can be ignored -> set $nberr to 0
9002 $nbcreated++;
9003 }
9004 } else {
9005 $nberr = 0; // At this point in the code, the previous failures can be ignored -> set $nberr to 0
9006 }
9007 }
9008 }
9009 return ($nberr ? -$nberr : $nbcreated);
9010}
9011
9012
9020function dolChmod($filepath, $newmask = '')
9021{
9022 if (!empty($newmask)) {
9023 @chmod($filepath, octdec($newmask));
9024 } elseif (getDolGlobalString('MAIN_UMASK')) {
9025 @chmod($filepath, octdec(getDolGlobalString('MAIN_UMASK')));
9026 }
9027}
9028
9029
9035function picto_required()
9036{
9037 return '<span class="fieldrequired">*</span>';
9038}
9039
9040
9057function dol_string_nohtmltag($stringtoclean, $removelinefeed = 1, $pagecodeto = 'UTF-8', $strip_tags = 0, $removedoublespaces = 1)
9058{
9059 if (is_null($stringtoclean)) {
9060 return '';
9061 }
9062
9063 if ($removelinefeed == 2) {
9064 $stringtoclean = preg_replace('/<br[^>]*>(\n|\r)+/ims', '<br>', $stringtoclean);
9065 }
9066 $temp = preg_replace('/<br[^>]*>/i', "\n", $stringtoclean);
9067
9068 // 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)
9069 $temp = dol_html_entity_decode($temp, ENT_COMPAT | ENT_HTML5, $pagecodeto);
9070
9071 $temp = str_replace('< ', '__ltspace__', $temp);
9072 $temp = str_replace('<:', '__lttwopoints__', $temp);
9073
9074 if ($strip_tags) {
9075 $temp = strip_tags($temp);
9076 } else {
9077 // 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).
9078 $pattern = "/<[^<>]+>/";
9079 // Example of $temp: <a href="/myurl" title="<u>A title</u>">0000-021</a>
9080 // pass 1 - $temp after pass 1: <a href="/myurl" title="A title">0000-021
9081 // pass 2 - $temp after pass 2: 0000-021
9082 $tempbis = $temp;
9083 do {
9084 $temp = $tempbis;
9085 $tempbis = str_replace('<>', '', $temp); // No reason to have this into a text, except if value is to try bypass the next html cleaning
9086 $tempbis = preg_replace($pattern, '', $tempbis);
9087 //$idowhile++; print $temp.'-'.$tempbis."\n"; if ($idowhile > 100) break;
9088 } while ($tempbis != $temp);
9089
9090 $temp = $tempbis;
9091
9092 // 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).
9093 $temp = preg_replace('/<+([a-z]+)/i', '\1', $temp);
9094 }
9095
9096 $temp = dol_html_entity_decode($temp, ENT_COMPAT, $pagecodeto);
9097
9098 // Remove also carriage returns
9099 if ($removelinefeed == 1) {
9100 $temp = str_replace(array("\r\n", "\r", "\n"), " ", $temp);
9101 }
9102
9103 // And double spaces
9104 if ($removedoublespaces) {
9105 while (strpos($temp, " ") !== false) {
9106 $temp = str_replace(" ", " ", $temp);
9107 }
9108 }
9109
9110 $temp = str_replace('__ltspace__', '< ', $temp);
9111 $temp = str_replace('__lttwopoints__', '<:', $temp);
9112
9113 return trim($temp);
9114}
9115
9135function dol_string_onlythesehtmltags($stringtoclean, $cleanalsosomestyles = 1, $removeclassattribute = 1, $cleanalsojavascript = 0, $allowiframe = 0, $allowed_tags = array(), $allowlink = 0, $allowscript = 0, $allowstyle = 0, $allowphp = 0)
9136{
9137 $sav_allowed_tags = $allowed_tags;
9138
9139 if (empty($allowed_tags) || (is_string($allowed_tags) && preg_match('/^common/', $allowed_tags))) {
9140 $allowed_tags = array(
9141 // HTML 4
9142 "html",
9143 "head",
9144 "body",
9145 "article",
9146 "a",
9147 "abbr",
9148 "b",
9149 "blockquote",
9150 "br",
9151 "cite",
9152 "div",
9153 "dl",
9154 "dd",
9155 "dt",
9156 "em",
9157 "font",
9158 "img",
9159 "ins",
9160 "hr",
9161 "i",
9162 "li",
9163 "ol",
9164 "p",
9165 "q",
9166 "s",
9167 "span",
9168 "strike",
9169 "strong",
9170 "title",
9171 "table",
9172 "tbody",
9173 "thead",
9174 "tfoot",
9175 "tr",
9176 "th",
9177 "td",
9178 "u",
9179 "ul",
9180 "sup",
9181 "sub",
9182 "blockquote",
9183 "pre",
9184 "h1",
9185 "h2",
9186 "h3",
9187 "h4",
9188 "h5",
9189 "h6",
9190
9191 // HTML 5
9192 "footer",
9193 "header",
9194 "menu",
9195 "menuitem",
9196 "nav",
9197 "section"
9198 );
9199 }
9200 $allowed_tags[] = "comment"; // this tags is added to manage comment <!--...--> that are replaced into <comment>...</comment>
9201 if ($allowiframe) {
9202 if (!in_array('iframe', $allowed_tags)) {
9203 $allowed_tags[] = "iframe";
9204 }
9205 }
9206 if ($allowlink) {
9207 if (!in_array('link', $allowed_tags)) {
9208 $allowed_tags[] = "link";
9209 }
9210 if (!in_array('meta', $allowed_tags)) {
9211 $allowed_tags[] = "meta";
9212 }
9213 }
9214 if ($allowscript) {
9215 if (!in_array('script', $allowed_tags)) {
9216 $allowed_tags[] = "script";
9217 }
9218 }
9219 if ($allowstyle) {
9220 if (!in_array('style', $allowed_tags)) {
9221 $allowed_tags[] = "style";
9222 }
9223 }
9224 if (is_string($sav_allowed_tags)) {
9225 $tmptags = explode(',', $sav_allowed_tags);
9226 foreach ($tmptags as $tag) {
9227 if ($tag != 'common') {
9228 $allowed_tags[] = $tag;
9229 }
9230 }
9231 }
9232
9233
9234 $allowed_tags_string = implode("><", $allowed_tags);
9235 $allowed_tags_string = '<' . $allowed_tags_string . '>';
9236
9237 $stringtoclean = str_replace('<!DOCTYPE html>', '__!DOCTYPE_HTML__', $stringtoclean); // Replace DOCTYPE to avoid to have it removed by the strip_tags
9238
9239 $stringtoclean = dol_string_nounprintableascii($stringtoclean, 0);
9240
9241 //$stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
9242 $stringtoclean = preg_replace('/<!--([^>]*)-->/', '<comment>\1</comment>', $stringtoclean);
9243
9244 if ($allowphp) {
9245 $allowed_tags[] = "commentphp";
9246 $stringtoclean = preg_replace('/^<\?php([^"]+)\?>$/i', '<commentphp>\1__</commentphp>', $stringtoclean); // Note: <?php ... > is allowed only if on the same line
9247 $stringtoclean = preg_replace('/"<\?php([^"]+)\?>"/i', '"<commentphp>\1</commentphp>"', $stringtoclean); // Note: "<?php ... >" is allowed only if on the same line
9248 }
9249
9250 $stringtoclean = preg_replace('/&colon;/i', ':', $stringtoclean);
9251 $stringtoclean = preg_replace('/&#58;|&#0+58|&#x3A/i', '', $stringtoclean); // refused string ':' encoded (no reason to have a : encoded like this) to disable 'javascript:...'
9252
9253 // Remove all HTML tags
9254 $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
9255
9256 if ($cleanalsosomestyles) { // Clean for remaining html tags
9257 //$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
9258 $temp = preg_replace('/position\s*:\s*(absolute|fixed)/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
9259 $temp = preg_replace('/z-index\s*:/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
9260 }
9261 if ($removeclassattribute) { // Clean for remaining html tags
9262 $temp = preg_replace('/(<[^>]+)\s+class=((["\']).*?\\3|\\w*)/i', '\\1', $temp);
9263 }
9264
9265 // Remove 'javascript:' that we should not find into a text
9266 // 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)).
9267 if ($cleanalsojavascript) {
9268 $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);
9269 }
9270
9271 $temp = str_replace('__!DOCTYPE_HTML__', '<!DOCTYPE html>', $temp); // Restore the DOCTYPE
9272
9273 if ($allowphp) {
9274 $temp = preg_replace('/<commentphp>(.*)<\/commentphp>/', '<?php\1?>', $temp); // Restore php code
9275 }
9276
9277 $temp = preg_replace('/<comment>([^>]*)<\/comment>/', '<!--\1-->', $temp); // Restore html comments
9278
9279
9280 return $temp;
9281}
9282
9283
9296function dol_string_onlythesehtmlattributes($stringtoclean, $allowed_attributes = null)
9297{
9298 if (is_null($allowed_attributes)) {
9299 $allowed_attributes = array(
9300 // HTML 4
9301 "allow",
9302 "allowfullscreen",
9303 "alt",
9304 "async",
9305 "class",
9306 "contenteditable",
9307 "crossorigin",
9308 "data-html",
9309 "frameborder",
9310 "height",
9311 "href",
9312 "id",
9313 "name",
9314 "property",
9315 "rel",
9316 "src",
9317 "style",
9318 "target",
9319 "title",
9320 "type",
9321 "width",
9322
9323 // HTML5
9324 "footer",
9325 "header",
9326 "menu",
9327 "menuitem",
9328 "nav",
9329 "section"
9330 );
9331 }
9332 // Always add content and http-equiv for meta tags, required to force encoding and keep html content in utf8 by load/saveHTML functions.
9333 if (!in_array("content", $allowed_attributes)) {
9334 $allowed_attributes[] = "content";
9335 }
9336 if (!in_array("http-equiv", $allowed_attributes)) {
9337 $allowed_attributes[] = "http-equiv";
9338 }
9339
9340 if (class_exists('DOMDocument') && !empty($stringtoclean)) {
9341 //$stringtoclean = '<?xml encoding="UTF-8"><html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"></head><body>'.$stringtoclean.'</body></html>';
9342 $stringtoclean = '<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"></head><body>' . $stringtoclean . '</body></html>';
9343
9344 // Warning: loadHTML does not support HTML5 on old libxml versions.
9345 $dom = new DOMDocument('', 'UTF-8');
9346 // If $stringtoclean is wrong, it will generates warnings. So we disable warnings and restore them later.
9347 $savwarning = error_reporting();
9348 error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE);
9349 $dom->loadHTML($stringtoclean, LIBXML_ERR_NONE | LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD | LIBXML_NONET | LIBXML_NOWARNING | LIBXML_NOXMLDECL);
9350 error_reporting($savwarning);
9351
9352 if ($dom instanceof DOMDocument) {
9353 for ($els = $dom->getElementsByTagname('*'), $i = $els->length - 1; $i >= 0; $i--) {
9354 $el = $els->item($i);
9355 if (!$el instanceof DOMElement) {
9356 continue;
9357 }
9358 $attrs = $el->attributes;
9359 for ($ii = $attrs->length - 1; $ii >= 0; $ii--) {
9360 //var_dump($attrs->item($ii));
9361 if (!empty($attrs->item($ii)->name)) {
9362 if (! in_array($attrs->item($ii)->name, $allowed_attributes)) {
9363 // Delete attribute if not into allowed_attributes @phan-suppress-next-line PhanUndeclaredMethod
9364 $els->item($i)->removeAttribute($attrs->item($ii)->name);
9365 } elseif (in_array($attrs->item($ii)->name, array('style'))) {
9366 // If attribute is 'style'
9367 $valuetoclean = $attrs->item($ii)->value;
9368
9369 if (isset($valuetoclean)) {
9370 do {
9371 $oldvaluetoclean = $valuetoclean;
9372 $valuetoclean = preg_replace('/\/\*.*\*\//m', '', $valuetoclean); // clean css comments
9373 $valuetoclean = preg_replace('/position\s*:\s*[a-z]+/mi', '', $valuetoclean);
9374 if ($els->item($i)->tagName == 'a') { // more paranoiac cleaning for clickable tags.
9375 $valuetoclean = preg_replace('/display\s*:/mi', '', $valuetoclean);
9376 $valuetoclean = preg_replace('/z-index\s*:/mi', '', $valuetoclean);
9377 $valuetoclean = preg_replace('/\s+(top|left|right|bottom)\s*:/mi', '', $valuetoclean);
9378 }
9379
9380 // We do not allow logout|passwordforgotten.php and action= into the content of a "style" tag
9381 $valuetoclean = preg_replace('/(logout|passwordforgotten)\.php/mi', '', $valuetoclean);
9382 $valuetoclean = preg_replace('/action=/mi', '', $valuetoclean);
9383 } while ($oldvaluetoclean != $valuetoclean);
9384 }
9385
9386 $attrs->item($ii)->value = $valuetoclean;
9387 }
9388 }
9389 }
9390 }
9391 }
9392
9393 $dom->encoding = 'UTF-8';
9394
9395 $return = $dom->saveHTML(); // This may add a LF at end of lines, so we will trim later
9396 //$return = '<html><body>aaaa</p>bb<p>ssdd</p>'."\n<p>aaa</p>aa<p>bb</p>";
9397
9398 //$return = preg_replace('/^'.preg_quote('<?xml encoding="UTF-8">', '/').'/', '', $return);
9399 $return = preg_replace('/^' . preg_quote('<html><head><', '/') . '[^<>]*' . preg_quote('></head><body>', '/') . '/', '', $return);
9400 $return = preg_replace('/' . preg_quote('</body></html>', '/') . '$/', '', trim($return));
9401
9402 return trim($return);
9403 } else {
9404 return $stringtoclean;
9405 }
9406}
9407
9419function dol_string_neverthesehtmltags($stringtoclean, $disallowed_tags = array('textarea'), $cleanalsosomestyles = 0)
9420{
9421 $temp = $stringtoclean;
9422 foreach ($disallowed_tags as $tagtoremove) {
9423 $temp = preg_replace('/<\/?' . $tagtoremove . '>/', '', $temp);
9424 $temp = preg_replace('/<\/?' . $tagtoremove . '\s+[^>]*>/', '', $temp);
9425 }
9426
9427 if ($cleanalsosomestyles) {
9428 $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
9429 }
9430
9431 return $temp;
9432}
9433
9434
9444function dolCloseUnclosedHtmlTags($text)
9445{
9446 if (!is_string($text) || $text === '') {
9447 return $text;
9448 }
9449
9450 // Tags that never carry a closing tag
9451 $selfclosing = array('br', 'hr', 'img', 'input', 'meta', 'link', 'source', 'col', 'area', 'base', 'embed', 'param', 'track', 'wbr');
9452
9453 $opened = array();
9454 if (preg_match_all('/<\s*(\/?)([a-zA-Z][a-zA-Z0-9]*)[^>]*?(\/?)\s*>/', $text, $matches, PREG_SET_ORDER)) {
9455 foreach ($matches as $match) {
9456 $tag = strtolower($match[2]);
9457 if (in_array($tag, $selfclosing) || !empty($match[3])) {
9458 continue;
9459 }
9460 if (empty($match[1])) {
9461 $opened[] = $tag;
9462 } else {
9463 // Close the most recent matching opened tag, ignore a stray closing tag
9464 $idx = array_search($tag, array_reverse($opened, true), true);
9465 if ($idx !== false) {
9466 unset($opened[$idx]);
9467 }
9468 }
9469 }
9470 }
9471
9472 foreach (array_reverse($opened) as $tag) {
9473 $text .= '</'.$tag.'>';
9474 }
9475
9476 return $text;
9477}
9478
9488function dolGetFirstLineOfText($text, $nboflines = 1, $charset = 'UTF-8')
9489{
9490 if ($nboflines == 1) {
9491 if (dol_textishtml($text)) {
9492 $firstline = preg_replace('/<br[^>]*>.*$/s', '', $text); // The s pattern modifier means the . can match newline characters
9493 $firstline = preg_replace('/<div[^>]*>.*$/s', '', $firstline); // The s pattern modifier means the . can match newline characters
9494 } else {
9495 if (isset($text)) {
9496 $firstline = preg_replace('/[\n\r].*/', '', $text);
9497 } else {
9498 $firstline = '';
9499 }
9500 }
9501 return $firstline . (isset($firstline) && isset($text) && (strlen($firstline) != strlen($text)) ? '...' : '');
9502 } else {
9503 $ishtml = 0;
9504 if (dol_textishtml($text)) {
9505 $text = preg_replace('/\n/', '', $text);
9506 $ishtml = 1;
9507 $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
9508 } else {
9509 $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
9510 }
9511
9512 $text = strtr($text, $repTable);
9513 if ($charset == 'UTF-8') {
9514 $pattern = '/(<br[^>]*>)/Uu';
9515 } else {
9516 // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
9517 $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
9518 }
9519 $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
9520
9521 $firstline = '';
9522 $i = 0;
9523 $countline = 0;
9524 $lastaddediscontent = 1;
9525 while ($countline < $nboflines && isset($a[$i])) {
9526 if (preg_match('/<br[^>]*>/', $a[$i])) {
9527 if (array_key_exists($i + 1, $a) && !empty($a[$i + 1])) {
9528 $firstline .= ($ishtml ? "<br>\n" : "\n");
9529 // Is it a br for a new line of after a printed line ?
9530 if (!$lastaddediscontent) {
9531 $countline++;
9532 }
9533 $lastaddediscontent = 0;
9534 }
9535 } else {
9536 $firstline .= $a[$i];
9537 $lastaddediscontent = 1;
9538 $countline++;
9539 }
9540 $i++;
9541 }
9542
9543 $adddots = (isset($a[$i]) && (!preg_match('/<br[^>]*>/', $a[$i]) || (array_key_exists($i + 1, $a) && !empty($a[$i + 1]))));
9544 //unset($a);
9545 $ret = $firstline . ($adddots ? '...' : '');
9546 //exit;
9547 return $ret;
9548 }
9549}
9550
9551
9563function dol_nl2br($stringtoencode, $nl2brmode = 0, $forxml = false)
9564{
9565 if (is_null($stringtoencode)) {
9566 return '';
9567 }
9568
9569 if (!$nl2brmode) {
9570 return nl2br($stringtoencode, $forxml);
9571 } else {
9572 $ret = preg_replace('/(\r\n|\r|\n)/i', ($forxml ? '<br />' : '<br>'), $stringtoencode);
9573 return $ret;
9574 }
9575}
9576
9586function dol_htmlwithnojs($stringtoencode, $nouseofiframesandbox = 0, $check = 'restricthtml')
9587{
9588 if (empty($nouseofiframesandbox) && getDolGlobalString('MAIN_SECURITY_USE_SANDBOX_FOR_HTMLWITHNOJS')) {
9589 // TODO using sandbox on inline html content is not possible yet with current browsers
9590 //$s = '<iframe class="iframewithsandbox" sandbox><html><body>';
9591 //$s .= $stringtoencode;
9592 //$s .= '</body></html></iframe>';
9593 return $stringtoencode;
9594 } else {
9595 $out = $stringtoencode;
9596
9597 // First clean HTML content
9598 do {
9599 $oldstringtoclean = $out;
9600
9601 $outishtml = 0;
9602 if (dol_textishtml($out)) {
9603 $outishtml = 1;
9604 }
9605
9606 // HTML sanitizer by DOMDocument
9607 if (!empty($out) && getDolGlobalInt('MAIN_RESTRICTHTML_ONLY_VALID_HTML') && $check != 'restricthtmlallowunvalid') {
9608 try {
9609 libxml_use_internal_errors(false); // Avoid to fill memory with xml errors
9610 if (LIBXML_VERSION < 20900) {
9611 // Avoid load of external entities (security problem).
9612 // Required only if LIBXML_VERSION < 20900
9613 // @phan-suppress-next-line PhanDeprecatedFunctionInternal
9614 libxml_disable_entity_loader(true);
9615 }
9616
9617 $dom = new DOMDocument();
9618 // Add a trick '<div class="tricktoremove">' to solve pb with text without parent tag
9619 // like '<h1>Foo</h1><p>bar</p>' that wrongly ends up, without the trick, with '<h1>Foo<p>bar</p></h1>'
9620 // like 'abc' that wrongly ends up, without the trick, with '<p>abc</p>'
9621 // Add also a trick <html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"> to solve utf8 lost.
9622 // I don't know what the xml encoding is the trick for
9623 if ($outishtml) {
9624 //$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>';
9625 $out = '<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"></head><body><div class="tricktoremove">' . $out . '</div></body></html>';
9626 //$out = '<html><head><meta charset="utf-8"></head><body><div class="tricktoremove">'.$out.'</div></body></html>';
9627 } else {
9628 // String is not a HTML content but pure text so we accept the & char alone. We protect it from being modified by HTML Tidy or XML sanitizers
9629 $out = preg_replace('/&(?![a-zA-Z0-9#]+;)/', '__AMPINTEXT__', $out);
9630
9631 //$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>';
9632 $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>';
9633 //$out = '<html><head><meta charset="utf-8"></head><body><div class="tricktoremove">'.dol_nl2br($out).'</div></body></html>';
9634 }
9635
9636 // Note: <a href="https://__[aaa]__/aaa.html"> is transformed into <a href="https://__[aaa]__/aaa.html">
9637 // We don't want that, so we protect __[xxx]__ by replacing [ and ] before loadHTML and restore them after saveHTML
9638 $out = preg_replace_callback(
9639 '/__\[([0-9a-zA-Z_]+)\]__/',
9644 function ($m) {
9645 return '__BRACKETSTART' . $m[1] . 'BRACKETEND__';
9646 },
9647 $out
9648 );
9649
9650 $dom->loadHTML($out, LIBXML_HTML_NODEFDTD | LIBXML_ERR_NONE | LIBXML_HTML_NOIMPLIED | LIBXML_NONET | LIBXML_NOWARNING | LIBXML_NOERROR | LIBXML_NOXMLDECL);
9651
9652 $dom->encoding = 'UTF-8';
9653
9654 // Add a layer to remove some styles
9655 if (getDolGlobalInt('MAIN_RESTRICTHTML_ONLY_VALID_HTML') == 2) {
9656 foreach ($dom->getElementsByTagName('*') as $el) {
9657 if (!$el instanceof DOMElement) {
9658 continue;
9659 }
9660
9661 // @phan-suppress-next-line PhanPluginUnknownObjectMethodCall
9662 if ($el->hasAttribute('style')) {
9663 // @phan-suppress-next-line PhanPluginUnknownObjectMethodCall
9664 $style = $el->getAttribute('style');
9665
9666 // delete some styles
9667 $style = preg_replace('/z-index\s*:/i', '', $style);
9668 $style = preg_replace('/position\s*:/i', '', $style);
9669 $style = preg_replace('/top\s*:/i', '', $style);
9670 $style = preg_replace('/left\s*:/i', '', $style);
9671 $style = preg_replace('/background\s*:/i', '', $style);
9672 /*
9673 $style = preg_replace('/width\s*:/i', '', $style);
9674 $style = preg_replace('/height\s*:/i', '', $style);
9675 $style = preg_replace('/backdrop-filter\s*:/i', '', $style);
9676 */
9677 if (trim($style) === '') {
9678 // @phan-suppress-next-line PhanPluginUnknownObjectMethodCall
9679 $el->removeAttribute('style');
9680 } else {
9681 // @phan-suppress-next-line PhanPluginUnknownObjectMethodCall
9682 $el->setAttribute('style', $style);
9683 }
9684 }
9685 }
9686 }
9687
9688 $out = trim($dom->saveHTML());
9689
9690 // Restore [ and ] that were protected before loadHTML
9691 $out = preg_replace_callback(
9692 '/__BRACKETSTART([0-9a-zA-Z_]+)BRACKETEND__/',
9697 function ($m) {
9698 return '__[' . $m[1] . ']__';
9699 },
9700 $out
9701 );
9702
9703 // Remove the trick added to solve pb with text in utf8 and text without parent tag
9704 //$out = preg_replace('/^'.preg_quote('<?xml encoding="UTF-8">', '/').'/', '', $out);
9705 $out = preg_replace('/^' . preg_quote('<html><head><', '/') . '[^<>]+' . preg_quote('></head><body><div class="tricktoremove">', '/') . '/', '', $out);
9706 $out = preg_replace('/' . preg_quote('</div></body></html>', '/') . '$/', '', trim($out));
9707 //$out = preg_replace('/^<\?xml encoding="UTF-8"><div class="tricktoremove">/', '', $out);
9708 //$out = preg_replace('/<\/div>$/', '', $out);
9709
9710 if (!$outishtml) { // If $out was not HTML content we made before a dol_nl2br so we must do the opposite operation now
9711 $out = str_replace('__AMPINTEXT__', '&', $out); // Restore & char not entity
9712 $out = str_replace('<br>', '', $out);
9713 }
9714 } catch (Exception $e) {
9715 // If error, invalid HTML string with no way to clean it
9716 //print $e->getMessage();
9717 $out = 'InvalidHTMLStringCantBeCleaned ' . $e->getMessage();
9718 }
9719 }
9720
9721 // HTML sanitizer by Tidy
9722 // Tidy can't be used for restricthtmlallowunvalid and restricthtmlallowlinkscript
9723 // Tidy can't be used for non html text content as it is corrupting the new lines fields.
9724 if (!empty($out) && getDolGlobalInt('MAIN_RESTRICTHTML_ONLY_VALID_HTML_TIDY') && !in_array($check, array('restricthtmlallowunvalid', 'restricthtmlallowlinkscript')) && $outishtml) {
9725 // TODO Try to implement a hack for restricthtmlallowlinkscript by renaming tag <link> and <script> ?
9726 try {
9727 //var_dump($out);
9728
9729 // Try cleaning using tidy
9730 if (extension_loaded('tidy') && class_exists("tidy")) {
9731 //print "aaa".$out."\n";
9732
9733 // See options at https://tidy.sourceforge.net/docs/quickref.html
9734 $config = array(
9735 'clean' => false,
9736 // 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;
9737 'quote-marks' => false,
9738 'doctype' => 'strict',
9739 'show-body-only' => true,
9740 "indent-attributes" => false,
9741 "vertical-space" => false,
9742 //'ident' => false, // Not always supported
9743 "wrap" => 0,
9744 'preserve-entities' => true
9745 // HTML5 tags
9746 //'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',
9747 //'new-blocklevel-tags' => 'footer header section menu menuitem'
9748 //'new-empty-tags' => 'command embed keygen source track wbr',
9749 //'new-inline-tags' => 'audio command datalist embed keygen mark menuitem meter output progress source time video wbr',
9750 );
9751
9752 // Tidy
9753 $locale = setlocale(LC_NUMERIC, '0'); // Tidy has a bug and is changing the PHP locale. So we save it to restore it after.
9754
9755 $tidy = new tidy();
9756 $out = $tidy->repairString($out, $config, 'utf8');
9757
9758 setlocale(LC_NUMERIC, $locale); // Restore original local
9759
9760 //print "xxx".$out;exit;
9761 }
9762
9763 //var_dump($out);
9764 } catch (Exception $e) {
9765 // If error, invalid HTML string with no way to clean it
9766 //print $e->getMessage();
9767 $out = 'InvalidHTMLStringCantBeCleaned ' . $e->getMessage();
9768 }
9769 }
9770
9771 // Clear ZERO WIDTH NO-BREAK SPACE, ZERO WIDTH SPACE, ZERO WIDTH JOINER
9772 // TODO $out = preg_replace('/[\x{2000}-\x{200D}\x{FEFF}]/u', ' ', $out);
9773 $out = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', ' ', $out);
9774
9775 // Clean some html entities that are useless so text is cleaner
9776 $out = preg_replace('/&(tab|newline);/i', ' ', $out);
9777
9778 // Ckeditor uses the numeric entity for apostrophe, so we force it to
9779 // the text entity (all other special chars are encoded using text entities) so we can then exclude all numeric entities.
9780 $out = preg_replace('/&#39;/i', '&apos;', $out);
9781
9782 // 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).
9783 // 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
9784 // using a non conventionnal way to be encoded, to not have them sanitized just after)
9785 if (function_exists('realCharForNumericEntities')) { // May not exist when main.inc.php not loaded, for example in a CLI context
9786 $out = preg_replace_callback(
9787 '/&#(x?[0-9][0-9a-f]+;?)/i',
9792 static function ($m) {
9793 return realCharForNumericEntities($m);
9794 },
9795 $out
9796 );
9797 }
9798
9799 // Now we remove all remaining HTML entities starting with a number. We don't want such entities.
9800 $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'.
9801
9802 // Keep only some html tags and remove also some 'javascript:' strings
9803 if ($check == 'restricthtmlallowlinkscript') {
9804 $out = dol_string_onlythesehtmltags($out, 0, 1, 0, 0, array(), 1, 1, 1, getDolGlobalInt("UNSECURED_restricthtmlallowlinkscript_ALLOW_PHP"));
9805 } elseif ($check == 'restricthtmlallowclass' || $check == 'restricthtmlallowunvalid') {
9806 $out = dol_string_onlythesehtmltags($out, 0, 0, 1);
9807 } elseif ($check == 'restricthtmlallowiframe') {
9808 $out = dol_string_onlythesehtmltags($out, 0, 0, 1, 1);
9809 } else {
9810 $out = dol_string_onlythesehtmltags($out, 0, 1, 1); // styles are allowed to allow rich text editor features of ckeditor managed by the "style=" attribute
9811 }
9812
9813 // Keep only some html attributes and exclude non expected HTML attributes and clean content of some attributes (keep only alt=, title=...).
9814 if (getDolGlobalString('MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES')) {
9816 }
9817
9818 // Restore entity &apos; into &#39; (restricthtml is for html content so we can use html entity) because it is
9819 // compatible with HTML 4 used y CKEditor, and HTML 5 (when &apos; works only with HTML5).
9820 $out = preg_replace('/&apos;/i', "&#39;", $out);
9821
9822 // Now remove js
9823 // 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
9824 $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)>
9825 $out = preg_replace('/on(abort|after|animation|auxclick|before|blur|cancel|canplay|canplaythrough|change|click|close|command|contentvisibility|context|cuechange|copy|cut)[a-z]*\s*=/i', '', $out);
9826 $out = preg_replace('/on(dblclick|drop|durationchange|emptied|end|ended|error|focus(in|out)?|formdata|gotpointercapture|hashchange|input|invalid)[a-z]*\s*=/i', '', $out);
9827 $out = preg_replace('/on(lost|offline|online|message|pagehide|pageshow)[a-z]*\s*=/i', '', $out);
9828 $out = preg_replace('/on(paste|pause|play|playing|progress|ratechange|rejectionn|reset|resize|scroll|search|security|seeked|seeking|show|stalled|start|submit|suspend)[a-z]*\s*=/i', '', $out);
9829 $out = preg_replace('/on(timeupdate|toggle|unhandled|unload|volumechange|waiting|wheel)[a-z]*\s*=/i', '', $out);
9830 // More not into the previous list
9831 $out = preg_replace('/on(repeat|begin|finish|beforeinput)[a-z]*\s*=/i', '', $out);
9832 // Add also a generic removal of any onxxx= attribute
9833 $out = preg_replace('/\son[a-z]+\s*=/i', ' ', $out);
9834 } while ($oldstringtoclean != $out);
9835
9836 // Check the limit of external links that are automatically executed in a Rich text content. We count:
9837 // '<img' to avoid <img src="http...">, we can only accept "<img src="data:..."
9838 // 'url(' to avoid inline style like background: url(http...
9839 // '<link' to avoid <link href="http...">
9840 $reg = array();
9841 $tmpout = preg_replace('/<img src="data:/mi', '<__IMG_SRC_DATA__ src="data:', $out);
9842 preg_match_all('/(<img|url\‍(|<link)/i', $tmpout, $reg);
9843 $nblinks = count($reg[0]);
9844 if ($nblinks > getDolGlobalInt("MAIN_SECURITY_MAX_IMG_IN_HTML_CONTENT", 1000)) {
9845 $out = 'ErrorTooManyLinksIntoHTMLString';
9846 }
9847
9848 if (getDolGlobalInt('MAIN_DISALLOW_URL_INTO_DESCRIPTIONS') == 2 || $check == 'restricthtmlnolink') {
9849 if ($nblinks > 0) {
9850 $out = 'ErrorHTMLLinksNotAllowed';
9851 }
9852 } elseif (getDolGlobalInt('MAIN_DISALLOW_URL_INTO_DESCRIPTIONS') == 1) {
9853 // Refuse any links except it they are to the wrapper document.php or viewimage.php
9854 $nblinks = 0;
9855
9856 // Loop on each url in src= and url(
9857 $pattern = '/src=["\']?(http[^"\']+)|url\‍(["\']?(http[^\‍)]+)/';
9858
9860
9861 $matches = array();
9862 if (preg_match_all($pattern, $out, $matches)) {
9863 // URLs are into $matches[1] or $matches[2]
9864 $urls = array();
9865 foreach ($matches[1] as $tmpval) {
9866 if (!empty($tmpval)) {
9867 $urls[] = $tmpval;
9868 }
9869 }
9870 foreach ($matches[2] as $tmpval) {
9871 if (!empty($tmpval)) {
9872 $urls[] = $tmpval;
9873 }
9874 }
9875
9876 // Show URLs
9877 $firstexturl = '';
9878 $secondexturl = '';
9879 foreach ($urls as $url) {
9880 $urlok = 0;
9881 $parsedurl = parse_url($url);
9882 if (!empty($parsedurl)) {
9883 if (preg_match('/'.preg_quote($dolibarr_main_url_root, '/').'/', $url)
9884 //&& preg_match('/(document|viewimage)\.php$/', $parsedurl['path']) && preg_match('/modulepart=(media|mycompany)/', $parsedurl['query'])
9885 ) {
9886 $urlok = 1;
9887 }
9888 }
9889 if (!$urlok) {
9890 $nblinks++;
9891 if (empty($firstexturl)) {
9892 $firstexturl = $url;
9893 } elseif (empty($secondexturl)) {
9894 $secondexturl = $url;
9895 }
9896 //echo "Found url = ".$url . "\n";
9897 }
9898 }
9899 if ($nblinks > 0) {
9900 $out = 'ErrorHTMLExternalLinksNotAllowed (Example: '.$firstexturl.($secondexturl ? ' '.$secondexturl : '').')';
9901 }
9902 }
9903 }
9904
9905 return $out;
9906 }
9907}
9908
9929function dol_htmlentitiesbr($stringtoencode, $nl2brmode = 0, $pagecodefrom = 'UTF-8', $removelasteolbr = 1)
9930{
9931 if (is_null($stringtoencode)) {
9932 return '';
9933 }
9934
9935 $newstring = $stringtoencode;
9936 if (dol_textishtml($stringtoencode)) { // Check if text is already HTML or not
9937 $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.
9938 if ($removelasteolbr) {
9939 $newstring = preg_replace('/<br>$/i', '', $newstring); // Remove last <br> (remove only last one)
9940 }
9941 $newstring = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', ' ', $newstring);
9942 $newstring = strtr($newstring, array('&' => '__PROTECTand__', '<' => '__PROTECTlt__', '>' => '__PROTECTgt__', '"' => '__PROTECTdquot__'));
9943 $newstring = dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom); // Make entity encoding
9944 $newstring = strtr($newstring, array('__PROTECTand__' => '&', '__PROTECTlt__' => '<', '__PROTECTgt__' => '>', '__PROTECTdquot__' => '"'));
9945 } else {
9946 if ($removelasteolbr) {
9947 $newstring = preg_replace('/(\r\n|\r|\n)$/i', '', $newstring); // Remove last \n (may remove several)
9948 }
9949 $newstring = dol_nl2br(dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom), $nl2brmode);
9950 }
9951 // Other substitutions that htmlentities does not do
9952 //$newstring=str_replace(chr(128),'&euro;',$newstring); // 128 = 0x80. Not in html entity table. // Seems useles with TCPDF. Make bug with UTF8 languages
9953 return $newstring;
9954}
9955
9963function dol_htmlentitiesbr_decode($stringtodecode, $pagecodeto = 'UTF-8')
9964{
9965 $ret = dol_html_entity_decode($stringtodecode, ENT_COMPAT | ENT_HTML5, $pagecodeto);
9966 $ret = preg_replace('/' . "\r\n" . '<br(\s[\sa-zA-Z_="]*)?\/?>/i', "<br>", $ret);
9967 $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>' . "\r\n" . '/i', "\r\n", $ret);
9968 $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>' . "\n" . '/i', "\n", $ret);
9969 $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i', "\n", $ret);
9970 return $ret;
9971}
9972
9979function dol_htmlcleanlastbr($stringtodecode)
9980{
9981 $ret = preg_replace('/&nbsp;$/i', "", $stringtodecode); // Because wysiwyg editor may add a &nbsp; at end of last line
9982 $ret = preg_replace('/(<br>|<br(\s[\sa-zA-Z_="]*)?\/?>|' . "\n" . '|' . "\r" . ')+$/i', "", $ret);
9983 return $ret;
9984}
9985
9995function dol_html_entity_decode($a, $b, $c = 'UTF-8', $keepsomeentities = 0)
9996{
9997 $newstring = $a;
9998 if ($keepsomeentities) {
9999 $newstring = strtr($newstring, array('&amp;' => '__andamp__', '&lt;' => '__andlt__', '&gt;' => '__andgt__', '"' => '__dquot__'));
10000 }
10001 $newstring = html_entity_decode((string) $newstring, (int) $b, (string) $c);
10002 if ($keepsomeentities) {
10003 $newstring = strtr($newstring, array('__andamp__' => '&amp;', '__andlt__' => '&lt;', '__andgt__' => '&gt;', '__dquot__' => '"'));
10004 }
10005 return $newstring;
10006}
10007
10019function dol_htmlentities($string, $flags = ENT_QUOTES | ENT_SUBSTITUTE, $encoding = 'UTF-8', $double_encode = false)
10020{
10021 return htmlentities($string, $flags, $encoding, $double_encode);
10022}
10023
10035function dol_string_is_good_iso($s, $clean = 0)
10036{
10037 $len = dol_strlen($s);
10038 $out = '';
10039 $ok = 1;
10040 for ($scursor = 0; $scursor < $len; $scursor++) {
10041 $ordchar = ord($s[$scursor]);
10042 //print $scursor.'-'.$ordchar.'<br>';
10043 if ($ordchar < 32 && $ordchar != 13 && $ordchar != 10) {
10044 $ok = 0;
10045 break;
10046 } elseif ($ordchar > 126 && $ordchar < 160) {
10047 $ok = 0;
10048 break;
10049 } elseif ($clean) {
10050 $out .= $s[$scursor];
10051 }
10052 }
10053 if ($clean) {
10054 return $out;
10055 }
10056 return $ok;
10057}
10058
10067function dol_nboflines($s, $maxchar = 0)
10068{
10069 if ($s == '') {
10070 return 0;
10071 }
10072 $arraystring = explode("\n", $s);
10073 $nb = count($arraystring);
10074
10075 return $nb;
10076}
10077
10078
10088function dol_nboflines_bis($text, $maxlinesize = 0, $charset = 'UTF-8')
10089{
10090 $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
10091 if (dol_textishtml($text)) {
10092 $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
10093 }
10094
10095 $text = strtr($text, $repTable);
10096 if ($charset == 'UTF-8') {
10097 $pattern = '/(<br[^>]*>)/Uu';
10098 } else {
10099 // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
10100 $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
10101 }
10102 $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
10103
10104 $nblines = (int) floor((count($a) + 1) / 2);
10105 // count possible auto line breaks
10106 if ($maxlinesize) {
10107 foreach ($a as $line) {
10108 if (dol_strlen($line) > $maxlinesize) {
10109 //$line_dec = html_entity_decode(strip_tags($line));
10110 $line_dec = html_entity_decode($line);
10111 if (dol_strlen($line_dec) > $maxlinesize) {
10112 $line_dec = wordwrap($line_dec, $maxlinesize, '\n', true);
10113 $nblines += substr_count($line_dec, '\n');
10114 }
10115 }
10116 }
10117 }
10118
10119 unset($a);
10120 return $nblines;
10121}
10122
10131function dol_textishtml($msg, $option = 0)
10132{
10133 if (is_null($msg)) {
10134 return false;
10135 }
10136
10137 if ($option == 1) {
10138 if (preg_match('/<(html|link|script)/i', $msg)) {
10139 return true;
10140 } elseif (preg_match('/<body/i', $msg)) {
10141 return true;
10142 } elseif (preg_match('/<\/textarea/i', $msg)) {
10143 return true;
10144 } elseif (preg_match('/<(b|em|i|u)(\s+[^>]+)?>/i', $msg)) {
10145 return true;
10146 } elseif (preg_match('/<br/i', $msg)) {
10147 return true;
10148 }
10149 return false;
10150 } else {
10151 // Remove all urls because 'http://aa?param1=abc&amp;param2=def' must not be used inside detection
10152 $msg = preg_replace('/https?:\/\/[^"\'\s]+/i', '', $msg);
10153 if (preg_match('/<(html|link|script|body)/i', $msg)) {
10154 return true;
10155 } elseif (preg_match('/<\/textarea/i', $msg)) {
10156 return true;
10157 } elseif (preg_match('/<(b|em|i|u)(\s+[^>]+)?>/i', $msg)) {
10158 return true;
10159 } elseif (preg_match('/<(br|hr)\/>/i', $msg)) {
10160 return true;
10161 } elseif (preg_match('/<(br|hr|div|font|li|p|span|strong|table)>/i', $msg)) {
10162 return true;
10163 } elseif (preg_match('/<(br|hr|div|font|li|p|span|strong|table)\s+[^<>\/]*\/?>/i', $msg)) {
10164 return true;
10165 } elseif (preg_match('/<img\s+[^<>]*src[^<>]*>/i', $msg)) {
10166 return true; // must accept <img src="http://example.com/aaa.png" />
10167 } elseif (preg_match('/<a\s+[^<>]*href[^<>]*>/i', $msg)) {
10168 return true; // must accept <a href="http://example.com/aaa.png" />
10169 } elseif (preg_match('/<h[0-9]>/i', $msg)) {
10170 return true;
10171 } elseif (preg_match('/&[A-Z0-9]{1,6};/i', $msg)) {
10172 // TODO If content is 'A link https://aaa?param=abc&amp;param2=def', it return true but must be false
10173 return true; // Html entities names (http://www.w3schools.com/tags/ref_entities.asp)
10174 } elseif (preg_match('/&#[0-9]{2,3};/i', $msg)) {
10175 return true; // Html entities numbers (http://www.w3schools.com/tags/ref_entities.asp)
10176 } elseif (preg_match('/&#x[a-f0-9][a-f0-9];/i', $msg)) {
10177 return true; // Html entities numbers in hexa
10178 }
10179
10180 return false;
10181 }
10182}
10183
10198function dol_concatdesc($text1, $text2, $forxml = false, $invert = false)
10199{
10200 if (!empty($invert)) {
10201 $tmp = $text1;
10202 $text1 = $text2;
10203 $text2 = $tmp;
10204 }
10205
10206 $ret = '';
10207 $ret .= (!dol_textishtml($text1) && dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text1, 0, 1, '', 1), 0, $forxml) : $text1;
10208 $ret .= (!empty($text1) && !empty($text2)) ? ((dol_textishtml($text1) || dol_textishtml($text2)) ? ($forxml ? "<br >\n" : "<br>\n") : "\n") : "";
10209 $ret .= (dol_textishtml($text1) && !dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text2, 0, 1, '', 1), 0, $forxml) : $text2;
10210 return $ret;
10211}
10212
10221function dol_concat($text1, $text2)
10222{
10223 return $text1.$text2;
10224}
10225
10233function safeArrayMap($callback, array $array)
10234{
10235 if (!is_string($callback)) {
10236 throw new InvalidArgumentException("Les callbacks sont désactivés.");
10237 }
10238 // Check that $callback is a sure function
10239 $allowed_callbacks = ['strtolower', 'strtoupper', 'intval'];
10240 if (!in_array($callback, $allowed_callbacks, true)) {
10241 throw new InvalidArgumentException("Callback function not allowed.");
10242 }
10243 return array_map($callback, $array);
10244}
10245
10246
10260function getCommonSubstitutionArray($outputlangs, $onlykey = 0, $exclude = null, $object = null, $include = null)
10261{
10262 global $db, $conf, $mysoc, $user, $extrafields;
10263
10264 $substitutionarray = array();
10265
10266 if ((empty($exclude) || !in_array('user', $exclude)) && (empty($include) || in_array('user', $include)) && $user instanceof User) {
10267 // Add SIGNATURE into substitutionarray first, so, when we will make the substitution,
10268 // this will include signature content first and then replace var found into content of signature
10269 //var_dump($onlykey);
10270 $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()
10271 $usersignature = $user->signature;
10272 $substitutionarray = array_merge($substitutionarray, array(
10273 '__SENDEREMAIL_SIGNATURE__' => (string) ((!getDolGlobalString('MAIN_MAIL_DO_NOT_USE_SIGN')) ? ($onlykey == 2 ? dol_trunc('SignatureFromTheSelectedSenderProfile', 30) : $emailsendersignature) : ''),
10274 '__USER_SIGNATURE__' => (string) (($usersignature && !getDolGlobalString('MAIN_MAIL_DO_NOT_USE_SIGN')) ? ($onlykey == 2 ? dol_trunc(dol_string_nohtmltag($usersignature), 30) : $usersignature) : '')
10275 ));
10276
10277 if (is_object($user) && ($user instanceof User)) {
10278 $substitutionarray = array_merge($substitutionarray, array(
10279 '__USER_ID__' => (string) $user->id,
10280 '__USER_LOGIN__' => (string) $user->login,
10281 '__USER_EMAIL__' => (string) $user->email,
10282 '__USER_PHONE__' => (string) dol_print_phone($user->office_phone, '', 0, 0, '', " ", '', '', -1),
10283 '__USER_PHONEPRO__' => (string) dol_print_phone($user->user_mobile, '', 0, 0, '', " ", '', '', -1),
10284 '__USER_PHONEMOBILE__' => (string) dol_print_phone($user->personal_mobile, '', 0, 0, '', " ", '', '', -1),
10285 '__USER_FAX__' => (string) $user->office_fax,
10286 '__USER_LASTNAME__' => (string) $user->lastname,
10287 '__USER_FIRSTNAME__' => (string) $user->firstname,
10288 '__USER_FULLNAME__' => (string) $user->getFullName($outputlangs),
10289 '__USER_SUPERVISOR_ID__' => (string) ($user->fk_user ? $user->fk_user : '0'),
10290 '__USER_JOB__' => (string) $user->job,
10291 '__USER_REMOTE_IP__' => (string) getUserRemoteIP(),
10292 '__USER_VCARD_URL__' => (string) $user->getOnlineVirtualCardUrl('', 'external')
10293 ));
10294 }
10295 }
10296 if ((empty($exclude) || !in_array('mycompany', $exclude)) && is_object($mysoc) && (empty($include) || in_array('mycompany', $include))) {
10297 $substitutionarray = array_merge($substitutionarray, array(
10298 '__MYCOMPANY_NAME__' => $mysoc->name,
10299 '__MYCOMPANY_EMAIL__' => $mysoc->email,
10300 '__MYCOMPANY_URL__' => $mysoc->url,
10301 '__MYCOMPANY_PHONE__' => dol_print_phone((string) $mysoc->phone, '', 0, 0, '', " ", '', '', -1),
10302 '__MYCOMPANY_PHONEMOBILE__' => dol_print_phone((string) $mysoc->phone_mobile, '', 0, 0, '', " ", '', '', -1),
10303 '__MYCOMPANY_FAX__' => dol_print_phone((string) $mysoc->fax, '', 0, 0, '', " ", '', '', -1),
10304 '__MYCOMPANY_PROFID1__' => $mysoc->idprof1,
10305 '__MYCOMPANY_PROFID2__' => $mysoc->idprof2,
10306 '__MYCOMPANY_PROFID3__' => $mysoc->idprof3,
10307 '__MYCOMPANY_PROFID4__' => $mysoc->idprof4,
10308 '__MYCOMPANY_PROFID5__' => $mysoc->idprof5,
10309 '__MYCOMPANY_PROFID6__' => $mysoc->idprof6,
10310 '__MYCOMPANY_PROFID7__' => $mysoc->idprof7,
10311 '__MYCOMPANY_PROFID8__' => $mysoc->idprof8,
10312 '__MYCOMPANY_PROFID9__' => $mysoc->idprof9,
10313 '__MYCOMPANY_PROFID10__' => $mysoc->idprof10,
10314 '__MYCOMPANY_CAPITAL__' => $mysoc->capital,
10315 '__MYCOMPANY_FULLADDRESS__' => (method_exists($mysoc, 'getFullAddress') ? $mysoc->getFullAddress(1, ', ') : ''), // $mysoc may be stdClass
10316 '__MYCOMPANY_ADDRESS__' => $mysoc->address,
10317 '__MYCOMPANY_VATNUMBER__' => $mysoc->tva_intra,
10318 '__MYCOMPANY_ZIP__' => $mysoc->zip,
10319 '__MYCOMPANY_TOWN__' => $mysoc->town,
10320 '__MYCOMPANY_STATE__' => $mysoc->state,
10321 '__MYCOMPANY_COUNTRY__' => $mysoc->country,
10322 '__MYCOMPANY_COUNTRY_ID__' => $mysoc->country_id,
10323 '__MYCOMPANY_COUNTRY_CODE__' => $mysoc->country_code,
10324 '__MYCOMPANY_CURRENCY_CODE__' => $conf->currency
10325 ));
10326 }
10327
10328 if (($onlykey || is_object($object)) && (empty($exclude) || !in_array('object', $exclude)) && (empty($include) || in_array('object', $include))) {
10329 if ($onlykey) {
10330 $substitutionarray['__ID__'] = '__ID__';
10331 $substitutionarray['__REF__'] = '__REF__';
10332 $substitutionarray['__NEWREF__'] = '__NEWREF__';
10333 $substitutionarray['__LABEL__'] = '__LABEL__';
10334 $substitutionarray['__REF_CLIENT__'] = '__REF_CLIENT__';
10335 $substitutionarray['__REF_SUPPLIER__'] = '__REF_SUPPLIER__';
10336 $substitutionarray['__NOTE_PUBLIC__'] = '__NOTE_PUBLIC__';
10337 $substitutionarray['__NOTE_PRIVATE__'] = '__NOTE_PRIVATE__';
10338 $substitutionarray['__EXTRAFIELD_XXX__'] = '__EXTRAFIELD_XXX__';
10339
10340 if (isModEnabled("societe")) { // Most objects are concerned
10341 $substitutionarray['__THIRDPARTY_ID__'] = '__THIRDPARTY_ID__';
10342 $substitutionarray['__THIRDPARTY_NAME__'] = '__THIRDPARTY_NAME__';
10343 $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = '__THIRDPARTY_NAME_ALIAS__';
10344 $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = '__THIRDPARTY_CODE_CLIENT__';
10345 $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = '__THIRDPARTY_CODE_FOURNISSEUR__';
10346 $substitutionarray['__THIRDPARTY_EMAIL__'] = '__THIRDPARTY_EMAIL__';
10347 //$substitutionarray['__THIRDPARTY_EMAIL_URLENCODED__'] = '__THIRDPARTY_EMAIL_URLENCODED__'; // We hide this one
10348 $substitutionarray['__THIRDPARTY_URL__'] = '__THIRDPARTY_URL__';
10349 //$substitutionarray['__THIRDPARTY_URL_URLENCODED__'] = '__THIRDPARTY_URL_URLENCODED__'; // We hide this one
10350 $substitutionarray['__THIRDPARTY_PHONE__'] = '__THIRDPARTY_PHONE__';
10351 $substitutionarray['__THIRDPARTY_FAX__'] = '__THIRDPARTY_FAX__';
10352 $substitutionarray['__THIRDPARTY_ADDRESS__'] = '__THIRDPARTY_ADDRESS__';
10353 $substitutionarray['__THIRDPARTY_ZIP__'] = '__THIRDPARTY_ZIP__';
10354 $substitutionarray['__THIRDPARTY_TOWN__'] = '__THIRDPARTY_TOWN__';
10355 $substitutionarray['__THIRDPARTY_STATE__'] = '__THIRDPARTY_STATE__';
10356 $substitutionarray['__THIRDPARTY_IDPROF1__'] = '__THIRDPARTY_IDPROF1__';
10357 $substitutionarray['__THIRDPARTY_IDPROF2__'] = '__THIRDPARTY_IDPROF2__';
10358 $substitutionarray['__THIRDPARTY_IDPROF3__'] = '__THIRDPARTY_IDPROF3__';
10359 $substitutionarray['__THIRDPARTY_IDPROF4__'] = '__THIRDPARTY_IDPROF4__';
10360 $substitutionarray['__THIRDPARTY_IDPROF5__'] = '__THIRDPARTY_IDPROF5__';
10361 $substitutionarray['__THIRDPARTY_IDPROF6__'] = '__THIRDPARTY_IDPROF6__';
10362 $substitutionarray['__THIRDPARTY_IDPROF7__'] = '__THIRDPARTY_IDPROF7__';
10363 $substitutionarray['__THIRDPARTY_IDPROF8__'] = '__THIRDPARTY_IDPROF8__';
10364 $substitutionarray['__THIRDPARTY_IDPROF9__'] = '__THIRDPARTY_IDPROF9__';
10365 $substitutionarray['__THIRDPARTY_IDPROF10__'] = '__THIRDPARTY_IDPROF10__';
10366 $substitutionarray['__THIRDPARTY_TVAINTRA__'] = '__THIRDPARTY_TVAINTRA__';
10367 $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = '__THIRDPARTY_NOTE_PUBLIC__';
10368 $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = '__THIRDPARTY_NOTE_PRIVATE__';
10369 }
10370 if (isModEnabled('member') && (!is_object($object) || $object->element == 'adherent') && (empty($exclude) || !in_array('member', $exclude)) && (empty($include) || in_array('member', $include))) {
10371 $substitutionarray['__MEMBER_ID__'] = '__MEMBER_ID__';
10372 $substitutionarray['__MEMBER_TITLE__'] = '__MEMBER_TITLE__';
10373 $substitutionarray['__MEMBER_FIRSTNAME__'] = '__MEMBER_FIRSTNAME__';
10374 $substitutionarray['__MEMBER_LASTNAME__'] = '__MEMBER_LASTNAME__';
10375 $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = 'Login and pass of the external user account';
10376 /*$substitutionarray['__MEMBER_NOTE_PUBLIC__'] = '__MEMBER_NOTE_PUBLIC__';
10377 $substitutionarray['__MEMBER_NOTE_PRIVATE__'] = '__MEMBER_NOTE_PRIVATE__';*/
10378 }
10379 // add substitution variables for ticket
10380 if (isModEnabled('ticket') && (!is_object($object) || $object->element == 'ticket') && (empty($exclude) || !in_array('ticket', $exclude)) && (empty($include) || in_array('ticket', $include))) {
10381 $substitutionarray['__TICKET_TRACKID__'] = '__TICKET_TRACKID__';
10382 $substitutionarray['__TICKET_SUBJECT__'] = '__TICKET_SUBJECT__';
10383 $substitutionarray['__TICKET_TYPE__'] = '__TICKET_TYPE__';
10384 $substitutionarray['__TICKET_SEVERITY__'] = '__TICKET_SEVERITY__';
10385 $substitutionarray['__TICKET_CATEGORY__'] = '__TICKET_CATEGORY__';
10386 $substitutionarray['__TICKET_ANALYTIC_CODE__'] = '__TICKET_ANALYTIC_CODE__';
10387 $substitutionarray['__TICKET_MESSAGE__'] = '__TICKET_MESSAGE__';
10388 $substitutionarray['__TICKET_PROGRESSION__'] = '__TICKET_PROGRESSION__';
10389 $substitutionarray['__TICKET_USER_ASSIGN__'] = '__TICKET_USER_ASSIGN__';
10390 $substitutionarray['__TICKET_TYPE_LABEL__'] = '__TICKET_TYPE_LABEL__';
10391 $substitutionarray['__TICKET_SEVERITY_LABEL__'] = '__TICKET_SEVERITY_LABEL__';
10392 $substitutionarray['__TICKET_CATEGORY_LABEL__'] = '__TICKET_CATEGORY_LABEL__';
10393 $substitutionarray['__TICKET_PUBLIC_URL__'] = '__TICKET_PUBLIC_URL__';
10394 $substitutionarray['__TICKET_MANAGEMENT_URL__'] = '__TICKET_MANAGEMENT_URL__';
10395 }
10396 if (isModEnabled('recruitment') && (!is_object($object) || $object->element == 'recruitmentcandidature') && (empty($exclude) || !in_array('recruitment', $exclude)) && (empty($include) || in_array('recruitment', $include))) {
10397 $substitutionarray['__CANDIDATE_FULLNAME__'] = '__CANDIDATE_FULLNAME__';
10398 $substitutionarray['__CANDIDATE_FIRSTNAME__'] = '__CANDIDATE_FIRSTNAME__';
10399 $substitutionarray['__CANDIDATE_LASTNAME__'] = '__CANDIDATE_LASTNAME__';
10400 }
10401 if (isModEnabled('holiday') && (!is_object($object) || $object->element == 'holiday') && (empty($exclude) || !in_array('holiday', $exclude)) && (empty($include) || in_array('holiday', $include))) {
10402 $substitutionarray['__HOLIDAY_ARRAY_PER_EMPLOYEE_FOR_PERIOD__'] = '__HOLIDAY_ARRAY_PER_EMPLOYEE_FOR_PERIOD__';
10403 }
10404 if (isModEnabled('project') && (empty($exclude) || !in_array('project', $exclude)) && (empty($include) || in_array('project', $include))) { // Most objects
10405 $substitutionarray['__PROJECT_ID__'] = '__PROJECT_ID__';
10406 $substitutionarray['__PROJECT_REF__'] = '__PROJECT_REF__';
10407 $substitutionarray['__PROJECT_NAME__'] = '__PROJECT_NAME__';
10408 /*$substitutionarray['__PROJECT_NOTE_PUBLIC__'] = '__PROJECT_NOTE_PUBLIC__';
10409 $substitutionarray['__PROJECT_NOTE_PRIVATE__'] = '__PROJECT_NOTE_PRIVATE__';*/
10410 }
10411 if (isModEnabled('contract') && (!is_object($object) || $object->element == 'contract') && (empty($exclude) || !in_array('contract', $exclude)) && (empty($include) || in_array('contract', $include))) {
10412 $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = 'Highest date planned for a service start';
10413 $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = 'Highest date and hour planned for service start';
10414 $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = 'Lowest data for planned expiration of service';
10415 $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = 'Lowest date and hour for planned expiration of service';
10416 }
10417 if (isModEnabled("propal") && (!is_object($object) || $object->element == 'propal') && (empty($exclude) || !in_array('propal', $exclude)) && (empty($include) || in_array('propal', $include))) {
10418 $substitutionarray['__ONLINE_SIGN_URL__'] = 'ToOfferALinkForOnlineSignature';
10419 }
10420 if (isModEnabled("intervention") && (!is_object($object) || $object->element == 'fichinter') && (empty($exclude) || !in_array('intervention', $exclude)) && (empty($include) || in_array('intervention', $include))) {
10421 $substitutionarray['__ONLINE_SIGN_FICHINTER_URL__'] = 'ToOfferALinkForOnlineSignature';
10422 }
10423 $substitutionarray['__ONLINE_PAYMENT_URL__'] = 'UrlToPayOnlineIfApplicable';
10424 $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = 'TextAndUrlToPayOnlineIfApplicable';
10425 $substitutionarray['__SECUREKEYPAYMENT__'] = 'Security key (if key is not unique per record)';
10426 $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = 'Security key for payment on a member subscription (one key per member)';
10427 $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = 'Security key for payment on an order';
10428 $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = 'Security key for payment on an invoice';
10429 $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = 'Security key for payment on a service of a contract';
10430
10431 $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = 'Direct download url of a proposal';
10432 $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = 'Direct download url of an order';
10433 $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = 'Direct download url of an invoice';
10434 $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = 'Direct download url of a contract';
10435 $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = 'Direct download url of a supplier proposal';
10436 $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_ORDER__'] = 'Direct download url of a supplier order';
10437 $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_INVOICE__'] = 'Direct download url of a supplier invoice';
10438
10439 if (isModEnabled("shipping") && (!is_object($object) || $object->element == 'shipping')) {
10440 $substitutionarray['__SHIPPINGTRACKNUM__'] = 'Shipping tracking number';
10441 $substitutionarray['__SHIPPINGTRACKNUMURL__'] = 'Shipping tracking url';
10442 $substitutionarray['__SHIPPINGMETHOD__'] = 'Shipping method';
10443 }
10444 if (isModEnabled("reception") && (!is_object($object) || $object->element == 'reception')) {
10445 $substitutionarray['__RECEPTIONTRACKNUM__'] = 'Shipping tracking number of shipment';
10446 $substitutionarray['__RECEPTIONTRACKNUMURL__'] = 'Shipping tracking url';
10447 }
10448 } else {
10449 '@phan-var-force Adherent|Delivery $object';
10451 $substitutionarray['__ID__'] = $object->id;
10452 $substitutionarray['__REF__'] = $object->ref;
10453 $substitutionarray['__NEWREF__'] = $object->newref;
10454 $substitutionarray['__LABEL__'] = (isset($object->label) ? $object->label : (isset($object->title) ? $object->title : null));
10455 $substitutionarray['__REF_CLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
10456 $substitutionarray['__REF_SUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
10457 $substitutionarray['__NOTE_PUBLIC__'] = (isset($object->note_public) ? $object->note_public : null);
10458 $substitutionarray['__NOTE_PRIVATE__'] = (isset($object->note_private) ? $object->note_private : null);
10459
10460 $substitutionarray['__DATE_CREATION__'] = (isset($object->date_creation) ? dol_print_date($object->date_creation, 'day', false, $outputlangs) : '');
10461 $substitutionarray['__DATE_MODIFICATION__'] = (isset($object->date_modification) ? dol_print_date($object->date_modification, 'day', false, $outputlangs) : '');
10462 $substitutionarray['__DATE_VALIDATION__'] = (isset($object->date_validation) ? dol_print_date($object->date_validation, 'day', false, $outputlangs) : '');
10463
10464 // handle date_delivery: in customer order/supplier order, the property name is delivery_date, in shipment/reception it is date_delivery
10465 $date_delivery = null;
10466 if (property_exists($object, 'date_delivery')) {
10467 $date_delivery = $object->date_delivery;
10468 } elseif (property_exists($object, 'delivery_date')) {
10469 $date_delivery = $object->delivery_date;
10470 }
10471 $substitutionarray['__DATE_DELIVERY__'] = (isset($date_delivery) ? dol_print_date($date_delivery, 'day', false, $outputlangs) : '');
10472 $substitutionarray['__DATE_DELIVERY_DAY__'] = (isset($date_delivery) ? dol_print_date($date_delivery, "%d") : '');
10473 $substitutionarray['__DATE_DELIVERY_DAY_TEXT__'] = (isset($date_delivery) ? dol_print_date($date_delivery, "%A") : '');
10474 $substitutionarray['__DATE_DELIVERY_MON__'] = (isset($date_delivery) ? dol_print_date($date_delivery, "%m") : '');
10475 $substitutionarray['__DATE_DELIVERY_MON_TEXT__'] = (isset($date_delivery) ? dol_print_date($date_delivery, "%b") : '');
10476 $substitutionarray['__DATE_DELIVERY_YEAR__'] = (isset($date_delivery) ? dol_print_date($date_delivery, "%Y") : '');
10477 $substitutionarray['__DATE_DELIVERY_HH__'] = (isset($date_delivery) ? dol_print_date($date_delivery, "%H") : '');
10478 $substitutionarray['__DATE_DELIVERY_MM__'] = (isset($date_delivery) ? dol_print_date($date_delivery, "%M") : '');
10479 $substitutionarray['__DATE_DELIVERY_SS__'] = (isset($date_delivery) ? dol_print_date($date_delivery, "%S") : '');
10480
10481 // For backward compatibility (deprecated)
10482 $substitutionarray['__REFCLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
10483 $substitutionarray['__REFSUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
10484
10485 $substitutionarray['__SUPPLIER_ORDER_DATE_DELIVERY__'] = (isset($date_delivery) ? dol_print_date($date_delivery, 'day', false, $outputlangs) : '');
10486 $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 : '')) : '');
10487 $substitutionarray['__EXPIRATION_DATE__'] = (isset($object->fin_validite) ? dol_print_date($object->fin_validite, 'daytext') : '');
10488
10489 if (is_object($object) && ($object->element == 'adherent' || $object->element == 'member') && $object->id > 0) {
10490 '@phan-var-force Adherent $object';
10492 $birthday = (empty($object->birth) ? '' : dol_print_date($object->birth, 'day'));
10493
10494 $substitutionarray['__MEMBER_ID__'] = (isset($object->id) ? $object->id : '');
10495 if (method_exists($object, 'getCivilityLabel')) {
10496 $substitutionarray['__MEMBER_TITLE__'] = $object->getCivilityLabel();
10497 }
10498 $substitutionarray['__MEMBER_FIRSTNAME__'] = (isset($object->firstname) ? $object->firstname : '');
10499 $substitutionarray['__MEMBER_LASTNAME__'] = (isset($object->lastname) ? $object->lastname : '');
10500 $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = '';
10501 if (method_exists($object, 'getFullName')) {
10502 $substitutionarray['__MEMBER_FULLNAME__'] = $object->getFullName($outputlangs);
10503 }
10504 $substitutionarray['__MEMBER_COMPANY__'] = (isset($object->societe) ? $object->societe : '');
10505 $substitutionarray['__MEMBER_ADDRESS__'] = (isset($object->address) ? $object->address : '');
10506 $substitutionarray['__MEMBER_ZIP__'] = (isset($object->zip) ? $object->zip : '');
10507 $substitutionarray['__MEMBER_TOWN__'] = (isset($object->town) ? $object->town : '');
10508 $substitutionarray['__MEMBER_STATE__'] = (isset($object->state) ? $object->state : '');
10509 $substitutionarray['__MEMBER_COUNTRY__'] = (isset($object->country) ? $object->country : '');
10510 $substitutionarray['__MEMBER_EMAIL__'] = (isset($object->email) ? $object->email : '');
10511 $substitutionarray['__MEMBER_BIRTH__'] = (isset($birthday) ? $birthday : '');
10512 $substitutionarray['__MEMBER_PHOTO__'] = (isset($object->photo) ? $object->photo : '');
10513 $substitutionarray['__MEMBER_LOGIN__'] = (isset($object->login) ? $object->login : '');
10514 $substitutionarray['__MEMBER_PASSWORD__'] = (isset($object->pass) ? $object->pass : '');
10515 $substitutionarray['__MEMBER_PHONE__'] = (isset($object->phone) ? dol_print_phone($object->phone) : '');
10516 $substitutionarray['__MEMBER_PHONEPRO__'] = (isset($object->phone_perso) ? dol_print_phone($object->phone_perso) : '');
10517 $substitutionarray['__MEMBER_PHONEMOBILE__'] = (isset($object->phone_mobile) ? dol_print_phone($object->phone_mobile) : '');
10518 $substitutionarray['__MEMBER_TYPE__'] = (isset($object->type) ? $object->type : '');
10519 $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE__'] = dol_print_date($object->first_subscription_date, 'day');
10520
10521 $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_RFC__'] = dol_print_date($object->first_subscription_date, 'dayrfc');
10522 $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_START__'] = (isset($object->first_subscription_date_start) ? dol_print_date($object->first_subscription_date_start, 'day') : '');
10523 $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_START_RFC__'] = (isset($object->first_subscription_date_start) ? dol_print_date($object->first_subscription_date_start, 'dayrfc') : '');
10524 $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_END__'] = (isset($object->first_subscription_date_end) ? dol_print_date($object->first_subscription_date_end, 'day') : '');
10525 $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_END_RFC__'] = (isset($object->first_subscription_date_end) ? dol_print_date($object->first_subscription_date_end, 'dayrfc') : '');
10526 $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE__'] = dol_print_date($object->last_subscription_date, 'day');
10527 $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_RFC__'] = dol_print_date($object->last_subscription_date, 'dayrfc');
10528 $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->last_subscription_date_start, 'day');
10529 $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_START_RFC__'] = dol_print_date($object->last_subscription_date_start, 'dayrfc');
10530 $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->last_subscription_date_end, 'day');
10531 $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_END_RFC__'] = dol_print_date($object->last_subscription_date_end, 'dayrfc');
10532 }
10533
10534 if (is_object($object) && $object->element == 'societe') {
10536 '@phan-var-force Societe $object';
10537 $substitutionarray['__THIRDPARTY_ID__'] = $object->id ?? '';
10538 $substitutionarray['__THIRDPARTY_NAME__'] = $object->name ?? '';
10539 $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = $object->name_alias ?? '';
10540 $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = $object->code_client ?? '';
10541 $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = $object->code_fournisseur ?? '';
10542 $substitutionarray['__THIRDPARTY_EMAIL__'] = $object->email ?? '';
10543 $substitutionarray['__THIRDPARTY_EMAIL_URLENCODED__'] = urlencode($object->email ?? '');
10544 $substitutionarray['__THIRDPARTY_URL__'] = $object->url ?? '';
10545 $substitutionarray['__THIRDPARTY_URL_URLENCODED__'] = urlencode($object->url ?? '');
10546 $substitutionarray['__THIRDPARTY_PHONE__'] = dol_print_phone($object->phone ?? '');
10547 $substitutionarray['__THIRDPARTY_FAX__'] = dol_print_phone($object->fax ?? '');
10548 $substitutionarray['__THIRDPARTY_ADDRESS__'] = $object->address ?? '';
10549 $substitutionarray['__THIRDPARTY_ZIP__'] = $object->zip ?? '';
10550 $substitutionarray['__THIRDPARTY_TOWN__'] = $object->town ?? '';
10551 $substitutionarray['__THIRDPARTY_STATE__'] = $object->state ?? '';
10552 $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = ($object->country_id > 0 ? $object->country_id : '');
10553 $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = $object->country_code ?? '';
10554 $substitutionarray['__THIRDPARTY_IDPROF1__'] = $object->idprof1 ?? '';
10555 $substitutionarray['__THIRDPARTY_IDPROF2__'] = $object->idprof2 ?? '';
10556 $substitutionarray['__THIRDPARTY_IDPROF3__'] = $object->idprof3 ?? '';
10557 $substitutionarray['__THIRDPARTY_IDPROF4__'] = $object->idprof4 ?? '';
10558 $substitutionarray['__THIRDPARTY_IDPROF5__'] = $object->idprof5 ?? '';
10559 $substitutionarray['__THIRDPARTY_IDPROF6__'] = $object->idprof6 ?? '';
10560 $substitutionarray['__THIRDPARTY_TVAINTRA__'] = $object->tva_intra ?? '';
10561 $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = dol_htmlentitiesbr($object->note_public ?? '');
10562 $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = dol_htmlentitiesbr($object->note_private ?? '');
10563 } elseif (is_object($object) && is_object($object->thirdparty)) {
10564 $substitutionarray['__THIRDPARTY_ID__'] = $object->thirdparty->id ?? '';
10565 $substitutionarray['__THIRDPARTY_NAME__'] = $object->thirdparty->name ?? '';
10566 $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = $object->thirdparty->name_alias ?? '';
10567 $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = $object->thirdparty->code_client ?? '';
10568 $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = $object->thirdparty->code_fournisseur ?? '';
10569 $substitutionarray['__THIRDPARTY_EMAIL__'] = $object->thirdparty->email ?? '';
10570 $substitutionarray['__THIRDPARTY_EMAIL_URLENCODED__'] = urlencode($object->thirdparty->email ?? '');
10571 $substitutionarray['__THIRDPARTY_PHONE__'] = dol_print_phone($object->thirdparty->phone ?? '');
10572 $substitutionarray['__THIRDPARTY_FAX__'] = dol_print_phone($object->thirdparty->fax ?? '');
10573 $substitutionarray['__THIRDPARTY_ADDRESS__'] = $object->thirdparty->address ?? '';
10574 $substitutionarray['__THIRDPARTY_ZIP__'] = $object->thirdparty->zip ?? '';
10575 $substitutionarray['__THIRDPARTY_TOWN__'] = $object->thirdparty->town ?? '';
10576 $substitutionarray['__THIRDPARTY_STATE__'] = $object->thirdparty->state ?? '';
10577 $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = ($object->thirdparty->country_id > 0 ? $object->thirdparty->country_id : '');
10578 $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = $object->thirdparty->country_code ?? '';
10579 $substitutionarray['__THIRDPARTY_IDPROF1__'] = $object->thirdparty->idprof1 ?? '';
10580 $substitutionarray['__THIRDPARTY_IDPROF2__'] = $object->thirdparty->idprof2 ?? '';
10581 $substitutionarray['__THIRDPARTY_IDPROF3__'] = $object->thirdparty->idprof3 ?? '';
10582 $substitutionarray['__THIRDPARTY_IDPROF4__'] = $object->thirdparty->idprof4 ?? '';
10583 $substitutionarray['__THIRDPARTY_IDPROF5__'] = $object->thirdparty->idprof5 ?? '';
10584 $substitutionarray['__THIRDPARTY_IDPROF6__'] = $object->thirdparty->idprof6 ?? '';
10585 $substitutionarray['__THIRDPARTY_TVAINTRA__'] = $object->thirdparty->tva_intra ?? '';
10586 $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = dol_htmlentitiesbr($object->thirdparty->note_public ?? '');
10587 $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = dol_htmlentitiesbr($object->thirdparty->note_private ?? '');
10588 }
10589
10590 if (is_object($object) && $object->element == 'recruitmentcandidature') {
10591 '@phan-var-force RecruitmentCandidature $object';
10593 $substitutionarray['__CANDIDATE_FULLNAME__'] = $object->getFullName($outputlangs);
10594 $substitutionarray['__CANDIDATE_FIRSTNAME__'] = isset($object->firstname) ? $object->firstname : '';
10595 $substitutionarray['__CANDIDATE_LASTNAME__'] = isset($object->lastname) ? $object->lastname : '';
10596 }
10597 if (is_object($object) && $object->element == 'conferenceorboothattendee') {
10598 '@phan-var-force ConferenceOrBoothAttendee $object';
10600 $substitutionarray['__ATTENDEE_FULLNAME__'] = $object->getFullName($outputlangs);
10601 $substitutionarray['__ATTENDEE_FIRSTNAME__'] = isset($object->firstname) ? $object->firstname : '';
10602 $substitutionarray['__ATTENDEE_LASTNAME__'] = isset($object->lastname) ? $object->lastname : '';
10603 }
10604
10605 if (is_object($object) && $object->element == 'project') {
10606 '@phan-var-force Project $object';
10608 $substitutionarray['__PROJECT_ID__'] = $object->id;
10609 $substitutionarray['__PROJECT_REF__'] = $object->ref;
10610 $substitutionarray['__PROJECT_NAME__'] = $object->title;
10611 } elseif (is_object($object)) {
10612 $project = null;
10613 if (!empty($object->project)) {
10614 $project = $object->project;
10615 }
10616 if (!is_null($project) && is_object($project)) {
10617 $substitutionarray['__PROJECT_ID__'] = $project->id;
10618 $substitutionarray['__PROJECT_REF__'] = $project->ref;
10619 $substitutionarray['__PROJECT_NAME__'] = $project->title;
10620 } else {
10621 // can substitute variables for project : uses lazy load in "make_substitutions" method
10622 $project_id = 0;
10623 if (!empty($object->fk_project) && $object->fk_project > 0) {
10624 $project_id = $object->fk_project;
10625 } elseif (!empty($object->fk_projet) && $object->fk_projet > 0) {
10626 $project_id = $object->fk_project;
10627 }
10628 if ($project_id > 0) {
10629 // path:class:method:id
10630 $substitutionarray['__PROJECT_ID__@lazyload'] = '/projet/class/project.class.php:Project:fetchAndSetSubstitution:' . $project_id;
10631 $substitutionarray['__PROJECT_REF__@lazyload'] = '/projet/class/project.class.php:Project:fetchAndSetSubstitution:' . $project_id;
10632 $substitutionarray['__PROJECT_NAME__@lazyload'] = '/projet/class/project.class.php:Project:fetchAndSetSubstitution:' . $project_id;
10633 }
10634 }
10635 }
10636
10637 if (is_object($object) && $object->element == 'facture') {
10638 '@phan-var-force Facture $object';
10640 $substitutionarray['__INVOICE_SITUATION_NUMBER__'] = isset($object->situation_counter) ? $object->situation_counter : '';
10641 }
10642 if (is_object($object) && $object->element == 'shipping') {
10643 '@phan-var-force Expedition $object';
10645 $substitutionarray['__SHIPPINGTRACKNUM__'] = $object->tracking_number;
10646 $substitutionarray['__SHIPPINGTRACKNUMURL__'] = $object->tracking_url;
10647 $substitutionarray['__SHIPPINGMETHOD__'] = $object->shipping_method;
10648 }
10649 if (is_object($object) && $object->element == 'reception') {
10650 '@phan-var-force Reception $object';
10652 $substitutionarray['__RECEPTIONTRACKNUM__'] = $object->tracking_number;
10653 $substitutionarray['__RECEPTIONTRACKNUMURL__'] = $object->tracking_url;
10654 }
10655
10656 if (is_object($object) && $object->element == 'contrat' && $object->id > 0 && is_array($object->lines)) {
10657 '@phan-var-force Contrat $object';
10659 $dateplannedstart = '';
10660 $datenextexpiration = '';
10661 foreach ($object->lines as $line) {
10662 if ($line->date_start > $dateplannedstart) {
10663 $dateplannedstart = $line->date_start;
10664 }
10665 if ($line->statut == 4 && $line->date_end && (!$datenextexpiration || $line->date_end < $datenextexpiration)) {
10666 $datenextexpiration = $line->date_end;
10667 }
10668 }
10669 $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = dol_print_date($dateplannedstart, 'day');
10670 $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE_RFC__'] = dol_print_date($dateplannedstart, 'dayrfc');
10671 $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = dol_print_date($dateplannedstart, 'standard');
10672
10673 $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = dol_print_date($datenextexpiration, 'day');
10674 $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE_RFC__'] = dol_print_date($datenextexpiration, 'dayrfc');
10675 $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = dol_print_date($datenextexpiration, 'standard');
10676 }
10677 // add substitution variables for ticket
10678 if (is_object($object) && $object->element == 'ticket') {
10679 '@phan-var-force Ticket $object';
10681 $substitutionarray['__TICKET_TRACKID__'] = $object->track_id;
10682 $substitutionarray['__TICKET_SUBJECT__'] = $object->subject;
10683 $substitutionarray['__TICKET_TYPE__'] = $object->type_code;
10684 $substitutionarray['__TICKET_SEVERITY__'] = $object->severity_code;
10685 $substitutionarray['__TICKET_CATEGORY__'] = $object->category_code; // For backward compatibility
10686 $substitutionarray['__TICKET_ANALYTIC_CODE__'] = $object->category_code;
10687 $substitutionarray['__TICKET_MESSAGE__'] = $object->message;
10688 $substitutionarray['__TICKET_PROGRESSION__'] = $object->progress;
10689 // __TICKET_TYPE__, __TICKET_SEVERITY__ and __TICKET_CATEGORY__ hold the raw codes.
10690 // An email usually needs the human readable labels instead.
10691 $substitutionarray['__TICKET_TYPE_LABEL__'] = empty($object->type_code) ? '' : $outputlangs->getLabelFromKey($db, 'TicketTypeShort'.$object->type_code, 'c_ticket_type', 'code', 'label', $object->type_code);
10692 $substitutionarray['__TICKET_SEVERITY_LABEL__'] = empty($object->severity_code) ? '' : $outputlangs->getLabelFromKey($db, 'TicketSeverityShort'.$object->severity_code, 'c_ticket_severity', 'code', 'label', $object->severity_code);
10693 $substitutionarray['__TICKET_CATEGORY_LABEL__'] = empty($object->category_code) ? '' : $outputlangs->getLabelFromKey($db, 'TicketCategoryShort'.$object->category_code, 'c_ticket_category', 'code', 'label', $object->category_code);
10694 $substitutionarray['__TICKET_PUBLIC_URL__'] = getDolGlobalString('TICKET_URL_PUBLIC_INTERFACE', dol_buildpath('/public/ticket/', 2)).'view.php?track_id='.urlencode((string) $object->track_id);
10695 $substitutionarray['__TICKET_MANAGEMENT_URL__'] = dol_buildpath('/ticket/card.php', 2).'?track_id='.urlencode((string) $object->track_id);
10696 $userstat = new User($db);
10697 if ($object->fk_user_assign > 0) {
10698 $userstat->fetch($object->fk_user_assign);
10699 $substitutionarray['__TICKET_USER_ASSIGN__'] = dolGetFirstLastname($userstat->firstname, $userstat->lastname);
10700 }
10701
10702 if ($object->fk_user_create > 0) {
10703 $userstat->fetch($object->fk_user_create);
10704 $substitutionarray['__USER_CREATE__'] = dolGetFirstLastname($userstat->firstname, $userstat->lastname);
10705 }
10706 }
10707
10708 // Create dynamic tags for __EXTRAFIELD_FIELD__
10709 if ($object->table_element && $object->id > 0) {
10710 if (!is_object($extrafields)) {
10711 $extrafields = new ExtraFields($db);
10712 }
10713 $extrafields->fetch_name_optionals_label($object->table_element, true);
10714
10715 if ($object->fetch_optionals() > 0) { // @FIXME: Remove this, the fetch should have been done already, by the caller of getCommonSubstitutionArray()
10716 if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) {
10717 foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) {
10718 if ($extrafields->attributes[$object->table_element]['type'][$key] == 'date') {
10719 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '__'] = dol_print_date($object->array_options['options_' . $key], 'day');
10720 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '_LOCALE__'] = dol_print_date($object->array_options['options_' . $key], 'day', 'tzserver', $outputlangs);
10721 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '_RFC__'] = dol_print_date($object->array_options['options_' . $key], 'dayrfc');
10722 } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'datetime') {
10723 $datetime = $object->array_options['options_' . $key];
10724 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour') : '');
10725 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour', 'tzserver', $outputlangs) : '');
10726 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '_DAY_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'day', 'tzserver', $outputlangs) : '');
10727 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '_RFC__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhourrfc') : '');
10728 } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'phone') {
10729 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '__'] = dol_print_phone($object->array_options['options_' . $key]);
10730 } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'price') {
10731 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '__'] = $object->array_options['options_' . $key];
10732 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '_FORMATED__'] = price($object->array_options['options_' . $key]); // For compatibility
10733 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '_FORMATTED__'] = price($object->array_options['options_' . $key]);
10734 } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'select') {
10735 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '__'] = !empty($object->array_options['options_' . $key]) ? $object->array_options['options_' . $key] : '';
10736 $val = $extrafields->attributes[$object->table_element]['param'][$key]['options'][$object->array_options['options_'.$key]] ?? $object->array_options['options_'.$key];
10737 $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LABEL__'] = $val;
10738 } elseif ($extrafields->attributes[$object->table_element]['type'][$key] != 'separator') {
10739 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '__'] = !empty($object->array_options['options_' . $key]) ? $object->array_options['options_' . $key] : '';
10740 }
10741 }
10742 }
10743 }
10744 }
10745
10746 // Complete substitution array with the url to make online payment
10747 if (empty($substitutionarray['__REF__'])) {
10748 $paymenturl = '';
10749 } else {
10750 // Set the online payment url link into __ONLINE_PAYMENT_URL__ key
10751 require_once DOL_DOCUMENT_ROOT . '/core/lib/payments.lib.php';
10752 $outputlangs->loadLangs(array('paypal', 'other'));
10753
10754 $amounttouse = 0;
10755 $typeforonlinepayment = 'free';
10756 if (is_object($object) && $object->element == 'commande') {
10757 $typeforonlinepayment = 'order';
10758 }
10759 if (is_object($object) && $object->element == 'facture') {
10760 $typeforonlinepayment = 'invoice';
10761 }
10762 if (is_object($object) && $object->element == 'member') {
10763 $typeforonlinepayment = 'member';
10764 if (!empty($object->last_subscription_amount)) {
10765 $amounttouse = $object->last_subscription_amount;
10766 }
10767 }
10768 if (is_object($object) && $object->element == 'contrat') {
10769 $typeforonlinepayment = 'contract';
10770 }
10771 if (is_object($object) && $object->element == 'fichinter') {
10772 $typeforonlinepayment = 'ficheinter';
10773 }
10774
10775 $url = getOnlinePaymentUrl(0, $typeforonlinepayment, $substitutionarray['__REF__'], (float) $amounttouse);
10776 $paymenturl = $url;
10777 }
10778
10779 if ($object->id > 0) {
10780 $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = ($paymenturl ? str_replace('\n', "\n", $outputlangs->trans("PredefinedMailContentLink", $paymenturl)) : '');
10781 $substitutionarray['__ONLINE_PAYMENT_URL__'] = $paymenturl;
10782
10783 // Show structured communication
10784 if (getDolGlobalString('INVOICE_PAYMENT_ENABLE_STRUCTURED_COMMUNICATION') && $object->element == 'facture') {
10785 include_once DOL_DOCUMENT_ROOT . '/core/lib/functions_be.lib.php';
10786 $substitutionarray['__PAYMENT_STRUCTURED_COMMUNICATION__'] = dolBECalculateStructuredCommunication((string) $object->ref, $object->type);
10787 }
10788
10789 if (getDolGlobalString('PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD') && is_object($object) && $object->element == 'propal') {
10790 $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
10791 } else {
10792 $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = '';
10793 }
10794 if (getDolGlobalString('ORDER_ALLOW_EXTERNAL_DOWNLOAD') && is_object($object) && $object->element == 'commande') {
10795 $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = $object->getLastMainDocLink($object->element);
10796 } else {
10797 $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = '';
10798 }
10799 if (getDolGlobalString('INVOICE_ALLOW_EXTERNAL_DOWNLOAD') && is_object($object) && $object->element == 'facture') {
10800 $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = $object->getLastMainDocLink($object->element);
10801 } else {
10802 $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = '';
10803 }
10804 if (getDolGlobalString('CONTRACT_ALLOW_EXTERNAL_DOWNLOAD') && is_object($object) && $object->element == 'contrat') {
10805 $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = $object->getLastMainDocLink($object->element);
10806 } else {
10807 $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = '';
10808 }
10809 if (getDolGlobalString('FICHINTER_ALLOW_EXTERNAL_DOWNLOAD') && is_object($object) && $object->element == 'fichinter') {
10810 $substitutionarray['__DIRECTDOWNLOAD_URL_FICHINTER__'] = $object->getLastMainDocLink($object->element);
10811 } else {
10812 $substitutionarray['__DIRECTDOWNLOAD_URL_FICHINTER__'] = '';
10813 }
10814 if (getDolGlobalString('SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD') && is_object($object) && $object->element == 'supplier_proposal') {
10815 $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
10816 } else {
10817 $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = '';
10818 }
10819 if (getDolGlobalString('SUPPLIER_ORDER_ALLOW_EXTERNAL_DOWNLOAD') && is_object($object) && $object->element == 'order_supplier') {
10820 $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_ORDER__'] = $object->getLastMainDocLink($object->element);
10821 } else {
10822 $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_ORDER__'] = '';
10823 }
10824 if (getDolGlobalString('SUPPLIER_INVOICE_ALLOW_EXTERNAL_DOWNLOAD') && is_object($object) && $object->element == 'invoice_supplier') {
10825 $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_INVOICE__'] = $object->getLastMainDocLink($object->element);
10826 } else {
10827 $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_INVOICE__'] = '';
10828 }
10829
10830 if (is_object($object) && $object->element == 'propal') {
10831 '@phan-var-force Propal $object';
10833 $substitutionarray['__URL_PROPOSAL__'] = DOL_MAIN_URL_ROOT . "/comm/propal/card.php?id=" . $object->id;
10834 require_once DOL_DOCUMENT_ROOT . '/core/lib/signature.lib.php';
10835 $substitutionarray['__ONLINE_SIGN_URL__'] = getOnlineSignatureUrl(0, 'proposal', (string) $object->ref, 1, $object);
10836 }
10837 if (is_object($object) && $object->element == 'commande') {
10838 '@phan-var-force Commande $object';
10840 $substitutionarray['__URL_ORDER__'] = DOL_MAIN_URL_ROOT . "/commande/card.php?id=" . $object->id;
10841 }
10842 if (is_object($object) && $object->element == 'facture') {
10843 '@phan-var-force Facture $object';
10845 $substitutionarray['__URL_INVOICE__'] = DOL_MAIN_URL_ROOT . "/compta/facture/card.php?id=" . $object->id;
10846 }
10847 if (is_object($object) && $object->element == 'contrat') {
10848 '@phan-var-force Contrat $object';
10850 $substitutionarray['__URL_CONTRACT__'] = DOL_MAIN_URL_ROOT . "/contrat/card.php?id=" . $object->id;
10851 require_once DOL_DOCUMENT_ROOT . '/core/lib/signature.lib.php';
10852 $substitutionarray['__ONLINE_SIGN_URL__'] = getOnlineSignatureUrl(0, 'contract', (string) $object->ref, 1, $object);
10853 }
10854 if (is_object($object) && $object->element == 'fichinter') {
10855 '@phan-var-force Fichinter $object';
10857 $substitutionarray['__URL_FICHINTER__'] = DOL_MAIN_URL_ROOT . "/fichinter/card.php?id=" . $object->id;
10858 require_once DOL_DOCUMENT_ROOT . '/core/lib/signature.lib.php';
10859 $substitutionarray['__ONLINE_SIGN_FICHINTER_URL__'] = getOnlineSignatureUrl(0, 'fichinter', (string) $object->ref, 1, $object);
10860 }
10861 if (is_object($object) && $object->element == 'supplier_proposal') {
10862 '@phan-var-force SupplierProposal $object';
10864 $substitutionarray['__URL_SUPPLIER_PROPOSAL__'] = DOL_MAIN_URL_ROOT . "/supplier_proposal/card.php?id=" . $object->id;
10865 }
10866 if (is_object($object) && $object->element == 'invoice_supplier') {
10867 '@phan-var-force FactureFournisseur $object';
10869 $substitutionarray['__URL_SUPPLIER_INVOICE__'] = DOL_MAIN_URL_ROOT . "/fourn/facture/card.php?id=" . $object->id;
10870 }
10871 if (is_object($object) && $object->element == 'payment_supplier') {
10872 '@phan-var-force PaiementFourn $object';
10874 //print_r($object);
10875 $liste_factures = [];
10876 $total = 0;
10877
10878 // @FIXME We must not have any repeated SQL access into this function.
10879 $sql = 'SELECT f.ref,f.multicurrency_code as f_mccode, pf.*
10880 FROM '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf
10881 JOIN '.MAIN_DB_PREFIX.'facture_fourn as f ON pf.fk_facturefourn = f.rowid
10882 WHERE pf.fk_paiementfourn = '.((int) $object->id);
10883
10884 $resql = $db->query($sql);
10885 if ($resql) {
10886 while ($objp = $db->fetch_object($resql)) {
10887 $liste_factures[] = ' - '.$outputlangs->trans('Invoice').' '. $objp->ref.' '.$outputlangs->trans('AmountPayed').' '.price($objp->multicurrency_amount, 0, $outputlangs, 0, -1, -1, $objp->multicurrency_code);
10888 }
10889 }
10890 $substitutionarray['__SUPPLIER_PAYMENT_INVOICES_LIST__'] = implode("\n", $liste_factures);
10891 ;
10892 $substitutionarray['__SUPPLIER_PAYMENT_INVOICES_TOTAL__'] = price($object->multicurrency_amount, 0, $outputlangs, 0, -1, -1, $object->multicurrency_code ? $object->multicurrency_code : $conf->currency);
10893 }
10894 if (is_object($object) && $object->element == 'shipping') {
10895 '@phan-var-force Expedition $object';
10897 $substitutionarray['__URL_SHIPMENT__'] = DOL_MAIN_URL_ROOT . "/expedition/card.php?id=" . $object->id;
10898 if (getDolGlobalInt('EXPEDITION_ALLOW_ONLINESIGN')) {
10899 require_once DOL_DOCUMENT_ROOT . '/core/lib/signature.lib.php';
10900 $substitutionarray['__ONLINE_SIGN_URL__'] = getOnlineSignatureUrl(0, 'expedition', (string) $object->ref, 1, $object);
10901 }
10902 }
10903 }
10904
10905 if (is_object($object) && $object->element == 'action') {
10906 '@phan-var-force ActionComm $object';
10908 $substitutionarray['__EVENT_LABEL__'] = $object->label;
10909 $substitutionarray['__EVENT_DESCRIPTION__'] = $object->note;
10910 $substitutionarray['__EVENT_TYPE__'] = $outputlangs->trans("Action" . $object->type_code);
10911 $substitutionarray['__EVENT_DATE__'] = dol_print_date($object->datep, 'day', 'auto', $outputlangs);
10912 $substitutionarray['__EVENT_TIME__'] = dol_print_date($object->datep, 'hour', 'auto', $outputlangs);
10913 $substitutionarray['__EVENT_DATE_TZUSER__'] = dol_print_date($object->datep, 'day', 'tzuserrel', $outputlangs);
10914 $substitutionarray['__EVENT_TIME_TZUSER__'] = dol_print_date($object->datep, 'hour', 'tzuserrel', $outputlangs);
10915 }
10916 }
10917 }
10918
10919 if ((empty($exclude) || !in_array('objectamount', $exclude)) && (empty($include) || in_array('objectamount', $include))) {
10920 '@phan-var-force Facture|FactureRec $object';
10922 include_once DOL_DOCUMENT_ROOT . '/core/lib/functionsnumtoword.lib.php';
10923
10924 $substitutionarray['__DATE_YMD__'] = is_object($object) ? (isset($object->date) ? dol_print_date($object->date, 'day', false, $outputlangs) : null) : '';
10925 $substitutionarray['__DATE_DUE_YMD__'] = is_object($object) ? (isset($object->date_lim_reglement) ? dol_print_date($object->date_lim_reglement, 'day', false, $outputlangs) : null) : '';
10926 $substitutionarray['__DATE_YMD_TEXT__'] = is_object($object) ? (isset($object->date) ? dol_print_date($object->date, 'daytext', false, $outputlangs) : null) : '';
10927 $substitutionarray['__DATE_DUE_YMD_TEXT__'] = is_object($object) ? (isset($object->date_lim_reglement) ? dol_print_date($object->date_lim_reglement, 'daytext', false, $outputlangs) : null) : '';
10928
10929 $already_payed_all = 0;
10930 if (is_object($object) && ($object instanceof Facture)) {
10931 $already_payed_all = $object->totalpaid + $object->totaldeposits + $object->totalcreditnotes;
10932 }
10933
10934 $substitutionarray['__SIMPLE_HTML_TABLE__'] = is_object($object) && !empty($object->lines) ? showSimpleHTMLTable($outputlangs, $object) : "";
10935 $substitutionarray['__AMOUNT_EXCL_TAX__'] = is_object($object) ? $object->total_ht : '';
10936 $substitutionarray['__AMOUNT_EXCL_TAX_TEXT__'] = is_object($object) ? dol_convertToWord($object->total_ht, $outputlangs, '', true) : '';
10937 $substitutionarray['__AMOUNT_EXCL_TAX_TEXTCURRENCY__'] = is_object($object) ? dol_convertToWord($object->total_ht, $outputlangs, $conf->currency, true) : '';
10938
10939 $substitutionarray['__AMOUNT__'] = is_object($object) ? $object->total_ttc : '';
10940 $substitutionarray['__AMOUNT_TEXT__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, '', true) : '';
10941 $substitutionarray['__AMOUNT_TEXTCURRENCY__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, $conf->currency, true) : '';
10942
10943 $substitutionarray['__DEPOSIT_PERCENT__'] = is_object($object) ? $object->deposit_percent : '';
10944 $substitutionarray['__DEPOSIT_AMOUNT__'] = is_object($object) ? price2num($object->total_ttc * ($object->deposit_percent / 100), 'MT') : '';
10945
10946 $substitutionarray['__AMOUNT_REMAIN__'] = is_object($object) ? price2num($object->total_ttc - $already_payed_all, 'MT') : '';
10947
10948 $substitutionarray['__AMOUNT_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
10949 $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)) : '';
10950 $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)) : '';
10951
10952 $mysocuselocaltax1 = false;
10953 $mysocuselocaltax2 = false;
10954 if ($mysoc instanceof Societe && !empty($mysoc->country_code)) {
10955 $tmparray = $mysoc->useLocalTax(-1);
10956 $mysocuselocaltax1 = $tmparray[1];
10957 $mysocuselocaltax2 = $tmparray[2];
10958 }
10959
10960 // Local taxes
10961 if ($onlykey != 2 || $mysocuselocaltax1) {
10962 $substitutionarray['__AMOUNT_TAX2__'] = is_object($object) ? $object->total_localtax1 : '';
10963 }
10964 if ($onlykey != 2 || $mysocuselocaltax2) {
10965 $substitutionarray['__AMOUNT_TAX3__'] = is_object($object) ? $object->total_localtax2 : '';
10966 }
10967
10968 // Amount keys formatted in a currency
10969 $substitutionarray['__AMOUNT_EXCL_TAX_FORMATTED__'] = is_object($object) ? ($object->total_ht ? price($object->total_ht, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
10970 $substitutionarray['__AMOUNT_FORMATTED__'] = is_object($object) ? ($object->total_ttc ? price($object->total_ttc, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
10971 $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) : '';
10972 $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)) : '';
10973 if ($onlykey != 2 || $mysocuselocaltax1) {
10974 $substitutionarray['__AMOUNT_TAX2_FORMATTED__'] = is_object($object) ? ($object->total_localtax1 ? price($object->total_localtax1, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
10975 }
10976 if ($onlykey != 2 || $mysocuselocaltax2) {
10977 $substitutionarray['__AMOUNT_TAX3_FORMATTED__'] = is_object($object) ? ($object->total_localtax2 ? price($object->total_localtax2, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
10978 }
10979 // Amount keys formatted in a currency (with the typo error for backward compatibility)
10980 if ($onlykey != 2) {
10981 $substitutionarray['__AMOUNT_EXCL_TAX_FORMATED__'] = $substitutionarray['__AMOUNT_EXCL_TAX_FORMATTED__'];
10982 $substitutionarray['__AMOUNT_FORMATED__'] = $substitutionarray['__AMOUNT_FORMATTED__'];
10983 $substitutionarray['__AMOUNT_REMAIN_FORMATED__'] = $substitutionarray['__AMOUNT_REMAIN_FORMATTED__'];
10984 $substitutionarray['__AMOUNT_VAT_FORMATED__'] = $substitutionarray['__AMOUNT_VAT_FORMATTED__'];
10985 if ($mysocuselocaltax1) {
10986 $substitutionarray['__AMOUNT_TAX2_FORMATED__'] = $substitutionarray['__AMOUNT_TAX2_FORMATTED__'];
10987 }
10988 if ($mysoc->useLocalTax2) {
10989 $substitutionarray['__AMOUNT_TAX3_FORMATED__'] = $substitutionarray['__AMOUNT_TAX3_FORMATTED__'];
10990 }
10991 }
10992
10993 $substitutionarray['__AMOUNT_MULTICURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? $object->multicurrency_total_ttc : '';
10994 $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) : '';
10995 $substitutionarray['__AMOUNT_MULTICURRENCY_TEXT__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, '', true) : '';
10996 $substitutionarray['__AMOUNT_MULTICURRENCY_TEXTCURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, $object->multicurrency_code, true) : '';
10997 $substitutionarray['__MULTICURRENCY_CODE__'] = (is_object($object) && isset($object->multicurrency_code)) ? $object->multicurrency_code : '';
10998 // TODO Add other keys for foreign multicurrency
10999
11000 // For backward compatibility
11001 if ($onlykey != 2) {
11002 $substitutionarray['__TOTAL_TTC__'] = is_object($object) ? $object->total_ttc : '';
11003 $substitutionarray['__TOTAL_HT__'] = is_object($object) ? $object->total_ht : '';
11004 $substitutionarray['__TOTAL_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
11005 }
11006 }
11007
11008
11009 if ((empty($exclude) || !in_array('date', $exclude)) && (empty($include) || in_array('date', $include))) {
11010 include_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
11011
11012 $now = dol_now();
11013
11014 $tmp = dol_getdate($now, true);
11015 $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
11016 $tmp3 = dol_get_prev_month($tmp['mon'], $tmp['year']);
11017 $tmp4 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
11018 $tmp5 = dol_get_next_month($tmp['mon'], $tmp['year']);
11019
11020 $daytext = $outputlangs->trans('Day' . $tmp['wday']);
11021
11022 $substitutionarray = array_merge($substitutionarray, array(
11023 '__NOW_TMS__' => (string) $now, // Must be the string that represent the int
11024 '__NOW_TMS_YMD__' => dol_print_date($now, 'day', 'auto', $outputlangs),
11025 '__DAY__' => (string) $tmp['mday'],
11026 '__DAY_TEXT__' => $daytext, // Monday
11027 '__DAY_TEXT_SHORT__' => dol_trunc($daytext, 3, 'right', 'UTF-8', 1), // Mon
11028 '__DAY_TEXT_MIN__' => dol_trunc($daytext, 1, 'right', 'UTF-8', 1), // M
11029 '__MONTH__' => (string) $tmp['mon'],
11030 '__MONTH_TEXT__' => $outputlangs->transnoentitiesnoconv('Month' . sprintf("%02d", $tmp['mon'])),
11031 '__MONTH_TEXT_SHORT__' => $outputlangs->transnoentitiesnoconv('MonthShort' . sprintf("%02d", $tmp['mon'])),
11032 '__MONTH_TEXT_MIN__' => $outputlangs->transnoentitiesnoconv('MonthVeryShort' . sprintf("%02d", $tmp['mon'])),
11033 '__YEAR__' => (string) $tmp['year'],
11034 '__YEAR_PREVIOUS_MONTH__' => (string) $tmp3['year'],
11035 '__YEAR_NEXT_MONTH__' => (string) $tmp5['year'],
11036 '__PREVIOUS_DAY__' => (string) $tmp2['day'],
11037 '__PREVIOUS_MONTH__' => (string) $tmp3['month'],
11038 '__PREVIOUS_MONTH_TEXT__' => $outputlangs->transnoentitiesnoconv('Month' . sprintf("%02d", $tmp3['month'])),
11039 '__PREVIOUS_MONTH_TEXT_SHORT__' => $outputlangs->transnoentitiesnoconv('MonthShort' . sprintf("%02d", $tmp3['month'])),
11040 '__PREVIOUS_MONTH_TEXT_MIN__' => $outputlangs->transnoentitiesnoconv('MonthVeryShort' . sprintf("%02d", $tmp3['month'])),
11041 '__PREVIOUS_YEAR__' => (string) ($tmp['year'] - 1),
11042 '__NEXT_DAY__' => (string) $tmp4['day'],
11043 '__NEXT_MONTH__' => (string) $tmp5['month'],
11044 '__NEXT_MONTH_TEXT__' => $outputlangs->transnoentitiesnoconv('Month' . sprintf("%02d", $tmp5['month'])),
11045 '__NEXT_MONTH_TEXT_SHORT__' => $outputlangs->transnoentitiesnoconv('MonthShort' . sprintf("%02d", $tmp5['month'])),
11046 '__NEXT_MONTH_TEXT_MIN__' => $outputlangs->transnoentitiesnoconv('MonthVeryShort' . sprintf("%02d", $tmp5['month'])),
11047 '__NEXT_YEAR__' => (string) ($tmp['year'] + 1),
11048 ));
11049 }
11050
11051 if (isModEnabled('multicompany')) {
11052 $substitutionarray = array_merge($substitutionarray, array('__ENTITY_ID__' => $conf->entity));
11053 }
11054 if ((empty($exclude) || !in_array('system', $exclude)) && (empty($include) || in_array('user', $include))) {
11055 $substitutionarray['__DOL_MAIN_URL_ROOT__'] = DOL_MAIN_URL_ROOT;
11056 $substitutionarray['__(AnyTranslationKey)__'] = $outputlangs->transnoentitiesnoconv('TranslationOfKey');
11057 $substitutionarray['__(AnyTranslationKey|langfile)__'] = $outputlangs->transnoentitiesnoconv('TranslationOfKey') . ' (load also language file before)';
11058 $substitutionarray['__[AnyConstantKey]__'] = $outputlangs->transnoentitiesnoconv('ValueOfConstantKey');
11059 }
11060
11061 // Note: The lazyload variables are replaced only during the call by make_substitutions, and only if necessary
11062
11063 return $substitutionarray;
11064}
11065
11082function make_substitutions($text, $substitutionarray, $outputlangs = null, $converttextinhtmlifnecessary = 0)
11083{
11084 global $db, $langs;
11085
11086 if (!is_array($substitutionarray)) {
11087 return 'ErrorBadParameterSubstitutionArrayWhenCalling_make_substitutions';
11088 }
11089
11090 if (empty($outputlangs)) {
11091 $outputlangs = $langs;
11092 }
11093
11094 // Is initial text HTML or simple text ?
11095 $msgishtml = 0;
11096 if (dol_textishtml($text, 1)) {
11097 $msgishtml = 1;
11098 }
11099
11100 // Make substitution for language keys: __(AnyTranslationKey)__ or __(AnyTranslationKey|langfile)__
11101 if (is_object($outputlangs)) {
11102 $reg = array();
11103 while (preg_match('/__\‍(([^\‍)]+)\‍)__/', $text, $reg)) {
11104 // If key is __(TranslationKey|langfile)__, then force load of langfile.lang
11105 $tmp = explode('|', $reg[1]);
11106 if (!empty($tmp[1])) {
11107 $outputlangs->load($tmp[1]);
11108 }
11109
11110 $value = $outputlangs->transnoentitiesnoconv($reg[1]);
11111
11112 if (empty($converttextinhtmlifnecessary)) {
11113 // convert $newval into HTML is necessary
11114 $text = preg_replace('/__\‍(' . preg_quote($reg[1], '/') . '\‍)__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
11115 } else {
11116 if (preg_match('/__\‍(' . preg_quote($reg[1], '/') . '\‍)__/', $text)) { // If found, so replacement will be done later
11117 if (! $msgishtml) {
11118 $valueishtml = dol_textishtml($value, 1);
11119 //var_dump("valueishtml=".$valueishtml);
11120
11121 if ($valueishtml) {
11122 $text = dol_htmlentitiesbr($text);
11123 $msgishtml = 1;
11124 }
11125 } else {
11126 $value = dol_nl2br((string) $value);
11127 }
11128 }
11129 $text = preg_replace('/__\‍(' . preg_quote($reg[1], '/') . '\‍)__/', $value, $text);
11130 }
11131 }
11132 }
11133
11134 // Make substitution for constant keys.
11135 // Must be after the substitution of translation, so if the text of translation contains a string __[xxx]__, it is also converted.
11136 $reg = array();
11137 while (preg_match('/__\[([^\]]+)\]__/', $text, $reg)) {
11138 $originalkeyfound = $reg[1];
11139 $keyfound = preg_replace('/\|urlencode$/', '', $originalkeyfound);
11140
11141 if (isASecretKey($keyfound)) {
11142 $value = '*****forbidden*****';
11143 } else {
11144 $value = getDolGlobalString($keyfound);
11145 // Execute some functions on value of substitution key
11146 if (preg_match('/\|urlencode$/', $originalkeyfound)) {
11147 $value = urlencode($value);
11148 }
11149 }
11150
11151 if (empty($converttextinhtmlifnecessary)) {
11152 // convert $newval into HTML is necessary
11153 $text = preg_replace('/__\[' . preg_quote($originalkeyfound, '/') . '\]__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
11154 } else {
11155 if (preg_match('/__\[' . preg_quote($reg[1], '/') . '\]__/', $text)) { // If found, so replacement will be done later
11156 if (! $msgishtml) {
11157 $valueishtml = dol_textishtml($value, 1);
11158
11159 if ($valueishtml) {
11160 $text = dol_htmlentitiesbr($text);
11161 $msgishtml = 1;
11162 }
11163 } else {
11164 $value = dol_nl2br((string) $value);
11165 }
11166 }
11167 $text = preg_replace('/__\[' . preg_quote($originalkeyfound, '/') . '\]__/', $value, $text);
11168 }
11169 }
11170
11171 // Make substitution for array $substitutionarray
11172 foreach ($substitutionarray as $key => $value) {
11173 if (!isset($value)) {
11174 continue; // If value is null, it same than not having substitution key at all into array, we do not replace.
11175 }
11176
11177 if (getDolGlobalString('MAIN_MAIL_DO_NOT_USE_SIGN') && ($key == '__USER_SIGNATURE__' || $key == '__SENDEREMAIL_SIGNATURE__')) {
11178 $value = ''; // Protection
11179 }
11180 if (empty($converttextinhtmlifnecessary)) {
11181 $text = str_replace((string) $key, (string) $value, $text); // Cast to string is needed when value is 123.5 for example
11182 } else {
11183 if (strpos($text, (string) $key) !== false) { // If found, so replacement will be done later
11184 if (! $msgishtml) {
11185 $valueishtml = dol_textishtml($value, 1);
11186
11187 if ($valueishtml) {
11188 $text = dol_htmlentitiesbr($text);
11189 $msgishtml = 1;
11190 }
11191 } else {
11192 $value = dol_nl2br((string) $value);
11193 }
11194 }
11195 $text = str_replace((string) $key, (string) $value, $text); // Cast to string is needed, for 123.5 for example
11196 }
11197 }
11198
11199 /*
11200 Loop to scan $substitutionarray for couples: key=__XXX__@lazyload and value='path:class:method:id' or 'path:class:method:id:keyinarrayresult' if method return array
11201 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.
11202 If no, we don't need to make replacement, so we do nothing.
11203 If yes, we can make the substitution:
11204
11205 include_once $path;
11206 $tmpobj = new $class($db);
11207 $valuetouseforsubstitution = $tmpobj->$method($id, '__XXX__');
11208 And make the replacement of "__XXX__@lazyload" with $valuetouseforsubstitution
11209 */
11210 $memory_object_list = array();
11211 foreach ($substitutionarray as $key => $value) {
11212 $lazy_load_arr = array();
11213 if (preg_match('/(__[A-Z\_]+__)@lazyload$/', $key, $lazy_load_arr)) {
11214 if (isset($lazy_load_arr[1]) && !empty($lazy_load_arr[1])) {
11215 $key_to_substitute = $lazy_load_arr[1];
11216 if (preg_match('/' . preg_quote($key_to_substitute, '/') . '/', $text)) {
11217 $param_arr = explode(':', (string) $value);
11218 // path:class:method:id
11219 if (count($param_arr) >= 4) {
11220 $path = $param_arr[0];
11221 $class = $param_arr[1];
11222 $method = $param_arr[2];
11223 $id = (int) $param_arr[3];
11224 $keyinarrayresult = empty($param_arr[4]) ? '' : $param_arr[4];
11225
11226 // load class file and init object list in memory
11227 if (!isset($memory_object_list[$class])) {
11228 if (dol_is_file(DOL_DOCUMENT_ROOT . $path)) {
11229 require_once DOL_DOCUMENT_ROOT . $path;
11230 if (class_exists($class)) {
11231 $memory_object_list[$class] = array(
11232 'list' => array(),
11233 );
11234 }
11235 }
11236 }
11237
11238 // fetch object and set substitution
11239 if (isset($memory_object_list[$class]) && isset($memory_object_list[$class]['list'])) {
11240 if (method_exists($class, $method)) {
11241 if (!isset($memory_object_list[$class]['list'][$id])) {
11242 $tmpobj = new $class($db);
11243 // @phan-suppress-next-line PhanPluginUnknownObjectMethodCall
11244 $tmpvaluetouseforsubstitution = $tmpobj->$method($id, $key_to_substitute);
11245 $memory_object_list[$class]['list'][$id] = $tmpobj;
11246 } else {
11247 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
11248 $tmpobj = $memory_object_list[$class]['list'][$id];
11249 // @phan-suppress-next-line PhanPluginUnknownObjectMethodCall
11250 $tmpvaluetouseforsubstitution = $tmpobj->$method($id, $key_to_substitute, true);
11251 }
11252
11253 if ($keyinarrayresult) {
11254 $valuetouseforsubstitution = (string) $tmpvaluetouseforsubstitution[$keyinarrayresult]; // Cast to string in case value is 123.5 for example
11255 } else {
11256 $valuetouseforsubstitution = (string) $tmpvaluetouseforsubstitution; // Cast to string in case value is 123.5 for example
11257 }
11258 $text = str_replace((string) $key_to_substitute, $valuetouseforsubstitution, $text);
11259 }
11260 }
11261 }
11262 }
11263 }
11264 }
11265 }
11266
11267 return $text;
11268}
11269
11282function complete_substitutions_array(&$substitutionarray, $outputlangs, $object = null, $parameters = null, $callfunc = "completesubstitutionarray")
11283{
11284 global $conf, $user;
11285
11286 require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
11287
11288 // Note: substitution key for each extrafields, using key __EXTRA_XXX__ is already available into the getCommonSubstitutionArray used to build the substitution array.
11289
11290 // Check if there is external substitution to do, requested by plugins
11291 $dirsubstitutions = array_merge(array(), (array) $conf->modules_parts['substitutions']);
11292
11293 foreach ($dirsubstitutions as $reldir) {
11294 $dir = dol_buildpath($reldir, 0);
11295
11296 // Check if directory exists
11297 if (!dol_is_dir($dir)) {
11298 continue;
11299 }
11300
11301 $substitfiles = dol_dir_list($dir, 'files', 0, 'functions_');
11302 foreach ($substitfiles as $substitfile) {
11303 $reg = array();
11304 if (preg_match('/functions_(.*)\.lib\.php/i', $substitfile['name'], $reg)) {
11305 $module = $reg[1];
11306
11307 dol_syslog("Library " . $substitfile['name'] . " found into " . $dir);
11308 // Include the user's functions file
11309 require_once $dir . $substitfile['name'];
11310 // Call the user's function, and only if it is defined
11311 $function_name = $module . "_" . $callfunc;
11312 if (function_exists($function_name)) {
11313 $function_name($substitutionarray, $outputlangs, $object, $parameters);
11314 }
11315 }
11316 }
11317 }
11318 if (getDolGlobalString('ODT_ENABLE_ALL_TAGS_IN_SUBSTITUTIONS')) {
11319 // to list all tags in odt template
11320 $tags = '';
11321 foreach ($substitutionarray as $key => $value) {
11322 $tags .= '{' . $key . '} => ' . $value . "\n";
11323 }
11324 $substitutionarray = array_merge($substitutionarray, array('__ALL_TAGS__' => $tags));
11325 }
11326}
11327
11337function print_date_range($date_start, $date_end, $format = '', $outputlangs = null)
11338{
11339 print get_date_range($date_start, $date_end, $format, $outputlangs);
11340}
11341
11352function get_date_range($date_start, $date_end, $format = '', $outputlangs = null, $withparenthesis = 1)
11353{
11354 global $langs;
11355
11356 $out = '';
11357
11358 if (!is_object($outputlangs)) {
11359 $outputlangs = $langs;
11360 }
11361
11362 if ($date_start && $date_end) {
11363 $out .= ($withparenthesis ? ($withparenthesis == 1 ? ' ' : '').'(' : '') . $outputlangs->transnoentitiesnoconv('DateFromTo', dol_print_date($date_start, $format, false, $outputlangs), dol_print_date($date_end, $format, false, $outputlangs)) . ($withparenthesis ? ')' : '');
11364 }
11365 if ($date_start && !$date_end) {
11366 $out .= ($withparenthesis ? ($withparenthesis == 1 ? ' ' : '').'(' : '') . $outputlangs->transnoentitiesnoconv('DateFrom', dol_print_date($date_start, $format, false, $outputlangs)) . ($withparenthesis ? ')' : '');
11367 }
11368 if (!$date_start && $date_end) {
11369 $out .= ($withparenthesis ? ($withparenthesis == 1 ? ' ' : '').'(' : '') . $outputlangs->transnoentitiesnoconv('DateUntil', dol_print_date($date_end, $format, false, $outputlangs)) . ($withparenthesis ? ')' : '');
11370 }
11371
11372 return $out;
11373}
11374
11383function dolGetFirstLastname($firstname, $lastname, $nameorder = -1)
11384{
11385 $ret = '';
11386 // If order not defined, we use the setup
11387 if ($nameorder < 0) {
11388 $nameorder = (!getDolGlobalString('MAIN_FIRSTNAME_NAME_POSITION') ? 1 : 0);
11389 }
11390 if ($nameorder == 1) {
11391 $ret .= $firstname;
11392 if ($firstname && $lastname) {
11393 $ret .= ' ';
11394 }
11395 $ret .= $lastname;
11396 } elseif ($nameorder == 2 || $nameorder == 3) {
11397 $ret .= $firstname;
11398 if (empty($ret) && $nameorder == 3) {
11399 $ret .= $lastname;
11400 }
11401 } else { // 0, 4 or 5
11402 $ret .= $lastname;
11403 if (empty($ret) && $nameorder == 5) {
11404 $ret .= $firstname;
11405 }
11406 if ($nameorder == 0) {
11407 if ($firstname && $lastname) {
11408 $ret .= ' ';
11409 }
11410 $ret .= $firstname;
11411 }
11412 }
11413 return $ret;
11414}
11415
11416
11429function setEventMessage($mesgs, $style = 'mesgs', $noduplicate = 0, $attop = 0)
11430{
11431 //dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING); This is not deprecated, it is used by setEventMessages function
11432 if (!is_array($mesgs)) {
11433 $mesgs = trim((string) $mesgs);
11434 // If mesgs is a not an empty string
11435 if ($mesgs) {
11436 if (!empty($noduplicate) && isset($_SESSION['dol_events'][$style]) && in_array($mesgs, $_SESSION['dol_events'][$style])) {
11437 return;
11438 }
11439 if ($attop) {
11440 array_unshift($_SESSION['dol_events'][$style], $mesgs);
11441 } else {
11442 $_SESSION['dol_events'][$style][] = $mesgs;
11443 }
11444 }
11445 } else {
11446 // If mesgs is an array
11447 foreach ($mesgs as $mesg) {
11448 $mesg = trim((string) $mesg);
11449 if ($mesg) {
11450 if (!empty($noduplicate) && isset($_SESSION['dol_events'][$style]) && in_array($mesg, $_SESSION['dol_events'][$style])) {
11451 return;
11452 }
11453 if ($attop) {
11454 array_unshift($_SESSION['dol_events'][$style], $mesgs);
11455 } else {
11456 $_SESSION['dol_events'][$style][] = $mesg;
11457 }
11458 }
11459 }
11460 }
11461}
11462
11476function setEventMessages($mesg, $mesgs, $style = 'mesgs', $messagekey = '', $noduplicate = 0, $attop = 0)
11477{
11478 if (empty($mesg) && empty($mesgs)) {
11479 dol_syslog("Try to add a message in stack, but value to add is empty message" . getCallerInfoString(), LOG_WARNING);
11480 } else {
11481 if ($messagekey) {
11482 // Complete message with a js link to set a cookie "DOLHIDEMESSAGE".$messagekey;
11483 // TODO
11484 $mesg .= '';
11485 }
11486 if (empty($messagekey) || empty($_COOKIE["DOLUSER_HIDEMESSAGE" . $messagekey])) {
11487 if (!in_array((string) $style, array('mesgs', 'warnings', 'errors'))) {
11488 dol_print_error(null, 'Bad parameter style=' . $style . ' for setEventMessages');
11489 }
11490 if (empty($mesgs)) {
11491 setEventMessage((string) $mesg, $style, $noduplicate, $attop);
11492 } else {
11493 if (!empty($mesg) && !in_array($mesg, $mesgs)) {
11494 setEventMessage($mesg, $style, $noduplicate, $attop); // Add message string if not already into array
11495 }
11496 setEventMessage($mesgs, $style, $noduplicate, $attop);
11497 }
11498 }
11499 }
11500}
11501
11511function dol_htmloutput_events($disabledoutputofmessages = 0)
11512{
11513 // Show mesgs
11514 if (isset($_SESSION['dol_events']['mesgs'])) {
11515 if (empty($disabledoutputofmessages)) {
11516 dol_htmloutput_mesg('', $_SESSION['dol_events']['mesgs']);
11517 }
11518 unset($_SESSION['dol_events']['mesgs']);
11519 }
11520 // Show errors
11521 if (isset($_SESSION['dol_events']['errors'])) {
11522 if (empty($disabledoutputofmessages)) {
11523 dol_htmloutput_mesg('', $_SESSION['dol_events']['errors'], 'error');
11524 }
11525 unset($_SESSION['dol_events']['errors']);
11526 }
11527
11528 // Show warnings
11529 if (isset($_SESSION['dol_events']['warnings'])) {
11530 if (empty($disabledoutputofmessages)) {
11531 dol_htmloutput_mesg('', $_SESSION['dol_events']['warnings'], 'warning');
11532 }
11533 unset($_SESSION['dol_events']['warnings']);
11534 }
11535}
11536
11551function get_htmloutput_mesg($mesgstring = '', $mesgarray = [], $style = 'ok', $keepembedded = 0)
11552{
11553 global $conf, $langs;
11554
11555 $ret = 0;
11556 $return = '';
11557 $out = '';
11558 $divstart = $divend = '';
11559
11560 // If inline message with no format, we add it.
11561 if ((empty($conf->use_javascript_ajax) || getDolGlobalString('MAIN_DISABLE_JQUERY_JNOTIFY') || defined('DISABLE_JQUERY_JNOTIFY') || $keepembedded) && !preg_match('/<div class=".*">/i', $out)) {
11562 $divstart = '<div class="' . $style . ' clearboth">';
11563 $divend = '</div>';
11564 }
11565
11566 if ((is_array($mesgarray) && count($mesgarray)) || $mesgstring) {
11567 $langs->load("errors");
11568 $out .= $divstart;
11569 if (is_array($mesgarray) && count($mesgarray)) {
11570 foreach ($mesgarray as $message) {
11571 $ret++;
11572 $out .= $langs->trans($message);
11573 if ($ret < count($mesgarray)) {
11574 $out .= "<br>\n";
11575 }
11576 }
11577 }
11578 if ($mesgstring) {
11579 $ret++;
11580 $out .= $langs->trans($mesgstring);
11581 }
11582 $out .= $divend;
11583 }
11584
11585 if ($out) {
11586 if (!empty($conf->use_javascript_ajax) && !getDolGlobalString('MAIN_DISABLE_JQUERY_JNOTIFY') && !defined('DISABLE_JQUERY_JNOTIFY') && empty($keepembedded)) {
11587 $return = '<script nonce="' . getNonce() . '">
11588 $(document).ready(function() {
11589 /* jnotify(message, preset of message type, keepmessage) */
11590 $.jnotify("' . dol_escape_js($out) . '", "' . ($style == "ok" ? 3000 : $style) . '", ' . ($style == "ok" ? "false" : "true") . ',{ remove: function (){} } );
11591 });
11592 </script>';
11593 } else {
11594 $return = $out;
11595 }
11596 }
11597
11598 return $return;
11599}
11600
11612function get_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
11613{
11614 return get_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
11615}
11616
11630function dol_htmloutput_mesg($mesgstring = '', $mesgarray = array(), $style = 'ok', $keepembedded = 0)
11631{
11632 if (empty($mesgstring) && (!is_array($mesgarray) || count($mesgarray) == 0)) {
11633 return;
11634 }
11635
11636 $iserror = 0;
11637 $iswarning = 0;
11638 if (is_array($mesgarray)) {
11639 foreach ($mesgarray as $val) {
11640 if ($val && preg_match('/class="error"/i', $val)) {
11641 $iserror++;
11642 break;
11643 }
11644 if ($val && preg_match('/class="warning"/i', $val)) {
11645 $iswarning++;
11646 break;
11647 }
11648 }
11649 } elseif ($mesgstring && preg_match('/class="error"/i', $mesgstring)) {
11650 $iserror++;
11651 } elseif ($mesgstring && preg_match('/class="warning"/i', $mesgstring)) {
11652 $iswarning++;
11653 }
11654 if ($style == 'error' || $style == 'errors') {
11655 $iserror++;
11656 }
11657 if ($style == 'warning' || $style == 'warnings') {
11658 $iswarning++;
11659 }
11660
11661 if ($iserror || $iswarning) {
11662 // Remove div from texts
11663 $mesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $mesgstring);
11664 $mesgstring = preg_replace('/<div class="(error|warning)">/', '', $mesgstring);
11665 $mesgstring = preg_replace('/<\/div>/', '', $mesgstring);
11666 // Remove div from texts array
11667 if (is_array($mesgarray)) {
11668 $newmesgarray = array();
11669 foreach ($mesgarray as $val) {
11670 if (is_string($val)) {
11671 $tmpmesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $val);
11672 $tmpmesgstring = preg_replace('/<div class="(error|warning)">/', '', $tmpmesgstring);
11673 $tmpmesgstring = preg_replace('/<\/div>/', '', $tmpmesgstring);
11674 $newmesgarray[] = $tmpmesgstring;
11675 } else {
11676 dol_syslog("Error call of dol_htmloutput_mesg with an array with a value that is not a string", LOG_WARNING);
11677 }
11678 }
11679 $mesgarray = $newmesgarray;
11680 }
11681 print get_htmloutput_mesg($mesgstring, $mesgarray, ($iserror ? 'error' : 'warning'), $keepembedded);
11682 } else {
11683 print get_htmloutput_mesg($mesgstring, $mesgarray, 'ok', $keepembedded);
11684 }
11685}
11686
11698function dol_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
11699{
11700 dol_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
11701}
11702
11710function dolSort($arraytosort)
11711{
11712 sort($arraytosort);
11713 return $arraytosort;
11714}
11715
11737function dol_sort_array(&$array, $index, $order = 'asc', $natsort = 0, $case_sensitive = 0, $keepindex = 0)
11738{
11739 // Clean parameters
11740 $order = strtolower($order);
11741
11742 if (is_array($array)) {
11743 $sizearray = count($array);
11744 if ($sizearray > 0) {
11745 // Build a temp array with sorting key as value
11746 $temp = array();
11747 foreach (array_keys($array) as $key) {
11748 $tmpmultikey = explode(',', $index);
11749 $newindex = $tmpmultikey[0];
11750 if (is_object($array[$key])) {
11751 $temp[$key] = empty($array[$key]->$newindex) ? 0 : $array[$key]->$newindex;
11752 // Add other keys
11753 if (!empty($tmpmultikey[1])) {
11754 $newindex = $tmpmultikey[1];
11755 $temp[$key] .= '__' . (empty($array[$key]->$newindex) ? 0 : $array[$key]->$newindex);
11756 }
11757 } else {
11758 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable,PhanTypeArraySuspicious,PhanTypeMismatchDimFetch
11759 $temp[$key] = empty($array[$key][$newindex]) ? 0 : $array[$key][$newindex];
11760 // Add other keys
11761 if (!empty($tmpmultikey[1])) {
11762 $newindex = $tmpmultikey[1];
11763 // @phan-suppress-next-line PhanTypeArraySuspicious,PhanTypeMismatchDimFetch
11764 $temp[$key] .= '__' . (empty($array[$key][$newindex]) ? 0 : $array[$key][$newindex]);
11765 }
11766 }
11767 if ($natsort == -1) {
11768 $temp[$key] = '___' . $temp[$key]; // We add a string at begin of value to force an alpha order when using asort.
11769 }
11770 }
11771 if (empty($natsort) || $natsort == -1) {
11772 if ($order == 'asc') {
11773 asort($temp);
11774 } else {
11775 arsort($temp);
11776 }
11777 } else {
11778 if ($case_sensitive) {
11779 natsort($temp);
11780 } else {
11781 natcasesort($temp); // natecasesort is not sensible to case
11782 }
11783 if ($order != 'asc') {
11784 $temp = array_reverse($temp, true);
11785 }
11786 }
11787
11788 $sorted = array();
11789
11790 foreach (array_keys($temp) as $key) {
11791 (is_numeric($key) && empty($keepindex)) ? $sorted[] = $array[$key] : $sorted[$key] = $array[$key];
11792 }
11793
11794 return $sorted;
11795 }
11796 }
11797 return $array;
11798}
11799
11800
11808function utf8_check($str)
11809{
11810 $str = (string) $str; // Sometimes string is an int.
11811
11812 // We must use here a binary strlen function (so not dol_strlen)
11813 $strLength = strlen($str);
11814 for ($i = 0; $i < $strLength; $i++) {
11815 if (ord($str[$i]) < 0x80) {
11816 continue; // 0bbbbbbb
11817 } elseif ((ord($str[$i]) & 0xE0) == 0xC0) {
11818 $n = 1; // 110bbbbb
11819 } elseif ((ord($str[$i]) & 0xF0) == 0xE0) {
11820 $n = 2; // 1110bbbb
11821 } elseif ((ord($str[$i]) & 0xF8) == 0xF0) {
11822 $n = 3; // 11110bbb
11823 } elseif ((ord($str[$i]) & 0xFC) == 0xF8) {
11824 $n = 4; // 111110bb
11825 } elseif ((ord($str[$i]) & 0xFE) == 0xFC) {
11826 $n = 5; // 1111110b
11827 } else {
11828 return false; // Does not match any model
11829 }
11830 for ($j = 0; $j < $n; $j++) { // n bytes matching 10bbbbbb follow ?
11831 if ((++$i == strlen($str)) || ((ord($str[$i]) & 0xC0) != 0x80)) {
11832 return false;
11833 }
11834 }
11835 }
11836 return true;
11837}
11838
11846function utf8_valid($str)
11847{
11848 /* 2 other methods to test if string is utf8
11849 $validUTF8 = mb_check_encoding($messagetext, 'UTF-8');
11850 $validUTF8b = ! (false === mb_detect_encoding($messagetext, 'UTF-8', true));
11851 */
11852 return preg_match('//u', $str) ? true : false;
11853}
11854
11855
11862function ascii_check($str)
11863{
11864 if (function_exists('mb_check_encoding')) {
11865 //if (mb_detect_encoding($str, 'ASCII', true) return false;
11866 if (!mb_check_encoding($str, 'ASCII')) {
11867 return false;
11868 }
11869 } else {
11870 if (preg_match('/[^\x00-\x7f]/', $str)) {
11871 return false; // Contains a byte > 7f
11872 }
11873 }
11874
11875 return true;
11876}
11877
11878
11886function dol_osencode($str)
11887{
11888 $tmp = ini_get("unicode.filesystem_encoding");
11889 if (empty($tmp) && !empty($_SERVER["WINDIR"])) {
11890 $tmp = 'iso-8859-1'; // By default for windows
11891 }
11892 if (empty($tmp)) {
11893 $tmp = 'utf-8'; // By default for other
11894 }
11895 if (getDolGlobalString('MAIN_FILESYSTEM_ENCODING')) {
11896 $tmp = getDolGlobalString('MAIN_FILESYSTEM_ENCODING');
11897 }
11898
11899 if ($tmp == 'iso-8859-1') {
11900 return mb_convert_encoding($str, 'ISO-8859-1', 'UTF-8');
11901 }
11902 return $str;
11903}
11904
11905
11921function dol_getIdFromCode($db, $key, $tablename, $fieldkey = 'code', $fieldid = 'id', $entityfilter = 0, $filters = '', $useCache = true)
11922{
11923 global $conf;
11924
11925 // If key empty
11926 if ($key == '') {
11927 return 0;
11928 }
11929
11930 // Check in cache
11931 if ($useCache && isset($conf->cache['codeid'][$tablename][$key][$fieldid])) { // Can be defined to 0 or ''
11932 return $conf->cache['codeid'][$tablename][$key][$fieldid]; // Found in cache
11933 }
11934
11935 dol_syslog('dol_getIdFromCode (value for field ' . $fieldid . ' from key ' . $key . ' not found into cache)', LOG_DEBUG);
11936
11937 $sql = "SELECT " . $db->sanitize($fieldid) . " as valuetoget";
11938 $sql .= " FROM " . MAIN_DB_PREFIX . $db->sanitize($tablename);
11939 if ($fieldkey == 'id' || $fieldkey == 'rowid') {
11940 $sql .= " WHERE " . $db->sanitize($fieldkey) . " = " . ((int) $key);
11941 } else {
11942 $sql .= " WHERE " . $db->sanitize($fieldkey) . " = '" . $db->escape($key) . "'";
11943 }
11944 if (!empty($entityfilter)) {
11945 $sql .= " AND entity IN (" . getEntity($tablename) . ")";
11946 }
11947 if ($filters) {
11948 $sql .= $filters; // @phan-suppress-current-line SqlInjection
11949 }
11950
11951 $resql = $db->query($sql);
11952 if ($resql) {
11953 $obj = $db->fetch_object($resql);
11954 $valuetoget = '';
11955 if ($obj) {
11956 $valuetoget = $obj->valuetoget;
11957 $conf->cache['codeid'][$tablename][$key][$fieldid] = $valuetoget;
11958 } else {
11959 $conf->cache['codeid'][$tablename][$key][$fieldid] = '';
11960 }
11961 $db->free($resql);
11962
11963 return $valuetoget;
11964 } else {
11965 return -1;
11966 }
11967}
11968
11978function isStringVarMatching($var, $regextext, $matchrule = 1)
11979{
11980 // Tolerate callers (custom modules, older code) that already pass a full regex with delimiters
11981 // like '/^(aaa|bbb)/' instead of the bare body. Without this, the function would build
11982 // '/^/^(aaa|bbb)//' which trips preg_match() with 'Unknown modifier ^'.
11983 $regextext = preg_replace('#^/\^?#', '', (string) $regextext);
11984 $regextext = preg_replace('#\$?/[imsxuADSUXJ]*$#', '', $regextext);
11985
11986 if ($matchrule == 1) {
11987 if ($var == 'mainmenu') {
11988 global $mainmenu;
11989 return (preg_match('/^' . $regextext . '/', $mainmenu));
11990 } elseif ($var == 'leftmenu') {
11991 global $leftmenu;
11992 return (preg_match('/^' . $regextext . '/', $leftmenu));
11993 } else {
11994 return 'This variable is not accessible with dol_eval';
11995 }
11996 } else {
11997 return 'This value '.$matchrule.' for param $matchrule is not yet implemented';
11998 }
11999}
12000
12001
12011function verifCond($strToEvaluate, $onlysimplestring = '1')
12012{
12013 //print $strToEvaluate."<br>\n";
12014 $rights = true;
12015 if (isset($strToEvaluate) && $strToEvaluate !== '') {
12016 //var_dump($strToEvaluate);
12017 //$rep = dol_eval($strToEvaluate, 1, 0, '1'); // to show the error
12018 $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
12019
12020 // On string syntax error, dol_eval may return a string that start with 'Bad call of ...' or 'Bad string syntax to evaluate...' !!!
12021 //var_dump($strToEvaluate, $rep);
12022 $rights = (bool) $rep && (!is_string($rep) || (strpos($rep, 'Exception during') === false && strpos($rep, 'Bad call of') === false && strpos($rep, 'Bad string syntax to evaluate') === false));
12023 //var_dump($rights);
12024 }
12025 return $rights;
12026}
12027
12043function dol_eval($s, $returnvalue = 1, $hideerrors = 1, $onlysimplestring = '1')
12044{
12045 if ($returnvalue != 1) {
12046 dol_syslog("Use of dol_eval with parameter returnvalue = 0 is now forbidden. Please fix this", LOG_ERR);
12047 }
12048
12049 global $dolibarr_main_use_dol_eval_new; // experimental option, not yet ready
12050 if (!empty($dolibarr_main_use_dol_eval_new)) {
12051 return dol_eval_new($s);
12052 } else {
12053 return dol_eval_standard($s, $hideerrors, $onlysimplestring);
12054 }
12055}
12056
12067function dol_eval_new($s)
12068{
12069 // Only this global variables can be read by eval function and returned to caller
12070 global $conf, // Read of const is done with getDolGlobalString() but we need $conf->currency for example
12071 $db, $langs, $user, $website, $websitepage,
12072 $action, $mainmenu, $leftmenu,
12073 $mysoc,
12074 $objectoffield, // To allow the use of $objectoffield in computed fields
12075
12076 // Old variables used
12077 $object;
12078
12079 if (getDolGlobalString('MAIN_ALLOW_OLD_VAR_OBJ_IN_DOL_EVAL')) {
12080 global $obj; // To get $obj used into list when dol_eval() is used for computed fields and $obj is not yet $object
12081 }
12082
12083 // PHP < 7.4.0
12084 defined('T_COALESCE_EQUAL') || define('T_COALESCE_EQUAL', PHP_INT_MAX);
12085 defined('T_FN') || define('T_FN', PHP_INT_MAX);
12086
12087 // PHP < 8.0.0
12088 defined('T_ATTRIBUTE') || define('T_ATTRIBUTE', PHP_INT_MAX);
12089 defined('T_MATCH') || define('T_MATCH', PHP_INT_MAX);
12090 defined('T_NAME_FULLY_QUALIFIED') || define('T_NAME_FULLY_QUALIFIED', PHP_INT_MAX);
12091 defined('T_NAME_QUALIFIED') || define('T_NAME_QUALIFIED', PHP_INT_MAX);
12092 defined('T_NAME_RELATIVE') || define('T_NAME_RELATIVE', PHP_INT_MAX);
12093
12094 // PHP < 8.1.0
12095 defined('T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG') || define('T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG', PHP_INT_MAX);
12096 defined('T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG') || define('T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG', PHP_INT_MAX);
12097 defined('T_ENUM') || define('T_ENUM', PHP_INT_MAX);
12098 defined('T_READONLY') || define('T_READONLY', PHP_INT_MAX);
12099
12100 // PHP < 8.4.0
12101 defined('T_PRIVATE_SET') || define('T_PRIVATE_SET', PHP_INT_MAX);
12102 defined('T_PROTECTED_SET') || define('T_PROTECTED_SET', PHP_INT_MAX);
12103 defined('T_PUBLIC_SET') || define('T_PUBLIC_SET', PHP_INT_MAX);
12104
12105 $prohibited_token_ids = [
12106 /*
12107 * Prohibited int tokens
12108 */
12109
12110 // T_AND_EQUAL', 'T_ARRAY', 'T_ARRAY_CAST', 'T_AS',
12111 'T_ABSTRACT',
12112 'T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG',
12113 'T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG',
12114 'T_ATTRIBUTE',
12115 // 'T_BOOLEAN_AND', 'T_BOOLEAN_OR', 'T_BOOL_CAST', 'T_BREAK',
12116 'T_BAD_CHARACTER',
12117 // 'T_CASE', 'T_CLASS_C', 'T_CLONE', 'T_COALESCE', 'T_COALESCE_EQUAL', 'T_COMMENT', 'T_CONCAT_EQUAL',
12118 // 'T_CONSTANT_ENCAPSED_STRING', 'T_CONTINUE', 'T_CURLY_OPEN',
12119 'T_CALLABLE',
12120 'T_CATCH',
12121 'T_CLASS',
12122 'T_CLOSE_TAG',
12123 'T_CONST',
12124 // 'T_DEC', 'T_DEFAULT', 'T_DIV_EQUAL', 'T_DNUMBER', 'T_DO', 'T_DOC_COMMENT',
12125 // 'T_DOLLAR_OPEN_CURLY_BRACES', 'T_DOUBLE_ARROW', 'T_DOUBLE_CAST', 'T_DOUBLE_COLON',
12126 'T_DECLARE',
12127 'T_DIR',
12128 // 'T_ELLIPSIS', 'T_ELSE', 'T_ELSEIF', 'T_EMPTY', 'T_ENCAPSED_AND_WHITESPACE', 'T_ENDFOR',
12129 // 'T_ENDFOREACH', 'T_ENDIF', 'T_ENDSWITCH', 'T_ENDWHILE', 'T_END_HEREDOC',
12130 'T_ECHO',
12131 'T_ENDDECLARE',
12132 'T_ENUM',
12133 'T_EVAL',
12134 'T_EXIT',
12135 'T_EXTENDS',
12136 // 'T_FOR', 'T_FOREACH',
12137 'T_FILE',
12138 'T_FINAL',
12139 'T_FINALLY',
12140 'T_FN',
12141 'T_FUNCTION',
12142 'T_FUNC_C',
12143 'T_GLOBAL',
12144 'T_GOTO',
12145 'T_HALT_COMPILER',
12146 // 'T_IF', 'T_INC', 'T_INLINE_HTML', 'T_INSTANCEOF', 'T_INT_CAST', 'T_ISSET', 'T_IS_EQUAL', 'T_IS_GREATER_OR_EQUAL',
12147 // 'T_IS_IDENTICAL', 'T_IS_NOT_EQUAL', 'T_IS_NOT_IDENTICAL', 'T_IS_SMALLER_OR_EQUAL',
12148 'T_IMPLEMENTS',
12149 'T_INCLUDE',
12150 'T_INCLUDE_ONCE',
12151 'T_INSTEADOF',
12152 'T_INTERFACE',
12153 // 'T_LIST', 'T_LNUMBER', 'T_LOGICAL_AND', 'T_LOGICAL_OR', 'T_LOGICAL_XOR',
12154 'T_LINE',
12155 // 'T_MINUS_EQUAL', 'T_MOD_EQUAL', 'T_MUL_EQUAL',
12156 'T_METHOD_C',
12157 // 'T_NEW',
12158 // 'T_NS_SEPARATOR', 'T_NUM_STRING',
12159 'T_NAMESPACE',
12160 // 'T_NAME_FULLY_QUALIFIED', 'T_NAME_QUALIFIED', 'T_NAME_RELATIVE', 'T_NS_C',
12161 // 'T_OBJECT_CAST', 'T_OBJECT_OPERATOR', 'T_OR_EQUAL',
12162 'T_OPEN_TAG',
12163 'T_OPEN_TAG_WITH_ECHO',
12164 // 'T_PAAMAYIM_NEKUDOTAYIM', 'T_PLUS_EQUAL', 'T_POW', 'T_POW_EQUAL',
12165 'T_PRINT',
12166 'T_PRIVATE',
12167 'T_PROTECTED',
12168 'T_PUBLIC',
12169 // 'T_PROPERTY_C',
12170 'T_READONLY',
12171 'T_REQUIRE',
12172 'T_REQUIRE_ONCE',
12173 'T_RETURN',
12174 // 'T_SL', 'T_SL_EQUAL', 'T_SPACESHIP', 'T_SR', 'T_SR_EQUAL', 'T_START_HEREDOC', 'T_STATIC',
12175 // 'T_STRING', 'T_STRING_CAST', 'T_STRING_VARNAME', 'T_SWITCH',
12176 'T_STATIC',
12177 'T_THROW',
12178 'T_TRAIT',
12179 'T_TRAIT_C',
12180 'T_TRY',
12181 'T_UNSET',
12182 'T_UNSET_CAST',
12183 'T_USE',
12184 // 'T_VARIABLE',
12185 'T_VAR',
12186 // 'T_WHILE', 'T_WHITESPACE',
12187 // 'T_XOR_EQUAL',
12188 // 'T_YIELD', 'T_YIELD_FROM',
12189
12190 /*
12191 * Prohibited string tokens
12192 */
12193 ';',
12194 '`',
12195 ];
12196
12197 $prohibited_variables = [
12198 '$_COOKIE',
12199 '$_ENV',
12200 '$_FILES',
12201 '$GLOBALS',
12202 '$_GET',
12203 '$_POST',
12204 '$_REQUEST',
12205 '$_SERVER',
12206 '$_SESSION',
12207 ];
12208
12209 $forbiddenphpfunctions = array();
12210 $forbiddenphpmethods = array();
12211
12212 // Same list than in dol_eval
12213 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("override_function", "session_id", "session_create_id", "session_regenerate_id"));
12214 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("get_defined_functions", "get_defined_vars", "get_defined_constants", "get_declared_classes"));
12215 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("function"));
12216
12217 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("GETPOST")); // native dolibarr functions
12218
12219 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("ob_start"));
12220
12221 // Functions with callable parameters
12222 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("call_user_func", "call_user_func_array"));
12223 $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"));
12224 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("usort", "uasort", "uksort"));
12225 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("preg_replace_callback", "preg_replace_callback_array", "header_register_callback"));
12226 $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"));
12227 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("spl_autoload_register", "spl_autoload_unregister", "iterator_apply", "session_set_save_handler"));
12228 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("forward_static_call", "forward_static_call_array", "register_postsend_function"));
12229 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("readline_completion_function", "readline_callback_handler_install"));
12230
12231 // Exec functions
12232 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("exec", "passthru", "shell_exec", "system", "proc_open", "popen"));
12233 $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"));
12234 $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", ));
12235 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("putenv", "dl", "apache_child_terminate", "apache_setenv"));
12236 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("dol_eval", "dol_eval_new", "dol_eval_standard", "executeCLI", "verifCond", "dolEncrypt", "dolDecrypt")); // native dolibarr functions
12237 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("eval", "create_function", "assert", "mb_ereg_replace")); // function with eval capabilities
12238
12239 // Include functions
12240 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("require", "include", "require_once", "include_once"));
12241
12242 $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
12243 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("chdir", "dir", "fopen", "file", "file_exists", "file_get_contents", "file_put_contents", "fget", "fgetc", "fgetcsv", "flock", "fputs", "fputscsv", "fpassthru", "fscanf", "fseek", "fwrite", "is_file", "is_dir", "is_link", "mkdir", "opendir", "rmdir", "scandir", "symlink", "touch", "unlink", "umask"));
12244
12245 if (!getDolGlobalString('MAIN_ALLOW_OBFUSCATION_METHODS_IN_DOL_EVAL')) { // We disallow all function that allow to obfuscate the real name of a function
12246 // @phpcs:ignore
12247 $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
12248 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("dol_concat", "dol_concatdesc")); // native dolibarr functions
12249 }
12250
12251 $forbiddenphpmethods = array_merge($forbiddenphpmethods, array('invoke', 'invokeArgs')); // Methods of ReflectionFunction to execute a function
12252
12253 $prohibited_functions = array_merge($forbiddenphpfunctions, $forbiddenphpmethods);
12254
12255 $prohibited_token_arrangements = [
12256 // Variable functions "$a(", '"$a"(', "'FN_NAME'(", ('FN_NAME')()
12257 ' T_VARIABLE ( ',
12258 ' " ( ',
12259 ' \' ( ',
12260 ' T_CONSTANT_ENCAPSED_STRING ( ',
12261 ' ) ( ',
12262 ];
12263
12264 $tokens = token_get_all("<?php return {$s};", TOKEN_PARSE);
12265
12266 $tokens_arrangement = ' ';
12267
12268 for ($i = 2, $c = count($tokens) - 1; $i < $c; ++$i) { // ignore <?php return and ;
12269 if (is_array($tokens[$i])) {
12270 $token_id = $tokens[$i][0];
12271 $token_value = $tokens[$i][1];
12272 $token_name = token_name($tokens[$i][0]);
12273 } else {
12274 $token_id = $tokens[$i];
12275 $token_value = $tokens[$i];
12276 $token_name = $tokens[$i];
12277 }
12278
12279 // Ignore whitespaces
12280 if (T_WHITESPACE === $token_id) {
12281 continue;
12282 }
12283
12284 // Keep history to check arrangements
12285 $tokens_arrangement .= "{$token_name} ";
12286
12287 // Prohibited Variables
12288 if (
12289 T_VARIABLE === $token_id
12290 && in_array($token_value, $prohibited_variables, true)
12291 ) {
12292 return "Bad string syntax to evaluate. « {$token_value} » is prohibited in « {$s} »";
12293 }
12294
12295 // Prohibited Functions
12296 if (
12297 T_STRING === $token_id
12298 && in_array($token_value, $prohibited_functions, true)
12299 ) {
12300 return "Bad string syntax to evaluate. « {$token_value} » is prohibited in « {$s} »";
12301 }
12302 }
12303
12304 // Prohibited Token IDs
12305 $maxi = count($prohibited_token_ids);
12306 for ($i = 0; $i < $maxi; ++$i) {
12307 if (false !== strpos($tokens_arrangement, " {$prohibited_token_ids[$i]} ")) {
12308 return "Bad string syntax to evaluate. « {$prohibited_token_ids[$i]} » is prohibited in « {$s} »";
12309 }
12310 }
12311
12312 // Prohibited token arrangements
12313 $maxi = count($prohibited_token_arrangements);
12314 for ($i = 0; $i < $maxi; ++$i) {
12315 if (false !== strpos($tokens_arrangement, $prohibited_token_arrangements[$i])) {
12316 return "Bad string syntax to evaluate. « {$prohibited_token_arrangements[$i]} » is prohibited in « {$s} »";
12317 }
12318 }
12319
12320 // Return result
12321 try {
12322 return @eval("return {$s};") ?? '';
12323 } catch (Throwable $ex) {
12324 return "Bad string syntax to evaluate. Exception during evaluation: " . $s . " - " . $ex->getMessage();
12325 }
12326}
12327
12342function dol_eval_standard($s, $hideerrors = 1, $onlysimplestring = '1')
12343{
12344 // Only this global variables can be read by eval function and returned to caller
12345 // The less we have, the better it is.
12346
12347 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()
12348 global $db, $langs, $user, $website, $websitepage;
12349 global $action, $mainmenu, $leftmenu;
12350 global $mysoc;
12351 global $objectoffield; // To allow the use of $objectoffield in computed fields
12352 global $object;
12353
12354 // Old variables (deprecated since v23)
12355 if (getDolGlobalString('MAIN_ALLOW_OLD_VAR_OBJ_IN_DOL_EVAL')) {
12356 global $obj; // To get $obj used into list when dol_eval() is used for computed fields and $obj is not yet $objectoffield
12357 }
12358
12359 $isObBufferActive = false; // When true, the ObBuffer must be cleaned in the exception handler
12360 if ($onlysimplestring == '0') { // '0' is deprecated, we process it as the more secured '1'
12361 $onlysimplestring = '1';
12362 }
12363 if (!in_array($onlysimplestring, array('1', '2'))) {
12364 return "Bad call of dol_eval. Parameter onlysimplestring must be '1' or '2'.";
12365 }
12366 if (!is_scalar($s)) {
12367 return "Bad call of dol_eval. First parameter must be a string, found ".var_export($s, true);
12368 }
12369
12370 try {
12371 global $dolibarr_main_restrict_eval_methods;
12372
12373 // Set $dolibarr_main_restrict_eval_methods_array
12374 if (!isset($dolibarr_main_restrict_eval_methods)) {
12375 $dolibarr_main_restrict_eval_methods = 'getDolGlobalString, getDolGlobalInt, getDolCurrency, getDolEntity, getDolDBType, fetchNoCompute, hasRight, isAdmin, isExternalUser, isModEnabled, isStringVarMatching, abs, min, max, round, dol_now, preg_match';
12376 }
12377 //print '$dolibarr_main_restrict_eval_methods = '.$dolibarr_main_restrict_eval_methods."\n";
12378 $dolibarr_main_restrict_eval_methods_array = explode(',', str_replace(" ", "", $dolibarr_main_restrict_eval_methods));
12379
12380 // Test on dangerous char (used for RCE), we allow only characters to make PHP variable testing
12381 // We must accept with 1: '1 && getDolGlobalInt("doesnotexist1") && getDolGlobalString("MAIN_FEATURES_LEVEL")'
12382 // We must accept with 1: '$user->hasRight("cabinetmed", "read") && !$objectoffield->canvas == "patient@cabinetmed"'
12383 // 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"
12384
12385 // Check if there is dynamic call (first we check chars are all into a whitelist chars)
12386 $specialcharsallowed = '^$_+-.*>&|=!?():"\',/@';
12387 if ($onlysimplestring == '2') {
12388 $specialcharsallowed .= '<[]'; // Later we check that < has space before and after
12389 }
12390 global $dolibarr_main_allow_unsecured_special_chars_in_dol_eval;
12391 if (!empty($dolibarr_main_allow_unsecured_special_chars_in_dol_eval)) {
12392 $specialcharsallowed .= (string) $dolibarr_main_allow_unsecured_special_chars_in_dol_eval;
12393 }
12394 if (preg_match('/[^a-z0-9\s' . preg_quote($specialcharsallowed, '/') . ']/i', $s)) {
12395 return 'Bad string syntax to evaluate (found chars that are not chars for a simple one line clean eval string): ' . $s;
12396 }
12397
12398 // Check if we found a | without a space before and after
12399 /* Disabled to allow preg_match('/(AAA|BBB)/')
12400 $tmps = str_replace(' || ', '__XXX__', $s);
12401 if (strpos($tmps, '|') !== false) {
12402 return 'Bad string syntax to evaluate (The char | can be used only when duplicated || with a space before and after): ' . $s;
12403 }
12404 */
12405
12406 // Check if there is PHP comments (can be used to obfuscate code)
12407 if (strpos($s, '/*') !== false || strpos($s, '//') !== false) {
12408 return 'Bad string syntax to evaluate (The comment string /* and // are not allowed): ' . $s;
12409 }
12410
12411 // Check if we found a ? without a space before and after
12412 $tmps = str_replace(' ? ', '__XXX__', $s);
12413 if (strpos($tmps, '?') !== false) {
12414 return 'Bad string syntax to evaluate (The char ? can be used only with a space before and after): ' . $s;
12415 }
12416
12417 // Check if there is a < or <= without spaces after
12418 if (preg_match('/<=?[^\s]/', $s)) {
12419 return 'Bad string syntax to evaluate (mode ' . $onlysimplestring . ', found a < or <= without space after): ' . $s;
12420 }
12421
12422 // Check if there is an include or a require
12423 if (preg_match('/(include|include_once|require|require_once)/', $s)) {
12424 return 'Bad string syntax to evaluate (found not allowed key include|include_once|require|require_once): ' . $s;
12425 }
12426
12427 // Check if there is dynamic call (first we use black list patterns)
12428 if (preg_match('/\$[\w]*\s*\‍(/', $s)) {
12429 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;
12430 }
12431
12432 if (empty($dolibarr_main_restrict_eval_methods)) {
12433 // If $dolibarr_main_restrict_eval_methods was set to '', we must check if we try dynamic call
12434
12435 // First we remove white list pattern of using parenthesis then testing if one open parenthesis exists
12436 $savescheck = '';
12437 $scheck = $s;
12438 while ($scheck && $savescheck != $scheck) {
12439 $savescheck = $scheck;
12440 $scheck = preg_replace('/->[a-zA-Z0-9_]+\‍(/', '->__METHOD__', $scheck); // accept parenthesis in '...->method(...'
12441 $scheck = preg_replace('/::[a-zA-Z0-9_]+\‍(/', '->__METHOD__', $scheck); // accept parenthesis in '...::method(...'
12442 $scheck = preg_replace('/^\‍(+/', '__PARENTHESIS__ ', $scheck); // accept parenthesis in '(...'. Must replace with "__PARENTHESIS__ with a space after "to allow following substitutions
12443 $scheck = preg_replace('/\&\&\s+\‍(/', '__ANDPARENTHESIS__ ', $scheck); // accept parenthesis in '&& ('. Must replace with "__PARENTHESIS__ with a space after" to allow following substitutions
12444 $scheck = preg_replace('/\|\|\s+\‍(/', '__ORPARENTHESIS__ ', $scheck); // accept parenthesis in '|| ('. Must replace with "__PARENTHESIS__ with a space after" to allow following substitutions
12445 $scheck = preg_replace('/^!?[a-zA-Z0-9_]+\‍(/', '__FUNCTION__', $scheck); // accept parenthesis in 'function(' and '!function('
12446 $scheck = preg_replace('/\s!?[a-zA-Z0-9_]+\‍(/', '__FUNCTION__', $scheck); // accept parenthesis in '... function(' and '... !function('
12447 $scheck = preg_replace('/^!\‍(/', '__NOTANDPARENTHESIS__', $scheck); // accept parenthesis in '!('
12448 $scheck = preg_replace('/\s!\‍(/', ' __NOTANDPARENTHESIS__', $scheck); // accept parenthesis in '... !('
12449 $scheck = preg_replace('/(\^|\')\‍(/', '__REGEXSTART__', $scheck); // To allow preg_match('/^(aaa|bbb)/'... or isStringVarMatching('leftmenu', '(aaa|bbb)')
12450 }
12451 //print 'scheck='.$scheck." : ".strpos($scheck, '(')."<br>\n";
12452
12453 // Now test if it remains 1 open parenthesis.
12454 if (strpos($scheck, '(') !== false) {
12455 return 'Bad string syntax to evaluate (mode ' . $onlysimplestring . ', found call of a function or method without using the direct name of the function): ' . $s;
12456 }
12457 }
12458
12459 if (strpos($s, '`') !== false) {
12460 return 'Bad string syntax to evaluate (backtick char is forbidden): ' . $s;
12461 }
12462
12463 // Disallow also concat operator
12464 if (!getDolGlobalString('MAIN_ALLOW_OBFUSCATION_METHODS_IN_DOL_EVAL')) {
12465 if (preg_match('/[^0-9]+\.[^0-9]+/', $s)) { // We refuse . if not between 2 numbers
12466 return 'Bad string syntax to evaluate (dot char is forbidden if not strictly between 2 numbers): ' . $s;
12467 }
12468 }
12469
12470 // We exclude string using a $ character that are not an expected global or temporary vars, so that are not:
12471 // $db, $langs, $leftmenu, $topmenu, $user, $langs, $objectoffield, $var....
12472 $savescheck = '';
12473 $scheck = $s;
12474 while ($scheck && $savescheck != $scheck) {
12475 $savescheck = $scheck;
12476 $scheck = preg_replace('/\$conf->[a-z\_]+->enabled/', '__VARCONFENABLED__', $scheck); // Remove this once $user->module->enabled has been replaced everywhere with isModEnabled.
12477 $scheck = preg_replace('/\$user->id/', '__VARUSERID__', $scheck);
12478 $scheck = preg_replace('/\$user->hasRight/', '__VARUSERHASRIGHT__', $scheck);
12479 $scheck = preg_replace('/\$user->rights/', '__VARUSERHASRIGHT__', $scheck); // Remove this once $user->rights->xxx is replaced everywhere with $user->hasRight()
12480 $scheck = preg_replace('/\$user->isAdmin/', '__VARUSERHASRIGHT__', $scheck);
12481 $scheck = preg_replace('/\$user->admin/', '__VARUSERISADMIN__', $scheck); // Remove this once $user->admin is replaced everywhere with $user->isAdmin()
12482 $scheck = preg_replace('/\$user->isExternalUser/', '__VARUSERSOCID__', $scheck);
12483 $scheck = preg_replace('/\$user->socid/', '__VARUSERSOCID__', $scheck); // Remove this once $user->admin is replaced everywhere with $user->isExternalUser()
12484 $scheck = preg_replace('/\‍(\$db\‍)/', '__VARDB__', $scheck);
12485 $scheck = preg_replace('/\$langs/', '__VARLANGSTRANS__', $scheck);
12486 $scheck = preg_replace('/\$mysoc/', '__VARMYSOC__', $scheck);
12487 $scheck = preg_replace('/\$action/', '__VARACTION__', $scheck);
12488 $scheck = preg_replace('/\$mainmenu/', '__VARMAINMENU__', $scheck); // Remove this once all tests on $mainmenu has been replaced with isStringVarMatching
12489 $scheck = preg_replace('/\$leftmenu/', '__VARLEFTMENU__', $scheck); // Remove this once all tests on $mainmenu has been replaced with isStringVarMatching
12490 $scheck = preg_replace('/\$websitepage/', '__VARWEBSITEPAGE__', $scheck);
12491 $scheck = preg_replace('/\$website/', '__VARWEBSITE__', $scheck);
12492 $scheck = preg_replace('/\$objectoffield/', '__VAROBJECTOFFIELD__', $scheck);
12493 $scheck = preg_replace('/\$object/', '__VAROBJECT__', $scheck);
12494 $scheck = preg_replace('/\$var/', '__VARVAR__', $scheck);
12495
12496 // deprecated (now we use $objecf->canvas or $objectoffield->canvas)
12497 $scheck = preg_replace('/\$soc->canvas/', '__VARSOCCANVAS__', $scheck);
12498 $scheck = preg_replace('/\$obj->canvas/', '__VAROBJCANVAS__', $scheck);
12499
12500 // Now test if it remains one '$'
12501 if (strpos($scheck, '$') !== false) {
12502 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);
12503 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;
12504 }
12505 }
12506
12507 // We block use of php exec or php file functions
12508 $forbiddenphpstrings = array('_ENV', '_SESSION', '_COOKIE', '_GET', '_GLOBAL', '_POST', '_REQUEST', 'ReflectionFunction', 'SplFileObject', 'SplTempFileObject');
12509
12510 if (empty($dolibarr_main_restrict_eval_methods)) { // If forced to ''
12511 // 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)
12512 // 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
12513 // like we can do with array_map and its callable parameter: dol_eval('json_encode(array_map(implode("",["ex","ec"]), ["id"]))', 1, 1, '0')
12514 $forbiddenphpfunctions = array();
12515 $forbiddenphpmethods = array();
12516
12517 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("override_function", "session_id", "session_create_id", "session_regenerate_id"));
12518 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("get_defined_functions", "get_defined_vars", "get_defined_constants", "get_declared_classes"));
12519 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("function"));
12520
12521 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("GETPOST")); // native dolibarr functions
12522
12523 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("ob_start"));
12524
12525 // Functions with callable parameters
12526 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("call_user_func", "call_user_func_array"));
12527 $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"));
12528 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("usort", "uasort", "uksort"));
12529 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("preg_replace_callback", "preg_replace_callback_array", "header_register_callback"));
12530 $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"));
12531 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("spl_autoload_register", "spl_autoload_unregister", "iterator_apply", "session_set_save_handler"));
12532 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("forward_static_call", "forward_static_call_array", "register_postsend_function"));
12533 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("readline_completion_function", "readline_callback_handler_install"));
12534
12535 // Exec functions
12536 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("exec", "passthru", "shell_exec", "system", "proc_open", "popen"));
12537 $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"));
12538 $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", ));
12539 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("putenv", "dl", "apache_child_terminate", "apache_setenv"));
12540 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("dol_eval", "dol_eval_new", "dol_eval_standard", "executeCLI", "verifCond", "dolEncrypt", "dolDecrypt")); // native dolibarr functions
12541 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("eval", "create_function", "assert", "mb_ereg_replace")); // function with eval capabilities
12542
12543 // Include functions
12544 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("require", "include", "require_once", "include_once"));
12545
12546 $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
12547 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("chdir", "dir", "fopen", "file", "file_exists", "file_get_contents", "file_put_contents", "fget", "fgetc", "fgetcsv", "flock", "fputs", "fputscsv", "fpassthru", "fscanf", "fseek", "fwrite", "is_file", "is_dir", "is_link", "mkdir", "opendir", "rmdir", "scandir", "symlink", "touch", "unlink", "umask"));
12548
12549 if (!getDolGlobalString('MAIN_ALLOW_OBFUSCATION_METHODS_IN_DOL_EVAL')) { // We disallow all function that allow to obfuscate the real name of a function
12550 // @phpcs:ignore
12551 $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
12552 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("dol_concat", "dol_concatdesc")); // native dolibarr functions
12553 }
12554 // Remove from blacklist the function that are into the whitelist
12555 /*foreach ($forbiddenphpfunctions as $key => $forbiddenphpfunction) {
12556 if (in_array($forbiddenphpfunction, $dolibarr_main_restrict_eval_methods_array)) {
12557 unset($forbiddenphpfunctions[$key]);
12558 }
12559 }*/
12560
12561 $forbiddenphpmethods = array_merge($forbiddenphpmethods, array('invoke', 'invokeArgs')); // Methods of ReflectionFunction to execute a function
12562 // Remove from blacklist the function that are into the whitelist
12563 /*foreach ($forbiddenphpmethods as $key => $forbiddenphpmethod) {
12564 if (in_array($forbiddenphpmethod, $dolibarr_main_restrict_eval_methods_array)) {
12565 unset($forbiddenphpmethods[$key]);
12566 }
12567 }*/
12568
12569 $forbiddenphpregex = 'global\s*\$';
12570 $forbiddenphpregex .= '|posix_[a-zA-Z0-9_]*|'; // All posix functions
12571 $forbiddenphpregex .= '\b(' . implode('|', $forbiddenphpfunctions) . ')\b';
12572
12573 $forbiddenphpmethodsregex = '->(' . implode('|', $forbiddenphpmethods) . ')';
12574
12575 // Now scan all forbidden patterns
12576 do {
12577 $oldstringtoclean = $s;
12578 $s = str_ireplace($forbiddenphpstrings, '__forbiddenstring__', $s);
12579 $s = preg_replace('/' . $forbiddenphpregex . '/i', '__forbiddenstring__', $s);
12580 $s = preg_replace('/' . $forbiddenphpmethodsregex . '/i', '__forbiddenstring__', $s);
12581 //$s = preg_replace('/\$[a-zA-Z0-9_\->\$]+\‍(/i', '', $s); // Remove $function( call and $mycall->mymethod(
12582 } while ($oldstringtoclean != $s);
12583
12584 if (strpos($s, '__forbiddenstring__') !== false) {
12585 dol_syslog('Bad string syntax to evaluate: ' . $s, LOG_WARNING);
12586 return 'Bad string syntax to evaluate: ' . $s;
12587 }
12588 }
12589
12590 if (!empty($dolibarr_main_restrict_eval_methods)) {
12591 // Accept only white-listed allowed function and classes
12592 // TODO Get all pattern '/([\s\w]+)\‍(/', then check that $matches[1] is a defined class or a function into a given list
12593 $pattern = '/([\s\w\'\]\"]+)\‍(/';
12594
12595 $matches = array();
12596 preg_match_all($pattern, $s, $matches);
12597
12598 if (count($matches)) {
12599 foreach ($matches[1] as $m) {
12600 $m = trim($m);
12601 if (empty($m)) {
12602 continue;
12603 }
12604 $reg = array();
12605 if (!preg_match('/new ([A-Z][\w]+)/i', $m, $reg)) {
12606 if (!in_array($m, $dolibarr_main_restrict_eval_methods_array)) {
12607 if ($m != "'" && $m != '"') {
12608 dol_syslog('Bad string syntax to evaluate: ' . $s, LOG_WARNING);
12609 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;
12610 }
12611 }
12612 } else {
12613 if (!class_exists($reg[1])) {
12614 dol_syslog('Bad string syntax to evaluate: Class "'.$reg[1].'" does not exist. ' . $s, LOG_WARNING);
12615 return 'Bad string syntax to evaluate. Class "'.$reg[1].'" does not exist. ' . $s;
12616 }
12617 $parents = class_parents($reg[1]); // Get list of parent classes of class we want to check
12618 if (!in_array('CommonObject', $parents)) { // Only classes that inherit CommonObject are ok. This forbid dangerous classes like ReflectionFunction, SplFileObject, ...
12619 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);
12620 return 'Bad string syntax to evaluate. Class "'.$reg[1].'" is not allowed because only classes extended CommonObject can be used in dynamic evaluation. ' . $s;
12621 }
12622 }
12623 }
12624 }
12625
12626 $forbiddenphpregex = 'global\s*\$';
12627 $forbiddenphpregex .= '|'; // or
12628 $forbiddenphpregex .= '}\s*\[';
12629 $forbiddenphpregex .= '|'; // or
12630 $forbiddenphpregex .= '\‍)\s*\‍(';
12631
12632 // Now scan all forbidden patterns
12633 do {
12634 $oldstringtoclean = $s;
12635 $s = str_ireplace($forbiddenphpstrings, '__forbiddenstring__', $s);
12636 $s = preg_replace('/' . $forbiddenphpregex . '/i', '__forbiddenstring__', $s);
12637 //$s = preg_replace('/' . $forbiddenphpmethodsregex . '/i', '__forbiddenstring__', $s);
12638 //$s = preg_replace('/\$[a-zA-Z0-9_\->\$]+\‍(/i', '', $s); // Remove $function( call and $mycall->mymethod(
12639 } while ($oldstringtoclean != $s);
12640
12641 if (strpos($s, '__forbiddenstring__') !== false) {
12642 dol_syslog('Bad string syntax to evaluate: ' . $s, LOG_WARNING);
12643 return 'Bad string syntax to evaluate: ' . $s;
12644 }
12645 }
12646
12647 //print $s."<br>\n";
12648 ob_start(); // An evaluation has no reason to output data
12649 $isObBufferActive = true;
12650 $tmps = $hideerrors ? @eval('return ' . $s . ';') : eval('return ' . $s . ';');
12651 $tmpo = ob_get_clean(); // This close the buffer
12652 $isObBufferActive = false;
12653 if ($tmpo) {
12654 print 'Bad string syntax to evaluate. Some data were output when it should not when evaluating: ' . $s;
12655 }
12656 return $tmps;
12657 } catch (Exception $e) {
12658 if ($isObBufferActive) {
12659 // Clean up buffer which was left behind due to exception.
12660 $tmpo = ob_get_clean(); // This close the buffer
12661 $isObBufferActive = false;
12662 }
12663 $error = 'dol_eval try/catch error for string: ' . $s . ' - Error: ';
12664 $error .= $e->getMessage();
12665 dol_syslog($error, LOG_WARNING);
12666 return 'Exception during evaluation: ' . $s;
12667 } catch (Error $e) {
12668 if ($isObBufferActive) {
12669 // Clean up buffer which was left behind due to exception.
12670 $tmpo = ob_get_clean(); // This close the buffer
12671 $isObBufferActive = false;
12672 }
12673 $error = 'dol_eval try/catch error for string: ' . $s . ' - Error: ';
12674 $error .= $e->getMessage();
12675 dol_syslog($error, LOG_WARNING);
12676 return 'Exception during evaluation: ' . $s;
12677 }
12678}
12679
12687function dol_validElement($element)
12688{
12689 return (trim($element) != '');
12690}
12691
12700function picto_from_langcode($codelang, $moreatt = '', $notitlealt = 0)
12701{
12702 if (empty($codelang)) {
12703 return '';
12704 }
12705
12706 if ($codelang == 'auto') {
12707 return '<span class="fa fa-language"></span>';
12708 }
12709
12710 $langtocountryflag = array(
12711 'ar_AR' => '',
12712 'ca_ES' => 'catalonia',
12713 'da_DA' => 'dk',
12714 'fr_CA' => 'mq',
12715 'sv_SV' => 'se',
12716 'sw_SW' => 'unknown',
12717 'AQ' => 'unknown',
12718 'CW' => 'unknown',
12719 'IM' => 'unknown',
12720 'JE' => 'unknown',
12721 'MF' => 'unknown',
12722 'BL' => 'unknown',
12723 'SX' => 'unknown'
12724 );
12725
12726 if (isset($langtocountryflag[$codelang])) {
12727 $flagImage = $langtocountryflag[$codelang];
12728 } else {
12729 $tmparray = explode('_', $codelang);
12730 $flagImage = empty($tmparray[1]) ? $tmparray[0] : $tmparray[1];
12731 }
12732
12733 $morecss = '';
12734 $reg = array();
12735 if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
12736 $morecss = $reg[1];
12737 $moreatt = "";
12738 }
12739
12740 // return img_picto_common($codelang, 'flags/'.strtolower($flagImage).'.png', $moreatt, 0, $notitlealt);
12741 return '<span class="flag-sprite ' . strtolower($flagImage) . ($morecss ? ' ' . $morecss : '') . '"' . ($moreatt ? ' ' . $moreatt : '') . (!$notitlealt ? ' title="' . $codelang . '"' : '') . '></span>';
12742}
12743
12751function getLanguageCodeFromCountryCode($countrycode)
12752{
12753 global $mysoc;
12754
12755 if (empty($countrycode)) {
12756 return null;
12757 }
12758
12759 if (strtoupper($countrycode) == 'MQ') {
12760 return 'fr_CA';
12761 }
12762 if (strtoupper($countrycode) == 'SE') {
12763 return 'sv_SE'; // se_SE is Sami/Sweden, and we want in priority sv_SE for SE country
12764 }
12765 if (strtoupper($countrycode) == 'CH') {
12766 if ($mysoc->country_code == 'FR') {
12767 return 'fr_CH';
12768 }
12769 if ($mysoc->country_code == 'DE') {
12770 return 'de_CH';
12771 }
12772 if ($mysoc->country_code == 'IT') {
12773 return 'it_CH';
12774 }
12775 }
12776
12777 // Locale list taken from:
12778 // http://stackoverflow.com/questions/3191664/
12779 // list-of-all-locales-and-their-short-codes
12780 $locales = array(
12781 'af-ZA',
12782 'am-ET',
12783 'ar-AE',
12784 'ar-BH',
12785 'ar-DZ',
12786 'ar-EG',
12787 'ar-IQ',
12788 'ar-JO',
12789 'ar-KW',
12790 'ar-LB',
12791 'ar-LY',
12792 'ar-MA',
12793 'ar-OM',
12794 'ar-QA',
12795 'ar-SA',
12796 'ar-SY',
12797 'ar-TN',
12798 'ar-YE',
12799 //'as-IN', // Moved after en-IN
12800 'ba-RU',
12801 'be-BY',
12802 'bg-BG',
12803 'bn-BD',
12804 //'bn-IN', // Moved after en-IN
12805 'bo-CN',
12806 'br-FR',
12807 'ca-ES',
12808 'co-FR',
12809 'cs-CZ',
12810 'cy-GB',
12811 'da-DK',
12812 'de-AT',
12813 'de-CH',
12814 'de-DE',
12815 'de-LI',
12816 'de-LU',
12817 'dv-MV',
12818 'el-GR',
12819 'en-AU',
12820 'en-BZ',
12821 'en-CA',
12822 'en-GB',
12823 'en-IE',
12824 'en-IN',
12825 'as-IN', // as-IN must be after en-IN (en in priority if country is IN)
12826 'bn-IN', // bn-IN must be after en-IN (en in priority if country is IN)
12827 'en-JM',
12828 'en-MY',
12829 'en-NZ',
12830 'en-PH',
12831 'en-SG',
12832 'en-TT',
12833 'en-US',
12834 'en-ZA',
12835 'en-ZW',
12836 'es-AR',
12837 'es-BO',
12838 'es-CL',
12839 'es-CO',
12840 'es-CR',
12841 'es-DO',
12842 'es-EC',
12843 'es-ES',
12844 'es-GT',
12845 'es-HN',
12846 'es-MX',
12847 'es-NI',
12848 'es-PA',
12849 'es-PE',
12850 'es-PR',
12851 'es-PY',
12852 'es-SV',
12853 'es-US',
12854 'es-UY',
12855 'es-VE',
12856 'et-EE',
12857 'eu-ES',
12858 'fa-IR',
12859 'fi-FI',
12860 'fo-FO',
12861 'fr-BE',
12862 'fr-CA',
12863 'fr-CH',
12864 'fr-FR',
12865 'fr-LU',
12866 'fr-MC',
12867 'fy-NL',
12868 'ga-IE',
12869 'gd-GB',
12870 'gl-ES',
12871 'gu-IN',
12872 'he-IL',
12873 'hi-IN',
12874 'hr-BA',
12875 'hr-HR',
12876 'hu-HU',
12877 'hy-AM',
12878 'id-ID',
12879 'ig-NG',
12880 'ii-CN',
12881 'is-IS',
12882 'it-CH',
12883 'it-IT',
12884 'ja-JP',
12885 'ka-GE',
12886 'kk-KZ',
12887 'kl-GL',
12888 'km-KH',
12889 'kn-IN',
12890 'ko-KR',
12891 'ky-KG',
12892 'lb-LU',
12893 'lo-LA',
12894 'lt-LT',
12895 'lv-LV',
12896 'mi-NZ',
12897 'mk-MK',
12898 'ml-IN',
12899 'mn-MN',
12900 'mr-IN',
12901 'ms-BN',
12902 'ms-MY',
12903 'mt-MT',
12904 'nb-NO',
12905 'ne-NP',
12906 'nl-BE',
12907 'nl-NL',
12908 'nn-NO',
12909 'oc-FR',
12910 'or-IN',
12911 'pa-IN',
12912 'pl-PL',
12913 'ps-AF',
12914 'pt-BR',
12915 'pt-PT',
12916 'rm-CH',
12917 'ro-MD',
12918 'ro-RO',
12919 'ru-RU',
12920 'rw-RW',
12921 'sa-IN',
12922 'se-FI',
12923 'se-NO',
12924 'se-SE',
12925 'si-LK',
12926 'sk-SK',
12927 'sl-SI',
12928 'sq-AL',
12929 'sv-FI',
12930 'sv-SE',
12931 'sw-KE',
12932 'ta-IN',
12933 'te-IN',
12934 'th-TH',
12935 'tk-TM',
12936 'tn-ZA',
12937 'tr-TR',
12938 'tt-RU',
12939 'ug-CN',
12940 'uk-UA',
12941 'ur-PK',
12942 'vi-VN',
12943 'wo-SN',
12944 'xh-ZA',
12945 'yo-NG',
12946 'zh-CN',
12947 'zh-HK',
12948 'zh-MO',
12949 'zh-SG',
12950 'zh-TW',
12951 'zu-ZA',
12952 );
12953
12954 $buildprimarykeytotest = strtolower($countrycode) . '-' . strtoupper($countrycode);
12955 if (in_array($buildprimarykeytotest, $locales)) {
12956 return strtolower($countrycode) . '_' . strtoupper($countrycode);
12957 }
12958
12959 if (function_exists('locale_get_primary_language') && function_exists('locale_get_region')) { // Need extension php-intl
12960 foreach ($locales as $locale) {
12961 $locale_language = locale_get_primary_language($locale);
12962 $locale_region = locale_get_region($locale);
12963 if (strtoupper($countrycode) == $locale_region) {
12964 //var_dump($locale.' - '.$locale_language.' - '.$locale_region);
12965 return strtolower($locale_language) . '_' . strtoupper($locale_region);
12966 }
12967 }
12968 } else {
12969 dol_syslog("Warning Extension php-intl is not available", LOG_WARNING);
12970 }
12971
12972 return null;
12973}
12974
13005function complete_head_from_modules($conf, $langs, $object, &$head, &$h, $type, $mode = 'add', $filterorigmodule = '')
13006{
13007 global $hookmanager, $db;
13008
13009 if (isset($conf->modules_parts['tabs'][$type]) && is_array($conf->modules_parts['tabs'][$type])) {
13010 foreach ($conf->modules_parts['tabs'][$type] as $value) {
13011 $values = explode(':', $value);
13012
13013 $reg = array();
13014 if ($mode == 'add' && !preg_match('/^\-/', $values[1])) {
13015 if (count($values) !== 6) {
13016 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);
13017 continue;
13018 }
13019
13020 // new declaration with permissions:
13021 // $value='objecttype:+tabname1:Title1:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
13022 // $value='objecttype:+tabname1:Title1,class,pathfile,method:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
13023 if ($values[0] != $type) {
13024 continue;
13025 }
13026
13027 $newtab = array();
13028 $postab = $h;
13029 // detect if position set in $values[1] ie : +(2)mytab@mymodule (first tab is 0, second is one, ...)
13030 $str = $values[1];
13031 $posstart = strpos($str, '(');
13032 if ($posstart > 0) {
13033 $posend = strpos($str, ')');
13034 if ($posstart > 0) {
13035 $res1 = substr($str, $posstart + 1, $posend - $posstart - 1);
13036 if (is_numeric($res1)) {
13037 $postab = (int) $res1;
13038 $values[1] = '+' . substr($str, $posend + 1);
13039 }
13040 }
13041 }
13042
13043 global $objectoffield; // So we can use $objectoffield int verifCond
13044 $objectoffield = $object;
13045
13046 if (!verifCond($values[4], '2')) {
13047 continue;
13048 }
13049
13050 if ($values[3]) {
13051 if ($filterorigmodule) { // If a filter of module origin has been requested
13052 if (strpos($values[3], '@')) { // This is an external module
13053 if ($filterorigmodule != 'external') {
13054 continue;
13055 }
13056 } else { // This looks a core module
13057 if ($filterorigmodule != 'core') {
13058 continue;
13059 }
13060 }
13061 }
13062 $langs->load($values[3]);
13063 }
13064
13065 if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
13066 // If label is "SUBSTITUION_..."
13067 $substitutionarray = array();
13068 complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey' => $values[2]));
13069 $label = make_substitutions($reg[1], $substitutionarray);
13070 } else {
13071 // If label is "Label,Class,File,Method", we call the method to show content inside the badge
13072 $labeltemp = explode(',', $values[2]);
13073 $label = $langs->trans($labeltemp[0]);
13074
13075 if (!empty($labeltemp[1]) && is_object($object) && !empty($object->id)) {
13076 dol_include_once($labeltemp[2]);
13077 $classtoload = $labeltemp[1];
13078 if (class_exists($classtoload)) {
13079 $obj = new $classtoload($db);
13080 $function = $labeltemp[3];
13081 if ($obj && $function && method_exists($obj, $function)) {
13082 // @phan-suppress-next-line PhanPluginUnknownObjectMethodCall
13083 $nbrec = $obj->$function($object->id, $obj);
13084 if (!empty($nbrec)) {
13085 $label .= '<span class="badge marginleftonlyshort">' . $nbrec . '</span>';
13086 }
13087 }
13088 }
13089 }
13090 }
13091 $url = preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[5]);
13092 $link = parse_url($url);
13093 $query = [];
13094 if (isset($link['query'])) {
13095 parse_str($link['query'], $query);
13096 }
13097 $newtab[0] = dolBuildUrl(dol_buildpath($link['path'], 1), $query);
13098 $newtab[1] = $label;
13099 $newtab[2] = str_replace('+', '', $values[1]);
13100 $h++;
13101
13102 // set tab at its position
13103 $head = array_merge(array_slice($head, 0, $postab), array($newtab), array_slice($head, $postab));
13104 } elseif ($mode == 'remove' && preg_match('/^\-/', $values[1])) {
13105 if ($values[0] != $type) {
13106 continue;
13107 }
13108 $tabname = str_replace('-', '', $values[1]);
13109 foreach ($head as $key => $val) {
13110 $condition = (!empty($values[3]) ? verifCond($values[3], '2') : 1);
13111 //var_dump($key.' - '.$tabname.' - '.$head[$key][2].' - '.$values[3].' - '.$condition);
13112 if ($head[$key][2] == $tabname && $condition) {
13113 unset($head[$key]);
13114 break;
13115 }
13116 }
13117 }
13118 }
13119 }
13120
13121 // No need to make a return $head. Var is modified as a reference
13122 if (!empty($hookmanager)) {
13123 $parameters = array('object' => $object, 'mode' => $mode, 'head' => &$head, 'filterorigmodule' => $filterorigmodule, 'type' => $type);
13124 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable
13125 $reshook = $hookmanager->executeHooks('completeTabsHead', $parameters, $object);
13126 if ($reshook > 0) { // Hook ask to replace completely the array
13127 $head = $hookmanager->resArray;
13128 } else { // Hook
13129 $head = array_merge($head, $hookmanager->resArray);
13130 }
13131 $h = count($head);
13132 }
13133}
13134
13146function printCommonFooter($zone = 'private')
13147{
13148 global $conf, $hookmanager, $user, $langs;
13149 global $action;
13150 global $micro_start_time;
13151
13152 if ($zone == 'private') {
13153 print "\n" . '<!-- Common footer for private page -->' . "\n";
13154 } else {
13155 print "\n" . '<!-- Common footer for public page -->' . "\n";
13156 }
13157
13158 // A div to store page_y POST parameter so we can read it using javascript
13159 print "\n<!-- A div to store page_y POST parameter -->\n";
13160 print '<div id="page_y" style="display: none;">' . (GETPOST('page_y') ? GETPOST('page_y') : '') . '</div>' . "\n";
13161
13162 $parameters = array('zone' => $zone);
13163 $tmpobject = null;
13164 // @phan-suppress-next-line PhanPluginConstantVariableNull
13165 $reshook = $hookmanager->executeHooks('printCommonFooter', $parameters, $tmpobject, $action); // Note that $action and $object may have been modified by some hooks
13166 if (empty($reshook)) {
13167 if (getDolGlobalString('MAIN_HTML_FOOTER')) {
13168 print getDolGlobalString('MAIN_HTML_FOOTER') . "\n";
13169 }
13170
13171 print "\n";
13172 if (!empty($conf->use_javascript_ajax)) {
13173 print "\n<!-- A script section to add menuhider handler on backoffice, manage focus and mandatory fields, tuning info, ... -->\n";
13174 print '<script>' . "\n";
13175 print 'jQuery(document).ready(function() {' . "\n";
13176
13177 if ($zone == 'private' && empty($conf->dol_use_jmobile)) {
13178 print "\n";
13179 print '/* JS CODE TO ENABLE to manage handler to switch left menu page (menuhider) */' . "\n";
13180 print 'jQuery("li.menuhider").click(function(event) {';
13181 print ' if (!$( "body" ).hasClass( "sidebar-collapse" )){ event.preventDefault(); }' . "\n";
13182 print ' console.log("We click on .menuhider");' . "\n";
13183 print ' $("body").toggleClass("sidebar-collapse")' . "\n";
13184 print '});' . "\n";
13185 }
13186
13187 // Management of focus and mandatory for fields
13188 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"])))) {
13189 print '/* JS CODE TO ENABLE to manage focus and mandatory form fields */' . "\n";
13190 $relativepathstring = $_SERVER["PHP_SELF"];
13191 // Clean $relativepathstring
13192 if (constant('DOL_URL_ROOT')) {
13193 $relativepathstring = preg_replace('/^' . preg_quote(constant('DOL_URL_ROOT'), '/') . '/', '', $relativepathstring);
13194 }
13195 $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
13196 $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
13197 //$tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
13198
13199 if (!empty($user->default_values[$relativepathstring]['focus'])) {
13200 foreach ($user->default_values[$relativepathstring]['focus'] as $defkey => $defval) {
13201 $qualified = 0;
13202 if ($defkey != '_noquery_') {
13203 $tmpqueryarraytohave = explode('&', $defkey);
13204 $foundintru = 0;
13205 foreach ($tmpqueryarraytohave as $tmpquerytohave) {
13206 $tmpquerytohaveparam = explode('=', $tmpquerytohave);
13207 //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
13208 if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) {
13209 $foundintru = 1;
13210 }
13211 }
13212 if (!$foundintru) {
13213 $qualified = 1;
13214 }
13215 //var_dump($defkey.'-'.$qualified);
13216 } else {
13217 $qualified = 1;
13218 }
13219
13220 if ($qualified) {
13221 print 'console.log("set the focus by executing jQuery(...).focus();")' . "\n";
13222 foreach ($defval as $paramkey => $paramval) {
13223 // Set focus on field
13224 print 'jQuery("input[name=\'' . $paramkey . '\']").focus();' . "\n";
13225 print 'jQuery("textarea[name=\'' . $paramkey . '\']").focus();' . "\n"; // TODO KO with ckeditor
13226 print 'jQuery("select[name=\'' . $paramkey . '\']").focus();' . "\n"; // Not really useful, but we keep it in case of.
13227 }
13228 }
13229 }
13230 }
13231 if (!empty($user->default_values[$relativepathstring]['mandatory'])) {
13232 foreach ($user->default_values[$relativepathstring]['mandatory'] as $defkey => $defval) {
13233 $qualified = 0;
13234 if ($defkey != '_noquery_') {
13235 $tmpqueryarraytohave = explode('&', $defkey);
13236 $foundintru = 0;
13237 foreach ($tmpqueryarraytohave as $tmpquerytohave) {
13238 $tmpquerytohaveparam = explode('=', $tmpquerytohave);
13239 //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
13240 if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) {
13241 $foundintru = 1;
13242 }
13243 }
13244 if (!$foundintru) {
13245 $qualified = 1;
13246 }
13247 //var_dump($defkey.'-'.$qualified);
13248 } else {
13249 $qualified = 1;
13250 }
13251
13252 if ($qualified) {
13253 print 'console.log("set the js code to manage fields that are set as mandatory");' . "\n";
13254
13255 foreach ($defval as $paramkey => $paramval) {
13256 // Solution 1: Add handler on submit to check if mandatory fields are empty
13257 print 'var form = $(\'[name="'.dol_escape_js($paramkey).'"]\').closest("form");'."\n";
13258 print "form.on('submit', function(event) {
13259 var submitter = \$(this).find(':submit:focus').get(0);
13260 var buttonName = submitter ? \$(submitter).attr('name') : 'save';
13261
13262 if (buttonName == 'cancel') {
13263 console.log('We click on cancel button so we accept submit with no need to check mandatory fields');
13264 return true;
13265 }
13266
13267 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');
13268
13269 var tmpvalue = jQuery('[name=\"".dol_escape_js($paramkey)."\"]').val();
13270 let tmptypefield = jQuery('[name=\"".dol_escape_js($paramkey)."\"]').prop('nodeName').toLowerCase(); // Get the tag name (div, section, footer...)
13271
13272 if (tmptypefield == 'textarea') {
13273 // We must instead check the content of ckeditor
13274 var tmpeditor = (typeof CKEDITOR !== 'undefined') ? CKEDITOR.instances['".dol_escape_js($paramkey)."'] : null;
13275 if (tmpeditor) {
13276 tmpvalue = tmpeditor.getData();
13277 console.log('For textarea tmpvalue is '+tmpvalue);
13278 }
13279 }
13280
13281 let tmpvalueisempty = false;
13282 if (tmpvalue === null || tmpvalue === undefined || tmpvalue === '' || tmpvalue === -1 || tmpvalue === '-1') {
13283 tmpvalueisempty = true;
13284 }
13285 if (tmpvalue === '0' && (tmptypefield == 'select' || tmptypefield == 'input')) {
13286 tmpvalueisempty = true;
13287 }
13288 if (tmpvalueisempty && buttonName !== 'cancel') {
13289 console.log('field has type '+tmptypefield+' and is empty, we cancel the submit');
13290 event.preventDefault(); // Stop submission of form to allow custom code to decide.
13291 event.stopPropagation(); // Stop other handlers.
13292
13293 alert('".dol_escape_js($langs->transnoentitiesnoconv("ErrorFieldRequired", $paramkey).' ('.$langs->transnoentitiesnoconv("CustomMandatoryFieldRule").')')."');
13294
13295 return false;
13296 }
13297 console.log('field has type '+tmptypefield+' and is defined to '+tmpvalue);
13298 return true;
13299 });
13300 \n";
13301
13302 // Solution 2: Add property 'required' on input
13303 // so browser will check value and try to focus on it when submitting the form.
13304 //print 'setTimeout(function() {'; // If we want to wait that ckeditor beuatifier has finished its job.
13305 //print 'jQuery("input[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
13306 //print 'jQuery("textarea[id=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
13307 //print 'jQuery("select[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";*/
13308 //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";
13309 //print 'jQuery("select[name=\''.$paramkey.'\'] option[value=\'-1\']").prop(\'value\', \'\');'."\n";
13310 //print 'jQuery("select[name=\''.$paramkey.'\'] option[value=\'0\']").prop(\'value\', \'\');'."\n";
13311 // Add 'field required' class on closest td for all input elements : input, textarea and select
13312 //print '}, 500);'; // 500 milliseconds delay
13313
13314 // Now set the class "fieldrequired"
13315 print 'jQuery(\':input[name="' . dol_escape_js($paramkey) . '"]\').closest("tr").find("td:first").addClass("fieldrequired");' . "\n";
13316 }
13317
13318 // If we submit using the cancel button, we remove the required attributes
13319 print 'jQuery("input[name=\'cancel\']").click(function() {
13320 console.log("We click on cancel button so removed all required attribute");
13321 jQuery("input, textarea, select").each(function(){this.removeAttribute(\'required\');});
13322 });' . "\n";
13323 }
13324 }
13325 }
13326 }
13327
13328 print '});' . "\n";
13329
13330 // End of tuning
13331 if (!empty($_SERVER['MAIN_SHOW_TUNING_INFO']) || getDolGlobalString('MAIN_SHOW_TUNING_INFO')) {
13332 print "\n";
13333 print "/* JS CODE TO ENABLE to add memory info */\n";
13334 print 'window.console && console.log("';
13335 if (getDolGlobalString('MEMCACHED_SERVER')) {
13336 print 'MEMCACHED_SERVER=' . getDolGlobalString('MEMCACHED_SERVER') . ' - ';
13337 }
13338 print 'MAIN_OPTIMIZE_SPEED=' . getDolGlobalString('MAIN_OPTIMIZE_SPEED', 'off');
13339 if (!empty($micro_start_time)) { // Works only if MAIN_SHOW_TUNING_INFO is defined at $_SERVER level. Not in global variable.
13340 $micro_end_time = microtime(true);
13341 print ' - Build time: ' . ceil(1000 * ($micro_end_time - $micro_start_time)) . ' ms';
13342 }
13343
13344 if (function_exists("memory_get_usage")) {
13345 print ' - Mem: ' . memory_get_usage(); // Do not use true here, it seems it takes the peak amount
13346 }
13347 if (function_exists("memory_get_peak_usage")) {
13348 print ' - Real mem peak: ' . memory_get_peak_usage(true);
13349 }
13350 if (function_exists("zend_loader_file_encoded")) {
13351 print ' - Zend encoded file: ' . (zend_loader_file_encoded() ? 'yes' : 'no');
13352 }
13353 print '");' . "\n";
13354 }
13355
13356 print "\n" . '</script>' . "\n";
13357
13358 // Google Analytics
13359 // TODO Remove this, can be replaced with the hook printCommonFooter
13360 if (isModEnabled('google') && getDolGlobalString('MAIN_GOOGLE_AN_ID')) {
13361 $tmptagarray = explode(',', getDolGlobalString('MAIN_GOOGLE_AN_ID'));
13362 foreach ($tmptagarray as $tmptag) {
13363 print "\n";
13364 print "<!-- JS CODE TO ENABLE for google analtics tag -->\n";
13365 print '
13366 <!-- Global site tag (gtag.js) - Google Analytics -->
13367 <script nonce="' . getNonce() . '" async src="https://www.googletagmanager.com/gtag/js?id=' . trim($tmptag) . '"></script>
13368 <script>
13369 window.dataLayer = window.dataLayer || [];
13370 function gtag(){dataLayer.push(arguments);}
13371 gtag(\'js\', new Date());
13372
13373 gtag(\'config\', \'' . trim($tmptag) . '\');
13374 </script>';
13375 print "\n";
13376 }
13377 }
13378 }
13379
13380 // Add Xdebug coverage of code
13381 if (defined('XDEBUGCOVERAGE')) {
13382 print_r(xdebug_get_code_coverage());
13383 }
13384
13385 // Output string from hooks
13386 if (!empty($hookmanager->resPrint)) {
13387 print $hookmanager->resPrint;
13388 }
13389
13390 // Add DebugBar data
13391 if ($user->hasRight('debugbar', 'read')) {
13392 global $debugbar;
13393 if ($debugbar instanceof DebugBar\DebugBar) {
13394 if (isset($debugbar['time'])) {
13395 // @phan-suppress-next-line PhanPluginUnknownObjectMethodCall
13396 $debugbar['time']->stopMeasure('pageaftermaster');
13397 }
13398 print '<!-- Output debugbar data -->' . "\n";
13399 $renderer = $debugbar->getJavascriptRenderer();
13400 print $renderer->render();
13401 }
13402 } elseif (count($conf->logbuffer)) { // If there is some logs in buffer to show
13403 print "\n";
13404 print "<!-- Start of log output\n";
13405 //print '<div class="hidden">'."\n";
13406 foreach ($conf->logbuffer as $logline) {
13407 print $logline . "<br>\n";
13408 }
13409 //print '</div>'."\n";
13410 print "End of log output -->\n";
13411 }
13412 }
13413}
13414
13424function dolExplodeIntoArray($string, $delimiter = ';', $kv = '=')
13425{
13426 if (is_null($string)) {
13427 return array();
13428 }
13429
13430 if (preg_match('/^\[.*\]$/sm', $delimiter) || preg_match('/^\‍(.*\‍)$/sm', $delimiter)) {
13431 // This is a regex string
13432 $newdelimiter = $delimiter;
13433 } else {
13434 // This is a simple string
13435 // @phan-suppress-next-line PhanPluginSuspiciousParamPositionInternal
13436 $newdelimiter = preg_quote($delimiter, '/');
13437 }
13438
13439 if ($a = preg_split('/' . $newdelimiter . '/', $string)) {
13440 $ka = array();
13441 foreach ($a as $s) { // each part
13442 if ($s) {
13443 if ($pos = strpos($s, $kv)) { // key/value delimiter
13444 $ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv)));
13445 } else { // key delimiter not found
13446 $ka[] = trim($s);
13447 }
13448 }
13449 }
13450 return $ka;
13451 }
13452
13453 return array();
13454}
13455
13463function dolExplodeKeepIfQuotes($input)
13464{
13465 // Use regexp to capture words and section in quotes
13466 $matches = array();
13467 preg_match_all('/"([^"]*)"|\'([^\']*)\'|(\S+)/', $input, $matches);
13468
13469 // Merge result and delete empty values
13470
13471 $result = array_map(
13478 static function ($a, $b, $c) {
13479 if ($a !== '') {
13480 return $a;
13481 }
13482 if ($b !== '') {
13483 return $b;
13484 }
13485 if ($c !== '') {
13486 return $c;
13487 }
13488 return '';
13489 },
13490 $matches[1],
13491 $matches[2],
13492 $matches[3]
13493 );
13494 return array_values(array_filter(
13495 $result,
13502 static function ($val) {
13503 return $val !== '';
13504 }
13505 ));
13506}
13507
13508
13515function dol_set_focus($selector)
13516{
13517 print "\n" . '<!-- Set focus onto a specific field -->' . "\n";
13518 print '<script nonce="' . getNonce() . '">jQuery(document).ready(function() { console.log("Force focus by dol_set_focus"); jQuery("' . dol_escape_js($selector) . '").focus(); });</script>' . "\n";
13519}
13520
13521
13529function dol_getmypid()
13530{
13531 if (!function_exists('getmypid')) {
13532 return mt_rand(99900000, 99965535);
13533 } else {
13534 return getmypid(); // May be a number on 64 bits (depending on OS)
13535 }
13536}
13537
13560function natural_search($fields, $value, $mode = 0, $nofirstand = 0, $sqltoadd = '')
13561{
13562 global $db, $langs;
13563
13564 $value = trim($value);
13565
13566 if ($mode == 0) {
13567 $value = preg_replace('/\*/', '%', $value); // Replace * with %
13568 }
13569 if ($mode == 1) {
13570 $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
13571 }
13572
13573 $value = preg_replace('/\s*\|\s*/', '|', $value);
13574
13575 // Split criteria on ' ' but not if we are inside quotes.
13576 // For mode 3, the split is done later on the , only and not on the ' '.
13577 if ($mode != -3 && $mode != 3) {
13578 $crits = dolExplodeKeepIfQuotes($value);
13579 } else {
13580 $crits = array($value);
13581 }
13582
13583 $res = '';
13584 if (!is_array($fields)) {
13585 $fields = array($fields);
13586 }
13587 $i1 = 0; // count the nb of "and" criteria added (all fields / criteria)
13588 foreach ($crits as $crit) { // Loop on each AND criteria
13589 $crit = trim($crit);
13590 $i2 = 0; // count the nb of valid criteria added for this this first criteria
13591 $newres = '';
13592
13593 foreach ($fields as $field) {
13594 if ($mode == 1) {
13595 $tmpcrits = explode('|', $crit);
13596 $i3 = 0; // count the nb of valid criteria added for this current field
13597 foreach ($tmpcrits as $tmpcrit) {
13598 if ($tmpcrit !== '0' && empty($tmpcrit)) {
13599 continue;
13600 }
13601 $tmpcrit = trim($tmpcrit);
13602
13603 $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
13604
13605 $operator = '=';
13606 $newcrit = preg_replace('/([!<>=]+)/', '', $tmpcrit);
13607
13608 $reg = array();
13609 preg_match('/([!<>=]+)/', $tmpcrit, $reg);
13610 if (!empty($reg[1])) {
13611 $operator = $reg[1];
13612 }
13613 if ($newcrit != '') {
13614 $numnewcrit = price2num($newcrit);
13615 if (is_numeric($numnewcrit)) {
13616 $newres .= $db->sanitize($field) . ' ' . $operator . ' ' . ((float) $numnewcrit); // should be a numeric
13617 } else {
13618 $newres .= '1 = 2'; // force false, we received a corrupted data
13619 }
13620 $i3++; // a criteria was added to string
13621 }
13622 }
13623 $i2++; // a criteria for 1 more field was added to string
13624 } elseif ($mode == 2 || $mode == -2) {
13625 $crit = preg_replace('/[^\-0-9,]/', '', $crit); // ID are always integer
13626 $newres .= ($i2 > 0 ? ' OR ' : '') . $db->sanitize($field) . " " . ($mode == -2 ? 'NOT ' : '');
13627 $newres .= $crit ? "IN (" . $db->sanitize($db->escape($crit)) . ")" : "IN (0)";
13628 if ($mode == -2) {
13629 $newres .= ' OR ' . $db->sanitize($field) . ' IS NULL';
13630 }
13631 $i2++; // a criteria for 1 more field was added to string
13632 } elseif ($mode == 3 || $mode == -3) {
13633 $tmparray = explode(',', $crit);
13634 if (count($tmparray)) {
13635 $listofcodes = '';
13636 $listofcodesnot = '';
13637 foreach ($tmparray as $val) {
13638 $val = trim($val);
13639 if ($val !== '') {
13640 if (preg_match('/^!/', $val)) {
13641 $listofcodesnot .= ($listofcodesnot ? ',' : '');
13642 $listofcodesnot .= "'" . $db->escape(preg_replace('/^!=?/', '', $val)) . "'";
13643 } else {
13644 $listofcodes .= ($listofcodes ? ',' : '');
13645 $listofcodes .= "'" . $db->escape($val) . "'";
13646 }
13647 }
13648 }
13649 $newres .= ($i2 > 0 ? ' OR ' : '');
13650 if ($listofcodes && $listofcodesnot) {
13651 $newres .= '(';
13652 }
13653 if ($listofcodes) {
13654 $newres .= $db->sanitize($field) . " " . ($mode == -3 ? 'NOT IN' : 'IN') . " (" . $db->sanitize($listofcodes, 1, 0, 1) . ")";
13655 }
13656 if ($listofcodes && $listofcodesnot) {
13657 $newres .= ' AND ';
13658 }
13659 if ($listofcodesnot) {
13660 $newres .= $db->sanitize($field) . " " . ($mode == -3 ? 'IN ' : 'NOT IN') . " (" . $db->sanitize($listofcodesnot, 1, 0, 1) . ")";
13661 }
13662 if ($listofcodes && $listofcodesnot) {
13663 $newres .= ')';
13664 }
13665 $i2++; // a criteria for 1 more field was added to string
13666 }
13667 if ($mode == -3) {
13668 $newres .= ' OR ' . $db->sanitize($field) . ' IS NULL';
13669 }
13670 } elseif ($mode == 4) {
13671 $tmparray = explode(',', $crit);
13672 if (count($tmparray)) {
13673 $listofcodes = '';
13674 foreach ($tmparray as $val) {
13675 $val = trim($val);
13676 if ($val) {
13677 $newres .= ($i2 > 0 ? " OR (" : "(") . $db->sanitize($field) . " LIKE '" . $db->escape($val) . ",%'";
13678 $newres .= ' OR ' . $db->sanitize($field) . " = '" . $db->escape($val) . "'";
13679 $newres .= ' OR ' . $db->sanitize($field) . " LIKE '%," . $db->escape($val) . "'";
13680 $newres .= ' OR ' . $db->sanitize($field) . " LIKE '%," . $db->escape($val) . ",%'";
13681 $newres .= ')';
13682 $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)
13683 }
13684 }
13685 }
13686 } else { // $mode=0
13687 $tmpcrits = explode('|', $crit);
13688 $i3 = 0; // count the nb of valid criteria added for the current couple criteria/field
13689 foreach ($tmpcrits as $tmpcrit) { // loop on each OR criteria
13690 if ($tmpcrit !== '0' && empty($tmpcrit)) {
13691 continue;
13692 }
13693 $tmpcrit = trim($tmpcrit);
13694
13695 if ($tmpcrit == '^$' || strpos($crit, '!') === 0) { // If we search empty, we must combined different OR fields with AND
13696 $newres .= (($i2 > 0 || $i3 > 0) ? ' AND ' : '');
13697 } else {
13698 $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
13699 }
13700
13701 $isSellist = false;
13702 $table = $label = $key = null;
13703
13704 if (strpos($field, 'ef.') === 0) {
13705 $extrafieldName = substr($field, 3);
13706 $extrafields = new ExtraFields($db);
13707 $extrafields->fetch_name_optionals_label('product');
13708
13709 if (isset($extrafields->attributes['product']['type'][$extrafieldName]) && $extrafields->attributes['product']['type'][$extrafieldName] === 'sellist') {
13710 $isSellist = true;
13711 $paramArray = $extrafields->attributes['product']['param'][$extrafieldName]['options'] ?? [];
13712 $param = array_key_first($paramArray);
13713 list($table, $label, $key) = explode(':', $param);
13714 }
13715 }
13716
13717 if (preg_match('/\.(id|rowid)$/', $field)) { // Special case for rowid that is sometimes a ref so used as a search field
13718 $newres .= $db->sanitize($field) . " = " . (is_numeric($tmpcrit) ? ((float) $tmpcrit) : '0');
13719 } else {
13720 $tmpcrit2 = $tmpcrit;
13721 $tmpbefore = '%';
13722 $tmpafter = '%';
13723 $tmps = '';
13724
13725 if ($isSellist && $key && $table && $label) {
13726 $newres .= $field . " IN (SELECT t." . $db->sanitize((string) $key) . " FROM " . $db->prefix() . $db->sanitize((string) $table) . " AS t WHERE t." . $db->sanitize((string) $label) . " LIKE '%" . $db->escape($tmpcrit2) . "%')";
13727 } else {
13728 if (preg_match('/^!/', $tmpcrit)) {
13729 $tmps .= $db->sanitize($field) . " NOT LIKE "; // ! as exclude character
13730 $tmpcrit2 = preg_replace('/^!/', '', $tmpcrit2);
13731 } else {
13732 $tmps .= $db->sanitize($field) . " LIKE ";
13733 }
13734 $tmps .= "'";
13735
13736 if (preg_match('/^[\^\$]/', $tmpcrit)) {
13737 $tmpbefore = '';
13738 $tmpcrit2 = preg_replace('/^[\^\$]/', '', $tmpcrit2);
13739 }
13740 if (preg_match('/[\^\$]$/', $tmpcrit)) {
13741 $tmpafter = '';
13742 $tmpcrit2 = preg_replace('/[\^\$]$/', '', $tmpcrit2);
13743 }
13744
13745 if ($tmpcrit2 == '' || preg_match('/^!/', $tmpcrit)) {
13746 $tmps = "(" . $tmps;
13747 }
13748 $newres .= $tmps;
13749 $newres .= $tmpbefore;
13750 $newres .= $db->escape($tmpcrit2);
13751 $newres .= $tmpafter;
13752 $newres .= "'";
13753 if ($tmpcrit2 == '' || preg_match('/^!/', $tmpcrit)) {
13754 $newres .= " OR " . $db->sanitize($field) . " IS NULL)";
13755 }
13756 }
13757 }
13758
13759 $i3++;
13760 }
13761
13762 $i2++; // a criteria for 1 more field was added to string
13763 }
13764 }
13765
13766 if ($sqltoadd) {
13767 $newres .= ($newres ? '' : ' OR ').str_replace('__KEYTOSEARCH__', $db->escape($crit), $sqltoadd);
13768 }
13769
13770 if ($newres) {
13771 $res = $res . ($res ? ' AND ' : '') . ($i2 > 1 ? '(' : '') . $newres . ($i2 > 1 ? ')' : '');
13772 }
13773 $i1++;
13774 }
13775 $res = ($nofirstand ? "" : " AND ") . "(" . $res . ")";
13776
13777 return $res;
13778}
13779
13787function showSimpleHTMLTable($outputlangs, $object)
13788{
13789 global $conf;
13790
13791 $discountIsAvailable = false;
13792 $orderPositionHasNoPrice = false;
13793
13794 if (!property_exists($object->lines[0], "remise_percent") ||
13795 !property_exists($object->lines[0], "fk_unit") ||
13796 !property_exists($object->lines[0], "multicurrency_total_ttc") ||
13797 !property_exists($object->lines[0], "description") ||
13798 !property_exists($object->lines[0], "qty")) {
13799 return"";
13800 }
13801
13802 foreach ($object->lines as $order_position) {
13803 if (!property_exists($order_position, "price")) {
13804 $orderPositionHasNoPrice = true;
13805 break;
13806 }
13807
13808 if (!empty($order_position->remise_percent)) {
13809 $discountIsAvailable = true;
13810 break;
13811 }
13812 };
13813
13814 if ($orderPositionHasNoPrice) {
13815 return "";
13816 }
13817
13818 $discountHeader = $discountIsAvailable ? '<th style="width:120px">'.$outputlangs->trans("Discount").'</th>' : '';
13819
13820 $table = '<table border="0" cellpadding="1" cellspacing="1">';
13821 $table .= '
13822 <thead>
13823 <tr>
13824 <th style="width:50px; text-align:left">#</th>
13825 <th style="text-align:left">'.$outputlangs->trans("Description").'</th>
13826 <th style="width:120px; text-align:right;">'.$outputlangs->trans("Price").'</th>
13827 <th style="width:100px; text-align:right;">'.$outputlangs->trans("Quantity").'</th>
13828 <th style="width:120px; text-align:right;">'.$outputlangs->trans("Unit").'</th>'.
13829 $discountHeader.'
13830 <th style="width:120px; text-align:right;">'.$outputlangs->trans("Sum").'</th>
13831 </tr>
13832 </thead>
13833 <tbody>';
13834
13835 foreach ($object->lines as $index => $order_position) {
13836 $position = $index + 1;
13837 $price = price($order_position->price, 0, $outputlangs, 0, -1, -1, $conf->currency);
13838 $unit = measuringUnitString($order_position->fk_unit, '', null, 1);
13839 $total = price($order_position->multicurrency_total_ttc, 0, $outputlangs, 0, -1, -1, $conf->currency);
13840 $discount = $discountIsAvailable ? '<td style="text-align:center">'.$order_position->remise_percent.'%</td>' : "";
13841
13842 $table .= '
13843 <tr>
13844 <td>'.$position.'</td>
13845 <td>'.$order_position->description.'</td>
13846 <td style="text-align:right">'.$price.'</td>
13847 <td style="text-align:right">'.$order_position->qty.'</td>
13848 <td style="text-align:right">'.$unit.'</td>'.
13849 $discount.'
13850 <td style="text-align:right">'.$total.'</td>
13851 </tr>';
13852 }
13853 $table .= '</tbody></table>';
13854
13855 return $table;
13856}
13857
13864function showDirectDownloadLink($object)
13865{
13866 global $langs;
13867
13868 $out = '';
13869 $url = $object->getLastMainDocLink($object->element);
13870
13871 $out .= img_picto($langs->trans("PublicDownloadLinkDesc"), 'globe') . ' <span class="opacitymedium">' . $langs->trans("DirectDownloadLink") . '</span><br>';
13872 if ($url) {
13873 $out .= '<div class="urllink"><input type="text" id="directdownloadlink" class="quatrevingtpercent" value="' . $url . '"></div>';
13874 $out .= ajax_autoselect("directdownloadlink", '');
13875 } else {
13876 $out .= '<div class="urllink">' . $langs->trans("FileNotShared") . '</div>';
13877 }
13878
13879 return $out;
13880}
13881
13890function getImageFileNameForSize($file, $extName, $extImgTarget = '')
13891{
13892 $dirName = dirname($file);
13893 if ($dirName == '.') {
13894 $dirName = '';
13895 }
13896
13897 if (!in_array($extName, array('', '_small', '_mini'))) {
13898 return 'Bad parameter extName';
13899 }
13900
13901 $fileName = preg_replace('/(\.gif|\.jpeg|\.jpg|\.png|\.bmp|\.webp|\.avif)$/i', '', $file); // We remove image extension, whatever is its case
13902 $fileName = basename($fileName);
13903
13904 if (empty($extImgTarget)) {
13905 $extImgTarget = (preg_match('/\.jpg$/i', $file) ? '.jpg' : '');
13906 }
13907 if (empty($extImgTarget)) {
13908 $extImgTarget = (preg_match('/\.jpeg$/i', $file) ? '.jpeg' : '');
13909 }
13910 if (empty($extImgTarget)) {
13911 $extImgTarget = (preg_match('/\.gif$/i', $file) ? '.gif' : '');
13912 }
13913 if (empty($extImgTarget)) {
13914 $extImgTarget = (preg_match('/\.png$/i', $file) ? '.png' : '');
13915 }
13916 if (empty($extImgTarget)) {
13917 $extImgTarget = (preg_match('/\.bmp$/i', $file) ? '.bmp' : '');
13918 }
13919 if (empty($extImgTarget)) {
13920 $extImgTarget = (preg_match('/\.webp$/i', $file) ? '.webp' : '');
13921 }
13922 if (empty($extImgTarget)) {
13923 $extImgTarget = (preg_match('/\.avif$/i', $file) ? '.avif' : '');
13924 }
13925
13926 if (!$extImgTarget) {
13927 return $file;
13928 }
13929
13930 $subdir = '';
13931 if ($extName) {
13932 $subdir = 'thumbs/';
13933 }
13934
13935 return ($dirName ? $dirName . '/' : '') . $subdir . $fileName . $extName . $extImgTarget; // New filename for thumb
13936}
13937
13938
13948function getAdvancedPreviewUrl($modulepart, $relativepath, $alldata = 0, $param = '')
13949{
13950 global $conf, $langs;
13951
13952 if (empty($conf->use_javascript_ajax)) {
13953 return '';
13954 }
13955
13956 $isAllowedForPreview = dolIsAllowedForPreview($relativepath);
13957
13958 if ($alldata == 1) {
13959 if ($isAllowedForPreview) {
13960 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));
13961 } else {
13962 return array();
13963 }
13964 }
13965
13966 // old behavior, return a string
13967 if ($isAllowedForPreview) {
13968 $tmpurl = DOL_URL_ROOT . '/document.php?modulepart=' . urlencode($modulepart) . '&attachment=0&file=' . urlencode($relativepath) . ($param ? '&' . $param : '');
13969 $title = $langs->transnoentities("Preview");
13970 //$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().
13971 //$tmpurl = 'file='.urlencode("'-alert(document.domain)-'_small.jpg"); // An example of tmpurl that should be blocked by the dol_escape_uri()
13972
13973 // 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,
13974 // 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.
13975 // Using the dol_escape_uri guarantee that we encode for URI so decode retrieve original expected value.
13976 return 'javascript:' . dol_escape_uri('document_preview(\'' . dol_escape_js($tmpurl) . '\', \'' . dol_escape_js(dol_mimetype($relativepath)) . '\', \'' . dol_escape_js($title) . '\')');
13977 } else {
13978 return '';
13979 }
13980}
13981
13988function getLabelSpecialCode($idcode)
13989{
13990 global $langs;
13991
13992 $arrayspecialines = array(1 => 'Transport', 2 => 'EcoTax', 3 => 'Option');
13993 if ($idcode > 10) {
13994 return 'Module ID ' . $idcode;
13995 }
13996 if (!empty($arrayspecialines[$idcode])) {
13997 return $langs->trans($arrayspecialines[$idcode]);
13998 }
13999 return '';
14000}
14001
14011function ajax_autoselect($htmlname, $addlink = '', $textonlink = 'Link')
14012{
14013 global $langs;
14014 $out = '<script nonce="' . getNonce() . '">
14015 jQuery(document).ready(function () {
14016 jQuery("' . ((strpos($htmlname, '.') === 0 ? '' : '#') . $htmlname) . '").click(function() { jQuery(this).select(); } );
14017 });
14018 </script>';
14019 if ($addlink) {
14020 if ($textonlink === 'image') {
14021 $out .= ' <a href="' . $addlink . '" target="_blank" rel="noopener noreferrer">' . img_picto('', 'globe') . '</a>';
14022 } else {
14023 $out .= ' <a href="' . $addlink . '" target="_blank" rel="noopener noreferrer">' . $langs->trans("Link") . '</a>';
14024 }
14025 }
14026 return $out;
14027}
14028
14036function dolIsAllowedForPreview($file)
14037{
14038 // Check .noexe extension in filename
14039 if (preg_match('/\.noexe$/i', $file)) {
14040 return 0;
14041 }
14042
14043 // Check mime types
14044 $mime_preview = array('avif', 'bmp', 'jpeg', 'png', 'gif', 'tiff', 'pdf', 'plain', 'css', 'webp', 'webm', 'mp4');
14045 if (getDolGlobalString('MAIN_ALLOW_SVG_FILES_AS_IMAGES')) {
14046 $mime_preview[] = 'svg+xml';
14047 }
14048 if (getDolGlobalString('MAIN_ALLOW_XML_FILES_AS_PREVIEW')) {
14049 $mime_preview[] = 'xml';
14050 }
14051
14052 //$mime_preview[]='vnd.oasis.opendocument.presentation';
14053 //$mime_preview[]='archive';
14054 $num_mime = array_search(dol_mimetype($file, '', 1), $mime_preview);
14055 if ($num_mime !== false) {
14056 return 1;
14057 }
14058
14059 // By default, not allowed for preview
14060 return 0;
14061}
14062
14063
14073function dol_mimetype($file, $default = 'application/octet-stream', $mode = 0)
14074{
14075 $mime = $default;
14076 $imgmime = 'other.png';
14077 $famime = 'file-o';
14078 $srclang = '';
14079
14080 $tmpfile = preg_replace('/\.noexe$/', '', $file);
14081
14082 // Plain text files
14083 if (preg_match('/\.txt$/i', $tmpfile)) {
14084 $mime = 'text/plain';
14085 $imgmime = 'text.png';
14086 $famime = 'file-alt';
14087 } elseif (preg_match('/\.rtx$/i', $tmpfile)) {
14088 $mime = 'text/richtext';
14089 $imgmime = 'text.png';
14090 $famime = 'file-alt';
14091 } elseif (preg_match('/\.csv$/i', $tmpfile)) {
14092 $mime = 'text/csv';
14093 $imgmime = 'text.png';
14094 $famime = 'file-csv';
14095 } elseif (preg_match('/\.tsv$/i', $tmpfile)) {
14096 $mime = 'text/tab-separated-values';
14097 $imgmime = 'text.png';
14098 $famime = 'file-alt';
14099 } elseif (preg_match('/\.(cf|conf|log)$/i', $tmpfile)) {
14100 $mime = 'text/plain';
14101 $imgmime = 'text.png';
14102 $famime = 'file-alt';
14103 } elseif (preg_match('/\.ini$/i', $tmpfile)) {
14104 $mime = 'text/plain';
14105 $imgmime = 'text.png';
14106 $srclang = 'ini';
14107 $famime = 'file-alt';
14108 } elseif (preg_match('/\.md$/i', $tmpfile)) {
14109 $mime = 'text/plain';
14110 $imgmime = 'text.png';
14111 $srclang = 'md';
14112 $famime = 'file-alt';
14113 } elseif (preg_match('/\.css$/i', $tmpfile)) {
14114 $mime = 'text/css';
14115 $imgmime = 'css.png';
14116 $srclang = 'css';
14117 $famime = 'file-alt';
14118 } elseif (preg_match('/\.lang$/i', $tmpfile)) {
14119 $mime = 'text/plain';
14120 $imgmime = 'text.png';
14121 $srclang = 'lang';
14122 $famime = 'file-alt';
14123 } elseif (preg_match('/\.(crt|cer|key|pub)$/i', $tmpfile)) { // Certificate files
14124 $mime = 'text/plain';
14125 $imgmime = 'text.png';
14126 $famime = 'file-alt';
14127 } elseif (preg_match('/\.(html|htm|shtml)$/i', $tmpfile)) { // XML based (HTML/XML/XAML)
14128 $mime = 'text/html';
14129 $imgmime = 'html.png';
14130 $srclang = 'html';
14131 $famime = 'file-alt';
14132 } elseif (preg_match('/\.(xml|xhtml)$/i', $tmpfile)) {
14133 $mime = 'text/xml';
14134 $imgmime = 'other.png';
14135 $srclang = 'xml';
14136 $famime = 'file-alt';
14137 } elseif (preg_match('/\.xaml$/i', $tmpfile)) {
14138 $mime = 'text/xml';
14139 $imgmime = 'other.png';
14140 $srclang = 'xaml';
14141 $famime = 'file-alt';
14142 } elseif (preg_match('/\.bas$/i', $tmpfile)) { // Languages
14143 $mime = 'text/plain';
14144 $imgmime = 'text.png';
14145 $srclang = 'bas';
14146 $famime = 'file-code';
14147 } elseif (preg_match('/\.(c)$/i', $tmpfile)) {
14148 $mime = 'text/plain';
14149 $imgmime = 'text.png';
14150 $srclang = 'c';
14151 $famime = 'file-code';
14152 } elseif (preg_match('/\.(cpp)$/i', $tmpfile)) {
14153 $mime = 'text/plain';
14154 $imgmime = 'text.png';
14155 $srclang = 'cpp';
14156 $famime = 'file-code';
14157 } elseif (preg_match('/\.cs$/i', $tmpfile)) {
14158 $mime = 'text/plain';
14159 $imgmime = 'text.png';
14160 $srclang = 'cs';
14161 $famime = 'file-code';
14162 } elseif (preg_match('/\.(h)$/i', $tmpfile)) {
14163 $mime = 'text/plain';
14164 $imgmime = 'text.png';
14165 $srclang = 'h';
14166 $famime = 'file-code';
14167 } elseif (preg_match('/\.(java|jsp)$/i', $tmpfile)) {
14168 $mime = 'text/plain';
14169 $imgmime = 'text.png';
14170 $srclang = 'java';
14171 $famime = 'file-code';
14172 } elseif (preg_match('/\.php([0-9]{1})?$/i', $tmpfile)) {
14173 $mime = 'text/plain';
14174 $imgmime = 'php.png';
14175 $srclang = 'php';
14176 $famime = 'file-code';
14177 } elseif (preg_match('/\.phtml$/i', $tmpfile)) {
14178 $mime = 'text/plain';
14179 $imgmime = 'php.png';
14180 $srclang = 'php';
14181 $famime = 'file-code';
14182 } elseif (preg_match('/\.(pl|pm)$/i', $tmpfile)) {
14183 $mime = 'text/plain';
14184 $imgmime = 'pl.png';
14185 $srclang = 'perl';
14186 $famime = 'file-code';
14187 } elseif (preg_match('/\.sql$/i', $tmpfile)) {
14188 $mime = 'text/plain';
14189 $imgmime = 'text.png';
14190 $srclang = 'sql';
14191 $famime = 'file-code';
14192 } elseif (preg_match('/\.js$/i', $tmpfile)) {
14193 $mime = 'text/x-javascript';
14194 $imgmime = 'jscript.png';
14195 $srclang = 'js';
14196 $famime = 'file-code';
14197 } elseif (preg_match('/\.odp$/i', $tmpfile)) { // Open office
14198 $mime = 'application/vnd.oasis.opendocument.presentation';
14199 $imgmime = 'ooffice.png';
14200 $famime = 'file-powerpoint';
14201 } elseif (preg_match('/\.ods$/i', $tmpfile)) {
14202 $mime = 'application/vnd.oasis.opendocument.spreadsheet';
14203 $imgmime = 'ooffice.png';
14204 $famime = 'file-excel';
14205 } elseif (preg_match('/\.odt$/i', $tmpfile)) {
14206 $mime = 'application/vnd.oasis.opendocument.text';
14207 $imgmime = 'ooffice.png';
14208 $famime = 'file-word';
14209 } elseif (preg_match('/\.mdb$/i', $tmpfile)) { // MS Office
14210 $mime = 'application/msaccess';
14211 $imgmime = 'mdb.png';
14212 $famime = 'file';
14213 } elseif (preg_match('/\.doc[xm]?$/i', $tmpfile)) {
14214 $mime = 'application/msword';
14215 $imgmime = 'doc.png';
14216 $famime = 'file-word';
14217 } elseif (preg_match('/\.dot[xm]?$/i', $tmpfile)) {
14218 $mime = 'application/msword';
14219 $imgmime = 'doc.png';
14220 $famime = 'file-word';
14221 } elseif (preg_match('/\.xlt(x)?$/i', $tmpfile)) {
14222 $mime = 'application/vnd.ms-excel';
14223 $imgmime = 'xls.png';
14224 $famime = 'file-excel';
14225 } elseif (preg_match('/\.xla(m)?$/i', $tmpfile)) {
14226 $mime = 'application/vnd.ms-excel';
14227 $imgmime = 'xls.png';
14228 $famime = 'file-excel';
14229 } elseif (preg_match('/\.xls$/i', $tmpfile)) {
14230 $mime = 'application/vnd.ms-excel';
14231 $imgmime = 'xls.png';
14232 $famime = 'file-excel';
14233 } elseif (preg_match('/\.xls[bmx]$/i', $tmpfile)) {
14234 $mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
14235 $imgmime = 'xls.png';
14236 $famime = 'file-excel';
14237 } elseif (preg_match('/\.pps[mx]?$/i', $tmpfile)) {
14238 $mime = 'application/vnd.ms-powerpoint';
14239 $imgmime = 'ppt.png';
14240 $famime = 'file-powerpoint';
14241 } elseif (preg_match('/\.ppt[mx]?$/i', $tmpfile)) {
14242 $mime = 'application/x-mspowerpoint';
14243 $imgmime = 'ppt.png';
14244 $famime = 'file-powerpoint';
14245 } elseif (preg_match('/\.pdf$/i', $tmpfile)) { // Other
14246 $mime = 'application/pdf';
14247 $imgmime = 'pdf.png';
14248 $famime = 'file-pdf';
14249 } elseif (preg_match('/\.bat$/i', $tmpfile)) { // Scripts
14250 $mime = 'text/x-bat';
14251 $imgmime = 'script.png';
14252 $srclang = 'dos';
14253 $famime = 'file-code';
14254 } elseif (preg_match('/\.sh$/i', $tmpfile)) {
14255 $mime = 'text/x-sh';
14256 $imgmime = 'script.png';
14257 $srclang = 'bash';
14258 $famime = 'file-code';
14259 } elseif (preg_match('/\.ksh$/i', $tmpfile)) {
14260 $mime = 'text/x-ksh';
14261 $imgmime = 'script.png';
14262 $srclang = 'bash';
14263 $famime = 'file-code';
14264 } elseif (preg_match('/\.bash$/i', $tmpfile)) {
14265 $mime = 'text/x-bash';
14266 $imgmime = 'script.png';
14267 $srclang = 'bash';
14268 $famime = 'file-code';
14269 } elseif (preg_match('/\.ico$/i', $tmpfile)) { // Images
14270 $mime = 'image/x-icon';
14271 $imgmime = 'image.png';
14272 $famime = 'file-image';
14273 } elseif (preg_match('/\.(jpg|jpeg)$/i', $tmpfile)) {
14274 $mime = 'image/jpeg';
14275 $imgmime = 'image.png';
14276 $famime = 'file-image';
14277 } elseif (preg_match('/\.png$/i', $tmpfile)) {
14278 $mime = 'image/png';
14279 $imgmime = 'image.png';
14280 $famime = 'file-image';
14281 } elseif (preg_match('/\.gif$/i', $tmpfile)) {
14282 $mime = 'image/gif';
14283 $imgmime = 'image.png';
14284 $famime = 'file-image';
14285 } elseif (preg_match('/\.bmp$/i', $tmpfile)) {
14286 $mime = 'image/bmp';
14287 $imgmime = 'image.png';
14288 $famime = 'file-image';
14289 } elseif (preg_match('/\.(tif|tiff)$/i', $tmpfile)) {
14290 $mime = 'image/tiff';
14291 $imgmime = 'image.png';
14292 $famime = 'file-image';
14293 } elseif (preg_match('/\.svg$/i', $tmpfile)) {
14294 $mime = 'image/svg+xml';
14295 $imgmime = 'image.png';
14296 $famime = 'file-image';
14297 } elseif (preg_match('/\.webp$/i', $tmpfile)) {
14298 $mime = 'image/webp';
14299 $imgmime = 'image.png';
14300 $famime = 'file-image';
14301 } elseif (preg_match('/\.vcs$/i', $tmpfile)) { // Calendar
14302 $mime = 'text/calendar';
14303 $imgmime = 'other.png';
14304 $famime = 'file-alt';
14305 } elseif (preg_match('/\.ics$/i', $tmpfile)) {
14306 $mime = 'text/calendar';
14307 $imgmime = 'other.png';
14308 $famime = 'file-alt';
14309 } elseif (preg_match('/\.torrent$/i', $tmpfile)) { // Other
14310 $mime = 'application/x-bittorrent';
14311 $imgmime = 'other.png';
14312 $famime = 'file-o';
14313 } elseif (preg_match('/\.(mp3|ogg|au|wav|wma|mid)$/i', $tmpfile)) { // Audio
14314 $mime = 'audio';
14315 $imgmime = 'audio.png';
14316 $famime = 'file-audio';
14317 } elseif (preg_match('/\.mp4$/i', $tmpfile)) { // Video
14318 $mime = 'video/mp4';
14319 $imgmime = 'video.png';
14320 $famime = 'file-video';
14321 } elseif (preg_match('/\.ogv$/i', $tmpfile)) {
14322 $mime = 'video/ogg';
14323 $imgmime = 'video.png';
14324 $famime = 'file-video';
14325 } elseif (preg_match('/\.webm$/i', $tmpfile)) {
14326 $mime = 'video/webm';
14327 $imgmime = 'video.png';
14328 $famime = 'file-video';
14329 } elseif (preg_match('/\.avif$/i', $tmpfile)) {
14330 $mime = 'image/avif';
14331 $imgmime = 'image.png';
14332 $famime = 'file-image';
14333 } elseif (preg_match('/\.avi$/i', $tmpfile)) {
14334 $mime = 'video/x-msvideo';
14335 $imgmime = 'video.png';
14336 $famime = 'file-video';
14337 } elseif (preg_match('/\.divx$/i', $tmpfile)) {
14338 $mime = 'video/divx';
14339 $imgmime = 'video.png';
14340 $famime = 'file-video';
14341 } elseif (preg_match('/\.xvid$/i', $tmpfile)) {
14342 $mime = 'video/xvid';
14343 $imgmime = 'video.png';
14344 $famime = 'file-video';
14345 } elseif (preg_match('/\.(wmv|mpg|mpeg)$/i', $tmpfile)) {
14346 $mime = 'video';
14347 $imgmime = 'video.png';
14348 $famime = 'file-video';
14349 } elseif (preg_match('/\.(zip|rar|gz|tgz|xz|z|cab|bz2|7z|tar|lzh|zst)$/i', $tmpfile)) { // Archive
14350 // application/xxx where zzz is zip, ...
14351 $mime = 'archive';
14352 $imgmime = 'archive.png';
14353 $famime = 'file-archive';
14354 } elseif (preg_match('/\.(exe|com)$/i', $tmpfile)) { // Exe
14355 $mime = 'application/octet-stream';
14356 $imgmime = 'other.png';
14357 $famime = 'file-o';
14358 } elseif (preg_match('/\.(dll|lib|o|so|a)$/i', $tmpfile)) { // Lib
14359 $mime = 'library';
14360 $imgmime = 'library.png';
14361 $famime = 'file-o';
14362 } elseif (preg_match('/\.err$/i', $tmpfile)) { // phpcs:ignore
14363 $mime = 'error';
14364 $imgmime = 'error.png';
14365 $famime = 'file-alt';
14366 }
14367
14368 if ($famime == 'file-o') {
14369 // file-o seems to not work in fontawesome 5
14370 $famime = 'file';
14371 }
14372
14373 // Return mimetype string
14374 switch ((int) $mode) {
14375 case 1:
14376 $tmp = explode('/', $mime);
14377 return (!empty($tmp[1]) ? $tmp[1] : $tmp[0]);
14378 case 2:
14379 return $imgmime;
14380 case 3:
14381 return $srclang;
14382 case 4:
14383 return $famime;
14384 }
14385 return $mime;
14386}
14387
14399function getDictionaryValue($tablename, $field, $id, $checkentity = false, $rowidfield = 'rowid')
14400{
14401 global $conf, $db;
14402
14403 $tablename = preg_replace('/^' . preg_quote(MAIN_DB_PREFIX, '/') . '/', '', $tablename); // Clean name of table for backward compatibility.
14404
14405 $dictvalues = (isset($conf->cache['dictvalues_' . $tablename]) ? $conf->cache['dictvalues_' . $tablename] : null);
14406
14407 if (is_null($dictvalues)) {
14408 $dictvalues = array();
14409
14410 $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
14411 if ($checkentity) {
14412 $sql .= ' AND entity IN (0,' . getEntity($tablename) . ')';
14413 }
14414
14415 $resql = $db->query($sql);
14416 if ($resql) {
14417 while ($obj = $db->fetch_object($resql)) {
14418 $dictvalues[$obj->$rowidfield] = $obj; // $obj is stdClass
14419 }
14420 } else {
14421 dol_print_error($db);
14422 }
14423
14424 $conf->cache['dictvalues_' . $tablename] = $dictvalues;
14425 }
14426
14427 if (!empty($dictvalues[$id])) {
14428 // Found
14429 $tmp = $dictvalues[$id];
14430 return (property_exists($tmp, $field) ? $tmp->$field : '');
14431 } else {
14432 // Not found
14433 return '';
14434 }
14435}
14436
14443function colorIsLight($stringcolor)
14444{
14445 $stringcolor = str_replace('#', '', $stringcolor);
14446 $res = -1;
14447 if (!empty($stringcolor)) {
14448 $res = 0;
14449 $tmp = explode(',', $stringcolor);
14450 if (count($tmp) > 1) { // This is a comma RGB ('255','255','255')
14451 $r = $tmp[0];
14452 $g = $tmp[1];
14453 $b = $tmp[2];
14454 } else {
14455 $hexr = $stringcolor[0] . $stringcolor[1];
14456 $hexg = $stringcolor[2] . $stringcolor[3];
14457 $hexb = $stringcolor[4] . $stringcolor[5];
14458 $r = hexdec($hexr);
14459 $g = hexdec($hexg);
14460 $b = hexdec($hexb);
14461 }
14462 $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm
14463 if ($bright > 0.6) {
14464 $res = 1;
14465 }
14466 }
14467 return $res;
14468}
14469
14478function isVisibleToUserType($type_user, &$menuentry, &$listofmodulesforexternal)
14479{
14480 //print 'type_user='.$type_user.' module='.$menuentry['module'].' enabled='.$menuentry['enabled'].' perms='.$menuentry['perms'];
14481 //print 'ok='.in_array($menuentry['module'], $listofmodulesforexternal);
14482 if (empty($menuentry['enabled'])) {
14483 return 0; // Entry disabled by condition
14484 }
14485 if ($type_user && array_key_exists('module', $menuentry) && $menuentry['module']) {
14486 $tmploops = explode('|', $menuentry['module']);
14487 $found = 0;
14488 foreach ($tmploops as $tmploop) {
14489 if (in_array($tmploop, $listofmodulesforexternal)) {
14490 $found++;
14491 break;
14492 }
14493 }
14494 if (!$found) {
14495 return 0; // Entry is for menus all excluded to external users
14496 }
14497 }
14498 if (!$menuentry['perms'] && $type_user) {
14499 return 0; // No permissions and user is external
14500 }
14501 if (!$menuentry['perms'] && getDolGlobalString('MAIN_MENU_HIDE_UNAUTHORIZED')) {
14502 return 0; // No permissions and option to hide when not allowed, even for internal user, is on
14503 }
14504 if (!$menuentry['perms']) {
14505 return 2; // No permissions and user is external
14506 }
14507 return 1;
14508}
14509
14517function roundUpToNextMultiple($n, $x = 5)
14518{
14519 $result = (ceil($n) % $x === 0) ? ceil($n) : (round(($n + $x / 2) / $x) * $x);
14520 return (int) $result;
14521}
14522
14534function dolGetBadge($label, $html = '', $type = 'primary', $mode = '', $url = '', $params = array())
14535{
14536 $csstouse = 'badge';
14537 $csstouse .= (!empty($mode) ? ' badge-' . $mode : '');
14538 $csstouse .= (!empty($type) ? ' badge-' . $type : '');
14539 $csstouse .= (empty($params['css']) ? '' : ' ' . $params['css']);
14540
14541 $attr = array(
14542 'class' => $csstouse
14543 );
14544
14545 if (empty($html)) {
14546 $html = $label;
14547 }
14548
14549 if (!empty($url)) {
14550 $attr['href'] = $url;
14551 }
14552
14553 if ($mode === 'dot') {
14554 $attr['class'] .= ' classfortooltip';
14555 $attr['title'] = $html;
14556 $attr['aria-label'] = $label;
14557 $html = '';
14558 }
14559
14560 // Override attr
14561 if (!empty($params['attr']) && is_array($params['attr'])) {
14562 foreach ($params['attr'] as $key => $value) {
14563 if ($key == 'class') {
14564 $attr['class'] .= ' ' . $value;
14565 } elseif ($key == 'classOverride') {
14566 $attr['class'] = $value;
14567 } else {
14568 $attr[$key] = $value;
14569 }
14570 }
14571 }
14572
14573 // TODO: add hook
14574
14575 // escape all attribute
14576 $attr = array_map('dolPrintHTMLForAttribute', $attr);
14577
14578 $TCompiledAttr = array();
14579 foreach ($attr as $key => $value) {
14580 $TCompiledAttr[] = $key . '="' . $value . '"';
14581 }
14582
14583 $compiledAttributes = !empty($TCompiledAttr) ? implode(' ', $TCompiledAttr) : '';
14584
14585 $tag = !empty($url) ? 'a' : 'span';
14586
14587 return '<' . $tag . ' ' . $compiledAttributes . '>' . $html . '</' . $tag . '>';
14588}
14589
14590
14603function dolGetStatus($statusLabel = '', $statusLabelShort = '', $html = '', $statusType = 'status0', $displayMode = 0, $url = '', $params = array())
14604{
14605 global $conf;
14606
14607 $return = '';
14608 $dolGetBadgeParams = array();
14609
14610 if (!empty($params['badgeParams'])) {
14611 $dolGetBadgeParams = $params['badgeParams'];
14612 }
14613
14614 // TODO : add a hook
14615 if ($displayMode == 0) {
14616 $return = !empty($html) ? $html : (empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort));
14617 } elseif ($displayMode == 1) {
14618 $return = !empty($html) ? $html : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
14619 } elseif (getDolGlobalString('MAIN_STATUS_USES_IMAGES')) {
14620 // Use status with images (for backward compatibility)
14621 $return = '';
14622 $htmlLabel = (in_array($displayMode, array(1, 2, 5)) ? '<span class="hideonsmartphone">' : '') . (!empty($html) ? $html : $statusLabel) . (in_array($displayMode, array(1, 2, 5)) ? '</span>' : '');
14623 $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>' : '');
14624
14625 // For small screen, we always use the short label instead of long label.
14626 if (!empty($conf->dol_optimize_smallscreen)) {
14627 if ($displayMode == 0) {
14628 $displayMode = 1;
14629 } elseif ($displayMode == 4) {
14630 $displayMode = 2;
14631 } elseif ($displayMode == 6) {
14632 $displayMode = 5;
14633 }
14634 }
14635
14636 // For backward compatibility. Image's filename are still in French, so we use this array to convert
14637 $statusImg = array(
14638 'status0' => 'statut0',
14639 'status1' => 'statut1',
14640 'status2' => 'statut2',
14641 'status3' => 'statut3',
14642 'status4' => 'statut4',
14643 'status5' => 'statut5',
14644 'status6' => 'statut6',
14645 'status7' => 'statut7',
14646 'status8' => 'statut8',
14647 'status9' => 'statut9'
14648 );
14649
14650 if (!empty($statusImg[$statusType])) {
14651 $htmlImg = img_picto($statusLabel, $statusImg[$statusType]);
14652 } else {
14653 $htmlImg = img_picto($statusLabel, $statusType);
14654 }
14655
14656 if ($displayMode === 2) {
14657 $return = $htmlImg . ' ' . $htmlLabelShort;
14658 } elseif ($displayMode === 3) {
14659 $return = $htmlImg;
14660 } elseif ($displayMode === 4) {
14661 $return = $htmlImg . ' ' . $htmlLabel;
14662 } elseif ($displayMode === 5) {
14663 $return = $htmlLabelShort . ' ' . $htmlImg;
14664 } else { // $displayMode >= 6
14665 $return = $htmlLabel . ' ' . $htmlImg;
14666 }
14667 } elseif (!getDolGlobalString('MAIN_STATUS_USES_IMAGES') && !empty($displayMode)) {
14668 // Use new badge
14669 $statusLabelShort = (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
14670
14671 $dolGetBadgeParams['attr']['class'] = 'badge-status';
14672 if (empty($dolGetBadgeParams['attr']['title'])) {
14673 $dolGetBadgeParams['attr']['title'] = empty($params['tooltip']) ? $statusLabel : ($params['tooltip'] != 'no' ? $params['tooltip'] : '');
14674 } else { // If a title was forced from $params['badgeParams']['attr']['title'], we set the class to get it as a tooltip.
14675 $dolGetBadgeParams['attr']['class'] .= ' classfortooltip';
14676 // And if we use tooltip, we can output title in HTML @phan-suppress-next-line PhanTypeInvalidDimOffset
14677 $dolGetBadgeParams['attr']['title'] = dol_htmlentitiesbr((string) $dolGetBadgeParams['attr']['title'], 1);
14678 }
14679
14680 if ($displayMode == 3) {
14681 $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), '', $statusType, 'dot', $url, $dolGetBadgeParams);
14682 } elseif ($displayMode === 5) {
14683 $return = dolGetBadge($statusLabelShort, $html, $statusType, '', $url, $dolGetBadgeParams);
14684 } else {
14685 $return = dolGetBadge(((empty($conf->dol_optimize_smallscreen) && $displayMode != 2) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), $html, $statusType, '', $url, $dolGetBadgeParams);
14686 }
14687 }
14688
14689 return $return;
14690}
14691
14692
14728function dolGetButtonAction($label, $text = '', $actionType = 'default', $url = '', $id = '', $userRight = 1, $params = array())
14729{
14730 global $hookmanager, $action, $object, $langs;
14731
14732 // If $url is an array, we must build a dropdown button or recursively iterate over each value
14733 if (is_array($url)) {
14734 // Loop on $url array to remove entries of disabled modules
14735 foreach ($url as $key => $subbutton) {
14736 if (isset($subbutton['enabled']) && empty($subbutton['enabled'])) {
14737 unset($url[$key]);
14738 }
14739 }
14740
14741 $out = '';
14742
14743 if (array_key_exists('areDropdownButtons', $params) && $params["areDropdownButtons"] === false) { // @phan-suppress-current-line PhanTypeInvalidDimOffset
14744 foreach ($url as $button) {
14745 if (!empty($button['lang'])) {
14746 $langs->load($button['lang']);
14747 }
14748 $label = $langs->trans($button['label']);
14749 $text = $button['text'] ?? '';
14750 $actionType = $button['actionType'] ?? '';
14751 $tmpUrl = DOL_URL_ROOT . $button['url'] . (empty($params['backtopage']) ? '' : '&amp;backtopage=' . urlencode($params['backtopage']));
14752 $id = $button['id'] ?? '';
14753 $userRight = $button['perm'] ?? 1;
14754 $button['params'] = $button['params'] ?? []; // @phan-suppress-current-line PhanPluginDuplicateExpressionAssignmentOperation
14755
14756 $out .= dolGetButtonAction($label, $text, $actionType, $tmpUrl, $id, $userRight, $button['params']);
14757 }
14758 return $out;
14759 }
14760
14761 if (count($url) > 1 || !empty($params["forceDropdownButtons"])) {
14762 $out .= '<div class="dropdown inline-block dropdown-holder">';
14763 $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>';
14764 $out .= '<div class="dropdown-content">';
14765 foreach ($url as $subbutton) {
14766 if (!empty($subbutton['lang'])) {
14767 $langs->load($subbutton['lang']);
14768 }
14769
14770 if (!empty($subbutton['urlraw'])) {
14771 $tmpurl = $subbutton['urlraw']; // Use raw url, no url completion, use only what developer send
14772 } else {
14773 $tmpurl = !empty($subbutton['urlroot']) ? $subbutton['urlroot'] : $subbutton['url'];
14774 $tmpurl = dolCompletUrlForDropdownButton($tmpurl, $params, empty($subbutton['urlroot']));
14775 }
14776
14777 $subbuttonparam = array();
14778 if (!empty($subbutton['attr'])) {
14779 $subbuttonparam['attr'] = $subbutton['attr'];
14780 }
14781 $subbuttonparam['isDropDown'] = (empty($params['isDropDown']) ? ($subbutton['isDropDown'] ?? false) : $params['isDropDown']);
14782
14783 $out .= dolGetButtonAction($subbutton['text'] ?? '', $langs->trans($subbutton['label']), 'default', $tmpurl, $subbutton['id'] ?? '', $subbutton['perm'], $subbuttonparam);
14784 }
14785 $out .= "</div>";
14786 $out .= "</div>";
14787 } else {
14788 foreach ($url as $subbutton) { // Should loop on 1 record only
14789 if (!empty($subbutton['lang'])) {
14790 $langs->load($subbutton['lang']);
14791 }
14792
14793 if (!empty($subbutton['urlraw'])) {
14794 $tmpurl = $subbutton['urlraw']; // Use raw url, no url completion, use only what developer send
14795 } else {
14796 $tmpurl = !empty($subbutton['urlroot']) ? $subbutton['urlroot'] : $subbutton['url'];
14797 $tmpurl = dolCompletUrlForDropdownButton($tmpurl, $params, empty($subbutton['urlroot']));
14798 }
14799
14800 $label = $langs->trans($subbutton['label']);
14801 $text = $subbutton['text'] ?? '';
14802 if (empty($text)) {
14803 $text = $label;
14804 $label = '';
14805 }
14806
14807 $out .= dolGetButtonAction($label, $text, 'default', $tmpurl, '', $subbutton['perm'], $params);
14808 }
14809 }
14810
14811 return $out;
14812 }
14813
14814 // Here, $url is a simple link
14815 if (!empty($params['isDropdown']) || !empty($params['isDropDown'])) { // Use the dropdown-item style (not for action button)
14816 $class = "dropdown-item";
14817 } else {
14818 $class = 'butAction';
14819 if ($actionType == 'edit') {
14820 $class = 'butAction butActionEdit';
14821 } elseif ($actionType == 'email') {
14822 $class = 'butAction butActionEmail';
14823 } elseif ($actionType == 'clone') {
14824 $class = 'butAction butActionClone';
14825 } elseif ($actionType == 'cancel') {
14826 $class = 'butAction butActionDelete';
14827 } elseif ($actionType == 'danger' || $actionType == 'delete') {
14828 $class = 'butAction butActionDelete';
14829 if (!empty($url) && strpos($url, 'token=') === false) {
14830 $url .= '&token=' . newToken();
14831 }
14832 }
14833 }
14834 $attr = array(
14835 'class' => $class,
14836 'href' => empty($url) ? '' : $url,
14837 'title' => $label
14838 );
14839
14840 if (empty($text)) {
14841 $text = $label;
14842 $attr['title'] = ''; // if html not set, using label on title is redundant
14843 } else {
14844 $attr['title'] = $label;
14845 $attr['aria-label'] = $label;
14846 }
14847
14848 if (empty($userRight) || $userRight < 0) {
14849 $attr['class'] = 'butActionRefused';
14850 $attr['href'] = '';
14851 $attr['title'] = (($label && $text && $label != $text) ? $label : '');
14852 $attr['title'] = ($attr['title'] ? $attr['title'] . (empty($userRight) ? '<br>' : '') : '');
14853 $attr['title'] .= ((empty($userRight) && empty($label)) ? $langs->trans('NotEnoughPermissions') : '');
14854 }
14855
14856 if (!empty($id)) {
14857 $attr['id'] = $id;
14858 }
14859
14860 // Override attr
14861 if (!empty($params['attr']) && is_array($params['attr'])) {
14862 foreach ($params['attr'] as $key => $value) {
14863 if ($key == 'class') {
14864 $attr['class'] .= ' ' . $value;
14865 } elseif ($key == 'classOverride') {
14866 $attr['class'] = $value;
14867 } else {
14868 $attr[$key] = $value;
14869 }
14870 }
14871 }
14872
14873 // automatic add tooltip when title is detected
14874 if (!empty($attr['title']) && !empty($attr['class']) && strpos($attr['class'], 'classfortooltip') === false) {
14875 $attr['class'] .= ' classfortooltip';
14876 }
14877
14878 // Js Confirm button
14879 if ($userRight && !empty($params['confirm'])) {
14880 if (!is_array($params['confirm'])) {
14881 $params['confirm'] = array();
14882 }
14883
14884 if (empty($params['confirm']['url'])) {
14885 $params['confirm']['url'] = $url . (strpos($url, '?') > 0 ? '&' : '?') . 'confirm=yes';
14886 }
14887
14888 // for js disabled compatibility set $url as call to confirm action and $params['confirm']['url'] to confirmed action
14889 $attr['data-confirm-url'] = $params['confirm']['url'];
14890 $attr['data-confirm-title'] = !empty($params['confirm']['title']) ? $params['confirm']['title'] : $langs->trans('ConfirmBtnCommonTitle', $label);
14891 $attr['data-confirm-content'] = !empty($params['confirm']['content']) ? $params['confirm']['content'] : $langs->trans('ConfirmBtnCommonContent', $label);
14892 $attr['data-confirm-content'] = preg_replace("/\r|\n/", "", $attr['data-confirm-content']);
14893 $attr['data-confirm-action-btn-label'] = !empty($params['confirm']['action-btn-label']) ? $params['confirm']['action-btn-label'] : $langs->trans('Confirm');
14894 $attr['data-confirm-cancel-btn-label'] = !empty($params['confirm']['cancel-btn-label']) ? $params['confirm']['cancel-btn-label'] : $langs->trans('CloseDialog');
14895 $attr['data-confirm-modal'] = !empty($params['confirm']['modal']) ? $params['confirm']['modal'] : true;
14896
14897 $attr['class'] .= ' butActionConfirm';
14898 }
14899
14900 if (isset($attr['href']) && empty($attr['href'])) {
14901 unset($attr['href']);
14902 }
14903
14904 // TODO replace this $TCompiledAttr generation block by commonHtmlAttributeBuilder like line below
14905 // $TCompiledAttr = commonHtmlAttributeBuilder($attr, $params['use_unsecured_unescapedattr'] ?? []);
14906 $TCompiledAttr = array();
14907 foreach ($attr as $key => $value) {
14908 if (!empty($params['use_unsecured_unescapedattr']) && is_array($params['use_unsecured_unescapedattr']) && in_array($key, $params['use_unsecured_unescapedattr'])) {
14909 // Deprecated, forbidden.
14910 $value = dol_htmlentities($value, ENT_QUOTES | ENT_SUBSTITUTE);
14911 } elseif (in_array($key, ['href', 'data-confirm-url'])) {
14912 $value = dolPrintHTMLForAttributeUrl($value);
14913 } else {
14914 $value = dolPrintHTMLForAttribute($value);
14915 }
14916
14917 $TCompiledAttr[] = $key . '="' . $value . '"'; // $value has been escaped by the dolPrintHTMLForAttribute... just before
14918 }
14919 $compiledAttributes = empty($TCompiledAttr) ? '' : implode(' ', $TCompiledAttr);
14920
14921 $tag = !empty($attr['href']) ? 'a' : 'span';
14922
14923 $parameters = array(
14924 'TCompiledAttr' => $TCompiledAttr, // array
14925 'compiledAttributes' => $compiledAttributes, // string
14926 'attr' => $attr,
14927 'tag' => $tag,
14928 'label' => $label,
14929 'html' => $text,
14930 'actionType' => $actionType,
14931 'url' => $url,
14932 'id' => $id,
14933 'userRight' => $userRight,
14934 'params' => $params
14935 );
14936
14937 $reshook = $hookmanager->executeHooks('dolGetButtonAction', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
14938 if ($reshook < 0) {
14939 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
14940 }
14941
14942 if (empty($reshook)) {
14943 if (dol_textishtml($text)) { // If content already HTML encoded
14944 return '<' . $tag . ' ' . $compiledAttributes . '><span class="textbutton">' . $text . '</span></' . $tag . '>';
14945 } else {
14946 return '<' . $tag . ' ' . $compiledAttributes . '><span class="textbutton">' . dol_escape_htmltag($text) . '</span></' . $tag . '>';
14947 }
14948 } else {
14949 return $hookmanager->resPrint;
14950 }
14951}
14952
14983function commonHtmlAttributeBuilder($attr, array $unescapedAttr = [])
14984{
14985 $TCompiledAttr = array();
14986 if (empty($attr)) {
14987 return [];
14988 }
14989
14990 foreach ($attr as $key => $value) {
14991 // special boolean attributes case
14992 if (in_array($key, getListOfHtmlBooleanAttributes())) {
14993 if ($value) {
14994 $TCompiledAttr[$key] = $key;
14995 }
14996 continue;
14997 }
14998
14999 if (!empty($unescapedAttr) && in_array($key, $unescapedAttr)) {
15000 // Not recommended
15001 $value = dol_htmlentities((string) $value, ENT_QUOTES | ENT_SUBSTITUTE);
15002 } elseif ($key == 'href') {
15003 $value = dolPrintHTMLForAttributeUrl((string) $value);
15004 } else {
15005 $value = dolPrintHTMLForAttribute((string) $value);
15006 }
15007
15008 $TCompiledAttr[$key] = $key . '="' . $value . '"'; // $value has been escaped by the dolPrintHTMLForAttribute... just before
15009 }
15010
15011 return $TCompiledAttr;
15012}
15013
15028function getListOfHtmlBooleanAttributes(): array
15029{
15030 return [
15031 // Input / Form
15032 'checked',
15033 'disabled',
15034 'readonly',
15035 'required',
15036 'autofocus',
15037 'multiple',
15038
15039 // Option
15040 'selected',
15041
15042 // Form / General
15043 'novalidate',
15044 'formnovalidate',
15045
15046 // Media
15047 'autoplay',
15048 'controls',
15049 'loop',
15050 'muted',
15051 'playsinline',
15052
15053 // Other elements
15054 'hidden',
15055 'open',
15056 'ismap',
15057 'reversed',
15058 'allowfullscreen',
15059 'itemscope',
15060 'nomodule',
15061 'defer',
15062 'async',
15063 'default',
15064 'inert',
15065 ];
15066}
15067
15068
15077function dolCompletUrlForDropdownButton(string $url, array $params, bool $addDolUrlRoot = true)
15078{
15079 if (empty($url)) {
15080 return '';
15081 }
15082
15083 $parsedUrl = parse_url($url);
15084 if ((isset($parsedUrl['scheme']) && in_array($parsedUrl['scheme'], ['javascript', 'mailto', 'tel'])) || strpos($url, '#') === 0) {
15085 return $url;
15086 }
15087
15088 if (!empty($parsedUrl['query'])) {
15089 // Use parse_str() function to parse the string passed via URL
15090 $urlQuery = '';
15091 parse_str($parsedUrl['query'], $urlQuery);
15092 if (!isset($urlQuery['backtopage']) && isset($params['backtopage'])) {
15093 $url .= '&amp;backtopage=' . urlencode($params['backtopage']);
15094 }
15095 }
15096
15097 if (!isset($parsedUrl['scheme']) && $addDolUrlRoot) {
15098 $url = DOL_URL_ROOT . $url;
15099 }
15100
15101 return $url;
15102}
15103
15104
15111function dolGetButtonTitleSeparator($moreClass = "")
15112{
15113 return '<span class="button-title-separator ' . $moreClass . '" ></span>';
15114}
15115
15122function getFieldErrorIcon($fieldValidationErrorMsg)
15123{
15124 $out = '';
15125 if (!empty($fieldValidationErrorMsg)) {
15126 $out .= '<span class="field-error-icon classfortooltip" title="' . dol_escape_htmltag($fieldValidationErrorMsg, 1) . '" role="alert" >'; // role alert is used for accessibility
15127 $out .= '<span class="fa fa-exclamation-circle" aria-hidden="true" ></span>'; // For accessibility icon is separated and aria-hidden
15128 $out .= '</span>';
15129 }
15130
15131 return $out;
15132}
15133
15146function dolGetButtonTitle($label, $helpText = '', $iconClass = 'fa fa-file', $url = '', $id = '', $status = 1, $params = array())
15147{
15148 global $langs, $user;
15149
15150 // Actually this conf is used in css too for external module compatibility and smooth transition to this function
15151 if (getDolGlobalString('MAIN_BUTTON_HIDE_UNAUTHORIZED') && (!$user->admin) && $status <= 0) {
15152 return '';
15153 }
15154 // Fix old picto fa-th-list to use fa-grid-vertical instead
15155 if ($iconClass == 'fa fa-th-list imgforviewmode') {
15156 $iconClass = ' fa fa-grip-horizontal imgforviewmode';
15157 }
15158
15159 $class = 'btnTitle';
15160 if (in_array($iconClass, array('fa fa-plus-circle', 'fa fa-plus-circle size15x', 'fa fa-comment-dots', 'fa fa-paper-plane'))) {
15161 $class .= ' btnTitlePlus';
15162 }
15163 $useclassfortooltip = 1;
15164
15165 if (!empty($params['morecss'])) {
15166 $class .= ' ' . $params['morecss'];
15167 }
15168
15169 $attr = array(
15170 'class' => $class,
15171 'href' => empty($url) ? '' : $url
15172 );
15173
15174 if (!empty($helpText)) {
15175 $attr['title'] = $helpText;
15176 } elseif ($label) { // empty($attr['title']) &&
15177 $attr['title'] = $label;
15178 $useclassfortooltip = 0;
15179 }
15180
15181 if ($status == 2) {
15182 $attr['class'] .= ' btnTitleSelected';
15183 } elseif ($status <= 0) {
15184 $attr['class'] .= ' refused';
15185
15186 $attr['href'] = '';
15187
15188 if ($status == -1) { // disable
15189 $attr['title'] = $langs->transnoentitiesnoconv("FeatureDisabled");
15190 } elseif ($status == 0) { // Not enough permissions
15191 $attr['title'] = $langs->transnoentitiesnoconv("NotEnoughPermissions");
15192 }
15193 }
15194
15195 if (!empty($attr['title']) && $useclassfortooltip) {
15196 $attr['class'] .= ' classfortooltip';
15197 }
15198
15199 if (!empty($id)) {
15200 $attr['id'] = $id;
15201 }
15202
15203 // Override attr
15204 if (!empty($params['attr']) && is_array($params['attr'])) {
15205 foreach ($params['attr'] as $key => $value) {
15206 if ($key == 'class') {
15207 $attr['class'] .= ' ' . $value;
15208 } elseif ($key == 'classOverride') {
15209 $attr['class'] = $value;
15210 } else {
15211 $attr[$key] = $value;
15212 }
15213 }
15214 }
15215
15216 if (isset($attr['href']) && empty($attr['href'])) {
15217 unset($attr['href']);
15218 }
15219
15220 // TODO : add a hook
15221
15222 // Generate attributes with escapement
15223 $TCompiledAttr = array();
15224 foreach ($attr as $key => $value) {
15225 $TCompiledAttr[] = $key . '="' . dol_escape_htmltag($value) . '"'; // Do not use dolPrintHTMLForAttribute() here, we must accept "javascript:string"
15226 }
15227
15228 $compiledAttributes = (empty($TCompiledAttr) ? '' : implode(' ', $TCompiledAttr));
15229
15230 $tag = (empty($attr['href']) ? 'span' : 'a');
15231
15232 $button = '<' . $tag . ' ' . $compiledAttributes . '>';
15233 $button .= '<span class="' . $iconClass . ' valignmiddle btnTitle-icon"></span>';
15234 if (!empty($params['forcenohideoftext'])) {
15235 $button .= '<span class="valignmiddle text-plus-circle btnTitle-label' . (empty($params['forcenohideoftext']) ? ' hideonsmartphone' : '') . '">' . $label . '</span>';
15236 }
15237 $button .= '</' . $tag . '>';
15238
15239 return $button;
15240}
15241
15252function getElementProperties($elementType)
15253{
15254 global $conf, $db, $hookmanager;
15255
15256 $regs = array();
15257
15258 //$element_type='facture';
15259
15260 $classfile = $classname = $classpath = $subdir = $dir_output = $dir_temp = $parent_element = '';
15261
15262 // Parse element/subelement
15263 $module = $elementType;
15264 $element = $elementType;
15265 $subelement = $elementType;
15266 $table_element = $elementType;
15267
15268 // If we ask a resource form external module (instead of default path)
15269 if (preg_match('/^([^@]+)@([^@]+)$/i', $elementType, $regs)) { // 'myobject@mymodule'
15270 $element = $subelement = $regs[1];
15271 $module = $regs[2];
15272 }
15273
15274 // If we ask a resource for a string with an element and a subelement
15275 // Example 'project_task'
15276 if (preg_match('/^([^_]+)_([^_]+)/i', $element, $regs)) { // 'myobject_mysubobject' with myobject=mymodule
15277 $module = $element = $regs[1];
15278 $subelement = $regs[2];
15279 }
15280
15281 // Object lines will use parent classpath and module ref
15282 if (substr($elementType, -3) == 'det') {
15283 $module = preg_replace('/det$/', '', $element);
15284 $subelement = preg_replace('/det$/', '', $subelement);
15285 $classpath = $module . '/class';
15286 $classfile = $module;
15287 $classname = preg_replace('/det$/', 'Line', $element);
15288 if (in_array($module, array('expedition', 'propale', 'facture', 'contrat', 'fichinter', 'supplier_order', 'commandefournisseur'))) {
15289 $classname = preg_replace('/det$/', 'Ligne', $element);
15290 }
15291 }
15292 // For compatibility and to work with non standard path
15293 if ($elementType == "action" || $elementType == "actioncomm") {
15294 $classpath = 'comm/action/class';
15295 $subelement = 'Actioncomm';
15296 $module = 'agenda';
15297 $table_element = 'actioncomm';
15298 } elseif ($elementType == 'cronjob') {
15299 $classpath = 'cron/class';
15300 $module = 'cron';
15301 $table_element = 'cron';
15302 } elseif ($elementType == 'adherent_type') {
15303 $classpath = 'adherents/class';
15304 $classfile = 'adherent_type';
15305 $module = 'adherent';
15306 $subelement = 'adherent_type';
15307 $classname = 'AdherentType';
15308 $table_element = 'adherent_type';
15309 } elseif ($elementType == 'bank_account') {
15310 $classpath = 'compta/bank/class';
15311 $module = 'bank'; // We need $conf->bank->dir_output and not $conf->banque->dir_output
15312 $classfile = 'account';
15313 $classname = 'Account';
15314 } elseif ($elementType == 'bank_line') {
15315 $classpath = 'compta/bank/class';
15316 $module = 'bank'; // We need $conf->bank->dir_output and not $conf->banque->dir_output
15317 $classfile = 'account';
15318 $classname = 'AccountLine';
15319 } elseif ($elementType == 'category') {
15320 $classpath = 'categories/class';
15321 $module = 'categorie';
15322 $subelement = 'categorie';
15323 $table_element = 'categorie';
15324 } elseif ($elementType == 'contact') {
15325 $classpath = 'contact/class';
15326 $classfile = 'contact';
15327 $module = 'societe';
15328 $subelement = 'contact';
15329 $table_element = 'socpeople';
15330 } elseif ($elementType == 'inventory') {
15331 $module = 'product';
15332 $classpath = 'product/inventory/class';
15333 } elseif ($elementType == 'inventoryline') {
15334 $module = 'product';
15335 $classpath = 'product/inventory/class';
15336 $table_element = 'inventorydet';
15337 $parent_element = 'inventory';
15338 } elseif ($elementType == 'stock' || $elementType == 'entrepot' || $elementType == 'warehouse') {
15339 $module = 'stock';
15340 $classpath = 'product/stock/class';
15341 $classfile = 'entrepot';
15342 $classname = 'Entrepot';
15343 $table_element = 'entrepot';
15344 } elseif ($elementType == 'project') {
15345 $classpath = 'projet/class';
15346 $module = 'projet';
15347 $table_element = 'projet';
15348 } elseif ($elementType == 'project_task') {
15349 $classpath = 'projet/class';
15350 $module = 'projet';
15351 $subelement = 'task';
15352 $table_element = 'projet_task';
15353 } elseif ($elementType == 'mo') {
15354 $classpath = 'mrp/class';
15355 $module = 'mrp';
15356 $classfile = 'mo';
15357 $classname = 'Mo';
15358 $table_element = 'mrp_mo';
15359 } elseif ($elementType == 'facture' || $elementType == 'invoice') {
15360 $classpath = 'compta/facture/class';
15361 $module = 'facture';
15362 $subelement = 'facture';
15363 $table_element = 'facture';
15364 } elseif ($elementType == 'facturedet') {
15365 $classpath = 'compta/facture/class';
15366 $classfile = 'facture';
15367 $classname = 'FactureLigne';
15368 $module = 'facture';
15369 $table_element = 'facturedet';
15370 $parent_element = 'facture';
15371 } elseif ($elementType == 'facturerec' || $elementType == 'facture_rec') {
15372 $classpath = 'compta/facture/class';
15373 $classfile = 'facture-rec';
15374 $module = 'facture';
15375 $classname = 'FactureRec';
15376 } elseif ($elementType == 'commande' || $elementType == 'order') {
15377 $classpath = 'commande/class';
15378 $module = 'commande';
15379 $subelement = 'commande';
15380 $table_element = 'commande';
15381 } elseif ($elementType == 'commandedet') {
15382 $classpath = 'commande/class';
15383 $classfile = 'commande';
15384 $classname = 'OrderLine';
15385 $module = 'commande';
15386 $table_element = 'commandedet';
15387 $parent_element = 'commande';
15388 } elseif ($elementType == 'propal') {
15389 $classpath = 'comm/propal/class';
15390 $table_element = 'propal';
15391 } elseif ($elementType == 'propaldet') {
15392 $classpath = 'comm/propal/class';
15393 $classfile = 'propal';
15394 $subelement = 'propaleligne';
15395 $module = 'propal';
15396 $table_element = 'propaldet';
15397 $parent_element = 'propal';
15398 } elseif ($elementType == 'shipping' || $elementType == 'shipment') {
15399 $classpath = 'expedition/class';
15400 $classfile = 'expedition';
15401 $classname = 'Expedition';
15402 $module = 'expedition';
15403 $table_element = 'expedition';
15404 } elseif ($elementType == 'expeditiondet' || $elementType == 'shippingdet') {
15405 $classpath = 'expedition/class';
15406 $classfile = 'expedition';
15407 $classname = 'ExpeditionLigne';
15408 $module = 'expedition';
15409 $table_element = 'expeditiondet';
15410 $parent_element = 'expedition';
15411 } elseif ($elementType == 'delivery_note') {
15412 $classpath = 'delivery/class';
15413 $subelement = 'delivery';
15414 $module = 'expedition';
15415 } elseif ($elementType == 'delivery') {
15416 $classpath = 'delivery/class';
15417 $subelement = 'delivery';
15418 $module = 'expedition';
15419 } elseif ($elementType == 'deliverydet') {
15420 // @todo
15421 } elseif ($elementType == 'supplier_proposal') {
15422 $classpath = 'supplier_proposal/class';
15423 $module = 'supplier_proposal';
15424 $element = 'supplierproposal';
15425 $classfile = 'supplier_proposal';
15426 $subelement = 'supplierproposal';
15427 } elseif ($elementType == 'supplier_proposaldet') {
15428 $classpath = 'supplier_proposal/class';
15429 $module = 'supplier_proposal';
15430 $classfile = 'supplier_proposal';
15431 $classname = 'SupplierProposalLine';
15432 $table_element = 'supplier_proposaldet';
15433 $parent_element = 'supplier_proposal';
15434 } elseif ($elementType == 'contract') {
15435 $classpath = 'contrat/class';
15436 $module = 'contrat';
15437 $subelement = 'contrat';
15438 $table_element = 'contract';
15439 } elseif ($elementType == 'contratdet') {
15440 $classpath = 'contrat/class';
15441 $module = 'contrat';
15442 $table_element = 'contratdet';
15443 $parent_element = 'contrat';
15444 } elseif ($elementType == 'mailing') {
15445 $classpath = 'comm/mailing/class';
15446 $module = 'mailing';
15447 $classfile = 'mailing';
15448 $classname = 'Mailing';
15449 $subelement = '';
15450 } elseif ($elementType == 'member' || $elementType == 'adherent') {
15451 $classpath = 'adherents/class';
15452 $module = 'adherent';
15453 $subelement = 'adherent';
15454 $table_element = 'adherent';
15455 } elseif ($elementType == 'subscription') {
15456 $classpath = 'adherents/class';
15457 $classfile = 'subscription';
15458 $module = 'adherent';
15459 $subelement = 'subscription';
15460 $classname = 'Subscription';
15461 $table_element = 'subscription';
15462 } elseif ($elementType == 'usergroup') {
15463 $classpath = 'user/class';
15464 $module = 'user';
15465 } elseif ($elementType == 'mo' || $elementType == 'mrp') {
15466 $classpath = 'mrp/class';
15467 $classfile = 'mo';
15468 $classname = 'Mo';
15469 $module = 'mrp';
15470 $subelement = '';
15471 $table_element = 'mrp_mo';
15472 } elseif ($elementType == 'mrp_production') {
15473 $classpath = 'mrp/class';
15474 $classfile = 'mo';
15475 $classname = 'MoLine';
15476 $module = 'mrp';
15477 $subelement = '';
15478 $table_element = 'mrp_production';
15479 $parent_element = 'mo';
15480 } elseif ($elementType == 'cabinetmed_cons') {
15481 $classpath = 'cabinetmed/class';
15482 $module = 'cabinetmed';
15483 $subelement = 'cabinetmedcons';
15484 $table_element = 'cabinetmedcons';
15485 } elseif ($elementType == 'fichinter') {
15486 $classpath = 'fichinter/class';
15487 $module = 'ficheinter';
15488 $subelement = 'fichinter';
15489 $table_element = 'fichinter';
15490 } elseif ($elementType == 'dolresource' || $elementType == 'resource') {
15491 $classpath = 'resource/class';
15492 $module = 'resource';
15493 $subelement = 'dolresource';
15494 $table_element = 'resource';
15495 } elseif ($elementType == 'opensurvey_sondage') {
15496 $classpath = 'opensurvey/class';
15497 $module = 'opensurvey';
15498 $subelement = 'opensurveysondage';
15499 } elseif ($elementType == 'order_supplier' || $elementType == 'supplier_order' || $elementType == 'commande_fournisseur' || $elementType == 'commandefournisseur') {
15500 $classpath = 'fourn/class';
15501 $module = 'fournisseur';
15502 $classfile = 'fournisseur.commande';
15503 $element = 'order_supplier';
15504 $subelement = '';
15505 $classname = 'CommandeFournisseur';
15506 $table_element = 'commande_fournisseur';
15507 } elseif ($elementType == 'commande_fournisseurdet') {
15508 $classpath = 'fourn/class';
15509 $module = 'fournisseur';
15510 $classfile = 'fournisseur.commande';
15511 $element = 'commande_fournisseurdet';
15512 $subelement = '';
15513 $classname = 'CommandeFournisseurLigne';
15514 $table_element = 'commande_fournisseurdet';
15515 $parent_element = 'commande_fournisseur';
15516 } elseif ($elementType == 'invoice_supplier' || $elementType == 'supplier_invoice' || $elementType == 'facture_fourn') {
15517 $classpath = 'fourn/class';
15518 $module = 'fournisseur';
15519 $classfile = 'fournisseur.facture';
15520 $element = 'invoice_supplier';
15521 $subelement = '';
15522 $classname = 'FactureFournisseur';
15523 $table_element = 'facture_fourn';
15524 } elseif ($elementType == 'facture_fourn_det') {
15525 $classpath = 'fourn/class';
15526 $module = 'fournisseur';
15527 $classfile = 'fournisseur.facture';
15528 $element = 'facture_fourn_det';
15529 $subelement = '';
15530 $classname = 'SupplierInvoiceLine';
15531 $table_element = 'facture_fourn_det';
15532 $parent_element = 'invoice_supplier';
15533 } elseif ($elementType == "service") {
15534 $classpath = 'product/class';
15535 $subelement = 'product';
15536 $table_element = 'product';
15537 } elseif ($elementType == 'product_attribute') {
15538 $module = 'variants';
15539 $element = 'product_attribute';
15540 $subelement = 'product_attribute';
15541 $classpath = 'variants/class';
15542 $classfile = 'ProductAttribute';
15543 $classname = 'ProductAttribute';
15544 $table_element = 'product_attribute';
15545 } elseif ($elementType == 'product_attribute_value') {
15546 $module = 'variants';
15547 $element = 'product_attribute_value';
15548 $subelement = 'product_attribute_value';
15549 $classpath = 'variants/class';
15550 $classfile = 'ProductAttributeValue';
15551 $classname = 'ProductAttributeValue';
15552 $table_element = 'product_attribute_value';
15553 $parent_element = 'product_attribute';
15554 } elseif ($elementType == 'salary') {
15555 $classpath = 'salaries/class';
15556 $module = 'salaries';
15557 } elseif ($elementType == 'payment_salary') {
15558 $classpath = 'salaries/class';
15559 $classfile = 'paymentsalary';
15560 $classname = 'PaymentSalary';
15561 $module = 'salaries';
15562 } elseif ($elementType == 'productlot') {
15563 $module = 'productbatch';
15564 $classpath = 'product/stock/class';
15565 $classfile = 'productlot';
15566 $classname = 'Productlot';
15567 $element = 'productlot';
15568 $subelement = '';
15569 $table_element = 'product_lot';
15570 } elseif ($elementType == 'societeaccount') {
15571 $classpath = 'societe/class';
15572 $classfile = 'societeaccount';
15573 $classname = 'SocieteAccount';
15574 $module = 'societe';
15575 } elseif ($elementType == 'websitepage' || $elementType == 'website_page') {
15576 $classpath = 'website/class';
15577 $classfile = 'websitepage';
15578 $classname = 'Websitepage';
15579 $module = 'website';
15580 $subelement = 'websitepage';
15581 $table_element = 'website_page';
15582 } elseif ($elementType == 'fiscalyear') {
15583 $classpath = 'core/class';
15584 $module = 'accounting';
15585 $subelement = 'fiscalyear';
15586 } elseif ($elementType == 'chargesociales') {
15587 $classpath = 'compta/sociales/class';
15588 $module = 'tax';
15589 $table_element = 'chargesociales';
15590 } elseif ($elementType == 'tva') {
15591 $classpath = 'compta/tva/class';
15592 $module = 'tax';
15593 $subdir = '/vat';
15594 $table_element = 'tva';
15595 } elseif ($elementType == 'emailsenderprofile') {
15596 $module = '';
15597 $classpath = 'core/class';
15598 $classfile = 'emailsenderprofile';
15599 $classname = 'EmailSenderProfile';
15600 $table_element = 'c_email_senderprofile';
15601 $subelement = '';
15602 } elseif ($elementType == 'conferenceorboothattendee') {
15603 $classpath = 'eventorganization/class';
15604 $classfile = 'conferenceorboothattendee';
15605 $classname = 'ConferenceOrBoothAttendee';
15606 $module = 'eventorganization';
15607 } elseif ($elementType == 'conferenceorbooth') {
15608 $classpath = 'eventorganization/class';
15609 $classfile = 'conferenceorbooth';
15610 $classname = 'ConferenceOrBooth';
15611 $module = 'eventorganization';
15612 } elseif ($elementType == 'ccountry') {
15613 $module = '';
15614 $classpath = 'core/class';
15615 $classfile = 'ccountry';
15616 $classname = 'Ccountry';
15617 $table_element = 'c_country';
15618 $subelement = '';
15619 } elseif ($elementType == 'ecmfiles') {
15620 $module = 'ecm';
15621 $classpath = 'ecm/class';
15622 $classfile = 'ecmfiles';
15623 $classname = 'Ecmfiles';
15624 $table_element = 'ecmfiles';
15625 $subelement = '';
15626 } elseif ($elementType == 'knowledgerecord' || $elementType == 'knowledgemanagement') {
15627 $module = 'knowledgemanagement';
15628 $classpath = 'knowledgemanagement/class';
15629 $classfile = 'knowledgerecord';
15630 $classname = 'KnowledgeRecord';
15631 $table_element = 'knowledgemanagement_knowledgerecord';
15632 $subelement = '';
15633 } elseif ($elementType == 'customer') {
15634 $module = 'societe';
15635 $classpath = 'societe/class';
15636 $classfile = 'client';
15637 $classname = 'Client';
15638 $table_element = 'societe';
15639 $subelement = '';
15640 } elseif ($elementType == 'fournisseur' || $elementType == 'supplier') {
15641 $module = 'societe';
15642 $classpath = 'fourn/class';
15643 $classfile = 'fournisseur';
15644 $classname = 'Fournisseur';
15645 $table_element = 'societe';
15646 $subelement = '';
15647 } elseif ($elementType == 'recruitmentcandidature') {
15648 $module = 'recruitment';
15649 $classfile = 'recruitmentcandidature';
15650 $classpath = 'recruitment/class';
15651 $classname = 'RecruitmentCandidature';
15652 $subelement = 'recruitmentcandidature';
15653 $subdir = '/recruitmentcandidature';
15654 } elseif ($elementType == 'recruitmentjobposition') {
15655 $module = 'recruitment';
15656 $classfile = 'recruitmentjobposition';
15657 $classpath = 'recruitment/class';
15658 $classname = 'RecruitmentJobPosition';
15659 $subelement = 'recruitmentjobposition';
15660 $subdir = '/recruitmentjobposition';
15661 }
15662
15663
15664 if (empty($classfile)) {
15665 $classfile = strtolower($subelement);
15666 }
15667 if (empty($classname)) {
15668 $classname = ucfirst($subelement);
15669 }
15670 if (empty($classpath)) {
15671 $classpath = $module . '/class';
15672 }
15673
15674 //print 'getElementProperties subdir='.$subdir;
15675
15676 // Set dir_output
15677 if ($module && isset($conf->$module)) { // The generic case
15678 if (!empty($conf->$module->multidir_output[$conf->entity])) {
15679 $dir_output = $conf->$module->multidir_output[$conf->entity];
15680 } elseif (!empty($conf->$module->output[$conf->entity])) {
15681 $dir_output = $conf->$module->output[$conf->entity];
15682 } elseif (!empty($conf->$module->dir_output)) {
15683 $dir_output = $conf->$module->dir_output;
15684 }
15685 if (!empty($conf->$module->multidir_temp[$conf->entity])) {
15686 $dir_temp = $conf->$module->multidir_temp[$conf->entity];
15687 } elseif (!empty($conf->$module->temp[$conf->entity])) {
15688 $dir_temp = $conf->$module->temp[$conf->entity];
15689 } elseif (!empty($conf->$module->dir_temp)) {
15690 $dir_temp = $conf->$module->dir_temp;
15691 }
15692 }
15693
15694 // Overwrite value for special cases
15695 if ($element == 'order_supplier' && isModEnabled('fournisseur')) {
15696 $dir_output = $conf->fournisseur->commande->dir_output;
15697 $dir_temp = $conf->fournisseur->commande->dir_temp;
15698 } elseif ($element == 'invoice_supplier' && isModEnabled('fournisseur')) {
15699 $dir_output = $conf->fournisseur->facture->dir_output;
15700 $dir_temp = $conf->fournisseur->facture->dir_temp;
15701 }
15702 $dir_output .= $subdir;
15703 $dir_temp .= $subdir;
15704
15705 $elementProperties = array(
15706 'module' => $module,
15707 'element' => $element,
15708 'table_element' => $table_element,
15709 'subelement' => $subelement,
15710 'classpath' => $classpath,
15711 'classfile' => $classfile,
15712 'classname' => $classname,
15713 'dir_output' => $dir_output,
15714 'dir_temp' => $dir_temp,
15715 'parent_element' => $parent_element,
15716 );
15717
15718
15719 // Add hook
15720 if (!is_object($hookmanager)) {
15721 include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
15722 $hookmanager = new HookManager($db);
15723 }
15724 $hookmanager->initHooks(array('elementproperties'));
15725
15726
15727 // Hook params
15728 $parameters = array(
15729 'elementType' => $elementType,
15730 'elementProperties' => $elementProperties
15731 );
15732
15733 $reshook = $hookmanager->executeHooks('getElementProperties', $parameters);
15734
15735 if ($reshook) {
15736 $elementProperties = $hookmanager->resArray;
15737 } elseif (!empty($hookmanager->resArray) && is_array($hookmanager->resArray)) { // resArray is always an array but for security against misconfigured external modules
15738 $elementProperties = array_replace($elementProperties, $hookmanager->resArray);
15739 }
15740
15741 // context of elementproperties doesn't need to exist out of this function so delete it to avoid elementproperties context is equal to all
15742 if (($key = array_search('elementproperties', $hookmanager->contextarray)) !== false) {
15743 unset($hookmanager->contextarray[$key]);
15744 }
15745
15746 return $elementProperties;
15747}
15748
15762function fetchObjectByElement($element_id, $element_type, $element_ref = '', $useCache = 0, $maxCacheByType = 10)
15763{
15764 global $db, $conf;
15765
15766 $ret = 0;
15767
15768 $element_prop = getElementProperties($element_type);
15769 //var_dump($element_prop); exit;
15770
15771 if ($element_prop['module'] == 'product' || $element_prop['module'] == 'service') {
15772 // For example, for an extrafield 'product' (shared for both product and service) that is a link to an object,
15773 // this is called with $element_type = 'product' when we need element properties of a service, we must return a product. If we create the
15774 // extrafield for a service, it is not supported and not found when editing the product/service card. So we must keep 'product' for extrafields
15775 // of service and we will return properties of a product.
15776 $ismodenabled = (isModEnabled('product') || isModEnabled('service'));
15777 } elseif ($element_prop['module'] == 'societeaccount') {
15778 $ismodenabled = isModEnabled('website') || isModEnabled('webportal');
15779 } else {
15780 $ismodenabled = isModEnabled($element_prop['module']);
15781 }
15782 //var_dump('element_type='.$element_type);
15783 //var_dump($element_prop);
15784 //var_dump($element_prop['module'].' '.$ismodenabled);
15785 if (is_array($element_prop) && (empty($element_prop['module']) || $ismodenabled)) {
15786 if ($useCache === 1 && $element_id > 0
15787 && !empty($conf->cache['fetchObjectByElement'][$element_type])
15788 && !empty($conf->cache['fetchObjectByElement'][$element_type][$element_id])
15789 && is_object($conf->cache['fetchObjectByElement'][$element_type][$element_id])
15790 ) {
15791 return $conf->cache['fetchObjectByElement'][$element_type][$element_id];
15792 }
15793
15794 dol_include_once('/' . $element_prop['classpath'] . '/' . $element_prop['classfile'] . '.class.php');
15795
15796 if (class_exists($element_prop['classname'])) {
15797 $className = $element_prop['classname'];
15798 $objecttmp = new $className($db);
15799 '@phan-var-force CommonObject $objecttmp';
15802 if ($element_id > 0 || !empty($element_ref)) {
15803 $ret = $objecttmp->fetch($element_id, $element_ref);
15804 if ($ret > 0) {
15805 if (empty($objecttmp->module)) {
15806 $objecttmp->module = $element_prop['module'];
15807 }
15808
15809 if ($useCache > 0) {
15810 if (!isset($conf->cache['fetchObjectByElement'][$element_type])) {
15811 $conf->cache['fetchObjectByElement'][$element_type] = [];
15812 }
15813
15814 // Manage cache limit
15815 if (! empty($conf->cache['fetchObjectByElement'][$element_type]) && is_array($conf->cache['fetchObjectByElement'][$element_type]) && count($conf->cache['fetchObjectByElement'][$element_type]) >= $maxCacheByType) {
15816 array_shift($conf->cache['fetchObjectByElement'][$element_type]);
15817 }
15818
15819 $conf->cache['fetchObjectByElement'][$element_type][$element_id] = $objecttmp;
15820 }
15821
15822 return $objecttmp;
15823 }
15824 } else {
15825 return $objecttmp; // returned an object without fetch
15826 }
15827 } else {
15828 dol_syslog($element_prop['classname'] . ' doesn\'t exists in /' . $element_prop['classpath'] . '/' . $element_prop['classfile'] . '.class.php');
15829 return -1;
15830 }
15831 }
15832
15833 return $ret;
15834}
15835
15841function getExecutableContent()
15842{
15843 $arrayofregexextension = array(
15844 'htm',
15845 'html',
15846 'shtml',
15847 'js',
15848 'phar',
15849 'php',
15850 'php3',
15851 'php4',
15852 'php5',
15853 'phtml',
15854 'pht',
15855 'pl',
15856 'py',
15857 'cgi',
15858 'ksh',
15859 'sh',
15860 'shtml',
15861 'bash',
15862 'bat',
15863 'cmd',
15864 'wpk',
15865 'exe',
15866 'dmg',
15867 'appimage'
15868 );
15869
15870 return $arrayofregexextension;
15871}
15872
15879function isAFileWithExecutableContent($filename)
15880{
15881 $arrayofregexextension = getExecutableContent();
15882
15883 foreach ($arrayofregexextension as $fileextension) {
15884 if (preg_match('/\.' . preg_quote($fileextension, '/') . '$/i', $filename)) {
15885 return true;
15886 }
15887 }
15888
15889 return false;
15890}
15891
15899function newToken()
15900{
15901 return empty($_SESSION['newtoken']) ? '' : $_SESSION['newtoken'];
15902}
15903
15911function currentToken()
15912{
15913 return isset($_SESSION['token']) ? $_SESSION['token'] : '';
15914}
15915
15921function getNonce()
15922{
15923 global $conf;
15924
15925 if (empty($conf->cache['nonce'])) {
15926 include_once DOL_DOCUMENT_ROOT . '/core/lib/security.lib.php';
15927 $conf->cache['nonce'] = dolGetRandomBytes(8);
15928 }
15929
15930 return $conf->cache['nonce'];
15931}
15932
15933
15947function startSimpleTable($header, $link = "", $arguments = "", $emptyColumns = 0, $number = -1, $pictofulllist = '')
15948{
15949 global $langs;
15950
15951 print '<div class="div-table-responsive-no-min">';
15952 print '<table class="noborder centpercent">';
15953 print '<tr class="liste_titre">';
15954
15955 print ($emptyColumns < 1) ? '<th>' : '<th colspan="' . ($emptyColumns + 1) . '">';
15956
15957 print '<span class="valignmiddle">' . $langs->trans($header) . '</span>';
15958
15959 if (!empty($link)) {
15960 if (!empty($arguments)) {
15961 print '<a href="' . DOL_URL_ROOT . '/' . $link . '?' . $arguments . '">';
15962 } else {
15963 print '<a href="' . DOL_URL_ROOT . '/' . $link . '">';
15964 }
15965 }
15966
15967 if ($number > -1) {
15968 print '<span class="badge marginleftonlyshort">' . $number . '</span>';
15969 } elseif (!empty($link)) {
15970 print '<span class="badge marginleftonlyshort">...</span>';
15971 }
15972
15973 if (!empty($link)) {
15974 print '</a>';
15975 }
15976
15977 print '</th>';
15978
15979 if ($number < 0 && !empty($link)) {
15980 print '<th class="right">';
15981 print '</th>';
15982 }
15983
15984 print '</tr>';
15985}
15986
15995function finishSimpleTable($addLineBreak = false)
15996{
15997 print '</table>';
15998 print '</div>';
15999
16000 if ($addLineBreak) {
16001 print '<br>';
16002 }
16003}
16004
16016function addSummaryTableLine($tableColumnCount, $num, $nbofloop = 0, $total = 0, $noneWord = "None", $extraRightColumn = false)
16017{
16018 global $langs;
16019
16020 if ($num === 0) {
16021 print '<tr class="oddeven">';
16022 print '<td colspan="' . $tableColumnCount . '"><span class="opacitymedium">' . $langs->trans($noneWord) . '</span></td>';
16023 print '</tr>';
16024 return;
16025 }
16026
16027 if ($nbofloop === 0) {
16028 // don't show a summary line
16029 return;
16030 }
16031
16032 /* Case already handled above, commented to satisfy phpstan.
16033 if ($num === 0) {
16034 $colspan = $tableColumnCount;
16035 } else
16036 */
16037 if ($num > $nbofloop) {
16038 $colspan = $tableColumnCount;
16039 } else {
16040 $colspan = $tableColumnCount - 1;
16041 }
16042
16043 if ($extraRightColumn) {
16044 $colspan--;
16045 }
16046
16047 print '<tr class="liste_total">';
16048
16049 if ($nbofloop > 0 && $num > $nbofloop) {
16050 print '<td colspan="' . $colspan . '" class="right">' . $langs->trans("XMoreLines", ($num - $nbofloop)) . '</td>';
16051 } else {
16052 print '<td colspan="' . $colspan . '" class="right"> ' . $langs->trans("Total") . '</td>';
16053 print '<td class="right centpercent">' . price($total) . '</td>';
16054 }
16055
16056 if ($extraRightColumn) {
16057 print '<td></td>';
16058 }
16059
16060 print '</tr>';
16061}
16062
16071function readfileLowMemory($fullpath_original_file_osencoded, $method = -1)
16072{
16073 if ($method == -1) {
16074 $method = 0;
16075 if (getDolGlobalString('MAIN_FORCE_READFILE_WITH_FREAD')) {
16076 $method = 1;
16077 }
16078 if (getDolGlobalString('MAIN_FORCE_READFILE_WITH_STREAM_COPY')) {
16079 $method = 2;
16080 }
16081 }
16082
16083 // Be sure we don't have output buffering enabled to have readfile working correctly
16084 $level = ob_get_level();
16085 ob_start();
16086 while (ob_get_level() > $level) {
16087 ob_end_clean();
16088 }
16089
16090 // Solution 0
16091 if ($method == 0) {
16092 readfile($fullpath_original_file_osencoded);
16093 } elseif ($method == 1) {
16094 // Solution 1
16095 $handle = fopen($fullpath_original_file_osencoded, "rb");
16096 while (!feof($handle)) {
16097 print fread($handle, 8192);
16098 }
16099 fclose($handle);
16100 } elseif ($method == 2) {
16101 // Solution 2
16102 $handle1 = fopen($fullpath_original_file_osencoded, "rb");
16103 $handle2 = fopen("php://output", "wb");
16104 stream_copy_to_stream($handle1, $handle2);
16105 fclose($handle1);
16106 fclose($handle2);
16107 }
16108}
16109
16119function showValueWithClipboardCPButton($valuetocopy, $showonlyonhover = 1, $texttoshow = '')
16120{
16121 global $langs;
16122
16123 $tag = 'span'; // Using div (like any style of type 'block') does not work when using the js copy code.
16124
16125 $result = '<span class="clipboardCP' . ($showonlyonhover ? ' clipboardCPShowOnHover valignmiddle' : '') . '">';
16126 if ($texttoshow === 'none') {
16127 $result .= '<' . $tag . ' class="clipboardCPValue hidewithsize">' . dol_escape_htmltag($valuetocopy, 1, 1) . '</' . $tag . '>';
16128 $result .= '<span class="clipboardCPValueToPrint"></span>';
16129 } elseif ($texttoshow) {
16130 $result .= '<' . $tag . ' class="clipboardCPValue hidewithsize">' . dol_escape_htmltag($valuetocopy, 1, 1) . '</' . $tag . '>';
16131 $result .= '<span class="clipboardCPValueToPrint">' . dol_escape_htmltag($texttoshow, 1, 1) . '</span>';
16132 } else {
16133 $result .= '<' . $tag . ' class="clipboardCPValue">' . dol_escape_htmltag($valuetocopy, 1, 1) . '</' . $tag . '>';
16134 }
16135 $result .= '<span class="clipboardCPButton far fa-clipboard opacitymedium paddingleft pictomodule" title="' . dolPrintHTML($langs->trans("ClickToCopyToClipboard")) . '"></span>';
16136 $result .= img_picto('', 'tick', 'class="clipboardCPTick hidden paddingleft pictomodule"');
16137 $result .= '<span class="clipboardCPText"></span>';
16138 $result .= '</span>';
16139
16140 return $result;
16141}
16142
16143
16151function jsonOrUnserialize($stringtodecode, $assoc = true)
16152{
16153 $result = json_decode($stringtodecode, $assoc);
16154 if ($result === null) {
16155 $result = unserialize($stringtodecode, ['allowed_classes' => false]); // For backward compatibility. Is no more used in recent versions.
16156 }
16157
16158 return $result;
16159}
16160
16161
16179function forgeSQLFromUniversalSearchCriteria($filter, &$errorstr = '', $noand = 0, $nopar = 0, $noerror = 0, $forbiddenfields = array())
16180{
16181 global $db, $user;
16182
16183 if (is_null($filter) || !is_string($filter) || $filter === '') {
16184 return '';
16185 }
16186 if (!preg_match('/^\‍(.*\‍)$/', $filter)) { // If $filter does not start and end with ()
16187 $filter = '(' . $filter . ')';
16188 }
16189
16190 $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'
16191 $firstandlastparenthesis = 0;
16192
16193 if (!dolCheckFilters($filter, $errorstr, $firstandlastparenthesis)) {
16194 if ($noerror) {
16195 return '1 = 2';
16196 } else {
16197 return 'Filter syntax error - ' . $errorstr; // Bad balance of parenthesis, we return an error message or force a SQL not found
16198 }
16199 }
16200
16201 // Test the filter syntax
16202 $t = preg_replace_callback('/' . $regexstring . '/i', 'dolForgeDummyCriteriaCallback', $filter);
16203 $t = str_ireplace(array('and', 'or', ' '), '', $t); // Remove the only strings allowed between each () criteria
16204
16205 // If the string result contains something else than '()', the syntax was wrong
16206 if (preg_match('/[^\‍(\‍)]/', $t)) {
16207 $tmperrorstr = 'Bad syntax of the search string';
16208 $errorstr = 'Bad syntax of the search string: ' . $filter;
16209 if ($noerror) {
16210 return '1 = 2';
16211 } else {
16212 dol_syslog("forgeSQLFromUniversalSearchCriteria Filter error - " . $errorstr, LOG_WARNING);
16213 return 'Filter error - ' . $tmperrorstr; // Bad syntax of the search string, we return an error message or force a SQL not found
16214 }
16215 }
16216
16217 global $globalforbiddenfields; // For use by dolForgeSQLCriteriaCallback()
16218 $globalforbiddenfields = $forbiddenfields;
16219
16220 $ret = ($noand ? "" : " AND ") . ($nopar ? "" : '(');
16221 $ret .= preg_replace_callback('/' . $regexstring . '/i', 'dolForgeSQLCriteriaCallback', $filter);
16222 $ret .= ($nopar ? "" : ')');
16223
16224 if (is_object($db)) {
16225 $ret = str_replace('__NOW__', "'" . $db->idate(dol_now()) . "'", $ret);
16226 }
16227 if (is_object($user)) {
16228 $ret = str_replace('__USER_ID__', (string) $user->id, $ret);
16229 }
16230
16231 return $ret;
16232}
16233
16241function dolForgeExplodeAnd($sqlfilters)
16242{
16243 $arrayofandtags = array();
16244 $nbofchars = dol_strlen($sqlfilters);
16245
16246 $error = '';
16247 $parenthesislevel = 0;
16248 $result = dolCheckFilters($sqlfilters, $error, $parenthesislevel);
16249 if (!$result) {
16250 return array();
16251 }
16252 if ($parenthesislevel >= 1) {
16253 $sqlfilters = preg_replace('/^\‍(/', '', preg_replace('/\‍)$/', '', $sqlfilters));
16254 }
16255
16256 $i = 0;
16257 $s = '';
16258 $countparenthesis = 0;
16259 while ($i < $nbofchars) {
16260 $char = dol_substr($sqlfilters, $i, 1);
16261
16262 if ($char == '(') {
16263 $countparenthesis++;
16264 } elseif ($char == ')') {
16265 $countparenthesis--;
16266 }
16267
16268 if ($countparenthesis == 0) {
16269 $char2 = dol_substr($sqlfilters, $i + 1, 1);
16270 $char3 = dol_substr($sqlfilters, $i + 2, 1);
16271 if ($char == 'A' && $char2 == 'N' && $char3 == 'D') {
16272 // We found a AND
16273 $s = trim($s);
16274 if (!preg_match('/^\‍(.*\‍)$/', $s)) {
16275 $s = '(' . $s . ')';
16276 }
16277 $arrayofandtags[] = $s;
16278 $s = '';
16279 $i += 2;
16280 } else {
16281 $s .= $char;
16282 }
16283 } else {
16284 $s .= $char;
16285 }
16286 $i++;
16287 }
16288 if ($s) {
16289 $s = trim($s);
16290 if (!preg_match('/^\‍(.*\‍)$/', $s)) {
16291 $s = '(' . $s . ')';
16292 }
16293 $arrayofandtags[] = $s;
16294 }
16295
16296 return $arrayofandtags;
16297}
16298
16308function dolCheckFilters($sqlfilters, &$error = '', &$parenthesislevel = 0)
16309{
16310 //$regexstring='\‍(([^:\'\‍(\‍)]+:[^:\'\‍(\‍)]+:[^:\‍(\‍)]+)\‍)';
16311 //$tmp=preg_replace_all('/'.$regexstring.'/', '', $sqlfilters);
16312 $tmp = $sqlfilters;
16313
16314 $nb = dol_strlen($tmp);
16315 $counter = 0;
16316 $parenthesislevel = 0;
16317
16318 $error = '';
16319
16320 $i = 0;
16321 while ($i < $nb) {
16322 $char = dol_substr($tmp, $i, 1);
16323
16324 if ($char == '(') {
16325 if ($i == $parenthesislevel && $parenthesislevel == $counter) {
16326 // We open a parenthesis and it is the first char
16327 $parenthesislevel++;
16328 }
16329 $counter++;
16330 } elseif ($char == ')') {
16331 $nbcharremaining = ($nb - $i - 1);
16332 if ($nbcharremaining >= $counter) {
16333 $parenthesislevel = min($parenthesislevel, $counter - 1);
16334 }
16335 if ($parenthesislevel > $counter && $nbcharremaining >= $counter) {
16336 $parenthesislevel = $counter;
16337 }
16338 $counter--;
16339 }
16340
16341 if ($counter < 0) {
16342 $error = "Wrong balance of parenthesis in sqlfilters=" . $sqlfilters;
16343 $parenthesislevel = 0;
16344 dol_syslog($error, LOG_WARNING);
16345 return false;
16346 }
16347
16348 $i++;
16349 }
16350
16351 if ($counter > 0) {
16352 $error = "Wrong balance of parenthesis in sqlfilters=" . $sqlfilters;
16353 $parenthesislevel = 0;
16354 dol_syslog($error, LOG_WARNING);
16355 return false;
16356 }
16357
16358 return true;
16359}
16360
16368function dolForgeDummyCriteriaCallback($matches)
16369{
16370 //dol_syslog("Convert matches ".$matches[1]);
16371 if (empty($matches[1])) {
16372 return '';
16373 }
16374 $tmp = explode(':', $matches[1]);
16375 if (count($tmp) < 3) {
16376 return '';
16377 }
16378
16379 return '()'; // An empty criteria
16380}
16381
16391function dolForgeSQLCriteriaCallback($matches)
16392{
16393 global $db;
16394 global $globalforbiddenfields;
16395
16396 //dol_syslog("Convert matches ".$matches[1]);
16397 if (empty($matches[1])) {
16398 return '';
16399 }
16400 $tmp = explode(':', $matches[1], 3);
16401 if (count($tmp) < 3) {
16402 return '';
16403 }
16404
16405 // Add fields that are forbidden by the caller when using USF search criteria
16406 // so we can't guess them using sequantial comparisons
16407 $newforbiddenfields = $globalforbiddenfields;
16408 if (!is_array($newforbiddenfields)) {
16409 $newforbiddenfields = array();
16410 }
16411 // Add fields that are ALWAYS forbidden when using USF search criteria
16412 $newforbiddenfields[] = 'pass';
16413 $newforbiddenfields[] = 'pass_crypted';
16414 $newforbiddenfields[] = 'pass_temp';
16415 $newforbiddenfields[] = 'api_key';
16416
16417 $operand = preg_replace('/[^a-z0-9\._]/i', '', trim($tmp[0]));
16418
16419 // An operand with more than one level of prefix (example: dbprefix.table.field) is not valid into a USF criteria,
16420 // we neutralize it like a forbidden field to avoid any leak or SQL error based on db prefix existence
16421 if (substr_count($operand, '.') > 1) {
16422 return '1=1';
16423 }
16424
16425 // Test that operand is not a forbidden search field
16426 if (!empty($newforbiddenfields)) {
16427 $operandwithoutprefix = preg_replace('/^[a-z0-9_]+\./i', '', $operand); // Remove prefix like t. or o. or s. or u. or d. or ...
16428 if (in_array(strtolower($operandwithoutprefix), $newforbiddenfields)) {
16429 return '1=1';
16430 }
16431 }
16432
16433 $operator = strtoupper(preg_replace('/[^a-z<>!=]/i', '', trim($tmp[1])));
16434
16435 $realOperator = [
16436 'NOTLIKE' => 'NOT LIKE',
16437 'ISNOT' => 'IS NOT',
16438 'NOTIN' => 'NOT IN',
16439 '!=' => '<>',
16440 ];
16441
16442 if (array_key_exists($operator, $realOperator)) {
16443 $operator = $realOperator[$operator];
16444 }
16445
16446 $tmpescaped = $tmp[2];
16447
16448 //print "Case: ".$operator." ".$operand." ".$tmpescaped."\n";
16449
16450 $regbis = array();
16451
16452 if ($operator == 'IN' || $operator == 'NOT IN') { // IN is allowed for list of ID/code/field only (or subrequest if $dolibarr_allow_unsecured_select_in_extrafields_filter not enabled)
16453 global $dolibarr_allow_unsecured_select_in_extrafields_filter;
16454
16455 //if (!preg_match('/^\‍(.*\‍)$/', $tmpescaped)) {
16456 $tmpescaped2 = '(';
16457 // Explode and sanitize each element in list
16458 $tmpelemarray = explode(',', $tmpescaped);
16459 foreach ($tmpelemarray as $tmpkey => $tmpelem) {
16460 $reg = array();
16461 $tmpelem = trim($tmpelem);
16462 if (preg_match('/^\'(.*)\'$/', $tmpelem, $reg)) {
16463 $tmpelemarray[$tmpkey] = "'" . $db->escape($db->sanitize($reg[1], 2, 1, 1, 1)) . "'";
16464 $tmpelemarray[$tmpkey] = "'".$db->escape($db->sanitize($reg[1], 2, 1, 1, 1))."'";
16465 } elseif (preg_match('/^[0-9]+$/', (string) $tmpelem)) { // if only 0-9 chars, no .
16466 $tmpelemarray[$tmpkey] = (int) $tmpelem;
16467 } elseif (is_numeric((string) $tmpelem)) { // it can be a float with a .
16468 $tmpelemarray[$tmpkey] = (float) $tmpelem;
16469 } elseif (!empty($dolibarr_allow_unsecured_select_in_extrafields_filter)) {
16470 $tmpelemarray[$tmpkey] = preg_replace('/[^a-z0-9_<>=!\s]/i', '', $tmpelem); // it can be a full subrequest (should be removed in a future as it allows blind SQL injection)
16471 } else {
16472 $tmpelemarray[$tmpkey] = preg_replace('/[^a-z0-9_]/i', '', $tmpelem); // it can be a name of field or a substitution variable like '__NOW__'
16473 }
16474 }
16475 $tmpescaped2 .= implode(',', $tmpelemarray);
16476 $tmpescaped2 .= ')';
16477
16478 $tmpescaped = $tmpescaped2;
16479 } elseif ($operator == 'LIKE' || $operator == 'NOT LIKE') {
16480 if (preg_match('/^\'([^\']*)\'$/', $tmpescaped, $regbis)) {
16481 $tmpescaped = $regbis[1];
16482 }
16483 //$tmpescaped = "'".$db->escape($db->escapeforlike($regbis[1]))."'";
16484 $tmpescaped = "'" . $db->escape($tmpescaped) . "'"; // We do not escape the _ and % so the LIKE will work as expected
16485 } elseif (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) {
16486 // TODO Retrieve type of field for $operand field name.
16487 // So we can complete format. For example we could complete a year with month and day.
16488 $tmpescaped = "'" . $db->escape($regbis[1]) . "'";
16489 } else {
16490 if (strtoupper($tmpescaped) == 'NULL') {
16491 $tmpescaped = 'NULL';
16492 } elseif (preg_match('/^[0-9]+$/', (string) $tmpescaped)) { // if only 0-9 chars, no .
16493 $tmpescaped = (int) $tmpescaped;
16494 } elseif (is_numeric((string) $tmpescaped)) { // it can be a float with a .
16495 $tmpescaped = (float) $tmpescaped;
16496 } else {
16497 $tmpescaped = preg_replace('/[^a-z0-9_]/i', '', $tmpescaped); // it can be a name of field or a substitution variable like '__NOW__'
16498 }
16499 }
16500
16501 return '(' . $db->escape($operand) . ' ' . strtoupper($operator) . ' ' . $tmpescaped . ')';
16502}
16503
16504
16514function getTimelineIcon($actionstatic, &$histo, $key)
16515{
16516 dol_syslog('getTimelineIcon::begin', LOG_DEBUG);
16517 global $langs;
16518
16519 $out = '<!-- timeline icon -->' . "\n";
16520 $iconClass = 'fa fa-comments';
16521 $img_picto = '';
16522 $colorClass = '';
16523 $pictoTitle = '';
16524
16525 if ($histo[$key]['percent'] == -1) {
16526 $colorClass = 'timeline-icon-not-applicble';
16527 $pictoTitle = $langs->trans('StatusNotApplicable');
16528 } elseif ($histo[$key]['percent'] == 0) {
16529 $colorClass = 'timeline-icon-todo';
16530 $pictoTitle = $langs->trans('StatusActionToDo') . ' (0%)';
16531 } elseif ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100) {
16532 $colorClass = 'timeline-icon-in-progress';
16533 $pictoTitle = $langs->trans('StatusActionInProcess') . ' (' . $histo[$key]['percent'] . '%)';
16534 } elseif ($histo[$key]['percent'] >= 100) {
16535 $colorClass = 'timeline-icon-done';
16536 $pictoTitle = $langs->trans('StatusActionDone') . ' (100%)';
16537 }
16538
16539 if ($actionstatic->code == 'AC_TICKET_CREATE') {
16540 $iconClass = 'fa fa-ticket';
16541 } elseif ($actionstatic->code == 'AC_TICKET_MODIFY') {
16542 $iconClass = 'fa fa-pencilxxx';
16543 } elseif (preg_match('/^TICKET_MSG/', $actionstatic->code)) {
16544 $iconClass = 'fa fa-comments';
16545 } elseif (preg_match('/^TICKET_MSG_PRIVATE/', $actionstatic->code)) {
16546 $iconClass = 'fa fa-mask';
16547 } elseif (getDolGlobalString('AGENDA_USE_EVENT_TYPE')) {
16548 if ($actionstatic->type_picto) {
16549 $img_picto = img_picto('', $actionstatic->type_picto);
16550 } else {
16551 if ($actionstatic->type_code == 'AC_RDV') {
16552 $iconClass = 'fa fa-handshake';
16553 } elseif ($actionstatic->type_code == 'AC_TEL') {
16554 $iconClass = 'fa fa-phone';
16555 } elseif ($actionstatic->type_code == 'AC_FAX') {
16556 $iconClass = 'fa fa-fax';
16557 } elseif ($actionstatic->type_code == 'AC_EMAIL') {
16558 $iconClass = 'fa fa-envelope';
16559 } elseif ($actionstatic->type_code == 'AC_INT') {
16560 $iconClass = 'fa fa-shipping-fast';
16561 } elseif ($actionstatic->type_code == 'AC_OTH_AUTO') {
16562 $iconClass = 'fa fa-robot';
16563 } elseif (!preg_match('/_AUTO/', $actionstatic->type_code)) {
16564 $iconClass = 'fa fa-robot';
16565 }
16566 }
16567 }
16568
16569 $out .= '<i class="' . $iconClass . ' ' . $colorClass . '" title="' . $pictoTitle . '">' . $img_picto . '</i>' . "\n";
16570 return $out;
16571}
16572
16580{
16581 global $db;
16582
16583 $documents = array();
16584
16585 $sql = 'SELECT ecm.rowid as id, ecm.src_object_type, ecm.src_object_id, ecm.filepath, ecm.filename, ecm.agenda_id';
16586 $sql .= ' FROM ' . MAIN_DB_PREFIX . 'ecm_files ecm';
16587 $sql .= " WHERE ecm.filepath = 'agenda/" . ((int) $object->id) . "'";
16588 //$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
16589 $sql .= ' OR ecm.agenda_id = ' . (int) $object->id;
16590 $sql .= ' ORDER BY ecm.position ASC';
16591
16592 $resql = $db->query($sql);
16593 if ($resql) {
16594 if ($db->num_rows($resql)) {
16595 while ($obj = $db->fetch_object($resql)) {
16596 $documents[$obj->id] = $obj;
16597 }
16598 }
16599 }
16600
16601 return $documents;
16602}
16603
16604
16622function show_actions_messaging($conf, $langs, $db, $filterobj, $objcon = null, $noprint = 0, $actioncode = '', $donetodo = 'done', $filters = array(), $sortfield = 'a.datep,a.id', $sortorder = 'DESC')
16623{
16624 dol_syslog('show_actions_messaging::begin', LOG_DEBUG);
16625 global $user, $conf;
16626 global $form;
16627
16628 global $param, $massactionbutton;
16629
16630 require_once DOL_DOCUMENT_ROOT . '/comm/action/class/actioncomm.class.php';
16631
16632 // Check parameters
16633 if (!is_object($filterobj) && !is_object($objcon)) {
16634 dol_print_error(null, 'BadParameter');
16635 }
16636
16637 $histo = array();
16638 '@phan-var-force array<int,array{type:string,tododone:string,id:string,datestart:int|string,dateend:int|string,fulldayevent:int,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';
16639
16640 $numaction = 0;
16641 $now = dol_now();
16642
16643 $sortfield_list = explode(',', $sortfield);
16644 $sortfield_label_list = array('a.id' => 'id', 'a.datep' => 'dp', 'a.percent' => 'percent');
16645 $sanitized_sortfield_new_list = array();
16646 foreach ($sortfield_list as $sortfield_value) {
16647 $sanitized_sortfield_new_list[] = $sortfield_label_list[trim($sortfield_value)]; //@phan-suppress-current-line SqlInjection
16648 }
16649 $sanitized_sortfield_new = implode(',', $sanitized_sortfield_new_list);
16650
16651 $sql = null;
16652 $sql2 = null;
16653
16654 if (isModEnabled('agenda')) {
16655 // Search histo on actioncomm
16656 if (is_object($objcon) && $objcon->id > 0) {
16657 $sql = "SELECT DISTINCT a.id, a.label as label,";
16658 } else {
16659 $sql = "SELECT a.id, a.label as label,";
16660 }
16661 $sql .= " a.datep as dp,";
16662 $sql .= " a.note as message,";
16663 $sql .= " a.datep2 as dp2,";
16664 $sql .= " a.percent as percent, 'action' as type,";
16665 $sql .= " a.fk_element, a.elementtype,";
16666 $sql .= " a.fk_contact, a.fulldayevent,";
16667 $sql .= " a.email_from as msg_from,";
16668 $sql .= " c.code as acode, c.libelle as alabel, c.picto as apicto,";
16669 $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";
16670 if (is_object($filterobj) && get_class($filterobj) == 'Societe') {
16671 $sql .= ", sp.lastname, sp.firstname";
16672 } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
16673 $sql .= ", m.lastname, m.firstname";
16674 } elseif (is_object($filterobj) && in_array(get_class($filterobj), array('Commande', 'CommandeFournisseur', 'Product', 'Ticket', 'BOM', 'Contrat', 'Facture', 'FactureFournisseur', 'Propal', 'Expedition'))) {
16675 $sql .= ", o.ref";
16676 } else {
16677 if (is_object($filterobj) && !empty($filterobj->table_element) && !empty($filterobj->element) && !empty($filterobj->id) && array_key_exists('ref', $filterobj->fields)) {
16678 $sql .= ", o.ref";
16679 }
16680 }
16681 $sql .= " FROM " . MAIN_DB_PREFIX . "actioncomm as a";
16682 $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "user as u on u.rowid = a.fk_user_action";
16683 $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_actioncomm as c ON a.fk_action = c.id";
16684
16685 $force_filter_contact = $filterobj instanceof User;
16686
16687 if (is_object($objcon) && $objcon->id > 0) {
16688 $force_filter_contact = true;
16689 $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "actioncomm_resources as r ON a.id = r.fk_actioncomm";
16690 $sql .= " AND r.element_type = '" . $db->escape($objcon->table_element) . "' AND r.fk_element = " . ((int) $objcon->id);
16691 }
16692
16693 if ((is_object($filterobj) && get_class($filterobj) == 'Societe') || (is_object($filterobj) && get_class($filterobj) == 'Contact')) {
16694 $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "socpeople as sp ON a.fk_contact = sp.rowid";
16695 } elseif (is_object($filterobj) && get_class($filterobj) == 'Dolresource') {
16696 $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "element_resources as er";
16697 $sql .= " ON er.resource_type = 'dolresource'";
16698 $sql .= " AND er.element_id = a.id";
16699 $sql .= " AND er.resource_id = " . ((int) $filterobj->id);
16700 } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
16701 $sql .= ", " . MAIN_DB_PREFIX . "adherent as m";
16702 } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
16703 $sql .= ", " . MAIN_DB_PREFIX . "commande_fournisseur as o";
16704 } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
16705 $sql .= ", " . MAIN_DB_PREFIX . "product as o";
16706 } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
16707 $sql .= ", " . MAIN_DB_PREFIX . "ticket as o";
16708 } elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') {
16709 $sql .= ", " . MAIN_DB_PREFIX . "bom_bom as o";
16710 } elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') {
16711 $sql .= ", " . MAIN_DB_PREFIX . "contrat as o";
16712 } elseif (is_object($filterobj) && get_class($filterobj) == 'Facture') {
16713 $sql .= ", " . MAIN_DB_PREFIX . "facture as o";
16714 } elseif (is_object($filterobj) && get_class($filterobj) == 'FactureFournisseur') {
16715 $sql .= ", " . MAIN_DB_PREFIX . "facture_fourn as o";
16716 } elseif (is_object($filterobj) && get_class($filterobj) == 'Commande') {
16717 $sql .= ", " . MAIN_DB_PREFIX . "commande as o";
16718 } elseif (is_object($filterobj) && get_class($filterobj) == 'Expedition') {
16719 $sql .= ", " . MAIN_DB_PREFIX . "expedition as o";
16720 } elseif (is_object($filterobj) && get_class($filterobj) == 'Propal') {
16721 $sql .= ", " . MAIN_DB_PREFIX . "propal as o";
16722 } else {
16723 if (is_object($filterobj) && !empty($filterobj->table_element) && !empty($filterobj->element) && !empty($filterobj->id) && array_key_exists('ref', $filterobj->fields)) {
16724 $sql .= ", " . MAIN_DB_PREFIX . $filterobj->table_element . " as o";
16725 }
16726 }
16727 $sql .= " WHERE a.entity IN (" . getEntity('agenda') . ")";
16728 if (!$force_filter_contact) {
16729 if (is_object($filterobj) && in_array(get_class($filterobj), array('Societe', 'Client', 'Fournisseur')) && $filterobj->id) {
16730 $sql .= " AND a.fk_soc = " . ((int) $filterobj->id);
16731 } elseif (is_object($filterobj) && get_class($filterobj) == 'Project' && $filterobj->id) {
16732 $sql .= " AND a.fk_project = o.rowid AND a.fk_project = " . ((int) $filterobj->id);
16733 } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
16734 $sql .= " AND a.fk_element = m.rowid AND a.elementtype = 'member'";
16735 if ($filterobj->id) {
16736 $sql .= " AND a.fk_element = " . ((int) $filterobj->id);
16737 }
16738 } elseif (is_object($filterobj) && get_class($filterobj) == 'Commande') {
16739 $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'order'";
16740 if ($filterobj->id) {
16741 $sql .= " AND a.fk_element = " . ((int) $filterobj->id);
16742 }
16743 } elseif (is_object($filterobj) && get_class($filterobj) == 'Expedition') {
16744 $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'shipping'";
16745 if ($filterobj->id) {
16746 $sql .= " AND a.fk_element = " . ((int) $filterobj->id);
16747 }
16748 } elseif (is_object($filterobj) && get_class($filterobj) == 'Propal') {
16749 $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'propal'";
16750 if ($filterobj->id) {
16751 $sql .= " AND a.fk_element = " . ((int) $filterobj->id);
16752 }
16753 } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
16754 $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'order_supplier'";
16755 if ($filterobj->id) {
16756 $sql .= " AND a.fk_element = " . ((int) $filterobj->id);
16757 }
16758 } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
16759 $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'product'";
16760 if ($filterobj->id) {
16761 $sql .= " AND a.fk_element = " . ((int) $filterobj->id);
16762 }
16763 } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
16764 $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'ticket'";
16765 if ($filterobj->id) {
16766 $sql .= " AND a.fk_element = " . ((int) $filterobj->id);
16767 }
16768 } elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') {
16769 $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'bom'";
16770 if ($filterobj->id) {
16771 $sql .= " AND a.fk_element = " . ((int) $filterobj->id);
16772 }
16773 } elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') {
16774 $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'contract'";
16775 if ($filterobj->id) {
16776 $sql .= " AND a.fk_element = " . ((int) $filterobj->id);
16777 }
16778 } elseif (is_object($filterobj) && get_class($filterobj) == 'Contact' && $filterobj->id) {
16779 $sql .= " AND a.fk_contact = sp.rowid";
16780 if ($filterobj->id) {
16781 $sql .= " AND a.fk_contact = " . ((int) $filterobj->id);
16782 }
16783 } elseif (is_object($filterobj) && get_class($filterobj) == 'Facture') {
16784 $sql .= " AND a.fk_element = o.rowid";
16785 if ($filterobj->id) {
16786 $sql .= " AND a.fk_element = " . ((int) $filterobj->id) . " AND a.elementtype = 'invoice'";
16787 }
16788 } elseif (is_object($filterobj) && get_class($filterobj) == 'FactureFournisseur') {
16789 $sql .= " AND a.fk_element = o.rowid";
16790 if ($filterobj->id) {
16791 $sql .= " AND a.fk_element = " . ((int) $filterobj->id) . " AND a.elementtype = 'invoice_supplier'";
16792 }
16793 } else {
16794 if (is_object($filterobj) && !empty($filterobj->element) && !empty($filterobj->id) && array_key_exists('ref', $filterobj->fields)) {
16795 $sql .= " AND a.fk_element = o.rowid";
16796 $sql .= " AND a.elementtype = '" . $db->escape($filterobj->element) . "'";
16797 if ($filterobj->id) {
16798 $sql .= " AND a.fk_element = " . ((int) $filterobj->id);
16799 }
16800 }
16801 }
16802 } else {
16803 $sql .= " AND u.rowid = " . ((int) $filterobj->id);
16804 }
16805
16806 // Condition on actioncode
16807 if (!empty($actioncode) && $actioncode != '-1') {
16808 if (!getDolGlobalString('AGENDA_USE_EVENT_TYPE')) {
16809 if ($actioncode == 'AC_NON_AUTO') {
16810 $sql .= " AND c.type != 'systemauto'";
16811 } elseif ($actioncode == 'AC_ALL_AUTO') {
16812 $sql .= " AND c.type = 'systemauto'";
16813 } else {
16814 if ($actioncode == 'AC_OTH') {
16815 $sql .= " AND c.type != 'systemauto'";
16816 } elseif ($actioncode == 'AC_OTH_AUTO') {
16817 $sql .= " AND c.type = 'systemauto'";
16818 }
16819 }
16820 } else {
16821 if ($actioncode == 'AC_NON_AUTO') {
16822 $sql .= " AND c.type != 'systemauto'";
16823 } elseif ($actioncode == 'AC_ALL_AUTO') {
16824 $sql .= " AND c.type = 'systemauto'";
16825 } else {
16826 $sql .= " AND c.code = '" . $db->escape($actioncode) . "'";
16827 }
16828 }
16829 }
16830 if ($donetodo == 'todo') {
16831 $sql .= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '" . $db->idate($now) . "'))";
16832 } elseif ($donetodo == 'done') {
16833 $sql .= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '" . $db->idate($now) . "'))";
16834 }
16835 if (is_array($filters) && $filters['search_agenda_label']) {
16836 $sql .= natural_search('a.label', $filters['search_agenda_label']);
16837 }
16838 }
16839
16840 // Add also event from emailings. TODO This should be replaced by an automatic event ? May be it's too much for very large emailing.
16841 if (
16842 isModEnabled('mailing') && !empty($objcon->email)
16843 && (empty($actioncode) || $actioncode == 'AC_OTH_AUTO' || $actioncode == 'AC_EMAILING')
16844 ) {
16845 $langs->load("mails");
16846
16847 $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";
16848 $sql2 .= ", null as fk_element, '' as elementtype, null as contact_id";
16849 $sql2 .= ", 'AC_EMAILING' as acode, '' as alabel, '' as apicto";
16850 $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
16851 if (is_object($filterobj) && get_class($filterobj) == 'Societe') {
16852 $sql2 .= ", '' as lastname, '' as firstname";
16853 } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
16854 $sql2 .= ", '' as lastname, '' as firstname";
16855 } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
16856 $sql2 .= ", '' as ref";
16857 } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
16858 $sql2 .= ", '' as ref";
16859 } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
16860 $sql2 .= ", '' as ref";
16861 }
16862 $sql2 .= " FROM " . MAIN_DB_PREFIX . "mailing as m, " . MAIN_DB_PREFIX . "mailing_cibles as mc, " . MAIN_DB_PREFIX . "user as u";
16863 $sql2 .= " WHERE mc.email = '" . $db->escape($objcon->email) . "'"; // Search is done on email.
16864 $sql2 .= " AND mc.statut = 1";
16865 $sql2 .= " AND u.rowid = m.fk_user_valid";
16866 $sql2 .= " AND mc.fk_mailing=m.rowid";
16867 }
16868
16869 $num = 0;
16870 $MAXWITHOUTPAGINATION = getDolGlobalInt('AGENDA_MAX_EVENTS_ON_PAGE_WITHOUT_PAGINATION', 100);
16871
16872 if ($sql || $sql2) { // May not be defined if module Agenda is not enabled and mailing module disabled too
16873 if (!empty($sql) && !empty($sql2)) {
16874 $sql = $sql . " UNION " . $sql2;
16875 } elseif (empty($sql) && !empty($sql2)) {
16876 $sql = $sql2;
16877 }
16878
16879 //TODO Add navigation with this limits...
16880 $offset = 0;
16881 $limit = $MAXWITHOUTPAGINATION;
16882
16883 // Complete request and execute it with limit
16884 $sql .= $db->order($sanitized_sortfield_new, $sortorder);
16885 if ($limit) {
16886 $sql .= $db->plimit($limit + 1, $offset);
16887 }
16888
16889 dol_syslog("function.lib::show_actions_messaging", LOG_DEBUG);
16890
16891 $resql = $db->query($sql);
16892 if ($resql) {
16893 $i = 0;
16894 $num = $db->num_rows($resql);
16895
16896 $imaxinloop = ($limit ? min($num, $limit) : $num);
16897 while ($i < $imaxinloop) {
16898 $obj = $db->fetch_object($resql);
16899
16900 if ($obj->type == 'action') {
16901 $contactaction = new ActionComm($db);
16902 $contactaction->id = $obj->id;
16903 $result = $contactaction->fetchResources();
16904 if ($result < 0) {
16906 setEventMessage("actions.lib::show_actions_messaging Error fetch resource", 'errors');
16907 }
16908
16909 //if ($donetodo == 'todo') $sql.= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))";
16910 //elseif ($donetodo == 'done') $sql.= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))";
16911 $tododone = '';
16912 if (($obj->percent >= 0 and $obj->percent < 100) || ($obj->percent == -1 && $obj->dp > $now)) {
16913 $tododone = 'todo';
16914 }
16915
16916 $histo[$numaction] = array(
16917 'type' => $obj->type,
16918 'tododone' => $tododone,
16919 'id' => $obj->id,
16920 'datestart' => $db->jdate($obj->dp),
16921 'dateend' => $db->jdate($obj->dp2),
16922 'fulldayevent' => (int) $obj->fulldayevent,
16923 'note' => $obj->label,
16924 'message' => $obj->message,
16925 'percent' => $obj->percent,
16926
16927 'userid' => $obj->user_id,
16928 'login' => $obj->user_login,
16929 'userfirstname' => $obj->user_firstname,
16930 'userlastname' => $obj->user_lastname,
16931 'userphoto' => $obj->user_photo,
16932 'msg_from' => $obj->msg_from,
16933
16934 'contact_id' => $obj->fk_contact,
16935 'socpeopleassigned' => $contactaction->socpeopleassigned,
16936 'lastname' => (empty($obj->lastname) ? '' : $obj->lastname),
16937 'firstname' => (empty($obj->firstname) ? '' : $obj->firstname),
16938 'fk_element' => $obj->fk_element,
16939 'elementtype' => $obj->elementtype,
16940 // Type of event
16941 'acode' => $obj->acode,
16942 'alabel' => $obj->alabel,
16943 'libelle' => $obj->alabel, // deprecated
16944 'apicto' => $obj->apicto
16945 );
16946 } else {
16947 $histo[$numaction] = array(
16948 'type' => $obj->type,
16949 'tododone' => 'done',
16950 'id' => $obj->id,
16951 'datestart' => $db->jdate($obj->dp),
16952 'dateend' => $db->jdate($obj->dp2),
16953 'fulldayevent' => (int) $obj->fulldayevent,
16954 'note' => $obj->label,
16955 'message' => $obj->message,
16956 'percent' => $obj->percent,
16957 'acode' => $obj->acode,
16958
16959 'userid' => $obj->user_id,
16960 'login' => $obj->user_login,
16961 'userfirstname' => $obj->user_firstname,
16962 'userlastname' => $obj->user_lastname,
16963 'userphoto' => $obj->user_photo
16964 );
16965 }
16966
16967 $numaction++;
16968 $i++;
16969 }
16970 } else {
16972 }
16973 }
16974
16975 // Set $out to show events
16976 $out = '';
16977
16978 if (!isModEnabled('agenda')) {
16979 $langs->loadLangs(array("admin", "errors"));
16980 $out = info_admin($langs->trans("WarningModuleXDisabledSoYouMayMissEventHere", $langs->transnoentitiesnoconv("Module2400Name")), 0, 0, 'warning');
16981 }
16982
16983 if (isModEnabled('agenda') || (isModEnabled('mailing') && !empty($objcon->email))) {
16984 $delay_warning = getDolGlobalInt('MAIN_DELAY_ACTIONS_TODO') * 24 * 60 * 60;
16985
16986 require_once DOL_DOCUMENT_ROOT . '/comm/action/class/actioncomm.class.php';
16987 include_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php';
16988 require_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php';
16989 require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
16990
16991 $formactions = new FormActions($db);
16992
16993 $actionstatic = new ActionComm($db);
16994 $userstatic = new User($db);
16995 $contactstatic = new Contact($db);
16996 $userGetNomUrlCache = array();
16997 $contactGetNomUrlCache = array();
16998
16999 $out .= '<div class="filters-container" >';
17000 $out .= '<form name="listactionsfilter" class="listactionsfilter" action="' . $_SERVER["PHP_SELF"] . '" method="POST">';
17001 $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
17002
17003 if (
17004 $objcon && get_class($objcon) == 'Contact' &&
17005 (is_null($filterobj) || get_class($filterobj) == 'Societe')
17006 ) {
17007 $out .= '<input type="hidden" name="id" value="' . $objcon->id . '" />';
17008 } else {
17009 $out .= '<input type="hidden" name="id" value="' . $filterobj->id . '" />';
17010 }
17011 if (($filterobj && get_class($filterobj) == 'Societe')) {
17012 $out .= '<input type="hidden" name="socid" value="' . $filterobj->id . '" />';
17013 } else {
17014 $out .= '<input type="hidden" name="userid" value="' . $filterobj->id . '" />';
17015 }
17016
17017 $out .= "\n";
17018
17019 $out .= '<div class="div-table-responsive-no-min">';
17020 $out .= '<table class="noborder borderbottom centpercent">';
17021
17022 $out .= '<tr class="liste_titre">';
17023
17024 // Action column
17025 if ($conf->main_checkbox_left_column) {
17026 $out .= '<th class="liste_titre width50 middle">';
17027 $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1);
17028 $out .= $searchpicto;
17029 $out .= '</th>';
17030 }
17031
17032 // Date
17033 $out .= getTitleFieldOfList('Date', 0, $_SERVER["PHP_SELF"], 'a.datep', '', $param, '', $sortfield, $sortorder, 'nowraponall nopaddingleftimp ') . "\n";
17034
17035 $out .= '<th class="liste_titre hideonsmartphone"><strong class="hideonsmartphone">' . $langs->trans("Search") . ' : </strong></th>';
17036 if ($donetodo) {
17037 $out .= '<th class="liste_titre"></th>';
17038 }
17039 // Type of event
17040 $out .= '<th class="liste_titre">';
17041 $out .= '<span class="fas fa-square inline-block fawidth30 hideonsmartphone" style="color: #ddd;" title="' . $langs->trans("ActionType") . '"></span>';
17042 $out .= $formactions->select_type_actions($actioncode, "actioncode", '', getDolGlobalString('AGENDA_USE_EVENT_TYPE') ? -1 : 1, 0, 0, 1, 'selecttype minwidth100', $langs->trans("Type"));
17043 $out .= '</th>';
17044 // Label
17045 $out .= '<th class="liste_titre maxwidth100onsmartphone">';
17046 $out .= '<input type="text" class="maxwidth100onsmartphone" name="search_agenda_label" value="' . $filters['search_agenda_label'] . '" placeholder="' . $langs->trans("Label") . '">';
17047 $out .= '</th>';
17048
17049 // Action column
17050 if (!$conf->main_checkbox_left_column) {
17051 $out .= '<th class="liste_titre width50 middle">';
17052 $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1);
17053 $out .= $searchpicto;
17054 $out .= '</th>';
17055 }
17056
17057 $out .= '</tr>';
17058
17059 $out .= '</table>';
17060
17061 $out .= '</form>';
17062 $out .= '</div>';
17063
17064 $out .= "\n";
17065
17066 $out .= '<ul class="timeline">';
17067
17068 if ($donetodo) {
17069 $tmp = '';
17070 if ($filterobj instanceof Societe) {
17071 $tmp .= '<a href="' . DOL_URL_ROOT . '/comm/action/list.php?mode=show_list&socid=' . $filterobj->id . '&status=done">';
17072 }
17073 if ($filterobj instanceof User) {
17074 $tmp .= '<a href="' . DOL_URL_ROOT . '/comm/action/list.php?mode=show_list&socid=' . $filterobj->id . '&status=done">';
17075 }
17076 $tmp .= ($donetodo != 'done' ? $langs->trans("ActionsToDoShort") : '');
17077 $tmp .= ($donetodo != 'done' && $donetodo != 'todo' ? ' / ' : '');
17078 $tmp .= ($donetodo != 'todo' ? $langs->trans("ActionsDoneShort") : '');
17079 //$out.=$langs->trans("ActionsToDoShort").' / '.$langs->trans("ActionsDoneShort");
17080 if ($filterobj instanceof Societe) {
17081 $tmp .= '</a>';
17082 }
17083 if ($filterobj instanceof User) {
17084 $tmp .= '</a>';
17085 }
17086 $out .= getTitleFieldOfList($tmp);
17087 }
17088
17089 require_once DOL_DOCUMENT_ROOT . '/comm/action/class/cactioncomm.class.php';
17090 $caction = new CActionComm($db);
17091 $arraylist = $caction->liste_array(1, 'code', '', (!getDolGlobalString('AGENDA_USE_EVENT_TYPE') ? 1 : 0), '', 1);
17092
17093 $actualCycleDate = false;
17094
17095 // Loop on each event to show it
17096 foreach ($histo as $key => $value) {
17097 $actionstatic->fetch($histo[$key]['id']); // TODO Do we need this, we already have a lot of data of line into $histo
17098
17099 $actionstatic->type_picto = $histo[$key]['apicto'];
17100 $actionstatic->type_code = $histo[$key]['acode'];
17101
17102 $labeltype = $actionstatic->type_code;
17103 if (!getDolGlobalString('AGENDA_USE_EVENT_TYPE') && empty($arraylist[$labeltype])) {
17104 $labeltype = 'AC_OTH';
17105 }
17106 if (!empty($actionstatic->code) && preg_match('/^TICKET_MSG/', $actionstatic->code)) {
17107 $labeltype = $langs->trans("Message");
17108 } else {
17109 if (!empty($arraylist[$labeltype])) {
17110 $labeltype = $arraylist[$labeltype];
17111 }
17112 if ($actionstatic->type_code == 'AC_OTH_AUTO' && ($actionstatic->type_code != $actionstatic->code) && $labeltype && !empty($arraylist[$actionstatic->code])) {
17113 $labeltype .= ' - ' . $arraylist[$actionstatic->code]; // Use code in priority on type_code
17114 }
17115 }
17116
17117 $url = DOL_URL_ROOT . '/comm/action/card.php?id=' . $histo[$key]['id'];
17118
17119 $tmpa = dol_getdate($histo[$key]['datestart'], false);
17120
17121 if (isset($tmpa['year']) && isset($tmpa['yday']) && $actualCycleDate !== $tmpa['year'] . '-' . $tmpa['yday']) {
17122 $actualCycleDate = $tmpa['year'] . '-' . $tmpa['yday'];
17123 $out .= '<!-- timeline time label -->';
17124 $out .= '<li class="time-label">';
17125 $out .= '<span class="timeline-badge-date">';
17126 $out .= dol_print_date($histo[$key]['datestart'], 'daytext', 'tzuserrel', $langs);
17127 $out .= '</span>';
17128 $out .= '</li>';
17129 $out .= '<!-- /.timeline-label -->';
17130 }
17131
17132
17133 $out .= '<!-- timeline item -->' . "\n";
17134 $out .= '<li class="timeline-code-' . (!empty($actionstatic->code) ? strtolower($actionstatic->code) : "none") . '">';
17135
17136 //$timelineicon = getTimelineIcon($actionstatic, $histo, $key);
17137 $typeicon = $actionstatic->getTypePicto('pictofixedwidth timeline-icon-not-applicble', $labeltype);
17138 //$out .= $timelineicon;
17139 //var_dump($timelineicon);
17140 $out .= $typeicon;
17141
17142 $out .= '<div class="timeline-item">' . "\n";
17143
17144 $out .= '<span class="time timeline-header-action2">';
17145
17146 if (isset($histo[$key]['type']) && $histo[$key]['type'] == 'mailing') {
17147 $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") . ' ';
17148 $out .= $histo[$key]['id'];
17149 $out .= '</a> ';
17150 } else {
17151 $out .= $actionstatic->getNomUrl(1, -1, 'valignmiddle') . ' ';
17152 }
17153
17154 if (
17155 $user->hasRight('agenda', 'allactions', 'create') ||
17156 (($actionstatic->authorid == $user->id || $actionstatic->userownerid == $user->id) && $user->hasRight('agenda', 'myactions', 'create'))
17157 ) {
17158 $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) . '">';
17159 //$out .= '<i class="fa fa-pencil" title="'.$langs->trans("Modify").'" ></i>';
17160 $out .= img_picto($langs->trans("Modify"), 'edit', 'class="edita"');
17161 $out .= '</a>';
17162 }
17163
17164 $out .= '</span>';
17165
17166 // Date
17167 $out .= '<span class="time"><i class="fa fa-clock valignmiddle"></i> ';
17168 $out .= '<span class="valignmiddle marginrightonly">';
17169 $out .= dol_print_date($histo[$key]['datestart'], 'day', 'tzuserrel');
17170 //$out .= '</span>';
17171 //$out .= '<span class="valignmiddle">'.
17172 $out .= ' '.dol_print_date($histo[$key]['datestart'], 'hour', 'tzuserrel', null, false, 'opacitymedium');
17173 //$out .= '</span>';
17174 if ($histo[$key]['dateend'] && $histo[$key]['dateend'] != $histo[$key]['datestart']) {
17175 $tmpa = dol_getdate($histo[$key]['datestart'], true);
17176 $tmpb = dol_getdate($histo[$key]['dateend'], true);
17177 if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year']) {
17178 $out .= ' - ' . dol_print_date($histo[$key]['dateend'], 'hour', 'tzuserrel', null, false, 1);
17179 } else {
17180 $out .= ' - ' . dol_print_date($histo[$key]['dateend'], 'day', 'tzuserrel');
17181 //$out .= '<span class="valignmiddle marginrightonly">';
17182 $out .= ' '.dol_print_date($histo[$key]['dateend'], 'hour', 'tzuserrel', null, false, 'opacitymedium');
17183 //$out .= '</span>';
17184 }
17185 }
17186 $late = 0;
17187 if ($histo[$key]['percent'] == 0 && $histo[$key]['datestart'] && $histo[$key]['datestart'] < ($now - $delay_warning)) {
17188 $late = 1;
17189 }
17190 if ($histo[$key]['percent'] == 0 && !$histo[$key]['datestart'] && $histo[$key]['dateend'] && $histo[$key]['datestart'] < ($now - $delay_warning)) {
17191 $late = 1;
17192 }
17193 if ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100 && $histo[$key]['dateend'] && $histo[$key]['dateend'] < ($now - $delay_warning)) {
17194 $late = 1;
17195 }
17196 if ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100 && !$histo[$key]['dateend'] && $histo[$key]['datestart'] && $histo[$key]['datestart'] < ($now - $delay_warning)) {
17197 $late = 1;
17198 }
17199 if ($late) {
17200 $out .= img_warning($langs->trans("Late")) . ' ';
17201 }
17202 $out .= "</span></span>\n";
17203
17204 $out .= '<span class="time">';
17205 $out .= $actionstatic->getLibStatut(2);
17206 $out .= '</span>';
17207
17208 // Ref
17209 $out .= '<h3 class="timeline-header">';
17210
17211 // Author of event
17212 $out .= '<div class="messaging-author inline-block tdoverflowmax150 valignmiddle marginrightonly">';
17213 if ($histo[$key]['userid'] > 0) {
17214 if (!isset($userGetNomUrlCache[$histo[$key]['userid']])) { // is in cache ?
17215 $userstatic->fetch($histo[$key]['userid']);
17216 $userGetNomUrlCache[$histo[$key]['userid']] = $userstatic->getNomUrl(-1, '', 0, 0, 16, 0, 'firstelselast', '');
17217 }
17218 $out .= $userGetNomUrlCache[$histo[$key]['userid']];
17219 } elseif (!empty($histo[$key]['msg_from']) && $actionstatic->code == 'TICKET_MSG') {
17220 if (!isset($contactGetNomUrlCache[$histo[$key]['msg_from']])) {
17221 if ($contactstatic->fetch(0, null, '', $histo[$key]['msg_from']) > 0) {
17222 $contactGetNomUrlCache[$histo[$key]['msg_from']] = $contactstatic->getNomUrl(-1, '', 16);
17223 } else {
17224 $contactGetNomUrlCache[$histo[$key]['msg_from']] = $histo[$key]['msg_from'];
17225 }
17226 }
17227 $out .= $contactGetNomUrlCache[$histo[$key]['msg_from']];
17228 } else {
17229 $out .= '<img class="photomemberphoto userphoto" alt="" src="/public/theme/common/user_anonymous.png">'.$langs->trans("Anonymous");
17230 }
17231 $out .= '</div>';
17232
17233 // Title
17234 $out .= ' <div class="messaging-title inline-block">';
17235 //$out .= $actionstatic->getTypePicto(); // The type of event is already into the timeline on left.
17236 if (empty($conf->dol_optimize_smallscreen) && $actionstatic->type_code != 'AC_OTH_AUTO') {
17237 $out .= $labeltype . ' - ';
17238 }
17239
17240 $libelle = '';
17241
17242 if (!empty($actionstatic->code) && preg_match('/^TICKET_MSG_PRIVATE/', $actionstatic->code)) {
17243 $out .= $langs->trans('TicketNewMessage').' - <em>'.img_picto($langs->trans('Private'), 'lock', 'class="valignmiddle"').' '.$langs->trans('Private').'</em>';
17244 $summary = preg_replace('/\[[^\]]*\]\s*/', '', $actionstatic->label);
17245 //if ($summary != $object->title) {
17246 $out .= ' - '.dolPrintHTML($summary);
17247 //}
17248 } elseif (!empty($actionstatic->code) && preg_match('/^TICKET_MSG/', $actionstatic->code)) {
17249 $out .= $langs->trans('TicketNewMessage');
17250 } elseif (isset($histo[$key]['type'])) {
17251 if ($histo[$key]['type'] == 'action') {
17252 $transcode = $langs->transnoentitiesnoconv("Action" . $histo[$key]['acode']);
17253 $libelle = ($transcode != "Action" . $histo[$key]['acode'] ? $transcode : $histo[$key]['alabel']);
17254 $libelle = $histo[$key]['note'];
17255 $actionstatic->id = $histo[$key]['id'];
17256 if ($libelle != $labeltype) {
17257 $out .= dol_escape_htmltag(dol_trunc($libelle, 120));
17258 }
17259 } elseif ($histo[$key]['type'] == 'mailing') {
17260 $out .= '<a href="' . DOL_URL_ROOT . '/comm/mailing/card.php?id=' . $histo[$key]['id'] . '">' . img_object($langs->trans("ShowEMailing"), "email") . ' ';
17261 $transcode = $langs->transnoentitiesnoconv("Action" . $histo[$key]['acode']);
17262 $libelle = ($transcode != "Action" . $histo[$key]['acode'] ? $transcode : 'Send mass mailing');
17263 $out .= dol_escape_htmltag(dol_trunc($libelle, 120));
17264 } else {
17265 $libelle .= $histo[$key]['note'];
17266 $out .= dol_escape_htmltag(dol_trunc($libelle, 120));
17267 }
17268 }
17269 $out = preg_replace('/ - $/', '', $out); // Remove ending ' - '
17270
17271 if (isset($histo[$key]['elementtype']) && !empty($histo[$key]['fk_element'])) {
17272 if (isset($conf->cache['elementlinkcache'][$histo[$key]['elementtype']]) && isset($conf->cache['elementlinkcache'][$histo[$key]['elementtype']][$histo[$key]['fk_element']])) {
17273 $link = $conf->cache['elementlinkcache'][$histo[$key]['elementtype']][$histo[$key]['fk_element']];
17274 } else {
17275 if (!isset($conf->cache['elementlinkcache'][$histo[$key]['elementtype']])) {
17276 $conf->cache['elementlinkcache'][$histo[$key]['elementtype']] = array();
17277 }
17278 $link = dolGetElementUrl($histo[$key]['fk_element'], $histo[$key]['elementtype'], 1);
17279 $conf->cache['elementlinkcache'][$histo[$key]['elementtype']][$histo[$key]['fk_element']] = $link;
17280 }
17281
17282 // We do not show if link if on object we are filtering on (no need to show the link to ticket X when we are on page of events for the ticket X)
17283 $showlink = 1;
17284 if (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
17285 if ($histo[$key]['elementtype'] == 'ticket') {
17286 $showlink = 0;
17287 }
17288 }
17289
17290 if ($link && $showlink) {
17291 $out .= ' - ' . $link;
17292 }
17293 }
17294
17295 $out .= '</div>';
17296
17297 $out .= '</h3>';
17298
17299 // Message
17300 if ($actionstatic->code == 'AC_TICKET_CREATE') {
17301 $newmess = $filterobj->message;
17302 } else {
17303 $newmess = $histo[$key]['message'];
17304 }
17305 if (
17306 !empty($newmess && $newmess != $libelle)
17307 && $actionstatic->code != 'AC_TICKET_MODIFY'
17308 ) {
17309 $out .= '<div class="timeline-body wordbreak small">';
17310 $truncateLines = getDolGlobalInt('MAIN_TRUNCATE_TIMELINE_MESSAGE', 3);
17311 $truncatedText = dolGetFirstLineOfText($newmess, $truncateLines);
17312 // dolGetFirstLineOfText() cuts on <br> without caring about tag balance, so a message wrapped in
17313 // a block tag leaves the excerpt with an unclosed tag. The browser then nests the read more link
17314 // and the full text inside the excerpt, and hiding the excerpt hides the whole message (#39035).
17315 $truncatedText = dolCloseUnclosedHtmlTags($truncatedText);
17316 if ($truncateLines > 0 && strlen($newmess) > strlen($truncatedText)) {
17317 $out .= '<div class="readmore-block --closed" >';
17318 $out .= ' <div class="readmore-block__excerpt">';
17319 $out .= dolPrintHTML($truncatedText, 0, array('pre', 'code'));
17320 $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>';
17321 $out .= ' </div>';
17322 $out .= ' <div class="readmore-block__full-text" >';
17323
17324 $out .= dolPrintHTML($newmess, 0, array('pre', 'code'));
17325
17326 $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>';
17327 $out .= ' </div>';
17328 $out .= '</div>';
17329 } else {
17330 $out .= dolPrintHTML($newmess, 0, array('pre', 'code'));
17331 }
17332 $out .= '</div>';
17333 }
17334
17335 // Timeline footer
17336 $footer = '';
17337
17338 // Contact for this action
17339 if (isset($histo[$key]['socpeopleassigned']) && is_array($histo[$key]['socpeopleassigned']) && count($histo[$key]['socpeopleassigned']) > 0) {
17340 $contactList = '';
17341 foreach ($histo[$key]['socpeopleassigned'] as $cid => $Tab) {
17342 if (empty($conf->cache['contact'][$cid])) {
17343 $contact = new Contact($db);
17344 $contact->fetch($cid);
17345 $conf->cache['contact'][$cid] = $contact;
17346 } else {
17347 $contact = $conf->cache['contact'][$cid];
17348 }
17349
17350 if ($contact) {
17351 $contactList .= !empty($contactList) ? ', ' : '';
17352 $contactList .= $contact->getNomUrl(1);
17353 if (isset($histo[$key]['acode']) && $histo[$key]['acode'] == 'AC_TEL') {
17354 if (!empty($contact->phone_pro)) {
17355 $contactList .= '(' . dol_print_phone($contact->phone_pro) . ')';
17356 }
17357 }
17358 }
17359 }
17360
17361 $footer .= $langs->trans('ActionOnContact') . ' : ' . $contactList;
17362 } elseif (empty($objcon->id) && isset($histo[$key]['contact_id']) && $histo[$key]['contact_id'] > 0) {
17363 if (empty($conf->cache['contact'][$histo[$key]['contact_id']])) {
17364 $contact = new Contact($db);
17365 $result = $contact->fetch($histo[$key]['contact_id']);
17366 $conf->cache['contact'][$histo[$key]['contact_id']] = $contact;
17367 } else {
17368 $contact = $conf->cache['contact'][$histo[$key]['contact_id']];
17369 $result = ($contact instanceof Contact) ? $contact->id : 0;
17370 }
17371
17372 if ($result > 0) {
17373 $footer .= $contact->getNomUrl(1);
17374 if (isset($histo[$key]['acode']) && $histo[$key]['acode'] == 'AC_TEL') {
17375 if (!empty($contact->phone_pro)) {
17376 $footer .= '(' . dol_print_phone($contact->phone_pro) . ')';
17377 }
17378 }
17379 }
17380 }
17381
17382 $documents = getActionCommEcmList($actionstatic);
17383 if (!empty($documents)) {
17384 $footer .= '<div class="timeline-documents-container">';
17385 foreach ($documents as $doc) {
17386 $footer .= '<span id="document_' . $doc->id . '" class="timeline-documents" ';
17387 $footer .= ' data-id="' . $doc->id . '" ';
17388 $footer .= ' data-path="' . $doc->filepath . '"';
17389 $footer .= ' data-filename="' . dol_escape_htmltag($doc->filename) . '" ';
17390 $footer .= '>';
17391
17392 $filePath = DOL_DATA_ROOT . '/' . $doc->filepath . '/' . $doc->filename;
17393 $mime = dol_mimetype($filePath);
17394 if (empty($doc->agenda_id)) {
17395 $dir_ref = $actionstatic->id;
17396 $modulepart = 'actions';
17397 } else {
17398 $split_dir = explode('/', $doc->filepath);
17399 $modulepart = array_shift($split_dir);
17400 $dir_ref = implode('/', $split_dir);
17401 }
17402
17403 $file = $dir_ref . '/' . $doc->filename;
17404 $thumb = $dir_ref . '/thumbs/' . substr($doc->filename, 0, strrpos($doc->filename, '.')) . '_mini' . substr($doc->filename, strrpos($doc->filename, '.'));
17405 $doclink = dol_buildpath('document.php', 1) . '?modulepart=' . $modulepart . '&attachment=0&file=' . urlencode($file) . '&entity=' . $conf->entity;
17406 $viewlink = dol_buildpath('viewimage.php', 1) . '?modulepart=' . $modulepart . '&file=' . urlencode($thumb) . '&entity=' . $conf->entity;
17407
17408
17409
17410 $mimeAttr = ' mime="' . $mime . '" ';
17411 $class = '';
17412 if (in_array($mime, array('image/png', 'image/jpeg', 'application/pdf'))) {
17413 $class .= ' documentpreview';
17414 }
17415
17416 $footer .= '<a href="' . $doclink . '" class="btn-link ' . $class . '" target="_blank" rel="noopener noreferrer" ' . $mimeAttr . ' >';
17417 $footer .= img_mime($filePath) . ' ' . $doc->filename;
17418 $footer .= '</a>';
17419
17420 $footer .= '</span>';
17421 }
17422 $footer .= '</div>';
17423 }
17424
17425 if (!empty($footer)) {
17426 $out .= '<div class="timeline-footer">' . $footer . '</div>';
17427 }
17428
17429 $out .= '</div>' . "\n"; // end timeline-item
17430
17431 $out .= '</li>';
17432 $out .= '<!-- END timeline item -->';
17433 }
17434
17435 $out .= "</ul>\n";
17436
17437 // Code to manage the click on button data-read-more-action to show full description of an event
17438 $out .= '<script>
17439 jQuery(document).ready(function () {
17440 $(document).on("click", "[data-read-more-action]", function(e){
17441 console.log("We click on data-read-more-action");
17442 let readMoreBloc = $(this).closest(".readmore-block");
17443 if(readMoreBloc.length > 0){
17444 e.preventDefault();
17445 if($(this).attr("data-read-more-action") == "close"){
17446 readMoreBloc.addClass("--closed").removeClass("--open");
17447 $("html, body").animate({
17448 scrollTop: readMoreBloc.offset().top - 200
17449 }, 100);
17450 }else{
17451 readMoreBloc.addClass("--open").removeClass("--closed");
17452 }
17453 }
17454 });
17455 });
17456 </script>';
17457
17458
17459 if (empty($histo)) {
17460 $out .= '<span class="opacitymedium">' . $langs->trans("NoRecordFound") . '</span>';
17461 }
17462
17463 if ($num > $MAXWITHOUTPAGINATION) {
17464 $langs->load("errors");
17465 $out .= '<center><span class="opacitymedium">...' . $langs->trans("WarningTooManyDataPleaseUseMoreFilters", $MAXWITHOUTPAGINATION) . '...</span></center>';
17466 }
17467 }
17468
17469 if ($noprint) {
17470 return $out;
17471 } else {
17472 print $out;
17473 return null;
17474 }
17475}
17476
17488function buildParamDate($prefix, $timestamp = null, $hourTime = '', $gm = 'auto')
17489{
17490 if ($timestamp === null) {
17491 $timestamp = GETPOSTDATE($prefix, $hourTime, $gm);
17492 }
17493 $TParam = array(
17494 $prefix . 'day' => intval(dol_print_date($timestamp, '%d')),
17495 $prefix . 'month' => intval(dol_print_date($timestamp, '%m')),
17496 $prefix . 'year' => intval(dol_print_date($timestamp, '%Y')),
17497 );
17498 if ($hourTime === 'getpost' || ($timestamp !== null && dol_print_date($timestamp, '%H:%M:%S') !== '00:00:00')) {
17499 $TParam = array_merge($TParam, array(
17500 $prefix . 'hour' => intval(dol_print_date($timestamp, '%H')),
17501 $prefix . 'min' => intval(dol_print_date($timestamp, '%M')),
17502 $prefix . 'sec' => intval(dol_print_date($timestamp, '%S'))
17503 ));
17504 }
17505
17506 return '&' . http_build_query($TParam);
17507}
17508
17527function recordNotFound($message = '', $printheader = 1, $printfooter = 1, $showonlymessage = 0, $params = null)
17528{
17529 global $conf, $db, $langs, $hookmanager;
17530 global $action, $object;
17531
17532 if (!is_object($langs)) {
17533 include_once DOL_DOCUMENT_ROOT . '/core/class/translate.class.php';
17534 $langs = new Translate('', $conf);
17535 $langs->setDefaultLang();
17536 }
17537
17538 $langs->load("errors");
17539
17540 if ($printheader) {
17541 if (function_exists("llxHeader")) {
17542 llxHeader('');
17543 } elseif (function_exists("llxHeaderVierge")) {
17544 llxHeaderVierge('');
17545 }
17546 }
17547
17548 print '<div class="error">';
17549 if (empty($message)) {
17550 print $langs->trans("ErrorRecordNotFound");
17551 } else {
17552 print $langs->trans($message);
17553 }
17554 print '</div>';
17555 print '<br>';
17556
17557 if (empty($showonlymessage)) {
17558 if (empty($hookmanager)) {
17559 include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
17560 $hookmanager = new HookManager($db);
17561 // Initialize a technical object to manage hooks of page. Note that conf->hooks_modules contains an array of hook context
17562 $hookmanager->initHooks(array('main'));
17563 }
17564
17565 $parameters = array('message' => $message, 'params' => $params);
17566 $reshook = $hookmanager->executeHooks('getErrorRecordNotFound', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
17567 print $hookmanager->resPrint;
17568 }
17569
17570 if ($printfooter && function_exists("llxFooter")) {
17571 llxFooter();
17572 if (is_object($db)) {
17573 $db->close();
17574 }
17575 }
17576 exit(0);
17577}
17578
17609function array_merge_recursive_distinct(array $array1, array $array2): array
17610{
17611 $merged = $array1;
17612
17613 foreach ($array2 as $key => $value) {
17614 if (is_array($value) && isset($merged[$key]) && is_array($merged[$key])) {
17615 $merged[$key] = array_merge_recursive_distinct($merged[$key], $value);
17616 } else {
17617 $merged[$key] = $value;
17618 }
17619 }
17620
17621 return $merged;
17622}
17623
17630function getObjectSocId($obj)
17631{
17632 if (!empty($obj->socid)) {
17633 return (int) $obj->socid;
17634 } elseif (!empty($obj->soc_id)) {
17635 return (int) $obj->soc_id;
17636 } elseif (!empty($obj->societe_id)) {
17637 return (int) $obj->societe_id;
17638 }
17639 return null;
17640}
17641
17648{
17649 $default = 10;
17650 if (!empty($_SESSION['dol_screenheight']) && $_SESSION['dol_screenheight'] < 700) {
17651 $default = 8;
17652 } elseif (!empty($_SESSION['dol_screenheight']) && $_SESSION['dol_screenheight'] < 950) {
17653 $default = 10;
17654 } elseif (!empty($_SESSION['dol_screenheight']) && $_SESSION['dol_screenheight'] > 1130) {
17655 $default = 15;
17656 }
17657
17658 return $default;
17659}
$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=[], $ws='')
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:476
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:808
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:334
$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:539
dol_get_next_day($day, $month, $year)
Return next day.
Definition date.lib.php:524
getServerTimeZoneInt($refgmtdate='now')
Return server timezone int.
Definition date.lib.php:87
dol_get_prev_day($day, $month, $year)
Return previous day.
Definition date.lib.php:508
dol_get_next_month($month, $year)
Return next month.
Definition date.lib.php:558
print $script_file $mode $langs defaultlang(is_numeric($duration_value) ? " delay=". $duration_value :"").(is_numeric($duration_value2) ? " after cd cd cd description as description
Only used if Module[ID]Desc translation string is not found.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
dol_convert_file($fileinput, $ext='png', $fileoutput='', $page='')
Convert a PDF file 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.
$date_start
Variables from include:
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.
dolSort($arraytosort)
Sort an array using a user defined function.
verifCond($strToEvaluate, $onlysimplestring='1')
Verify if condition in string is ok or not.
getDolGlobalLoginBadCharUnauthorized()
Return the list of unauthorized characters in user logins.
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.
dolPrintHTML($s, $allowiframe=0, $moreallowedtags=array())
Return a string (that can be on several lines) ready to be output on a HTML page.
dolGetFirstLineOfText($text, $nboflines=1, $charset='UTF-8')
Return first line of text.
dol_format_address($object, $withcountry=0, $sep="\n", $outputlangs=null, $mode=0, $extralangcode='')
Return a formatted address (part address/zip/town/state) according to country rules.
getDolUserInt($key, $default=0, $tmpuser=null)
Return Dolibarr user constant int value.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
getObjectSocId($obj)
Get the socid of an object, supporting legacy attribute names.
getListLimitFromScreenHeight()
Get the limit of list to show according to the screen height.
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.
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 ...
dolBuildUrl($url, $params=[], $addtoken=false, $anchor='')
Return path of url.
dolOutputDates($datep, $datef=null, $fullday=0, $addseconds=0, $pictotoadd='', $tzoutput='tzuserrel', $reduceformat=0)
Print decorated date-hour.
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.
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 value of 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)
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.
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.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
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...
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0, $forbiddenfields=array())
forgeSQLFromUniversalSearchCriteria
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.
safeArrayMap($callback, array $array)
Add a function to replace array_map with allowed callback.
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.
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)
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dolForgeSQLCriteriaCallback($matches)
Function to forge a SQL criteria from a USF (Universal Filter Syntax) string.
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.
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')) formatLogObject($data)
Return a string serialized to be output on log with dol_syslog() An option allow to output log in one...
getDolDBType()
Return the current entity.
print_titre($title)
Show a title.
showSimpleHTMLTable($outputlangs, $object)
Returns simple order table template as string.
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.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
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.
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).
info_admin($text, $infoonimgalt=0, $nodiv=0, $admin='1', $morecss='hideonsmartphone', $textfordropdown='', $picto='', $textonpictotooltip='', $cssfordropdown='info_admin')
Show information in HTML for admin users or standard users.
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
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
buildzip.php
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:137
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:140
isHTTPS()
Return if we are using a HTTPS connection Check HTTPS (no way to be modified by user but may be empty...
realCharForNumericEntities($matches)
Return the real char for a numeric entities.
Definition waf.inc.php:66