dolibarr 25.0.0-alpha
functions.lib.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2000-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2003 Jean-Louis Bergamo <jlb@j1b.org>
4 * Copyright (C) 2004-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-2026 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 'partnership':
191 $subdirectory = '/partnership';
192 break;
193 case 'stocktransfer':
194 $subdirectory = '/stocktransfer';
195 break;
196 case 'commande_fournisseur':
197 $module = 'fournisseur';
198 $subdirectory = '/commande';
199 break;
200 case 'expedition':
201 case 'shipment':
202 case 'shipping':
203 $module = 'expedition';
204 $subdirectory = '/sending';
205 break;
206 case 'company':
207 $module = 'societe';
208 break;
209 case 'service':
210 case 'produit':
211 $module = 'product';
212 break;
213 case 'project_task':
214 $module = 'projet';
215
216 // Fetch the project to build the correct path. The signature of this function accepts an object
217 // that is not a CommonObject, and even a null when a module is given, so we must not call a method
218 // that only a CommonObject owns without testing it exists.
219 if (is_object($object) && method_exists($object, 'fetchProject')) {
220 $object->fetchProject();
221 }
222
223 // The ref must be sanitized with dol_sanitizeFileName() and not only with dol_sanitizePathName()
224 // done at the end of this function, because a project ref is a user input that may contain a '/',
225 // a ':' or an accented char. dol_sanitizePathName() keeps them, so we would not return the
226 // directory used by projet/tasks/document.php, that sanitizes the ref with dol_sanitizeFileName().
227 if (!empty($object->project->ref)) {
228 $subdirectory = '/'.dol_sanitizeFileName($object->project->ref);
229 }
230 break;
231 case 'action':
232 case 'actioncomm':
233 case 'event':
234 $module = 'agenda';
235 break;
236 default:
237 break;
238 }
239
240 // Get the relative path of directory
241 if ($mode == 'output' || $mode == 'outputrel' || $mode == 'version') {
242 if (isset($conf->$module) && property_exists($conf->$module, 'multidir_output')) {
243 $s = '';
244 if ($mode != 'outputrel') {
245 // An entity with no declared directory returned an undefined index, so an empty path that
246 // made the caller read or write a relative path under the web root. Answer the error instead.
247 $entity = (int) (empty($object->entity) ? $conf->entity : $object->entity);
248 if (!isset($conf->$module->multidir_output[$entity])) {
249 return 'error-diroutput-not-defined-for-this-entity-and-object='.$module;
250 }
251 $s = $conf->$module->multidir_output[$entity] . $subdirectory;
252 }
253 if ($forobject && $object->id > 0) {
254 $s .= ($mode != 'outputrel' ? '/' : '') . get_exdir(0, 0, 0, 0, $object);
255 }
256 return dol_sanitizePathName($s);
257 } elseif (isset($conf->$module) && property_exists($conf->$module, 'dir_output')) {
258 $s = '';
259 if ($mode != 'outputrel') {
260 $s = $conf->$module->dir_output . $subdirectory;
261 }
262 if ($forobject && $object->id > 0) {
263 $s .= ($mode != 'outputrel' ? '/' : '') . get_exdir(0, 0, 0, 0, $object);
264 }
265 return dol_sanitizePathName($s);
266 } else {
267 return 'error-diroutput-not-defined-for-this-entity-and-object='.$module;
268 }
269 } elseif ($mode == 'temp') {
270 if (isset($conf->$module) && property_exists($conf->$module, 'multidir_temp')) {
271 // Same guard as the 'output' mode above, see the comment there
272 $entity = (int) (empty($object->entity) ? $conf->entity : $object->entity);
273 if (!isset($conf->$module->multidir_temp[$entity])) {
274 return 'error-dirtemp-not-defined-for-this-entity-and-object='.$module;
275 }
276 return dol_sanitizePathName($conf->$module->multidir_temp[$entity]);
277 } elseif (isset($conf->$module) && property_exists($conf->$module, 'dir_temp')) {
278 return dol_sanitizePathName($conf->$module->dir_temp);
279 } else {
280 return 'error-dirtemp-not-defined-for-this-entity-and-object='.$module;
281 }
282 } else {
283 return 'error-bad-value-for-mode';
284 }
285}
286
296function getMultidirTemp($object, $module = '', $forobject = 0)
297{
298 return getMultidirOutput($object, $module, $forobject, 'temp');
299}
300
310function getMultidirVersion($object, $module = '', $forobject = 0)
311{
312 return getMultidirOutput($object, $module, $forobject, 'version');
313}
314
315
324function getDolGlobalString($key, $default = '')
325{
326 global $conf;
327 return (string) (isset($conf->global->$key) ? $conf->global->$key : $default);
328}
329
336{
337 global $dolibarr_login_badcharunauthorized;
338
339 if (isset($dolibarr_login_badcharunauthorized)) {
340 if ($dolibarr_login_badcharunauthorized === 'MAIN_LOGIN_BADCHARUNAUTHORIZED') {
341 return getDolGlobalString('MAIN_LOGIN_BADCHARUNAUTHORIZED', ',@<>"\'');
342 }
343
344 return (string) $dolibarr_login_badcharunauthorized;
345 }
346
347 return ',@<>"\'';
348}
349
359function getDolGlobalInt($key, $default = 0)
360{
361 global $conf;
362 return (int) (isset($conf->global->$key) ? $conf->global->$key : $default);
363}
364
374function getDolGlobalFloat($key, $default = 0)
375{
376 global $conf;
377 return (float) (isset($conf->global->$key) ? $conf->global->$key : $default);
378}
379
388function getDolGlobalBool($key, $default = false)
389{
390 global $conf;
391 return (bool) ($conf->global->$key ?? $default);
392}
393
400{
401 global $conf;
402 return (string) $conf->currency;
403}
404
411{
412 global $conf;
413 return (string) $conf->dol_optimize_smallscreen;
414}
415
421function getDolEntity()
422{
423 global $conf;
424 return (int) $conf->entity;
425}
426
432function getDolDBType()
433{
434 global $conf;
435 return $conf->db->type;
436}
437
445{
446 return str_replace('_', '', basename(dirname($s)).basename($s, '.php'));
447}
448
458function getDolUserString($key, $default = '', $tmpuser = null)
459{
460 if (empty($tmpuser)) {
461 global $user;
462 $tmpuser = $user;
463 }
464
465 return (string) (isset($tmpuser->conf->$key) ? $tmpuser->conf->$key : $default);
466}
467
476function getDolUserInt($key, $default = 0, $tmpuser = null)
477{
478 if (empty($tmpuser)) {
479 global $user;
480 $tmpuser = $user;
481 }
482
483 return (int) (isset($tmpuser->conf->$key) ? $tmpuser->conf->$key : $default);
484}
485
486
495define(
496 'MODULE_MAPPING',
497 array(
498 // Map deprecated names to new names
499 'adherent' => 'member', // Has new directory
500 'member_type' => 'adherent_type', // No directory, but file called adherent_type
501 'banque' => 'bank', // Has new directory
502 'contrat' => 'contract', // Has new directory
503 'entrepot' => 'stock', // Has new directory
504 'projet' => 'project', // Has new directory
505 'categorie' => 'category', // Has old directory
506 'commande' => 'order', // Has old directory
507 'expedition' => 'shipping', // Has old directory
508 'facture' => 'invoice', // Has old directory
509 'fichinter' => 'intervention', // Has old directory
510 'ficheinter' => 'intervention', // Backup for 'fichinter'
511 'propale' => 'propal', // Has old directory
512 'societe' => 'thirdparty', // Has old directory
513 'socpeople' => 'contact', // Has old directory
514 'fournisseur' => 'supplier', // Has old directory
515
516 'actioncomm' => 'agenda', // NO module directory (public dir agenda)
517 'product_price' => 'productprice', // NO directory
518 'product_fournisseur_price' => 'productsupplierprice', // NO directory
519 )
520);
521
528function isModEnabled($module)
529{
530 global $conf;
531
532 if (!empty($conf->modules[$module])) {
533 return true; // Most calls use the real name of the module: no need to look at the old/new names mapping
534 }
535
536 // Fix old names (map to new names). The mappings are constant for the request, so they are built once: this function is
537 // called thousands of times per page (hooks, rights, logs...), and array_flip() on each call was most of its cost.
538 static $arrayconv = null;
539 static $arrayconvbis = null;
540 if ($arrayconv === null) {
541 $arrayconv = MODULE_MAPPING;
542 $arrayconvbis = array_flip(MODULE_MAPPING);
543
544 if (!getDolGlobalString('MAIN_USE_NEW_SUPPLIERMOD')) {
545 // Special cases: both use the same module.
546 $arrayconv['supplier_order'] = 'fournisseur';
547 $arrayconv['supplier_invoice'] = 'fournisseur';
548 }
549 }
550
551 if (!empty($arrayconv[$module]) && !empty($conf->modules[$arrayconv[$module]])) {
552 return true;
553 }
554 if (!empty($arrayconvbis[$module]) && !empty($conf->modules[$arrayconvbis[$module]])) {
555 return true;
556 }
557
558 return false;
559}
560
571function getWarningDelay($module, $parmlevel1, $parmlevel2 = '')
572{
573 global $conf;
574
575 // For compatibility with bad naming on module
576 $moduletomoduletouse = array(
577 'invoice' => 'facture',
578 );
579 $moduleParmsMapping = array(
580 'product' => 'produit',
581 );
582
583 if (!empty($moduletomoduletouse[$module])) {
584 $module = $moduletomoduletouse[$module];
585 }
586
587 $warningDelayPath = $parmlevel1;
588 if (!empty($moduleParmsMapping[$warningDelayPath])) {
589 $warningDelayPath = $moduleParmsMapping[$warningDelayPath];
590 }
591
592 if ($parmlevel2) {
593 if (!empty($conf->$module) && !empty($conf->$module->$warningDelayPath) && !empty($conf->$module->$warningDelayPath->$parmlevel2) && !empty($conf->$module->$warningDelayPath->$parmlevel2->warning_delay)) {
594 return (int) $conf->$module->$warningDelayPath->$parmlevel2->warning_delay;
595 }
596 } else {
597 if (!empty($conf->$module) && !empty($conf->$module->$warningDelayPath) && !empty($conf->$module->$warningDelayPath->warning_delay)) {
598 return (int) $conf->$module->$warningDelayPath->warning_delay;
599 }
600 }
601
602 return 0;
603}
604
611function isDolTms($timestamp)
612{
613 if ($timestamp === '') {
614 dol_syslog('Using empty string for a timestamp is deprecated, prefer use of null when calling page ' . $_SERVER["PHP_SELF"] . getCallerInfoString(), LOG_DEBUG);
615 return false;
616 }
617 if (is_null($timestamp) || !is_numeric($timestamp)) {
618 return false;
619 }
620
621 return true;
622}
623
636function getDoliDBInstance($type, $host, $user, $pass, $name, $port, $forcenew = false)
637{
638 require_once DOL_DOCUMENT_ROOT . "/core/db/" . $type . '.class.php';
639
640 $class = 'DoliDB' . ucfirst($type);
641 $db = new $class($type, $host, $user, $pass, $name, $port, $forcenew);
642 return $db;
643}
644
662function getEntity($element, $shared = 1, $currentobject = null)
663{
664 global $conf, $mc, $hookmanager, $object, $action, $db;
665
666 if (!is_object($hookmanager)) {
667 include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
668 $hookmanager = new HookManager($db);
669 }
670
671 // fix different element names (France to English)
672 switch ($element) {
673 case 'projet':
674 $element = 'project';
675 break;
676 case 'contrat':
677 $element = 'contract';
678 break; // "/contrat/class/contrat.class.php"
679 case 'order_supplier':
680 $element = 'supplier_order';
681 break; // "/fourn/class/fournisseur.commande.class.php"
682 case 'invoice_supplier':
683 $element = 'supplier_invoice';
684 break; // "/fourn/class/fournisseur.facture.class.php"
685 }
686
687 if (is_object($mc)) {
688 $out = $mc->getEntity($element, $shared, $currentobject);
689 } else {
690 $out = '';
691 $addzero = array('user', 'usergroup', 'cronjob', 'c_email_templates', 'email_template', 'default_values', 'overwrite_trans', 'extrafields');
692 if (getDolGlobalString('HOLIDAY_ALLOW_ZERO_IN_DIC')) { // this constant break the dictionary admin without Multicompany
693 $addzero[] = 'c_holiday_types';
694 }
695 if (in_array($element, $addzero)) {
696 $out .= '0,';
697 }
698 $out .= ((int) $conf->entity);
699 }
700
701 // Manipulate entities to query on the fly
702 $parameters = array(
703 'element' => $element,
704 'shared' => $shared,
705 'object' => $object,
706 'currentobject' => $currentobject,
707 'out' => $out
708 );
709 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable
710 $reshook = $hookmanager->executeHooks('hookGetEntity', $parameters, $currentobject, $action); // Note that $action and $object may have been modified by some hooks
711
712 if (is_numeric($reshook)) {
713 if ($reshook == 0 && !empty($hookmanager->resPrint)) {
714 $out .= ',' . $hookmanager->resPrint; // add
715 } elseif ($reshook == 1) {
716 $out = $hookmanager->resPrint; // replace
717 }
718 }
719
720 return $out;
721}
722
729function setEntity($currentobject)
730{
731 global $conf, $mc;
732
733 if (is_object($mc) && method_exists($mc, 'setEntity')) {
734 return $mc->setEntity($currentobject);
735 } else {
736 return ((is_object($currentobject) && $currentobject->id > 0 && ((int) $currentobject->entity) > 0) ? (int) $currentobject->entity : $conf->entity);
737 }
738}
739
746function isASecretKey($keyname)
747{
748 return preg_match('/(_pass|password|_pw|_key|securekey|serverkey|secret\d?|p12key|exportkey|_PW_[a-z]+|token)$/i', $keyname);
749}
750
751
758function num2Alpha($n)
759{
760 $r = '';
761 for ($r = ""; $n >= 0; $n = intval($n / 26) - 1) {
762 $r = chr($n % 26 + 0x41) . $r;
763 }
764 return $r;
765}
766
767
784function getBrowserInfo($user_agent)
785{
786 include_once DOL_DOCUMENT_ROOT . '/includes/mobiledetect/mobiledetectlib/Mobile_Detect.php';
787
788 $name = 'unknown';
789 $version = '';
790 $os = 'unknown';
791 $phone = '';
792
793 $user_agent = substr($user_agent, 0, 512); // Avoid to process too large user agent
794
795 // @phan-suppress-next-line PhanTypeMismatchArgumentProbablyReal Bad definition of Mobile_Detect function
796 $detectmobile = new Mobile_Detect(null, $user_agent);
797 $tablet = $detectmobile->isTablet();
798
799 if ($detectmobile->isMobile()) {
800 $phone = 'unknown';
801
802 // If phone/smartphone, we set phone os name.
803 if ($detectmobile->is('AndroidOS')) {
804 $os = $phone = 'android';
805 } elseif ($detectmobile->is('BlackBerryOS')) {
806 $os = $phone = 'blackberry';
807 } elseif ($detectmobile->is('iOS')) {
808 $os = 'ios';
809 $phone = 'iphone';
810 } elseif ($detectmobile->is('PalmOS')) {
811 $os = $phone = 'palm';
812 } elseif ($detectmobile->is('SymbianOS')) {
813 $os = 'symbian';
814 } elseif ($detectmobile->is('webOS')) {
815 $os = 'webos';
816 } elseif ($detectmobile->is('MaemoOS')) {
817 $os = 'maemo';
818 } elseif ($detectmobile->is('WindowsMobileOS') || $detectmobile->is('WindowsPhoneOS')) {
819 $os = 'windows';
820 }
821 }
822
823 // OS
824 if (preg_match('/linux/i', $user_agent)) {
825 $os = 'linux';
826 } elseif (preg_match('/macintosh/i', $user_agent)) {
827 $os = 'macintosh';
828 } elseif (preg_match('/windows/i', $user_agent)) {
829 $os = 'windows';
830 }
831
832 // Name
833 $reg = array();
834 if (preg_match('/firefox(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
835 $name = 'firefox';
836 $version = empty($reg[2]) ? '' : $reg[2];
837 } elseif (preg_match('/edge(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
838 $name = 'edge';
839 $version = empty($reg[2]) ? '' : $reg[2];
840 } elseif (preg_match('/chrome(\/|\s)([\d\.]+)/i', $user_agent, $reg)) {
841 $name = 'chrome';
842 $version = empty($reg[2]) ? '' : $reg[2];
843 } elseif (preg_match('/chrome/i', $user_agent, $reg)) {
844 // we can have 'chrome (Mozilla...) chrome x.y' in one string
845 $name = 'chrome';
846 } elseif (preg_match('/iceweasel/i', $user_agent)) {
847 $name = 'iceweasel';
848 } elseif (preg_match('/epiphany/i', $user_agent)) {
849 $name = 'epiphany';
850 } elseif (preg_match('/safari(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
851 $name = 'safari';
852 $version = empty($reg[2]) ? '' : $reg[2];
853 } elseif (preg_match('/opera(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
854 // Safari is often present in string for mobile but its not.
855 $name = 'opera';
856 $version = empty($reg[2]) ? '' : $reg[2];
857 } elseif (preg_match('/(MSIE\s([0-9]+\.[0-9]))|.*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
858 $name = 'ie';
859 $version = end($reg);
860 } elseif (preg_match('/(Windows NT\s([0-9]+\.[0-9])).*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
861 // MS products at end
862 $name = 'ie';
863 $version = end($reg);
864 } elseif (preg_match('/l[iy]n(x|ks)(\‍(|\/|\s)*([\d\.]+)/i', $user_agent, $reg)) {
865 // MS products at end
866 $name = 'textbrowser';
867 $version = empty($reg[3]) ? '' : $reg[3];
868 } elseif (preg_match('/w3m\/([\d\.]+)/i', $user_agent, $reg)) {
869 // MS products at end
870 $name = 'textbrowser';
871 $version = empty($reg[1]) ? '' : $reg[1];
872 }
873
874 if ($tablet) {
875 $layout = 'tablet';
876 } elseif ($phone) {
877 $layout = 'phone';
878 } else {
879 $layout = 'classic';
880 }
881
882 return array(
883 'browsername' => $name,
884 'browserversion' => $version,
885 'browseros' => $os,
886 'browserua' => $user_agent,
887 'layout' => $layout, // tablet, phone, classic
888 'phone' => $phone, // deprecated
889 'tablet' => $tablet // deprecated
890 );
891}
892
898function dol_shutdown()
899{
900 global $db;
901 $disconnectdone = false;
902 $depth = 0;
903 if (is_object($db) && !empty($db->connected)) {
904 $depth = $db->transaction_opened;
905 $disconnectdone = $db->close();
906 }
907 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));
908}
909
919function GETPOSTISSET($paramname)
920{
921 $isset = false;
922
923 $relativepathstring = $_SERVER["PHP_SELF"];
924 // Clean $relativepathstring
925 if (constant('DOL_URL_ROOT')) {
926 $relativepathstring = preg_replace('/^' . preg_quote(constant('DOL_URL_ROOT'), '/') . '/', '', $relativepathstring);
927 }
928 $relativepathstring = ltrim($relativepathstring, '/');
929 $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
930
931 // Code for search criteria persistence.
932 // Retrieve values if restore_lastsearch_values
933 if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
934 if (!empty($_SESSION['lastsearch_values_' . $relativepathstring])) { // If there is saved values
935 $tmp = json_decode($_SESSION['lastsearch_values_' . $relativepathstring], true);
936 if (is_array($tmp)) {
937 foreach ($tmp as $key => $val) {
938 if ($key == $paramname) { // We are on the requested parameter
939 $isset = true;
940 break;
941 }
942 }
943 }
944 }
945 // If there is saved contextpage, limit, page or mode
946 if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_' . $relativepathstring])) {
947 $isset = true;
948 } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_' . $relativepathstring])) {
949 $isset = true;
950 } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_' . $relativepathstring])) {
951 $isset = true;
952 } elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_' . $relativepathstring])) {
953 $isset = true;
954 }
955 } else {
956 $isset = (isset($_POST[$paramname]) || isset($_GET[$paramname])); // We must keep $_POST and $_GET here
957 }
958
959 return $isset;
960}
961
970function GETPOSTISARRAY($paramname, $method = 0)
971{
972 // for $method test need return the same $val as GETPOST
973 if (empty($method)) {
974 $val = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
975 } elseif ($method == 1) {
976 $val = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
977 } elseif ($method == 2) {
978 $val = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
979 } elseif ($method == 3) {
980 $val = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
981 } else {
982 $val = 'BadFirstParameterForGETPOST';
983 }
984
985 return is_array($val);
986}
987
988
999function GETPOSTINT($paramname, $method = 0, $nodefault = 0)
1000{
1001 return (int) GETPOST($paramname, 'int', $method, null, null, 0, $nodefault);
1002}
1003
1017function GETPOSTFLOAT($paramname, $rounding = '', $option = 2)
1018{
1019 // 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.)
1020 return (float) price2num(GETPOST($paramname), $rounding, $option);
1021}
1022
1038function GETPOSTDATE($prefix, $hourTime = '', $gm = 'auto', $saverestore = '')
1039{
1040 $m = array();
1041 if ($hourTime === 'getpost' || $hourTime === 'getpostend') {
1042 $hour = (GETPOSTISSET($prefix . 'hour') && GETPOSTINT($prefix . 'hour') >= 0) ? GETPOSTINT($prefix . 'hour') : ($hourTime === 'getpostend' ? 23 : 0);
1043 $minute = (GETPOSTISSET($prefix . 'min') && GETPOSTINT($prefix . 'min') >= 0) ? GETPOSTINT($prefix . 'min') : ($hourTime === 'getpostend' ? 59 : 0);
1044 $second = (GETPOSTISSET($prefix . 'sec') && GETPOSTINT($prefix . 'sec') >= 0) ? GETPOSTINT($prefix . 'sec') : ($hourTime === 'getpostend' ? 59 : 0);
1045 } elseif (preg_match('/^(\d\d):(\d\d):(\d\d)$/', $hourTime, $m)) {
1046 $hour = intval($m[1]);
1047 $minute = intval($m[2]);
1048 $second = intval($m[3]);
1049 } elseif ($hourTime === 'end') {
1050 $hour = 23;
1051 $minute = 59;
1052 $second = 59;
1053 } else {
1054 $hour = $minute = $second = 0;
1055 }
1056
1057 if (
1058 $saverestore
1059 && !GETPOSTISSET($prefix . 'day')
1060 && !GETPOSTISSET($prefix . 'month')
1061 && !GETPOSTISSET($prefix . 'year')
1062 && isset($_SESSION['DOLDATE_' . $saverestore . '_day'])
1063 && isset($_SESSION['DOLDATE_' . $saverestore . '_month'])
1064 && isset($_SESSION['DOLDATE_' . $saverestore . '_year'])
1065 ) {
1066 $day = $_SESSION['DOLDATE_' . $saverestore . '_day'];
1067 $month = $_SESSION['DOLDATE_' . $saverestore . '_month'];
1068 $year = $_SESSION['DOLDATE_' . $saverestore . '_year'];
1069 } else {
1070 $month = GETPOSTINT($prefix . 'month');
1071 $day = GETPOSTINT($prefix . 'day');
1072 $year = GETPOSTINT($prefix . 'year');
1073 }
1074
1075 // normalize out of range values
1076 $hour = (int) min($hour, 23);
1077 $minute = (int) min($minute, 59);
1078 $second = (int) min($second, 59);
1079
1080 if ($saverestore) {
1081 $_SESSION['DOLDATE_' . $saverestore . '_day'] = $day;
1082 $_SESSION['DOLDATE_' . $saverestore . '_month'] = $month;
1083 $_SESSION['DOLDATE_' . $saverestore . '_year'] = $year;
1084 }
1085
1086 //print "$hour, $minute, $second, $month, $day, $year, $gm<br>";
1087 return dol_mktime($hour, $minute, $second, $month, $day, $year, $gm);
1088}
1089
1131function GETPOST($paramname, $check = 'alphanohtml', $method = 0, $filter = null, $options = null, $noreplace = 0, $nodefault = 0)
1132{
1133 global $langs, $user;
1134
1135 if (empty($paramname)) { // Explicit test for null for phan.
1136 return 'BadFirstParameterForGETPOST';
1137 }
1138 if (empty($check)) {
1139 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);
1140 // Enable this line to know who call the GETPOST with '' $check parameter.
1141 //var_dump(getCallerInfoString());
1142 }
1143 if (in_array($paramname, array('sortfield', 'sortorder'))) { // Force the $check to a more appropriated value
1144 $check = 'aZ09comma';
1145 }
1146
1147 if (empty($method)) {
1148 $out = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
1149 } elseif ($method == 1) {
1150 $out = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
1151 } elseif ($method == 2) {
1152 $out = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
1153 } elseif ($method == 3) {
1154 $out = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
1155 } else {
1156 return 'BadThirdParameterForGETPOST';
1157 }
1158
1159 $relativepathstring = ''; // For static analysis - looks possibly undefined if not set.
1160
1161 if (empty($method) || $method == 3 || $method == 4) {
1162 $relativepathstring = (empty($_SERVER["PHP_SELF"]) ? '' : $_SERVER["PHP_SELF"]);
1163 // Clean $relativepathstring
1164 if (constant('DOL_URL_ROOT')) {
1165 $relativepathstring = preg_replace('/^' . preg_quote(constant('DOL_URL_ROOT'), '/') . '/', '', $relativepathstring);
1166 }
1167 $relativepathstring = ltrim($relativepathstring, '/');
1168 $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
1169
1170 // Code for search criteria persistence.
1171 // Retrieve saved values if restore_lastsearch_values is set
1172 if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
1173 if (!empty($_SESSION['lastsearch_values_' . $relativepathstring])) { // If there is saved values
1174 $tmp = json_decode($_SESSION['lastsearch_values_' . $relativepathstring], true);
1175 if (is_array($tmp)) {
1176 foreach ($tmp as $key => $val) {
1177 if ($key == $paramname) { // We are on the requested parameter
1178 $out = $val;
1179 break;
1180 }
1181 }
1182 }
1183 }
1184 // If there is saved contextpage, page or limit
1185 if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_' . $relativepathstring])) {
1186 $out = $_SESSION['lastsearch_contextpage_' . $relativepathstring];
1187 } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_' . $relativepathstring])) {
1188 $out = $_SESSION['lastsearch_limit_' . $relativepathstring];
1189 } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_' . $relativepathstring])) {
1190 $out = $_SESSION['lastsearch_page_' . $relativepathstring];
1191 } elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_' . $relativepathstring])) {
1192 $out = $_SESSION['lastsearch_mode_' . $relativepathstring];
1193 }
1194 } elseif (!isset($_GET['sortfield'])) {
1195 // Else, retrieve default values if we are not doing a sort
1196 // 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
1197 if (!empty($_GET['action']) && $_GET['action'] == 'create' && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
1198 // Search default value from $object->field
1199 global $object;
1200 '@phan-var-force CommonObject $object'; // Suppose it's a CommonObject for analysis, but other objects have the $fields field as well
1201 if (is_object($object) && isset($object->fields[$paramname]['default'])) {
1202 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
1203 $out = $object->fields[$paramname]['default'];
1204 }
1205 }
1206 if (getDolGlobalString('MAIN_ENABLE_DEFAULT_VALUES')) {
1207 if (!empty($_GET['action']) && (preg_match('/^create/', $_GET['action']) || preg_match('/^presend/', $_GET['action'])) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
1208 // Now search in setup to overwrite default values
1209 if (!empty($user->default_values)) { // $user->default_values defined from menu 'Setup - Default values'
1210 if (isset($user->default_values[$relativepathstring]['createform'])) {
1211 foreach ($user->default_values[$relativepathstring]['createform'] as $defkey => $defval) {
1212 $qualified = 0;
1213 if ($defkey != '_noquery_') {
1214 $tmpqueryarraytohave = explode('&', $defkey);
1215 $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
1216 $foundintru = 0;
1217 foreach ($tmpqueryarraytohave as $tmpquerytohave) {
1218 if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
1219 $foundintru = 1;
1220 }
1221 }
1222 if (!$foundintru) {
1223 $qualified = 1;
1224 }
1225 } else {
1226 $qualified = 1;
1227 }
1228
1229 if ($qualified) {
1230 if (isset($user->default_values[$relativepathstring]['createform'][$defkey][$paramname])) {
1231 $out = $user->default_values[$relativepathstring]['createform'][$defkey][$paramname];
1232 break;
1233 }
1234 }
1235 }
1236 }
1237 }
1238 } elseif (!empty($paramname) && !isset($_GET[$paramname]) && !isset($_POST[$paramname]) && empty($nodefault)) {
1239 // Management of default search_filters and sort order
1240 if (!empty($user->default_values)) {
1241 // $user->default_values defined from menu 'Setup - Default values'
1242 //var_dump($user->default_values[$relativepathstring]);
1243 if ($paramname == 'sortfield' || $paramname == 'sortorder') {
1244 // Sorted on which fields ? ASC or DESC ?
1245 if (isset($user->default_values[$relativepathstring]['sortorder'])) {
1246 // Even if paramname is sortfield, data are stored into ['sortorder...']
1247 foreach ($user->default_values[$relativepathstring]['sortorder'] as $defkey => $defval) {
1248 $qualified = 0;
1249 if ($defkey != '_noquery_') {
1250 $tmpqueryarraytohave = explode('&', $defkey);
1251 $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
1252 $foundintru = 0;
1253 foreach ($tmpqueryarraytohave as $tmpquerytohave) {
1254 if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
1255 $foundintru = 1;
1256 }
1257 }
1258 if (!$foundintru) {
1259 $qualified = 1;
1260 }
1261 } else {
1262 $qualified = 1;
1263 }
1264
1265 if ($qualified) {
1266 $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
1267 foreach ($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val) {
1268 if ($out) {
1269 $out .= ', ';
1270 }
1271 if ($paramname == 'sortfield') {
1272 $out .= dol_string_nospecial($key, '', $forbidden_chars_to_replace);
1273 }
1274 if ($paramname == 'sortorder') {
1275 $out .= dol_string_nospecial($val, '', $forbidden_chars_to_replace);
1276 }
1277 }
1278 //break; // No break for sortfield and sortorder so we can cumulate fields (is it really useful ?)
1279 }
1280 }
1281 }
1282 } elseif (isset($user->default_values[$relativepathstring]['filters'])) {
1283 foreach ($user->default_values[$relativepathstring]['filters'] as $defkey => $defval) { // $defkey is a querystring like 'a=b&c=d', $defval is key of user
1284 if (!empty($_GET['disabledefaultvalues'])) { // If set of default values has been disabled by a request parameter
1285 continue;
1286 }
1287 $qualified = 0;
1288 if ($defkey != '_noquery_') {
1289 $tmpqueryarraytohave = explode('&', $defkey);
1290 $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
1291 $foundintru = 0;
1292 foreach ($tmpqueryarraytohave as $tmpquerytohave) {
1293 if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
1294 $foundintru = 1;
1295 }
1296 }
1297 if (!$foundintru) {
1298 $qualified = 1;
1299 }
1300 } else {
1301 $qualified = 1;
1302 }
1303
1304 if ($qualified && isset($user->default_values[$relativepathstring]['filters'][$defkey][$paramname])) {
1305 // We must keep $_POST and $_GET here
1306 if (isset($_POST['search_all']) || isset($_GET['search_all'])) {
1307 // We made a search from quick search menu, do we still use default filter ?
1308 if (!getDolGlobalString('MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH')) {
1309 $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
1310 $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
1311 }
1312 } else {
1313 $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
1314 $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
1315 }
1316 break;
1317 }
1318 }
1319 }
1320 }
1321 }
1322 }
1323 }
1324 }
1325
1326 // 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)
1327 // Example of variables: __DAY__, __MONTH__, __YEAR__, __MYCOMPANY_COUNTRY_ID__, __USER_ID__, ...
1328 // 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.
1329 '@phan-var-force string $paramname';
1330 if (!is_array($out) && empty($_POST[$paramname]) && empty($noreplace)) {
1331 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
1332 $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $user, array('mycompany', 'date', 'system', 'user'));
1333 complete_substitutions_array($substitutionarray, $langs, $user);
1334
1335 $out = make_substitutions($out, $substitutionarray, $langs);
1336 }
1337 }
1338
1339 // Check type of variable and make sanitization according to this
1340 if (preg_match('/^array/', $check)) { // If 'array' or 'array:restricthtml' or 'array:aZ09' or 'array:int'
1341 $tmpcheck = 'alphanohtml';
1342 if ($out === null || $out === '') {
1343 $out = array();
1344 } elseif (!is_array($out)) {
1345 $out = explode(',', $out);
1346 } else {
1347 $tmparray = explode(':', $check);
1348 if (!empty($tmparray[1])) {
1349 $tmpcheck = $tmparray[1];
1350 }
1351 }
1352 foreach ($out as $outkey => $outval) {
1353 $out[$outkey] = sanitizeVal($outval, $tmpcheck, $filter, $options);
1354 }
1355 } else {
1356 // If field name is 'search_xxx' then we force the add of space after each < and > (when following char is numeric) because it means
1357 // 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
1358 if (strpos($paramname, 'search_') === 0) {
1359 $out = preg_replace('/([<>])([-+]?\d)/', '\1 \2', $out);
1360 }
1361
1362 // @phan-suppress-next-line UnknownSanitizeType
1363 $out = sanitizeVal($out, $check, $filter, $options);
1364 }
1365
1366 // Sanitizing for special parameters.
1367 // 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.
1368 // @TODO Merge backtopage with backtourl
1369 // @TODO Rename backtolist into backtopagelist
1370 // @TODO Merge urlfrom into backtourl
1371 if (preg_match('/^backto/i', $paramname) || preg_match('/^urlfrom/i', $paramname)) {
1372 $out = str_replace('\\', '/', $out); // Can be before the loop because only 1 char is replaced. No risk to get it after other replacements.
1373 $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.
1374 do {
1375 $oldstringtoclean = $out;
1376 $out = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $out);
1377 $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'
1378 $out = preg_replace(array('/^[a-z]*\/\s*\/+/i'), '', $out); // We remove schema*// to remove external URL
1379 } while ($oldstringtoclean != $out);
1380 }
1381
1382 // Code for search criteria persistence.
1383 // Save data into session if key start with 'search_'
1384 if (empty($method) || $method == 3 || $method == 4) {
1385 if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder', 'sortfield'))) {
1386 //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]);
1387
1388 // We save search key only if $out not empty that means:
1389 // - posted value not empty, or
1390 // - 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).
1391
1392 if ($out != '' && isset($user)) { // $out = '0' or 'abc', it is a search criteria to keep
1393 $user->lastsearch_values_tmp[$relativepathstring][$paramname] = $out;
1394 }
1395 }
1396 }
1397
1398 if ($paramname == 'hashp' && $out == 'shared') {
1399 $out = ''; // We refuse to have hashp=shared as a parameter
1400 }
1401
1402 return $out;
1403}
1404
1414function sanitizeVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
1415{
1416 // TODO : use class "Validate" to perform tests (and add missing tests) if needed for factorize
1417 // Check is done after replacement
1418 if ($out === null) {
1419 $out = '';
1420 }
1421 switch ($check) {
1422 case 'none':
1423 case 'password':
1424 break;
1425 case 'int': // Check param is a numeric value (integer but also float or hexadecimal)
1426 if (!is_numeric($out)) {
1427 $out = '';
1428 }
1429 break;
1430 case 'intcomma':
1431 if (is_array($out)) {
1432 $out = implode(',', $out);
1433 }
1434 if (preg_match('/[^0-9,-]+/i', $out)) {
1435 $out = '';
1436 }
1437 break;
1438 case 'san_alpha':
1439 dol_syslog("Use of parameter value 'san_alpha' in GETPOST is deprecated. Use 'alphanohtml', 'aZ09comma', ...", LOG_WARNING);
1440 $out = filter_var($out, FILTER_SANITIZE_STRING);
1441 break;
1442 case 'email':
1443 $out = filter_var($out, FILTER_SANITIZE_EMAIL);
1444 break;
1445 case 'url':
1446 //$out = filter_var($out, FILTER_SANITIZE_URL); // Not reliable, replaced with FILTER_VALIDATE_URL
1447 $out = preg_replace('/[^:\/\[\]a-z0-9@\$\'\*\~\.\-_,;\?\!=%&+#]+/i', '', $out);
1448 // TODO Allow ( ) but only into password of https://login:password@domain...
1449 break;
1450 case 'aZ':
1451 if (!is_array($out)) {
1452 $out = trim($out);
1453 if (preg_match('/[^a-z]+/i', $out)) {
1454 $out = '';
1455 }
1456 }
1457 break;
1458 case 'aZ09':
1459 if (!is_array($out)) {
1460 $out = trim($out);
1461 if (preg_match('/[^a-z0-9_\-\.]+/i', $out)) {
1462 $out = '';
1463 }
1464 }
1465 break;
1466 case 'aZ09arobase': // great to sanitize $objecttype parameter
1467 if (!is_array($out)) {
1468 $out = trim($out);
1469 if (preg_match('/[^a-z0-9_\-\.@]+/i', $out)) {
1470 $out = '';
1471 }
1472 }
1473 break;
1474 case 'aZ09comma': // great to sanitize $sortfield or $sortorder params that can be 't.abc,t.def_gh'
1475 if (!is_array($out)) {
1476 $out = trim($out);
1477 if (preg_match('/[^a-z0-9_\-\.,]+/i', $out)) {
1478 $out = '';
1479 }
1480 }
1481 break;
1482 case 'alpha': // No html and no ../ and "
1483 case 'alphanohtml': // Recommended for most scalar parameters and search parameters. Not valid for json string.
1484 if (!is_array($out)) {
1485 $out = trim($out);
1486 do {
1487 $oldstringtoclean = $out;
1488 // Remove html tags
1489 $out = dol_string_nohtmltag($out, 0);
1490 // 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).
1491 $out = preg_replace('/\\\‍([0-9xu])/', '/\1', $out);
1492 // Remove also other dangerous string sequences
1493 // '../' or '..\' is dangerous because it allows dir transversals
1494 // '&#38', '&#0000038', '&#x26'... is a the char '&' alone but there is no reason to accept such way to encode input char
1495 // '"' = '&#34' = '&#0000034' = '&#x22' is dangerous because param in url can close the href= or src= and add javascript functions.
1496 // '&#47', '&#0000047', '&#x2F' is the char '/' but there is no reason to accept such way to encode this input char
1497 // '&#92' = '&#0000092' = '&#x5C' is the char '\' but there is no reason to accept such way to encode this input char
1498 $out = str_ireplace(array('../', '..\\', '&#38', '&#0000038', '&#x26', '&quot', '"', '&#34', '&#0000034', '&#x22', '&#47', '&#0000047', '&#x2F', '&#92', '&#0000092', '&#x5C'), '', $out);
1499 } while ($oldstringtoclean != $out);
1500 // keep lines feed
1501 }
1502 break;
1503 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'
1504 if (!is_array($out)) {
1505 $out = trim($out);
1506 do {
1507 $oldstringtoclean = $out;
1508 // Decode html entities
1509 $out = dol_html_entity_decode($out, ENT_COMPAT | ENT_HTML5, 'UTF-8');
1510 // 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).
1511 $out = preg_replace('/\\\‍([0-9xu])/', '/\1', $out);
1512 // Remove also other dangerous string sequences
1513 // '../' or '..\' is dangerous because it allows dir transversals
1514 // '&#38', '&#0000038', '&#x26'... is a the char '&' alone but there is no reason to accept such way to encode input char
1515 // '"' = '&#34' = '&#0000034' = '&#x22' is dangerous because param in url can close the href= or src= and add javascript functions.
1516 // '&#47', '&#0000047', '&#x2F' is the char '/' but there is no reason to accept such way to encode this input char
1517 // '&#92' = '&#0000092' = '&#x5C' is the char '\' but there is no reason to accept such way to encode this input char
1518 $out = str_ireplace(array('../', '..\\', '&#38', '&#0000038', '&#x26', '&quot', '"', '&#34', '&#0000034', '&#x22', '&#47', '&#0000047', '&#x2F', '&#92', '&#0000092', '&#x5C'), '', $out);
1519 } while ($oldstringtoclean != $out);
1520 }
1521 break;
1522 case 'nohtml': // No html. Valid for JSON strings.
1523 $out = dol_string_nohtmltag($out, 0);
1524 break;
1525 case 'restricthtmlnolink':
1526 case 'restricthtml': // Recommended for most html textarea
1527 case 'restricthtmlallowclass':
1528 case 'restricthtmlallowiframe':
1529 case 'restricthtmlallowlinkscript': // Allow link and script tag for head section.
1530 case 'restricthtmlallowunvalid':
1531 $out = dol_htmlwithnojs($out, 1, $check);
1532 break;
1533 case 'custom':
1534 if (!empty($out)) {
1535 if (empty($filter)) {
1536 return 'BadParameterForGETPOST - Param 3 of sanitizeVal()';
1537 }
1538 if (is_null($options)) {
1539 $options = 0;
1540 }
1541 $out = filter_var($out, $filter, $options);
1542 }
1543 break;
1544 default:
1545 dol_syslog("Error, you call sanitizeVal() with a bad value for the check type. Data will be sanitized with alphanohtml.", LOG_ERR);
1546 $out = GETPOST($out, 'alphanohtml');
1547 break;
1548 }
1549
1550 return $out;
1551}
1552
1561function dolSetCookie(string $cookiename, string $cookievalue, int $expire = -1)
1562{
1563 include_once DOL_DOCUMENT_ROOT.'/blockedlog/lib/securitycore.lib.php';
1564
1565 global $dolibarr_main_force_https;
1566
1567 if ($expire == -1) {
1568 $expire = (time() + (86400 * 354)); // keep cookie 1 year.
1569 }
1570
1571 if (PHP_VERSION_ID < 70300) {
1572 setcookie($cookiename, empty($cookievalue) ? '' : $cookievalue, empty($cookievalue) ? 0 : $expire, '/', '', !(empty($dolibarr_main_force_https) && isHTTPS() === false), true); // add tag httponly
1573 } else {
1574 // Only available for php >= 7.3
1575 $cookieparams = array(
1576 'expires' => empty($cookievalue) ? 0 : $expire,
1577 'path' => '/',
1578 //'domain' => '.mywebsite.com', // the dot at the beginning allows compatibility with subdomains
1579 'secure' => !(empty($dolibarr_main_force_https) && isHTTPS() === false),
1580 'httponly' => true,
1581 'samesite' => 'Lax' // None || Lax || Strict
1582 );
1583 setcookie($cookiename, empty($cookievalue) ? '' : $cookievalue, $cookieparams);
1584 }
1585 if (empty($cookievalue)) {
1586 unset($_COOKIE[$cookiename]);
1587 }
1588}
1589
1590if (!function_exists('dol_getprefix')) {
1601 function dol_getprefix($mode = '')
1602 {
1603 // If prefix is for email (we need to have $conf already loaded for this case)
1604 if ($mode == 'email') {
1605 global $conf;
1606
1607 if (getDolGlobalString('MAIL_PREFIX_FOR_EMAIL_ID')) { // If MAIL_PREFIX_FOR_EMAIL_ID is set
1608 if (getDolGlobalString('MAIL_PREFIX_FOR_EMAIL_ID') != 'SERVER_NAME') {
1609 return getDolGlobalString('MAIL_PREFIX_FOR_EMAIL_ID');
1610 } elseif (isset($_SERVER["SERVER_NAME"])) { // If MAIL_PREFIX_FOR_EMAIL_ID is set to 'SERVER_NAME'
1611 return $_SERVER["SERVER_NAME"];
1612 }
1613 }
1614
1615 // The recommended value if MAIL_PREFIX_FOR_EMAIL_ID is not defined (may be not defined for old versions)
1616 if (!empty($conf->file->instance_unique_id)) {
1617 return sha1('dolibarr' . $conf->file->instance_unique_id);
1618 }
1619
1620 // For backward compatibility when instance_unique_id is not set
1621 return sha1(DOL_DOCUMENT_ROOT . DOL_URL_ROOT);
1622 }
1623
1624 // If prefix is for session (no need to have $conf loaded)
1625 global $dolibarr_main_instance_unique_id, $dolibarr_main_cookie_cryptkey; // This is loaded by filefunc.inc.php
1626 $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
1627
1628 // The recommended value (may be not defined for old versions)
1629 if (!empty($tmp_instance_unique_id)) {
1630 return sha1('dolibarr' . $tmp_instance_unique_id);
1631 }
1632
1633 // For backward compatibility when instance_unique_id is not set
1634 if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"])) {
1635 return sha1($_SERVER["SERVER_NAME"] . $_SERVER["DOCUMENT_ROOT"] . DOL_DOCUMENT_ROOT . DOL_URL_ROOT);
1636 } else {
1637 return sha1(DOL_DOCUMENT_ROOT . DOL_URL_ROOT);
1638 }
1639 }
1640}
1641
1652function dol_include_once($relpath, $classname = '')
1653{
1654 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']
1655
1656 if (strpos($relpath, '..') !== false) {
1657 // Found a not valid path
1658 dol_syslog('functions::dol_include_once Tried to load a file with a path including a forbidden sequence ".." : ' . $relpath, LOG_WARNING);
1659 return false;
1660 }
1661 if (!preg_match('/\.php$/', $relpath)) {
1662 // Found a not valid path
1663 dol_syslog('functions::dol_include_once Tried to load a file that is not a PHP file : ' . $relpath, LOG_WARNING);
1664 return false;
1665 }
1666
1667 $fullpath = dol_buildpath($relpath);
1668
1669 if (!file_exists($fullpath)) {
1670 dol_syslog('functions::dol_include_once Tried to load unexisting file: ' . $relpath, LOG_WARNING);
1671 return false;
1672 }
1673 if (!empty($classname) && !class_exists($classname)) {
1674 return include $fullpath;
1675 } else {
1676 return include_once $fullpath;
1677 }
1678}
1679
1680
1694function dol_buildpath($path, $type = 0, $returnemptyifnotfound = 0)
1695{
1696 global $conf;
1697
1698 $path = preg_replace('/^\//', '', $path);
1699
1700 if (empty($type)) { // For a filesystem path
1701 $res = DOL_DOCUMENT_ROOT . '/' . $path; // Standard default path
1702 if (is_array($conf->file->dol_document_root)) {
1703 foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array("main"=>"/home/main/htdocs", "alt0"=>"/home/dirmod/htdocs", ...)
1704 if ($key == 'main') {
1705 continue;
1706 }
1707 // if (@file_exists($dirroot.'/'.$path)) {
1708 if (@file_exists($dirroot . '/' . $path)) { // avoid [php:warn]
1709 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/...'
1710 continue;
1711 }
1712 $res = $dirroot . '/' . $path;
1713 return $res;
1714 }
1715 }
1716 }
1717 if ($returnemptyifnotfound) {
1718 // Not found into alternate dir
1719 if ($returnemptyifnotfound == 1 || !file_exists($res)) {
1720 return '';
1721 }
1722 }
1723 } else {
1724 // For an url path
1725 // We try to get local path of file on filesystem from url
1726 // Note that trying to know if a file on disk exist by forging path on disk from url
1727 // works only for some web server and some setup. This is bugged when
1728 // using proxy, rewriting, virtual path, etc...
1729 $res = '';
1730 if ($type == 1) {
1731 $res = DOL_URL_ROOT . '/' . $path; // Standard value
1732 }
1733 if ($type == 2) {
1734 $res = DOL_MAIN_URL_ROOT . '/' . $path; // Standard value
1735 }
1736 if ($type == 3) {
1737 $res = DOL_URL_ROOT . '/' . $path;
1738 }
1739
1740 foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
1741 if ($key == 'main') {
1742 if ($type == 3) {
1743 /*global $dolibarr_main_url_root;*/
1744
1745 // Define $urlwithroot
1746 $urlwithouturlroot = preg_replace('/' . preg_quote(DOL_URL_ROOT, '/') . '$/i', '', trim($conf->file->dol_main_url_root));
1747 $urlwithroot = $urlwithouturlroot . DOL_URL_ROOT; // This is to use external domain name found into config file
1748 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
1749
1750 $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : $urlwithroot) . '/' . $path; // Test on start with http is for old conf syntax
1751 }
1752 continue;
1753 }
1754 $regs = array();
1755 preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i', $path, $regs); // Take part before '?'
1756 if (!empty($regs[1])) {
1757 //print $key.' - '.$dirroot.' - '.$path.' - '.$conf->file->dol_url_root[$key].' - '.$regs[1].'<br>'."\n";
1758 //if (file_exists($dirroot.'/'.$regs[1])) {
1759 if (@file_exists($dirroot . '/' . $regs[1])) { // avoid [php:warn]
1760 if ($type == 1) {
1761 $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_URL_ROOT) . $conf->file->dol_url_root[$key] . '/' . $path;
1762 } elseif ($type == 2) {
1763 $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_MAIN_URL_ROOT) . $conf->file->dol_url_root[$key] . '/' . $path;
1764 } elseif ($type == 3) {
1765 /*global $dolibarr_main_url_root;*/
1766
1767 // Define $urlwithroot
1768 $urlwithouturlroot = preg_replace('/' . preg_quote(DOL_URL_ROOT, '/') . '$/i', '', trim($conf->file->dol_main_url_root));
1769 $urlwithroot = $urlwithouturlroot . DOL_URL_ROOT; // This is to use external domain name found into config file
1770 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
1771
1772 $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
1773 }
1774 break;
1775 }
1776 }
1777 }
1778 }
1779
1780 return $res;
1781}
1782
1796function dol_getThemeFilePath($file, $theme = '')
1797{
1798 global $conf;
1799
1800 if (empty($theme)) {
1801 $theme = $conf->theme;
1802 }
1803 $file = '/theme/'.$theme.'/'.preg_replace('/^\//', '', $file);
1804
1805 // No module registers a theme directory: the file can only be the native one.
1806 // Return it directly without an extra file_exists() call, like the historical code.
1807 if (empty($conf->modules_parts['theme'])) {
1808 return DOL_DOCUMENT_ROOT.$file;
1809 }
1810
1811 // A module may provide or override the theme: look into the native directory
1812 // first, then into the module-provided theme directories.
1813 if (file_exists(DOL_DOCUMENT_ROOT.$file)) {
1814 return DOL_DOCUMENT_ROOT.$file;
1815 }
1816 foreach ($conf->modules_parts['theme'] as $reldir) {
1817 $tmp = dol_buildpath($reldir.$file, 0, 1);
1818 if ($tmp) {
1819 return $tmp;
1820 }
1821 }
1822
1823 return '';
1824}
1825
1835function dolBuildUrl($url, $params = [], $addtoken = false, $anchor = '')
1836{
1837 global $db, $hookmanager;
1838
1839 if (!is_object($hookmanager)) {
1840 include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
1841 $hookmanager = new HookManager($db);
1842 }
1843 if ((!isset($params['mainmenu']) || empty($params['mainmenu'])) && GETPOSTISSET('mainmenu')) {
1844 $params = array_merge($params, ['mainmenu' => (GETPOST('mainmenu', 'restricthtml'))]);
1845 }
1846 if ((!isset($params['leftmenu'])/* || empty($params['leftmenu']) */) && GETPOSTISSET('leftmenu')) { // do not fill leftmenu if we have leftmenu=
1847 $params = array_merge($params, ['leftmenu' => (GETPOST('leftmenu', 'restricthtml'))]);
1848 }
1849 $parameters = [
1850 'path' => &$url,
1851 'params' => &$params,
1852 'addtoken' => &$addtoken,
1853 ];
1854 $hookmanager->executeHooks('buildurl', $parameters);
1855 if ($addtoken) {
1856 $params = array_merge($params, ['token' => newToken()]);
1857 }
1858 if ($params) {
1859 $url .= '?' . http_build_query($params);
1860 }
1861 if ($anchor) {
1862 $url .= '#' . preg_replace('/[^a-z]/i', '', $anchor);
1863 }
1864
1865 return $url;
1866}
1867
1878function dol_get_object_properties($obj, $properties = [])
1879{
1880 // Get real properties using get_object_vars() if $properties is empty
1881 if (empty($properties)) {
1882 return get_object_vars($obj);
1883 }
1884
1885 $existingProperties = [];
1886 $realProperties = get_object_vars($obj);
1887
1888 // Get the real or magic property values
1889 foreach ($properties as $property) {
1890 if (array_key_exists($property, $realProperties)) {
1891 // Real property, add the value
1892 $existingProperties[$property] = $obj->{$property};
1893 } elseif (property_exists($obj, $property)) {
1894 // Magic property
1895 $existingProperties[$property] = $obj->{$property};
1896 }
1897 }
1898
1899 return $existingProperties;
1900}
1901
1902
1920function dol_clone($srcobject, $native = 2)
1921{
1922 if ($native == 0) {
1923 // deprecated method, use the method with native = 2 instead
1924 dol_syslog("Warning, call to dol_clone() with the deprecated parameter native=0, use 2 instead", LOG_WARNING);
1925
1926 $tmpsavdb = null;
1927 if (isset($srcobject->db) && isset($srcobject->db->db) && is_object($srcobject->db->db) && get_class($srcobject->db->db) == 'PgSql\Connection') {
1928 $tmpsavdb = $srcobject->db;
1929 unset($srcobject->db); // Such property can not be serialized with pgsl (when object->db->db = 'PgSql\Connection')
1930 }
1931
1932 $myclone = unserialize(serialize($srcobject)); // serialize then unserialize is a hack to be sure to have a new object for all fields
1933
1934 if (!empty($tmpsavdb)) {
1935 $srcobject->db = $tmpsavdb;
1936 }
1937 } elseif ($native == 2) {
1938 // recommended method to have a full secured isolated cloned object
1939 $myclone = new stdClass();
1940 $tmparray = get_object_vars($srcobject); // return only public properties
1941
1942 if (is_array($tmparray)) {
1943 foreach ($tmparray as $propertykey => $propertyval) {
1944 if (is_scalar($propertyval) || is_array($propertyval)) {
1945 $myclone->$propertykey = $propertyval;
1946 }
1947 }
1948 }
1949 } else {
1950 $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)
1951 }
1952
1953 return $myclone;
1954}
1955
1956
1965function dol_clone_in_array($srcobject, $startlevel = 0)
1966{
1967 if (is_object($srcobject)) {
1968 $srcobject = get_object_vars($srcobject); // exclude private/protected properties
1969 }
1970
1971 if (is_array($srcobject)) {
1972 $result = [];
1973 foreach ($srcobject as $key => $value) {
1974 if (in_array($key, array('db', 'fields', 'error', 'errorhidden', 'errors', 'oldcopy', 'linkedObjects', 'linked_objects'))) {
1975 continue;
1976 }
1977 $result[$key] = dol_clone_in_array($value, $startlevel + 1);
1978 }
1979 return $result;
1980 }
1981
1982 return $srcobject;
1983}
1984
1985
1995function dol_size($size, $type = '')
1996{
1997 global $conf;
1998 if (empty($conf->dol_optimize_smallscreen)) {
1999 return $size;
2000 }
2001 if ($type == 'width' && $size > 250) {
2002 return 250;
2003 } else {
2004 return 10;
2005 }
2006}
2007
2008
2022function dol_sanitizeFileName($str, $newstr = '_', $unaccent = 1, $includequotes = 0, $allowdash = 0)
2023{
2024 $str = (string) $str;
2025
2026 // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
2027 // Char '>' '<' '|' '$' and ';' are special chars for shells.
2028 // Char '/' and '\' are file delimiters.
2029 // 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
2030 $filesystem_forbidden_chars = array('<', '>', '/', '\\', '?', '*', '|', '"', ':', '°', '$', ';', '`');
2031 if ($includequotes) {
2032 $filesystem_forbidden_chars[] = "'";
2033 }
2034 $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
2035 $tmp = preg_replace('/\-\-+/', '_', $tmp);
2036 if (empty($allowdash)) {
2037 $tmp = preg_replace('/\s+\-([^\s])/', ' _$1', $tmp);
2038 $tmp = preg_replace('/\s+\-$/', '', $tmp);
2039 }
2040 $tmp = str_replace('..', '', $tmp);
2041 $tmp = str_replace('~', $newstr, $tmp);
2042 $tmp = preg_replace('/\s{2,}/', ' ', $tmp);
2043
2044 return $tmp;
2045}
2046
2047
2060function dol_sanitizePathName($str, $newstr = '_', $unaccent = 0, $allowdash = 0)
2061{
2062 // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
2063 // Char '>' '<' '|' '$' ';' and '`' are special chars for shells.
2064 // Char '?' and '*' are for wild card chars.
2065 // Char '"' is dangerous.
2066 // Char '°' is just not expected.
2067 // 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
2068 // Chars '--' and '~' can be used for path transversal
2069 $filesystem_forbidden_chars = array('<', '>', '?', '*', '|', '"', '°', '$', ';', '`');
2070
2071 $tmp = $str;
2072 if ($unaccent) {
2073 $tmp = dol_string_unaccent($tmp);
2074 }
2075 $tmp = dol_string_nospecial($tmp, $newstr, $filesystem_forbidden_chars);
2076 $tmp = preg_replace('/\-\-+/', $newstr, $tmp);
2077 if (empty($allowdash)) {
2078 $tmp = preg_replace('/\s+\-([^\s])/', ' '.$newstr.'$1', $tmp);
2079 $tmp = preg_replace('/\s+\-$/', '', $tmp);
2080 }
2081 $tmp = str_replace('..', $newstr, $tmp);
2082 $tmp = str_replace('~', $newstr, $tmp);
2083 $tmp = preg_replace('/\s{2,}/', ' ', $tmp);
2084
2085 return $tmp;
2086}
2087
2096function dol_sanitizeUrl($stringtoclean, $type = 1)
2097{
2098 // 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)
2099 // We should use dol_string_nounprintableascii but function may not be yet loaded/available
2100 $stringtoclean = preg_replace('/[\x00-\x1F\x7F]/u', '', $stringtoclean); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
2101 // We clean html comments because some hacks try to obfuscate evil strings by inserting HTML comments. Example: on<!-- -->error=alert(1)
2102 $stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
2103
2104 $stringtoclean = str_replace('\\', '/', $stringtoclean);
2105 if ($type == 1) {
2106 // removing : should disable links to external url like http:aaa)
2107 // removing ';' should disable "named" html entities encode into an url (we should not have this into an url)
2108 $stringtoclean = str_replace(array(':', ';', '@'), '', $stringtoclean);
2109 }
2110
2111 do {
2112 $oldstringtoclean = $stringtoclean;
2113 // removing '&colon' should disable links to external url like http:aaa)
2114 // removing '&#' should disable "numeric" html entities encode into an url (we should not have this into an url)
2115 $stringtoclean = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $stringtoclean);
2116 } while ($oldstringtoclean != $stringtoclean);
2117
2118 if ($type == 1) {
2119 // removing '//' should disable links to external url like //aaa or http//)
2120 $stringtoclean = preg_replace(array('/^[a-z]*\/\/+/i'), '', $stringtoclean);
2121 }
2122
2123 // A raw < or > can not be part of a valid URL. We encode them, so the result can not open an html tag or close an inline script block (</script does not need a >).
2124 $stringtoclean = str_replace(array('<', '>'), array('%3C', '%3E'), $stringtoclean);
2125
2126 return $stringtoclean;
2127}
2128
2135function dol_sanitizeEmail($stringtoclean)
2136{
2137 do {
2138 $oldstringtoclean = $stringtoclean;
2139 $stringtoclean = str_ireplace(array('"', ':', '[', ']', "\n", "\r", '\\', '\/'), '', $stringtoclean);
2140 } while ($oldstringtoclean != $stringtoclean);
2141
2142 return $stringtoclean;
2143}
2144
2153function dol_sanitizeKeyCode($str)
2154{
2155 return preg_replace('/[^\w]+/', '', $str);
2156}
2157
2158
2167function dol_string_unaccent($str)
2168{
2169 if (is_null($str)) {
2170 return '';
2171 }
2172
2173 if (utf8_check($str)) {
2174 if (extension_loaded('intl') && getDolGlobalString('MAIN_UNACCENT_USE_TRANSLITERATOR')) {
2175 $transliterator = Transliterator::createFromRules(':: Any-Latin; :: Latin-ASCII; :: NFD; :: [:Nonspacing Mark:] Remove; :: NFC;', Transliterator::FORWARD);
2176 return $transliterator->transliterate($str);
2177 }
2178 // See http://www.utf8-chartable.de/
2179 $string = rawurlencode($str);
2180 $replacements = array(
2181 '%C3%80' => 'A', '%C3%81' => 'A', '%C3%82' => 'A', '%C3%83' => 'A', '%C3%84' => 'A', '%C3%85' => 'A',
2182 '%C3%87' => 'C',
2183 '%C3%88' => 'E', '%C3%89' => 'E', '%C3%8A' => 'E', '%C3%8B' => 'E',
2184 '%C3%8C' => 'I', '%C3%8D' => 'I', '%C3%8E' => 'I', '%C3%8F' => 'I',
2185 '%C3%91' => 'N',
2186 '%C3%92' => 'O', '%C3%93' => 'O', '%C3%94' => 'O', '%C3%95' => 'O', '%C3%96' => 'O', '%C5%90' => 'O',
2187 '%C5%A0' => 'S',
2188 '%C3%99' => 'U', '%C3%9A' => 'U', '%C3%9B' => 'U', '%C3%9C' => 'U', '%C5%B0' => 'U',
2189 '%C3%9D' => 'Y', '%C5%B8' => 'y',
2190 '%C3%A0' => 'a', '%C3%A1' => 'a', '%C3%A2' => 'a', '%C3%A3' => 'a', '%C3%A4' => 'a', '%C3%A5' => 'a',
2191 '%C3%A7' => 'c',
2192 '%C3%A8' => 'e', '%C3%A9' => 'e', '%C3%AA' => 'e', '%C3%AB' => 'e',
2193 '%C3%AC' => 'i', '%C3%AD' => 'i', '%C3%AE' => 'i', '%C3%AF' => 'i',
2194 '%C3%B1' => 'n',
2195 '%C3%B2' => 'o', '%C3%B3' => 'o', '%C3%B4' => 'o', '%C3%B5' => 'o', '%C3%B6' => 'o', '%C5%91' => 'o',
2196 '%C5%A1' => 's',
2197 '%C3%B9' => 'u', '%C3%BA' => 'u', '%C3%BB' => 'u', '%C3%BC' => 'u', '%C5%B1' => 'u',
2198 '%C3%BD' => 'y', '%C3%BF' => 'y',
2199 '%CC%80' => '',
2200 '%CC%81' => '',
2201 '%CC%82' => '',
2202 '%CC%83' => '',
2203 '%CC%84' => '',
2204 '%CC%85' => '',
2205 '%CC%86' => '',
2206 '%CC%87' => '',
2207 '%CC%88' => '',
2208 '%CC%89' => '',
2209 '%CC%8A' => '',
2210 '%CC%8B' => '',
2211 '%CC%8C' => '',
2212 '%CC%8D' => '',
2213 '%CC%8E' => '',
2214 '%CC%8F' => '',
2215 '%CC%90' => '',
2216 '%CC%91' => '',
2217 '%CC%A7' => ''
2218 );
2219 $string = strtr($string, $replacements);
2220 return rawurldecode($string);
2221 } else {
2222 // See http://www.ascii-code.com/
2223 $string = strtr(
2224 $str,
2225 "\xC0\xC1\xC2\xC3\xC4\xC5\xC7
2226 \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
2227 \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
2228 \xE0\xE1\xE2\xE3\xE4\xE5\xE7\xE8\xE9\xEA\xEB
2229 \xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
2230 \xF9\xFA\xFB\xFC\xFD\xFF",
2231 "AAAAAAC
2232 EEEEIIIIDN
2233 OOOOOUUUY
2234 aaaaaaceeee
2235 iiiidnooooo
2236 uuuuyy"
2237 );
2238 $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"));
2239 return $string;
2240 }
2241}
2242
2256function dol_string_nospecial($str, $newstr = '_', $badcharstoreplace = '', $badcharstoremove = '', $keepspaces = 0)
2257{
2258 $forbidden_chars_to_replace = array("'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°', '$', ';'); // more complete than dol_sanitizeFileName
2259 if (empty($keepspaces)) {
2260 $forbidden_chars_to_replace[] = " ";
2261 }
2262 $forbidden_chars_to_remove = array();
2263 //$forbidden_chars_to_remove=array("(",")");
2264
2265 if (is_array($badcharstoreplace)) {
2266 $forbidden_chars_to_replace = $badcharstoreplace;
2267 }
2268 if (is_array($badcharstoremove)) {
2269 $forbidden_chars_to_remove = $badcharstoremove;
2270 }
2271
2272 // @phan-suppress-next-line PhanPluginSuspiciousParamOrderInternal
2273 return str_replace($forbidden_chars_to_replace, $newstr, str_replace($forbidden_chars_to_remove, "", $str));
2274}
2275
2276
2290function dol_string_nounprintableascii($str, $removetabcrlf = 1)
2291{
2292 if ($removetabcrlf) {
2293 return preg_replace('/[\x00-\x1F\x7F]/u', '', $str); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
2294 } else {
2295 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
2296 }
2297}
2298
2305function dolSlugify($stringtoslugify)
2306{
2307 $slug = dol_string_unaccent($stringtoslugify);
2308
2309 // Convert special characters to their ASCII equivalents
2310 if (function_exists('iconv')) {
2311 $slug = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $slug);
2312 }
2313
2314 // Convert to lowercase
2315 $slug = strtolower($slug);
2316
2317 // Replace non-alphanumeric characters with hyphens
2318 $slug = preg_replace('/[^a-z0-9]+/', '-', $slug);
2319
2320 // Remove leading and trailing hyphens
2321 $slug = trim($slug, '-');
2322
2323 return $slug;
2324}
2325
2334function dol_escape_js($stringtoescape, $mode = 0, $noescapebackslashn = 0)
2335{
2336 if (is_null($stringtoescape)) {
2337 return '';
2338 }
2339
2340 // escape quotes and backslashes, newlines, etc.
2341 $substitjs = array("&#039;" => "\\'", "\r" => '\\r');
2342 //$substitjs['</']='<\/'; // We removed this. Should be useless.
2343 if (empty($noescapebackslashn)) {
2344 $substitjs["\n"] = '\\n';
2345 $substitjs['\\'] = '\\\\';
2346 }
2347 if (empty($mode)) {
2348 $substitjs["'"] = "\\'";
2349 $substitjs['"'] = "\\'";
2350 } elseif ($mode == 1) {
2351 $substitjs["'"] = "\\'";
2352 } elseif ($mode == 2) {
2353 $substitjs['"'] = '\\"';
2354 } elseif ($mode == 3) {
2355 $substitjs["'"] = "\\'";
2356 $substitjs['"'] = "\\\"";
2357 }
2358 // Escape also "</script" so the string can't close the <script> block that contains it ("<\/" is "</" in a JS string)
2359 return preg_replace('/<\/(script)/i', '<\\/$1', strtr((string) $stringtoescape, $substitjs));
2360}
2361
2371function dol_escape_uri($stringtoescape)
2372{
2373 return rawurlencode($stringtoescape);
2374}
2375
2382function dol_escape_json($stringtoescape)
2383{
2384 return str_replace('"', '\"', $stringtoescape);
2385}
2386
2394function dol_escape_php($stringtoescape, $stringforquotes = 2)
2395{
2396 if (is_null($stringtoescape)) {
2397 return '';
2398 }
2399
2400 if ($stringforquotes == 2) {
2401 return str_replace('"', "'", $stringtoescape);
2402 } elseif ($stringforquotes == 1) {
2403 // We remove the \ char.
2404 // If we allow the \ char, we can have $stringtoescape =
2405 // abc\';phpcodedanger; so the escapement will become
2406 // abc\\';phpcodedanger; and injecting this into
2407 // $a='...' will give $ac='abc\\';phpcodedanger;
2408 $stringtoescape = str_replace('\\', '', $stringtoescape);
2409 return str_replace("'", "\'", str_replace('"', "'", $stringtoescape));
2410 }
2411
2412 return 'Bad parameter for stringforquotes in dol_escape_php';
2413}
2414
2421function dol_escape_all($stringtoescape)
2422{
2423 return preg_replace('/[^a-z0-9_]/i', '', $stringtoescape);
2424}
2425
2432function dol_escape_xml($stringtoescape)
2433{
2434 $stringtoescape = (string) preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', '', (string) $stringtoescape); // Characters not allowed in XML 1.0
2435
2436 return htmlspecialchars($stringtoescape, ENT_XML1 | ENT_QUOTES, 'UTF-8');
2437}
2438
2439
2447function dol_strtolower($string, $encoding = "UTF-8")
2448{
2449 if (function_exists('mb_strtolower')) {
2450 return mb_strtolower($string, $encoding);
2451 } else {
2452 return strtolower($string);
2453 }
2454}
2455
2464function dol_strtoupper($string, $encoding = "UTF-8")
2465{
2466 if (function_exists('mb_strtoupper')) {
2467 return mb_strtoupper($string, $encoding);
2468 } else {
2469 return strtoupper($string);
2470 }
2471}
2472
2481function dol_ucfirst($string, $encoding = "UTF-8")
2482{
2483 if (function_exists('mb_substr')) {
2484 return mb_strtoupper(mb_substr($string, 0, 1, $encoding), $encoding) . mb_substr($string, 1, null, $encoding);
2485 } else {
2486 return ucfirst($string);
2487 }
2488}
2489
2498function dol_ucwords($string, $encoding = "UTF-8")
2499{
2500 if (function_exists('mb_convert_case')) {
2501 return mb_convert_case($string, MB_CASE_TITLE, $encoding);
2502 } else {
2503 return ucwords($string);
2504 }
2505}
2506
2507
2513function getCallerInfoString()
2514{
2515 $backtrace = debug_backtrace();
2516 $msg = "";
2517 if (count($backtrace) >= 1) {
2518 $pos = 1;
2519 if (count($backtrace) == 1) {
2520 $pos = 0;
2521 }
2522 $trace = $backtrace[$pos];
2523 if (isset($trace['file'], $trace['line'])) {
2524 $msg = " From {$trace['file']}:{$trace['line']}.";
2525 }
2526 }
2527 return $msg;
2528}
2529
2552function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename = '', $restricttologhandler = '', $logcontext = null)
2553{
2554 global $conf, $user, $debugbar;
2555
2556 // If syslog module enabled
2557 if (!isModEnabled('syslog')) {
2558 return;
2559 }
2560
2561 // Check if we are into execution of code of a website
2562 if (defined('USEEXTERNALSERVER') && !defined('USEDOLIBARRSERVER') && !defined('USEDOLIBARREDITOR')) {
2563 global $website, $websitekey;
2564 if (is_object($website) && !empty($website->ref)) {
2565 $suffixinfilename .= '_website_' . $website->ref;
2566 } elseif (!empty($websitekey)) {
2567 $suffixinfilename .= '_website_' . $websitekey;
2568 }
2569 }
2570
2571 // Check if we have a forced suffix
2572 if (defined('USESUFFIXINLOG')) {
2573 $suffixinfilename .= constant('USESUFFIXINLOG');
2574 }
2575
2576 if ($ident < 0) {
2577 foreach ($conf->loghandlers as $loghandlerinstance) {
2578 $loghandlerinstance->setIdent($ident);
2579 }
2580 }
2581
2582 if (!empty($message)) {
2583 // Test log level
2584 // @phan-suppress-next-line PhanPluginDuplicateArrayKey
2585 $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');
2586
2587 if (!array_key_exists($level, $logLevels)) {
2588 dol_syslog('Error Bad Log Level ' . $level, LOG_ERR);
2589 $level = LOG_ERR;
2590 }
2591 if ($level > getDolGlobalInt('SYSLOG_LEVEL')) {
2592 return;
2593 }
2594
2595 if (!getDolGlobalString('MAIN_SHOW_PASSWORD_INTO_LOG')) {
2596 $message = preg_replace('/password=\'[^\']*\'/', 'password=\'hidden\'', $message); // protection to avoid to have value of password in log
2597 }
2598
2599 // If adding log inside HTML page is required
2600 if ((!empty($_REQUEST['logtohtml']) && getDolGlobalString('MAIN_ENABLE_LOG_TO_HTML'))
2601 || (is_object($user) && $user->hasRight('debugbar', 'read') && is_object($debugbar))
2602 ) {
2603 $ospid = sprintf("%7s", dol_trunc((string) getmypid(), 7, 'right', 'UTF-8', 1));
2604 $osuser = " " . sprintf("%6s", dol_trunc(function_exists('posix_getuid') ? posix_getuid() : '', 6, 'right', 'UTF-8', 1));
2605
2606 $conf->logbuffer[] = dol_print_date(dol_now(), "%Y-%m-%d %H:%M:%S") . " " . sprintf("%-7s", $logLevels[$level]) . " " . $ospid . " " . $osuser . " " . $message;
2607 }
2608
2609 //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output
2610 // If html log tag enabled and url parameter log defined, we show output log on HTML comments
2611 if (getDolGlobalString('MAIN_ENABLE_LOG_INLINE_HTML') && GETPOSTINT("log")) {
2612 print "\n\n<!-- Log start\n";
2613 print dol_escape_htmltag($message) . "\n";
2614 print "Log end -->\n";
2615 }
2616
2617 $data = array(
2618 'message' => $message,
2619 'script' => (isset($_SERVER['PHP_SELF']) ? basename($_SERVER['PHP_SELF'], '.php') : ''),
2620 'level' => $level,
2621 'user' => ((is_object($user) && $user->id) ? $user->login : ''),
2622 'ip' => '',
2623 'osuser' => function_exists('posix_getuid') ? (string) posix_getuid() : '',
2624 'ospid' => (string) getmypid() // on linux, max value is defined into cat /proc/sys/kernel/pid_max
2625 );
2626
2627 // For log, we want the reliable IP first.
2628 $remoteip = getUserRemoteIP(1); // Get ip when page run on a web server
2629 if (!empty($remoteip)) {
2630 $data['ip'] = $remoteip;
2631 // This is when server run behind a reverse proxy
2632 // A HTTP_X_FORWARDED_FOR as format "ip real of user, ip of proxy1, ip of proxy2, ..."
2633 // $data['ip'] is last
2634 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
2635 $tmpips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
2636 $data['ip'] = '';
2637 $foundremoteip = 0;
2638 $j = 0;
2639 foreach ($tmpips as $tmpip) {
2640 $tmpip = trim($tmpip);
2641 if (strtolower($tmpip) == strtolower($remoteip)) {
2642 $foundremoteip = 1;
2643 }
2644 if (empty($data['ip'])) {
2645 $data['ip'] = $tmpip;
2646 } else {
2647 $j++;
2648 $data['ip'] .= (($j == 1) ? ' [via ' : ',') . $tmpip;
2649 }
2650 }
2651 if (!$foundremoteip) {
2652 $j++;
2653 $data['ip'] .= (($j == 1) ? ' [via ' : ',') . $remoteip;
2654 }
2655 $data['ip'] .= (($j > 0) ? ']' : '');
2656 } elseif (!empty($_SERVER['HTTP_CLIENT_IP'])) {
2657 $tmpips = explode(',', $_SERVER['HTTP_CLIENT_IP']);
2658 $data['ip'] = '';
2659 $foundremoteip = 0;
2660 $j = 0;
2661 foreach ($tmpips as $tmpip) {
2662 $tmpip = trim($tmpip);
2663 if (strtolower($tmpip) == strtolower($remoteip)) {
2664 $foundremoteip = 1;
2665 }
2666 if (empty($data['ip'])) {
2667 $data['ip'] = $tmpip;
2668 } else {
2669 $j++;
2670 $data['ip'] .= (($j == 1) ? ' [via ' : ',') . $tmpip;
2671 }
2672 }
2673 if (!$foundremoteip) {
2674 $j++;
2675 $data['ip'] .= (($j == 1) ? ' [via ' : ',') . $remoteip;
2676 }
2677 $data['ip'] .= (($j > 0) ? ']' : '');
2678 }
2679 } elseif (!empty($_SERVER['SERVER_ADDR'])) {
2680 // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
2681 $data['ip'] = (string) $_SERVER['SERVER_ADDR'];
2682 } elseif (!empty($_SERVER['COMPUTERNAME'])) {
2683 // 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).
2684 $data['ip'] = (string) $_SERVER['COMPUTERNAME'];
2685 } else {
2686 $data['ip'] = '???';
2687 }
2688
2689 if (!empty($_SERVER['USERNAME'])) {
2690 // 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).
2691 $data['osuser'] = (string) $_SERVER['USERNAME'];
2692 } elseif (!empty($_SERVER['LOGNAME'])) {
2693 // 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).
2694 $data['osuser'] = (string) $_SERVER['LOGNAME'];
2695 }
2696
2697 // Loop on each log handler and send output
2698 foreach ($conf->loghandlers as $loghandlerinstance) {
2699 if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler) {
2700 continue;
2701 }
2702 $loghandlerinstance->export($data, $suffixinfilename);
2703 }
2704 unset($data);
2705 }
2706
2707 if ($ident > 0) {
2708 foreach ($conf->loghandlers as $loghandlerinstance) {
2709 $loghandlerinstance->setIdent($ident);
2710 }
2711 }
2712}
2713
2714
2728function dol_format_address($object, $withcountry = 0, $sep = "\n", $outputlangs = null, $mode = 0, $extralangcode = '')
2729{
2730 global $langs, $hookmanager;
2731
2732 $ret = '';
2733 $countriesusingstate = array('AU', 'CA', 'US', 'IN', 'GB', 'ES', 'UK', 'TR', 'CN'); // See also MAIN_FORCE_STATE_INTO_ADDRESS
2734
2735 // See format of addresses on https://en.wikipedia.org/wiki/Address
2736 // Address
2737 if (empty($mode)) {
2738 $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)));
2739 }
2740 // Zip/Town/State
2741 if (isset($object->country_code) && in_array($object->country_code, array('AU', 'CA', 'US', 'CN')) || getDolGlobalString('MAIN_FORCE_STATE_INTO_ADDRESS')) {
2742 // US: title firstname name \n address lines \n town, state, zip \n country
2743 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
2744 $ret .= (($ret && $town) ? $sep : '') . $town;
2745
2746 if (!empty($object->state)) {
2747 $ret .= ($ret ? ($town ? ", " : $sep) : '') . $object->state;
2748 }
2749 if (!empty($object->zip)) {
2750 $ret .= ($ret ? (($town || $object->state) ? ", " : $sep) : '') . $object->zip;
2751 }
2752 } elseif (isset($object->country_code) && in_array($object->country_code, array('GB', 'UK'))) {
2753 // UK: title firstname name \n address lines \n town state \n zip \n country
2754 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
2755 $ret .= ($ret ? $sep : '') . $town;
2756 if (!empty($object->state)) {
2757 $ret .= ($ret ? ", " : '') . $object->state;
2758 }
2759 if (!empty($object->zip)) {
2760 $ret .= ($ret ? $sep : '') . $object->zip;
2761 }
2762 } elseif (isset($object->country_code) && in_array($object->country_code, array('ES', 'TR'))) {
2763 // ES: title firstname name \n address lines \n zip town \n state \n country
2764 $ret .= ($ret ? $sep : '') . $object->zip;
2765 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
2766 $ret .= ($town ? (($object->zip ? ' ' : '') . $town) : '');
2767 if (!empty($object->state)) {
2768 $ret .= $sep . $object->state;
2769 }
2770 } elseif (isset($object->country_code) && in_array($object->country_code, array('JP'))) {
2771 // JP: In romaji, title firstname name\n address lines \n [state,] town zip \n country
2772 // See https://www.sljfaq.org/afaq/addresses.html
2773 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
2774 $ret .= ($ret ? $sep : '') . ($object->state ? $object->state . ', ' : '') . $town . ($object->zip ? ' ' : '') . $object->zip;
2775 } elseif (isset($object->country_code) && in_array($object->country_code, array('IT'))) {
2776 // IT: title firstname name\n address lines \n zip town state_code \n country
2777 $ret .= ($ret ? $sep : '') . $object->zip;
2778 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
2779 $ret .= ($town ? (($object->zip ? ' ' : '') . $town) : '');
2780 $ret .= (empty($object->state_code) ? '' : (' ' . $object->state_code));
2781 } else {
2782 // Other: title firstname name \n address lines \n zip town[, state] \n country
2783 $town = (($extralangcode && !empty($object->array_languages['address'][$extralangcode])) ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
2784 $ret .= !empty($object->zip) ? (($ret ? $sep : '') . $object->zip) : '';
2785 $ret .= ($town ? (($object->zip ? ' ' : ($ret ? $sep : '')) . $town) : '');
2786 if (!empty($object->state) && in_array($object->country_code, $countriesusingstate)) {
2787 $ret .= ($ret ? ", " : '') . $object->state;
2788 }
2789 }
2790
2791 if (!is_object($outputlangs)) {
2792 $outputlangs = $langs;
2793 }
2794 if ($withcountry) {
2795 $langs->load("dict");
2796 $ret .= (empty($object->country_code) ? '' : ($ret ? $sep : '') . $outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country" . $object->country_code)));
2797 }
2798 if ($hookmanager) {
2799 $parameters = array('withcountry' => $withcountry, 'sep' => $sep, 'outputlangs' => $outputlangs, 'mode' => $mode, 'extralangcode' => $extralangcode);
2800 $reshook = $hookmanager->executeHooks('formatAddress', $parameters, $object);
2801 if ($reshook > 0) {
2802 $ret = '';
2803 }
2804 $ret .= $hookmanager->resPrint;
2805 }
2806
2807 return $ret;
2808}
2809
2810
2811
2821function dol_strftime($fmt, $ts = false, $is_gmt = false)
2822{
2823 if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
2824 return dol_print_date($ts, $fmt, $is_gmt);
2825 } else {
2826 return 'Error date outside supported range';
2827 }
2828}
2829
2852function dol_print_date($time, $format = '', $tzoutput = 'auto', $outputlangs = null, $encodetooutput = false, $decorate = 0)
2853{
2854 global $conf, $langs;
2855
2856 // If date undefined or "", we return ""
2857 if (dol_strlen((string) $time) == 0) {
2858 return ''; // $time=0 allowed (it means 01/01/1970 00:00:00)
2859 }
2860
2861 if ($tzoutput === 'auto') {
2862 $tzoutput = (empty($conf) ? 'tzserver' : (isset($conf->tzuserinputkey) ? $conf->tzuserinputkey : 'tzserver'));
2863 }
2864
2865 // Clean parameters
2866 $to_gmt = false; // false if we want date in server timezone, true if we want to add offset
2867 $offsettz = $offsetdst = 0;
2868 if ($tzoutput) {
2869 $to_gmt = true; // For backward compatibility
2870 if (is_string($tzoutput)) {
2871 if ($tzoutput == 'tzserver') {
2872 $to_gmt = false;
2873 $offsettzstring = @date_default_timezone_get(); // Example 'Europe/Berlin' or 'Indian/Reunion'
2874 // @phan-suppress-next-line PhanPluginRedundantAssignment
2875 $offsettz = 0; // Timezone offset with server timezone (because to_gmt is false), so 0
2876 // @phan-suppress-next-line PhanPluginRedundantAssignment
2877 $offsetdst = 0; // Dst offset with server timezone (because to_gmt is false), so 0
2878 } elseif ($tzoutput == 'tzuser' || $tzoutput == 'tzuserrel') {
2879 $to_gmt = true;
2880 // if no session (by example in cron) may use MAIN_DOLIBARR_USER_TIMEZONE instead UTC
2881 $offsettzstring = (empty($_SESSION['dol_tz_string']) ? getDolGlobalString('MAIN_DOLIBARR_USER_TIMEZONE', 'UTC') : $_SESSION['dol_tz_string']); // Example 'Europe/Berlin' or 'Indian/Reunion'
2882
2883 if (class_exists('DateTimeZone')) {
2884 try {
2885 $user_date_tz = new DateTimeZone($offsettzstring);
2886 } catch (Exception $e) {
2887 // Bad value for $offsettzstring
2888 dol_syslog("DateInvalidTimeZoneException for timezone string '".$offsettzstring."'. Falling back to UTC.", LOG_ERR);
2889 $user_date_tz = new DateTimeZone('UTC'); // Force valid timezone as UTC
2890 }
2891 $user_dt = new DateTime();
2892 $user_dt->setTimezone($user_date_tz);
2893 $user_dt->setTimestamp($tzoutput == 'tzuser' ? dol_now() : (int) $time);
2894 $offsettz = $user_dt->getOffset(); // should include dst ?
2895 } else { // with old method (The 'tzuser' was processed like the 'tzuserrel')
2896 $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60; // Will not be used anymore
2897 $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60; // Will not be used anymore
2898 }
2899 }
2900 }
2901 }
2902 if (!is_object($outputlangs)) {
2903 $outputlangs = $langs;
2904 }
2905 if (!$format) {
2906 $format = 'daytextshort';
2907 }
2908
2909 // Do we have to reduce the length of date (year on 2 chars) to save space.
2910 // Note: dayinputnoreduce is same than day but no reduction of year length will be done
2911 $reduceformat = (!empty($conf->dol_optimize_smallscreen) && in_array($format, array('day', 'dayhour', 'dayhoursec'))) ? 1 : 0; // Test on original $format param.
2912 $format = preg_replace('/inputnoreduce/', '', $format); // so format 'dayinputnoreduce' is processed like day
2913 $formatwithoutreduce = preg_replace('/reduceformat/', '', $format);
2914 if ($formatwithoutreduce != $format) {
2915 $format = $formatwithoutreduce;
2916 $reduceformat = 1;
2917 } // so format 'dayreduceformat' is processed like day
2918
2919 // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
2920 // TODO Add format daysmallyear and dayhoursmallyear
2921 if ($format == 'day') {
2922 $format = ($outputlangs->trans("FormatDateShort") != "FormatDateShort" ? $outputlangs->trans("FormatDateShort") : $conf->format_date_short);
2923 } elseif ($format == 'hour') {
2924 $format = ($outputlangs->trans("FormatHourShort") != "FormatHourShort" ? $outputlangs->trans("FormatHourShort") : $conf->format_hour_short);
2925 } elseif ($format == 'hoursec') {
2926 $s1 = $outputlangs->trans("FormatDateShort");
2927 $s2 = $outputlangs->trans("FormatDateHourSecShort");
2928 $s3 = trim(preg_replace('/'.preg_quote($s1, '/').'/', '', $s2)); // Try to guess the format for FormatHourSecShort using FormatDateShort and FormatDateHourSecShort
2929 $format = $s3;
2930 //$format = ($outputlangs->trans("FormatHourSecShort") != "FormatHourSecShort" ? $outputlangs->trans("FormatHourSecShort") : ($s3 ? $s3 : $conf->format_hour_sec_short));
2931 } elseif ($format == 'hourduration') {
2932 $format = ($outputlangs->trans("FormatHourShortDuration") != "FormatHourShortDuration" ? $outputlangs->trans("FormatHourShortDuration") : $conf->format_hour_short_duration);
2933 } elseif ($format == 'daytext') {
2934 $format = ($outputlangs->trans("FormatDateText") != "FormatDateText" ? $outputlangs->trans("FormatDateText") : $conf->format_date_text);
2935 } elseif ($format == 'daytextshort') {
2936 $format = ($outputlangs->trans("FormatDateTextShort") != "FormatDateTextShort" ? $outputlangs->trans("FormatDateTextShort") : $conf->format_date_text_short);
2937 } elseif ($format == 'dayhour') {
2938 $format = ($outputlangs->trans("FormatDateHourShort") != "FormatDateHourShort" ? $outputlangs->trans("FormatDateHourShort") : $conf->format_date_hour_short);
2939 } elseif ($format == 'dayhoursec') {
2940 $format = ($outputlangs->trans("FormatDateHourSecShort") != "FormatDateHourSecShort" ? $outputlangs->trans("FormatDateHourSecShort") : $conf->format_date_hour_sec_short);
2941 } elseif ($format == 'dayhourtext') {
2942 $format = ($outputlangs->trans("FormatDateHourText") != "FormatDateHourText" ? $outputlangs->trans("FormatDateHourText") : $conf->format_date_hour_text);
2943 } elseif ($format == 'dayhourtextshort') {
2944 $format = ($outputlangs->trans("FormatDateHourTextShort") != "FormatDateHourTextShort" ? $outputlangs->trans("FormatDateHourTextShort") : $conf->format_date_hour_text_short);
2945 } elseif ($format == 'dayhourlog') {
2946 // Format not sensitive to language
2947 $format = '%Y%m%d%H%M%S';
2948 } elseif ($format == 'dayhourlogsmall') {
2949 // Format not sensitive to language
2950 $format = '%y%m%d%H%M';
2951 } elseif ($format == 'dayhourldap') {
2952 $format = '%Y%m%d%H%M%SZ';
2953 } elseif ($format == 'dayhourxcard') {
2954 $format = '%Y%m%dT%H%M%SZ';
2955 } elseif ($format == 'dayxcard') {
2956 $format = '%Y%m%d';
2957 } elseif ($format == 'dayrfc') {
2958 $format = '%Y-%m-%d'; // DATE_RFC3339
2959 } elseif ($format == 'dayhourrfc') {
2960 $format = '%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339
2961 } elseif ($format == 'standard') {
2962 $format = '%Y-%m-%d %H:%M:%S';
2963 }
2964
2965 if ($reduceformat) {
2966 $format = str_replace('%Y', '%y', $format);
2967 $format = str_replace('yyyy', 'yy', $format);
2968 }
2969
2970 // Clean format
2971 if (preg_match('/%b/i', $format)) { // There is some text to translate
2972 // We inhibit translation to text made by strftime functions. We will use trans instead later.
2973 $format = str_replace('%b', '__b__', $format);
2974 $format = str_replace('%B', '__B__', $format);
2975 }
2976 if (preg_match('/%a/i', $format)) { // There is some text to translate
2977 // We inhibit translation to text made by strftime functions. We will use trans instead later.
2978 $format = str_replace('%a', '__a__', $format);
2979 $format = str_replace('%A', '__A__', $format);
2980 }
2981
2982 // Analyze date
2983 $reg = array();
2984 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
2985 dol_print_error(null, "Functions.lib::dol_print_date function called with a bad value" . getCallerInfoString());
2986 return '';
2987 } 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
2988 // This part of code should not be used anymore.
2989 dol_syslog("Functions.lib::dol_print_date function called with a bad value" . getCallerInfoString(), LOG_WARNING);
2990 // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
2991 $syear = (!empty($reg[1]) ? $reg[1] : '');
2992 $smonth = (!empty($reg[2]) ? $reg[2] : '');
2993 $sday = (!empty($reg[3]) ? $reg[3] : '');
2994 $shour = (!empty($reg[4]) ? $reg[4] : '');
2995 $smin = (!empty($reg[5]) ? $reg[5] : '');
2996 $ssec = (!empty($reg[6]) ? $reg[6] : '');
2997
2998 $time = dol_mktime((int) $shour, (int) $smin, (int) $ssec, (int) $smonth, (int) $sday, (int) $syear, true);
2999
3000 if ($to_gmt) {
3001 $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
3002 } else {
3003 $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
3004 }
3005 $dtts = new DateTime();
3006 $dtts->setTimestamp($time);
3007 $dtts->setTimezone($tzo);
3008 $newformat = str_replace(
3009 array('%Y', '%y', '%m', '%d', '%H', '%I', '%M', '%S', '%p', 'T', 'Z', '__a__', '__A__', '__b__', '__B__'),
3010 array('Y', 'y', 'm', 'd', 'H', 'h', 'i', 's', 'A', '__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
3011 $format
3012 );
3013 $ret = $dtts->format($newformat);
3014 $ret = str_replace(
3015 array('__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
3016 array('T', 'Z', '__a__', '__A__', '__b__', '__B__'),
3017 $ret
3018 );
3019 } else {
3020 // Date is a timestamps
3021 if ($time < 100000000000) { // Protection against bad date values
3022 $dtts = new DateTime();
3023 //var_dump($tzoutput.' '.$offsettzstring.' '.$offsettz.$offsetdst.' x '.$to_gmt);
3024 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
3025 $timetouse = (int) $time + $offsettz + $offsetdst; // TODO We could be able to disable use of offsettz and offsetdst to use only offsettzstring.
3026
3027 $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
3028 $dtts->setTimezone($tzo); // important: must be before the setTimestamp
3029 $dtts->setTimestamp($timetouse);
3030 } else {
3031 $timetouse = (int) $time + $offsettz + $offsetdst; // TODO We could be able to disable use of offsettz and offsetdst to use only offsettzstring.
3032
3033 $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
3034 $dtts->setTimestamp($timetouse); // TODO May be we can invert setTimestamp and setTimezone
3035 $dtts->setTimezone($tzo);
3036 }
3037
3038 $newformat = str_replace(
3039 array('%Y', '%y', '%m', '%d', '%H', '%I', '%M', '%S', '%p', '%w', 'T', 'Z', '__a__', '__A__', '__b__', '__B__'),
3040 array('Y', 'y', 'm', 'd', 'H', 'h', 'i', 's', 'A', 'w', '__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
3041 $format
3042 );
3043
3044 $ret = $dtts->format($newformat);
3045 //var_dump($timetouse, $offsettz, $offsetdst, $tzo, $newformat, $ret);
3046 $ret = str_replace(
3047 array('__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
3048 array('T', 'Z', '__a__', '__A__', '__b__', '__B__'),
3049 $ret
3050 );
3051 } else {
3052 $ret = 'Bad value ' . $time . ' for date';
3053 }
3054 }
3055
3056 if (preg_match('/__b__/i', $format)) {
3057 $timetouse = $time + $offsettz + $offsetdst; // TODO We could be able to disable use of offsettz and offsetdst to use only offsettzstring.
3058
3059 if ($to_gmt) {
3060 $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
3061 } else {
3062 $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
3063 }
3064 $dtts = new DateTime();
3065 $dtts->setTimestamp($timetouse);
3066 $dtts->setTimezone($tzo);
3067 $month = (int) $dtts->format("m");
3068 $month = sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'.
3069 if ($encodetooutput) {
3070 $monthtext = $outputlangs->transnoentities('Month' . $month);
3071 $monthtextshort = $outputlangs->transnoentities('MonthShort' . $month);
3072 } else {
3073 $monthtext = $outputlangs->transnoentitiesnoconv('Month' . $month);
3074 $monthtextshort = $outputlangs->transnoentitiesnoconv('MonthShort' . $month);
3075 }
3076 //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
3077 $ret = str_replace('__b__', $monthtextshort, $ret);
3078 $ret = str_replace('__B__', $monthtext, $ret);
3079 //print 'x'.$outputlangs->charset_output.'-'.$ret.'x';
3080 //return $ret;
3081 }
3082 if (preg_match('/__a__/i', $format)) {
3083 //print "time=$time offsettz=$offsettz offsetdst=$offsetdst offsettzstring=$offsettzstring";
3084 $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
3085
3086 if ($to_gmt) {
3087 $tzo = new DateTimeZone('UTC');
3088 } else {
3089 $tzo = new DateTimeZone(date_default_timezone_get());
3090 }
3091 $dtts = new DateTime();
3092 $dtts->setTimestamp($timetouse);
3093 $dtts->setTimezone($tzo);
3094 $w = $dtts->format("w");
3095 $dayweek = $outputlangs->transnoentitiesnoconv('Day' . $w);
3096
3097 $ret = str_replace('__A__', $dayweek, $ret);
3098 $ret = str_replace('__a__', dol_substr($dayweek, 0, 3), $ret);
3099 }
3100
3101 if ($decorate) {
3102 $ret = preg_replace('/(\d\d:\d\d [AP]M)$/', '<span class="'.($decorate === 1 ? 'opacitymedium' : $decorate).'">\1</span>', $ret);
3103 $ret = preg_replace('/(\d\d:\d\d)$/', '<span class="'.($decorate === 1 ? 'opacitymedium' : $decorate).'">\1</span>', $ret);
3104 }
3105
3106 return $ret;
3107}
3108
3109
3130function dol_getdate($timestamp, $fast = false, $forcetimezone = '')
3131{
3132 if ($timestamp === '') {
3133 return array();
3134 }
3135
3136 $datetimeobj = new DateTime();
3137 $datetimeobj->setTimestamp($timestamp); // Use local PHP server timezone
3138 if ($forcetimezone && $forcetimezone != 'tzserver') {
3139 $datetimeobj->setTimezone(new DateTimeZone($forcetimezone == 'gmt' ? 'UTC' : $forcetimezone)); // (add timezone relative to the date entered)
3140 }
3141 $arrayinfo = array(
3142 'year' => ((int) date_format($datetimeobj, 'Y')),
3143 'mon' => ((int) date_format($datetimeobj, 'm')),
3144 'mday' => ((int) date_format($datetimeobj, 'd')),
3145 'wday' => ((int) date_format($datetimeobj, 'w')),
3146 'yday' => ((int) date_format($datetimeobj, 'z')),
3147 'hours' => ((int) date_format($datetimeobj, 'H')),
3148 'minutes' => ((int) date_format($datetimeobj, 'i')),
3149 'seconds' => ((int) date_format($datetimeobj, 's')),
3150 '0' => $timestamp
3151 );
3152
3153 return $arrayinfo;
3154}
3155
3177function dol_mktime($hour, $minute, $second, $month, $day, $year, $gm = 'auto', $check = 1)
3178{
3179 global $conf;
3180 //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
3181
3182 if ($gm === 'auto') {
3183 $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
3184 }
3185 //print 'gm:'.$gm.' gm === auto:'.($gm === 'auto').'<br>';exit;
3186
3187 // Clean parameters
3188 if ($hour == -1 || empty($hour)) {
3189 $hour = 0;
3190 }
3191 if ($minute == -1 || empty($minute)) {
3192 $minute = 0;
3193 }
3194 if ($second == -1 || empty($second)) {
3195 $second = 0;
3196 }
3197
3198 // Check parameters
3199 if ($check) {
3200 if (!$month || !$day) {
3201 return '';
3202 }
3203 if ($day > 31) {
3204 return '';
3205 }
3206 if ($month > 12) {
3207 return '';
3208 }
3209 if ($hour < 0 || $hour > 24) {
3210 return '';
3211 }
3212 if ($minute < 0 || $minute > 60) {
3213 return '';
3214 }
3215 if ($second < 0 || $second > 60) {
3216 return '';
3217 }
3218 }
3219
3220 if (empty($gm) || ($gm === 'server' || $gm === 'tzserver')) {
3221 $default_timezone = @date_default_timezone_get(); // Example 'Europe/Berlin'
3222 $localtz = new DateTimeZone($default_timezone);
3223 } elseif ($gm === 'user' || $gm === 'tzuser' || $gm === 'tzuserrel') {
3224 // We use dol_tz_string first because it is more reliable.
3225 $default_timezone = (empty($_SESSION["dol_tz_string"]) ? @date_default_timezone_get() : $_SESSION["dol_tz_string"]); // Example 'Europe/Berlin'
3226 try {
3227 $localtz = new DateTimeZone($default_timezone);
3228 } catch (Exception $e) {
3229 dol_syslog("Warning dol_tz_string contains an invalid value " . json_encode($_SESSION["dol_tz_string"] ?? null), LOG_WARNING);
3230 $default_timezone = @date_default_timezone_get();
3231 }
3232 } elseif (strrpos($gm, "tz,") !== false) {
3233 $timezone = (string) str_replace("tz,", "", $gm); // Example 'tz,Europe/Berlin'
3234 try {
3235 $localtz = new DateTimeZone($timezone);
3236 } catch (Exception $e) {
3237 dol_syslog("Warning passed timezone contains an invalid value " . $timezone, LOG_WARNING);
3238 }
3239 }
3240
3241 if (empty($localtz)) {
3242 $localtz = new DateTimeZone('UTC');
3243 }
3244 $dt = new DateTime('now', $localtz);
3245 $dt->setDate((int) $year, (int) $month, (int) $day);
3246 $dt->setTime((int) $hour, (int) $minute, (int) $second);
3247 $date = $dt->getTimestamp(); // should include daylight saving time
3248
3249 return $date;
3250}
3251
3252
3263function dol_now($mode = 'gmt')
3264{
3265 $ret = 0;
3266
3267 if ($mode === 'auto') {
3268 $mode = 'gmt';
3269 }
3270
3271 if ($mode == 'gmt') {
3272 $ret = time(); // Time for now at greenwich.
3273 } elseif ($mode == 'tzserver') { // Time for now with PHP server timezone added
3274 require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
3275 $tzsecond = getServerTimeZoneInt('now'); // Contains tz+dayling saving time
3276 $ret = (int) (dol_now('gmt') + ($tzsecond * 3600));
3277 // } elseif ($mode == 'tzref') {// Time for now with parent company timezone is added
3278 // require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
3279 // $tzsecond=getParentCompanyTimeZoneInt(); // Contains tz+dayling saving time
3280 // $ret=dol_now('gmt')+($tzsecond*3600);
3281 } elseif ($mode == 'tzuser' || $mode == 'tzuserrel') {
3282 // Time for now with user timezone added
3283 // print 'time: '.time();
3284 $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60;
3285 $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60;
3286 $ret = (int) (dol_now('gmt') + ($offsettz + $offsetdst));
3287 }
3288
3289 return $ret;
3290}
3291
3292
3301function dol_print_size($size, $shortvalue = 0, $shortunit = 0)
3302{
3303 global $conf, $langs;
3304 $level = 1024;
3305
3306 if (!empty($conf->dol_optimize_smallscreen)) {
3307 $shortunit = 1;
3308 }
3309
3310 // Set value text
3311 if (empty($shortvalue) || $size < ($level * 10)) {
3312 $ret = $size;
3313 $textunitshort = $langs->trans("b");
3314 $textunitlong = $langs->trans("Bytes");
3315 } else {
3316 $ret = round($size / $level, 0);
3317 $textunitshort = $langs->trans("Kb");
3318 $textunitlong = $langs->trans("KiloBytes");
3319 }
3320 // Use long or short text unit
3321 if (empty($shortunit)) {
3322 $ret .= ' ' . $textunitlong;
3323 } else {
3324 $ret .= ' ' . $textunitshort;
3325 }
3326
3327 return $ret;
3328}
3329
3340function dol_print_url($url, $target = '_blank', $max = 32, $withpicto = 0, $morecss = '')
3341{
3342 global $langs;
3343
3344 if (empty($url)) {
3345 return '';
3346 }
3347
3348 $linkstart = '<a href="';
3349 if (!preg_match('/^http/i', $url)) {
3350 $linkstart .= 'http://';
3351 }
3352 $linkstart .= $url;
3353 $linkstart .= '"';
3354 if ($target) {
3355 $linkstart .= ' target="' . $target . '"';
3356 }
3357 $linkstart .= ' title="' . $langs->trans("URL") . ': ' . $url . '"';
3358 $linkstart .= '>';
3359
3360 $link = '';
3361 if (!preg_match('/^http/i', $url)) {
3362 $link .= 'http://';
3363 }
3364 $link .= dol_trunc($url, $max);
3365
3366 $linkend = '</a>';
3367
3368 if ($morecss == 'float') { // deprecated
3369 return '<div class="nospan' . ($morecss ? ' ' . $morecss : '') . '" style="margin-right: 10px">' . ($withpicto ? img_picto($langs->trans("Url"), 'globe', 'class="paddingrightonly"') : '') . $link . '</div>';
3370 } else {
3371 return $linkstart . '<span class="nospan' . ($morecss ? ' ' . $morecss : '') . '" style="margin-right: 10px">' . ($withpicto ? img_picto('', 'globe', 'class="paddingrightonly"') : '') . $link . '</span>' . $linkend;
3372 }
3373}
3374
3388function dol_print_email($email, $contactid = 0, $socid = 0, $addlink = 0, $max = 0, $showinvalid = 2, $withpicto = 0, $morecss = 'paddingrightonly')
3389{
3390 global $user, $langs, $hookmanager;
3391
3392 //global $conf; $conf->global->AGENDA_ADDACTIONFOREMAIL = 1;
3393 //$showinvalid = 1; $email = 'rrrrr';
3394
3395 $newemail = dol_escape_htmltag($email);
3396
3397 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') && $withpicto) {
3398 $withpicto = 0;
3399 }
3400
3401 if (empty($email)) {
3402 return '&nbsp;';
3403 }
3404
3405 if ($addlink == 1) {
3406 $newemail = '<a class="' . ($morecss ? $morecss : '') . '" style="text-overflow: ellipsis;" href="';
3407 if (!preg_match('/^mailto:/i', $email)) {
3408 $newemail .= 'mailto:';
3409 }
3410 $newemail .= $email;
3411 $newemail .= '" target="_blank">';
3412
3413 $newemail .= ($withpicto ? img_picto($langs->trans("EMail") . ' : ' . $email, (is_numeric($withpicto) ? 'email' : $withpicto), 'class="paddingrightonly"') : '');
3414
3415 if ($max > 0) {
3416 $newemail .= dol_trunc($email, $max);
3417 } else {
3418 $newemail .= $email;
3419 }
3420 $newemail .= '</a>';
3421
3422 if ($showinvalid) {
3423 include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
3424 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
3425 $emailonly = CMailFile::getValidAddress($email, 2);
3426 if (!isValidEmail($emailonly)) {
3427 $langs->load("errors");
3428 $newemail .= img_warning($langs->transnoentitiesnoconv("ErrorBadEMail", $emailonly), '', 'paddingrightonly');
3429 } elseif ($showinvalid == 2 && !isValidMailDomain($emailonly)) {
3430 $langs->load("errors");
3431 $newemail .= img_warning($langs->transnoentitiesnoconv("ErrorBadMXDomain", $emailonly), '', 'paddingrightonly');
3432 }
3433 }
3434
3435 if (($contactid || $socid) && isModEnabled('agenda') && $user->hasRight("agenda", "myactions", "create")) {
3436 $type = 'AC_EMAIL';
3437 $linktoaddaction = '';
3438 if (getDolGlobalString('AGENDA_ADDACTIONFOREMAIL')) {
3439 $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>';
3440 }
3441 if ($linktoaddaction) {
3442 $newemail = '<div>' . $newemail . ' ' . $linktoaddaction . '</div>';
3443 }
3444 }
3445 } elseif ($addlink === 'thirdparty') {
3446 $tmpnewemail = '<a class="' . ($morecss ? $morecss : '') . '" style="text-overflow: ellipsis;" href="' . DOL_URL_ROOT . '/societe/card.php?socid=' . $socid . '&action=presend&mode=init#formmailbeforetitle">';
3447 $tmpnewemail .= ($withpicto ? img_picto($langs->trans("EMail") . ' : ' . $email, (is_numeric($withpicto) ? 'email' : $withpicto), 'class="paddingrightonly"') : '');
3448 if ($withpicto == 1) {
3449 $tmpnewemail .= $newemail;
3450 }
3451 $tmpnewemail .= '</a>';
3452
3453 $newemail = $tmpnewemail;
3454 } else {
3455 $newemail = ($withpicto ? img_picto($langs->trans("EMail") . ' : ' . $email, (is_numeric($withpicto) ? 'email' : $withpicto), 'class="paddingrightonly"') : '') . $newemail;
3456
3457 if ($showinvalid) {
3458 include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
3459 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
3460 $emailonly = CMailFile::getValidAddress($email, 2);
3461 if (!isValidEmail($emailonly)) {
3462 $langs->load("errors");
3463 $newemail .= img_warning($langs->transnoentitiesnoconv("ErrorBadEMail", $email));
3464 } elseif ($showinvalid == 2 && !isValidMailDomain($emailonly)) {
3465 $langs->load("errors");
3466 $newemail .= img_warning($langs->transnoentitiesnoconv("ErrorBadMXDomain", $emailonly));
3467 }
3468 }
3469 }
3470
3471 //$rep = '<div class="nospan" style="margin-right: 10px">';
3472 //$rep = ($withpicto ? img_picto($langs->trans("EMail").' : '.$email, (is_numeric($withpicto) ? 'email' : $withpicto), 'class="paddingrightonly"') : '').$newemail;
3473 //$rep .= '</div>';
3474 $rep = $newemail;
3475 if (getDolGlobalString('MAIN_MAIL_COPY_ON_CLICK')) {
3476 $rep .= showValueWithClipboardCPButton($newemail, 0, 'none');
3477 }
3478
3479 if ($hookmanager) {
3480 $parameters = array('cid' => $contactid, 'socid' => $socid, 'addlink' => $addlink, 'picto' => $withpicto);
3481
3482 $reshook = $hookmanager->executeHooks('printEmail', $parameters, $email);
3483 if ($reshook > 0) {
3484 $rep = '';
3485 }
3486 $rep .= $hookmanager->resPrint;
3487 }
3488
3489 return $rep;
3490}
3491
3492
3498function getArrayOfSocialNetworks()
3499{
3500 global $db;
3501
3502 $socialnetworks = array();
3503 // Enable caching of array
3504 require_once DOL_DOCUMENT_ROOT . '/core/lib/memory.lib.php';
3505 $cachekey = dol_sanitizeKeyCode(str_replace(',', '_', 'socialnetworks_'.getEntity('c_socialnetworks')));
3506 $dataretrieved = dol_getcache($cachekey);
3507
3508 if (!is_null($dataretrieved)) {
3509 $socialnetworks = $dataretrieved;
3510 } else {
3511 $sql = "SELECT rowid, code, label, url, icon, active FROM " . MAIN_DB_PREFIX . "c_socialnetworks";
3512 $sql .= " WHERE entity IN (" . getEntity('c_socialnetworks').")";
3513
3514 $resql = $db->query($sql);
3515 if ($resql) {
3516 while ($obj = $db->fetch_object($resql)) {
3517 $socialnetworks[$obj->code] = array(
3518 'rowid' => $obj->rowid,
3519 'label' => $obj->label,
3520 'url' => $obj->url,
3521 'icon' => $obj->icon,
3522 'active' => $obj->active,
3523 );
3524 }
3525 }
3526 dol_setcache($cachekey, $socialnetworks); // If setting cache fails, this is not a problem, so we do not test result.
3527 }
3528
3529 return (is_array($socialnetworks) ? $socialnetworks : array());
3530}
3531
3542function dol_print_socialnetworks($value, $contactid, $socid, $type, $dictsocialnetworks = array())
3543{
3544 global $hookmanager, $langs, $user;
3545
3546 $htmllink = $value;
3547
3548 if (empty($value)) {
3549 return '&nbsp;';
3550 }
3551
3552 if (!empty($type)) {
3553 $htmllink = '<div class="divsocialnetwork inline-block valignmiddle">';
3554 // Use dictionary definition for picto $dictsocialnetworks[$type]['icon']
3555 $htmllink .= '<span class="fab pictofixedwidth ' . ($dictsocialnetworks[$type]['icon'] ? $dictsocialnetworks[$type]['icon'] : 'fa-link') . '"></span>';
3556 if ($type == 'skype') {
3557 $htmllink .= dol_escape_htmltag($value);
3558 $htmllink .= '&nbsp; <a href="skype:';
3559 $htmllink .= dol_string_nospecial($value, '_', '', array('@'));
3560 $htmllink .= '?call" alt="' . $langs->trans("Call") . '&nbsp;' . $value . '" title="' . dol_escape_htmltag($langs->trans("Call") . ' ' . $value) . '">';
3561 $htmllink .= '<img src="' . DOL_URL_ROOT . '/theme/common/skype_callbutton.png" border="0">';
3562 $htmllink .= '</a><a href="skype:';
3563 $htmllink .= dol_string_nospecial($value, '_', '', array('@'));
3564 $htmllink .= '?chat" alt="' . $langs->trans("Chat") . '&nbsp;' . $value . '" title="' . dol_escape_htmltag($langs->trans("Chat") . ' ' . $value) . '">';
3565 $htmllink .= '<img class="paddingleft" src="' . DOL_URL_ROOT . '/theme/common/skype_chatbutton.png" border="0">';
3566 $htmllink .= '</a>';
3567 if (($contactid || $socid) && isModEnabled('agenda') && $user->hasRight('agenda', 'myactions', 'create')) {
3568 $addlink = 'AC_SKYPE';
3569 $link = '';
3570 if (getDolGlobalString('AGENDA_ADDACTIONFORSKYPE')) {
3571 $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>';
3572 }
3573 $htmllink .= ($link ? ' ' . $link : '');
3574 }
3575 } else {
3576 if (!empty($dictsocialnetworks[$type]['url'])) {
3577 $tmpvirginurl = preg_replace('/\/?{socialid}/', '', $dictsocialnetworks[$type]['url']);
3578 if ($tmpvirginurl) {
3579 $value = preg_replace('/^www\.' . preg_quote($tmpvirginurl, '/') . '\/?/', '', $value);
3580 $value = preg_replace('/^' . preg_quote($tmpvirginurl, '/') . '\/?/', '', $value);
3581
3582 $tmpvirginurl3 = preg_replace('/^https:\/\//i', 'https://www.', $tmpvirginurl);
3583 if ($tmpvirginurl3) {
3584 $value = preg_replace('/^www\.' . preg_quote($tmpvirginurl3, '/') . '\/?/', '', $value);
3585 $value = preg_replace('/^' . preg_quote($tmpvirginurl3, '/') . '\/?/', '', $value);
3586 }
3587
3588 $tmpvirginurl2 = preg_replace('/^https?:\/\//i', '', $tmpvirginurl);
3589 if ($tmpvirginurl2) {
3590 $value = preg_replace('/^www\.' . preg_quote($tmpvirginurl2, '/') . '\/?/', '', $value);
3591 $value = preg_replace('/^' . preg_quote($tmpvirginurl2, '/') . '\/?/', '', $value);
3592 }
3593 }
3594 if (preg_match('/^https?:\/\//i', $value)) {
3595 $link = $value;
3596 } else {
3597 $link = str_replace('{socialid}', $value, $dictsocialnetworks[$type]['url']);
3598 }
3599 $valuetoshow = $value;
3600 $valuetoshow = preg_replace('/https:\/\/www\.(twitter|x|linkedin)\.com\/?/', '', $valuetoshow);
3601 if (preg_match('/^https?:\/\//i', $link)) {
3602 $htmllink .= '<a href="' . dol_sanitizeUrl($link, 0) . '" target="_blank" rel="noopener noreferrer">' . dol_escape_htmltag($valuetoshow) . '</a>';
3603 } else {
3604 $htmllink .= '<a href="' . dol_sanitizeUrl($link, 1) . '" target="_blank" rel="noopener noreferrer">' . dol_escape_htmltag($valuetoshow) . '</a>';
3605 }
3606 } else {
3607 $htmllink .= dol_escape_htmltag($value);
3608 }
3609 }
3610 $htmllink .= '</div>';
3611 } else {
3612 $langs->load("errors");
3613 $htmllink .= img_warning($langs->trans("ErrorBadSocialNetworkValue", $value));
3614 }
3615
3616 if ($hookmanager) {
3617 $parameters = array(
3618 'value' => $value,
3619 'cid' => $contactid,
3620 'socid' => $socid,
3621 'type' => $type,
3622 'dictsocialnetworks' => $dictsocialnetworks,
3623 );
3624
3625 $reshook = $hookmanager->executeHooks('printSocialNetworks', $parameters);
3626 if ($reshook > 0) {
3627 $htmllink = '';
3628 }
3629 $htmllink .= $hookmanager->resPrint;
3630 }
3631
3632 return $htmllink;
3633}
3634
3644function dol_print_profids($profID, $profIDtype, $countrycode = '', $addcpButton = 1)
3645{
3646 global $mysoc;
3647
3648 if (empty($profID) || empty($profIDtype)) {
3649 return '';
3650 }
3651 if (empty($countrycode)) {
3652 $countrycode = (is_object($mysoc) ? $mysoc->country_code : '');
3653 }
3654 $newProfID = $profID;
3655 $id = substr($profIDtype, -1);
3656 $ret = '';
3657 if (strtoupper($countrycode) == 'FR') {
3658 // France
3659 // (see https://www.economie.gouv.fr/entreprises/numeros-identification-entreprise)
3660
3661 if ($id == 1 && dol_strlen($newProfID) == 9) {
3662 // SIREN (ex: 123 123 123)
3663 $newProfID = substr($newProfID, 0, 3) . ' ' . substr($newProfID, 3, 3) . ' ' . substr($newProfID, 6, 3);
3664 }
3665 if ($id == 2 && dol_strlen($newProfID) == 14) {
3666 // SIRET (ex: 123 123 123 12345)
3667 $newProfID = substr($newProfID, 0, 3) . ' ' . substr($newProfID, 3, 3) . ' ' . substr($newProfID, 6, 3) . ' ' . substr($newProfID, 9, 5);
3668 }
3669 if ($id == 3 && dol_strlen($newProfID) == 5) {
3670 // NAF/APE (ex: 69.20Z)
3671 $newProfID = substr($newProfID, 0, 2) . '.' . substr($newProfID, 2, 3);
3672 }
3673 if ($profIDtype === 'VAT' && dol_strlen($newProfID) == 13) {
3674 // TVA intracommunautaire (ex: FR12 123 123 123)
3675 $newProfID = substr($newProfID, 0, 4) . ' ' . substr($newProfID, 4, 3) . ' ' . substr($newProfID, 7, 3) . ' ' . substr($newProfID, 10, 3);
3676 }
3677 }
3678 if (!empty($addcpButton)) {
3679 $ret = showValueWithClipboardCPButton(dol_escape_htmltag($profID), ($addcpButton == 1 ? 1 : 0), $newProfID);
3680 } else {
3681 $ret = $newProfID;
3682 }
3683 return $ret;
3684}
3685
3701function dol_print_phone($phone, $countrycode = '', $contactid = 0, $socid = 0, $addlink = '', $separ = "&nbsp;", $withpicto = '', $titlealt = '', $adddivfloat = 0, $morecss = 'paddingright')
3702{
3703 global $conf, $user, $langs, $mysoc, $hookmanager;
3704
3705 // Clean phone parameter
3706 $phone = is_null($phone) ? '' : preg_replace("/[\s.-]/", "", trim($phone));
3707 if (empty($phone)) {
3708 return '';
3709 }
3710 if (getDolGlobalString('MAIN_PHONE_SEPAR')) {
3711 $separ = getDolGlobalString('MAIN_PHONE_SEPAR');
3712 }
3713 if (empty($countrycode) && is_object($mysoc)) {
3714 $countrycode = $mysoc->country_code;
3715 }
3716
3717 // Short format for small screens
3718 if (!empty($conf->dol_optimize_smallscreen) && $separ != 'hidenum') {
3719 $separ = '';
3720 }
3721
3722 $newphone = $phone;
3723 $newphonewa = $phone;
3724 if (strtoupper($countrycode) == "FR") {
3725 // France
3726 if (dol_strlen($phone) == 10) {
3727 $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);
3728 } elseif (dol_strlen($phone) == 7) {
3729 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 2) . $separ . substr($newphone, 5, 2);
3730 } elseif (dol_strlen($phone) == 9) {
3731 $newphone = substr($newphone, 0, 2) . $separ . substr($newphone, 2, 3) . $separ . substr($newphone, 5, 2) . $separ . substr($newphone, 7, 2);
3732 } elseif (dol_strlen($phone) == 11) {
3733 $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);
3734 } elseif (dol_strlen($phone) == 12) {
3735 $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);
3736 } elseif (dol_strlen($phone) == 13) {
3737 $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);
3738 }
3739 } elseif (strtoupper($countrycode) == "CA") {
3740 if (dol_strlen($phone) == 10) {
3741 $newphone = ($separ != '' ? '(' : '') . substr($newphone, 0, 3) . ($separ != '' ? ')' : '') . $separ . substr($newphone, 3, 3) . ($separ != '' ? '-' : '') . substr($newphone, 6, 4);
3742 }
3743 } elseif (strtoupper($countrycode) == "PT") { //Portugal
3744 if (dol_strlen($phone) == 13) { //ex: +351_ABC_DEF_GHI
3745 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 3) . $separ . substr($newphone, 10, 3);
3746 }
3747 } elseif (strtoupper($countrycode) == "SR") { //Suriname
3748 if (dol_strlen($phone) == 10) { //ex: +597_ABC_DEF
3749 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 3);
3750 } elseif (dol_strlen($phone) == 11) { //ex: +597_ABC_DEFG
3751 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 4);
3752 }
3753 } elseif (strtoupper($countrycode) == "DE") { //Deutschland
3754 if (dol_strlen($phone) == 14) { //ex: +49_ABCD_EFGH_IJK
3755 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 4) . $separ . substr($newphone, 7, 4) . $separ . substr($newphone, 11, 3);
3756 } elseif (dol_strlen($phone) == 13) { //ex: +49_ABC_DEFG_HIJ
3757 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 4) . $separ . substr($newphone, 10, 3);
3758 }
3759 } elseif (strtoupper($countrycode) == "ES") { //Spain
3760 if (dol_strlen($phone) == 12) { //ex: +34_ABC_DEF_GHI
3761 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 3) . $separ . substr($newphone, 9, 3);
3762 }
3763 } elseif (strtoupper($countrycode) == "BF") { // Burkina Faso
3764 if (dol_strlen($phone) == 12) { //ex : +22 A BC_DE_FG_HI
3765 $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);
3766 }
3767 } elseif (strtoupper($countrycode) == "RO") { // Roumanie
3768 if (dol_strlen($phone) == 12) { //ex : +40 AB_CDE_FG_HI
3769 $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);
3770 }
3771 } elseif (strtoupper($countrycode) == "TR") { //Turquie
3772 if (dol_strlen($phone) == 13) { //ex : +90 ABC_DEF_GHIJ
3773 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 3) . $separ . substr($newphone, 9, 4);
3774 }
3775 } elseif (strtoupper($countrycode) == "US") { //Etat-Unis
3776 if (dol_strlen($phone) == 12) { //ex: +1 ABC_DEF_GHIJ
3777 $newphone = substr($newphone, 0, 2) . $separ . substr($newphone, 2, 3) . $separ . substr($newphone, 5, 3) . $separ . substr($newphone, 8, 4);
3778 }
3779 } elseif (strtoupper($countrycode) == "MX") { //Mexique
3780 if (dol_strlen($phone) == 12) { //ex: +52 ABCD_EFG_HI
3781 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 4) . $separ . substr($newphone, 7, 3) . $separ . substr($newphone, 10, 2);
3782 } elseif (dol_strlen($phone) == 11) { //ex: +52 AB_CD_EF_GH
3783 $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);
3784 } elseif (dol_strlen($phone) == 13) { //ex: +52 ABC_DEF_GHIJ
3785 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 3) . $separ . substr($newphone, 9, 4);
3786 }
3787 } elseif (strtoupper($countrycode) == "ML") { //Mali
3788 if (dol_strlen($phone) == 12) { //ex: +223 AB_CD_EF_GH
3789 $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);
3790 }
3791 } elseif (strtoupper($countrycode) == "TH") { //Thailand
3792 if (dol_strlen($phone) == 11) { //ex: +66_ABC_DE_FGH
3793 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 2) . $separ . substr($newphone, 8, 3);
3794 } elseif (dol_strlen($phone) == 12) { //ex: +66_A_BCD_EF_GHI
3795 $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);
3796 }
3797 } elseif (strtoupper($countrycode) == "MU") {
3798 //Maurice
3799 if (dol_strlen($phone) == 11) { //ex: +230_ABC_DE_FG
3800 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 2) . $separ . substr($newphone, 9, 2);
3801 } elseif (dol_strlen($phone) == 12) { //ex: +230_ABCD_EF_GH
3802 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 4) . $separ . substr($newphone, 8, 2) . $separ . substr($newphone, 10, 2);
3803 }
3804 } elseif (strtoupper($countrycode) == "ZA") { //Afrique du sud
3805 if (dol_strlen($phone) == 12) { //ex: +27_AB_CDE_FG_HI
3806 $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);
3807 }
3808 } elseif (strtoupper($countrycode) == "SY") { //Syrie
3809 if (dol_strlen($phone) == 12) { //ex: +963_AB_CD_EF_GH
3810 $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);
3811 } elseif (dol_strlen($phone) == 13) { //ex: +963_AB_CD_EF_GHI
3812 $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);
3813 }
3814 } elseif (strtoupper($countrycode) == "AE") { //Emirats Arabes Unis
3815 if (dol_strlen($phone) == 12) { //ex: +971_ABC_DEF_GH
3816 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 3) . $separ . substr($newphone, 10, 2);
3817 } elseif (dol_strlen($phone) == 13) { //ex: +971_ABC_DEF_GHI
3818 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 3) . $separ . substr($newphone, 10, 3);
3819 } elseif (dol_strlen($phone) == 14) { //ex: +971_ABC_DEF_GHIK
3820 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 3) . $separ . substr($newphone, 10, 4);
3821 }
3822 } elseif (strtoupper($countrycode) == "DZ") { //Algeria
3823 if (dol_strlen($phone) == 13) { //ex: +213_ABC_DEF_GHI
3824 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 3) . $separ . substr($newphone, 10, 3);
3825 }
3826 } elseif (strtoupper($countrycode) == "BE") { //Belgique
3827 if (dol_strlen($phone) == 11) { //ex: +32_ABC_DE_FGH
3828 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 2) . $separ . substr($newphone, 8, 3);
3829 } elseif (dol_strlen($phone) == 12) { //ex: +32_ABC_DEF_GHI
3830 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 3) . $separ . substr($newphone, 9, 3);
3831 }
3832 } elseif (strtoupper($countrycode) == "PF") { //French Polynesia
3833 if (dol_strlen($phone) == 12) { //ex: +689_AB_CD_EF_GH
3834 $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);
3835 }
3836 } elseif (strtoupper($countrycode) == "CO") { //Colombie
3837 if (dol_strlen($phone) == 13) { //ex: +57_ABC_DEF_GH_IJ
3838 $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);
3839 }
3840 } elseif (strtoupper($countrycode) == "JO") { //Jordanie
3841 if (dol_strlen($phone) == 12) { //ex: +962_A_BCD_EF_GH
3842 $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);
3843 }
3844 } elseif (strtoupper($countrycode) == "JM") { //Jamaica
3845 if (dol_strlen($newphone) == 12) { //ex: +1867_ABC_DEFG
3846 $newphone = substr($newphone, 0, 5) . $separ . substr($newphone, 5, 3) . $separ . substr($newphone, 8, 4);
3847 }
3848 } elseif (strtoupper($countrycode) == "MG") { //Madagascar
3849 if (dol_strlen($phone) == 13) { //ex: +261_AB_CD_EFG_HI
3850 $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);
3851 }
3852 } elseif (strtoupper($countrycode) == "GB") { //Royaume uni
3853 if (dol_strlen($phone) == 13) { //ex: +44_ABCD_EFG_HIJ
3854 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 4) . $separ . substr($newphone, 7, 3) . $separ . substr($newphone, 10, 3);
3855 }
3856 } elseif (strtoupper($countrycode) == "CH") { //Suisse
3857 if (dol_strlen($phone) == 12) { //ex: +41_AB_CDE_FG_HI
3858 $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);
3859 } elseif (dol_strlen($phone) == 15) { // +41_AB_CDE_FGH_IJKL
3860 $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);
3861 }
3862 } elseif (strtoupper($countrycode) == "TN") { //Tunisie
3863 if (dol_strlen($phone) == 12) { //ex: +216_AB_CDE_FGH
3864 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 2) . $separ . substr($newphone, 6, 3) . $separ . substr($newphone, 9, 3);
3865 }
3866 } elseif (strtoupper($countrycode) == "GF") { //Guyane francaise
3867 if (dol_strlen($phone) == 13) { //ex: +594_ABC_DE_FG_HI (ABC=594 de nouveau)
3868 $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);
3869 }
3870 } elseif (strtoupper($countrycode) == "GP") { //Guadeloupe
3871 if (dol_strlen($phone) == 13) { //ex: +590_ABC_DE_FG_HI (ABC=590 de nouveau)
3872 $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);
3873 }
3874 } elseif (strtoupper($countrycode) == "MQ") { //Martinique
3875 if (dol_strlen($phone) == 13) { //ex: +596_ABC_DE_FG_HI (ABC=596 de nouveau)
3876 $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);
3877 }
3878 } elseif (strtoupper($countrycode) == "IT") { //Italie
3879 if (dol_strlen($phone) == 12) { //ex: +39_ABC_DEF_GHI
3880 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 3) . $separ . substr($newphone, 9, 3);
3881 } elseif (dol_strlen($phone) == 13) { //ex: +39_ABC_DEF_GH_IJ
3882 $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);
3883 }
3884 } elseif (strtoupper($countrycode) == "AU") {
3885 //Australie
3886 if (dol_strlen($phone) == 12) {
3887 //ex: +61_A_BCDE_FGHI
3888 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 1) . $separ . substr($newphone, 4, 4) . $separ . substr($newphone, 8, 4);
3889 }
3890 } elseif (strtoupper($countrycode) == "LU") {
3891 // Luxembourg
3892 if (dol_strlen($phone) == 10) { // fix 6 digits +352_AA_BB_CC
3893 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 2) . $separ . substr($newphone, 6, 2) . $separ . substr($newphone, 8, 2);
3894 } elseif (dol_strlen($phone) == 11) { // fix 7 digits +352_AA_BB_CC_D
3895 $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);
3896 } elseif (dol_strlen($phone) == 12) { // fix 8 digits +352_AA_BB_CC_DD
3897 $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);
3898 } elseif (dol_strlen($phone) == 13) { // mobile +352_AAA_BB_CC_DD
3899 $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);
3900 }
3901 } elseif (strtoupper($countrycode) == "PE") {
3902 // Peru
3903 if (dol_strlen($phone) == 7) { // fix 7 numbers without code AAA_BBBB
3904 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 4);
3905 } elseif (dol_strlen($phone) == 9) { // mobile add code and fix 9 numbers +51_AAA_BBB_CCC
3906 $newphonewa = '+51' . $newphone;
3907 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 3);
3908 } elseif (dol_strlen($phone) == 11) { // fix 11 numbers +511_AAA_BBBB
3909 $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 4);
3910 } elseif (dol_strlen($phone) == 12) { // mobile +51_AAA_BBB_CCC
3911 $newphonewa = $newphone;
3912 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 3) . $separ . substr($newphone, 9, 3);
3913 }
3914 } elseif (strtoupper($countrycode) == "IN") { //India
3915 if (dol_strlen($phone) == 13) {
3916 if ($withpicto == 'phone') { //ex: +91_AB_CDEF_GHIJ
3917 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 2) . $separ . substr($newphone, 5, 4) . $separ . substr($newphone, 9, 4);
3918 } else { //ex: +91_ABCDE_FGHIJ
3919 $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 5) . $separ . substr($newphone, 8, 5);
3920 }
3921 }
3922 } elseif (strtoupper($countrycode) == "CI") { //Ivory cost
3923 if (dol_strlen($phone) == 14) { //ex : +225_AB_CD_EF_GH_IJ
3924 $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) . $separ.substr($newphone, 12, 2);
3925 }
3926 }
3927
3928 $newphoneastart = $newphoneaend = '';
3929 if (!empty($addlink)) { // Link on phone number (+ link to add action if conf->global->AGENDA_ADDACTIONFORPHONE set)
3930 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
3931 $newphoneastart = '<a href="tel:' . urlencode($phone) . '">';
3932 $newphoneaend .= '</a>';
3933 } elseif (isModEnabled('clicktodial') && $addlink == 'AC_TEL') { // If click to dial, we use click to dial url
3934 if (empty($user->clicktodial_loaded)) {
3935 $user->fetch_clicktodial();
3936 }
3937
3938 // Define urlmask
3939 $urlmask = getDolGlobalString('CLICKTODIAL_URL', 'ErrorClickToDialModuleNotConfigured');
3940 if (!empty($user->clicktodial_url)) {
3941 $urlmask = $user->clicktodial_url;
3942 }
3943
3944 $clicktodial_poste = (!empty($user->clicktodial_poste) ? urlencode($user->clicktodial_poste) : '');
3945 $clicktodial_login = (!empty($user->clicktodial_login) ? urlencode($user->clicktodial_login) : '');
3946 $clicktodial_password = (!empty($user->clicktodial_password) ? urlencode($user->clicktodial_password) : '');
3947 // This line is for backward compatibility @phan-suppress-next-line PhanPluginPrintfVariableFormatString
3948 $url = sprintf($urlmask, urlencode($phone), $clicktodial_poste, $clicktodial_login, $clicktodial_password);
3949 // Those lines are for substitution
3950 $substitarray = array(
3951 '__PHONEFROM__' => $clicktodial_poste,
3952 '__PHONETO__' => urlencode($phone),
3953 '__LOGIN__' => $clicktodial_login,
3954 '__PASS__' => $clicktodial_password
3955 );
3956 $url = make_substitutions($url, $substitarray);
3957 if (!getDolGlobalString('CLICKTODIAL_DO_NOT_USE_AJAX_CALL')) {
3958 // Default and recommended: New method using ajax without submitting a page making a javascript history.go(-1) back
3959 $newphoneastart = '<a href="' . $url . '" class="cssforclicktodial">'; // Call of ajax is handled by the lib_foot.js.php on class 'cssforclicktodial'
3960 $newphoneaend = '</a>';
3961 } else {
3962 // Old method
3963 $newphoneastart = '<a href="' . $url . '"';
3964 if (getDolGlobalString('CLICKTODIAL_FORCENEWTARGET')) {
3965 $newphoneastart .= ' target="_blank" rel="noopener noreferrer"';
3966 }
3967 $newphoneastart .= '>';
3968 $newphoneaend .= '</a>';
3969 }
3970 }
3971 //if (($contactid || $socid) && isModEnabled('agenda') && $user->hasRight('agenda', 'myactions', 'create'))
3972 if (isModEnabled('agenda') && $user->hasRight("agenda", "myactions", "create")) {
3973 $type = 'AC_TEL';
3974 $addlinktoagenda = '';
3975 if ($addlink == 'AC_FAX') {
3976 $type = 'AC_FAX';
3977 }
3978 if (getDolGlobalString('AGENDA_ADDACTIONFORPHONE')) {
3979 $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>';
3980 }
3981 if ($addlinktoagenda) {
3982 $newphone = '<span>' . $newphone . ' ' . $addlinktoagenda . '</span>';
3983 }
3984 }
3985 }
3986
3987 if (getDolGlobalString('CONTACT_PHONEMOBILE_SHOW_LINK_TO_WHATSAPP') && $withpicto == 'mobile') {
3988 // Link to Whatsapp
3989 $newphone .= ' <a href="https://wa.me/' . $newphonewa . '" target="_blank"'; // Use api to whatasapp contacts
3990 $newphone .= '><span class="paddingright fab fa-whatsapp" style="color:#25D366;" title="WhatsApp"></span></a>';
3991 }
3992
3993 if (empty($titlealt) && isset($langs)) {
3994 $titlealt = ($withpicto == 'fax' ? $langs->trans("Fax") : $langs->trans("Phone"));
3995 }
3996 $rep = '';
3997
3998 if ($hookmanager) {
3999 $parameters = array('countrycode' => $countrycode, 'cid' => $contactid, 'socid' => $socid, 'titlealt' => $titlealt, 'picto' => $withpicto);
4000 $reshook = $hookmanager->executeHooks('printPhone', $parameters, $phone);
4001 $rep .= $hookmanager->resPrint;
4002 }
4003 if (empty($reshook)) {
4004 $picto = '';
4005 if ($withpicto) {
4006 if ($withpicto == 'fax') {
4007 $picto = 'phoning_fax';
4008 } elseif ($withpicto == 'phone') {
4009 $picto = 'phone';
4010 } elseif ($withpicto == 'mobile') {
4011 $picto = 'phoning_mobile';
4012 } else {
4013 $picto = '';
4014 }
4015 }
4016 if ($adddivfloat == 1) {
4017 $rep .= '<div class="nospan float' . ($morecss ? ' ' . $morecss : '') . '">';
4018 } elseif (empty($adddivfloat)) {
4019 $rep .= '<span' . ($morecss ? ' class="' . $morecss . '"' : '') . '>';
4020 }
4021
4022 $rep .= $newphoneastart;
4023 $rep .= ($withpicto ? img_picto($titlealt, $picto) : '');
4024 if ($separ != 'hidenum') {
4025 $rep .= ($withpicto ? ' ' : '') . $newphone;
4026 }
4027 $rep .= $newphoneaend;
4028
4029 if ($adddivfloat == 1) {
4030 $rep .= '</div>';
4031 } elseif (empty($adddivfloat)) {
4032 $rep .= '</span>';
4033 }
4034 }
4035
4036 return $rep;
4037}
4038
4047function dol_print_ip($ip, $mode = 0, $showname = 0)
4048{
4049 global $conf;
4050
4051 $ret = '';
4052 if (!isset($conf->cache['resolveips'])) {
4053 $conf->cache['resolveips'] = array();
4054 }
4055
4056 if ($mode != 2) {
4057 $countrycode = dolGetCountryCodeFromIp($ip);
4058 if ($countrycode) { // If success, countrycode is us, fr, ...
4059 if (file_exists(DOL_DOCUMENT_ROOT . '/theme/common/flags/' . $countrycode . '.png')) {
4060 $ret .= picto_from_langcode($countrycode);
4061 } else {
4062 $ret .= '(' . $countrycode . ')';
4063 }
4064 $ret .= '&nbsp;';
4065 } else {
4066 // Nothing
4067 }
4068
4069 $cityname = dolGetCityFromIp($ip);
4070 if ($cityname) { // Only set if the GeoIP datafile in use is a City database
4071 $ret .= dol_escape_htmltag($cityname) . '&nbsp;';
4072 }
4073 }
4074
4075 if (in_array($mode, [0, 2])) {
4076 $domain = '';
4077 if ($showname) {
4078 if (!array_key_exists($ip, $conf->cache['resolveips'])) {
4079 $domain = gethostbyaddr($ip);
4080 $conf->cache['resolveips'][$ip] = $domain; // false or domain
4081 } else {
4082 $domain = $conf->cache['resolveips'][$ip];
4083 }
4084 }
4085 if ($domain) {
4086 $ret .= $domain;
4087 } else {
4088 $ret .= $ip;
4089 }
4090 }
4091
4092 return $ret;
4093}
4094
4107function getUserRemoteIP($trusted = 0)
4108{
4109 if ($trusted) { // Return only IP we can rely on (not spoofable by the client)
4110 $ip = (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']); // value may be the IP of a proxy
4111 // 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)
4112 // This can happen if the proxy were added in the list of trusted proxy.
4113 return $ip;
4114 }
4115
4116 // Try to guess the real IP of client (but this may not be reliable)
4117 if (empty($_SERVER['HTTP_X_FORWARDED_FOR']) || preg_match('/[^0-9\.\:,\[\]\s]/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {
4118 if (empty($_SERVER['HTTP_CLIENT_IP']) || preg_match('/[^0-9\.\:,\[\]\s]/', $_SERVER['HTTP_CLIENT_IP'])) {
4119 if (empty($_SERVER["HTTP_CF_CONNECTING_IP"])) {
4120 $ip = (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']); // value may be the IP of the proxy and not the client
4121 } else {
4122 $ip = $_SERVER["HTTP_CF_CONNECTING_IP"]; // value here may have been forged by client
4123 }
4124 } else {
4125 $ip = preg_replace('/,.*$/', '', $_SERVER['HTTP_CLIENT_IP']); // value is clean here but may have been forged by proxy
4126 }
4127 } else {
4128 $ip = preg_replace('/,.*$/', '', $_SERVER['HTTP_X_FORWARDED_FOR']); // value is clean here but may have been forged by proxy
4129 }
4130 return $ip;
4131}
4132
4139function dolGetCountryCodeFromIp($ip)
4140{
4141 $countrycode = '';
4142
4143 if (isModEnabled('geoipmaxmind')) {
4144 if (getDolGlobalString('GEOIP_VERSION') == 'php') {
4145 $datafile = getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE');
4146 } else {
4147 $diroffile = getMultidirOutput(null, 'geoipmaxmind');
4148 $datafile = $diroffile . '/' . getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE_EMBEDDED');
4149 }
4150 //$ip='24.24.24.24';
4151 //$datafile='/usr/share/GeoIP/GeoIP.dat'; Note that this must be downloaded datafile (not same than datafile provided with ubuntu packages)
4152 if ($datafile) {
4153 try {
4154 include_once DOL_DOCUMENT_ROOT . '/core/class/dolgeoip.class.php';
4155 $geoip = new DolGeoIP('country', $datafile);
4156 //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
4157 $countrycode = $geoip->getCountryCodeFromIP($ip);
4158 } catch (Exception $e) {
4159 //print 'Error with GeoIP database: '.$e->getMessage();
4160 }
4161 }
4162 }
4163
4164 return $countrycode;
4165}
4166
4174function dolGetCityFromIp($ip)
4175{
4176 $cityname = '';
4177
4178 if (isModEnabled('geoipmaxmind')) {
4179 if (getDolGlobalString('GEOIP_VERSION') == 'php') {
4180 $datafile = getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE');
4181 } else {
4182 $diroffile = getMultidirOutput(null, 'geoipmaxmind');
4183 $datafile = $diroffile . '/' . getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE_EMBEDDED');
4184 }
4185 if ($datafile) {
4186 try {
4187 include_once DOL_DOCUMENT_ROOT . '/core/class/dolgeoip.class.php';
4188 $geoip = new DolGeoIP('country', $datafile);
4189 $cityname = $geoip->getCityNameFromIP($ip);
4190 } catch (Exception $e) {
4191 //print 'Error with GeoIP database: '.$e->getMessage();
4192 }
4193 }
4194 }
4195
4196 return $cityname;
4197}
4198
4199
4206function dol_user_country()
4207{
4208 //$ret=$user->xxx;
4209 $ret = '';
4210 if (isModEnabled('geoipmaxmind')) {
4211 $ip = getUserRemoteIP();
4212 $datafile = getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE');
4213 //$ip='24.24.24.24';
4214 //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';
4215 include_once DOL_DOCUMENT_ROOT . '/core/class/dolgeoip.class.php';
4216 $geoip = new DolGeoIP('country', $datafile);
4217 $countrycode = $geoip->getCountryCodeFromIP($ip);
4218 $ret = $countrycode;
4219 }
4220 return $ret;
4221}
4222
4235function dol_print_address($address, $htmlid, $element, $id, $noprint = 0, $charfornl = '')
4236{
4237 global $hookmanager;
4238
4239 $out = '';
4240
4241 if ($address) {
4242 if ($hookmanager) {
4243 $parameters = array('element' => $element, 'id' => $id);
4244 $reshook = $hookmanager->executeHooks('printAddress', $parameters, $address);
4245 $out .= $hookmanager->resPrint;
4246 }
4247 if (empty($reshook)) {
4248 if (empty($charfornl)) {
4249 $out .= nl2br((string) $address);
4250 } else {
4251 $out .= preg_replace('/[\r\n]+/', $charfornl, (string) $address);
4252 }
4253
4254 // TODO Remove this block, we can add this using the hook now
4255 $showgmap = $showomap = 0;
4256 if (($element == 'thirdparty' || $element == 'societe') && isModEnabled('google') && getDolGlobalString('GOOGLE_ENABLE_GMAPS')) {
4257 $showgmap = 1;
4258 }
4259 if ($element == 'contact' && isModEnabled('google') && getDolGlobalString('GOOGLE_ENABLE_GMAPS_CONTACTS')) {
4260 $showgmap = 1;
4261 }
4262 if ($element == 'member' && isModEnabled('google') && getDolGlobalString('GOOGLE_ENABLE_GMAPS_MEMBERS')) {
4263 $showgmap = 1;
4264 }
4265 if ($element == 'user' && isModEnabled('google') && getDolGlobalString('GOOGLE_ENABLE_GMAPS_USERS')) {
4266 $showgmap = 1;
4267 }
4268 if (($element == 'thirdparty' || $element == 'societe') && isModEnabled('openstreetmap') && getDolGlobalString('OPENSTREETMAP_ENABLE_MAPS')) {
4269 $showomap = 1;
4270 }
4271 if ($element == 'contact' && isModEnabled('openstreetmap') && getDolGlobalString('OPENSTREETMAP_ENABLE_MAPS_CONTACTS')) {
4272 $showomap = 1;
4273 }
4274 if ($element == 'member' && isModEnabled('openstreetmap') && getDolGlobalString('OPENSTREETMAP_ENABLE_MAPS_MEMBERS')) {
4275 $showomap = 1;
4276 }
4277 if ($element == 'user' && isModEnabled('openstreetmap') && getDolGlobalString('OPENSTREETMAP_ENABLE_MAPS_USERS')) {
4278 $showomap = 1;
4279 }
4280 if ($showgmap) {
4281 $url = dol_buildpath('/google/gmaps.php?mode=' . $element . '&id=' . $id, 1);
4282 $out .= ' <a href="' . $url . '" target="_gmaps"><img id="' . $htmlid . '" class="valigntextbottom" src="' . DOL_URL_ROOT . '/theme/common/gmap.png"></a>';
4283 }
4284 if ($showomap) {
4285 $url = dol_buildpath('/openstreetmap/maps.php?mode=' . $element . '&id=' . $id, 1);
4286 $out .= ' <a href="' . $url . '" target="_gmaps"><img id="' . $htmlid . '_openstreetmap" class="valigntextbottom" src="' . DOL_URL_ROOT . '/theme/common/gmap.png"></a>';
4287 }
4288 }
4289 }
4290 if ($noprint) {
4291 return $out;
4292 } else {
4293 print $out;
4294 return null;
4295 }
4296}
4297
4298
4308function isValidEmail($address, $acceptsupervisorkey = 0, $acceptuserkey = 0)
4309{
4310 if ($acceptsupervisorkey && $address == '__SUPERVISOREMAIL__') {
4311 return true;
4312 }
4313 if ($acceptuserkey && $address == '__USER_EMAIL__') {
4314 return true;
4315 }
4316 if (filter_var($address, FILTER_VALIDATE_EMAIL)) {
4317 return true;
4318 }
4319
4320 return false;
4321}
4322
4332function isValidMXRecord($domain)
4333{
4334 if (function_exists('idn_to_ascii') && function_exists('checkdnsrr')) {
4335 if (!checkdnsrr(idn_to_ascii($domain), 'MX')) {
4336 return 0;
4337 }
4338 if (function_exists('getmxrr')) {
4339 $mxhosts = array();
4340 $weight = array();
4341 getmxrr(idn_to_ascii($domain), $mxhosts, $weight);
4342 if (count($mxhosts) > 1) {
4343 return 1;
4344 }
4345 if (count($mxhosts) == 1 && !in_array((string) $mxhosts[0], array('', '.'))) {
4346 return 1;
4347 }
4348
4349 return 0;
4350 }
4351 }
4352
4353 // function idn_to_ascii or checkdnsrr or getmxrr does not exists
4354 return -1;
4355}
4356
4364function isValidPhone($phone)
4365{
4366 return true;
4367}
4368
4369
4379function dolGetFirstLetters($s, $nbofchar = 1)
4380{
4381 $ret = '';
4382 $tmparray = explode(' ', $s);
4383 foreach ($tmparray as $tmps) {
4384 $ret .= dol_substr($tmps, 0, $nbofchar);
4385 }
4386
4387 return $ret;
4388}
4389
4390
4399function dol_strlen($string, $stringencoding = 'UTF-8', $binarycount = 0)
4400{
4401 if (is_null($string)) {
4402 return 0;
4403 }
4404
4405 if (function_exists('mb_strlen') && empty($binarycount)) {
4406 return mb_strlen($string, $stringencoding);
4407 } else {
4408 return strlen($string);
4409 }
4410}
4411
4422function dol_substr($string, $start, $length = null, $stringencoding = '', $trunconbytes = 0)
4423{
4424 global $langs;
4425
4426 if (empty($stringencoding)) {
4427 $stringencoding = (empty($langs) ? 'UTF-8' : $langs->charset_output);
4428 }
4429
4430 $ret = '';
4431 if (empty($trunconbytes)) {
4432 if (function_exists('mb_substr')) {
4433 $ret = mb_substr($string, $start, $length, $stringencoding);
4434 } else {
4435 $ret = substr($string, $start, $length);
4436 }
4437 } else {
4438 if (function_exists('mb_strcut')) {
4439 $ret = mb_strcut($string, $start, $length, $stringencoding);
4440 } else {
4441 $ret = substr($string, $start, $length);
4442 }
4443 }
4444 return $ret;
4445}
4446
4447
4461function dol_trunc($string, $size = 40, $trunc = 'right', $stringencoding = 'UTF-8', $nodot = 0, $display = 0)
4462{
4463 global $conf;
4464
4465 if (empty($size) || getDolGlobalString('MAIN_DISABLE_TRUNC')) {
4466 return $string;
4467 }
4468
4469 if (empty($stringencoding)) {
4470 $stringencoding = 'UTF-8';
4471 }
4472 // reduce for small screen
4473 if (!empty($conf->dol_optimize_smallscreen) && $conf->dol_optimize_smallscreen == 1 && $display == 1) {
4474 $size = round($size / 3);
4475 }
4476
4477 // We go always here
4478 if ($trunc == 'right') {
4479 $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
4480 if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
4481 // If nodot is 0 and size is 1 chars more, we don't trunc and don't add '...'
4482 return dol_substr($newstring, 0, $size, $stringencoding) . ($nodot ? '' : '…');
4483 } else {
4484 //return 'u'.$size.'-'.$newstring.'-'.dol_strlen($newstring,$stringencoding).'-'.$string;
4485 return $string;
4486 }
4487 } elseif ($trunc == 'middle') {
4488 $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
4489 if (dol_strlen($newstring, $stringencoding) > 2 && dol_strlen($newstring, $stringencoding) > ($size + 1)) {
4490 $size1 = (int) round($size / 2);
4491 $size2 = (int) round($size / 2);
4492 return dol_substr($newstring, 0, $size1, $stringencoding) . '…' . dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size2, $size2, $stringencoding);
4493 } else {
4494 return $string;
4495 }
4496 } elseif ($trunc == 'left') {
4497 $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
4498 if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
4499 // If nodot is 0 and size is 1 chars more, we don't trunc and don't add '...'
4500 return '…' . dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size, $size, $stringencoding);
4501 } else {
4502 return $string;
4503 }
4504 } elseif ($trunc == 'wrap') {
4505 $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
4506 if (dol_strlen($newstring, $stringencoding) > ($size + 1)) {
4507 return dol_substr($newstring, 0, $size, $stringencoding) . "\n" . dol_trunc(dol_substr($newstring, $size, dol_strlen($newstring, $stringencoding) - $size, $stringencoding), $size, $trunc);
4508 } else {
4509 return $string;
4510 }
4511 } else {
4512 return 'BadParam3CallingDolTrunc';
4513 }
4514}
4515
4516
4528function vatrate($rate, $addpercent = false, $info_bits = 0, $usestarfornpr = 0, $html = 0)
4529{
4530 $morelabel = '';
4531
4532 if (preg_match('/%/', $rate)) {
4533 $rate = str_replace('%', '', $rate);
4534 $addpercent = true;
4535 }
4536 $reg = array();
4537 if (preg_match('/\‍((.*)\‍)/', $rate, $reg)) {
4538 $morelabel = ' (' . $reg[1] . ')';
4539 $rate = preg_replace('/\s*' . preg_quote($morelabel, '/') . '/', '', $rate);
4540 $morelabel = ' ' . ($html ? '<span class="opacitymedium small">' : '') . '(' . $reg[1] . ')' . ($html ? '</span>' : '');
4541 }
4542 if (preg_match('/\*/', $rate)) {
4543 $rate = str_replace('*', '', $rate);
4544 $info_bits |= 1;
4545 }
4546
4547 // If rate is '9/9/9' we don't change it. If rate is '9.000' we apply price()
4548 if (!preg_match('/\//', $rate)) {
4549 $ret = price($rate, 0, '', 0, 0) . ($addpercent ? '%' : '');
4550 } else {
4551 // TODO Split on / and output with a price2num to have clean numbers without ton of 000.
4552 $ret = $rate . ($addpercent ? '%' : '');
4553 }
4554 if (($info_bits & 1) && $usestarfornpr >= 0) {
4555 $ret .= ' *';
4556 }
4557 $ret .= $morelabel;
4558 return $ret;
4559}
4560
4561
4576function price($amount, $form = 0, $outlangs = '', $trunc = 1, $rounding = -1, $forcerounding = -1, $currency_code = '')
4577{
4578 global $langs, $conf;
4579
4580 // Clean parameters
4581 if (empty($amount)) {
4582 $amount = 0; // To have a numeric value if amount not defined or = ''
4583 }
4584 $amount = (is_numeric($amount) ? $amount : 0); // Check if amount is numeric, for example, an error occurred when amount value = o (letter) instead 0 (number)
4585 if ($rounding == -1) {
4586 $curcode = $currency_code;
4587 if ($curcode === 'auto') {
4588 $curcode = $conf->currency;
4589 }
4590
4591 $max_decimals_unit = getDolGlobalInt('MAIN_MAX_DECIMALS_UNIT');
4592 $max_decimals_tot = getDolGlobalInt('MAIN_MAX_DECIMALS_TOT');
4593 if (getDolGlobalString('MULTICURRENCY_USE_LIMIT_BY_CURRENCY') && !empty($curcode)) {
4594 if (getDolGlobalString('MAIN_MAX_DECIMALS_UNIT_'.$curcode) !== '') {
4595 $max_decimals_unit = getDolGlobalInt('MAIN_MAX_DECIMALS_UNIT_'.$curcode);
4596 }
4597 if (getDolGlobalString('MAIN_MAX_DECIMALS_TOT_'.$curcode) !== '') {
4598 $max_decimals_tot = getDolGlobalInt('MAIN_MAX_DECIMALS_TOT_'.$curcode);
4599 }
4600 }
4601
4602 $rounding = min($max_decimals_unit, $max_decimals_tot);
4603 }
4604 $nbdecimal = $rounding;
4605
4606 if ($outlangs === 'none') {
4607 // Use international separators
4608 $dec = '.';
4609 $thousand = '';
4610 } else {
4611 // Output separators by default (french)
4612 $dec = ',';
4613 $thousand = ' ';
4614
4615 // If $outlangs not forced, we use use language
4616 if (!($outlangs instanceof Translate)) {
4617 $outlangs = $langs;
4618 }
4619
4620 if ($outlangs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
4621 $dec = $outlangs->transnoentitiesnoconv("SeparatorDecimal");
4622 }
4623 if ($outlangs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
4624 $thousand = $outlangs->transnoentitiesnoconv("SeparatorThousand");
4625 }
4626 if ($thousand == 'None') {
4627 $thousand = '';
4628 } elseif ($thousand == 'Space') {
4629 $thousand = ' ';
4630 }
4631 }
4632 //print "outlangs=".$outlangs->defaultlang." amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
4633
4634 //print "amount=".$amount."-";
4635 $amount = str_replace(',', '.', $amount); // should be useless
4636 //print $amount."-";
4637 $data = explode('.', $amount);
4638 $decpart = isset($data[1]) ? $data[1] : '';
4639 $decpart = preg_replace('/0+$/i', '', $decpart); // Remove 0 at end of decimal part
4640 //print "decpart=".$decpart."<br>";
4641 $end = '';
4642
4643 // We increase nbdecimal if there is more decimal than asked (to not loose information)
4644 if (dol_strlen($decpart) > $nbdecimal) {
4645 $nbdecimal = dol_strlen($decpart);
4646 }
4647
4648 $curcode = $currency_code;
4649 if ($curcode === 'auto') {
4650 $curcode = $conf->currency;
4651 }
4652
4653 $max_decimals_shown = getDolGlobalString('MAIN_MAX_DECIMALS_SHOWN');
4654 if (getDolGlobalString('MULTICURRENCY_USE_LIMIT_BY_CURRENCY') && !empty($curcode) && getDolGlobalString('MAIN_MAX_DECIMALS_SHOWN_'.$curcode) !== '') {
4655 $max_decimals_shown = getDolGlobalString('MAIN_MAX_DECIMALS_SHOWN_'.$curcode);
4656 }
4657
4658 // If nbdecimal is higher than max to show
4659 $nbdecimalmaxshown = (int) str_replace('...', '', $max_decimals_shown);
4660 if ($trunc && $nbdecimal > $nbdecimalmaxshown) {
4661 $nbdecimal = $nbdecimalmaxshown;
4662 if (preg_match('/\.\.\./i', $max_decimals_shown)) {
4663 // If output is truncated, we show ...
4664 $end = '...';
4665 }
4666 }
4667
4668 // If force rounding
4669 if ((string) $forcerounding != '-1' && (string) $forcerounding != '') {
4670 $max_decimals_unit = getDolGlobalInt('MAIN_MAX_DECIMALS_UNIT');
4671 $max_decimals_tot = getDolGlobalInt('MAIN_MAX_DECIMALS_TOT');
4672 if (getDolGlobalString('MULTICURRENCY_USE_LIMIT_BY_CURRENCY') && !empty($curcode)) {
4673 if (getDolGlobalString('MAIN_MAX_DECIMALS_UNIT_'.$curcode) !== '') {
4674 $max_decimals_unit = getDolGlobalInt('MAIN_MAX_DECIMALS_UNIT_'.$curcode);
4675 }
4676 if (getDolGlobalString('MAIN_MAX_DECIMALS_TOT_'.$curcode) !== '') {
4677 $max_decimals_tot = getDolGlobalInt('MAIN_MAX_DECIMALS_TOT_'.$curcode);
4678 }
4679 }
4680
4681 if ($forcerounding === 'MU' || $forcerounding === 'CU') {
4682 $nbdecimal = $max_decimals_unit;
4683 } elseif ($forcerounding === 'MT' || $forcerounding === 'CT') {
4684 $nbdecimal = $max_decimals_tot;
4685 } elseif ($forcerounding >= 0) {
4686 $nbdecimal = (int) $forcerounding;
4687 }
4688 }
4689
4690 // Format number
4691 $output = number_format((float) $amount, $nbdecimal, $dec, $thousand);
4692 // Add symbol of currency if requested
4693 $cursymbolbefore = $cursymbolafter = '';
4694 if ($currency_code && is_object($outlangs)) {
4695 if ($currency_code == 'auto') {
4696 $currency_code = $conf->currency;
4697 }
4698
4699 $listofcurrenciesbefore = array('AUD', 'CAD', 'CNY', 'COP', 'CLP', 'GBP', 'HKD', 'MXN', 'PEN', 'USD', 'CRC', 'ZAR');
4700 $listoflanguagesbefore = array('nl_NL');
4701 if (in_array($currency_code, $listofcurrenciesbefore) || in_array($outlangs->defaultlang, $listoflanguagesbefore)) {
4702 $cursymbolbefore .= $outlangs->getCurrencySymbol($currency_code);
4703 } else {
4704 $tmpcur = $outlangs->getCurrencySymbol($currency_code);
4705 $cursymbolafter .= ($tmpcur == $currency_code ? ' ' . $tmpcur : $tmpcur);
4706 }
4707 }
4708 if ($form) {
4709 $output = preg_replace('/\s/', '&nbsp;', $output);
4710 $output = $cursymbolbefore . $output . $end . ($cursymbolafter ? ' <span class="small">'.$cursymbolafter.'</span>' : '');
4711 $output = preg_replace('/\'/', '&#039;', $output);
4712 } else {
4713 $output = $cursymbolbefore . $output . $end . ($cursymbolafter ? ' '.$cursymbolafter : '');
4714 }
4715
4716 return $output;
4717}
4718
4746function price2num($amount, $rounding = '', $option = 0, $currencycode = '')
4747{
4748 global $langs;
4749
4750 // Clean parameters
4751 if (is_null($amount)) {
4752 $amount = '';
4753 }
4754
4755 // Round PHP function does not allow number like '1,234.56' nor '1.234,56' nor '1 234,56'
4756 // Numbers must be '1234.56'
4757 // Decimal delimiter for PHP and database SQL requests must be '.'
4758 $dec = ',';
4759 $thousand = ' ';
4760 if (is_null($langs)) { // $langs is not defined, we use english values.
4761 $dec = '.';
4762 $thousand = ',';
4763 } else {
4764 if ($langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
4765 $dec = $langs->transnoentitiesnoconv("SeparatorDecimal");
4766 }
4767 if ($langs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
4768 $thousand = $langs->transnoentitiesnoconv("SeparatorThousand");
4769 }
4770 }
4771 if ($thousand == 'None') {
4772 $thousand = '';
4773 } elseif ($thousand == 'Space') {
4774 $thousand = ' ';
4775 }
4776 //print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
4777
4778 // Convert value to universal number format (no thousand separator, '.' as decimal separator)
4779 if ($option != 1) { // If not a PHP number or unknown, we change or clean format
4780 //print "\n".'PP'.$amount.' - '.$dec.' - '.$thousand.' - '.intval($amount).'<br>';
4781 if (!is_numeric($amount)) {
4782 $amount = preg_replace('/[a-zA-Z\/\\\*\‍(\‍)<>\_]/', '', $amount);
4783 }
4784
4785 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
4786 $amount = str_replace($thousand, '', $amount);
4787 }
4788
4789 // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
4790 // to format defined by LC_NUMERIC after a calculation and we want source format to be like defined by Dolibarr setup.
4791 // So if number was already a good number, it is converted into local Dolibarr setup.
4792 if (is_numeric($amount)) {
4793 // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
4794 $temps = sprintf("%10.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
4795 $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
4796 $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
4797 $amount = number_format($amount, $nbofdec, $dec, $thousand);
4798 }
4799 //print "QQ".$amount."<br>\n";
4800
4801 // Now make replaceents (the main goal of function)
4802
4803 if ($thousand != ',' && $thousand != '.') {
4804 // Accept the two types of decimal points french users (i.e., using ' ' for thousands)
4805
4806 // REGEX: Find the integral and decimal parts.
4807 //
4808 // We require that the decimal point only appears once in $amount.
4809 // The regex `/^(?<int>[^,]*,|[^.]*\.)(?<dec>[^.,]*)$/u` can be broken down as follows:
4810 // - `(?<int>[^,]*,|[^.]*\.)` is any accepted sequence up to the last potential decimal point '.' or ',' and named `int`.
4811 // It covers two cases:
4812 // - `[^,]*,`: Any sequence of characters that is not ',' with ',' accepted as the decimal point (from start of string because of earlier `^`);
4813 // - `[^.]*\.`: Any sequence of characters that is not a '.' with '.' accepted as the decimal point (from start of string.
4814 // - `(?<dec>[^.,]*)`: The sequence after the character accepted as the decimal point, not including it.
4815 $matches = array();
4816 if (preg_match('/^(?<int>[^,]*,|[^.]*\.)(?<dec>[^.,]*)$/u', $amount, $matches)) {
4817 $intPart = $matches['int'];
4818 $decPart = $matches['dec'];
4819
4820 // Remove all commas and dots from intPart
4821 $intPart = str_replace(['.', ','], '', $intPart);
4822
4823 // Combine intPart and decPart with a dot
4824 $amount = $intPart . $dec . $decPart;
4825 }
4826 }
4827
4828 $amount = str_replace(' ', '', $amount); // To avoid spaces
4829 $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
4830 $amount = str_replace($dec, '.', $amount);
4831
4832 $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
4833 }
4834 //print ' XX'.$amount.' '.$rounding;
4835
4836 // Now, $amount is a real PHP float number. We make a rounding if required.
4837 if ($rounding) {
4838 $nbofdectoround = '';
4839 if ($rounding == 'MU') {
4840 if (getDolGlobalString('MULTICURRENCY_USE_LIMIT_BY_CURRENCY') && !empty($currencycode) && getDolGlobalString('MAIN_MAX_DECIMALS_UNIT_'.$currencycode) !== '') {
4841 $nbofdectoround = getDolGlobalInt('MAIN_MAX_DECIMALS_UNIT_'.$currencycode);
4842 } else {
4843 $nbofdectoround = getDolGlobalInt('MAIN_MAX_DECIMALS_UNIT'); // usually 5
4844 }
4845 } elseif ($rounding == 'MT') {
4846 if (getDolGlobalString('MULTICURRENCY_USE_LIMIT_BY_CURRENCY') && !empty($currencycode) && getDolGlobalString('MAIN_MAX_DECIMALS_TOT_'.$currencycode) !== '') {
4847 $nbofdectoround = getDolGlobalInt('MAIN_MAX_DECIMALS_TOT_'.$currencycode);
4848 } else {
4849 $nbofdectoround = getDolGlobalInt('MAIN_MAX_DECIMALS_TOT'); // usually 2 or 3
4850 }
4851 } elseif ($rounding == 'MS') {
4852 $nbofdectoround = getDolGlobalInt('MAIN_MAX_DECIMALS_STOCK', 5);
4853 } elseif ($rounding == 'CU' || preg_match('/^CU_([a-zA-Z]+)$/', (string) $rounding, $regscu)) {
4854 $cur = !empty($regscu[1]) ? $regscu[1] : $currencycode;
4855 if (getDolGlobalString('MULTICURRENCY_USE_LIMIT_BY_CURRENCY') && !empty($cur) && getDolGlobalString('MAIN_MAX_DECIMALS_UNIT_'.$cur) !== '') {
4856 $nbofdectoround = getDolGlobalInt('MAIN_MAX_DECIMALS_UNIT_'.$cur);
4857 } else {
4858 $nbofdectoround = getDolGlobalInt('MAIN_MAX_DECIMALS_CURRENCY_UNIT', getDolGlobalInt('MAIN_MAX_DECIMALS_UNIT'));
4859 }
4860 } elseif ($rounding == 'CT' || preg_match('/^CT_([a-zA-Z]+)$/', (string) $rounding, $regsct)) {
4861 $cur = !empty($regsct[1]) ? $regsct[1] : $currencycode;
4862 if (getDolGlobalString('MULTICURRENCY_USE_LIMIT_BY_CURRENCY') && !empty($cur) && getDolGlobalString('MAIN_MAX_DECIMALS_TOT_'.$cur) !== '') {
4863 $nbofdectoround = getDolGlobalInt('MAIN_MAX_DECIMALS_TOT_'.$cur);
4864 } else {
4865 $nbofdectoround = getDolGlobalInt('MAIN_MAX_DECIMALS_CURRENCY_TOT', getDolGlobalInt('MAIN_MAX_DECIMALS_TOT'));
4866 }
4867 } elseif ($rounding == 'CR' || preg_match('/^CR_([a-zA-Z]+)$/', (string) $rounding, $regscr)) {
4868 $cur = !empty($regscr[1]) ? $regscr[1] : $currencycode;
4869 if (empty($cur) && (string) getDolGlobalString('MULTICURRENCY_USE_LIMIT_BY_CURRENCY')) {
4870 $cur = getDolCurrency();
4871 }
4872 $rounding_const = 'MAIN_MAX_DECIMALS_CURRENCY_RATE' . (!empty($cur) ? '_' . $cur : '');
4873 $nbofdectoround = getDolGlobalInt($rounding_const, getDolGlobalInt('MAIN_MAX_DECIMALS_CURRENCY_RATE', 8));
4874 } elseif (is_numeric($rounding)) {
4875 $nbofdectoround = (int) $rounding;
4876 }
4877
4878 //print " RR".$amount.' - '.$nbofdectoround.'<br>';
4879 if (dol_strlen($nbofdectoround)) {
4880 $amount = round(is_string($amount) ? (float) $amount : $amount, $nbofdectoround); // $nbofdectoround can be 0.
4881 } else {
4882 return 'ErrorBadParameterProvidedToFunction';
4883 }
4884 //print ' SS'.$amount.' - '.$nbofdec.' - '.$dec.' - '.$thousand.' - '.$nbofdectoround.'<br>';
4885
4886 // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
4887 // to format defined by LC_NUMERIC after a calculation and we want source format to be defined by Dolibarr setup.
4888 if (is_numeric($amount)) {
4889 // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
4890 $temps = sprintf("%10.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
4891 $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
4892 $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
4893 $amount = number_format($amount, min($nbofdec, $nbofdectoround), $dec, $thousand); // Convert amount to format with dolibarr dec and thousand
4894 }
4895 //print "TT".$amount.'<br>';
4896
4897 // Always make replace because each math function (like round) replace
4898 // with local values and we want a number that has a SQL string format x.y
4899 if ($thousand != ',' && $thousand != '.') {
4900 $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
4901 }
4902
4903 $amount = str_replace(' ', '', $amount); // To avoid spaces
4904 $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
4905 $amount = str_replace($dec, '.', $amount);
4906
4907 $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
4908 }
4909
4910 return $amount;
4911}
4912
4913
4926function get_localtax($vatrate, $local, $thirdparty_buyer = null, $thirdparty_seller = null, $vatnpr = 0)
4927{
4928 global $db, $conf, $mysoc;
4929
4930 if (empty($thirdparty_seller) || !is_object($thirdparty_seller)) {
4931 $thirdparty_seller = $mysoc;
4932 }
4933 // $mysoc may be null when called from a page with NOREQUIRESOC (like viewimage.php). With no seller, there is no localtax.
4934 if (!is_object($thirdparty_seller)) {
4935 return 0;
4936 }
4937
4938 dol_syslog(
4939 "get_localtax tva=" . $vatrate . " local=" . $local
4940 ." thirdparty_buyer id=" . (is_object($thirdparty_buyer) ? $thirdparty_buyer->id : '') . "/country_code=" . (is_object($thirdparty_buyer) ? $thirdparty_buyer->country_code : '')
4941 ." thirdparty_seller id=" . $thirdparty_seller->id . "/country_code=" . $thirdparty_seller->country_code
4942 ." thirdparty_seller localtax1_assuj=" . $thirdparty_seller->localtax1_assuj . " thirdparty_seller localtax2_assuj=" . $thirdparty_seller->localtax2_assuj
4943 );
4944
4945 $vatratecleaned = $vatrate;
4946 $reg = array();
4947 if (preg_match('/^(.*)\s*\‍((.*)\‍)$/', (string) $vatrate, $reg)) { // If vat is "xx (yy)"
4948 $vatratecleaned = trim($reg[1]);
4949 $vatratecode = $reg[2];
4950 }
4951
4952 /*if ($thirdparty_buyer->country_code != $thirdparty_seller->country_code)
4953 {
4954 return 0;
4955 }*/
4956
4957 // Some test to guess with no need to make database access
4958 if ($mysoc->country_code == 'ES') { // For spain localtaxes 1 and 2, tax is qualified if buyer use local tax
4959 if ($local == 1) {
4960 if (!$mysoc->localtax1_assuj || (string) $vatratecleaned == "0") {
4961 return 0;
4962 }
4963 if ($thirdparty_seller->id == $mysoc->id) {
4964 if (!$thirdparty_buyer->localtax1_assuj) {
4965 return 0;
4966 }
4967 } else {
4968 if (!$thirdparty_seller->localtax1_assuj) {
4969 return 0;
4970 }
4971 }
4972 }
4973
4974 if ($local == 2) {
4975 //if (! $mysoc->localtax2_assuj || (string) $vatratecleaned == "0") return 0;
4976 if (!$mysoc->localtax2_assuj) {
4977 return 0; // If main vat is 0, IRPF may be different than 0.
4978 }
4979 if ($thirdparty_seller->id == $mysoc->id) {
4980 if (!$thirdparty_buyer->localtax2_assuj) {
4981 return 0;
4982 }
4983 } else {
4984 if (!$thirdparty_seller->localtax2_assuj) {
4985 return 0;
4986 }
4987 }
4988 }
4989 } else {
4990 if ($local == 1 && !$thirdparty_seller->localtax1_assuj) {
4991 return 0;
4992 }
4993 if ($local == 2 && !$thirdparty_seller->localtax2_assuj) {
4994 return 0;
4995 }
4996 }
4997
4998 // For some country MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY is forced to on.
4999 if (in_array($mysoc->country_code, array('ES'))) {
5000 $conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY = 1;
5001 }
5002
5003 // Search local taxes
5004 if (getDolGlobalString('MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY')) {
5005 if ($local == 1) {
5006 if ($thirdparty_seller != $mysoc) {
5007 if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
5008 return $thirdparty_seller->localtax1_value;
5009 }
5010 } else { // i am the seller
5011 if (!isOnlyOneLocalTax($local)) { // TODO If seller is me, why not always returning this, even if there is only one locatax vat.
5012 return getDolGlobalString('MAIN_INFO_VALUE_LOCALTAX1');
5013 }
5014 }
5015 }
5016 if ($local == 2) {
5017 if ($thirdparty_seller != $mysoc) {
5018 if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
5019 // TODO We should also return value defined on thirdparty only if defined
5020 return $thirdparty_seller->localtax2_value;
5021 }
5022 } else { // i am the seller
5023 if (in_array($mysoc->country_code, array('ES'))) {
5024 return $thirdparty_buyer->localtax2_value;
5025 } else {
5026 return getDolGlobalString('MAIN_INFO_VALUE_LOCALTAX2');
5027 }
5028 }
5029 }
5030 }
5031
5032 // By default, search value of local tax on line of common tax
5033 $sql = "SELECT t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
5034 $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t, " . MAIN_DB_PREFIX . "c_country as c";
5035 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '" . $db->escape($thirdparty_seller->country_code) . "'";
5036 $sql .= " AND t.taux = " . ((float) $vatratecleaned) . " AND t.active = 1";
5037 $sql .= " AND t.entity IN (" . getEntity('c_tva') . ")";
5038 if (!empty($vatratecode)) {
5039 $sql .= " AND t.code ='" . $db->escape($vatratecode) . "'"; // If we have the code, we use it in priority
5040 } else {
5041 $sql .= " AND t.recuperableonly = '" . $db->escape((string) $vatnpr) . "'";
5042 }
5043
5044 $resql = $db->query($sql);
5045
5046 if ($resql) {
5047 $obj = $db->fetch_object($resql);
5048 if ($obj) {
5049 if ($local == 1) {
5050 return $obj->localtax1;
5051 } elseif ($local == 2) {
5052 return $obj->localtax2;
5053 }
5054 }
5055 }
5056
5057 return 0;
5058}
5059
5060
5069function isOnlyOneLocalTax($local)
5070{
5071 $tax = get_localtax_by_third($local);
5072
5073 $valors = explode(":", $tax);
5074
5075 if (count($valors) > 1) {
5076 return false;
5077 } else {
5078 return true;
5079 }
5080}
5081
5088function get_localtax_by_third($local)
5089{
5090 global $db, $mysoc;
5091
5092 $sql = " SELECT t.localtax" . ((int) $local) . " as localtax";
5093 $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t INNER JOIN " . MAIN_DB_PREFIX . "c_country as c ON c.rowid = t.fk_pays";
5094 $sql .= " WHERE c.code = '" . $db->escape($mysoc->country_code) . "' AND t.active = 1 AND t.entity IN (" . getEntity('c_tva') . ") AND t.taux = (";
5095 $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";
5096 $sql .= " WHERE c.code = '" . $db->escape($mysoc->country_code) . "' AND t.entity IN (" . getEntity('c_tva') . ") AND tt.active = 1)";
5097 $sql .= " AND t.localtax" . ((int) $local) . "_type <> '0'";
5098 $sql .= " ORDER BY t.rowid DESC";
5099
5100 $resql = $db->query($sql);
5101 if ($resql) {
5102 $obj = $db->fetch_object($resql);
5103 if ($obj) {
5104 return $obj->localtax;
5105 } else {
5106 return '0';
5107 }
5108 }
5109
5110 return 'Error';
5111}
5112
5113
5125function getTaxesFromId($vatrate, $buyer = null, $seller = null, $firstparamisid = 1)
5126{
5127 global $db;
5128
5129 dol_syslog("getTaxesFromId vat id or rate = " . $vatrate);
5130
5131 // Search local taxes
5132 $sql = "SELECT t.rowid, t.code, t.taux as rate, t.recuperableonly as npr, t.accountancy_code_sell, t.accountancy_code_buy,";
5133 $sql .= " t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type";
5134 $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t";
5135 if ($firstparamisid) {
5136 $sql .= " WHERE t.rowid = " . (int) $vatrate;
5137 } else {
5138 $vatratecleaned = $vatrate;
5139 $vatratecode = '';
5140 $reg = array();
5141 if (preg_match('/^(.*)\s*\‍((.*)\‍)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
5142 $vatratecleaned = $reg[1];
5143 $vatratecode = $reg[2];
5144 }
5145
5146 $sql .= ", " . MAIN_DB_PREFIX . "c_country as c";
5147 /*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 ??
5148 else $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";*/
5149 $sql .= " WHERE t.fk_pays = c.rowid";
5150 if (getDolGlobalString('SERVICE_ARE_ECOMMERCE_200238EC')) {
5151 $sql .= " AND c.code = '" . $db->escape($buyer->country_code) . "'";
5152 } else {
5153 $sql .= " AND c.code = '" . $db->escape($seller->country_code) . "'";
5154 }
5155 $sql .= " AND t.taux = " . ((float) $vatratecleaned) . " AND t.active = 1";
5156 $sql .= " AND t.entity IN (" . getEntity('c_tva') . ")";
5157 if ($vatratecode) {
5158 $sql .= " AND t.code = '" . $db->escape($vatratecode) . "'";
5159 }
5160 }
5161
5162 $resql = $db->query($sql);
5163 if ($resql) {
5164 $obj = $db->fetch_object($resql);
5165 if ($obj) {
5166 return array(
5167 'rowid' => $obj->rowid,
5168 'code' => $obj->code,
5169 'rate' => $obj->rate,
5170 'localtax1' => $obj->localtax1,
5171 'localtax1_type' => $obj->localtax1_type,
5172 'localtax2' => $obj->localtax2,
5173 'localtax2_type' => $obj->localtax2_type,
5174 'npr' => $obj->npr,
5175 'accountancy_code_sell' => $obj->accountancy_code_sell,
5176 'accountancy_code_buy' => $obj->accountancy_code_buy
5177 );
5178 } else {
5179 return array();
5180 }
5181 } else {
5182 dol_print_error($db);
5183 }
5184
5185 return array();
5186}
5187
5204function getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid = 0)
5205{
5206 global $db, $mysoc;
5207
5208 dol_syslog("getLocalTaxesFromRate vatrate=" . $vatrate . " local=" . $local);
5209
5210 // Search local taxes
5211 $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";
5212 $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t";
5213 if ($firstparamisid) {
5214 $sql .= " WHERE t.rowid = " . (int) $vatrate;
5215 } else {
5216 $vatratecleaned = $vatrate;
5217 $vatratecode = '';
5218 $reg = array();
5219 if (preg_match('/^(.*)\s*\‍((.*)\‍)$/', $vatrate, $reg)) { // If vat is "x.x (yy)"
5220 $vatratecleaned = $reg[1];
5221 $vatratecode = $reg[2];
5222 }
5223
5224 $sql .= ", " . MAIN_DB_PREFIX . "c_country as c";
5225 if (!empty($mysoc) && $mysoc->country_code == 'ES') {
5226 $countrycodetouse = ((empty($buyer) || empty($buyer->country_code)) ? $mysoc->country_code : $buyer->country_code);
5227 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '" . $db->escape($countrycodetouse) . "'"; // local tax in spain use the buyer country ??
5228 } else {
5229 $countrycodetouse = ((empty($seller) || empty($seller->country_code)) ? $mysoc->country_code : $seller->country_code);
5230 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '" . $db->escape($countrycodetouse) . "'";
5231 }
5232 $sql .= " AND t.taux = " . ((float) $vatratecleaned) . " AND t.active = 1";
5233 if ($vatratecode) {
5234 $sql .= " AND t.code = '" . $db->escape($vatratecode) . "'";
5235 }
5236 }
5237
5238 $resql = $db->query($sql);
5239 if ($resql) {
5240 $obj = $db->fetch_object($resql);
5241
5242 if ($obj) {
5243 $vateratestring = $obj->rate . ($obj->code ? ' (' . $obj->code . ')' : '');
5244
5245 if ($local == 1) {
5246 return array($obj->localtax1_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
5247 } elseif ($local == 2) {
5248 return array($obj->localtax2_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
5249 } else {
5250 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);
5251 }
5252 }
5253 }
5254
5255 return array();
5256}
5257
5268function get_product_vat_for_country($idprod, $thirdpartytouseforcountry, $idprodfournprice = 0)
5269{
5270 global $db, $mysoc;
5271
5272 require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
5273
5274 $ret = 0;
5275 $found = 0;
5276
5277 if ($idprod > 0) {
5278 // Load product
5279 $product = new Product($db);
5280 $product->fetch($idprod);
5281
5282 if (($mysoc->country_code == $thirdpartytouseforcountry->country_code)
5283 || (in_array($mysoc->country_code, array('FR', 'MC')) && in_array($thirdpartytouseforcountry->country_code, array('FR', 'MC')))
5284 || (in_array($mysoc->country_code, array('MQ', 'GP')) && in_array($thirdpartytouseforcountry->country_code, array('MQ', 'GP')))
5285 ) {
5286 // If country of thirdparty to consider is ours
5287 if ($idprodfournprice > 0) { // We want vat for product for a "supplier" object
5288 $result = $product->get_buyprice($idprodfournprice, 0, 0, '');
5289 if ($result > 0) {
5290 $ret = $product->vatrate_supplier;
5291 if ($product->default_vat_code_supplier) {
5292 $ret .= ' (' . $product->default_vat_code_supplier . ')';
5293 }
5294 $found = 1;
5295 }
5296 }
5297 if (!$found) {
5298 $ret = $product->tva_tx; // Default sales vat of product
5299 if ($product->default_vat_code) {
5300 $ret .= ' (' . $product->default_vat_code . ')';
5301 }
5302 $found = 1;
5303 }
5304 } else {
5305 // TODO Read default product vat according to product and an other countrycode.
5306 // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
5307 }
5308 }
5309
5310 if (!$found) {
5311 if (!getDolGlobalString('MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS')) {
5312 // 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).
5313 $sql = "SELECT t.taux as vat_rate, t.code as default_vat_code";
5314 $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t, " . MAIN_DB_PREFIX . "c_country as c";
5315 $sql .= " WHERE t.active = 1 AND t.fk_pays = c.rowid AND c.code = '" . $db->escape($thirdpartytouseforcountry->country_code) . "'";
5316 $sql .= " AND t.entity IN (" . getEntity('c_tva') . ")";
5317 $sql .= " ORDER BY t.use_default DESC, t.taux DESC, t.code ASC, t.recuperableonly ASC";
5318 $sql .= $db->plimit(1);
5319
5320 $resql = $db->query($sql);
5321 if ($resql) {
5322 $obj = $db->fetch_object($resql);
5323 if ($obj) {
5324 $ret = $obj->vat_rate;
5325 if ($obj->default_vat_code) {
5326 $ret .= ' (' . $obj->default_vat_code . ')';
5327 }
5328 }
5329 $db->free($resql);
5330 } else {
5331 dol_print_error($db);
5332 }
5333 } else {
5334 // Forced value if autodetect fails. MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS can be
5335 // '1.23'
5336 // or '1.23 (CODE)'
5337 $defaulttx = '';
5338 if (getDolGlobalString('MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS') != 'none') {
5339 $defaulttx = getDolGlobalString('MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS');
5340 }
5341 /*if (preg_match('/\‍((.*)\‍)/', $defaulttx, $reg)) {
5342 $defaultcode = $reg[1];
5343 $defaulttx = preg_replace('/\s*\‍(.*\‍)/', '', $defaulttx);
5344 }*/
5345
5346 $ret = $defaulttx;
5347 }
5348 }
5349
5350 dol_syslog("get_product_vat_for_country: ret=" . $ret);
5351
5352 return $ret;
5353}
5354
5364function get_product_localtax_for_country($idprod, $local, $thirdpartytouseforcountry)
5365{
5366 global $db, $mysoc;
5367
5368 if (!class_exists('Product')) {
5369 require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
5370 }
5371
5372 $ret = 0;
5373 $found = 0;
5374
5375 if ($idprod > 0) {
5376 // Load product
5377 $product = new Product($db);
5378 $result = $product->fetch($idprod);
5379
5380 if ($mysoc->country_code == $thirdpartytouseforcountry->country_code) { // If selling country is ours
5381 /* Not defined yet, so we don't use this
5382 if ($local==1) $ret=$product->localtax1_tx;
5383 elseif ($local==2) $ret=$product->localtax2_tx;
5384 $found=1;
5385 */
5386 } else {
5387 // TODO Read default product vat according to product and another countrycode.
5388 // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
5389 }
5390 }
5391
5392 if (!$found) {
5393 // If vat of product for the country not found or not defined, we return higher vat of country.
5394 $sql = "SELECT taux as vat_rate, localtax1, localtax2";
5395 $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t, " . MAIN_DB_PREFIX . "c_country as c";
5396 $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='" . $db->escape($thirdpartytouseforcountry->country_code) . "'";
5397 $sql .= " AND t.entity IN (" . getEntity('c_tva') . ")";
5398 $sql .= " ORDER BY t.taux DESC, t.recuperableonly ASC";
5399 $sql .= $db->plimit(1);
5400
5401 $resql = $db->query($sql);
5402 if ($resql) {
5403 $obj = $db->fetch_object($resql);
5404 if ($obj) {
5405 if ($local == 1) {
5406 $ret = $obj->localtax1;
5407 } elseif ($local == 2) {
5408 $ret = $obj->localtax2;
5409 }
5410 }
5411 } else {
5412 dol_print_error($db);
5413 }
5414 }
5415
5416 dol_syslog("get_product_localtax_for_country: ret=" . $ret);
5417 return $ret;
5418}
5419
5438function get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
5439{
5440 global $mysoc, $db, $hookmanager;
5441
5442 require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
5443
5444 // Note: possible values for tva_assuj are 0/1 or franchise/reel
5445 $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;
5446
5447 if (empty($thirdparty_seller->country_code)) {
5448 $thirdparty_seller->country_code = $mysoc->country_code;
5449 }
5450 $seller_country_code = $thirdparty_seller->country_code;
5451 $seller_in_cee = isInEEC($thirdparty_seller);
5452
5453 if (empty($thirdparty_buyer->country_code)) {
5454 $thirdparty_buyer->country_code = $mysoc->country_code;
5455 }
5456 $buyer_country_code = $thirdparty_buyer->country_code;
5457 $buyer_in_cee = isInEEC($thirdparty_buyer);
5458
5459 dol_syslog(
5460 "get_default_tva: seller use vat=" . $seller_use_vat . ", seller country=" . $seller_country_code . ", seller in cee=" . ((string) (int) $seller_in_cee)
5461 .", 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)
5462 .", idprod=" . $idprod . ", idprodfournprice=" . $idprodfournprice . ", SERVICE_ARE_ECOMMERCE_200238EC=" . getDolGlobalString('SERVICE_ARE_ECOMMERCE_200238EC')
5463 );
5464
5465 $vatvalue = 0;
5466 $vatrule = '';
5467
5468 // 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)
5469 // we use the buyer VAT.
5470 if (getDolGlobalString('SERVICE_ARE_ECOMMERCE_200238EC')) {
5471 if ($seller_in_cee && $buyer_in_cee) {
5472 $isacompany = $thirdparty_buyer->isACompany();
5473 if ($isacompany && !getDolGlobalString('MAIN_USE_VAT_ZERO_FOR_COMPANIES_IN_EEC_EVEN_IF_VAT_ID_UNKNOWN')) {
5474 require_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php';
5475 if (!isValidVATID($thirdparty_buyer)) {
5476 $isacompany = 0;
5477 }
5478 }
5479
5480 if (!$isacompany) {
5481 $vatvalue = get_product_vat_for_country($idprod, $thirdparty_buyer, $idprodfournprice);
5482 $vatrule = 'VATRULE 0';
5483 }
5484 }
5485 }
5486
5487 // If seller does not use VAT, default VAT is 0. End of rule.
5488 if (empty($vatrule) && !$seller_use_vat) {
5489 //print 'VATRULE 1';
5490 // TODO get the VAT Code of exemption asked into setup if country isInEEC (from an array list of possible
5491 // values like VATEX-EU-132-*, VATEX-FR-FRANCHISE, VATEX-EU-AE...
5492 // When we had recorded it, we also added a corresponding entry into table of vat code if it does not exists yet.
5493 // Here we test if entry for the VAT exemption code exists in llx_vat, we can return '0 (VATEX-EU-132-xx)'
5494 // If not, we add it and we return '0 (VATEX-EU-132-xx)'
5495 $vatvalue = 0;
5496 $vatrule = 'VATRULE 1';
5497 }
5498
5499 // 'VATRULE 2' - Force VAT if a buyer department is defined on vat rates dictionary
5500 if (empty($vatrule) && !empty($thirdparty_buyer->state_id)) {
5501 $sql = "SELECT d.rowid, t.taux as vat_default_rate, t.code as vat_default_code ";
5502 $sql .= " FROM " . $db->prefix() . "c_tva as t";
5503 $sql .= " INNER JOIN " . $db->prefix() . "c_departements as d ON t.fk_department_buyer = d.rowid";
5504 $sql .= " WHERE d.rowid = " . ((int) $thirdparty_buyer->state_id);
5505 $sql .= " AND t.active > 0";
5506 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
5507 $sql .= " ORDER BY t.use_default DESC, t.taux DESC, t.code ASC, t.recuperableonly ASC";
5508
5509 $res = $db->query($sql);
5510 if ($res) {
5511 if ($db->num_rows($res)) {
5512 $obj = $db->fetch_object($res);
5513
5514 $vatvalue = $obj->vat_default_rate . ' (' . $obj->vat_default_code . ')';
5515 $vatrule = 'VATRULE 2';
5516 }
5517 $db->free($res);
5518 }
5519 }
5520
5521 // If the (seller country = buyer country) then the default VAT = VAT of the product sold. End of rule.
5522 if (empty($vatrule) && (
5523 ($seller_country_code == $buyer_country_code)
5524 || (in_array($seller_country_code, array('FR', 'MC')) && in_array($buyer_country_code, array('FR', 'MC')))
5525 || (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.
5526 )) { // Warning ->country_code not always defined
5527 //print 'VATRULE 3';
5528 $tmpvat = get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
5529
5530 if ($seller_country_code == 'IN' && getDolGlobalString('MAIN_SALETAX_AUTOSWITCH_I_CS_FOR_INDIA')) {
5531 // Special case for india.
5532 //print 'VATRULE 3b';
5533 $reg = array();
5534 if (preg_match('/C+S-(\d+)/', $tmpvat, $reg) && $thirdparty_seller->state_id != $thirdparty_buyer->state_id) {
5535 // we must revert the C+S into I
5536 $tmpvat = str_replace("C+S", "I", $tmpvat);
5537 } elseif (preg_match('/I-(\d+)/', $tmpvat, $reg) && $thirdparty_seller->state_id == $thirdparty_buyer->state_id) {
5538 // we must revert the I into C+S
5539 $tmpvat = str_replace("I", "C+S", $tmpvat);
5540 }
5541 }
5542
5543 $vatvalue = $tmpvat;
5544 $vatrule = 'VATRULE 3b';
5545 }
5546
5547 // 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.
5548 // 'VATRULE 4' - Not supported
5549
5550 // If (seller and buyer in the European Community) and (buyer = individual) then VAT by default = VAT of the product sold. End of rule
5551 // If (seller and buyer in European Community) and (buyer = company) then VAT by default=0. End of rule
5552 if (empty($vatrule) && ($seller_in_cee && $buyer_in_cee)) {
5553 $isacompany = $thirdparty_buyer->isACompany();
5554 if ($isacompany && !getDolGlobalString('MAIN_USE_VAT_ZERO_FOR_COMPANIES_IN_EEC_EVEN_IF_VAT_ID_UNKNOWN')) {
5555 require_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php';
5556 if (!isValidVATID($thirdparty_buyer)) {
5557 $isacompany = 0;
5558 }
5559 }
5560
5561 if (!$isacompany) {
5562 //print 'VATRULE 5';
5563 $vatvalue = get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
5564 $vatrule = 'VATRULE 5';
5565 } else {
5566 //print 'VATRULE 6';
5567 // TODO This is the case of VAT exemption 'VATEX-EU-IC'
5568 // If entry for the VAT exemption code exists in llx_vat, we can return '0 (VATEX-EU-IC)'
5569 // If not, we add it and we return '0 (VATEX-EU-IC)'
5570 $vatvalue = 0;
5571 $vatrule = 'VATRULE 6';
5572 }
5573 }
5574
5575 // 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
5576 // 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
5577 if (empty($vatrule) && getDolGlobalString('MAIN_USE_VAT_OF_PRODUCT_FOR_INDIVIDUAL_CUSTOMER_OUT_OF_EEC') && empty($buyer_in_cee)) {
5578 $isacompany = $thirdparty_buyer->isACompany();
5579 if (!$isacompany) {
5580 $vatvalue = get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
5581 $vatrule = 'VATRULE extra';
5582 //print 'VATRULE extra';
5583 }
5584 }
5585
5586 // Otherwise the VAT proposed by default=0. End of rule.
5587 // Rem: This means that at least one of the 2 is outside the European Community and the country differs
5588 //print 'VATRULE 7';
5589 // TODO This is the case of VAT exemption 'VATEX-EU-G'
5590 // If entry for the VAT exemption code exists in llx_vat, we can return '0 (VATEX-xxx)'
5591 // If not, we add it and we return '0 (VATEX-xxx)'
5592
5593 // Allow an external module to bypass the calculation of prices
5594 $parameters = array('vatvalue' => $vatvalue, 'vatrule' => $vatrule);
5595 $tmpobject = null;
5596 $tmpaction = '';
5597 // @phan-suppress-next-line PhanPluginConstantVariableNull
5598 $reshook = $hookmanager->executeHooks('get_default_tva', $parameters, $tmpobject, $tmpaction); // @phan-suppress-current-line PhanPluginConstantVariableNull
5599 if ($reshook > 0 && !empty($hookmanager->resArray['vatvalue'])) {
5600 $vatvalue = $hookmanager->resArray['vatvalue'];
5601 $vatrule = $hookmanager->resArray['vatrule']; // For information
5602 }
5603
5604 return $vatvalue;
5605}
5606
5607
5618function get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
5619{
5620 global $db;
5621
5622 if ($idprodfournprice > 0) {
5623 if (!class_exists('ProductFournisseur')) {
5624 require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.product.class.php';
5625 }
5626 $prodprice = new ProductFournisseur($db);
5627 $prodprice->fetch_product_fournisseur_price($idprodfournprice);
5628 return $prodprice->fourn_tva_npr;
5629 } elseif ($idprod > 0) {
5630 if (!class_exists('Product')) {
5631 require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
5632 }
5633 $prod = new Product($db);
5634 $prod->fetch($idprod);
5635 return $prod->tva_npr;
5636 }
5637
5638 return 0;
5639}
5640
5654function get_default_localtax($thirdparty_seller, $thirdparty_buyer, $local, $idprod = 0)
5655{
5656 global $mysoc;
5657
5658 if (!is_object($thirdparty_seller)) {
5659 return -1;
5660 }
5661 if (!is_object($thirdparty_buyer)) {
5662 return -1;
5663 }
5664
5665 if (empty($thirdparty_seller->country_code)) {
5666 $thirdparty_seller->country_code = $mysoc->country_code;
5667 }
5668 $seller_country_code = $thirdparty_seller->country_code;
5669 //$seller_in_cee = isInEEC($thirdparty_seller);
5670
5671 if (empty($thirdparty_buyer->country_code)) {
5672 $thirdparty_buyer->country_code = $mysoc->country_code;
5673 }
5674 $buyer_country_code = $thirdparty_buyer->country_code;
5675 //$buyer_in_cee = isInEEC($thirdparty_buyer);
5676
5677 if ($local == 1) { // Localtax 1
5678 if ($mysoc->country_code == 'ES') {
5679 if (is_numeric($thirdparty_buyer->localtax1_assuj) && !$thirdparty_buyer->localtax1_assuj) {
5680 return 0;
5681 }
5682 } else {
5683 // Si vendeur non assujeti a Localtax1, localtax1 par default=0
5684 if (is_numeric($thirdparty_seller->localtax1_assuj) && !$thirdparty_seller->localtax1_assuj) {
5685 return 0;
5686 }
5687 if (!is_numeric($thirdparty_seller->localtax1_assuj) && $thirdparty_seller->localtax1_assuj == 'localtax1off') {
5688 return 0;
5689 }
5690 }
5691 } elseif ($local == 2) { //I Localtax 2
5692 // Si vendeur non assujeti a Localtax2, localtax2 par default=0
5693 if (is_numeric($thirdparty_seller->localtax2_assuj) && !$thirdparty_seller->localtax2_assuj) {
5694 return 0;
5695 }
5696 if (!is_numeric($thirdparty_seller->localtax2_assuj) && $thirdparty_seller->localtax2_assuj == 'localtax2off') {
5697 return 0;
5698 }
5699 }
5700
5701 if ($seller_country_code == $buyer_country_code) {
5702 return get_product_localtax_for_country($idprod, $local, $thirdparty_seller);
5703 }
5704
5705 return 0;
5706}
5707
5708
5727function get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart = '')
5728{
5729 if (empty($modulepart) && is_object($object)) {
5730 if (!empty($object->module)) {
5731 $modulepart = $object->module;
5732 } elseif (!empty($object->element)) {
5733 $modulepart = $object->element;
5734 }
5735 }
5736
5737 $path = '';
5738
5739 // Define $arrayforoldpath that is module path using a hierarchy on more than 1 level.
5740 $arrayforoldpath = array('cheque' => 2, 'category' => 2, 'supplier_invoice' => 2, 'invoice_supplier' => 2, 'mailing' => 2, 'supplier_payment' => 2);
5741 if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
5742 $arrayforoldpath['product'] = 2;
5743 }
5744
5745 if (empty($level) && array_key_exists($modulepart, $arrayforoldpath)) {
5746 $level = $arrayforoldpath[$modulepart];
5747 }
5748 if (!empty($level) && array_key_exists($modulepart, $arrayforoldpath)) {
5749 // This part should be removed once all code is using "get_exdir" to forge path, with parameter $object and $modulepart provided.
5750 if (empty($num) && is_object($object)) {
5751 $num = ((int) $object->id);
5752 }
5753 if (empty($alpha)) {
5754 $num = preg_replace('/([^0-9])/i', '', $num);
5755 } else {
5756 $num = preg_replace('/^.*\-/i', '', $num);
5757 }
5758 $num = substr("000" . $num, -$level);
5759 if ($level == 1) {
5760 $path = substr($num, 0, 1);
5761 }
5762 if ($level == 2) {
5763 $path = substr($num, 1, 1) . '/' . substr($num, 0, 1);
5764 }
5765 if ($level == 3) {
5766 $path = substr($num, 2, 1) . '/' . substr($num, 1, 1) . '/' . substr($num, 0, 1);
5767 }
5768 } else {
5769 // We will enhance here a common way of forging path for document storage.
5770 // In a future, we may distribute directories on several levels depending on setup and object.
5771 // Here, $object->id, $object->ref and $modulepart are required.
5772 if (in_array($modulepart, array('societe', 'thirdparty')) && $object instanceof Societe) {
5773 // 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
5774 $path = dol_sanitizeFileName((string) $object->id);
5775 } else {
5776 $path = dol_sanitizeFileName(empty($object->ref) ? (string) ((is_object($object) && property_exists($object, 'id')) ? ((int) $object->id) : '') : $object->ref);
5777 }
5778 }
5779
5780 if (empty($withoutslash) && !empty($path)) {
5781 $path .= '/';
5782 }
5783
5784 return $path;
5785}
5786
5795function dol_mkdir($dir, $dataroot = '', $newmask = '')
5796{
5797 dol_syslog("functions.lib::dol_mkdir: dir=" . $dir, LOG_INFO);
5798
5799 $dir = dol_sanitizePathName($dir, '_', 0);
5800
5801 $dir_osencoded = dol_osencode($dir);
5802 if (@is_dir($dir_osencoded)) {
5803 return 0;
5804 }
5805
5806 $nberr = 0;
5807 $nbcreated = 0;
5808
5809 $ccdir = '';
5810 if (!empty($dataroot)) {
5811 // Remove data root from loop
5812 $dir = str_replace($dataroot . '/', '', $dir);
5813 $ccdir = $dataroot . '/';
5814 }
5815
5816 $cdir = explode("/", $dir);
5817 $num = count($cdir);
5818 for ($i = 0; $i < $num; $i++) {
5819 if ($i > 0) {
5820 $ccdir .= '/' . $cdir[$i];
5821 } else {
5822 $ccdir .= $cdir[$i];
5823 }
5824 $regs = array();
5825 if (preg_match("/^.:$/", $ccdir, $regs)) {
5826 continue; // If the Windows path is incomplete, continue with next directory
5827 }
5828
5829 // Attention, is_dir() can fail event if the directory exists
5830 // (i.e. according the open_basedir configuration)
5831 if ($ccdir) {
5832 $ccdir_osencoded = dol_osencode($ccdir);
5833 if (!@is_dir($ccdir_osencoded)) {
5834 dol_syslog("functions.lib::dol_mkdir: Directory '" . $ccdir . "' is not found (does not exists or is outside open_basedir PHP setting).", LOG_DEBUG);
5835
5836 umask(0);
5837 $dirmaskdec = octdec((string) $newmask);
5838 if (empty($newmask)) {
5839 $dirmaskdec = octdec(getDolGlobalString('MAIN_UMASK', '0755'));
5840 }
5841 $dirmaskdec |= octdec('0111'); // Set x bit required for directories
5842 if (!@mkdir($ccdir_osencoded, $dirmaskdec)) {
5843 // If the is_dir has returned a false information, we arrive here
5844 dol_syslog("functions.lib::dol_mkdir: Fails to create directory '" . $ccdir . "' (no permission to write into parent or directory already exists).", LOG_WARNING);
5845 $nberr++;
5846 } else {
5847 dol_syslog("functions.lib::dol_mkdir: Directory '" . $ccdir . "' created", LOG_DEBUG);
5848 $nberr = 0; // At this point in the code, the previous failures can be ignored -> set $nberr to 0
5849 $nbcreated++;
5850 }
5851 } else {
5852 $nberr = 0; // At this point in the code, the previous failures can be ignored -> set $nberr to 0
5853 }
5854 }
5855 }
5856 return ($nberr ? -$nberr : $nbcreated);
5857}
5858
5859
5867function dolChmod($filepath, $newmask = '')
5868{
5869 if (!empty($newmask)) {
5870 @chmod($filepath, octdec($newmask));
5871 } elseif (getDolGlobalString('MAIN_UMASK')) {
5872 @chmod($filepath, octdec(getDolGlobalString('MAIN_UMASK')));
5873 }
5874}
5875
5876
5882function picto_required()
5883{
5884 return '<span class="fieldrequired">*</span>';
5885}
5886
5887
5904function dol_string_nohtmltag($stringtoclean, $removelinefeed = 1, $pagecodeto = 'UTF-8', $strip_tags = 0, $removedoublespaces = 1)
5905{
5906 if (is_null($stringtoclean)) {
5907 return '';
5908 }
5909
5910 if ($removelinefeed == 2) {
5911 $stringtoclean = preg_replace('/<br[^>]*>(\n|\r)+/ims', '<br>', $stringtoclean);
5912 }
5913 $temp = preg_replace('/<br[^>]*>/i', "\n", $stringtoclean);
5914
5915 // 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)
5916 $temp = dol_html_entity_decode($temp, ENT_COMPAT | ENT_HTML5, $pagecodeto);
5917
5918 $temp = str_replace('< ', '__ltspace__', $temp);
5919 $temp = str_replace('<:', '__lttwopoints__', $temp);
5920
5921 if ($strip_tags) {
5922 $temp = strip_tags($temp);
5923 } else {
5924 // 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).
5925 $pattern = "/<[^<>]+>/";
5926 // Example of $temp: <a href="/myurl" title="<u>A title</u>">0000-021</a>
5927 // pass 1 - $temp after pass 1: <a href="/myurl" title="A title">0000-021
5928 // pass 2 - $temp after pass 2: 0000-021
5929 $tempbis = $temp;
5930 do {
5931 $temp = $tempbis;
5932 $tempbis = str_replace('<>', '', $temp); // No reason to have this into a text, except if value is to try bypass the next html cleaning
5933 $tempbis = preg_replace($pattern, '', $tempbis);
5934 //$idowhile++; print $temp.'-'.$tempbis."\n"; if ($idowhile > 100) break;
5935 } while ($tempbis != $temp);
5936
5937 $temp = $tempbis;
5938
5939 // 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).
5940 $temp = preg_replace('/<+([a-z]+)/i', '\1', $temp);
5941 }
5942
5943 $temp = dol_html_entity_decode($temp, ENT_COMPAT, $pagecodeto);
5944
5945 // Remove also carriage returns
5946 if ($removelinefeed == 1) {
5947 $temp = str_replace(array("\r\n", "\r", "\n"), " ", $temp);
5948 }
5949
5950 // And double spaces
5951 if ($removedoublespaces) {
5952 while (strpos($temp, " ") !== false) {
5953 $temp = str_replace(" ", " ", $temp);
5954 }
5955 }
5956
5957 $temp = str_replace('__ltspace__', '< ', $temp);
5958 $temp = str_replace('__lttwopoints__', '<:', $temp);
5959
5960 return trim($temp);
5961}
5962
5982function dol_string_onlythesehtmltags($stringtoclean, $cleanalsosomestyles = 1, $removeclassattribute = 1, $cleanalsojavascript = 0, $allowiframe = 0, $allowed_tags = array(), $allowlink = 0, $allowscript = 0, $allowstyle = 0, $allowphp = 0)
5983{
5984 $sav_allowed_tags = $allowed_tags;
5985
5986 if (empty($allowed_tags) || (is_string($allowed_tags) && preg_match('/^common/', $allowed_tags))) {
5987 $allowed_tags = array(
5988 // HTML 4
5989 "html",
5990 "head",
5991 "body",
5992 "article",
5993 "a",
5994 "abbr",
5995 "b",
5996 "blockquote",
5997 "br",
5998 "cite",
5999 "div",
6000 "dl",
6001 "dd",
6002 "dt",
6003 "em",
6004 "font",
6005 "img",
6006 "ins",
6007 "hr",
6008 "i",
6009 "li",
6010 "ol",
6011 "p",
6012 "q",
6013 "s",
6014 "span",
6015 "strike",
6016 "strong",
6017 "title",
6018 "table",
6019 "tr",
6020 "th",
6021 "td",
6022 "u",
6023 "ul",
6024 "sup",
6025 "sub",
6026 "blockquote",
6027 "pre",
6028 "h1",
6029 "h2",
6030 "h3",
6031 "h4",
6032 "h5",
6033 "h6",
6034
6035 // HTML 5
6036 "footer",
6037 "header",
6038 "menu",
6039 "menuitem",
6040 "nav",
6041 "section"
6042 );
6043 }
6044 $allowed_tags[] = "comment"; // this tags is added to manage comment <!--...--> that are replaced into <comment>...</comment>
6045 if ($allowiframe) {
6046 if (!in_array('iframe', $allowed_tags)) {
6047 $allowed_tags[] = "iframe";
6048 }
6049 }
6050 if ($allowlink) {
6051 if (!in_array('link', $allowed_tags)) {
6052 $allowed_tags[] = "link";
6053 }
6054 if (!in_array('meta', $allowed_tags)) {
6055 $allowed_tags[] = "meta";
6056 }
6057 }
6058 if ($allowscript) {
6059 if (!in_array('script', $allowed_tags)) {
6060 $allowed_tags[] = "script";
6061 }
6062 }
6063 if ($allowstyle) {
6064 if (!in_array('style', $allowed_tags)) {
6065 $allowed_tags[] = "style";
6066 }
6067 }
6068 if (is_string($sav_allowed_tags)) {
6069 $tmptags = explode(',', $sav_allowed_tags);
6070 foreach ($tmptags as $tag) {
6071 if ($tag != 'common') {
6072 $allowed_tags[] = $tag;
6073 }
6074 }
6075 }
6076
6077
6078 $allowed_tags_string = implode("><", $allowed_tags);
6079 $allowed_tags_string = '<' . $allowed_tags_string . '>';
6080
6081 $stringtoclean = str_replace('<!DOCTYPE html>', '__!DOCTYPE_HTML__', $stringtoclean); // Replace DOCTYPE to avoid to have it removed by the strip_tags
6082
6083 $stringtoclean = dol_string_nounprintableascii($stringtoclean, 0);
6084
6085 //$stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
6086 $stringtoclean = preg_replace('/<!--([^>]*)-->/', '<comment>\1</comment>', $stringtoclean);
6087
6088 if ($allowphp) {
6089 $allowed_tags[] = "commentphp";
6090 $stringtoclean = preg_replace('/^<\?php([^"]+)\?>$/i', '<commentphp>\1__</commentphp>', $stringtoclean); // Note: <?php ... > is allowed only if on the same line
6091 $stringtoclean = preg_replace('/"<\?php([^"]+)\?>"/i', '"<commentphp>\1</commentphp>"', $stringtoclean); // Note: "<?php ... >" is allowed only if on the same line
6092 }
6093
6094 $stringtoclean = preg_replace('/&colon;/i', ':', $stringtoclean);
6095 $stringtoclean = preg_replace('/&#58;|&#0+58|&#x3A/i', '', $stringtoclean); // refused string ':' encoded (no reason to have a : encoded like this) to disable 'javascript:...'
6096
6097 // Remove all HTML tags
6098 $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
6099
6100 if ($cleanalsosomestyles) { // Clean for remaining html tags
6101 //$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
6102 $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
6103 $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
6104 }
6105 if ($removeclassattribute) { // Clean for remaining html tags
6106 $temp = preg_replace('/(<[^>]+)\s+class=((["\']).*?\\3|\\w*)/i', '\\1', $temp);
6107 }
6108
6109 // Remove 'javascript:' that we should not find into a text
6110 // 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)).
6111 if ($cleanalsojavascript) {
6112 $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);
6113 }
6114
6115 $temp = str_replace('__!DOCTYPE_HTML__', '<!DOCTYPE html>', $temp); // Restore the DOCTYPE
6116
6117 if ($allowphp) {
6118 $temp = preg_replace('/<commentphp>(.*)<\/commentphp>/', '<?php\1?>', $temp); // Restore php code
6119 }
6120
6121 $temp = preg_replace('/<comment>([^>]*)<\/comment>/', '<!--\1-->', $temp); // Restore html comments
6122
6123
6124 return $temp;
6125}
6126
6127
6141function dol_string_onlythesehtmlattributes($stringtoclean, $allowed_attributes = null, $ishtml = null)
6142{
6143 if (is_null($allowed_attributes)) {
6144 $allowed_attributes = array(
6145 // HTML 4
6146 "allow",
6147 "allowfullscreen",
6148 "alt",
6149 "async",
6150 "class",
6151 "contenteditable",
6152 "crossorigin",
6153 "data-html",
6154 "frameborder",
6155 "height",
6156 "href",
6157 "id",
6158 "name",
6159 "property",
6160 "rel",
6161 "src",
6162 "style",
6163 "target",
6164 "title",
6165 "type",
6166 "width",
6167
6168 // HTML5
6169 "footer",
6170 "header",
6171 "menu",
6172 "menuitem",
6173 "nav",
6174 "section"
6175 );
6176 }
6177 // Always add content and http-equiv for meta tags, required to force encoding and keep html content in utf8 by load/saveHTML functions.
6178 if (!in_array("content", $allowed_attributes)) {
6179 $allowed_attributes[] = "content";
6180 }
6181 if (!in_array("http-equiv", $allowed_attributes)) {
6182 $allowed_attributes[] = "http-equiv";
6183 }
6184
6185 if (class_exists('DOMDocument') && !empty($stringtoclean)) {
6186 if ($ishtml === 0) {
6187 $stringtoclean = str_replace('&', '__AMPINTEXT__', $stringtoclean); // Restore & char not entity
6188 }
6189
6190 // Warning: loadHTML does not support HTML5 on old libxml versions.
6191 $dom = new DOMDocument('', 'UTF-8');
6192 // If $stringtoclean is wrong, it will generates warnings. So we disable warnings and restore them later.
6193 $savwarning = error_reporting();
6194 error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE);
6195 $wrapperId = "dol_string_onlythesehtmlattributes___wrapper";
6196 $dom->loadHTML('<?xml encoding="UTF-8"><div id="' . $wrapperId . '">' . $stringtoclean . '</div>', LIBXML_HTML_NODEFDTD | LIBXML_ERR_NONE | LIBXML_HTML_NOIMPLIED | LIBXML_NONET | LIBXML_NOWARNING | LIBXML_NOERROR | LIBXML_NOXMLDECL);
6197 error_reporting($savwarning);
6198
6199 for ($els = $dom->getElementsByTagname('*'), $i = $els->length - 1; $i >= 0; $i--) {
6200 $el = $els->item($i);
6201 if (!$el instanceof DOMElement) {
6202 continue;
6203 }
6204 $attrs = $el->attributes;
6205 for ($ii = $attrs->length - 1; $ii >= 0; $ii--) {
6206 //var_dump($attrs->item($ii));
6207 if (!empty($attrs->item($ii)->name)) {
6208 if (! in_array($attrs->item($ii)->name, $allowed_attributes)) {
6209 // Delete attribute if not into allowed_attributes @phan-suppress-next-line PhanUndeclaredMethod
6210 $els->item($i)->removeAttribute($attrs->item($ii)->name);
6211 } elseif (in_array($attrs->item($ii)->name, array('style'))) {
6212 // If attribute is 'style'
6213 $valuetoclean = $attrs->item($ii)->value;
6214
6215 if ($valuetoclean !== null) {
6216 do {
6217 $oldvaluetoclean = $valuetoclean;
6218 $valuetoclean = preg_replace('/\/\*.*\*\//m', '', $valuetoclean); // clean css comments
6219 $valuetoclean = preg_replace('/position\s*:\s*[a-z]+/mi', '', $valuetoclean);
6220 if ($els->item($i)->tagName == 'a') { // more paranoiac cleaning for clickable tags.
6221 $valuetoclean = preg_replace('/display\s*:/mi', '', $valuetoclean);
6222 $valuetoclean = preg_replace('/z-index\s*:/mi', '', $valuetoclean);
6223 $valuetoclean = preg_replace('/\s+(top|left|right|bottom)\s*:/mi', '', $valuetoclean);
6224 }
6225
6226 // We do not allow logout|passwordforgotten.php and action= into the content of a "style" tag
6227 $valuetoclean = preg_replace('/(logout|passwordforgotten)\.php/mi', '', $valuetoclean);
6228 $valuetoclean = preg_replace('/action=/mi', '', $valuetoclean);
6229 } while ($oldvaluetoclean != $valuetoclean);
6230 }
6231
6232 $attrs->item($ii)->value = $valuetoclean;
6233 }
6234 }
6235 }
6236 }
6237
6238 $dom->encoding = 'UTF-8';
6239 $wrapper = $dom->getElementById($wrapperId);
6240 $return = '';
6241 foreach ($wrapper->childNodes as $child) {
6242 $return .= $dom->saveHTML($child);
6243 }
6244
6245 if ($ishtml === 0) {
6246 $return = str_replace('__AMPINTEXT__', '&', $return); // Restore & char not entity
6247 }
6248
6249 return trim($return);
6250 } else {
6251 return $stringtoclean;
6252 }
6253}
6254
6266function dol_string_neverthesehtmltags($stringtoclean, $disallowed_tags = array('textarea'), $cleanalsosomestyles = 0)
6267{
6268 $temp = $stringtoclean;
6269 foreach ($disallowed_tags as $tagtoremove) {
6270 $temp = preg_replace('/<\/?' . $tagtoremove . '>/', '', $temp);
6271 $temp = preg_replace('/<\/?' . $tagtoremove . '\s+[^>]*>/', '', $temp);
6272 }
6273
6274 if ($cleanalsosomestyles) {
6275 $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
6276 }
6277
6278 return $temp;
6279}
6280
6281
6291function dolCloseUnclosedHtmlTags($text)
6292{
6293 if (!is_string($text) || $text === '') {
6294 return $text;
6295 }
6296
6297 // Tags that never carry a closing tag
6298 $selfclosing = array('br', 'hr', 'img', 'input', 'meta', 'link', 'source', 'col', 'area', 'base', 'embed', 'param', 'track', 'wbr');
6299
6300 $opened = array();
6301 if (preg_match_all('/<\s*(\/?)([a-zA-Z][a-zA-Z0-9]*)[^>]*?(\/?)\s*>/', $text, $matches, PREG_SET_ORDER)) {
6302 foreach ($matches as $match) {
6303 $tag = strtolower($match[2]);
6304 if (in_array($tag, $selfclosing) || !empty($match[3])) {
6305 continue;
6306 }
6307 if (empty($match[1])) {
6308 $opened[] = $tag;
6309 } else {
6310 // Close the most recent matching opened tag, ignore a stray closing tag
6311 $idx = array_search($tag, array_reverse($opened, true), true);
6312 if ($idx !== false) {
6313 unset($opened[$idx]);
6314 }
6315 }
6316 }
6317 }
6318
6319 foreach (array_reverse($opened) as $tag) {
6320 $text .= '</'.$tag.'>';
6321 }
6322
6323 return $text;
6324}
6325
6335function dolGetFirstLineOfText($text, $nboflines = 1, $charset = 'UTF-8')
6336{
6337 if ($nboflines == 1) {
6338 if (dol_textishtml($text)) {
6339 $firstline = preg_replace('/<br[^>]*>.*$/s', '', $text); // The s pattern modifier means the . can match newline characters
6340 $firstline = preg_replace('/<div[^>]*>.*$/s', '', $firstline); // The s pattern modifier means the . can match newline characters
6341 } else {
6342 if (isset($text)) {
6343 $firstline = preg_replace('/[\n\r].*/', '', $text);
6344 } else {
6345 $firstline = '';
6346 }
6347 }
6348 return $firstline . (isset($firstline) && isset($text) && (strlen($firstline) != strlen($text)) ? '...' : '');
6349 } else {
6350 $ishtml = 0;
6351 if (dol_textishtml($text)) {
6352 $text = preg_replace('/\n/', '', $text);
6353 $ishtml = 1;
6354 $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
6355 } else {
6356 $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
6357 }
6358
6359 $text = strtr($text, $repTable);
6360 if ($charset == 'UTF-8') {
6361 $pattern = '/(<br[^>]*>)/Uu';
6362 } else {
6363 // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
6364 $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
6365 }
6366 $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
6367
6368 $firstline = '';
6369 $i = 0;
6370 $countline = 0;
6371 $lastaddediscontent = 1;
6372 while ($countline < $nboflines && isset($a[$i])) {
6373 if (preg_match('/<br[^>]*>/', $a[$i])) {
6374 if (array_key_exists($i + 1, $a) && !empty($a[$i + 1])) {
6375 $firstline .= ($ishtml ? "<br>\n" : "\n");
6376 // Is it a br for a new line of after a printed line ?
6377 if (!$lastaddediscontent) {
6378 $countline++;
6379 }
6380 $lastaddediscontent = 0;
6381 }
6382 } else {
6383 $firstline .= $a[$i];
6384 $lastaddediscontent = 1;
6385 $countline++;
6386 }
6387 $i++;
6388 }
6389
6390 $adddots = (isset($a[$i]) && (!preg_match('/<br[^>]*>/', $a[$i]) || (array_key_exists($i + 1, $a) && !empty($a[$i + 1]))));
6391 //unset($a);
6392 $ret = $firstline . ($adddots ? '...' : '');
6393 //exit;
6394 return $ret;
6395 }
6396}
6397
6398
6410function dol_nl2br($stringtoencode, $nl2brmode = 0, $forxml = false)
6411{
6412 if (is_null($stringtoencode)) {
6413 return '';
6414 }
6415
6416 if (!$nl2brmode) {
6417 return nl2br($stringtoencode, $forxml);
6418 } else {
6419 $ret = preg_replace('/(\r\n|\r|\n)/i', ($forxml ? '<br />' : '<br>'), $stringtoencode);
6420 return $ret;
6421 }
6422}
6423
6434function dol_htmlwithnojs($stringtoencode, $nouseofiframesandbox = 0, $check = 'restricthtml')
6435{
6436 if (empty($nouseofiframesandbox) && getDolGlobalString('MAIN_SECURITY_USE_SANDBOX_FOR_HTMLWITHNOJS')) {
6437 // TODO using sandbox on inline html content is not possible yet with current browsers
6438 //$s = '<iframe class="iframewithsandbox" sandbox><html><body>';
6439 //$s .= $stringtoencode;
6440 //$s .= '</body></html></iframe>';
6441 return $stringtoencode;
6442 } else {
6443 $out = $stringtoencode;
6444
6445 $antiinfinitloop = 0;
6446
6447 // First clean HTML content
6448 do {
6449 if ($antiinfinitloop >= 20) {
6450 dol_print_error(null, "Infinite loop detected after ".$antiinfinitloop." iterations in dol_htmlwithnojs");
6451 die; // We must not break and we must not return a string for security issue. This should never happen.
6452 }
6453 $antiinfinitloop++;
6454
6455 $oldstringtoclean = $out;
6456
6457 $outishtml = 0;
6458 if (dol_textishtml($out)) {
6459 $outishtml = 1;
6460 }
6461
6462 // HTML sanitizer by DOMDocument
6463 if (!empty($out) && getDolGlobalInt('MAIN_RESTRICTHTML_ONLY_VALID_HTML') && $check != 'restricthtmlallowunvalid') {
6464 try {
6465 libxml_use_internal_errors(false); // Avoid to fill memory with xml errors
6466 if (LIBXML_VERSION < 20900) {
6467 // Avoid load of external entities (security problem).
6468 // Required only if LIBXML_VERSION < 20900
6469 // @phan-suppress-next-line PhanDeprecatedFunctionInternal
6470 libxml_disable_entity_loader(true);
6471 }
6472
6473 if (!$outishtml) {
6474 $out = preg_replace('/&(?![a-zA-Z0-9#]+;)/', '__AMPINTEXT__', $out);
6475 }
6476
6477 $dom = new DOMDocument();
6478
6479 // Note: <a href="https://__[aaa]__/aaa.html"> is transformed into <a href="https://__[aaa]__/aaa.html">
6480 // We don't want that, so we protect __[xxx]__ by replacing [ and ] before loadHTML and restore them after saveHTML
6481 $out = preg_replace_callback(
6482 '/__\[([0-9a-zA-Z_]+)\]__/',
6487 function ($m) {
6488 return '__BRACKETSTART' . $m[1] . 'BRACKETEND__';
6489 },
6490 $out
6491 );
6492 $wrapperId = "dol_htmlwithnojs___wrapper___toremove";
6493 $dom->loadHTML('<?xml encoding="UTF-8"><div id="' . $wrapperId . '">' . $out . '</div>', LIBXML_HTML_NODEFDTD | LIBXML_ERR_NONE | LIBXML_HTML_NOIMPLIED | LIBXML_NONET | LIBXML_NOWARNING | LIBXML_NOERROR | LIBXML_NOXMLDECL);
6494
6495 $dom->encoding = 'UTF-8';
6496
6497 // Add a layer to remove some styles
6498 if (getDolGlobalInt('MAIN_RESTRICTHTML_ONLY_VALID_HTML') == 2) {
6499 foreach ($dom->getElementsByTagName('*') as $el) {
6500 if (!$el instanceof DOMElement) {
6501 continue;
6502 }
6503
6504 // @phan-suppress-next-line PhanPluginUnknownObjectMethodCall
6505 if ($el->hasAttribute('style')) {
6506 // @phan-suppress-next-line PhanPluginUnknownObjectMethodCall
6507 $style = $el->getAttribute('style');
6508
6509 // delete some styles
6510 $style = preg_replace('/z-index\s*:/i', '', $style);
6511 $style = preg_replace('/position\s*:/i', '', $style);
6512 $style = preg_replace('/top\s*:/i', '', $style);
6513 $style = preg_replace('/left\s*:/i', '', $style);
6514 $style = preg_replace('/background\s*:/i', '', $style);
6515 /*
6516 $style = preg_replace('/width\s*:/i', '', $style);
6517 $style = preg_replace('/height\s*:/i', '', $style);
6518 $style = preg_replace('/backdrop-filter\s*:/i', '', $style);
6519 */
6520 if (trim($style) === '') {
6521 // @phan-suppress-next-line PhanPluginUnknownObjectMethodCall
6522 $el->removeAttribute('style');
6523 } else {
6524 // @phan-suppress-next-line PhanPluginUnknownObjectMethodCall
6525 $el->setAttribute('style', $style);
6526 }
6527 }
6528 }
6529 }
6530
6531 $wrapper = $dom->getElementById($wrapperId);
6532 $result = '';
6533 foreach ($wrapper->childNodes as $child) {
6534 $result .= $dom->saveHTML($child);
6535 }
6536
6537 $out = trim($result);
6538
6539 // Restore [ and ] that were protected before loadHTML
6540 $out = preg_replace_callback(
6541 '/__BRACKETSTART([0-9a-zA-Z_]+)BRACKETEND__/',
6546 function ($m) {
6547 return '__[' . $m[1] . ']__';
6548 },
6549 $out
6550 );
6551
6552 if (!$outishtml) { // If $out was not HTML content we made before a dol_nl2br so we must do the opposite operation now
6553 $out = str_replace('__AMPINTEXT__', '&', $out); // Restore & char not entity
6554 $out = preg_replace('/<br\s*\/?>/i', "\n", $out);
6555 }
6556 } catch (Exception $e) {
6557 // If error, invalid HTML string with no way to clean it
6558 //print $e->getMessage();
6559 $out = 'InvalidHTMLStringCantBeCleaned ' . $e->getMessage();
6560 }
6561 }
6562
6563 // HTML sanitizer by Tidy
6564 // Tidy can't be used for restricthtmlallowunvalid and restricthtmlallowlinkscript
6565 // Tidy can't be used for non html text content as it is corrupting the new lines fields.
6566 if (!empty($out) && getDolGlobalInt('MAIN_RESTRICTHTML_ONLY_VALID_HTML_TIDY') && !in_array($check, array('restricthtmlallowunvalid', 'restricthtmlallowlinkscript')) && $outishtml) {
6567 // TODO Try to implement a hack for restricthtmlallowlinkscript by renaming tag <link> and <script> ?
6568 try {
6569 //var_dump($out);
6570
6571 // Try cleaning using tidy
6572 if (extension_loaded('tidy') && class_exists("tidy")) {
6573 //print "aaa".$out."\n";
6574
6575 // See options at https://tidy.sourceforge.net/docs/quickref.html
6576 $config = array(
6577 'clean' => false,
6578 // 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;
6579 'quote-marks' => false,
6580 'doctype' => 'strict',
6581 'show-body-only' => true,
6582 "indent-attributes" => false,
6583 "vertical-space" => false,
6584 //'ident' => false, // Not always supported
6585 "wrap" => 0,
6586 'preserve-entities' => true
6587 // HTML5 tags
6588 //'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',
6589 //'new-blocklevel-tags' => 'footer header section menu menuitem'
6590 //'new-empty-tags' => 'command embed keygen source track wbr',
6591 //'new-inline-tags' => 'audio command datalist embed keygen mark menuitem meter output progress source time video wbr',
6592 );
6593
6594 // Tidy
6595 $locale = setlocale(LC_NUMERIC, '0'); // Tidy has a bug and is changing the PHP locale. So we save it to restore it after.
6596
6597 $tidy = new tidy();
6598 $out = $tidy->repairString($out, $config, 'utf8');
6599
6600 setlocale(LC_NUMERIC, $locale); // Restore original local
6601
6602 //print "xxx".$out;exit;
6603 }
6604
6605 //var_dump($out);
6606 } catch (Exception $e) {
6607 // If error, invalid HTML string with no way to clean it
6608 //print $e->getMessage();
6609 $out = 'InvalidHTMLStringCantBeCleaned ' . $e->getMessage();
6610 }
6611 }
6612
6613 // Clear ZERO WIDTH NO-BREAK SPACE, ZERO WIDTH SPACE, ZERO WIDTH JOINER
6614 // TODO $out = preg_replace('/[\x{2000}-\x{200D}\x{FEFF}]/u', ' ', $out);
6615 $out = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', ' ', $out);
6616
6617 // Clean some html entities that are useless so text is cleaner
6618 $out = preg_replace('/&(tab|newline);/i', ' ', $out);
6619
6620 // Ckeditor uses the numeric entity for apostrophe, so we force it to
6621 // the text entity (all other special chars are encoded using text entities) so we can then exclude all numeric entities.
6622 $out = preg_replace('/&#39;/i', '&apos;', $out);
6623
6624 // 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).
6625 // 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
6626 // using a non conventionnal way to be encoded, to not have them sanitized just after)
6627 if (function_exists('realCharForNumericEntities')) { // May not exist when main.inc.php not loaded, for example in a CLI context
6628 $out = preg_replace_callback(
6629 '/&#(x?[0-9][0-9a-f]+;?)/i',
6634 static function ($m) {
6635 return realCharForNumericEntities($m);
6636 },
6637 $out
6638 );
6639 }
6640
6641 // Now we remove all remaining HTML entities starting with a number. We don't want such entities.
6642 $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'.
6643
6644 // Keep only some html tags and remove also some 'javascript:' strings
6645 if ($check == 'restricthtmlallowlinkscript') {
6646 $out = dol_string_onlythesehtmltags($out, 0, 1, 0, 0, array(), 1, 1, 1, getDolGlobalInt("UNSECURED_restricthtmlallowlinkscript_ALLOW_PHP"));
6647 } elseif ($check == 'restricthtmlallowclass' || $check == 'restricthtmlallowunvalid') {
6648 $out = dol_string_onlythesehtmltags($out, 0, 0, 1);
6649 } elseif ($check == 'restricthtmlallowiframe') {
6650 $out = dol_string_onlythesehtmltags($out, 0, 0, 1, 1);
6651 } else {
6652 $out = dol_string_onlythesehtmltags($out, 0, 1, 1); // styles are allowed to allow rich text editor features of ckeditor managed by the "style=" attribute
6653 }
6654
6655 // Keep only some html attributes and exclude non expected HTML attributes and clean content of some attributes (keep only alt=, title=...).
6656 if (getDolGlobalString('MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES')) {
6657 $out = dol_string_onlythesehtmlattributes($out, null, $outishtml);
6658 }
6659
6660 // Restore entity &apos; into &#39; (restricthtml is for html content so we can use html entity) because it is
6661 // compatible with HTML 4 used y CKEditor, and HTML 5 (when &apos; works only with HTML5).
6662 $out = preg_replace('/&apos;/i', "&#39;", $out);
6663
6664 // Now remove js
6665 // 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
6666 $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)>
6667 $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);
6668 $out = preg_replace('/on(dblclick|drop|durationchange|emptied|end|ended|error|focus(in|out)?|formdata|gotpointercapture|hashchange|input|invalid)[a-z]*\s*=/i', '', $out);
6669 $out = preg_replace('/on(lost|offline|online|message|pagehide|pageshow)[a-z]*\s*=/i', '', $out);
6670 $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);
6671 $out = preg_replace('/on(timeupdate|toggle|unhandled|unload|volumechange|waiting|wheel)[a-z]*\s*=/i', '', $out);
6672 // More not into the previous list
6673 $out = preg_replace('/on(repeat|begin|finish|beforeinput)[a-z]*\s*=/i', '', $out);
6674 // Add also a generic removal of any onxxx= attribute
6675 $out = preg_replace('/\son[a-z]+\s*=/i', ' ', $out);
6676 } while ($oldstringtoclean != $out);
6677
6678 // Check the limit of external links that are automatically executed in a Rich text content. We count:
6679 // '<img' to avoid <img src="http...">, we can only accept "<img src="data:..."
6680 // 'url(' to avoid inline style like background: url(http...
6681 // '<link' to avoid <link href="http...">
6682 $reg = array();
6683 $tmpout = preg_replace('/<img src="data:/mi', '<__IMG_SRC_DATA__ src="data:', $out);
6684 preg_match_all('/(<img|url\‍(|<link)/i', $tmpout, $reg);
6685 $nblinks = count($reg[0]);
6686 if ($nblinks > getDolGlobalInt("MAIN_SECURITY_MAX_IMG_IN_HTML_CONTENT", 1000)) {
6687 $out = 'ErrorTooManyLinksIntoHTMLString';
6688 }
6689
6690 if (getDolGlobalInt('MAIN_DISALLOW_URL_INTO_DESCRIPTIONS') == 2 || $check == 'restricthtmlnolink') {
6691 if ($nblinks > 0) {
6692 $out = 'ErrorHTMLLinksNotAllowed';
6693 }
6694 } elseif (getDolGlobalInt('MAIN_DISALLOW_URL_INTO_DESCRIPTIONS') == 1) {
6695 // Refuse any links except it they are to the wrapper document.php or viewimage.php
6696 $nblinks = 0;
6697
6698 // Loop on each url in src= and url(
6699 $pattern = '/src=["\']?(http[^"\']+)|url\‍(["\']?(http[^\‍)]+)/';
6700
6702
6703 $matches = array();
6704 if (preg_match_all($pattern, $out, $matches)) {
6705 // URLs are into $matches[1] or $matches[2]
6706 $urls = array();
6707 foreach ($matches[1] as $tmpval) {
6708 if (!empty($tmpval)) {
6709 $urls[] = $tmpval;
6710 }
6711 }
6712 foreach ($matches[2] as $tmpval) {
6713 if (!empty($tmpval)) {
6714 $urls[] = $tmpval;
6715 }
6716 }
6717
6718 // Show URLs
6719 $firstexturl = '';
6720 $secondexturl = '';
6721 foreach ($urls as $url) {
6722 $urlok = 0;
6723 $parsedurl = parse_url($url);
6724 if (!empty($parsedurl)) {
6725 if (preg_match('/'.preg_quote($dolibarr_main_url_root, '/').'/', $url)
6726 //&& preg_match('/(document|viewimage)\.php$/', $parsedurl['path']) && preg_match('/modulepart=(media|mycompany)/', $parsedurl['query'])
6727 ) {
6728 $urlok = 1;
6729 }
6730 }
6731 if (!$urlok) {
6732 $nblinks++;
6733 if (empty($firstexturl)) {
6734 $firstexturl = $url;
6735 } elseif (empty($secondexturl)) {
6736 $secondexturl = $url;
6737 }
6738 //echo "Found url = ".$url . "\n";
6739 }
6740 }
6741 if ($nblinks > 0) {
6742 $out = 'ErrorHTMLExternalLinksNotAllowed (Example: '.$firstexturl.($secondexturl ? ' '.$secondexturl : '').')';
6743 }
6744 }
6745 }
6746
6747 return $out;
6748 }
6749}
6750
6771function dol_htmlentitiesbr($stringtoencode, $nl2brmode = 0, $pagecodefrom = 'UTF-8', $removelasteolbr = 1)
6772{
6773 if (is_null($stringtoencode)) {
6774 return '';
6775 }
6776
6777 $newstring = $stringtoencode;
6778 if (dol_textishtml($stringtoencode)) { // Check if text is already HTML or not
6779 $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.
6780 if ($removelasteolbr) {
6781 $newstring = preg_replace('/<br>$/i', '', $newstring); // Remove last <br> (remove only last one)
6782 }
6783 $newstring = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', ' ', $newstring);
6784 $newstring = strtr($newstring, array('&' => '__PROTECTand__', '<' => '__PROTECTlt__', '>' => '__PROTECTgt__', '"' => '__PROTECTdquot__'));
6785 $newstring = dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom); // Make entity encoding
6786 $newstring = strtr($newstring, array('__PROTECTand__' => '&', '__PROTECTlt__' => '<', '__PROTECTgt__' => '>', '__PROTECTdquot__' => '"'));
6787 } else {
6788 if ($removelasteolbr) {
6789 $newstring = preg_replace('/(\r\n|\r|\n)$/i', '', $newstring); // Remove last \n (may remove several)
6790 }
6791 $newstring = dol_nl2br(dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom), $nl2brmode);
6792 }
6793 // Other substitutions that htmlentities does not do
6794 //$newstring=str_replace(chr(128),'&euro;',$newstring); // 128 = 0x80. Not in html entity table. // Seems useles with TCPDF. Make bug with UTF8 languages
6795 return $newstring;
6796}
6797
6805function dol_htmlentitiesbr_decode($stringtodecode, $pagecodeto = 'UTF-8')
6806{
6807 $ret = dol_html_entity_decode($stringtodecode, ENT_COMPAT | ENT_HTML5, $pagecodeto);
6808 $ret = preg_replace('/' . "\r\n" . '<br(\s[\sa-zA-Z_="]*)?\/?>/i', "<br>", $ret);
6809 $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>' . "\r\n" . '/i', "\r\n", $ret);
6810 $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>' . "\n" . '/i', "\n", $ret);
6811 $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i', "\n", $ret);
6812 return $ret;
6813}
6814
6821function dol_htmlcleanlastbr($stringtodecode)
6822{
6823 $ret = preg_replace('/&nbsp;$/i', "", $stringtodecode); // Because wysiwyg editor may add a &nbsp; at end of last line
6824 $ret = preg_replace('/(<br>|<br(\s[\sa-zA-Z_="]*)?\/?>|' . "\n" . '|' . "\r" . ')+$/i', "", $ret);
6825 return $ret;
6826}
6827
6837function dol_html_entity_decode($a, $b, $c = 'UTF-8', $keepsomeentities = 0)
6838{
6839 $newstring = $a;
6840 if ($keepsomeentities) {
6841 $newstring = strtr($newstring, array('&amp;' => '__andamp__', '&lt;' => '__andlt__', '&gt;' => '__andgt__', '"' => '__dquot__'));
6842 }
6843 $newstring = html_entity_decode((string) $newstring, (int) $b, (string) $c);
6844 if ($keepsomeentities) {
6845 $newstring = strtr($newstring, array('__andamp__' => '&amp;', '__andlt__' => '&lt;', '__andgt__' => '&gt;', '__dquot__' => '"'));
6846 }
6847 return $newstring;
6848}
6849
6861function dol_htmlentities($string, $flags = ENT_QUOTES | ENT_SUBSTITUTE, $encoding = 'UTF-8', $double_encode = false)
6862{
6863 return htmlentities($string, $flags, $encoding, $double_encode);
6864}
6865
6877function dol_string_is_good_iso($s, $clean = 0)
6878{
6879 $len = dol_strlen($s);
6880 $out = '';
6881 $ok = 1;
6882 for ($scursor = 0; $scursor < $len; $scursor++) {
6883 $ordchar = ord($s[$scursor]);
6884 //print $scursor.'-'.$ordchar.'<br>';
6885 if ($ordchar < 32 && $ordchar != 13 && $ordchar != 10) {
6886 $ok = 0;
6887 break;
6888 } elseif ($ordchar > 126 && $ordchar < 160) {
6889 $ok = 0;
6890 break;
6891 } elseif ($clean) {
6892 $out .= $s[$scursor];
6893 }
6894 }
6895 if ($clean) {
6896 return $out;
6897 }
6898 return $ok;
6899}
6900
6909function dol_nboflines($s, $maxchar = 0)
6910{
6911 if ($s == '') {
6912 return 0;
6913 }
6914 $arraystring = explode("\n", $s);
6915 $nb = count($arraystring);
6916
6917 return $nb;
6918}
6919
6920
6930function dol_nboflines_bis($text, $maxlinesize = 0, $charset = 'UTF-8')
6931{
6932 $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
6933 if (dol_textishtml($text)) {
6934 $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
6935 }
6936
6937 $text = strtr($text, $repTable);
6938 if ($charset == 'UTF-8') {
6939 $pattern = '/(<br[^>]*>)/Uu';
6940 } else {
6941 // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
6942 $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
6943 }
6944 $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
6945
6946 $nblines = (int) floor((count($a) + 1) / 2);
6947 // count possible auto line breaks
6948 if ($maxlinesize) {
6949 foreach ($a as $line) {
6950 if (dol_strlen($line) > $maxlinesize) {
6951 //$line_dec = html_entity_decode(strip_tags($line));
6952 $line_dec = html_entity_decode($line);
6953 if (dol_strlen($line_dec) > $maxlinesize) {
6954 $line_dec = wordwrap($line_dec, $maxlinesize, '\n', true);
6955 $nblines += substr_count($line_dec, '\n');
6956 }
6957 }
6958 }
6959 }
6960
6961 unset($a);
6962 return $nblines;
6963}
6964
6973function dol_textishtml($msg, $option = 0)
6974{
6975 if (is_null($msg)) {
6976 return false;
6977 }
6978
6979 // Every pattern below needs a '<' (a tag) or a '&' (an entity): without both, the string can not be HTML. This saves the
6980 // dozen of preg_match() below for the very common case of a plain label.
6981 if (strpos($msg, '<') === false && strpos($msg, '&') === false) {
6982 return false;
6983 }
6984
6985 if ($option == 1) {
6986 if (preg_match('/<(html|link|script)/i', $msg)) {
6987 return true;
6988 } elseif (preg_match('/<body/i', $msg)) {
6989 return true;
6990 } elseif (preg_match('/<\/textarea/i', $msg)) {
6991 return true;
6992 } elseif (preg_match('/<(b|em|i|u)(\s+[^>]+)?>/i', $msg)) {
6993 return true;
6994 } elseif (preg_match('/<br/i', $msg)) {
6995 return true;
6996 }
6997 return false;
6998 } else {
6999 // Remove all urls because 'http://aa?param1=abc&amp;param2=def' must not be used inside detection
7000 $msg = preg_replace('/https?:\/\/[^"\'\s]+/i', '', $msg);
7001 if (preg_match('/<(html|link|script|body)/i', $msg)) {
7002 return true;
7003 } elseif (preg_match('/<\/textarea/i', $msg)) {
7004 return true;
7005 } elseif (preg_match('/<(b|em|i|u)(\s+[^>]+)?>/i', $msg)) {
7006 return true;
7007 } elseif (preg_match('/<(br|hr)\/>/i', $msg)) {
7008 return true;
7009 } elseif (preg_match('/<(br|hr|div|font|li|p|span|strong|table)>/i', $msg)) {
7010 return true;
7011 } elseif (preg_match('/<(br|hr|div|font|li|p|span|strong|table)\s+[^<>\/]*\/?>/i', $msg)) {
7012 return true;
7013 } elseif (preg_match('/<img\s+[^<>]*src[^<>]*>/i', $msg)) {
7014 return true; // must accept <img src="http://example.com/aaa.png" />
7015 } elseif (preg_match('/<a\s+[^<>]*href[^<>]*>/i', $msg)) {
7016 return true; // must accept <a href="http://example.com/aaa.png" />
7017 } elseif (preg_match('/<h[0-9]>/i', $msg)) {
7018 return true;
7019 } elseif (preg_match('/&[A-Z0-9]{1,6};/i', $msg)) {
7020 // TODO If content is 'A link https://aaa?param=abc&amp;param2=def', it return true but must be false
7021 return true; // Html entities names (http://www.w3schools.com/tags/ref_entities.asp)
7022 } elseif (preg_match('/&#[0-9]{2,3};/i', $msg)) {
7023 return true; // Html entities numbers (http://www.w3schools.com/tags/ref_entities.asp)
7024 } elseif (preg_match('/&#x[a-f0-9][a-f0-9];/i', $msg)) {
7025 return true; // Html entities numbers in hexa
7026 }
7027
7028 return false;
7029 }
7030}
7031
7046function dol_concatdesc($text1, $text2, $forxml = false, $invert = false)
7047{
7048 if (!empty($invert)) {
7049 $tmp = $text1;
7050 $text1 = $text2;
7051 $text2 = $tmp;
7052 }
7053
7054 $ret = '';
7055 $ret .= (!dol_textishtml($text1) && dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text1, 0, 1, '', 1), 0, $forxml) : $text1;
7056 $ret .= (!empty($text1) && !empty($text2)) ? ((dol_textishtml($text1) || dol_textishtml($text2)) ? ($forxml ? "<br >\n" : "<br>\n") : "\n") : "";
7057 $ret .= (dol_textishtml($text1) && !dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text2, 0, 1, '', 1), 0, $forxml) : $text2;
7058 return $ret;
7059}
7060
7069function dol_concat($text1, $text2)
7070{
7071 return $text1.$text2;
7072}
7073
7081function safeArrayMap($callback, array $array)
7082{
7083 if (!is_string($callback)) {
7084 throw new InvalidArgumentException("Les callbacks sont désactivés.");
7085 }
7086 // Check that $callback is a sure function
7087 $allowed_callbacks = ['strtolower', 'strtoupper', 'intval'];
7088 if (!in_array($callback, $allowed_callbacks, true)) {
7089 throw new InvalidArgumentException("Callback function not allowed.");
7090 }
7091 return array_map($callback, $array);
7092}
7093
7094
7113function getCommonSubstitutionArray($outputlangs, $onlykey = 0, $exclude = null, $object = null, $include = null)
7114{
7115 global $db, $conf, $mysoc, $user, $extrafields;
7116
7117 $substitutionarray = array();
7118
7119 if ((empty($exclude) || !in_array('user', $exclude)) && (empty($include) || in_array('user', $include)) && $user instanceof User) {
7120 // Add SIGNATURE into substitutionarray first, so, when we will make the substitution,
7121 // this will include signature content first and then replace var found into content of signature
7122 //var_dump($onlykey);
7123 $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()
7124 $usersignature = $user->signature;
7125 if (getDolGlobalString('MAIN_MAIL_DEFAULT_SIGNATURE_FOR_ALL_USERS') && !empty($user->employee)) {
7126 $emailsendersignature = getDolGlobalString('MAIN_MAIL_DEFAULT_SIGNATURE_FOR_ALL_USERS');
7127 $usersignature = getDolGlobalString('MAIN_MAIL_DEFAULT_SIGNATURE_FOR_ALL_USERS');
7128 }
7129 $substitutionarray = array_merge($substitutionarray, array(
7130 '__SENDEREMAIL_SIGNATURE__' => (string) ((!getDolGlobalString('MAIN_MAIL_DO_NOT_USE_SIGN')) ? ($onlykey == 2 ? dol_trunc('SignatureFromTheSelectedSenderProfile', 30) : $emailsendersignature) : ''),
7131 '__USER_SIGNATURE__' => (string) (($usersignature && !getDolGlobalString('MAIN_MAIL_DO_NOT_USE_SIGN')) ? ($onlykey == 2 ? dol_trunc(dol_string_nohtmltag($usersignature), 30) : $usersignature) : '')
7132 ));
7133
7134 if (is_object($user)) {
7135 $substitutionarray = array_merge($substitutionarray, array(
7136 '__USER_ID__' => (string) $user->id,
7137 '__USER_LOGIN__' => (string) $user->login,
7138 '__USER_EMAIL__' => (string) $user->email,
7139 '__USER_PHONE__' => (string) dol_print_phone($user->office_phone, '', 0, 0, '', " ", '', '', -1),
7140 '__USER_PHONEPRO__' => (string) dol_print_phone($user->user_mobile, '', 0, 0, '', " ", '', '', -1),
7141 '__USER_PHONEMOBILE__' => (string) dol_print_phone($user->personal_mobile, '', 0, 0, '', " ", '', '', -1),
7142 '__USER_FAX__' => (string) $user->office_fax,
7143 '__USER_LASTNAME__' => (string) $user->lastname,
7144 '__USER_FIRSTNAME__' => (string) $user->firstname,
7145 '__USER_FULLNAME__' => (string) $user->getFullName($outputlangs),
7146 '__USER_SUPERVISOR_ID__' => (string) ($user->fk_user ? $user->fk_user : '0'),
7147 '__USER_JOB__' => (string) $user->job,
7148 '__USER_REMOTE_IP__' => (string) getUserRemoteIP(),
7149 '__USER_VCARD_URL__' => (string) $user->getOnlineVirtualCardUrl('', 'external')
7150 ));
7151 if (isModEnabled('stock') && getDolGlobalString('MAIN_DEFAULT_WAREHOUSE_USER') && is_object($user->warehouse)) {
7152 $substitutionarray = array_merge($substitutionarray, array(
7153 '__USER_WAREHOUSE_ID__' => isset($user->warehouse->id) ? $user->warehouse->id : '',
7154 '__USER_WAREHOUSE_REF__' => isset($user->warehouse->ref) ? $user->warehouse->ref : '',
7155 '__USER_WAREHOUSE_DESCRIPTION__' => isset($user->warehouse->description) ? $user->warehouse->description : '',
7156 '__USER_WAREHOUSE_ADDRESS__' => isset($user->warehouse->address) ? $user->warehouse->address : '',
7157 '__USER_WAREHOUSE_ZIP__' => isset($user->warehouse->zip) ? $user->warehouse->zip : '',
7158 '__USER_WAREHOUSE_TOWN__' => isset($user->warehouse->town) ? $user->warehouse->town : '',
7159 '__USER_WAREHOUSE_PHONE__' => isset($user->warehouse->phone) ? (string) dol_print_phone($user->warehouse->phone, '', 0, 0, '', " ", '', '', -1) : '',
7160 '__USER_WAREHOUSE_FAX__' => isset($user->warehouse->fax) ? (string) dol_print_phone($user->warehouse->fax, '', 0, 0, '', " ", '', '', -1) : ''
7161 ));
7162 }
7163 }
7164 }
7165 if ((empty($exclude) || !in_array('mycompany', $exclude)) && is_object($mysoc) && (empty($include) || in_array('mycompany', $include))) {
7166 $substitutionarray = array_merge($substitutionarray, array(
7167 '__MYCOMPANY_NAME__' => $mysoc->name,
7168 '__MYCOMPANY_EMAIL__' => $mysoc->email,
7169 '__MYCOMPANY_URL__' => $mysoc->url,
7170 '__MYCOMPANY_PHONE__' => dol_print_phone((string) $mysoc->phone, '', 0, 0, '', " ", '', '', -1),
7171 '__MYCOMPANY_PHONEMOBILE__' => dol_print_phone((string) $mysoc->phone_mobile, '', 0, 0, '', " ", '', '', -1),
7172 '__MYCOMPANY_FAX__' => dol_print_phone((string) $mysoc->fax, '', 0, 0, '', " ", '', '', -1),
7173 '__MYCOMPANY_PROFID1__' => $mysoc->idprof1,
7174 '__MYCOMPANY_PROFID2__' => $mysoc->idprof2,
7175 '__MYCOMPANY_PROFID3__' => $mysoc->idprof3,
7176 '__MYCOMPANY_PROFID4__' => $mysoc->idprof4,
7177 '__MYCOMPANY_PROFID5__' => $mysoc->idprof5,
7178 '__MYCOMPANY_PROFID6__' => $mysoc->idprof6,
7179 '__MYCOMPANY_PROFID7__' => $mysoc->idprof7,
7180 '__MYCOMPANY_PROFID8__' => $mysoc->idprof8,
7181 '__MYCOMPANY_PROFID9__' => $mysoc->idprof9,
7182 '__MYCOMPANY_PROFID10__' => $mysoc->idprof10,
7183 '__MYCOMPANY_OBJECT__' => $mysoc->socialobject,
7184 '__MYCOMPANY_CAPITAL__' => $mysoc->capital,
7185 '__MYCOMPANY_FULLADDRESS__' => (method_exists($mysoc, 'getFullAddress') ? $mysoc->getFullAddress(1, ', ') : ''), // $mysoc may be stdClass
7186 '__MYCOMPANY_ADDRESS__' => $mysoc->address,
7187 '__MYCOMPANY_VATNUMBER__' => $mysoc->tva_intra,
7188 '__MYCOMPANY_ZIP__' => $mysoc->zip,
7189 '__MYCOMPANY_TOWN__' => $mysoc->town,
7190 '__MYCOMPANY_STATE__' => $mysoc->state,
7191 '__MYCOMPANY_COUNTRY__' => $mysoc->country,
7192 '__MYCOMPANY_COUNTRY_ID__' => $mysoc->country_id,
7193 '__MYCOMPANY_COUNTRY_CODE__' => $mysoc->country_code,
7194 '__MYCOMPANY_CURRENCY__' => $outputlangs->transnoentitiesnoconv("Currency".$conf->currency),
7195 '__MYCOMPANY_CURRENCY_CODE__' => $conf->currency
7196 ));
7197 }
7198
7199 if (($onlykey || is_object($object)) && (empty($exclude) || !in_array('object', $exclude)) && (empty($include) || in_array('object', $include))) {
7200 if ($onlykey) {
7201 $substitutionarray['__ID__'] = '__ID__';
7202 $substitutionarray['__REF__'] = '__REF__';
7203 $substitutionarray['__NEWREF__'] = '__NEWREF__';
7204 $substitutionarray['__LABEL__'] = '__LABEL__';
7205 $substitutionarray['__REF_CLIENT__'] = '__REF_CLIENT__';
7206 $substitutionarray['__REF_SUPPLIER__'] = '__REF_SUPPLIER__';
7207 $substitutionarray['__NOTE_PUBLIC__'] = '__NOTE_PUBLIC__';
7208 $substitutionarray['__NOTE_PRIVATE__'] = '__NOTE_PRIVATE__';
7209 $substitutionarray['__EXTRAFIELD_XXX__'] = '__EXTRAFIELD_XXX__';
7210
7211 if (isModEnabled("societe")) { // Most objects are concerned
7212 $substitutionarray['__THIRDPARTY_ID__'] = '__THIRDPARTY_ID__';
7213 $substitutionarray['__THIRDPARTY_NAME__'] = '__THIRDPARTY_NAME__';
7214 $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = '__THIRDPARTY_NAME_ALIAS__';
7215 $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = '__THIRDPARTY_CODE_CLIENT__';
7216 $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = '__THIRDPARTY_CODE_FOURNISSEUR__';
7217 $substitutionarray['__THIRDPARTY_EMAIL__'] = '__THIRDPARTY_EMAIL__';
7218 //$substitutionarray['__THIRDPARTY_EMAIL_URLENCODED__'] = '__THIRDPARTY_EMAIL_URLENCODED__'; // We hide this one
7219 $substitutionarray['__THIRDPARTY_URL__'] = '__THIRDPARTY_URL__';
7220 //$substitutionarray['__THIRDPARTY_URL_URLENCODED__'] = '__THIRDPARTY_URL_URLENCODED__'; // We hide this one
7221 $substitutionarray['__THIRDPARTY_PHONE__'] = '__THIRDPARTY_PHONE__';
7222 $substitutionarray['__THIRDPARTY_FAX__'] = '__THIRDPARTY_FAX__';
7223 $substitutionarray['__THIRDPARTY_ADDRESS__'] = '__THIRDPARTY_ADDRESS__';
7224 $substitutionarray['__THIRDPARTY_ZIP__'] = '__THIRDPARTY_ZIP__';
7225 $substitutionarray['__THIRDPARTY_TOWN__'] = '__THIRDPARTY_TOWN__';
7226 $substitutionarray['__THIRDPARTY_STATE__'] = '__THIRDPARTY_STATE__';
7227 $substitutionarray['__THIRDPARTY_IDPROF1__'] = '__THIRDPARTY_IDPROF1__';
7228 $substitutionarray['__THIRDPARTY_IDPROF2__'] = '__THIRDPARTY_IDPROF2__';
7229 $substitutionarray['__THIRDPARTY_IDPROF3__'] = '__THIRDPARTY_IDPROF3__';
7230 $substitutionarray['__THIRDPARTY_IDPROF4__'] = '__THIRDPARTY_IDPROF4__';
7231 $substitutionarray['__THIRDPARTY_IDPROF5__'] = '__THIRDPARTY_IDPROF5__';
7232 $substitutionarray['__THIRDPARTY_IDPROF6__'] = '__THIRDPARTY_IDPROF6__';
7233 $substitutionarray['__THIRDPARTY_IDPROF7__'] = '__THIRDPARTY_IDPROF7__';
7234 $substitutionarray['__THIRDPARTY_IDPROF8__'] = '__THIRDPARTY_IDPROF8__';
7235 $substitutionarray['__THIRDPARTY_IDPROF9__'] = '__THIRDPARTY_IDPROF9__';
7236 $substitutionarray['__THIRDPARTY_IDPROF10__'] = '__THIRDPARTY_IDPROF10__';
7237 $substitutionarray['__THIRDPARTY_TVAINTRA__'] = '__THIRDPARTY_TVAINTRA__';
7238 $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = '__THIRDPARTY_NOTE_PUBLIC__';
7239 $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = '__THIRDPARTY_NOTE_PRIVATE__';
7240 }
7241 if (isModEnabled('member') && (!is_object($object) || $object->element == 'adherent') && (empty($exclude) || !in_array('member', $exclude)) && (empty($include) || in_array('member', $include))) {
7242 $substitutionarray['__MEMBER_ID__'] = '__MEMBER_ID__';
7243 $substitutionarray['__MEMBER_TITLE__'] = '__MEMBER_TITLE__';
7244 $substitutionarray['__MEMBER_FIRSTNAME__'] = '__MEMBER_FIRSTNAME__';
7245 $substitutionarray['__MEMBER_LASTNAME__'] = '__MEMBER_LASTNAME__';
7246 $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = 'Login and pass of the external user account';
7247 /*$substitutionarray['__MEMBER_NOTE_PUBLIC__'] = '__MEMBER_NOTE_PUBLIC__';
7248 $substitutionarray['__MEMBER_NOTE_PRIVATE__'] = '__MEMBER_NOTE_PRIVATE__';*/
7249 }
7250 // add substitution variables for ticket
7251 if (isModEnabled('ticket') && (!is_object($object) || $object->element == 'ticket') && (empty($exclude) || !in_array('ticket', $exclude)) && (empty($include) || in_array('ticket', $include))) {
7252 $substitutionarray['__TICKET_TRACKID__'] = '__TICKET_TRACKID__';
7253 $substitutionarray['__TICKET_SUBJECT__'] = '__TICKET_SUBJECT__';
7254 $substitutionarray['__TICKET_TYPE__'] = '__TICKET_TYPE__';
7255 $substitutionarray['__TICKET_SEVERITY__'] = '__TICKET_SEVERITY__';
7256 $substitutionarray['__TICKET_CATEGORY__'] = '__TICKET_CATEGORY__';
7257 $substitutionarray['__TICKET_ANALYTIC_CODE__'] = '__TICKET_ANALYTIC_CODE__';
7258 $substitutionarray['__TICKET_MESSAGE__'] = '__TICKET_MESSAGE__';
7259 $substitutionarray['__TICKET_PROGRESSION__'] = '__TICKET_PROGRESSION__';
7260 $substitutionarray['__TICKET_USER_ASSIGN__'] = '__TICKET_USER_ASSIGN__';
7261 $substitutionarray['__TICKET_TYPE_LABEL__'] = '__TICKET_TYPE_LABEL__';
7262 $substitutionarray['__TICKET_SEVERITY_LABEL__'] = '__TICKET_SEVERITY_LABEL__';
7263 $substitutionarray['__TICKET_CATEGORY_LABEL__'] = '__TICKET_CATEGORY_LABEL__';
7264 $substitutionarray['__TICKET_PUBLIC_URL__'] = '__TICKET_PUBLIC_URL__';
7265 $substitutionarray['__TICKET_MANAGEMENT_URL__'] = '__TICKET_MANAGEMENT_URL__';
7266 }
7267 if (isModEnabled('recruitment') && (!is_object($object) || $object->element == 'recruitmentcandidature') && (empty($exclude) || !in_array('recruitment', $exclude)) && (empty($include) || in_array('recruitment', $include))) {
7268 $substitutionarray['__CANDIDATE_FULLNAME__'] = '__CANDIDATE_FULLNAME__';
7269 $substitutionarray['__CANDIDATE_FIRSTNAME__'] = '__CANDIDATE_FIRSTNAME__';
7270 $substitutionarray['__CANDIDATE_LASTNAME__'] = '__CANDIDATE_LASTNAME__';
7271 }
7272 if (isModEnabled('holiday') && (!is_object($object) || $object->element == 'holiday') && (empty($exclude) || !in_array('holiday', $exclude)) && (empty($include) || in_array('holiday', $include))) {
7273 $substitutionarray['__HOLIDAY_ARRAY_PER_EMPLOYEE_FOR_PERIOD__'] = '__HOLIDAY_ARRAY_PER_EMPLOYEE_FOR_PERIOD__';
7274 }
7275 if (isModEnabled('project') && (empty($exclude) || !in_array('project', $exclude)) && (empty($include) || in_array('project', $include))) { // Most objects
7276 $substitutionarray['__PROJECT_ID__'] = '__PROJECT_ID__';
7277 $substitutionarray['__PROJECT_REF__'] = '__PROJECT_REF__';
7278 $substitutionarray['__PROJECT_NAME__'] = '__PROJECT_NAME__';
7279 /*$substitutionarray['__PROJECT_NOTE_PUBLIC__'] = '__PROJECT_NOTE_PUBLIC__';
7280 $substitutionarray['__PROJECT_NOTE_PRIVATE__'] = '__PROJECT_NOTE_PRIVATE__';*/
7281 }
7282 if (isModEnabled('contract') && (!is_object($object) || $object->element == 'contract') && (empty($exclude) || !in_array('contract', $exclude)) && (empty($include) || in_array('contract', $include))) {
7283 $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = 'Highest date planned for a service start';
7284 $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = 'Highest date and hour planned for service start';
7285 $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = 'Lowest data for planned expiration of service';
7286 $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = 'Lowest date and hour for planned expiration of service';
7287 }
7288 if (isModEnabled("propal") && (!is_object($object) || $object->element == 'propal') && (empty($exclude) || !in_array('propal', $exclude)) && (empty($include) || in_array('propal', $include))) {
7289 $substitutionarray['__ONLINE_SIGN_URL__'] = 'ToOfferALinkForOnlineSignature';
7290 }
7291 if (isModEnabled("intervention") && (!is_object($object) || $object->element == 'fichinter') && (empty($exclude) || !in_array('intervention', $exclude)) && (empty($include) || in_array('intervention', $include))) {
7292 $substitutionarray['__ONLINE_SIGN_FICHINTER_URL__'] = 'ToOfferALinkForOnlineSignature';
7293 }
7294 $substitutionarray['__ONLINE_PAYMENT_URL__'] = 'UrlToPayOnlineIfApplicable';
7295 $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = 'TextAndUrlToPayOnlineIfApplicable';
7296 $substitutionarray['__SECUREKEYPAYMENT__'] = 'Security key (if key is not unique per record)';
7297 $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = 'Security key for payment on a member subscription (one key per member)';
7298 $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = 'Security key for payment on an order';
7299 $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = 'Security key for payment on an invoice';
7300 $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = 'Security key for payment on a service of a contract';
7301
7302 $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = 'Direct download url of a proposal';
7303 $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = 'Direct download url of an order';
7304 $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = 'Direct download url of an invoice';
7305 $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = 'Direct download url of a contract';
7306 $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = 'Direct download url of a supplier proposal';
7307 $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_ORDER__'] = 'Direct download url of a supplier order';
7308 $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_INVOICE__'] = 'Direct download url of a supplier invoice';
7309
7310 if (isModEnabled("shipping") && (!is_object($object) || $object->element == 'shipping')) {
7311 $substitutionarray['__SHIPPINGTRACKNUM__'] = 'Shipping tracking number';
7312 $substitutionarray['__SHIPPINGTRACKNUMURL__'] = 'Shipping tracking url';
7313 $substitutionarray['__SHIPPINGMETHOD__'] = 'Shipping method';
7314 }
7315 if (isModEnabled("reception") && (!is_object($object) || $object->element == 'reception')) {
7316 $substitutionarray['__RECEPTIONTRACKNUM__'] = 'Shipping tracking number of shipment';
7317 $substitutionarray['__RECEPTIONTRACKNUMURL__'] = 'Shipping tracking url';
7318 }
7319 } else {
7320 '@phan-var-force Adherent|Delivery $object';
7322 $substitutionarray['__ID__'] = $object->id;
7323 $substitutionarray['__REF__'] = $object->ref;
7324 $substitutionarray['__NEWREF__'] = $object->newref;
7325 $substitutionarray['__LABEL__'] = (isset($object->label) ? $object->label : (isset($object->title) ? $object->title : null));
7326 $substitutionarray['__REF_CLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
7327 $substitutionarray['__REF_SUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
7328 $substitutionarray['__NOTE_PUBLIC__'] = (isset($object->note_public) ? $object->note_public : null);
7329 $substitutionarray['__NOTE_PRIVATE__'] = (isset($object->note_private) ? $object->note_private : null);
7330
7331 $substitutionarray['__DATE_CREATION__'] = (isset($object->date_creation) ? dol_print_date($object->date_creation, 'day', false, $outputlangs) : '');
7332 $substitutionarray['__DATE_MODIFICATION__'] = (isset($object->date_modification) ? dol_print_date($object->date_modification, 'day', false, $outputlangs) : '');
7333 $substitutionarray['__DATE_VALIDATION__'] = (isset($object->date_validation) ? dol_print_date($object->date_validation, 'day', false, $outputlangs) : '');
7334
7335 // handle date_delivery: in customer order/supplier order, the property name is delivery_date, in shipment/reception it is date_delivery
7336 $date_delivery = null;
7337 if (property_exists($object, 'date_delivery')) {
7338 $date_delivery = $object->date_delivery;
7339 } elseif (property_exists($object, 'delivery_date')) {
7340 $date_delivery = $object->delivery_date;
7341 }
7342 $substitutionarray['__DATE_DELIVERY__'] = (isset($date_delivery) ? dol_print_date($date_delivery, 'day', false, $outputlangs) : '');
7343 $substitutionarray['__DATE_DELIVERY_DAY__'] = (isset($date_delivery) ? dol_print_date($date_delivery, "%d") : '');
7344 $substitutionarray['__DATE_DELIVERY_DAY_TEXT__'] = (isset($date_delivery) ? dol_print_date($date_delivery, "%A") : '');
7345 $substitutionarray['__DATE_DELIVERY_MON__'] = (isset($date_delivery) ? dol_print_date($date_delivery, "%m") : '');
7346 $substitutionarray['__DATE_DELIVERY_MON_TEXT__'] = (isset($date_delivery) ? dol_print_date($date_delivery, "%b") : '');
7347 $substitutionarray['__DATE_DELIVERY_YEAR__'] = (isset($date_delivery) ? dol_print_date($date_delivery, "%Y") : '');
7348 $substitutionarray['__DATE_DELIVERY_HH__'] = (isset($date_delivery) ? dol_print_date($date_delivery, "%H") : '');
7349 $substitutionarray['__DATE_DELIVERY_MM__'] = (isset($date_delivery) ? dol_print_date($date_delivery, "%M") : '');
7350 $substitutionarray['__DATE_DELIVERY_SS__'] = (isset($date_delivery) ? dol_print_date($date_delivery, "%S") : '');
7351
7352 // For backward compatibility (deprecated)
7353 $substitutionarray['__REFCLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
7354 $substitutionarray['__REFSUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
7355
7356 $substitutionarray['__SUPPLIER_ORDER_DATE_DELIVERY__'] = (isset($date_delivery) ? dol_print_date($date_delivery, 'day', false, $outputlangs) : '');
7357 $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 : '')) : '');
7358 $substitutionarray['__EXPIRATION_DATE__'] = (isset($object->fin_validite) ? dol_print_date($object->fin_validite, 'daytext') : '');
7359
7360 if (is_object($object) && ($object->element == 'adherent' || $object->element == 'member') && $object->id > 0) {
7361 '@phan-var-force Adherent $object';
7363 $birthday = (empty($object->birth) ? '' : dol_print_date($object->birth, 'day'));
7364
7365 $substitutionarray['__MEMBER_ID__'] = (isset($object->id) ? $object->id : '');
7366 if (method_exists($object, 'getCivilityLabel')) {
7367 $substitutionarray['__MEMBER_TITLE__'] = $object->getCivilityLabel();
7368 }
7369 $substitutionarray['__MEMBER_FIRSTNAME__'] = (isset($object->firstname) ? $object->firstname : '');
7370 $substitutionarray['__MEMBER_LASTNAME__'] = (isset($object->lastname) ? $object->lastname : '');
7371 $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = '';
7372 if (method_exists($object, 'getFullName')) {
7373 $substitutionarray['__MEMBER_FULLNAME__'] = $object->getFullName($outputlangs);
7374 }
7375 $substitutionarray['__MEMBER_COMPANY__'] = (isset($object->societe) ? $object->societe : '');
7376 $substitutionarray['__MEMBER_ADDRESS__'] = (isset($object->address) ? $object->address : '');
7377 $substitutionarray['__MEMBER_ZIP__'] = (isset($object->zip) ? $object->zip : '');
7378 $substitutionarray['__MEMBER_TOWN__'] = (isset($object->town) ? $object->town : '');
7379 $substitutionarray['__MEMBER_STATE__'] = (isset($object->state) ? $object->state : '');
7380 $substitutionarray['__MEMBER_COUNTRY__'] = (isset($object->country) ? $object->country : '');
7381 $substitutionarray['__MEMBER_EMAIL__'] = (isset($object->email) ? $object->email : '');
7382 $substitutionarray['__MEMBER_BIRTH__'] = (isset($birthday) ? $birthday : '');
7383 $substitutionarray['__MEMBER_PHOTO__'] = (isset($object->photo) ? $object->photo : '');
7384 $substitutionarray['__MEMBER_LOGIN__'] = (isset($object->login) ? $object->login : '');
7385 $substitutionarray['__MEMBER_PASSWORD__'] = (isset($object->pass) ? $object->pass : '');
7386 $substitutionarray['__MEMBER_PHONE__'] = (isset($object->phone) ? dol_print_phone($object->phone) : '');
7387 $substitutionarray['__MEMBER_PHONEPRO__'] = (isset($object->phone_perso) ? dol_print_phone($object->phone_perso) : '');
7388 $substitutionarray['__MEMBER_PHONEMOBILE__'] = (isset($object->phone_mobile) ? dol_print_phone($object->phone_mobile) : '');
7389 $substitutionarray['__MEMBER_TYPE__'] = (isset($object->type) ? $object->type : '');
7390 $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE__'] = dol_print_date($object->first_subscription_date, 'day');
7391
7392 $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_RFC__'] = dol_print_date($object->first_subscription_date, 'dayrfc');
7393 $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_START__'] = (isset($object->first_subscription_date_start) ? dol_print_date($object->first_subscription_date_start, 'day') : '');
7394 $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_START_RFC__'] = (isset($object->first_subscription_date_start) ? dol_print_date($object->first_subscription_date_start, 'dayrfc') : '');
7395 $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_END__'] = (isset($object->first_subscription_date_end) ? dol_print_date($object->first_subscription_date_end, 'day') : '');
7396 $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_END_RFC__'] = (isset($object->first_subscription_date_end) ? dol_print_date($object->first_subscription_date_end, 'dayrfc') : '');
7397 $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE__'] = dol_print_date($object->last_subscription_date, 'day');
7398 $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_RFC__'] = dol_print_date($object->last_subscription_date, 'dayrfc');
7399 $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->last_subscription_date_start, 'day');
7400 $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_START_RFC__'] = dol_print_date($object->last_subscription_date_start, 'dayrfc');
7401 $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->last_subscription_date_end, 'day');
7402 $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_END_RFC__'] = dol_print_date($object->last_subscription_date_end, 'dayrfc');
7403 }
7404
7405 if (is_object($object) && $object->element == 'societe') {
7407 '@phan-var-force Societe $object';
7408 $substitutionarray['__THIRDPARTY_ID__'] = ($object->id > 0 ? $object->id : '');
7409 $substitutionarray['__THIRDPARTY_NAME__'] = (string) $object->name;
7410 $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (string) $object->name_alias;
7411 $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = $object->code_client ?? '';
7412 $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = $object->code_fournisseur ?? '';
7413 $substitutionarray['__THIRDPARTY_EMAIL__'] = $object->email ?? '';
7414 $substitutionarray['__THIRDPARTY_EMAIL_URLENCODED__'] = urlencode($object->email ?? '');
7415 $substitutionarray['__THIRDPARTY_URL__'] = $object->url ?? '';
7416 $substitutionarray['__THIRDPARTY_URL_URLENCODED__'] = urlencode($object->url ?? '');
7417 $substitutionarray['__THIRDPARTY_PHONE__'] = dol_print_phone($object->phone);
7418 $substitutionarray['__THIRDPARTY_FAX__'] = dol_print_phone($object->fax);
7419 $substitutionarray['__THIRDPARTY_ADDRESS__'] = $object->address ?? '';
7420 $substitutionarray['__THIRDPARTY_ZIP__'] = $object->zip ?? '';
7421 $substitutionarray['__THIRDPARTY_TOWN__'] = $object->town ?? '';
7422 $substitutionarray['__THIRDPARTY_STATE__'] = $object->state ?? '';
7423 $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = ($object->country_id > 0 ? $object->country_id : '');
7424 $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = $object->country_code;
7425 $substitutionarray['__THIRDPARTY_IDPROF1__'] = $object->idprof1 ?? '';
7426 $substitutionarray['__THIRDPARTY_IDPROF2__'] = $object->idprof2 ?? '';
7427 $substitutionarray['__THIRDPARTY_IDPROF3__'] = $object->idprof3 ?? '';
7428 $substitutionarray['__THIRDPARTY_IDPROF4__'] = $object->idprof4 ?? '';
7429 $substitutionarray['__THIRDPARTY_IDPROF5__'] = $object->idprof5 ?? '';
7430 $substitutionarray['__THIRDPARTY_IDPROF6__'] = $object->idprof6 ?? '';
7431 $substitutionarray['__THIRDPARTY_TVAINTRA__'] = $object->tva_intra ?? '';
7432 $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = dol_htmlentitiesbr($object->note_public ?? '');
7433 $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = dol_htmlentitiesbr($object->note_private ?? '');
7434 } elseif (is_object($object) && is_object($object->thirdparty)) {
7435 $substitutionarray['__THIRDPARTY_ID__'] = $object->thirdparty->id ?? '';
7436 $substitutionarray['__THIRDPARTY_NAME__'] = $object->thirdparty->name ?? '';
7437 $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = $object->thirdparty->name_alias ?? '';
7438 $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = $object->thirdparty->code_client ?? '';
7439 $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = $object->thirdparty->code_fournisseur ?? '';
7440 $substitutionarray['__THIRDPARTY_EMAIL__'] = $object->thirdparty->email ?? '';
7441 $substitutionarray['__THIRDPARTY_EMAIL_URLENCODED__'] = urlencode($object->thirdparty->email ?? '');
7442 $substitutionarray['__THIRDPARTY_PHONE__'] = dol_print_phone($object->thirdparty->phone ?? '');
7443 $substitutionarray['__THIRDPARTY_FAX__'] = dol_print_phone($object->thirdparty->fax ?? '');
7444 $substitutionarray['__THIRDPARTY_ADDRESS__'] = $object->thirdparty->address ?? '';
7445 $substitutionarray['__THIRDPARTY_ZIP__'] = $object->thirdparty->zip ?? '';
7446 $substitutionarray['__THIRDPARTY_TOWN__'] = $object->thirdparty->town ?? '';
7447 $substitutionarray['__THIRDPARTY_STATE__'] = $object->thirdparty->state ?? '';
7448 $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = ($object->thirdparty->country_id > 0 ? $object->thirdparty->country_id : '');
7449 $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = $object->thirdparty->country_code ?? '';
7450 $substitutionarray['__THIRDPARTY_IDPROF1__'] = $object->thirdparty->idprof1 ?? '';
7451 $substitutionarray['__THIRDPARTY_IDPROF2__'] = $object->thirdparty->idprof2 ?? '';
7452 $substitutionarray['__THIRDPARTY_IDPROF3__'] = $object->thirdparty->idprof3 ?? '';
7453 $substitutionarray['__THIRDPARTY_IDPROF4__'] = $object->thirdparty->idprof4 ?? '';
7454 $substitutionarray['__THIRDPARTY_IDPROF5__'] = $object->thirdparty->idprof5 ?? '';
7455 $substitutionarray['__THIRDPARTY_IDPROF6__'] = $object->thirdparty->idprof6 ?? '';
7456 $substitutionarray['__THIRDPARTY_TVAINTRA__'] = $object->thirdparty->tva_intra ?? '';
7457 $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = dol_htmlentitiesbr($object->thirdparty->note_public ?? '');
7458 $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = dol_htmlentitiesbr($object->thirdparty->note_private ?? '');
7459 }
7460
7461 if (is_object($object) && $object->element == 'recruitmentcandidature') {
7462 '@phan-var-force RecruitmentCandidature $object';
7464 $substitutionarray['__CANDIDATE_FULLNAME__'] = $object->getFullName($outputlangs);
7465 $substitutionarray['__CANDIDATE_FIRSTNAME__'] = isset($object->firstname) ? $object->firstname : '';
7466 $substitutionarray['__CANDIDATE_LASTNAME__'] = isset($object->lastname) ? $object->lastname : '';
7467 }
7468 if (is_object($object) && $object->element == 'conferenceorboothattendee') {
7469 '@phan-var-force ConferenceOrBoothAttendee $object';
7471 $substitutionarray['__ATTENDEE_FULLNAME__'] = $object->getFullName($outputlangs);
7472 $substitutionarray['__ATTENDEE_FIRSTNAME__'] = isset($object->firstname) ? $object->firstname : '';
7473 $substitutionarray['__ATTENDEE_LASTNAME__'] = isset($object->lastname) ? $object->lastname : '';
7474 }
7475
7476 if (is_object($object) && $object->element == 'project') {
7477 '@phan-var-force Project $object';
7479 $substitutionarray['__PROJECT_ID__'] = $object->id;
7480 $substitutionarray['__PROJECT_REF__'] = $object->ref;
7481 $substitutionarray['__PROJECT_NAME__'] = $object->title;
7482 } elseif (is_object($object)) {
7483 $project = null;
7484 if (!empty($object->project)) {
7485 $project = $object->project;
7486 }
7487 if (!is_null($project) && is_object($project)) {
7488 $substitutionarray['__PROJECT_ID__'] = $project->id;
7489 $substitutionarray['__PROJECT_REF__'] = $project->ref;
7490 $substitutionarray['__PROJECT_NAME__'] = $project->title;
7491 } else {
7492 // can substitute variables for project : uses lazy load in "make_substitutions" method
7493 $project_id = 0;
7494 if (!empty($object->fk_project) && $object->fk_project > 0) {
7495 $project_id = $object->fk_project;
7496 } elseif (!empty($object->fk_projet) && $object->fk_projet > 0) {
7497 $project_id = $object->fk_project;
7498 }
7499 if ($project_id > 0) {
7500 // path:class:method:id
7501 $substitutionarray['__PROJECT_ID__@lazyload'] = '/projet/class/project.class.php:Project:fetchAndSetSubstitution:' . $project_id;
7502 $substitutionarray['__PROJECT_REF__@lazyload'] = '/projet/class/project.class.php:Project:fetchAndSetSubstitution:' . $project_id;
7503 $substitutionarray['__PROJECT_NAME__@lazyload'] = '/projet/class/project.class.php:Project:fetchAndSetSubstitution:' . $project_id;
7504 }
7505 }
7506 }
7507
7508 if (is_object($object) && $object->element == 'facture') {
7509 '@phan-var-force Facture $object';
7511 $substitutionarray['__INVOICE_SITUATION_NUMBER__'] = isset($object->situation_counter) ? $object->situation_counter : '';
7512 }
7513 if (is_object($object) && $object->element == 'shipping') {
7514 '@phan-var-force Expedition $object';
7516 $substitutionarray['__SHIPPINGTRACKNUM__'] = $object->tracking_number;
7517 $substitutionarray['__SHIPPINGTRACKNUMURL__'] = $object->tracking_url;
7518 $substitutionarray['__SHIPPINGMETHOD__'] = $object->shipping_method;
7519 }
7520 if (is_object($object) && $object->element == 'reception') {
7521 '@phan-var-force Reception $object';
7523 $substitutionarray['__RECEPTIONTRACKNUM__'] = $object->tracking_number;
7524 $substitutionarray['__RECEPTIONTRACKNUMURL__'] = $object->tracking_url;
7525 }
7526
7527 if (is_object($object) && $object->element == 'contrat' && $object->id > 0 && is_array($object->lines)) {
7528 '@phan-var-force Contrat $object';
7530 $dateplannedstart = '';
7531 $datenextexpiration = '';
7532 foreach ($object->lines as $line) {
7533 if ($line->date_start > $dateplannedstart) {
7534 $dateplannedstart = $line->date_start;
7535 }
7536 if ($line->statut == 4 && $line->date_end && (!$datenextexpiration || $line->date_end < $datenextexpiration)) {
7537 $datenextexpiration = $line->date_end;
7538 }
7539 }
7540 $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = dol_print_date($dateplannedstart, 'day');
7541 $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE_RFC__'] = dol_print_date($dateplannedstart, 'dayrfc');
7542 $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = dol_print_date($dateplannedstart, 'standard');
7543
7544 $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = dol_print_date($datenextexpiration, 'day');
7545 $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE_RFC__'] = dol_print_date($datenextexpiration, 'dayrfc');
7546 $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = dol_print_date($datenextexpiration, 'standard');
7547 }
7548 // add substitution variables for ticket
7549 if (is_object($object) && $object->element == 'ticket') {
7550 '@phan-var-force Ticket $object';
7552 $substitutionarray['__TICKET_TRACKID__'] = $object->track_id;
7553 $substitutionarray['__TICKET_SUBJECT__'] = $object->subject;
7554 $substitutionarray['__TICKET_TYPE__'] = $object->type_code;
7555 $substitutionarray['__TICKET_SEVERITY__'] = $object->severity_code;
7556 $substitutionarray['__TICKET_CATEGORY__'] = $object->category_code; // For backward compatibility
7557 $substitutionarray['__TICKET_ANALYTIC_CODE__'] = $object->category_code;
7558 $substitutionarray['__TICKET_MESSAGE__'] = $object->message;
7559 $substitutionarray['__TICKET_PROGRESSION__'] = $object->progress;
7560 // __TICKET_TYPE__, __TICKET_SEVERITY__ and __TICKET_CATEGORY__ hold the raw codes.
7561 // An email usually needs the human readable labels instead.
7562 $substitutionarray['__TICKET_TYPE_LABEL__'] = empty($object->type_code) ? '' : $outputlangs->getLabelFromKey($db, 'TicketTypeShort'.$object->type_code, 'c_ticket_type', 'code', 'label', $object->type_code);
7563 $substitutionarray['__TICKET_SEVERITY_LABEL__'] = empty($object->severity_code) ? '' : $outputlangs->getLabelFromKey($db, 'TicketSeverityShort'.$object->severity_code, 'c_ticket_severity', 'code', 'label', $object->severity_code);
7564 $substitutionarray['__TICKET_CATEGORY_LABEL__'] = empty($object->category_code) ? '' : $outputlangs->getLabelFromKey($db, 'TicketCategoryShort'.$object->category_code, 'c_ticket_category', 'code', 'label', $object->category_code);
7565 $substitutionarray['__TICKET_PUBLIC_URL__'] = getDolGlobalString('TICKET_URL_PUBLIC_INTERFACE', dol_buildpath('/public/ticket/', 2)).'view.php?track_id='.urlencode((string) $object->track_id);
7566 $substitutionarray['__TICKET_MANAGEMENT_URL__'] = dol_buildpath('/ticket/card.php', 2).'?track_id='.urlencode((string) $object->track_id);
7567 $userstat = new User($db);
7568 if ($object->fk_user_assign > 0) {
7569 $userstat->fetch($object->fk_user_assign);
7570 $substitutionarray['__TICKET_USER_ASSIGN__'] = dolGetFirstLastname($userstat->firstname, $userstat->lastname);
7571 }
7572
7573 if ($object->fk_user_create > 0) {
7574 $userstat->fetch($object->fk_user_create);
7575 $substitutionarray['__USER_CREATE__'] = dolGetFirstLastname($userstat->firstname, $userstat->lastname);
7576 }
7577 }
7578
7579 // Create dynamic tags for __EXTRAFIELD_FIELD__
7580 if ($object->table_element && $object->id > 0) {
7581 if (!is_object($extrafields)) {
7582 $extrafields = new ExtraFields($db);
7583 }
7584 $extrafields->fetch_name_optionals_label($object->table_element, true);
7585
7586 if ($object->fetch_optionals() > 0) { // @FIXME: Remove this, the fetch should have been done already, by the caller of getCommonSubstitutionArray()
7587 if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) {
7588 foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) {
7589 if ($extrafields->attributes[$object->table_element]['type'][$key] == 'date') {
7590 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '__'] = dol_print_date($object->array_options['options_' . $key], 'day');
7591 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '_LOCALE__'] = dol_print_date($object->array_options['options_' . $key], 'day', 'tzserver', $outputlangs);
7592 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '_RFC__'] = dol_print_date($object->array_options['options_' . $key], 'dayrfc');
7593 } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'datetime') {
7594 $datetime = $object->array_options['options_' . $key];
7595 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour') : '');
7596 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour', 'tzserver', $outputlangs) : '');
7597 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '_DAY_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'day', 'tzserver', $outputlangs) : '');
7598 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '_RFC__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhourrfc') : '');
7599 } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'phone') {
7600 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '__'] = dol_print_phone($object->array_options['options_' . $key]);
7601 } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'price') {
7602 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '__'] = $object->array_options['options_' . $key];
7603 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '_FORMATED__'] = price($object->array_options['options_' . $key]); // For compatibility
7604 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '_FORMATTED__'] = price($object->array_options['options_' . $key]);
7605 } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'select') {
7606 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '__'] = !empty($object->array_options['options_' . $key]) ? $object->array_options['options_' . $key] : '';
7607 $val = $extrafields->attributes[$object->table_element]['param'][$key]['options'][$object->array_options['options_'.$key]] ?? $object->array_options['options_'.$key];
7608 $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LABEL__'] = $val;
7609 } elseif ($extrafields->attributes[$object->table_element]['type'][$key] != 'separator') {
7610 $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '__'] = !empty($object->array_options['options_' . $key]) ? $object->array_options['options_' . $key] : '';
7611 }
7612 }
7613 }
7614 }
7615 }
7616
7617 // Complete substitution array with the url to make online payment
7618 if (empty($substitutionarray['__REF__'])) {
7619 $paymenturl = '';
7620 } else {
7621 // Set the online payment url link into __ONLINE_PAYMENT_URL__ key
7622 require_once DOL_DOCUMENT_ROOT . '/core/lib/payments.lib.php';
7623 $outputlangs->loadLangs(array('paypal', 'other'));
7624
7625 $amounttouse = 0;
7626 $typeforonlinepayment = 'free';
7627 if (is_object($object) && $object->element == 'commande') {
7628 $typeforonlinepayment = 'order';
7629 }
7630 if (is_object($object) && $object->element == 'facture') {
7631 $typeforonlinepayment = 'invoice';
7632 }
7633 if (is_object($object) && $object->element == 'member') {
7634 $typeforonlinepayment = 'member';
7635 if (!empty($object->last_subscription_amount)) {
7636 $amounttouse = $object->last_subscription_amount;
7637 }
7638 }
7639 if (is_object($object) && $object->element == 'contrat') {
7640 $typeforonlinepayment = 'contract';
7641 }
7642 if (is_object($object) && $object->element == 'fichinter') {
7643 $typeforonlinepayment = 'ficheinter';
7644 }
7645
7646 $url = getOnlinePaymentUrl(0, $typeforonlinepayment, $substitutionarray['__REF__'], (float) $amounttouse);
7647 $paymenturl = $url;
7648 }
7649
7650 if ($object->id > 0) {
7651 $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = ($paymenturl ? str_replace('\n', "\n", $outputlangs->trans("PredefinedMailContentLink", $paymenturl)) : '');
7652 $substitutionarray['__ONLINE_PAYMENT_URL__'] = $paymenturl;
7653
7654 // Show structured communication
7655 if (getDolGlobalString('INVOICE_PAYMENT_ENABLE_STRUCTURED_COMMUNICATION') && $object->element == 'facture') {
7656 include_once DOL_DOCUMENT_ROOT . '/core/lib/functions_be.lib.php';
7657 $substitutionarray['__PAYMENT_STRUCTURED_COMMUNICATION__'] = dolBECalculateStructuredCommunication((string) $object->ref, $object->type);
7658 }
7659
7660 if (getDolGlobalString('PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD') && is_object($object) && $object->element == 'propal') {
7661 $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
7662 } else {
7663 $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = '';
7664 }
7665 if (getDolGlobalString('ORDER_ALLOW_EXTERNAL_DOWNLOAD') && is_object($object) && $object->element == 'commande') {
7666 $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = $object->getLastMainDocLink($object->element);
7667 } else {
7668 $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = '';
7669 }
7670 if (getDolGlobalString('INVOICE_ALLOW_EXTERNAL_DOWNLOAD') && is_object($object) && $object->element == 'facture') {
7671 $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = $object->getLastMainDocLink($object->element);
7672 } else {
7673 $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = '';
7674 }
7675 if (getDolGlobalString('CONTRACT_ALLOW_EXTERNAL_DOWNLOAD') && is_object($object) && $object->element == 'contrat') {
7676 $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = $object->getLastMainDocLink($object->element);
7677 } else {
7678 $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = '';
7679 }
7680 if (getDolGlobalString('FICHINTER_ALLOW_EXTERNAL_DOWNLOAD') && is_object($object) && $object->element == 'fichinter') {
7681 $substitutionarray['__DIRECTDOWNLOAD_URL_FICHINTER__'] = $object->getLastMainDocLink($object->element);
7682 } else {
7683 $substitutionarray['__DIRECTDOWNLOAD_URL_FICHINTER__'] = '';
7684 }
7685 if (getDolGlobalString('SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD') && is_object($object) && $object->element == 'supplier_proposal') {
7686 $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
7687 } else {
7688 $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = '';
7689 }
7690 if (getDolGlobalString('SUPPLIER_ORDER_ALLOW_EXTERNAL_DOWNLOAD') && is_object($object) && $object->element == 'order_supplier') {
7691 $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_ORDER__'] = $object->getLastMainDocLink($object->element);
7692 } else {
7693 $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_ORDER__'] = '';
7694 }
7695 if (getDolGlobalString('SUPPLIER_INVOICE_ALLOW_EXTERNAL_DOWNLOAD') && is_object($object) && $object->element == 'invoice_supplier') {
7696 $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_INVOICE__'] = $object->getLastMainDocLink($object->element);
7697 } else {
7698 $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_INVOICE__'] = '';
7699 }
7700
7701 if (is_object($object) && $object->element == 'propal') {
7702 '@phan-var-force Propal $object';
7704 $substitutionarray['__URL_PROPOSAL__'] = DOL_MAIN_URL_ROOT . "/comm/propal/card.php?id=" . $object->id;
7705 require_once DOL_DOCUMENT_ROOT . '/core/lib/signature.lib.php';
7706 $substitutionarray['__ONLINE_SIGN_URL__'] = getOnlineSignatureUrl(0, 'proposal', (string) $object->ref, 1, $object);
7707 }
7708 if (is_object($object) && $object->element == 'commande') {
7709 '@phan-var-force Commande $object';
7711 $substitutionarray['__URL_ORDER__'] = DOL_MAIN_URL_ROOT . "/commande/card.php?id=" . $object->id;
7712 }
7713 if (is_object($object) && $object->element == 'facture') {
7714 '@phan-var-force Facture $object';
7716 $substitutionarray['__URL_INVOICE__'] = DOL_MAIN_URL_ROOT . "/compta/facture/card.php?id=" . $object->id;
7717 }
7718 if (is_object($object) && $object->element == 'contrat') {
7719 '@phan-var-force Contrat $object';
7721 $substitutionarray['__URL_CONTRACT__'] = DOL_MAIN_URL_ROOT . "/contrat/card.php?id=" . $object->id;
7722 require_once DOL_DOCUMENT_ROOT . '/core/lib/signature.lib.php';
7723 $substitutionarray['__ONLINE_SIGN_URL__'] = getOnlineSignatureUrl(0, 'contract', (string) $object->ref, 1, $object);
7724 }
7725 if (is_object($object) && $object->element == 'fichinter') {
7726 '@phan-var-force Fichinter $object';
7728 $substitutionarray['__URL_FICHINTER__'] = DOL_MAIN_URL_ROOT . "/fichinter/card.php?id=" . $object->id;
7729 require_once DOL_DOCUMENT_ROOT . '/core/lib/signature.lib.php';
7730 $substitutionarray['__ONLINE_SIGN_FICHINTER_URL__'] = getOnlineSignatureUrl(0, 'fichinter', (string) $object->ref, 1, $object);
7731 }
7732 if (is_object($object) && $object->element == 'supplier_proposal') {
7733 '@phan-var-force SupplierProposal $object';
7735 $substitutionarray['__URL_SUPPLIER_PROPOSAL__'] = DOL_MAIN_URL_ROOT . "/supplier_proposal/card.php?id=" . $object->id;
7736 }
7737 if (is_object($object) && $object->element == 'invoice_supplier') {
7738 '@phan-var-force FactureFournisseur $object';
7740 $substitutionarray['__URL_SUPPLIER_INVOICE__'] = DOL_MAIN_URL_ROOT . "/fourn/facture/card.php?id=" . $object->id;
7741 }
7742 if (is_object($object) && $object->element == 'payment_supplier') {
7743 '@phan-var-force PaiementFourn $object';
7745 //print_r($object);
7746 $liste_factures = [];
7747 $total = 0;
7748
7749 // @FIXME We must not have any repeated SQL access into this function.
7750 $sql = 'SELECT f.ref,f.multicurrency_code as f_mccode, pf.*
7751 FROM '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf
7752 JOIN '.MAIN_DB_PREFIX.'facture_fourn as f ON pf.fk_facturefourn = f.rowid
7753 WHERE pf.fk_paiementfourn = '.((int) $object->id);
7754
7755 $resql = $db->query($sql);
7756 if ($resql) {
7757 while ($objp = $db->fetch_object($resql)) {
7758 $liste_factures[] = ' - '.$outputlangs->trans('Invoice').' '. $objp->ref.' '.$outputlangs->trans('AmountPayed').' '.price($objp->multicurrency_amount, 0, $outputlangs, 0, -1, -1, $objp->multicurrency_code);
7759 }
7760 }
7761 $substitutionarray['__SUPPLIER_PAYMENT_INVOICES_LIST__'] = implode("\n", $liste_factures);
7762 ;
7763 $substitutionarray['__SUPPLIER_PAYMENT_INVOICES_TOTAL__'] = price($object->multicurrency_amount, 0, $outputlangs, 0, -1, -1, $object->multicurrency_code ? $object->multicurrency_code : $conf->currency);
7764 }
7765 if (is_object($object) && $object->element == 'shipping') {
7766 '@phan-var-force Expedition $object';
7768 $substitutionarray['__URL_SHIPMENT__'] = DOL_MAIN_URL_ROOT . "/expedition/card.php?id=" . $object->id;
7769 if (getDolGlobalInt('EXPEDITION_ALLOW_ONLINESIGN')) {
7770 require_once DOL_DOCUMENT_ROOT . '/core/lib/signature.lib.php';
7771 $substitutionarray['__ONLINE_SIGN_URL__'] = getOnlineSignatureUrl(0, 'expedition', (string) $object->ref, 1, $object);
7772 }
7773 }
7774 }
7775
7776 if (is_object($object) && $object->element == 'action') {
7777 '@phan-var-force ActionComm $object';
7779 $substitutionarray['__EVENT_LABEL__'] = $object->label;
7780 $substitutionarray['__EVENT_DESCRIPTION__'] = $object->note;
7781 $substitutionarray['__EVENT_TYPE__'] = $outputlangs->trans("Action" . $object->type_code);
7782 $substitutionarray['__EVENT_DATE__'] = dol_print_date($object->datep, 'day', 'auto', $outputlangs);
7783 $substitutionarray['__EVENT_TIME__'] = dol_print_date($object->datep, 'hour', 'auto', $outputlangs);
7784 $substitutionarray['__EVENT_DATE_TZUSER__'] = dol_print_date($object->datep, 'day', 'tzuserrel', $outputlangs);
7785 $substitutionarray['__EVENT_TIME_TZUSER__'] = dol_print_date($object->datep, 'hour', 'tzuserrel', $outputlangs);
7786 }
7787 }
7788 }
7789
7790 if ((empty($exclude) || !in_array('objectamount', $exclude)) && (empty($include) || in_array('objectamount', $include))) {
7791 '@phan-var-force Facture|FactureRec $object';
7793 include_once DOL_DOCUMENT_ROOT . '/core/lib/functionsnumtoword.lib.php';
7794
7795 $substitutionarray['__DATE_YMD__'] = is_object($object) ? (isset($object->date) ? dol_print_date($object->date, 'day', false, $outputlangs) : null) : '';
7796 $substitutionarray['__DATE_DUE_YMD__'] = is_object($object) ? (isset($object->date_lim_reglement) ? dol_print_date($object->date_lim_reglement, 'day', false, $outputlangs) : null) : '';
7797 $substitutionarray['__DATE_YMD_TEXT__'] = is_object($object) ? (isset($object->date) ? dol_print_date($object->date, 'daytext', false, $outputlangs) : null) : '';
7798 $substitutionarray['__DATE_DUE_YMD_TEXT__'] = is_object($object) ? (isset($object->date_lim_reglement) ? dol_print_date($object->date_lim_reglement, 'daytext', false, $outputlangs) : null) : '';
7799
7800 $already_payed_all = 0;
7801 if (is_object($object) && ($object instanceof Facture)) {
7802 $already_payed_all = $object->totalpaid + $object->totaldeposits + $object->totalcreditnotes;
7803 }
7804
7805 $substitutionarray['__SIMPLE_HTML_TABLE__'] = is_object($object) && !empty($object->lines) ? showSimpleHTMLTable($outputlangs, $object) : "";
7806 $substitutionarray['__AMOUNT_EXCL_TAX__'] = is_object($object) ? $object->total_ht : '';
7807 $substitutionarray['__AMOUNT_EXCL_TAX_TEXT__'] = is_object($object) ? dol_convertToWord($object->total_ht, $outputlangs, '', true) : '';
7808 $substitutionarray['__AMOUNT_EXCL_TAX_TEXTCURRENCY__'] = is_object($object) ? dol_convertToWord($object->total_ht, $outputlangs, $conf->currency, true) : '';
7809
7810 $substitutionarray['__AMOUNT__'] = is_object($object) ? $object->total_ttc : '';
7811 $substitutionarray['__AMOUNT_TEXT__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, '', true) : '';
7812 $substitutionarray['__AMOUNT_TEXTCURRENCY__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, $conf->currency, true) : '';
7813
7814 $substitutionarray['__DEPOSIT_PERCENT__'] = is_object($object) ? $object->deposit_percent : '';
7815 $substitutionarray['__DEPOSIT_AMOUNT__'] = is_object($object) ? price2num($object->total_ttc * ($object->deposit_percent / 100), 'MT') : '';
7816
7817 $substitutionarray['__AMOUNT_REMAIN__'] = is_object($object) ? price2num($object->total_ttc - $already_payed_all, 'MT') : '';
7818
7819 $substitutionarray['__AMOUNT_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
7820 $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)) : '';
7821 $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)) : '';
7822
7823 $mysocuselocaltax1 = false;
7824 $mysocuselocaltax2 = false;
7825 if ($mysoc instanceof Societe && !empty($mysoc->country_code)) {
7826 $tmparray = $mysoc->useLocalTax(-1);
7827 if (is_array($tmparray)) {
7828 $mysocuselocaltax1 = $tmparray[1];
7829 $mysocuselocaltax2 = $tmparray[2];
7830 }
7831 }
7832
7833 // Local taxes
7834 if ($onlykey != 2 || $mysocuselocaltax1) {
7835 $substitutionarray['__AMOUNT_TAX2__'] = is_object($object) ? $object->total_localtax1 : '';
7836 }
7837 if ($onlykey != 2 || $mysocuselocaltax2) {
7838 $substitutionarray['__AMOUNT_TAX3__'] = is_object($object) ? $object->total_localtax2 : '';
7839 }
7840
7841 // Amount keys formatted in a currency
7842 $substitutionarray['__AMOUNT_EXCL_TAX_FORMATTED__'] = is_object($object) ? ($object->total_ht ? price($object->total_ht, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
7843 $substitutionarray['__AMOUNT_FORMATTED__'] = is_object($object) ? ($object->total_ttc ? price($object->total_ttc, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
7844 $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) : '';
7845 $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)) : '';
7846 if ($onlykey != 2 || $mysocuselocaltax1) {
7847 $substitutionarray['__AMOUNT_TAX2_FORMATTED__'] = is_object($object) ? ($object->total_localtax1 ? price($object->total_localtax1, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
7848 }
7849 if ($onlykey != 2 || $mysocuselocaltax2) {
7850 $substitutionarray['__AMOUNT_TAX3_FORMATTED__'] = is_object($object) ? ($object->total_localtax2 ? price($object->total_localtax2, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
7851 }
7852 // Amount keys formatted in a currency (with the typo error for backward compatibility)
7853 if ($onlykey != 2) {
7854 $substitutionarray['__AMOUNT_EXCL_TAX_FORMATED__'] = $substitutionarray['__AMOUNT_EXCL_TAX_FORMATTED__'];
7855 $substitutionarray['__AMOUNT_FORMATED__'] = $substitutionarray['__AMOUNT_FORMATTED__'];
7856 $substitutionarray['__AMOUNT_REMAIN_FORMATED__'] = $substitutionarray['__AMOUNT_REMAIN_FORMATTED__'];
7857 $substitutionarray['__AMOUNT_VAT_FORMATED__'] = $substitutionarray['__AMOUNT_VAT_FORMATTED__'];
7858 if ($mysocuselocaltax1) {
7859 $substitutionarray['__AMOUNT_TAX2_FORMATED__'] = $substitutionarray['__AMOUNT_TAX2_FORMATTED__'];
7860 }
7861 if ($mysoc->useLocalTax2) {
7862 $substitutionarray['__AMOUNT_TAX3_FORMATED__'] = $substitutionarray['__AMOUNT_TAX3_FORMATTED__'];
7863 }
7864 }
7865
7866 $substitutionarray['__AMOUNT_MULTICURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? $object->multicurrency_total_ttc : '';
7867 $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) : '';
7868 $substitutionarray['__AMOUNT_MULTICURRENCY_TEXT__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, '', true) : '';
7869 $substitutionarray['__AMOUNT_MULTICURRENCY_TEXTCURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, $object->multicurrency_code, true) : '';
7870 $substitutionarray['__MULTICURRENCY_CODE__'] = (is_object($object) && isset($object->multicurrency_code)) ? $object->multicurrency_code : '';
7871 // TODO Add other keys for foreign multicurrency
7872
7873 // For backward compatibility
7874 if ($onlykey != 2) {
7875 $substitutionarray['__TOTAL_TTC__'] = is_object($object) ? $object->total_ttc : '';
7876 $substitutionarray['__TOTAL_HT__'] = is_object($object) ? $object->total_ht : '';
7877 $substitutionarray['__TOTAL_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
7878 }
7879 }
7880
7881 if ((empty($exclude) || !in_array('date', $exclude)) && (empty($include) || in_array('date', $include))) {
7882 include_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
7883
7884 $now = dol_now();
7885
7886 $tmp = dol_getdate($now, true);
7887 $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
7888 $tmp3 = dol_get_prev_month($tmp['mon'], $tmp['year']);
7889 $tmp4 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
7890 $tmp5 = dol_get_next_month($tmp['mon'], $tmp['year']);
7891
7892 $daytext = $outputlangs->trans('Day' . $tmp['wday']);
7893
7894 $substitutionarray = array_merge($substitutionarray, array(
7895 '__NOW_TMS__' => (string) $now, // Must be the string that represent the int
7896 '__NOW_TMS_YMD__' => dol_print_date($now, 'day', 'auto', $outputlangs),
7897 '__DAY__' => (string) $tmp['mday'],
7898 '__DAY_TEXT__' => $daytext, // Monday
7899 '__DAY_TEXT_SHORT__' => dol_trunc($daytext, 3, 'right', 'UTF-8', 1), // Mon
7900 '__DAY_TEXT_MIN__' => dol_trunc($daytext, 1, 'right', 'UTF-8', 1), // M
7901 '__MONTH__' => (string) $tmp['mon'],
7902 '__MONTH_TEXT__' => $outputlangs->transnoentitiesnoconv('Month' . sprintf("%02d", $tmp['mon'])),
7903 '__MONTH_TEXT_SHORT__' => $outputlangs->transnoentitiesnoconv('MonthShort' . sprintf("%02d", $tmp['mon'])),
7904 '__MONTH_TEXT_MIN__' => $outputlangs->transnoentitiesnoconv('MonthVeryShort' . sprintf("%02d", $tmp['mon'])),
7905 '__YEAR__' => (string) $tmp['year'],
7906 '__YEAR_PREVIOUS_MONTH__' => (string) $tmp3['year'],
7907 '__YEAR_NEXT_MONTH__' => (string) $tmp5['year'],
7908 '__PREVIOUS_DAY__' => (string) $tmp2['day'],
7909 '__PREVIOUS_MONTH__' => (string) $tmp3['month'],
7910 '__PREVIOUS_MONTH_TEXT__' => $outputlangs->transnoentitiesnoconv('Month' . sprintf("%02d", $tmp3['month'])),
7911 '__PREVIOUS_MONTH_TEXT_SHORT__' => $outputlangs->transnoentitiesnoconv('MonthShort' . sprintf("%02d", $tmp3['month'])),
7912 '__PREVIOUS_MONTH_TEXT_MIN__' => $outputlangs->transnoentitiesnoconv('MonthVeryShort' . sprintf("%02d", $tmp3['month'])),
7913 '__PREVIOUS_YEAR__' => (string) ($tmp['year'] - 1),
7914 '__NEXT_DAY__' => (string) $tmp4['day'],
7915 '__NEXT_MONTH__' => (string) $tmp5['month'],
7916 '__NEXT_MONTH_TEXT__' => $outputlangs->transnoentitiesnoconv('Month' . sprintf("%02d", $tmp5['month'])),
7917 '__NEXT_MONTH_TEXT_SHORT__' => $outputlangs->transnoentitiesnoconv('MonthShort' . sprintf("%02d", $tmp5['month'])),
7918 '__NEXT_MONTH_TEXT_MIN__' => $outputlangs->transnoentitiesnoconv('MonthVeryShort' . sprintf("%02d", $tmp5['month'])),
7919 '__NEXT_YEAR__' => (string) ($tmp['year'] + 1),
7920 ));
7921 }
7922
7923 if (isModEnabled('multicompany')) {
7924 $substitutionarray = array_merge($substitutionarray, array('__ENTITY_ID__' => $conf->entity));
7925 }
7926 if ((empty($exclude) || !in_array('system', $exclude)) && (empty($include) || in_array('user', $include))) {
7927 $substitutionarray['__DOL_MAIN_URL_ROOT__'] = DOL_MAIN_URL_ROOT;
7928 $substitutionarray['__(AnyTranslationKey)__'] = $outputlangs->transnoentitiesnoconv('TranslationOfKey');
7929 $substitutionarray['__(AnyTranslationKey|langfile)__'] = $outputlangs->transnoentitiesnoconv('TranslationOfKey') . ' (load also language file before)';
7930 $substitutionarray['__[AnyConstantKey]__'] = $outputlangs->transnoentitiesnoconv('ValueOfConstantKey');
7931 }
7932
7933 // Note: The lazyload variables are replaced only during the call by make_substitutions, and only if necessary
7934
7935 return $substitutionarray;
7936}
7937
7954function make_substitutions($text, $substitutionarray, $outputlangs = null, $converttextinhtmlifnecessary = 0)
7955{
7956 global $db, $langs;
7957
7958 if (!is_array($substitutionarray)) {
7959 return 'ErrorBadParameterSubstitutionArrayWhenCalling_make_substitutions';
7960 }
7961
7962 if (empty($outputlangs)) {
7963 $outputlangs = $langs;
7964 }
7965
7966 // Is initial text HTML or simple text ?
7967 $msgishtml = 0;
7968 if (dol_textishtml($text, 1)) {
7969 $msgishtml = 1;
7970 }
7971
7972 // Make substitution for language keys: __(AnyTranslationKey)__ or __(AnyTranslationKey|langfile)__
7973 if (is_object($outputlangs)) {
7974 $reg = array();
7975 while (preg_match('/__\‍(([^\‍)]+)\‍)__/', $text, $reg)) {
7976 // If key is __(TranslationKey|langfile)__, then force load of langfile.lang
7977 $tmp = explode('|', $reg[1]);
7978 if (!empty($tmp[1])) {
7979 $outputlangs->load($tmp[1]);
7980 }
7981
7982 $value = $outputlangs->transnoentitiesnoconv($reg[1]);
7983
7984 if (empty($converttextinhtmlifnecessary)) {
7985 // convert $newval into HTML is necessary
7986 $text = preg_replace('/__\‍(' . preg_quote($reg[1], '/') . '\‍)__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
7987 } else {
7988 if (preg_match('/__\‍(' . preg_quote($reg[1], '/') . '\‍)__/', $text)) { // If found, so replacement will be done later
7989 if (! $msgishtml) {
7990 $valueishtml = dol_textishtml($value, 1);
7991 //var_dump("valueishtml=".$valueishtml);
7992
7993 if ($valueishtml) {
7994 $text = dol_htmlentitiesbr($text);
7995 $msgishtml = 1;
7996 }
7997 } else {
7998 $value = dol_nl2br((string) $value);
7999 }
8000 }
8001 $text = preg_replace('/__\‍(' . preg_quote($reg[1], '/') . '\‍)__/', $value, $text);
8002 }
8003 }
8004 }
8005
8006 // Make substitution for constant keys.
8007 // Must be after the substitution of translation, so if the text of translation contains a string __[xxx]__, it is also converted.
8008 $reg = array();
8009 while (preg_match('/__\[([^\]]+)\]__/', $text, $reg)) {
8010 $originalkeyfound = $reg[1];
8011 $keyfound = preg_replace('/\|urlencode$/', '', $originalkeyfound);
8012
8013 if (isASecretKey($keyfound)) {
8014 $value = '*****forbidden*****';
8015 } else {
8016 $value = getDolGlobalString($keyfound);
8017 // Execute some functions on value of substitution key
8018 if (preg_match('/\|urlencode$/', $originalkeyfound)) {
8019 $value = urlencode($value);
8020 }
8021 }
8022
8023 if (empty($converttextinhtmlifnecessary)) {
8024 // convert $newval into HTML is necessary
8025 $text = preg_replace('/__\[' . preg_quote($originalkeyfound, '/') . '\]__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
8026 } else {
8027 if (preg_match('/__\[' . preg_quote($originalkeyfound, '/') . '\]__/', $text)) { // If found, so replacement will be done later
8028 if (! $msgishtml) {
8029 $valueishtml = dol_textishtml($value, 1);
8030
8031 if ($valueishtml) {
8032 $text = dol_htmlentitiesbr($text);
8033 $msgishtml = 1;
8034 }
8035 } else {
8036 $value = dol_nl2br((string) $value);
8037 }
8038 }
8039 $text = preg_replace('/__\[' . preg_quote($originalkeyfound, '/') . '\]__/', $value, $text);
8040 }
8041 }
8042
8043 // Make substitution for array $substitutionarray
8044 foreach ($substitutionarray as $key => $value) {
8045 if (!isset($value)) {
8046 continue; // If value is null, it same than not having substitution key at all into array, we do not replace.
8047 }
8048
8049 if (getDolGlobalString('MAIN_MAIL_DO_NOT_USE_SIGN') && ($key == '__USER_SIGNATURE__' || $key == '__SENDEREMAIL_SIGNATURE__')) {
8050 $value = ''; // Protection
8051 }
8052 if (empty($converttextinhtmlifnecessary)) {
8053 $text = str_replace((string) $key, (string) $value, $text); // Cast to string is needed when value is 123.5 for example
8054 } else {
8055 if (strpos($text, (string) $key) !== false) { // If found, so replacement will be done later
8056 if (! $msgishtml) {
8057 $valueishtml = dol_textishtml($value, 1);
8058
8059 if ($valueishtml) {
8060 $text = dol_htmlentitiesbr($text);
8061 $msgishtml = 1;
8062 }
8063 } else {
8064 $value = dol_nl2br((string) $value);
8065 }
8066 }
8067 $text = str_replace((string) $key, (string) $value, $text); // Cast to string is needed, for 123.5 for example
8068 }
8069 }
8070
8071 /*
8072 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
8073 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.
8074 If no, we don't need to make replacement, so we do nothing.
8075 If yes, we can make the substitution:
8076
8077 include_once $path;
8078 $tmpobj = new $class($db);
8079 $valuetouseforsubstitution = $tmpobj->$method($id, '__XXX__');
8080 And make the replacement of "__XXX__@lazyload" with $valuetouseforsubstitution
8081 */
8082 $memory_object_list = array();
8083 foreach ($substitutionarray as $key => $value) {
8084 $lazy_load_arr = array();
8085 if (preg_match('/(__[A-Z\_]+__)@lazyload$/', $key, $lazy_load_arr)) {
8086 if (!empty($lazy_load_arr[1])) {
8087 $key_to_substitute = $lazy_load_arr[1];
8088 if (preg_match('/' . preg_quote($key_to_substitute, '/') . '/', $text)) {
8089 $param_arr = explode(':', (string) $value);
8090 // path:class:method:id
8091 if (count($param_arr) >= 4) {
8092 $path = $param_arr[0];
8093 $class = $param_arr[1];
8094 $method = $param_arr[2];
8095 $id = (int) $param_arr[3];
8096 $keyinarrayresult = empty($param_arr[4]) ? '' : $param_arr[4];
8097
8098 // load class file and init object list in memory
8099 if (!isset($memory_object_list[$class])) {
8100 if (dol_is_file(DOL_DOCUMENT_ROOT . $path)) {
8101 require_once DOL_DOCUMENT_ROOT . $path;
8102 if (class_exists($class)) {
8103 $memory_object_list[$class] = array(
8104 'list' => array(),
8105 );
8106 }
8107 }
8108 }
8109
8110 // fetch object and set substitution
8111 if (isset($memory_object_list[$class]['list'])) {
8112 if (method_exists($class, $method)) {
8113 if (!isset($memory_object_list[$class]['list'][$id])) {
8114 $tmpobj = new $class($db);
8115 // @phan-suppress-next-line PhanPluginUnknownObjectMethodCall
8116 $tmpvaluetouseforsubstitution = $tmpobj->$method($id, $key_to_substitute);
8117 $memory_object_list[$class]['list'][$id] = $tmpobj;
8118 } else {
8119 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
8120 $tmpobj = $memory_object_list[$class]['list'][$id];
8121 // @phan-suppress-next-line PhanPluginUnknownObjectMethodCall
8122 $tmpvaluetouseforsubstitution = $tmpobj->$method($id, $key_to_substitute, true);
8123 }
8124
8125 if ($keyinarrayresult) {
8126 $valuetouseforsubstitution = (string) $tmpvaluetouseforsubstitution[$keyinarrayresult]; // Cast to string in case value is 123.5 for example
8127 } else {
8128 $valuetouseforsubstitution = (string) $tmpvaluetouseforsubstitution; // Cast to string in case value is 123.5 for example
8129 }
8130 $text = str_replace((string) $key_to_substitute, $valuetouseforsubstitution, $text);
8131 }
8132 }
8133 }
8134 }
8135 }
8136 }
8137 }
8138
8139 return $text;
8140}
8141
8154function complete_substitutions_array(&$substitutionarray, $outputlangs, $object = null, $parameters = null, $callfunc = "completesubstitutionarray")
8155{
8156 global $conf, $user;
8157
8158 require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
8159
8160 // Note: substitution key for each extrafields, using key __EXTRA_XXX__ is already available into the getCommonSubstitutionArray used to build the substitution array.
8161
8162 // Check if there is external substitution to do, requested by plugins
8163 $dirsubstitutions = array_merge(array(), (array) $conf->modules_parts['substitutions']);
8164
8165 foreach ($dirsubstitutions as $reldir) {
8166 $dir = dol_buildpath($reldir, 0);
8167
8168 // Check if directory exists
8169 if (!dol_is_dir($dir)) {
8170 continue;
8171 }
8172
8173 $substitfiles = dol_dir_list($dir, 'files', 0, 'functions_');
8174 foreach ($substitfiles as $substitfile) {
8175 $reg = array();
8176 if (preg_match('/functions_(.*)\.lib\.php/i', $substitfile['name'], $reg)) {
8177 $module = $reg[1];
8178
8179 dol_syslog("Library " . $substitfile['name'] . " found into " . $dir);
8180 // Include the user's functions file
8181 require_once $dir . $substitfile['name'];
8182 // Call the user's function, and only if it is defined
8183 $function_name = $module . "_" . $callfunc;
8184 if (function_exists($function_name)) {
8185 $function_name($substitutionarray, $outputlangs, $object, $parameters);
8186 }
8187 }
8188 }
8189 }
8190 if (getDolGlobalString('ODT_ENABLE_ALL_TAGS_IN_SUBSTITUTIONS')) {
8191 // to list all tags in odt template
8192 $tags = '';
8193 foreach ($substitutionarray as $key => $value) {
8194 $tags .= '{' . $key . '} => ' . $value . "\n";
8195 }
8196 $substitutionarray = array_merge($substitutionarray, array('__ALL_TAGS__' => $tags));
8197 }
8198}
8199
8209function print_date_range($date_start, $date_end, $format = '', $outputlangs = null)
8210{
8211 print get_date_range($date_start, $date_end, $format, $outputlangs);
8212}
8213
8224function get_date_range($date_start, $date_end, $format = '', $outputlangs = null, $withparenthesis = 1)
8225{
8226 global $langs;
8227
8228 $out = '';
8229
8230 if (!is_object($outputlangs)) {
8231 $outputlangs = $langs;
8232 }
8233
8234 if ($date_start && $date_end) {
8235 $out .= ($withparenthesis ? ($withparenthesis == 1 ? ' ' : '').'(' : '') . $outputlangs->transnoentitiesnoconv('DateFromTo', dol_print_date($date_start, $format, false, $outputlangs), dol_print_date($date_end, $format, false, $outputlangs)) . ($withparenthesis ? ')' : '');
8236 }
8237 if ($date_start && !$date_end) {
8238 $out .= ($withparenthesis ? ($withparenthesis == 1 ? ' ' : '').'(' : '') . $outputlangs->transnoentitiesnoconv('DateFrom', dol_print_date($date_start, $format, false, $outputlangs)) . ($withparenthesis ? ')' : '');
8239 }
8240 if (!$date_start && $date_end) {
8241 $out .= ($withparenthesis ? ($withparenthesis == 1 ? ' ' : '').'(' : '') . $outputlangs->transnoentitiesnoconv('DateUntil', dol_print_date($date_end, $format, false, $outputlangs)) . ($withparenthesis ? ')' : '');
8242 }
8243
8244 return $out;
8245}
8246
8255function dolGetFirstLastname($firstname, $lastname, $nameorder = -1)
8256{
8257 $ret = '';
8258 // If order not defined, we use the setup
8259 if ($nameorder < 0) {
8260 $nameorder = (!getDolGlobalString('MAIN_FIRSTNAME_NAME_POSITION') ? 1 : 0);
8261 }
8262 if ($nameorder == 1) {
8263 $ret .= $firstname;
8264 if ($firstname && $lastname) {
8265 $ret .= ' ';
8266 }
8267 $ret .= $lastname;
8268 } elseif ($nameorder == 2 || $nameorder == 3) {
8269 $ret .= $firstname;
8270 if (empty($ret) && $nameorder == 3) {
8271 $ret .= $lastname;
8272 }
8273 } else { // 0, 4 or 5
8274 $ret .= $lastname;
8275 if (empty($ret) && $nameorder == 5) {
8276 $ret .= $firstname;
8277 }
8278 if ($nameorder == 0) {
8279 if ($firstname && $lastname) {
8280 $ret .= ' ';
8281 }
8282 $ret .= $firstname;
8283 }
8284 }
8285 return $ret;
8286}
8287
8288
8296function dolSort($arraytosort)
8297{
8298 sort($arraytosort);
8299 return $arraytosort;
8300}
8301
8323function dol_sort_array(&$array, $index, $order = 'asc', $natsort = 0, $case_sensitive = 0, $keepindex = 0)
8324{
8325 // Clean parameters
8326 $order = strtolower($order);
8327
8328 if (is_array($array)) {
8329 $sizearray = count($array);
8330 if ($sizearray > 0) {
8331 // Build a temp array with sorting key as value
8332 $temp = array();
8333 foreach (array_keys($array) as $key) {
8334 $tmpmultikey = explode(',', $index);
8335 $newindex = $tmpmultikey[0];
8336 if (is_object($array[$key])) {
8337 $temp[$key] = empty($array[$key]->$newindex) ? 0 : $array[$key]->$newindex;
8338 // Add other keys
8339 if (!empty($tmpmultikey[1])) {
8340 $newindex = $tmpmultikey[1];
8341 $temp[$key] .= '__' . (empty($array[$key]->$newindex) ? 0 : $array[$key]->$newindex);
8342 }
8343 } else {
8344 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable,PhanTypeArraySuspicious,PhanTypeMismatchDimFetch
8345 $temp[$key] = empty($array[$key][$newindex]) ? 0 : $array[$key][$newindex];
8346 // Add other keys
8347 if (!empty($tmpmultikey[1])) {
8348 $newindex = $tmpmultikey[1];
8349 // @phan-suppress-next-line PhanTypeArraySuspicious,PhanTypeMismatchDimFetch
8350 $temp[$key] .= '__' . (empty($array[$key][$newindex]) ? 0 : $array[$key][$newindex]);
8351 }
8352 }
8353 if ($natsort == -1) {
8354 $temp[$key] = '___' . $temp[$key]; // We add a string at begin of value to force an alpha order when using asort.
8355 }
8356 }
8357 if (empty($natsort) || $natsort == -1) {
8358 if ($order == 'asc') {
8359 asort($temp);
8360 } else {
8361 arsort($temp);
8362 }
8363 } else {
8364 if ($case_sensitive) {
8365 natsort($temp);
8366 } else {
8367 natcasesort($temp); // natecasesort is not sensible to case
8368 }
8369 if ($order != 'asc') {
8370 $temp = array_reverse($temp, true);
8371 }
8372 }
8373
8374 $sorted = array();
8375
8376 foreach (array_keys($temp) as $key) {
8377 (is_numeric($key) && empty($keepindex)) ? $sorted[] = $array[$key] : $sorted[$key] = $array[$key];
8378 }
8379
8380 return $sorted;
8381 }
8382 }
8383 return $array;
8384}
8385
8386
8394function utf8_check($str)
8395{
8396 $str = (string) $str; // Sometimes string is an int.
8397
8398 // We must use here a binary strlen function (so not dol_strlen)
8399 $strLength = strlen($str);
8400 for ($i = 0; $i < $strLength; $i++) {
8401 if (ord($str[$i]) < 0x80) {
8402 continue; // 0bbbbbbb
8403 } elseif ((ord($str[$i]) & 0xE0) == 0xC0) {
8404 $n = 1; // 110bbbbb
8405 } elseif ((ord($str[$i]) & 0xF0) == 0xE0) {
8406 $n = 2; // 1110bbbb
8407 } elseif ((ord($str[$i]) & 0xF8) == 0xF0) {
8408 $n = 3; // 11110bbb
8409 } elseif ((ord($str[$i]) & 0xFC) == 0xF8) {
8410 $n = 4; // 111110bb
8411 } elseif ((ord($str[$i]) & 0xFE) == 0xFC) {
8412 $n = 5; // 1111110b
8413 } else {
8414 return false; // Does not match any model
8415 }
8416 for ($j = 0; $j < $n; $j++) { // n bytes matching 10bbbbbb follow ?
8417 if ((++$i == strlen($str)) || ((ord($str[$i]) & 0xC0) != 0x80)) {
8418 return false;
8419 }
8420 }
8421 }
8422 return true;
8423}
8424
8432function utf8_valid($str)
8433{
8434 /* 2 other methods to test if string is utf8
8435 $validUTF8 = mb_check_encoding($messagetext, 'UTF-8');
8436 $validUTF8b = ! (false === mb_detect_encoding($messagetext, 'UTF-8', true));
8437 */
8438 return preg_match('//u', $str) ? true : false;
8439}
8440
8441
8448function ascii_check($str)
8449{
8450 if (function_exists('mb_check_encoding')) {
8451 //if (mb_detect_encoding($str, 'ASCII', true) return false;
8452 if (!mb_check_encoding($str, 'ASCII')) {
8453 return false;
8454 }
8455 } else {
8456 if (preg_match('/[^\x00-\x7f]/', $str)) {
8457 return false; // Contains a byte > 7f
8458 }
8459 }
8460
8461 return true;
8462}
8463
8464
8472function dol_osencode($str)
8473{
8474 $tmp = ini_get("unicode.filesystem_encoding");
8475 if (empty($tmp) && !empty($_SERVER["WINDIR"])) {
8476 $tmp = 'iso-8859-1'; // By default for windows
8477 }
8478 if (empty($tmp)) {
8479 $tmp = 'utf-8'; // By default for other
8480 }
8481 if (getDolGlobalString('MAIN_FILESYSTEM_ENCODING')) {
8482 $tmp = getDolGlobalString('MAIN_FILESYSTEM_ENCODING');
8483 }
8484
8485 if ($tmp == 'iso-8859-1') {
8486 return mb_convert_encoding($str, 'ISO-8859-1', 'UTF-8');
8487 }
8488 return $str;
8489}
8490
8491
8507function dol_getIdFromCode($db, $key, $tablename, $fieldkey = 'code', $fieldid = 'id', $entityfilter = 0, $filters = '', $useCache = true)
8508{
8509 global $conf;
8510
8511 // If key empty
8512 if ($key == '') {
8513 return 0;
8514 }
8515
8516 // Check in cache
8517 if ($useCache && isset($conf->cache['codeid'][$tablename][$key][$fieldid])) { // Can be defined to 0 or ''
8518 return $conf->cache['codeid'][$tablename][$key][$fieldid]; // Found in cache
8519 }
8520
8521 dol_syslog('dol_getIdFromCode (value for field ' . $fieldid . ' from key ' . $key . ' not found into cache)', LOG_DEBUG);
8522
8523 $sql = "SELECT " . $db->sanitize($fieldid) . " as valuetoget";
8524 $sql .= " FROM " . MAIN_DB_PREFIX . $db->sanitize($tablename);
8525 if ($fieldkey == 'id' || $fieldkey == 'rowid') {
8526 $sql .= " WHERE " . $db->sanitize($fieldkey) . " = " . ((int) $key);
8527 } else {
8528 $sql .= " WHERE " . $db->sanitize($fieldkey) . " = '" . $db->escape($key) . "'";
8529 }
8530 if (!empty($entityfilter)) {
8531 $sql .= " AND entity IN (" . getEntity($tablename) . ")";
8532 }
8533 if ($filters) {
8534 $sql .= $filters; // @phan-suppress-current-line SqlInjection
8535 }
8536
8537 $resql = $db->query($sql);
8538 if ($resql) {
8539 $obj = $db->fetch_object($resql);
8540 $valuetoget = '';
8541 if ($obj) {
8542 $valuetoget = $obj->valuetoget;
8543 $conf->cache['codeid'][$tablename][$key][$fieldid] = $valuetoget;
8544 } else {
8545 $conf->cache['codeid'][$tablename][$key][$fieldid] = '';
8546 }
8547 $db->free($resql);
8548
8549 return $valuetoget;
8550 } else {
8551 return -1;
8552 }
8553}
8554
8564function isStringVarMatching($var, $regextext, $matchrule = 1)
8565{
8566 // Tolerate callers (custom modules, older code) that already pass a full regex with delimiters
8567 // like '/^(aaa|bbb)/' instead of the bare body. Without this, the function would build
8568 // '/^/^(aaa|bbb)//' which trips preg_match() with 'Unknown modifier ^'.
8569 $regextext = preg_replace('#^/\^?#', '', (string) $regextext);
8570 $regextext = preg_replace('#\$?/[imsxuADSUXJ]*$#', '', $regextext);
8571
8572 if ($matchrule == 1) {
8573 if ($var == 'mainmenu') {
8574 global $mainmenu;
8575 return (preg_match('/^' . $regextext . '/', $mainmenu));
8576 } elseif ($var == 'leftmenu') {
8577 global $leftmenu;
8578 return (preg_match('/^' . $regextext . '/', $leftmenu));
8579 } else {
8580 return 'This variable is not accessible with dol_eval';
8581 }
8582 } else {
8583 return 'This value '.$matchrule.' for param $matchrule is not yet implemented';
8584 }
8585}
8586
8587
8600function dolEvalSimpleCondition($s)
8601{
8602 global $conf, $user, $leftmenu, $mainmenu;
8603
8604 $s = trim((string) $s);
8605 if ($s === '1' || $s === 'true') {
8606 return true;
8607 }
8608 if ($s === '0' || $s === 'false') {
8609 return false;
8610 }
8611 // Only the characters of the known terms, and parentheses only around the quoted arguments of a call
8612 if (!preg_match('/^[a-zA-Z0-9_$>=!&|\s\'",()-]+$/', $s)) {
8613 return null;
8614 }
8615 if (strpbrk($s, '()') !== false && !preg_match('/^(?:[^()]*\‍((?:\s*[\'"][a-zA-Z0-9_]+[\'"]\s*)(?:,\s*[\'"][a-zA-Z0-9_]+[\'"]\s*)*\‍))*[^()]*$/', $s)) {
8616 return null;
8617 }
8618 $hasand = (strpos($s, '&&') !== false);
8619 $hasor = (strpos($s, '||') !== false);
8620 if ($hasand && $hasor) {
8621 return null;
8622 }
8623 $terms = ($hasor ? explode('||', $s) : ($hasand ? explode('&&', $s) : array($s)));
8624
8625 $result = null;
8626 foreach ($terms as $term) {
8627 $term = trim($term);
8628 $negation = false;
8629 if (substr($term, 0, 1) === '!') {
8630 $negation = true;
8631 $term = ltrim(substr($term, 1));
8632 }
8633 $reg = array();
8634 if (preg_match('/^isModEnabled\‍(\s*[\'"]([a-zA-Z0-9_]+)[\'"]\s*\‍)$/', $term, $reg)) {
8635 $value = isModEnabled($reg[1]);
8636 } elseif (preg_match('/^\$user->hasRight\‍(\s*[\'"]([a-zA-Z0-9_]+)[\'"]\s*,\s*[\'"]([a-zA-Z0-9_]+)[\'"]\s*(?:,\s*[\'"]([a-zA-Z0-9_]+)[\'"]\s*)?\‍)$/', $term, $reg)) {
8637 $value = (bool) (!empty($reg[3]) ? $user->hasRight($reg[1], $reg[2], $reg[3]) : $user->hasRight($reg[1], $reg[2]));
8638 } elseif (preg_match('/^\$user->rights->([a-zA-Z0-9_]+)->([a-zA-Z0-9_]+)(?:->([a-zA-Z0-9_]+))?$/', $term, $reg)) {
8639 if (!empty($reg[3])) {
8640 $value = !empty($user->rights->{$reg[1]}->{$reg[2]}->{$reg[3]});
8641 } else {
8642 $value = !empty($user->rights->{$reg[1]}->{$reg[2]});
8643 }
8644 } elseif ($term === '$user->admin') {
8645 $value = !empty($user->admin);
8646 } elseif (preg_match('/^\$conf->([a-zA-Z0-9_]+)->enabled$/', $term, $reg)) {
8647 $value = !empty($conf->{$reg[1]}->enabled);
8648 } elseif (preg_match('/^getDolGlobal(String|Int)\‍(\s*[\'"]([a-zA-Z0-9_]+)[\'"]\s*\‍)$/', $term, $reg)) {
8649 $value = ($reg[1] == 'Int' ? (bool) getDolGlobalInt($reg[2]) : (bool) getDolGlobalString($reg[2]));
8650 } elseif (preg_match('/^\$(leftmenu|mainmenu)\s*(==|!=)\s*[\'"]([a-zA-Z0-9_]*)[\'"]$/', $term, $reg)) {
8651 $current = ($reg[1] == 'leftmenu' ? $leftmenu : $mainmenu);
8652 $value = ($reg[2] == '==' ? ($current == $reg[3]) : ($current != $reg[3]));
8653 } elseif ($term === '1' || $term === 'true') {
8654 $value = true;
8655 } elseif ($term === '0' || $term === 'false') {
8656 $value = false;
8657 } else {
8658 return null; // Not a known term, the caller will use eval()
8659 }
8660 if ($negation) {
8661 $value = !$value;
8662 }
8663 if ($result === null) {
8664 $result = $value;
8665 } elseif ($hasor) {
8666 $result = ($result || $value);
8667 } else {
8668 $result = ($result && $value);
8669 }
8670 }
8671
8672 return $result;
8673}
8674
8684function verifCond($strToEvaluate, $onlysimplestring = '1')
8685{
8686 //print $strToEvaluate."<br>\n";
8687 $rights = true;
8688 if (isset($strToEvaluate) && $strToEvaluate !== '') {
8689 // Most of the conditions are simple (isModEnabled('xxx'), $user->hasRight('xxx', 'yyy'), $conf->xxx->enabled...): they are
8690 // evaluated directly, without eval() and its checks, when they match one of the known shapes.
8691 $rights = dolEvalSimpleCondition($strToEvaluate);
8692 if ($rights !== null) {
8693 return $rights;
8694 }
8695 //var_dump($strToEvaluate);
8696 //$rep = dol_eval($strToEvaluate, 1, 0, '1'); // to show the error
8697 $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
8698
8699 // On string syntax error, dol_eval may return a string that start with 'Bad call of ...' or 'Bad string syntax to evaluate...' !!!
8700 //var_dump($strToEvaluate, $rep);
8701 $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));
8702 //var_dump($rights);
8703 }
8704 return $rights;
8705}
8706
8722function dol_eval($s, $returnvalue = 1, $hideerrors = 1, $onlysimplestring = '1')
8723{
8724 if ($returnvalue != 1) {
8725 dol_syslog("Use of dol_eval with parameter returnvalue = 0 is now forbidden. Please fix this", LOG_ERR);
8726 }
8727
8728 global $dolibarr_main_use_dol_eval_new; // experimental option, not yet ready
8729 if (!empty($dolibarr_main_use_dol_eval_new)) {
8730 return dol_eval_new($s);
8731 } else {
8732 return dol_eval_standard($s, $hideerrors, $onlysimplestring);
8733 }
8734}
8735
8746function dol_eval_new($s)
8747{
8748 // Only this global variables can be read by eval function and returned to caller
8749 global $conf, // Read of const is done with getDolGlobalString() but we need $conf->currency for example
8750 $db, $langs, $user, $website, $websitepage,
8751 $action, $mainmenu, $leftmenu,
8752 $mysoc,
8753 $objectoffield, // To allow the use of $objectoffield in computed fields
8754
8755 // Old variables used
8756 $object;
8757
8758 if (getDolGlobalString('MAIN_ALLOW_OLD_VAR_OBJ_IN_DOL_EVAL')) {
8759 global $obj; // To get $obj used into list when dol_eval() is used for computed fields and $obj is not yet $object
8760 }
8761
8762 // PHP < 7.4.0
8763 defined('T_COALESCE_EQUAL') || define('T_COALESCE_EQUAL', PHP_INT_MAX);
8764 defined('T_FN') || define('T_FN', PHP_INT_MAX);
8765
8766 // PHP < 8.0.0
8767 defined('T_ATTRIBUTE') || define('T_ATTRIBUTE', PHP_INT_MAX);
8768 defined('T_MATCH') || define('T_MATCH', PHP_INT_MAX);
8769 defined('T_NAME_FULLY_QUALIFIED') || define('T_NAME_FULLY_QUALIFIED', PHP_INT_MAX);
8770 defined('T_NAME_QUALIFIED') || define('T_NAME_QUALIFIED', PHP_INT_MAX);
8771 defined('T_NAME_RELATIVE') || define('T_NAME_RELATIVE', PHP_INT_MAX);
8772
8773 // PHP < 8.1.0
8774 defined('T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG') || define('T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG', PHP_INT_MAX);
8775 defined('T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG') || define('T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG', PHP_INT_MAX);
8776 defined('T_ENUM') || define('T_ENUM', PHP_INT_MAX);
8777 defined('T_READONLY') || define('T_READONLY', PHP_INT_MAX);
8778
8779 // PHP < 8.4.0
8780 defined('T_PRIVATE_SET') || define('T_PRIVATE_SET', PHP_INT_MAX);
8781 defined('T_PROTECTED_SET') || define('T_PROTECTED_SET', PHP_INT_MAX);
8782 defined('T_PUBLIC_SET') || define('T_PUBLIC_SET', PHP_INT_MAX);
8783
8784 $prohibited_token_ids = [
8785 /*
8786 * Prohibited int tokens
8787 */
8788
8789 // T_AND_EQUAL', 'T_ARRAY', 'T_ARRAY_CAST', 'T_AS',
8790 'T_ABSTRACT',
8791 'T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG',
8792 'T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG',
8793 'T_ATTRIBUTE',
8794 // 'T_BOOLEAN_AND', 'T_BOOLEAN_OR', 'T_BOOL_CAST', 'T_BREAK',
8795 'T_BAD_CHARACTER',
8796 // 'T_CASE', 'T_CLASS_C', 'T_CLONE', 'T_COALESCE', 'T_COALESCE_EQUAL', 'T_COMMENT', 'T_CONCAT_EQUAL',
8797 // 'T_CONSTANT_ENCAPSED_STRING', 'T_CONTINUE', 'T_CURLY_OPEN',
8798 'T_CALLABLE',
8799 'T_CATCH',
8800 'T_CLASS',
8801 'T_CLOSE_TAG',
8802 'T_CONST',
8803 // 'T_DEC', 'T_DEFAULT', 'T_DIV_EQUAL', 'T_DNUMBER', 'T_DO', 'T_DOC_COMMENT',
8804 // 'T_DOLLAR_OPEN_CURLY_BRACES', 'T_DOUBLE_ARROW', 'T_DOUBLE_CAST', 'T_DOUBLE_COLON',
8805 'T_DECLARE',
8806 'T_DIR',
8807 // 'T_ELLIPSIS', 'T_ELSE', 'T_ELSEIF', 'T_EMPTY', 'T_ENCAPSED_AND_WHITESPACE', 'T_ENDFOR',
8808 // 'T_ENDFOREACH', 'T_ENDIF', 'T_ENDSWITCH', 'T_ENDWHILE', 'T_END_HEREDOC',
8809 'T_ECHO',
8810 'T_ENDDECLARE',
8811 'T_ENUM',
8812 'T_EVAL',
8813 'T_EXIT',
8814 'T_EXTENDS',
8815 // 'T_FOR', 'T_FOREACH',
8816 'T_FILE',
8817 'T_FINAL',
8818 'T_FINALLY',
8819 'T_FN',
8820 'T_FUNCTION',
8821 'T_FUNC_C',
8822 'T_GLOBAL',
8823 'T_GOTO',
8824 'T_HALT_COMPILER',
8825 // 'T_IF', 'T_INC', 'T_INLINE_HTML', 'T_INSTANCEOF', 'T_INT_CAST', 'T_ISSET', 'T_IS_EQUAL', 'T_IS_GREATER_OR_EQUAL',
8826 // 'T_IS_IDENTICAL', 'T_IS_NOT_EQUAL', 'T_IS_NOT_IDENTICAL', 'T_IS_SMALLER_OR_EQUAL',
8827 'T_IMPLEMENTS',
8828 'T_INCLUDE',
8829 'T_INCLUDE_ONCE',
8830 'T_INSTEADOF',
8831 'T_INTERFACE',
8832 // 'T_LIST', 'T_LNUMBER', 'T_LOGICAL_AND', 'T_LOGICAL_OR', 'T_LOGICAL_XOR',
8833 'T_LINE',
8834 // 'T_MINUS_EQUAL', 'T_MOD_EQUAL', 'T_MUL_EQUAL',
8835 'T_METHOD_C',
8836 // 'T_NEW',
8837 // 'T_NS_SEPARATOR', 'T_NUM_STRING',
8838 'T_NAMESPACE',
8839 // 'T_NAME_FULLY_QUALIFIED', 'T_NAME_QUALIFIED', 'T_NAME_RELATIVE', 'T_NS_C',
8840 // 'T_OBJECT_CAST', 'T_OBJECT_OPERATOR', 'T_OR_EQUAL',
8841 'T_OPEN_TAG',
8842 'T_OPEN_TAG_WITH_ECHO',
8843 // 'T_PAAMAYIM_NEKUDOTAYIM', 'T_PLUS_EQUAL', 'T_POW', 'T_POW_EQUAL',
8844 'T_PRINT',
8845 'T_PRIVATE',
8846 'T_PROTECTED',
8847 'T_PUBLIC',
8848 // 'T_PROPERTY_C',
8849 'T_READONLY',
8850 'T_REQUIRE',
8851 'T_REQUIRE_ONCE',
8852 'T_RETURN',
8853 // 'T_SL', 'T_SL_EQUAL', 'T_SPACESHIP', 'T_SR', 'T_SR_EQUAL', 'T_START_HEREDOC', 'T_STATIC',
8854 // 'T_STRING', 'T_STRING_CAST', 'T_STRING_VARNAME', 'T_SWITCH',
8855 'T_STATIC',
8856 'T_THROW',
8857 'T_TRAIT',
8858 'T_TRAIT_C',
8859 'T_TRY',
8860 'T_UNSET',
8861 'T_UNSET_CAST',
8862 'T_USE',
8863 // 'T_VARIABLE',
8864 'T_VAR',
8865 // 'T_WHILE', 'T_WHITESPACE',
8866 // 'T_XOR_EQUAL',
8867 // 'T_YIELD', 'T_YIELD_FROM',
8868
8869 /*
8870 * Prohibited string tokens
8871 */
8872 ';',
8873 '`',
8874 ];
8875
8876 $prohibited_variables = [
8877 '$_COOKIE',
8878 '$_ENV',
8879 '$_FILES',
8880 '$GLOBALS',
8881 '$_GET',
8882 '$_POST',
8883 '$_REQUEST',
8884 '$_SERVER',
8885 '$_SESSION',
8886 ];
8887
8888 $forbiddenphpfunctions = array();
8889 $forbiddenphpmethods = array();
8890
8891 // Same list than in dol_eval
8892 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("override_function", "session_id", "session_create_id", "session_regenerate_id"));
8893 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("get_defined_functions", "get_defined_vars", "get_defined_constants", "get_declared_classes"));
8894 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("function"));
8895
8896 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("GETPOST")); // native dolibarr functions
8897
8898 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("ob_start"));
8899
8900 // Functions with callable parameters
8901 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("call_user_func", "call_user_func_array"));
8902 $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"));
8903 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("usort", "uasort", "uksort"));
8904 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("preg_replace_callback", "preg_replace_callback_array", "header_register_callback"));
8905 $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"));
8906 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("spl_autoload_register", "spl_autoload_unregister", "iterator_apply", "session_set_save_handler"));
8907 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("forward_static_call", "forward_static_call_array", "register_postsend_function"));
8908 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("readline_completion_function", "readline_callback_handler_install"));
8909
8910 // Exec functions
8911 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("exec", "passthru", "shell_exec", "system", "proc_open", "popen"));
8912 $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"));
8913 $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", ));
8914 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("putenv", "dl", "apache_child_terminate", "apache_setenv"));
8915 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("dol_eval", "dol_eval_new", "dol_eval_standard", "executeCLI", "verifCond", "dolEncrypt", "dolDecrypt")); // native dolibarr functions
8916 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("eval", "create_function", "assert", "mb_ereg_replace")); // function with eval capabilities
8917
8918 // Include functions
8919 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("require", "include", "require_once", "include_once"));
8920
8921 $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
8922 $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"));
8923
8924 if (!getDolGlobalString('MAIN_ALLOW_OBFUSCATION_METHODS_IN_DOL_EVAL')) { // We disallow all function that allow to obfuscate the real name of a function
8925 // @phpcs:ignore
8926 $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
8927 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("dol_concat", "dol_concatdesc")); // native dolibarr functions
8928 }
8929
8930 $forbiddenphpmethods = array_merge($forbiddenphpmethods, array('invoke', 'invokeArgs')); // Methods of ReflectionFunction to execute a function
8931
8932 $prohibited_functions = array_merge($forbiddenphpfunctions, $forbiddenphpmethods);
8933
8934 $prohibited_token_arrangements = [
8935 // Variable functions "$a(", '"$a"(', "'FN_NAME'(", ('FN_NAME')()
8936 ' T_VARIABLE ( ',
8937 ' " ( ',
8938 ' \' ( ',
8939 ' T_CONSTANT_ENCAPSED_STRING ( ',
8940 ' ) ( ',
8941 ];
8942
8943 $tokens = token_get_all("<?php return {$s};", TOKEN_PARSE);
8944
8945 $tokens_arrangement = ' ';
8946
8947 for ($i = 2, $c = count($tokens) - 1; $i < $c; ++$i) { // ignore <?php return and ;
8948 if (is_array($tokens[$i])) {
8949 $token_id = $tokens[$i][0];
8950 $token_value = $tokens[$i][1];
8951 $token_name = token_name($tokens[$i][0]);
8952 } else {
8953 $token_id = $tokens[$i];
8954 $token_value = $tokens[$i];
8955 $token_name = $tokens[$i];
8956 }
8957
8958 // Ignore whitespaces
8959 if (T_WHITESPACE === $token_id) {
8960 continue;
8961 }
8962
8963 // Keep history to check arrangements
8964 $tokens_arrangement .= "{$token_name} ";
8965
8966 // Prohibited Variables
8967 if (
8968 T_VARIABLE === $token_id
8969 && in_array($token_value, $prohibited_variables, true)
8970 ) {
8971 return "Bad string syntax to evaluate. « {$token_value} » is prohibited in « {$s} »";
8972 }
8973
8974 // Prohibited Functions
8975 if (
8976 T_STRING === $token_id
8977 && in_array($token_value, $prohibited_functions, true)
8978 ) {
8979 return "Bad string syntax to evaluate. « {$token_value} » is prohibited in « {$s} »";
8980 }
8981 }
8982
8983 // Prohibited Token IDs
8984 $maxi = count($prohibited_token_ids);
8985 for ($i = 0; $i < $maxi; ++$i) {
8986 if (false !== strpos($tokens_arrangement, " {$prohibited_token_ids[$i]} ")) {
8987 return "Bad string syntax to evaluate. « {$prohibited_token_ids[$i]} » is prohibited in « {$s} »";
8988 }
8989 }
8990
8991 // Prohibited token arrangements
8992 $maxi = count($prohibited_token_arrangements);
8993 for ($i = 0; $i < $maxi; ++$i) {
8994 if (false !== strpos($tokens_arrangement, $prohibited_token_arrangements[$i])) {
8995 return "Bad string syntax to evaluate. « {$prohibited_token_arrangements[$i]} » is prohibited in « {$s} »";
8996 }
8997 }
8998
8999 // Return result
9000 try {
9001 return @eval("return {$s};") ?? '';
9002 } catch (Throwable $ex) {
9003 return "Bad string syntax to evaluate. Exception during evaluation: " . $s . " - " . $ex->getMessage();
9004 }
9005}
9006
9021function dol_eval_standard($s, $hideerrors = 1, $onlysimplestring = '1')
9022{
9023 // Only this global variables can be read by eval function and returned to caller
9024 // The less we have, the better it is.
9025
9026 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()
9027 global $db, $langs, $user, $website, $websitepage;
9028 global $action, $mainmenu, $leftmenu;
9029 global $mysoc;
9030 global $objectoffield; // To allow the use of $objectoffield in computed fields
9031 global $object;
9032
9033 // Old variables (deprecated since v23)
9034 if (getDolGlobalString('MAIN_ALLOW_OLD_VAR_OBJ_IN_DOL_EVAL')) {
9035 global $obj; // To get $obj used into list when dol_eval() is used for computed fields and $obj is not yet $objectoffield
9036 }
9037
9038 $isObBufferActive = false; // When true, the ObBuffer must be cleaned in the exception handler
9039 if ($onlysimplestring == '0') { // '0' is deprecated, we process it as the more secured '1'
9040 $onlysimplestring = '1';
9041 }
9042 if (!in_array($onlysimplestring, array('1', '2'))) {
9043 return "Bad call of dol_eval. Parameter onlysimplestring must be '1' or '2'.";
9044 }
9045 if (!is_scalar($s)) {
9046 return "Bad call of dol_eval. First parameter must be a string, found ".var_export($s, true);
9047 }
9048
9049 try {
9050 global $dolibarr_main_restrict_eval_methods;
9051
9052 // Set $dolibarr_main_restrict_eval_methods_array
9053 if (!isset($dolibarr_main_restrict_eval_methods)) {
9054 $dolibarr_main_restrict_eval_methods = 'getDolGlobalString, getDolGlobalInt, getDolCurrency, getDolEntity, getDolDBType, fetchNoCompute, hasRight, isAdmin, isExternalUser, isModEnabled, isStringVarMatching, abs, min, max, round, dol_now, preg_match';
9055 }
9056 //print '$dolibarr_main_restrict_eval_methods = '.$dolibarr_main_restrict_eval_methods."\n";
9057 $dolibarr_main_restrict_eval_methods_array = explode(',', str_replace(" ", "", $dolibarr_main_restrict_eval_methods));
9058
9059 // Test on dangerous char (used for RCE), we allow only characters to make PHP variable testing
9060 // We must accept with 1: '1 && getDolGlobalInt("doesnotexist1") && getDolGlobalString("MAIN_FEATURES_LEVEL")'
9061 // We must accept with 1: '$user->hasRight("cabinetmed", "read") && !$objectoffield->canvas == "patient@cabinetmed"'
9062 // 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"
9063
9064 // Check if there is dynamic call (first we check chars are all into a whitelist chars)
9065 $specialcharsallowed = '^$_+-.*>&|=!?():"\',/@';
9066 if ($onlysimplestring == '2') {
9067 $specialcharsallowed .= '<[]'; // Later we check that < has space before and after
9068 }
9069 global $dolibarr_main_allow_unsecured_special_chars_in_dol_eval;
9070 if (!empty($dolibarr_main_allow_unsecured_special_chars_in_dol_eval)) {
9071 $specialcharsallowed .= (string) $dolibarr_main_allow_unsecured_special_chars_in_dol_eval;
9072 }
9073 if (preg_match('/[^a-z0-9\s' . preg_quote($specialcharsallowed, '/') . ']/i', $s)) {
9074 return 'Bad string syntax to evaluate (found chars that are not chars for a simple one line clean eval string): ' . $s;
9075 }
9076
9077 // Check if we found a | without a space before and after
9078 /* Disabled to allow preg_match('/(AAA|BBB)/')
9079 $tmps = str_replace(' || ', '__XXX__', $s);
9080 if (strpos($tmps, '|') !== false) {
9081 return 'Bad string syntax to evaluate (The char | can be used only when duplicated || with a space before and after): ' . $s;
9082 }
9083 */
9084
9085 // Check if there is PHP comments (can be used to obfuscate code)
9086 if (strpos($s, '/*') !== false || strpos($s, '//') !== false) {
9087 return 'Bad string syntax to evaluate (The comment string /* and // are not allowed): ' . $s;
9088 }
9089
9090 // Check if we found a ? without a space before and after
9091 $tmps = str_replace(' ? ', '__XXX__', $s);
9092 if (strpos($tmps, '?') !== false) {
9093 return 'Bad string syntax to evaluate (The char ? can be used only with a space before and after): ' . $s;
9094 }
9095
9096 // Check if there is a < or <= without spaces after
9097 if (preg_match('/<=?[^\s]/', $s)) {
9098 return 'Bad string syntax to evaluate (mode ' . $onlysimplestring . ', found a < or <= without space after): ' . $s;
9099 }
9100
9101 // Check if there is an include or a require
9102 if (preg_match('/(include|include_once|require|require_once)/', $s)) {
9103 return 'Bad string syntax to evaluate (found not allowed key include|include_once|require|require_once): ' . $s;
9104 }
9105
9106 // Check if there is dynamic call (first we use black list patterns)
9107 if (preg_match('/\$[\w]*\s*\‍(/', $s)) {
9108 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;
9109 }
9110
9111 if (empty($dolibarr_main_restrict_eval_methods)) {
9112 // If $dolibarr_main_restrict_eval_methods was set to '', we must check if we try dynamic call
9113
9114 // First we remove white list pattern of using parenthesis then testing if one open parenthesis exists
9115 $savescheck = '';
9116 $scheck = $s;
9117 while ($scheck && $savescheck != $scheck) {
9118 $savescheck = $scheck;
9119 $scheck = preg_replace('/->[a-zA-Z0-9_]+\‍(/', '->__METHOD__', $scheck); // accept parenthesis in '...->method(...'
9120 $scheck = preg_replace('/::[a-zA-Z0-9_]+\‍(/', '->__METHOD__', $scheck); // accept parenthesis in '...::method(...'
9121 $scheck = preg_replace('/^\‍(+/', '__PARENTHESIS__ ', $scheck); // accept parenthesis in '(...'. Must replace with "__PARENTHESIS__ with a space after "to allow following substitutions
9122 $scheck = preg_replace('/\&\&\s+\‍(/', '__ANDPARENTHESIS__ ', $scheck); // accept parenthesis in '&& ('. Must replace with "__PARENTHESIS__ with a space after" to allow following substitutions
9123 $scheck = preg_replace('/\|\|\s+\‍(/', '__ORPARENTHESIS__ ', $scheck); // accept parenthesis in '|| ('. Must replace with "__PARENTHESIS__ with a space after" to allow following substitutions
9124 $scheck = preg_replace('/^!?[a-zA-Z0-9_]+\‍(/', '__FUNCTION__', $scheck); // accept parenthesis in 'function(' and '!function('
9125 $scheck = preg_replace('/\s!?[a-zA-Z0-9_]+\‍(/', '__FUNCTION__', $scheck); // accept parenthesis in '... function(' and '... !function('
9126 $scheck = preg_replace('/^!\‍(/', '__NOTANDPARENTHESIS__', $scheck); // accept parenthesis in '!('
9127 $scheck = preg_replace('/\s!\‍(/', ' __NOTANDPARENTHESIS__', $scheck); // accept parenthesis in '... !('
9128 $scheck = preg_replace('/(\^|\')\‍(/', '__REGEXSTART__', $scheck); // To allow preg_match('/^(aaa|bbb)/'... or isStringVarMatching('leftmenu', '(aaa|bbb)')
9129 }
9130 //print 'scheck='.$scheck." : ".strpos($scheck, '(')."<br>\n";
9131
9132 // Now test if it remains 1 open parenthesis.
9133 if (strpos($scheck, '(') !== false) {
9134 return 'Bad string syntax to evaluate (mode ' . $onlysimplestring . ', found call of a function or method without using the direct name of the function): ' . $s;
9135 }
9136 }
9137
9138 if (strpos($s, '`') !== false) {
9139 return 'Bad string syntax to evaluate (backtick char is forbidden): ' . $s;
9140 }
9141
9142 // Disallow also concat operator
9143 if (!getDolGlobalString('MAIN_ALLOW_OBFUSCATION_METHODS_IN_DOL_EVAL')) {
9144 if (preg_match('/[^0-9]+\.[^0-9]+/', $s)) { // We refuse . if not between 2 numbers
9145 return 'Bad string syntax to evaluate (dot char is forbidden if not strictly between 2 numbers): ' . $s;
9146 }
9147 }
9148
9149 // We exclude string using a $ character that are not an expected global or temporary vars, so that are not:
9150 // $db, $langs, $leftmenu, $topmenu, $user, $langs, $objectoffield, $var....
9151 $savescheck = '';
9152 $scheck = $s;
9153 while ($scheck && $savescheck != $scheck) {
9154 $savescheck = $scheck;
9155 $scheck = preg_replace('/\$conf->[a-z\_]+->enabled/', '__VARCONFENABLED__', $scheck); // Remove this once $user->module->enabled has been replaced everywhere with isModEnabled.
9156 $scheck = preg_replace('/\$user->id/', '__VARUSERID__', $scheck);
9157 $scheck = preg_replace('/\$user->hasRight/', '__VARUSERHASRIGHT__', $scheck);
9158 $scheck = preg_replace('/\$user->rights/', '__VARUSERHASRIGHT__', $scheck); // Remove this once $user->rights->xxx is replaced everywhere with $user->hasRight()
9159 $scheck = preg_replace('/\$user->isAdmin/', '__VARUSERHASRIGHT__', $scheck);
9160 $scheck = preg_replace('/\$user->admin/', '__VARUSERISADMIN__', $scheck); // Remove this once $user->admin is replaced everywhere with $user->isAdmin()
9161 $scheck = preg_replace('/\$user->isExternalUser/', '__VARUSERSOCID__', $scheck);
9162 $scheck = preg_replace('/\$user->socid/', '__VARUSERSOCID__', $scheck); // Remove this once $user->admin is replaced everywhere with $user->isExternalUser()
9163 $scheck = preg_replace('/\‍(\$db\‍)/', '__VARDB__', $scheck);
9164 $scheck = preg_replace('/\$langs/', '__VARLANGSTRANS__', $scheck);
9165 $scheck = preg_replace('/\$mysoc/', '__VARMYSOC__', $scheck);
9166 $scheck = preg_replace('/\$action/', '__VARACTION__', $scheck);
9167 $scheck = preg_replace('/\$mainmenu/', '__VARMAINMENU__', $scheck); // Remove this once all tests on $mainmenu has been replaced with isStringVarMatching
9168 $scheck = preg_replace('/\$leftmenu/', '__VARLEFTMENU__', $scheck); // Remove this once all tests on $mainmenu has been replaced with isStringVarMatching
9169 $scheck = preg_replace('/\$websitepage/', '__VARWEBSITEPAGE__', $scheck);
9170 $scheck = preg_replace('/\$website/', '__VARWEBSITE__', $scheck);
9171 $scheck = preg_replace('/\$objectoffield/', '__VAROBJECTOFFIELD__', $scheck);
9172 $scheck = preg_replace('/\$object/', '__VAROBJECT__', $scheck);
9173 $scheck = preg_replace('/\$var/', '__VARVAR__', $scheck);
9174
9175 // deprecated (now we use $objecf->canvas or $objectoffield->canvas)
9176 $scheck = preg_replace('/\$soc->canvas/', '__VARSOCCANVAS__', $scheck);
9177 $scheck = preg_replace('/\$obj->canvas/', '__VAROBJCANVAS__', $scheck);
9178
9179 // Now test if it remains one '$'
9180 if (strpos($scheck, '$') !== false) {
9181 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);
9182 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;
9183 }
9184 }
9185
9186 // We block use of php exec or php file functions
9187 $forbiddenphpstrings = array('_ENV', '_SESSION', '_COOKIE', '_GET', '_GLOBAL', '_POST', '_REQUEST', 'ReflectionFunction', 'SplFileObject', 'SplTempFileObject');
9188
9189 if (empty($dolibarr_main_restrict_eval_methods)) { // If forced to ''
9190 // 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)
9191 // 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
9192 // like we can do with array_map and its callable parameter: dol_eval('json_encode(array_map(implode("",["ex","ec"]), ["id"]))', 1, 1, '0')
9193 $forbiddenphpfunctions = array();
9194 $forbiddenphpmethods = array();
9195
9196 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("override_function", "session_id", "session_create_id", "session_regenerate_id"));
9197 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("get_defined_functions", "get_defined_vars", "get_defined_constants", "get_declared_classes"));
9198 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("function"));
9199
9200 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("GETPOST")); // native dolibarr functions
9201
9202 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("ob_start"));
9203
9204 // Functions with callable parameters
9205 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("call_user_func", "call_user_func_array"));
9206 $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"));
9207 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("usort", "uasort", "uksort"));
9208 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("preg_replace_callback", "preg_replace_callback_array", "header_register_callback"));
9209 $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"));
9210 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("spl_autoload_register", "spl_autoload_unregister", "iterator_apply", "session_set_save_handler"));
9211 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("forward_static_call", "forward_static_call_array", "register_postsend_function"));
9212 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("readline_completion_function", "readline_callback_handler_install"));
9213
9214 // Exec functions
9215 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("exec", "passthru", "shell_exec", "system", "proc_open", "popen"));
9216 $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"));
9217 $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", ));
9218 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("putenv", "dl", "apache_child_terminate", "apache_setenv"));
9219 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("dol_eval", "dol_eval_new", "dol_eval_standard", "executeCLI", "verifCond", "dolEncrypt", "dolDecrypt")); // native dolibarr functions
9220 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("eval", "create_function", "assert", "mb_ereg_replace")); // function with eval capabilities
9221
9222 // Include functions
9223 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("require", "include", "require_once", "include_once"));
9224
9225 $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
9226 $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"));
9227
9228 if (!getDolGlobalString('MAIN_ALLOW_OBFUSCATION_METHODS_IN_DOL_EVAL')) { // We disallow all function that allow to obfuscate the real name of a function
9229 // @phpcs:ignore
9230 $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
9231 $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("dol_concat", "dol_concatdesc")); // native dolibarr functions
9232 }
9233 // Remove from blacklist the function that are into the whitelist
9234 /*foreach ($forbiddenphpfunctions as $key => $forbiddenphpfunction) {
9235 if (in_array($forbiddenphpfunction, $dolibarr_main_restrict_eval_methods_array)) {
9236 unset($forbiddenphpfunctions[$key]);
9237 }
9238 }*/
9239
9240 $forbiddenphpmethods = array_merge($forbiddenphpmethods, array('invoke', 'invokeArgs')); // Methods of ReflectionFunction to execute a function
9241 // Remove from blacklist the function that are into the whitelist
9242 /*foreach ($forbiddenphpmethods as $key => $forbiddenphpmethod) {
9243 if (in_array($forbiddenphpmethod, $dolibarr_main_restrict_eval_methods_array)) {
9244 unset($forbiddenphpmethods[$key]);
9245 }
9246 }*/
9247
9248 $forbiddenphpregex = 'global\s*\$';
9249 $forbiddenphpregex .= '|posix_[a-zA-Z0-9_]*|'; // All posix functions
9250 $forbiddenphpregex .= '\b(' . implode('|', $forbiddenphpfunctions) . ')\b';
9251
9252 $forbiddenphpmethodsregex = '->(' . implode('|', $forbiddenphpmethods) . ')';
9253
9254 // Now scan all forbidden patterns
9255 do {
9256 $oldstringtoclean = $s;
9257 $s = str_ireplace($forbiddenphpstrings, '__forbiddenstring__', $s);
9258 $s = preg_replace('/' . $forbiddenphpregex . '/i', '__forbiddenstring__', $s);
9259 $s = preg_replace('/' . $forbiddenphpmethodsregex . '/i', '__forbiddenstring__', $s);
9260 //$s = preg_replace('/\$[a-zA-Z0-9_\->\$]+\‍(/i', '', $s); // Remove $function( call and $mycall->mymethod(
9261 } while ($oldstringtoclean != $s);
9262
9263 if (strpos($s, '__forbiddenstring__') !== false) {
9264 dol_syslog('Bad string syntax to evaluate: ' . $s, LOG_WARNING);
9265 return 'Bad string syntax to evaluate: ' . $s;
9266 }
9267 }
9268
9269 if (!empty($dolibarr_main_restrict_eval_methods)) {
9270 // Accept only white-listed allowed function and classes
9271 // TODO Get all pattern '/([\s\w]+)\‍(/', then check that $matches[1] is a defined class or a function into a given list
9272 $pattern = '/([\s\w\'\]\"]+)\‍(/';
9273
9274 $matches = array();
9275 preg_match_all($pattern, $s, $matches);
9276
9277 if (count($matches)) {
9278 foreach ($matches[1] as $m) {
9279 $m = trim($m);
9280 if (empty($m)) {
9281 continue;
9282 }
9283 $reg = array();
9284 if (!preg_match('/new ([A-Z][\w]+)/i', $m, $reg)) {
9285 if (!in_array($m, $dolibarr_main_restrict_eval_methods_array)) {
9286 if ($m != "'" && $m != '"') {
9287 dol_syslog('Bad string syntax to evaluate: ' . $s, LOG_WARNING);
9288 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;
9289 }
9290 }
9291 } else {
9292 if (!class_exists($reg[1])) {
9293 dol_syslog('Bad string syntax to evaluate: Class "'.$reg[1].'" does not exist. ' . $s, LOG_WARNING);
9294 return 'Bad string syntax to evaluate. Class "'.$reg[1].'" does not exist. ' . $s;
9295 }
9296 $parents = class_parents($reg[1]); // Get list of parent classes of class we want to check
9297 if (!in_array('CommonObject', $parents)) { // Only classes that inherit CommonObject are ok. This forbid dangerous classes like ReflectionFunction, SplFileObject, ...
9298 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);
9299 return 'Bad string syntax to evaluate. Class "'.$reg[1].'" is not allowed because only classes extended CommonObject can be used in dynamic evaluation. ' . $s;
9300 }
9301 }
9302 }
9303 }
9304
9305 $forbiddenphpregex = 'global\s*\$';
9306 $forbiddenphpregex .= '|'; // or
9307 $forbiddenphpregex .= '}\s*\[';
9308 $forbiddenphpregex .= '|'; // or
9309 $forbiddenphpregex .= '\‍)\s*\‍(';
9310
9311 // Now scan all forbidden patterns
9312 do {
9313 $oldstringtoclean = $s;
9314 $s = str_ireplace($forbiddenphpstrings, '__forbiddenstring__', $s);
9315 $s = preg_replace('/' . $forbiddenphpregex . '/i', '__forbiddenstring__', $s);
9316 //$s = preg_replace('/' . $forbiddenphpmethodsregex . '/i', '__forbiddenstring__', $s);
9317 //$s = preg_replace('/\$[a-zA-Z0-9_\->\$]+\‍(/i', '', $s); // Remove $function( call and $mycall->mymethod(
9318 } while ($oldstringtoclean != $s);
9319
9320 if (strpos($s, '__forbiddenstring__') !== false) {
9321 dol_syslog('Bad string syntax to evaluate: ' . $s, LOG_WARNING);
9322 return 'Bad string syntax to evaluate: ' . $s;
9323 }
9324 }
9325
9326 //print $s."<br>\n";
9327 ob_start(); // An evaluation has no reason to output data
9328 $isObBufferActive = true;
9329 $tmps = $hideerrors ? @eval('return ' . $s . ';') : eval('return ' . $s . ';');
9330 $tmpo = ob_get_clean(); // This close the buffer
9331 $isObBufferActive = false;
9332 if ($tmpo) {
9333 print 'Bad string syntax to evaluate. Some data were output when it should not when evaluating: ' . $s;
9334 }
9335 return $tmps;
9336 } catch (Exception $e) {
9337 if ($isObBufferActive) {
9338 // Clean up buffer which was left behind due to exception.
9339 $tmpo = ob_get_clean(); // This close the buffer
9340 $isObBufferActive = false;
9341 }
9342 $error = 'dol_eval try/catch error for string: ' . $s . ' - Error: ';
9343 $error .= $e->getMessage();
9344 dol_syslog($error, LOG_WARNING);
9345 return 'Exception during evaluation: ' . $s;
9346 } catch (Error $e) {
9347 if ($isObBufferActive) {
9348 // Clean up buffer which was left behind due to exception.
9349 $tmpo = ob_get_clean(); // This close the buffer
9350 $isObBufferActive = false;
9351 }
9352 $error = 'dol_eval try/catch error for string: ' . $s . ' - Error: ';
9353 $error .= $e->getMessage();
9354 dol_syslog($error, LOG_WARNING);
9355 return 'Exception during evaluation: ' . $s;
9356 }
9357}
9358
9366function dol_validElement($element)
9367{
9368 return (trim($element) != '');
9369}
9370
9371
9379function getLanguageCodeFromCountryCode($countrycode)
9380{
9381 global $mysoc;
9382
9383 if (empty($countrycode)) {
9384 return null;
9385 }
9386
9387 if (strtoupper($countrycode) == 'MQ') {
9388 return 'fr_CA';
9389 }
9390 if (strtoupper($countrycode) == 'SE') {
9391 return 'sv_SE'; // se_SE is Sami/Sweden, and we want in priority sv_SE for SE country
9392 }
9393 if (strtoupper($countrycode) == 'CH') {
9394 if ($mysoc->country_code == 'FR') {
9395 return 'fr_CH';
9396 }
9397 if ($mysoc->country_code == 'DE') {
9398 return 'de_CH';
9399 }
9400 if ($mysoc->country_code == 'IT') {
9401 return 'it_CH';
9402 }
9403 }
9404
9405 // Locale list taken from:
9406 // http://stackoverflow.com/questions/3191664/
9407 // list-of-all-locales-and-their-short-codes
9408 $locales = array(
9409 'af-ZA',
9410 'am-ET',
9411 'ar-AE',
9412 'ar-BH',
9413 'ar-DZ',
9414 'ar-EG',
9415 'ar-IQ',
9416 'ar-JO',
9417 'ar-KW',
9418 'ar-LB',
9419 'ar-LY',
9420 'ar-MA',
9421 'ar-OM',
9422 'ar-QA',
9423 'ar-SA',
9424 'ar-SY',
9425 'ar-TN',
9426 'ar-YE',
9427 //'as-IN', // Moved after en-IN
9428 'ba-RU',
9429 'be-BY',
9430 'bg-BG',
9431 'bn-BD',
9432 //'bn-IN', // Moved after en-IN
9433 'bo-CN',
9434 'br-FR',
9435 'ca-ES',
9436 'co-FR',
9437 'cs-CZ',
9438 'cy-GB',
9439 'da-DK',
9440 'de-AT',
9441 'de-CH',
9442 'de-DE',
9443 'de-LI',
9444 'de-LU',
9445 'dv-MV',
9446 'el-GR',
9447 'en-AU',
9448 'en-BZ',
9449 'en-CA',
9450 'en-GB',
9451 'en-IE',
9452 'en-IN',
9453 'as-IN', // as-IN must be after en-IN (en in priority if country is IN)
9454 'bn-IN', // bn-IN must be after en-IN (en in priority if country is IN)
9455 'en-JM',
9456 'en-MY',
9457 'en-NZ',
9458 'en-PH',
9459 'en-SG',
9460 'en-TT',
9461 'en-US',
9462 'en-ZA',
9463 'en-ZW',
9464 'es-AR',
9465 'es-BO',
9466 'es-CL',
9467 'es-CO',
9468 'es-CR',
9469 'es-DO',
9470 'es-EC',
9471 'es-ES',
9472 'es-GT',
9473 'es-HN',
9474 'es-MX',
9475 'es-NI',
9476 'es-PA',
9477 'es-PE',
9478 'es-PR',
9479 'es-PY',
9480 'es-SV',
9481 'es-US',
9482 'es-UY',
9483 'es-VE',
9484 'et-EE',
9485 'eu-ES',
9486 'fa-IR',
9487 'fi-FI',
9488 'fo-FO',
9489 'fr-BE',
9490 'fr-CA',
9491 'fr-CH',
9492 'fr-FR',
9493 'fr-LU',
9494 'fr-MC',
9495 'fy-NL',
9496 'ga-IE',
9497 'gd-GB',
9498 'gl-ES',
9499 'gu-IN',
9500 'he-IL',
9501 'hi-IN',
9502 'hr-BA',
9503 'hr-HR',
9504 'hu-HU',
9505 'hy-AM',
9506 'id-ID',
9507 'ig-NG',
9508 'ii-CN',
9509 'is-IS',
9510 'it-CH',
9511 'it-IT',
9512 'ja-JP',
9513 'ka-GE',
9514 'kk-KZ',
9515 'kl-GL',
9516 'km-KH',
9517 'kn-IN',
9518 'ko-KR',
9519 'ky-KG',
9520 'lb-LU',
9521 'lo-LA',
9522 'lt-LT',
9523 'lv-LV',
9524 'mi-NZ',
9525 'mk-MK',
9526 'ml-IN',
9527 'mn-MN',
9528 'mr-IN',
9529 'ms-BN',
9530 'ms-MY',
9531 'mt-MT',
9532 'nb-NO',
9533 'ne-NP',
9534 'nl-BE',
9535 'nl-NL',
9536 'nn-NO',
9537 'oc-FR',
9538 'or-IN',
9539 'pa-IN',
9540 'pl-PL',
9541 'ps-AF',
9542 'pt-BR',
9543 'pt-PT',
9544 'rm-CH',
9545 'ro-MD',
9546 'ro-RO',
9547 'ru-RU',
9548 'rw-RW',
9549 'sa-IN',
9550 'se-FI',
9551 'se-NO',
9552 'se-SE',
9553 'si-LK',
9554 'sk-SK',
9555 'sl-SI',
9556 'sq-AL',
9557 'sv-FI',
9558 'sv-SE',
9559 'sw-KE',
9560 'ta-IN',
9561 'te-IN',
9562 'th-TH',
9563 'tk-TM',
9564 'tn-ZA',
9565 'tr-TR',
9566 'tt-RU',
9567 'ug-CN',
9568 'uk-UA',
9569 'ur-PK',
9570 'vi-VN',
9571 'wo-SN',
9572 'xh-ZA',
9573 'yo-NG',
9574 'zh-CN',
9575 'zh-HK',
9576 'zh-MO',
9577 'zh-SG',
9578 'zh-TW',
9579 'zu-ZA',
9580 );
9581
9582 $buildprimarykeytotest = strtolower($countrycode) . '-' . strtoupper($countrycode);
9583 if (in_array($buildprimarykeytotest, $locales)) {
9584 return strtolower($countrycode) . '_' . strtoupper($countrycode);
9585 }
9586
9587 if (function_exists('locale_get_primary_language') && function_exists('locale_get_region')) { // Need extension php-intl
9588 foreach ($locales as $locale) {
9589 $locale_language = locale_get_primary_language($locale);
9590 $locale_region = locale_get_region($locale);
9591 if (strtoupper($countrycode) == $locale_region) {
9592 //var_dump($locale.' - '.$locale_language.' - '.$locale_region);
9593 return strtolower($locale_language) . '_' . strtoupper($locale_region);
9594 }
9595 }
9596 } else {
9597 dol_syslog("Warning Extension php-intl is not available", LOG_WARNING);
9598 }
9599
9600 return null;
9601}
9602
9633function complete_head_from_modules($conf, $langs, $object, &$head, &$h, $type, $mode = 'add', $filterorigmodule = '')
9634{
9635 global $hookmanager, $db;
9636
9637 if (isset($conf->modules_parts['tabs'][$type]) && is_array($conf->modules_parts['tabs'][$type])) {
9638 foreach ($conf->modules_parts['tabs'][$type] as $value) {
9639 $values = explode(':', $value);
9640
9641 $reg = array();
9642 if ($mode == 'add' && !preg_match('/^\-/', $values[1])) {
9643 if (count($values) !== 6) {
9644 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);
9645 continue;
9646 }
9647
9648 // new declaration with permissions:
9649 // $value='objecttype:+tabname1:Title1:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
9650 // $value='objecttype:+tabname1:Title1,class,pathfile,method:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
9651 if ($values[0] != $type) {
9652 continue;
9653 }
9654
9655 $newtab = array();
9656 $postab = $h;
9657 // detect if position set in $values[1] ie : +(2)mytab@mymodule (first tab is 0, second is one, ...)
9658 $str = $values[1];
9659 $posstart = strpos($str, '(');
9660 if ($posstart > 0) {
9661 $posend = strpos($str, ')');
9662 if ($posstart > 0) {
9663 $res1 = substr($str, $posstart + 1, $posend - $posstart - 1);
9664 if (is_numeric($res1)) {
9665 $postab = (int) $res1;
9666 $values[1] = '+' . substr($str, $posend + 1);
9667 }
9668 }
9669 }
9670
9671 global $objectoffield; // So we can use $objectoffield int verifCond
9672 $objectoffield = $object;
9673
9674 if (!verifCond($values[4], '2')) {
9675 continue;
9676 }
9677
9678 if ($values[3]) {
9679 if ($filterorigmodule) { // If a filter of module origin has been requested
9680 if (strpos($values[3], '@')) { // This is an external module
9681 if ($filterorigmodule != 'external') {
9682 continue;
9683 }
9684 } else { // This looks a core module
9685 if ($filterorigmodule != 'core') {
9686 continue;
9687 }
9688 }
9689 }
9690 $langs->load($values[3]);
9691 }
9692
9693 if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
9694 // If label is "SUBSTITUION_..."
9695 $substitutionarray = array();
9696 complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey' => $values[2]));
9697 $label = make_substitutions($reg[1], $substitutionarray);
9698 } else {
9699 // If label is "Label,Class,File,Method", we call the method to show content inside the badge
9700 $labeltemp = explode(',', $values[2]);
9701 $label = $langs->trans($labeltemp[0]);
9702
9703 if (!empty($labeltemp[1]) && is_object($object) && !empty($object->id)) {
9704 dol_include_once($labeltemp[2]);
9705 $classtoload = $labeltemp[1];
9706 if (class_exists($classtoload)) {
9707 $obj = new $classtoload($db);
9708 $function = $labeltemp[3];
9709 if ($obj && $function && method_exists($obj, $function)) {
9710 // @phan-suppress-next-line PhanPluginUnknownObjectMethodCall
9711 $nbrec = $obj->$function($object->id, $obj);
9712 if (!empty($nbrec)) {
9713 $label .= '<span class="badge marginleftonlyshort">' . $nbrec . '</span>';
9714 }
9715 }
9716 }
9717 }
9718 }
9719 $url = preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[5]);
9720 $link = parse_url($url);
9721 $query = [];
9722 if (isset($link['query'])) {
9723 parse_str($link['query'], $query);
9724 }
9725 $newtab[0] = dolBuildUrl(dol_buildpath($link['path'], 1), $query);
9726 $newtab[1] = $label;
9727 $newtab[2] = str_replace('+', '', $values[1]);
9728 $h++;
9729
9730 // set tab at its position
9731 $head = array_merge(array_slice($head, 0, $postab), array($newtab), array_slice($head, $postab));
9732 } elseif ($mode == 'remove' && preg_match('/^\-/', $values[1])) {
9733 if ($values[0] != $type) {
9734 continue;
9735 }
9736 $tabname = str_replace('-', '', $values[1]);
9737 foreach ($head as $key => $val) {
9738 $condition = (!empty($values[3]) ? verifCond($values[3], '2') : 1);
9739 //var_dump($key.' - '.$tabname.' - '.$head[$key][2].' - '.$values[3].' - '.$condition);
9740 if ($head[$key][2] == $tabname && $condition) {
9741 unset($head[$key]);
9742 break;
9743 }
9744 }
9745 }
9746 }
9747 }
9748
9749 // No need to make a return $head. Var is modified as a reference
9750 if (!empty($hookmanager)) {
9751 $parameters = array('object' => $object, 'mode' => $mode, 'head' => &$head, 'filterorigmodule' => $filterorigmodule, 'type' => $type);
9752 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable
9753 $reshook = $hookmanager->executeHooks('completeTabsHead', $parameters, $object);
9754 if ($reshook > 0) { // Hook ask to replace completely the array
9755 $head = $hookmanager->resArray;
9756 } else { // Hook
9757 $head = array_merge($head, $hookmanager->resArray);
9758 }
9759 $h = count($head);
9760 }
9761}
9762
9763
9773function dolExplodeIntoArray($string, $delimiter = ';', $kv = '=')
9774{
9775 if (is_null($string)) {
9776 return array();
9777 }
9778
9779 if (preg_match('/^\[.*\]$/sm', $delimiter) || preg_match('/^\‍(.*\‍)$/sm', $delimiter)) {
9780 // This is a regex string
9781 $newdelimiter = $delimiter;
9782 } else {
9783 // This is a simple string
9784 // @phan-suppress-next-line PhanPluginSuspiciousParamPositionInternal
9785 $newdelimiter = preg_quote($delimiter, '/');
9786 }
9787
9788 if ($a = preg_split('/' . $newdelimiter . '/', $string)) {
9789 $ka = array();
9790 foreach ($a as $s) { // each part
9791 if ($s) {
9792 if ($pos = strpos($s, $kv)) { // key/value delimiter
9793 $ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv)));
9794 } else { // key delimiter not found
9795 $ka[] = trim($s);
9796 }
9797 }
9798 }
9799 return $ka;
9800 }
9801
9802 return array();
9803}
9804
9812function dolExplodeKeepIfQuotes($input)
9813{
9814 // Use regexp to capture words and section in quotes
9815 $matches = array();
9816 preg_match_all('/"([^"]*)"|\'([^\']*)\'|(\S+)/', $input, $matches);
9817
9818 // Merge result and delete empty values
9819
9820 $result = array_map(
9827 static function ($a, $b, $c) {
9828 if ($a !== '') {
9829 return $a;
9830 }
9831 if ($b !== '') {
9832 return $b;
9833 }
9834 if ($c !== '') {
9835 return $c;
9836 }
9837 return '';
9838 },
9839 $matches[1],
9840 $matches[2],
9841 $matches[3]
9842 );
9843 return array_values(array_filter(
9844 $result,
9851 static function ($val) {
9852 return $val !== '';
9853 }
9854 ));
9855}
9856
9857
9865function dol_getmypid()
9866{
9867 if (!function_exists('getmypid')) {
9868 return mt_rand(99900000, 99965535);
9869 } else {
9870 return getmypid(); // May be a number on 64 bits (depending on OS)
9871 }
9872}
9873
9896function natural_search($fields, $value, $mode = 0, $nofirstand = 0, $sqltoadd = '')
9897{
9898 global $db, $langs;
9899
9900 $value = trim($value);
9901
9902 if ($mode == 0) {
9903 $value = preg_replace('/\*/', '%', $value); // Replace * with %
9904 }
9905 if ($mode == 1) {
9906 $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
9907 }
9908
9909 $value = preg_replace('/\s*\|\s*/', '|', $value);
9910
9911 // Split criteria on ' ' but not if we are inside quotes.
9912 // For mode 3, the split is done later on the , only and not on the ' '.
9913 if ($mode != -3 && $mode != 3) {
9914 $crits = dolExplodeKeepIfQuotes($value);
9915 } else {
9916 $crits = array($value);
9917 }
9918
9919 $res = '';
9920 if (!is_array($fields)) {
9921 $fields = array($fields);
9922 }
9923 $i1 = 0; // count the nb of "and" criteria added (all fields / criteria)
9924 foreach ($crits as $crit) { // Loop on each AND criteria
9925 $crit = trim($crit);
9926 $i2 = 0; // count the nb of valid criteria added for this this first criteria
9927 $newres = '';
9928
9929 foreach ($fields as $field) {
9930 if ($mode == 1) {
9931 $tmpcrits = explode('|', $crit);
9932 $i3 = 0; // count the nb of valid criteria added for this current field
9933 foreach ($tmpcrits as $tmpcrit) {
9934 if ($tmpcrit !== '0' && empty($tmpcrit)) {
9935 continue;
9936 }
9937 $tmpcrit = trim($tmpcrit);
9938
9939 $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
9940
9941 $operator = '=';
9942 $newcrit = preg_replace('/([!<>=]+)/', '', $tmpcrit);
9943
9944 $reg = array();
9945 preg_match('/([!<>=]+)/', $tmpcrit, $reg);
9946 if (!empty($reg[1])) {
9947 $operator = $reg[1];
9948 }
9949 if ($newcrit != '') {
9950 $numnewcrit = price2num($newcrit);
9951 if (is_numeric($numnewcrit)) {
9952 $newres .= $db->sanitize($field) . ' ' . $operator . ' ' . ((float) $numnewcrit); // should be a numeric
9953 } else {
9954 $newres .= '1 = 2'; // force false, we received a corrupted data
9955 }
9956 $i3++; // a criteria was added to string
9957 }
9958 }
9959 $i2++; // a criteria for 1 more field was added to string
9960 } elseif ($mode == 2 || $mode == -2) {
9961 $crit = preg_replace('/[^\-0-9,]/', '', $crit); // ID are always integer
9962 $newres .= ($i2 > 0 ? ' OR ' : '') . $db->sanitize($field) . " " . ($mode == -2 ? 'NOT ' : '');
9963 $newres .= $crit ? "IN (" . $db->sanitize($db->escape($crit)) . ")" : "IN (0)";
9964 if ($mode == -2) {
9965 $newres .= ' OR ' . $db->sanitize($field) . ' IS NULL';
9966 }
9967 $i2++; // a criteria for 1 more field was added to string
9968 } elseif ($mode == 3 || $mode == -3) {
9969 $tmparray = explode(',', $crit);
9970 if (count($tmparray)) {
9971 $listofcodes = '';
9972 $listofcodesnot = '';
9973 foreach ($tmparray as $val) {
9974 $val = trim($val);
9975 if ($val !== '') {
9976 if (preg_match('/^!/', $val)) {
9977 $listofcodesnot .= ($listofcodesnot ? ',' : '');
9978 $listofcodesnot .= "'" . $db->escape(preg_replace('/^!=?/', '', $val)) . "'";
9979 } else {
9980 $listofcodes .= ($listofcodes ? ',' : '');
9981 $listofcodes .= "'" . $db->escape($val) . "'";
9982 }
9983 }
9984 }
9985 $newres .= ($i2 > 0 ? ' OR ' : '');
9986 if ($listofcodes && $listofcodesnot) {
9987 $newres .= '(';
9988 }
9989 if ($listofcodes) {
9990 $newres .= $db->sanitize($field) . " " . ($mode == -3 ? 'NOT IN' : 'IN') . " (" . $db->sanitize($listofcodes, 1, 0, 1) . ")";
9991 }
9992 if ($listofcodes && $listofcodesnot) {
9993 $newres .= ' AND ';
9994 }
9995 if ($listofcodesnot) {
9996 $newres .= $db->sanitize($field) . " " . ($mode == -3 ? 'IN ' : 'NOT IN') . " (" . $db->sanitize($listofcodesnot, 1, 0, 1) . ")";
9997 }
9998 if ($listofcodes && $listofcodesnot) {
9999 $newres .= ')';
10000 }
10001 $i2++; // a criteria for 1 more field was added to string
10002 }
10003 if ($mode == -3) {
10004 $newres .= ' OR ' . $db->sanitize($field) . ' IS NULL';
10005 }
10006 } elseif ($mode == 4) {
10007 $tmparray = explode(',', $crit);
10008 if (count($tmparray)) {
10009 $listofcodes = '';
10010 foreach ($tmparray as $val) {
10011 $val = trim($val);
10012 if ($val) {
10013 $newres .= ($i2 > 0 ? " OR (" : "(") . $db->sanitize($field) . " LIKE '" . $db->escape($val) . ",%'";
10014 $newres .= ' OR ' . $db->sanitize($field) . " = '" . $db->escape($val) . "'";
10015 $newres .= ' OR ' . $db->sanitize($field) . " LIKE '%," . $db->escape($val) . "'";
10016 $newres .= ' OR ' . $db->sanitize($field) . " LIKE '%," . $db->escape($val) . ",%'";
10017 $newres .= ')';
10018 $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)
10019 }
10020 }
10021 }
10022 } else { // $mode=0
10023 $tmpcrits = explode('|', $crit);
10024 $i3 = 0; // count the nb of valid criteria added for the current couple criteria/field
10025 foreach ($tmpcrits as $tmpcrit) { // loop on each OR criteria
10026 if ($tmpcrit !== '0' && empty($tmpcrit)) {
10027 continue;
10028 }
10029 $tmpcrit = trim($tmpcrit);
10030
10031 if ($tmpcrit == '^$' || strpos($crit, '!') === 0) { // If we search empty, we must combined different OR fields with AND
10032 $newres .= (($i2 > 0 || $i3 > 0) ? ' AND ' : '');
10033 } else {
10034 $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
10035 }
10036
10037 $isSellist = false;
10038 $table = $label = $key = null;
10039
10040 if (strpos($field, 'ef.') === 0) {
10041 $extrafieldName = substr($field, 3);
10042 $extrafields = new ExtraFields($db);
10043 $extrafields->fetch_name_optionals_label('product');
10044
10045 if (isset($extrafields->attributes['product']['type'][$extrafieldName]) && $extrafields->attributes['product']['type'][$extrafieldName] === 'sellist') {
10046 $isSellist = true;
10047 $paramArray = $extrafields->attributes['product']['param'][$extrafieldName]['options'] ?? [];
10048 $param = array_key_first($paramArray);
10049 list($table, $label, $key) = explode(':', $param);
10050 }
10051 }
10052
10053 if (preg_match('/\.(id|rowid)$/', $field)) { // Special case for rowid that is sometimes a ref so used as a search field
10054 $newres .= $db->sanitize($field) . " = " . (is_numeric($tmpcrit) ? ((float) $tmpcrit) : '0');
10055 } else {
10056 $tmpcrit2 = $tmpcrit;
10057 $tmpbefore = '%';
10058 $tmpafter = '%';
10059 $tmps = '';
10060
10061 if ($isSellist && $key && $table && $label) {
10062 $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) . "%')";
10063 } else {
10064 if (preg_match('/^!/', $tmpcrit)) {
10065 $tmps .= $db->sanitize($field) . " NOT LIKE "; // ! as exclude character
10066 $tmpcrit2 = preg_replace('/^!/', '', $tmpcrit2);
10067 } else {
10068 $tmps .= $db->sanitize($field) . " LIKE ";
10069 }
10070 $tmps .= "'";
10071
10072 if (preg_match('/^[\^\$]/', $tmpcrit)) {
10073 $tmpbefore = '';
10074 $tmpcrit2 = preg_replace('/^[\^\$]/', '', $tmpcrit2);
10075 }
10076 if (preg_match('/[\^\$]$/', $tmpcrit)) {
10077 $tmpafter = '';
10078 $tmpcrit2 = preg_replace('/[\^\$]$/', '', $tmpcrit2);
10079 }
10080
10081 if ($tmpcrit2 == '' || preg_match('/^!/', $tmpcrit)) {
10082 $tmps = "(" . $tmps;
10083 }
10084 $newres .= $tmps;
10085 $newres .= $tmpbefore;
10086 $newres .= $db->escape($tmpcrit2);
10087 $newres .= $tmpafter;
10088 $newres .= "'";
10089 if ($tmpcrit2 == '' || preg_match('/^!/', $tmpcrit)) {
10090 $newres .= " OR " . $db->sanitize($field) . " IS NULL)";
10091 }
10092 }
10093 }
10094
10095 $i3++;
10096 }
10097
10098 $i2++; // a criteria for 1 more field was added to string
10099 }
10100 }
10101
10102 if ($sqltoadd) {
10103 $newres .= ($newres ? '' : ' OR ').str_replace('__KEYTOSEARCH__', $db->escape($crit), $sqltoadd);
10104 }
10105
10106 if ($newres) {
10107 $res = $res . ($res ? ' AND ' : '') . ($i2 > 1 ? '(' : '') . $newres . ($i2 > 1 ? ')' : '');
10108 }
10109 $i1++;
10110 }
10111 $res = ($nofirstand ? "" : " AND ") . "(" . $res . ")";
10112
10113 return $res;
10114}
10115
10116
10125function getImageFileNameForSize($file, $extName, $extImgTarget = '')
10126{
10127 $dirName = dirname($file);
10128 if ($dirName == '.') {
10129 $dirName = '';
10130 }
10131
10132 if (!in_array($extName, array('', '_small', '_mini'))) {
10133 return 'Bad parameter extName';
10134 }
10135
10136 $fileName = preg_replace('/(\.gif|\.jpeg|\.jpg|\.png|\.bmp|\.webp|\.avif)$/i', '', $file); // We remove image extension, whatever is its case
10137 $fileName = basename($fileName);
10138
10139 if (empty($extImgTarget)) {
10140 $extImgTarget = (preg_match('/\.jpg$/i', $file) ? '.jpg' : '');
10141 }
10142 if (empty($extImgTarget)) {
10143 $extImgTarget = (preg_match('/\.jpeg$/i', $file) ? '.jpeg' : '');
10144 }
10145 if (empty($extImgTarget)) {
10146 $extImgTarget = (preg_match('/\.gif$/i', $file) ? '.gif' : '');
10147 }
10148 if (empty($extImgTarget)) {
10149 $extImgTarget = (preg_match('/\.png$/i', $file) ? '.png' : '');
10150 }
10151 if (empty($extImgTarget)) {
10152 $extImgTarget = (preg_match('/\.bmp$/i', $file) ? '.bmp' : '');
10153 }
10154 if (empty($extImgTarget)) {
10155 $extImgTarget = (preg_match('/\.webp$/i', $file) ? '.webp' : '');
10156 }
10157 if (empty($extImgTarget)) {
10158 $extImgTarget = (preg_match('/\.avif$/i', $file) ? '.avif' : '');
10159 }
10160
10161 if (!$extImgTarget) {
10162 return $file;
10163 }
10164
10165 $subdir = '';
10166 if ($extName) {
10167 $subdir = 'thumbs/';
10168 }
10169
10170 return ($dirName ? $dirName . '/' : '') . $subdir . $fileName . $extName . $extImgTarget; // New filename for thumb
10171}
10172
10173
10180function getLabelSpecialCode($idcode)
10181{
10182 global $langs;
10183
10184 $arrayspecialines = array(1 => 'Transport', 2 => 'EcoTax', 3 => 'Option');
10185 if ($idcode > 10) {
10186 return 'Module ID ' . $idcode;
10187 }
10188 if (!empty($arrayspecialines[$idcode])) {
10189 return $langs->trans($arrayspecialines[$idcode]);
10190 }
10191 return '';
10192}
10193
10194
10202function dolIsAllowedForPreview($file)
10203{
10204 // Check .noexe extension in filename
10205 if (preg_match('/\.noexe$/i', $file)) {
10206 return 0;
10207 }
10208
10209 // Check mime types
10210 $mime_preview = array('avif', 'bmp', 'jpeg', 'png', 'gif', 'tiff', 'pdf', 'plain', 'css', 'webp', 'webm', 'mp4');
10211 if (getDolGlobalString('MAIN_ALLOW_SVG_FILES_AS_IMAGES')) {
10212 $mime_preview[] = 'svg+xml';
10213 }
10214 if (getDolGlobalString('MAIN_ALLOW_XML_FILES_AS_PREVIEW')) {
10215 $mime_preview[] = 'xml';
10216 }
10217
10218 //$mime_preview[]='vnd.oasis.opendocument.presentation';
10219 //$mime_preview[]='archive';
10220 $num_mime = array_search(dol_mimetype($file, '', 1), $mime_preview);
10221 if ($num_mime !== false) {
10222 return 1;
10223 }
10224
10225 // By default, not allowed for preview
10226 return 0;
10227}
10228
10229
10239function dol_mimetype($file, $default = 'application/octet-stream', $mode = 0)
10240{
10241 $mime = $default;
10242 $imgmime = 'other.png';
10243 $famime = 'file-o';
10244 $srclang = '';
10245
10246 $tmpfile = preg_replace('/\.noexe$/', '', $file);
10247
10248 // Plain text files
10249 if (preg_match('/\.txt$/i', $tmpfile)) {
10250 $mime = 'text/plain';
10251 $imgmime = 'text.png';
10252 $famime = 'file-alt';
10253 } elseif (preg_match('/\.rtx$/i', $tmpfile)) {
10254 $mime = 'text/richtext';
10255 $imgmime = 'text.png';
10256 $famime = 'file-alt';
10257 } elseif (preg_match('/\.csv$/i', $tmpfile)) {
10258 $mime = 'text/csv';
10259 $imgmime = 'text.png';
10260 $famime = 'file-csv';
10261 } elseif (preg_match('/\.tsv$/i', $tmpfile)) {
10262 $mime = 'text/tab-separated-values';
10263 $imgmime = 'text.png';
10264 $famime = 'file-alt';
10265 } elseif (preg_match('/\.(cf|conf|log)$/i', $tmpfile)) {
10266 $mime = 'text/plain';
10267 $imgmime = 'text.png';
10268 $famime = 'file-alt';
10269 } elseif (preg_match('/\.ini$/i', $tmpfile)) {
10270 $mime = 'text/plain';
10271 $imgmime = 'text.png';
10272 $srclang = 'ini';
10273 $famime = 'file-alt';
10274 } elseif (preg_match('/\.md$/i', $tmpfile)) {
10275 $mime = 'text/plain';
10276 $imgmime = 'text.png';
10277 $srclang = 'md';
10278 $famime = 'file-alt';
10279 } elseif (preg_match('/\.css$/i', $tmpfile)) {
10280 $mime = 'text/css';
10281 $imgmime = 'css.png';
10282 $srclang = 'css';
10283 $famime = 'file-alt';
10284 } elseif (preg_match('/\.lang$/i', $tmpfile)) {
10285 $mime = 'text/plain';
10286 $imgmime = 'text.png';
10287 $srclang = 'lang';
10288 $famime = 'file-alt';
10289 } elseif (preg_match('/\.(crt|cer|key|pub)$/i', $tmpfile)) { // Certificate files
10290 $mime = 'text/plain';
10291 $imgmime = 'text.png';
10292 $famime = 'file-alt';
10293 } elseif (preg_match('/\.(html|htm|shtml)$/i', $tmpfile)) { // XML based (HTML/XML/XAML)
10294 $mime = 'text/html';
10295 $imgmime = 'html.png';
10296 $srclang = 'html';
10297 $famime = 'file-alt';
10298 } elseif (preg_match('/\.(xml|xhtml)$/i', $tmpfile)) {
10299 $mime = 'text/xml';
10300 $imgmime = 'other.png';
10301 $srclang = 'xml';
10302 $famime = 'file-alt';
10303 } elseif (preg_match('/\.xaml$/i', $tmpfile)) {
10304 $mime = 'text/xml';
10305 $imgmime = 'other.png';
10306 $srclang = 'xaml';
10307 $famime = 'file-alt';
10308 } elseif (preg_match('/\.bas$/i', $tmpfile)) { // Languages
10309 $mime = 'text/plain';
10310 $imgmime = 'text.png';
10311 $srclang = 'bas';
10312 $famime = 'file-code';
10313 } elseif (preg_match('/\.(c)$/i', $tmpfile)) {
10314 $mime = 'text/plain';
10315 $imgmime = 'text.png';
10316 $srclang = 'c';
10317 $famime = 'file-code';
10318 } elseif (preg_match('/\.(cpp)$/i', $tmpfile)) {
10319 $mime = 'text/plain';
10320 $imgmime = 'text.png';
10321 $srclang = 'cpp';
10322 $famime = 'file-code';
10323 } elseif (preg_match('/\.cs$/i', $tmpfile)) {
10324 $mime = 'text/plain';
10325 $imgmime = 'text.png';
10326 $srclang = 'cs';
10327 $famime = 'file-code';
10328 } elseif (preg_match('/\.(h)$/i', $tmpfile)) {
10329 $mime = 'text/plain';
10330 $imgmime = 'text.png';
10331 $srclang = 'h';
10332 $famime = 'file-code';
10333 } elseif (preg_match('/\.(java|jsp)$/i', $tmpfile)) {
10334 $mime = 'text/plain';
10335 $imgmime = 'text.png';
10336 $srclang = 'java';
10337 $famime = 'file-code';
10338 } elseif (preg_match('/\.php([0-9]{1})?$/i', $tmpfile)) {
10339 $mime = 'text/plain';
10340 $imgmime = 'php.png';
10341 $srclang = 'php';
10342 $famime = 'file-code';
10343 } elseif (preg_match('/\.phtml$/i', $tmpfile)) {
10344 $mime = 'text/plain';
10345 $imgmime = 'php.png';
10346 $srclang = 'php';
10347 $famime = 'file-code';
10348 } elseif (preg_match('/\.(pl|pm)$/i', $tmpfile)) {
10349 $mime = 'text/plain';
10350 $imgmime = 'pl.png';
10351 $srclang = 'perl';
10352 $famime = 'file-code';
10353 } elseif (preg_match('/\.sql$/i', $tmpfile)) {
10354 $mime = 'text/plain';
10355 $imgmime = 'text.png';
10356 $srclang = 'sql';
10357 $famime = 'file-code';
10358 } elseif (preg_match('/\.js$/i', $tmpfile)) {
10359 $mime = 'text/x-javascript';
10360 $imgmime = 'jscript.png';
10361 $srclang = 'js';
10362 $famime = 'file-code';
10363 } elseif (preg_match('/\.odp$/i', $tmpfile)) { // Open office
10364 $mime = 'application/vnd.oasis.opendocument.presentation';
10365 $imgmime = 'ooffice.png';
10366 $famime = 'file-powerpoint';
10367 } elseif (preg_match('/\.ods$/i', $tmpfile)) {
10368 $mime = 'application/vnd.oasis.opendocument.spreadsheet';
10369 $imgmime = 'ooffice.png';
10370 $famime = 'file-excel';
10371 } elseif (preg_match('/\.odt$/i', $tmpfile)) {
10372 $mime = 'application/vnd.oasis.opendocument.text';
10373 $imgmime = 'ooffice.png';
10374 $famime = 'file-word';
10375 } elseif (preg_match('/\.mdb$/i', $tmpfile)) { // MS Office
10376 $mime = 'application/msaccess';
10377 $imgmime = 'mdb.png';
10378 $famime = 'file';
10379 } elseif (preg_match('/\.doc[xm]?$/i', $tmpfile)) {
10380 $mime = 'application/msword';
10381 $imgmime = 'doc.png';
10382 $famime = 'file-word';
10383 } elseif (preg_match('/\.dot[xm]?$/i', $tmpfile)) {
10384 $mime = 'application/msword';
10385 $imgmime = 'doc.png';
10386 $famime = 'file-word';
10387 } elseif (preg_match('/\.xlt(x)?$/i', $tmpfile)) {
10388 $mime = 'application/vnd.ms-excel';
10389 $imgmime = 'xls.png';
10390 $famime = 'file-excel';
10391 } elseif (preg_match('/\.xla(m)?$/i', $tmpfile)) {
10392 $mime = 'application/vnd.ms-excel';
10393 $imgmime = 'xls.png';
10394 $famime = 'file-excel';
10395 } elseif (preg_match('/\.xls$/i', $tmpfile)) {
10396 $mime = 'application/vnd.ms-excel';
10397 $imgmime = 'xls.png';
10398 $famime = 'file-excel';
10399 } elseif (preg_match('/\.xls[bmx]$/i', $tmpfile)) {
10400 $mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
10401 $imgmime = 'xls.png';
10402 $famime = 'file-excel';
10403 } elseif (preg_match('/\.pps[mx]?$/i', $tmpfile)) {
10404 $mime = 'application/vnd.ms-powerpoint';
10405 $imgmime = 'ppt.png';
10406 $famime = 'file-powerpoint';
10407 } elseif (preg_match('/\.ppt[mx]?$/i', $tmpfile)) {
10408 $mime = 'application/x-mspowerpoint';
10409 $imgmime = 'ppt.png';
10410 $famime = 'file-powerpoint';
10411 } elseif (preg_match('/\.pdf$/i', $tmpfile)) { // Other
10412 $mime = 'application/pdf';
10413 $imgmime = 'pdf.png';
10414 $famime = 'file-pdf';
10415 } elseif (preg_match('/\.bat$/i', $tmpfile)) { // Scripts
10416 $mime = 'text/x-bat';
10417 $imgmime = 'script.png';
10418 $srclang = 'dos';
10419 $famime = 'file-code';
10420 } elseif (preg_match('/\.sh$/i', $tmpfile)) {
10421 $mime = 'text/x-sh';
10422 $imgmime = 'script.png';
10423 $srclang = 'bash';
10424 $famime = 'file-code';
10425 } elseif (preg_match('/\.ksh$/i', $tmpfile)) {
10426 $mime = 'text/x-ksh';
10427 $imgmime = 'script.png';
10428 $srclang = 'bash';
10429 $famime = 'file-code';
10430 } elseif (preg_match('/\.bash$/i', $tmpfile)) {
10431 $mime = 'text/x-bash';
10432 $imgmime = 'script.png';
10433 $srclang = 'bash';
10434 $famime = 'file-code';
10435 } elseif (preg_match('/\.ico$/i', $tmpfile)) { // Images
10436 $mime = 'image/x-icon';
10437 $imgmime = 'image.png';
10438 $famime = 'file-image';
10439 } elseif (preg_match('/\.(jpg|jpeg)$/i', $tmpfile)) {
10440 $mime = 'image/jpeg';
10441 $imgmime = 'image.png';
10442 $famime = 'file-image';
10443 } elseif (preg_match('/\.png$/i', $tmpfile)) {
10444 $mime = 'image/png';
10445 $imgmime = 'image.png';
10446 $famime = 'file-image';
10447 } elseif (preg_match('/\.gif$/i', $tmpfile)) {
10448 $mime = 'image/gif';
10449 $imgmime = 'image.png';
10450 $famime = 'file-image';
10451 } elseif (preg_match('/\.bmp$/i', $tmpfile)) {
10452 $mime = 'image/bmp';
10453 $imgmime = 'image.png';
10454 $famime = 'file-image';
10455 } elseif (preg_match('/\.(tif|tiff)$/i', $tmpfile)) {
10456 $mime = 'image/tiff';
10457 $imgmime = 'image.png';
10458 $famime = 'file-image';
10459 } elseif (preg_match('/\.svg$/i', $tmpfile)) {
10460 $mime = 'image/svg+xml';
10461 $imgmime = 'image.png';
10462 $famime = 'file-image';
10463 } elseif (preg_match('/\.webp$/i', $tmpfile)) {
10464 $mime = 'image/webp';
10465 $imgmime = 'image.png';
10466 $famime = 'file-image';
10467 } elseif (preg_match('/\.vcs$/i', $tmpfile)) { // Calendar
10468 $mime = 'text/calendar';
10469 $imgmime = 'other.png';
10470 $famime = 'file-alt';
10471 } elseif (preg_match('/\.ics$/i', $tmpfile)) {
10472 $mime = 'text/calendar';
10473 $imgmime = 'other.png';
10474 $famime = 'file-alt';
10475 } elseif (preg_match('/\.torrent$/i', $tmpfile)) { // Other
10476 $mime = 'application/x-bittorrent';
10477 $imgmime = 'other.png';
10478 $famime = 'file-o';
10479 } elseif (preg_match('/\.(mp3|ogg|au|wav|wma|mid)$/i', $tmpfile)) { // Audio
10480 $mime = 'audio';
10481 $imgmime = 'audio.png';
10482 $famime = 'file-audio';
10483 } elseif (preg_match('/\.mp4$/i', $tmpfile)) { // Video
10484 $mime = 'video/mp4';
10485 $imgmime = 'video.png';
10486 $famime = 'file-video';
10487 } elseif (preg_match('/\.ogv$/i', $tmpfile)) {
10488 $mime = 'video/ogg';
10489 $imgmime = 'video.png';
10490 $famime = 'file-video';
10491 } elseif (preg_match('/\.webm$/i', $tmpfile)) {
10492 $mime = 'video/webm';
10493 $imgmime = 'video.png';
10494 $famime = 'file-video';
10495 } elseif (preg_match('/\.avif$/i', $tmpfile)) {
10496 $mime = 'image/avif';
10497 $imgmime = 'image.png';
10498 $famime = 'file-image';
10499 } elseif (preg_match('/\.avi$/i', $tmpfile)) {
10500 $mime = 'video/x-msvideo';
10501 $imgmime = 'video.png';
10502 $famime = 'file-video';
10503 } elseif (preg_match('/\.divx$/i', $tmpfile)) {
10504 $mime = 'video/divx';
10505 $imgmime = 'video.png';
10506 $famime = 'file-video';
10507 } elseif (preg_match('/\.xvid$/i', $tmpfile)) {
10508 $mime = 'video/xvid';
10509 $imgmime = 'video.png';
10510 $famime = 'file-video';
10511 } elseif (preg_match('/\.(wmv|mpg|mpeg)$/i', $tmpfile)) {
10512 $mime = 'video';
10513 $imgmime = 'video.png';
10514 $famime = 'file-video';
10515 } elseif (preg_match('/\.(zip|rar|gz|tgz|xz|z|cab|bz2|7z|tar|lzh|zst)$/i', $tmpfile)) { // Archive
10516 // application/xxx where zzz is zip, ...
10517 $mime = 'archive';
10518 $imgmime = 'archive.png';
10519 $famime = 'file-archive';
10520 } elseif (preg_match('/\.(exe|com)$/i', $tmpfile)) { // Exe
10521 $mime = 'application/octet-stream';
10522 $imgmime = 'other.png';
10523 $famime = 'file-o';
10524 } elseif (preg_match('/\.(dll|lib|o|so|a)$/i', $tmpfile)) { // Lib
10525 $mime = 'library';
10526 $imgmime = 'library.png';
10527 $famime = 'file-o';
10528 } elseif (preg_match('/\.err$/i', $tmpfile)) { // phpcs:ignore
10529 $mime = 'error';
10530 $imgmime = 'error.png';
10531 $famime = 'file-alt';
10532 }
10533
10534 if ($famime == 'file-o') {
10535 // file-o seems to not work in fontawesome 5
10536 $famime = 'file';
10537 }
10538
10539 // Return mimetype string
10540 switch ((int) $mode) {
10541 case 1:
10542 $tmp = explode('/', $mime);
10543 return (!empty($tmp[1]) ? $tmp[1] : $tmp[0]);
10544 case 2:
10545 return $imgmime;
10546 case 3:
10547 return $srclang;
10548 case 4:
10549 return $famime;
10550 }
10551 return $mime;
10552}
10553
10565function getDictionaryValue($tablename, $field, $id, $checkentity = false, $rowidfield = 'rowid')
10566{
10567 global $conf, $db;
10568
10569 $tablename = preg_replace('/^' . preg_quote(MAIN_DB_PREFIX, '/') . '/', '', $tablename); // Clean name of table for backward compatibility.
10570
10571 $dictvalues = (isset($conf->cache['dictvalues_' . $tablename]) ? $conf->cache['dictvalues_' . $tablename] : null);
10572
10573 if (is_null($dictvalues)) {
10574 $dictvalues = array();
10575
10576 $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
10577 if ($checkentity) {
10578 $sql .= ' AND entity IN (0,' . getEntity($tablename) . ')';
10579 }
10580
10581 $resql = $db->query($sql);
10582 if ($resql) {
10583 while ($obj = $db->fetch_object($resql)) {
10584 $dictvalues[$obj->$rowidfield] = $obj; // $obj is stdClass
10585 }
10586 } else {
10587 dol_print_error($db);
10588 }
10589
10590 $conf->cache['dictvalues_' . $tablename] = $dictvalues;
10591 }
10592
10593 if (!empty($dictvalues[$id])) {
10594 // Found
10595 $tmp = $dictvalues[$id];
10596 return (property_exists($tmp, $field) ? $tmp->$field : '');
10597 } else {
10598 // Not found
10599 return '';
10600 }
10601}
10602
10609function colorIsLight($stringcolor)
10610{
10611 $stringcolor = str_replace('#', '', $stringcolor);
10612 $res = -1;
10613 if (!empty($stringcolor)) {
10614 $res = 0;
10615 $tmp = explode(',', $stringcolor);
10616 if (count($tmp) > 1) { // This is a comma RGB ('255','255','255')
10617 $r = $tmp[0];
10618 $g = $tmp[1];
10619 $b = $tmp[2];
10620 } else {
10621 $hexr = $stringcolor[0] . $stringcolor[1];
10622 $hexg = $stringcolor[2] . $stringcolor[3];
10623 $hexb = $stringcolor[4] . $stringcolor[5];
10624 $r = hexdec($hexr);
10625 $g = hexdec($hexg);
10626 $b = hexdec($hexb);
10627 }
10628 $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm
10629 if ($bright > 0.6) {
10630 $res = 1;
10631 }
10632 }
10633 return $res;
10634}
10635
10644function isVisibleToUserType($type_user, &$menuentry, &$listofmodulesforexternal)
10645{
10646 //print 'type_user='.$type_user.' module='.$menuentry['module'].' enabled='.$menuentry['enabled'].' perms='.$menuentry['perms'];
10647 //print 'ok='.in_array($menuentry['module'], $listofmodulesforexternal);
10648 if (empty($menuentry['enabled'])) {
10649 return 0; // Entry disabled by condition
10650 }
10651 if ($type_user && array_key_exists('module', $menuentry) && $menuentry['module']) {
10652 $tmploops = explode('|', $menuentry['module']);
10653 $found = 0;
10654 foreach ($tmploops as $tmploop) {
10655 if (in_array($tmploop, $listofmodulesforexternal)) {
10656 $found++;
10657 break;
10658 }
10659 }
10660 if (!$found) {
10661 return 0; // Entry is for menus all excluded to external users
10662 }
10663 }
10664 if (!$menuentry['perms'] && $type_user) {
10665 return 0; // No permissions and user is external
10666 }
10667 if (!$menuentry['perms'] && getDolGlobalString('MAIN_MENU_HIDE_UNAUTHORIZED')) {
10668 return 0; // No permissions and option to hide when not allowed, even for internal user, is on
10669 }
10670 if (!$menuentry['perms']) {
10671 return 2; // No permissions and user is external
10672 }
10673 return 1;
10674}
10675
10683function roundUpToNextMultiple($n, $x = 5)
10684{
10685 $result = (ceil($n) % $x === 0) ? ceil($n) : (round(($n + $x / 2) / $x) * $x);
10686 return (int) $result;
10687}
10688
10689
10700function getElementProperties($elementType)
10701{
10702 global $conf, $db, $hookmanager;
10703
10704 $regs = array();
10705
10706 //var_dump($elementType);
10707
10708 $classfile = $classname = $classpath = $subdir = $dir_output = $dir_temp = $parent_element = '';
10709
10710 // Parse element/subelement
10711 $module = $elementType;
10712 $element = $elementType;
10713 $subelement = $elementType;
10714 $table_element = $elementType;
10715
10716 // If we ask a resource form external module (instead of default path)
10717 if (preg_match('/^([^@]+)@([^@]+)$/i', $elementType, $regs)) { // 'myobject@mymodule' (usually external modules)
10718 $element = $subelement = $regs[1];
10719 $table_element = $regs[2].'_'.$regs[1];
10720 $subdir = '/'.$regs[1];
10721 $module = $regs[2];
10722 } elseif (preg_match('/^([^_]+)_([^_]+)/i', $element, $regs)) { // old deprecated syntax: 'myobject_mysubobject' with myobject=mymodule, example 'project_task'
10723 // This is an alternative syntax to 'myobject@mymodule', so it must not be applied when the previous case already matched,
10724 // otherwise the module resolved from the '@' syntax would be overwritten by a wrong guess when $element contains a '_'.
10725 $module = $element = $regs[1];
10726 $table_element = $elementType;
10727 $subelement = $regs[2];
10728 }
10729
10730 // Object lines will use parent classpath and module ref
10731 if (substr($elementType, -3) == 'det') {
10732 $module = preg_replace('/det$/', '', $element);
10733 $subelement = preg_replace('/det$/', '', $subelement);
10734 $classpath = $module . '/class';
10735 $classfile = $module;
10736 $classname = preg_replace('/det$/', 'Line', $element);
10737 if (in_array($module, array('expedition', 'propale', 'facture', 'contrat', 'fichinter', 'ficheinter', 'supplier_order', 'commandefournisseur'))) {
10738 $classname = preg_replace('/det$/', 'Ligne', $element);
10739 }
10740 }
10741 // For compatibility and to work with non standard path
10742 if ($elementType == "action" || $elementType == "actioncomm") {
10743 $classpath = 'comm/action/class';
10744 $subelement = 'Actioncomm';
10745 $module = 'agenda';
10746 $table_element = 'actioncomm';
10747 } elseif ($elementType == 'cronjob') {
10748 $classpath = 'cron/class';
10749 $module = 'cron';
10750 $table_element = 'cron';
10751 } elseif ($elementType == 'adherent_type') {
10752 $classpath = 'adherents/class';
10753 $classfile = 'adherent_type';
10754 $module = 'adherent';
10755 $subelement = 'adherent_type';
10756 $classname = 'AdherentType';
10757 $table_element = 'adherent_type';
10758 } elseif ($elementType == 'bank_account' || $elementType == 'bank' || $elementType == 'banque') {
10759 // 'bank' is the value used for the modulepart when downloading files attached to a bank account
10760 $classpath = 'compta/bank/class';
10761 $module = 'bank'; // We need $conf->bank->dir_output and not $conf->banque->dir_output
10762 $classfile = 'account';
10763 $classname = 'Account';
10764 $element = $subelement = 'bank_account';
10765 $table_element = 'bank_account';
10766 } elseif ($elementType == 'bank_line') {
10767 $classpath = 'compta/bank/class';
10768 $module = 'bank'; // We need $conf->bank->dir_output and not $conf->banque->dir_output
10769 $classfile = 'account';
10770 $classname = 'AccountLine';
10771 } elseif ($elementType == 'remisecheque') {
10772 $classpath = 'compta/paiement/cheque/class';
10773 $classfile = 'remisecheque';
10774 $classname = 'RemiseCheque';
10775 $module = 'bank';
10776 $element = 'chequereceipt';
10777 $subelement = 'cheque';
10778 $table_element = 'bordereau_cheque';
10779 } elseif ($elementType == 'category') {
10780 $classpath = 'categories/class';
10781 $module = 'categorie';
10782 $subelement = 'categorie';
10783 $table_element = 'categorie';
10784 } elseif ($elementType == 'contact') {
10785 $classpath = 'contact/class';
10786 $classfile = 'contact';
10787 $module = 'societe';
10788 $subelement = 'contact';
10789 $table_element = 'socpeople';
10790 $subdir = '/contact';
10791 } elseif ($elementType == 'inventory') {
10792 $module = 'product';
10793 $classpath = 'product/inventory/class';
10794 } elseif ($elementType == 'inventoryline') {
10795 $module = 'product';
10796 $classpath = 'product/inventory/class';
10797 $table_element = 'inventorydet';
10798 $parent_element = 'inventory';
10799 } elseif ($elementType == 'stock' || $elementType == 'entrepot' || $elementType == 'warehouse') {
10800 $module = 'stock';
10801 $classpath = 'product/stock/class';
10802 $classfile = 'entrepot';
10803 $classname = 'Entrepot';
10804 $table_element = 'entrepot';
10805 } elseif ($elementType == 'project' || $elementType == 'projet') {
10806 $classpath = 'projet/class';
10807 $module = 'projet';
10808 $table_element = 'projet';
10809 $classfile = 'project';
10810 $classname = 'Project';
10811 } elseif ($elementType == 'project_task') {
10812 $classpath = 'projet/class';
10813 $module = 'projet';
10814 $subelement = 'task';
10815 $table_element = 'projet_task';
10816 } elseif ($elementType == 'mo') {
10817 $classpath = 'mrp/class';
10818 $module = 'mrp';
10819 $classfile = 'mo';
10820 $classname = 'Mo';
10821 $table_element = 'mrp_mo';
10822 } elseif ($elementType == 'facture' || $elementType == 'invoice') {
10823 $classpath = 'compta/facture/class';
10824 $module = 'facture';
10825 $subelement = 'facture';
10826 $table_element = 'facture';
10827 } elseif ($elementType == 'facturedet') {
10828 $classpath = 'compta/facture/class';
10829 $classfile = 'facture';
10830 $classname = 'FactureLigne';
10831 $module = 'facture';
10832 $table_element = 'facturedet';
10833 $parent_element = 'facture';
10834 } elseif ($elementType == 'facturerec' || $elementType == 'facture_rec') {
10835 $classpath = 'compta/facture/class';
10836 $classfile = 'facture-rec';
10837 $module = 'facture';
10838 $classname = 'FactureRec';
10839 } elseif ($elementType == 'commande' || $elementType == 'order') {
10840 $classpath = 'commande/class';
10841 $module = 'commande';
10842 $subelement = 'commande';
10843 $table_element = 'commande';
10844 } elseif ($elementType == 'commandedet') {
10845 $classpath = 'commande/class';
10846 $classfile = 'commande';
10847 $classname = 'OrderLine';
10848 $module = 'commande';
10849 $table_element = 'commandedet';
10850 $parent_element = 'commande';
10851 } elseif ($elementType == 'propal') {
10852 $classpath = 'comm/propal/class';
10853 $table_element = 'propal';
10854 } elseif ($elementType == 'propaldet') {
10855 $classpath = 'comm/propal/class';
10856 $classfile = 'propal';
10857 $subelement = 'propaleligne';
10858 $module = 'propal';
10859 $table_element = 'propaldet';
10860 $parent_element = 'propal';
10861 } elseif ($elementType == 'shipping' || $elementType == 'shipment') {
10862 $classpath = 'expedition/class';
10863 $classfile = 'expedition';
10864 $classname = 'Expedition';
10865 $module = 'expedition';
10866 $table_element = 'expedition';
10867 } elseif ($elementType == 'expeditiondet' || $elementType == 'shippingdet') {
10868 $classpath = 'expedition/class';
10869 $classfile = 'expedition';
10870 $classname = 'ExpeditionLigne';
10871 $module = 'expedition';
10872 $table_element = 'expeditiondet';
10873 $parent_element = 'expedition';
10874 } elseif ($elementType == 'delivery_note') {
10875 $classpath = 'delivery/class';
10876 $subelement = 'delivery';
10877 $module = 'expedition';
10878 } elseif ($elementType == 'delivery') {
10879 $classpath = 'delivery/class';
10880 $subelement = 'delivery';
10881 $module = 'expedition';
10882 } elseif ($elementType == 'deliverydet') {
10883 // @todo
10884 } elseif ($elementType == 'supplier_proposal') {
10885 $classpath = 'supplier_proposal/class';
10886 $module = 'supplier_proposal';
10887 $element = 'supplierproposal';
10888 $classfile = 'supplier_proposal';
10889 $subelement = 'supplierproposal';
10890 } elseif ($elementType == 'supplier_proposaldet') {
10891 $classpath = 'supplier_proposal/class';
10892 $module = 'supplier_proposal';
10893 $classfile = 'supplier_proposal';
10894 $classname = 'SupplierProposalLine';
10895 $table_element = 'supplier_proposaldet';
10896 $parent_element = 'supplier_proposal';
10897 } elseif ($elementType == 'contract') {
10898 $classpath = 'contrat/class';
10899 $module = 'contrat';
10900 $subelement = 'contrat';
10901 $table_element = 'contract';
10902 } elseif ($elementType == 'contratdet') {
10903 $classpath = 'contrat/class';
10904 $module = 'contrat';
10905 $table_element = 'contratdet';
10906 $parent_element = 'contrat';
10907 } elseif ($elementType == 'mailing') {
10908 $classpath = 'comm/mailing/class';
10909 $module = 'mailing';
10910 $classfile = 'mailing';
10911 $classname = 'Mailing';
10912 $subelement = '';
10913 } elseif ($elementType == 'member' || $elementType == 'adherent') {
10914 $classpath = 'adherents/class';
10915 $module = 'adherent';
10916 $subelement = 'adherent';
10917 $table_element = 'adherent';
10918 } elseif ($elementType == 'subscription') {
10919 $classpath = 'adherents/class';
10920 $classfile = 'subscription';
10921 $module = 'adherent';
10922 $subelement = 'subscription';
10923 $classname = 'Subscription';
10924 $table_element = 'subscription';
10925 } elseif ($elementType == 'usergroup') {
10926 $classpath = 'user/class';
10927 $module = 'user';
10928 } elseif ($elementType == 'mrp') {
10929 $classpath = 'mrp/class';
10930 $classfile = 'mo';
10931 $classname = 'Mo';
10932 $module = 'mrp';
10933 $subelement = '';
10934 $table_element = 'mrp_mo';
10935 } elseif ($elementType == 'mrp_production') {
10936 $classpath = 'mrp/class';
10937 $classfile = 'mo';
10938 $classname = 'MoLine';
10939 $module = 'mrp';
10940 $subelement = '';
10941 $table_element = 'mrp_production';
10942 $parent_element = 'mo';
10943 } elseif ($elementType == 'cabinetmed_cons') {
10944 $classpath = 'cabinetmed/class';
10945 $module = 'cabinetmed';
10946 $subelement = 'cabinetmedcons';
10947 $table_element = 'cabinetmedcons';
10948 } elseif ($elementType == 'fichinter' || $elementType == 'ficheinter') {
10949 $classpath = 'fichinter/class';
10950 $module = 'ficheinter';
10951 $subelement = 'fichinter';
10952 $table_element = 'fichinter';
10953 } elseif ($elementType == 'dolresource' || $elementType == 'resource') {
10954 $classpath = 'resource/class';
10955 $module = 'resource';
10956 $subelement = 'dolresource';
10957 $table_element = 'resource';
10958 } elseif ($elementType == 'opensurvey_sondage') {
10959 $classpath = 'opensurvey/class';
10960 $module = 'opensurvey';
10961 $subelement = 'opensurveysondage';
10962 } elseif ($elementType == 'order_supplier' || $elementType == 'supplier_order' || $elementType == 'commande_fournisseur' || $elementType == 'commandefournisseur') {
10963 $classpath = 'fourn/class';
10964 $module = 'fournisseur';
10965 $classfile = 'fournisseur.commande';
10966 $element = 'order_supplier';
10967 $subelement = '';
10968 $classname = 'CommandeFournisseur';
10969 $table_element = 'commande_fournisseur';
10970 } elseif ($elementType == 'commande_fournisseurdet') {
10971 $classpath = 'fourn/class';
10972 $module = 'fournisseur';
10973 $classfile = 'fournisseur.commande';
10974 $element = 'commande_fournisseurdet';
10975 $subelement = '';
10976 $classname = 'CommandeFournisseurLigne';
10977 $table_element = 'commande_fournisseurdet';
10978 $parent_element = 'commande_fournisseur';
10979 } elseif ($elementType == 'invoice_supplier' || $elementType == 'supplier_invoice' || $elementType == 'facture_fourn') {
10980 $classpath = 'fourn/class';
10981 $module = 'fournisseur';
10982 $classfile = 'fournisseur.facture';
10983 $element = 'invoice_supplier';
10984 $subelement = '';
10985 $classname = 'FactureFournisseur';
10986 $table_element = 'facture_fourn';
10987 } elseif ($elementType == 'invoice_supplier_rec' || $elementType == 'supplier_invoice_rec' || $elementType == 'facture_fourn_rec') {
10988 $classpath = 'fourn/class';
10989 $module = 'fournisseur';
10990 $classfile = 'fournisseur.facture-rec';
10991 $element = 'invoice_supplier_rec';
10992 $subelement = '';
10993 $classname = 'FactureFournisseurRec';
10994 $table_element = 'facture_fourn_rec';
10995 } elseif ($elementType == 'facture_fourn_det') {
10996 $classpath = 'fourn/class';
10997 $module = 'fournisseur';
10998 $classfile = 'fournisseur.facture';
10999 $element = 'facture_fourn_det';
11000 $subelement = '';
11001 $classname = 'SupplierInvoiceLine';
11002 $table_element = 'facture_fourn_det';
11003 $parent_element = 'invoice_supplier';
11004 } elseif ($elementType == "service") {
11005 $classpath = 'product/class';
11006 $module = 'product';
11007 $subelement = 'product';
11008 $table_element = 'product';
11009 } elseif ($elementType == 'product_attribute') {
11010 $module = 'variants';
11011 $element = 'product_attribute';
11012 $subelement = 'product_attribute';
11013 $classpath = 'variants/class';
11014 $classfile = 'ProductAttribute';
11015 $classname = 'ProductAttribute';
11016 $table_element = 'product_attribute';
11017 } elseif ($elementType == 'product_attribute_value') {
11018 $module = 'variants';
11019 $element = 'product_attribute_value';
11020 $subelement = 'product_attribute_value';
11021 $classpath = 'variants/class';
11022 $classfile = 'ProductAttributeValue';
11023 $classname = 'ProductAttributeValue';
11024 $table_element = 'product_attribute_value';
11025 $parent_element = 'product_attribute';
11026 } elseif ($elementType == 'salary') {
11027 $classpath = 'salaries/class';
11028 $module = 'salaries';
11029 } elseif ($elementType == 'payment_salary') {
11030 $classpath = 'salaries/class';
11031 $classfile = 'paymentsalary';
11032 $classname = 'PaymentSalary';
11033 $module = 'salaries';
11034 } elseif ($elementType == 'payment') {
11035 $classpath = 'compta/paiement/class';
11036 $classfile = 'paiement';
11037 $classname = 'Paiement';
11038 $module = 'facture'; // A customer payment belongs to the invoice module, there is no 'compta' module
11039 $element = 'payment';
11040 $subelement = 'payment';
11041 $table_element = 'paiement';
11042 } elseif ($elementType == 'payment_supplier') {
11043 $classpath = 'fourn/class';
11044 $classfile = 'paiementfourn';
11045 $classname = 'PaiementFourn';
11046 $module = 'fournisseur';
11047 $element = 'payment_supplier';
11048 $subelement = 'payment_supplier';
11049 $table_element = 'paiementfourn';
11050 } elseif ($elementType == 'payment_various') {
11051 $classpath = 'compta/bank/class';
11052 $classfile = 'paymentvarious';
11053 $classname = 'PaymentVarious';
11054 $module = 'bank'; // We need $conf->bank->dir_output and not $conf->banque->dir_output
11055 $element = 'payment_various';
11056 $subelement = 'payment_various';
11057 $table_element = 'payment_various';
11058 } elseif ($elementType == 'stocktransfer') {
11059 $classpath = 'product/stock/stocktransfer/class';
11060 $classfile = 'stocktransfer';
11061 $classname = 'StockTransfer'; // Not the ucfirst() of the element, so it must be set explicitly
11062 $module = 'stocktransfer';
11063 $subelement = 'stocktransfer';
11064 $table_element = 'stocktransfer_stocktransfer';
11065 } elseif ($elementType == 'job' || $elementType == 'position' || $elementType == 'skill' || $elementType == 'evaluation') {
11066 $classpath = 'hrm/class';
11067 $classfile = $elementType;
11068 $classname = ucfirst($elementType);
11069 $module = 'hrm';
11070 $subelement = $elementType;
11071 $table_element = ($elementType == 'position' ? 'hrm_job_user' : 'hrm_'.$elementType);
11072 $subdir = '/'.$elementType;
11073 } elseif ($elementType == 'evaluationdet') {
11074 $classpath = 'hrm/class';
11075 $classfile = 'evaluationdet';
11076 $classname = 'EvaluationLine'; // Not the ucfirst() of the element, so it must be set explicitly
11077 $module = 'hrm';
11078 $subelement = 'evaluationdet';
11079 $table_element = 'hrm_evaluationdet';
11080 } elseif ($elementType == 'productlot') {
11081 $module = 'productbatch';
11082 $classpath = 'product/stock/class';
11083 $classfile = 'productlot';
11084 $classname = 'Productlot';
11085 $element = 'productlot';
11086 $subelement = '';
11087 $table_element = 'product_lot';
11088 } elseif ($elementType == 'societeaccount') {
11089 $classpath = 'societe/class';
11090 $classfile = 'societeaccount';
11091 $classname = 'SocieteAccount';
11092 $module = 'societe';
11093 } elseif ($elementType == 'websitepage' || $elementType == 'website_page') {
11094 $classpath = 'website/class';
11095 $classfile = 'websitepage';
11096 $classname = 'Websitepage';
11097 $module = 'website';
11098 $subelement = 'websitepage';
11099 $table_element = 'website_page';
11100 } elseif ($elementType == 'fiscalyear') {
11101 $classpath = 'core/class';
11102 $module = 'accounting';
11103 $subelement = 'fiscalyear';
11104 } elseif ($elementType == 'chargesociales') {
11105 $classpath = 'compta/sociales/class';
11106 $module = 'tax';
11107 $table_element = 'chargesociales';
11108 } elseif ($elementType == 'tva') {
11109 $classpath = 'compta/tva/class';
11110 $module = 'tax';
11111 $subdir = '/vat';
11112 $table_element = 'tva';
11113 } elseif ($elementType == 'cashcontrol') {
11114 $classpath = 'compta/cashcontrol/class';
11115 $classfile = 'cashcontrol';
11116 $classname = 'CashControl';
11117 $module = 'takepos';
11118 $table_element = 'pos_cash_fence';
11119 } elseif ($elementType == 'emailsenderprofile') {
11120 $module = '';
11121 $classpath = 'core/class';
11122 $classfile = 'emailsenderprofile';
11123 $classname = 'EmailSenderProfile';
11124 $table_element = 'c_email_senderprofile';
11125 $subelement = '';
11126 } elseif ($elementType == 'conferenceorboothattendee') {
11127 $classpath = 'eventorganization/class';
11128 $classfile = 'conferenceorboothattendee';
11129 $classname = 'ConferenceOrBoothAttendee';
11130 $module = 'eventorganization';
11131 } elseif ($elementType == 'conferenceorbooth') {
11132 $classpath = 'eventorganization/class';
11133 $classfile = 'conferenceorbooth';
11134 $classname = 'ConferenceOrBooth';
11135 $module = 'eventorganization';
11136 $subdir = '/conferenceorbooth';
11137 } elseif ($elementType == 'ccountry') {
11138 $module = '';
11139 $classpath = 'core/class';
11140 $classfile = 'ccountry';
11141 $classname = 'Ccountry';
11142 $table_element = 'c_country';
11143 $subelement = '';
11144 } elseif ($elementType == 'ecmfiles') {
11145 $module = 'ecm';
11146 $classpath = 'ecm/class';
11147 $classfile = 'ecmfiles';
11148 $classname = 'Ecmfiles';
11149 $table_element = 'ecmfiles';
11150 $subelement = '';
11151 } elseif ($elementType == 'knowledgerecord' || $elementType == 'knowledgemanagement') {
11152 $module = 'knowledgemanagement';
11153 $classpath = 'knowledgemanagement/class';
11154 $classfile = 'knowledgerecord';
11155 $classname = 'KnowledgeRecord';
11156 $table_element = 'knowledgemanagement_knowledgerecord';
11157 $subelement = '';
11158 } elseif ($elementType == 'customer') {
11159 $module = 'societe';
11160 $classpath = 'societe/class';
11161 $classfile = 'client';
11162 $classname = 'Client';
11163 $table_element = 'societe';
11164 $subelement = '';
11165 } elseif ($elementType == 'fournisseur' || $elementType == 'supplier') {
11166 $module = 'societe';
11167 $classpath = 'fourn/class';
11168 $classfile = 'fournisseur';
11169 $classname = 'Fournisseur';
11170 $table_element = 'societe';
11171 $subelement = '';
11172 } elseif ($elementType == 'recruitmentcandidature') {
11173 $module = 'recruitment';
11174 $classfile = 'recruitmentcandidature';
11175 $classpath = 'recruitment/class';
11176 $classname = 'RecruitmentCandidature';
11177 $subelement = 'recruitmentcandidature';
11178 $subdir = '/recruitmentcandidature';
11179 } elseif ($elementType == 'recruitmentjobposition') {
11180 $module = 'recruitment';
11181 $classfile = 'recruitmentjobposition';
11182 $classpath = 'recruitment/class';
11183 $classname = 'RecruitmentJobPosition';
11184 $subelement = 'recruitmentjobposition';
11185 $subdir = '/recruitmentjobposition';
11186 } elseif ($elementType == 'recruitment') {
11187 // The recruitment module has no class of its own, and the document links of its objects use
11188 // the module name as modulepart (see document.php), so the module name resolves to the job
11189 // position, the main object of the module.
11190 $module = 'recruitment';
11191 $classfile = 'recruitmentjobposition';
11192 $classpath = 'recruitment/class';
11193 $classname = 'RecruitmentJobPosition';
11194 $element = $subelement = 'recruitmentjobposition';
11195 $table_element = 'recruitment_recruitmentjobposition';
11196 $subdir = '/recruitmentjobposition';
11197 } elseif ($elementType == 'product_attribute_combination') {
11198 $module = 'variants';
11199 $classpath = 'variants/class';
11200 $classfile = 'ProductCombination';
11201 $classname = 'ProductCombination';
11202 $element = 'productcombination';
11203 $subelement = '';
11204 $table_element = 'product_attribute_combination';
11205 } elseif ($elementType == 'product_attribute_combination2val') {
11206 $module = 'variants';
11207 $classpath = 'variants/class';
11208 $classfile = 'ProductCombination2ValuePair';
11209 $classname = 'ProductCombination2ValuePair';
11210 $element = 'productcombination2valuepair';
11211 $subelement = '';
11212 $table_element = 'product_attribute_combination2val';
11213 } elseif ($elementType == 'product_attribute_combination_price_level') {
11214 // Class ProductCombinationLevel is declared inside ProductCombination.class.php
11215 $module = 'variants';
11216 $classpath = 'variants/class';
11217 $classfile = 'ProductCombination';
11218 $classname = 'ProductCombinationLevel';
11219 $element = 'productcombinationlevel';
11220 $subelement = '';
11221 $table_element = 'product_attribute_combination_price_level';
11222 }
11223
11224
11225 if (empty($classfile)) {
11226 $classfile = strtolower($subelement);
11227 }
11228 if (empty($classname)) {
11229 $classname = ucfirst($subelement);
11230 }
11231 if (empty($classpath)) {
11232 $classpath = $module . '/class';
11233 }
11234
11235 //print 'getElementProperties subdir='.$subdir;
11236
11237 // Set dir_output
11238 if ($module && isset($conf->$module)) { // The generic case
11239 if (!empty($conf->$module->multidir_output[$conf->entity])) {
11240 $dir_output = $conf->$module->multidir_output[$conf->entity];
11241 } elseif (!empty($conf->$module->output[$conf->entity])) {
11242 $dir_output = $conf->$module->output[$conf->entity];
11243 } elseif (!empty($conf->$module->dir_output)) {
11244 $dir_output = $conf->$module->dir_output;
11245 }
11246 if (!empty($conf->$module->multidir_temp[$conf->entity])) {
11247 $dir_temp = $conf->$module->multidir_temp[$conf->entity];
11248 } elseif (!empty($conf->$module->temp[$conf->entity])) {
11249 $dir_temp = $conf->$module->temp[$conf->entity];
11250 } elseif (!empty($conf->$module->dir_temp)) {
11251 $dir_temp = $conf->$module->dir_temp;
11252 }
11253 }
11254
11255 // Overwrite value for special cases
11256 if ($element == 'order_supplier' && isModEnabled('fournisseur')) {
11257 $dir_output = $conf->fournisseur->commande->dir_output;
11258 $dir_temp = $conf->fournisseur->commande->dir_temp;
11259 } elseif ($element == 'invoice_supplier' && isModEnabled('fournisseur')) {
11260 $dir_output = $conf->fournisseur->facture->dir_output;
11261 $dir_temp = $conf->fournisseur->facture->dir_temp;
11262 } elseif ($elementType == 'payment' && isModEnabled('invoice') && isset($conf->compta->payment)) {
11263 // A customer payment is stored into a sub object of $conf, not handled by the generic case.
11264 // Note: we must test $elementType and not $element, because the 'myobject_mysubobject' rule above
11265 // rewrites $element to 'payment' for the element 'payment_salary' too, which is stored elsewhere.
11266 $dir_output = $conf->compta->payment->dir_output;
11267 $dir_temp = $conf->compta->payment->dir_temp;
11268 } elseif ($elementType == 'payment_supplier' && isModEnabled('fournisseur') && isset($conf->fournisseur->payment)) {
11269 $dir_output = $conf->fournisseur->payment->dir_output;
11270 $dir_temp = $conf->fournisseur->payment->dir_temp;
11271 }
11272
11273 // The sub directory must not be appended when the module is disabled, because $dir_output is then empty
11274 // and we would return a path at the root of the file system instead of an empty string.
11275 if (!empty($dir_output)) {
11276 $dir_output .= $subdir;
11277 }
11278 if (!empty($dir_temp)) {
11279 //$dir_temp = preg_replace('/\/temp$/', '', $dir_temp).$subdir.'/temp'; // To get mymoduledir/myobject/temp
11280 $dir_temp .= $subdir; // To get mymoduledir/temp/myobject
11281 }
11282
11283 $elementProperties = array(
11284 'module' => $module,
11285 'element' => $element,
11286 'table_element' => $table_element,
11287 'subelement' => $subelement,
11288 'classpath' => $classpath,
11289 'classfile' => $classfile,
11290 'classname' => $classname,
11291 'dir_output' => $dir_output,
11292 'dir_temp' => $dir_temp,
11293 'parent_element' => $parent_element,
11294 );
11295
11296
11297 // Add hook
11298 if (!is_object($hookmanager)) {
11299 include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
11300 $hookmanager = new HookManager($db);
11301 }
11302 $hookmanager->initHooks(array('elementproperties'));
11303
11304
11305 // Hook params
11306 $parameters = array(
11307 'elementType' => $elementType,
11308 'elementProperties' => $elementProperties
11309 );
11310
11311 $reshook = $hookmanager->executeHooks('getElementProperties', $parameters);
11312
11313 if ($reshook) {
11314 $elementProperties = $hookmanager->resArray;
11315 } elseif (!empty($hookmanager->resArray) && is_array($hookmanager->resArray)) { // resArray is always an array but for security against misconfigured external modules
11316 $elementProperties = array_replace($elementProperties, $hookmanager->resArray);
11317 }
11318
11319 // context of elementproperties doesn't need to exist out of this function so delete it to avoid elementproperties context is equal to all
11320 if (($key = array_search('elementproperties', $hookmanager->contextarray)) !== false) {
11321 unset($hookmanager->contextarray[$key]);
11322 }
11323
11324 return $elementProperties;
11325}
11326
11340function fetchObjectByElement($element_id, $element_type, $element_ref = '', $useCache = 0, $maxCacheByType = 10)
11341{
11342 global $db, $conf;
11343
11344 $ret = 0;
11345
11346 $element_prop = getElementProperties($element_type);
11347 //var_dump($element_type, $element_prop);
11348
11349 // Check special cases
11350 if ($element_prop['module'] == 'product' || $element_prop['module'] == 'service') {
11351 // For example, for an extrafield 'product' (shared for both product and service) that is a link to an object,
11352 // this is called with $element_type = 'product' when we need element properties of a service, we must return a product. If we create the
11353 // extrafield for a service, it is not supported and not found when editing the product/service card. So we must keep 'product' for extrafields
11354 // of service and we will return properties of a product.
11355 $ismodenabled = (isModEnabled('product') || isModEnabled('service'));
11356 } elseif ($element_prop['module'] == 'societeaccount') {
11357 $ismodenabled = isModEnabled('website') || isModEnabled('webportal');
11358 } else {
11359 $ismodenabled = isModEnabled($element_prop['module']);
11360 }
11361
11362 //var_dump('element_type='.$element_type);
11363 //var_dump($element_prop);
11364 //var_dump($element_prop['module'].' '.$ismodenabled);
11365 if (is_array($element_prop) && (empty($element_prop['module']) || $ismodenabled)) {
11366 if ($useCache === 1 && $element_id > 0
11367 && !empty($conf->cache['fetchObjectByElement'][$element_type])
11368 && !empty($conf->cache['fetchObjectByElement'][$element_type][$element_id])
11369 && is_object($conf->cache['fetchObjectByElement'][$element_type][$element_id])
11370 ) {
11371 return $conf->cache['fetchObjectByElement'][$element_type][$element_id];
11372 }
11373
11374 $includeresult = dol_include_once('/' . $element_prop['classpath'] . '/' . $element_prop['classfile'] . '.class.php');
11375 if ($includeresult === false) {
11376 dol_syslog('fetchObjectByElement: class file /' . $element_prop['classpath'] . '/' . $element_prop['classfile'] . '.class.php not found for element ' . $element_type, LOG_WARNING);
11377 }
11378 //var_dump('/' . $element_prop['classpath'] . '/' . $element_prop['classfile'] . '.class.php', $element_prop['classname']);
11379
11380 if (class_exists($element_prop['classname'])) {
11381 $className = $element_prop['classname'];
11382 // Never instantiate a PHP internal class: the name can only be a collision with a
11383 // class of the language (for example an element resolved to the native 'Attribute').
11384 try {
11385 $isinternalclass = (new ReflectionClass($className))->isInternal();
11386 } catch (ReflectionException $e) {
11387 $isinternalclass = false;
11388 }
11389 if ($isinternalclass) {
11390 dol_syslog('fetchObjectByElement: refuse to instantiate PHP internal class ' . $className . ' for element ' . $element_type, LOG_ERR);
11391 return -1;
11392 }
11393 $objecttmp = new $className($db);
11394 '@phan-var-force CommonObject $objecttmp';
11397 if ($element_id > 0 || !empty($element_ref)) {
11398 // Special case for job, there is no ref, it is the id
11399 // TODO Replace hard coded code with a test if object has a ref or not.
11400 if (empty($element_id) && !empty($element_ref) && (in_array($objecttmp->element, array('evaluation', 'job', 'position', 'skill')))) {
11401 $element_id = $element_ref;
11402 $element_ref = '';
11403 }
11404
11405 $ret = $objecttmp->fetch($element_id, $element_ref);
11406 if ($ret > 0) {
11407 if (empty($objecttmp->module)) {
11408 $objecttmp->module = $element_prop['module'];
11409 }
11410
11411 if ($useCache > 0) {
11412 if (!isset($conf->cache['fetchObjectByElement'][$element_type])) {
11413 $conf->cache['fetchObjectByElement'][$element_type] = [];
11414 }
11415
11416 // Manage cache limit
11417 if (! empty($conf->cache['fetchObjectByElement'][$element_type]) && is_array($conf->cache['fetchObjectByElement'][$element_type]) && count($conf->cache['fetchObjectByElement'][$element_type]) >= $maxCacheByType) {
11418 array_shift($conf->cache['fetchObjectByElement'][$element_type]);
11419 }
11420
11421 $conf->cache['fetchObjectByElement'][$element_type][$element_id] = $objecttmp;
11422 }
11423
11424 return $objecttmp;
11425 }
11426 } else {
11427 return $objecttmp; // returned an object without fetch
11428 }
11429 } else {
11430 dol_syslog($element_prop['classname'] . " doesn't exists in /" . $element_prop['classpath'] . "/" . $element_prop['classfile'] . ".class.php");
11431 return -1;
11432 }
11433 }
11434
11435 return $ret;
11436}
11437
11443function getExecutableContent()
11444{
11445 $arrayofregexextension = array(
11446 'htm',
11447 'html',
11448 'shtml',
11449 'js',
11450 'phar',
11451 'php',
11452 'php3',
11453 'php4',
11454 'php5',
11455 'phtml',
11456 'pht',
11457 'pl',
11458 'py',
11459 'cgi',
11460 'ksh',
11461 'sh',
11462 'shtml',
11463 'bash',
11464 'bat',
11465 'cmd',
11466 'wpk',
11467 'exe',
11468 'dmg',
11469 'appimage'
11470 );
11471
11472 return $arrayofregexextension;
11473}
11474
11481function isAFileWithExecutableContent($filename)
11482{
11483 $arrayofregexextension = getExecutableContent();
11484
11485 foreach ($arrayofregexextension as $fileextension) {
11486 if (preg_match('/\.' . preg_quote($fileextension, '/') . '$/i', $filename)) {
11487 return true;
11488 }
11489 }
11490
11491 return false;
11492}
11493
11501function newToken()
11502{
11503 return empty($_SESSION['newtoken']) ? '' : $_SESSION['newtoken'];
11504}
11505
11513function currentToken()
11514{
11515 return isset($_SESSION['token']) ? $_SESSION['token'] : '';
11516}
11517
11523function getNonce()
11524{
11525 global $conf;
11526
11527 if (empty($conf->cache['nonce'])) {
11528 include_once DOL_DOCUMENT_ROOT . '/core/lib/security.lib.php';
11529 $conf->cache['nonce'] = dolGetRandomBytes(8);
11530 }
11531
11532 return $conf->cache['nonce'];
11533}
11534
11535
11544function readfileLowMemory($fullpath_original_file_osencoded, $method = -1)
11545{
11546 if ($method == -1) {
11547 $method = 0;
11548 if (getDolGlobalString('MAIN_FORCE_READFILE_WITH_FREAD')) {
11549 $method = 1;
11550 }
11551 if (getDolGlobalString('MAIN_FORCE_READFILE_WITH_STREAM_COPY')) {
11552 $method = 2;
11553 }
11554 }
11555
11556 // Be sure we don't have output buffering enabled to have readfile working correctly
11557 $level = ob_get_level();
11558 ob_start();
11559 while (ob_get_level() > $level) {
11560 ob_end_clean();
11561 }
11562
11563 // Solution 0
11564 if ($method == 0) {
11565 readfile($fullpath_original_file_osencoded);
11566 } elseif ($method == 1) {
11567 // Solution 1
11568 $handle = fopen($fullpath_original_file_osencoded, "rb");
11569 while (!feof($handle)) {
11570 print fread($handle, 8192);
11571 }
11572 fclose($handle);
11573 } elseif ($method == 2) {
11574 // Solution 2
11575 $handle1 = fopen($fullpath_original_file_osencoded, "rb");
11576 $handle2 = fopen("php://output", "wb");
11577 stream_copy_to_stream($handle1, $handle2);
11578 fclose($handle1);
11579 fclose($handle2);
11580 }
11581}
11582
11583
11591function jsonOrUnserialize($stringtodecode, $assoc = true)
11592{
11593 $result = json_decode($stringtodecode, $assoc);
11594 if ($result === null) {
11595 $result = unserialize($stringtodecode, ['allowed_classes' => false]); // For backward compatibility. Is no more used in recent versions.
11596 }
11597
11598 return $result;
11599}
11600
11601
11619function forgeSQLFromUniversalSearchCriteria($filter, &$errorstr = '', $noand = 0, $nopar = 0, $noerror = 0, $forbiddenfields = array())
11620{
11621 global $db, $user;
11622
11623 if (is_null($filter) || !is_string($filter) || $filter === '') {
11624 return '';
11625 }
11626 if (!preg_match('/^\‍(.*\‍)$/', $filter)) { // If $filter does not start and end with ()
11627 $filter = '(' . $filter . ')';
11628 }
11629
11630 $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'
11631 $firstandlastparenthesis = 0;
11632
11633 if (!dolCheckFilters($filter, $errorstr, $firstandlastparenthesis)) {
11634 if ($noerror) {
11635 return '1 = 2';
11636 } else {
11637 return 'Filter syntax error - ' . $errorstr; // Bad balance of parenthesis, we return an error message or force a SQL not found
11638 }
11639 }
11640
11641 // Test the filter syntax
11642 $t = preg_replace_callback('/' . $regexstring . '/i', 'dolForgeDummyCriteriaCallback', $filter);
11643 $t = str_ireplace(array('and', 'or', ' '), '', $t); // Remove the only strings allowed between each () criteria
11644
11645 // If the string result contains something else than '()', the syntax was wrong
11646 if (preg_match('/[^\‍(\‍)]/', $t)) {
11647 $tmperrorstr = 'Bad syntax of the search string';
11648 $errorstr = 'Bad syntax of the search string: ' . $filter;
11649 if ($noerror) {
11650 return '1 = 2';
11651 } else {
11652 dol_syslog("forgeSQLFromUniversalSearchCriteria Filter error - " . $errorstr, LOG_WARNING);
11653 return 'Filter error - ' . $tmperrorstr; // Bad syntax of the search string, we return an error message or force a SQL not found
11654 }
11655 }
11656
11657 global $globalforbiddenfields; // For use by dolForgeSQLCriteriaCallback()
11658 $globalforbiddenfields = $forbiddenfields;
11659
11660 $ret = ($noand ? "" : " AND ") . ($nopar ? "" : '(');
11661 $ret .= preg_replace_callback('/' . $regexstring . '/i', 'dolForgeSQLCriteriaCallback', $filter);
11662 $ret .= ($nopar ? "" : ')');
11663
11664 if (is_object($db)) {
11665 $ret = str_replace('__NOW__', "'" . $db->idate(dol_now()) . "'", $ret);
11666 }
11667 if (is_object($user)) {
11668 $ret = str_replace('__USER_ID__', (string) $user->id, $ret);
11669 }
11670
11671 return $ret;
11672}
11673
11681function dolForgeExplodeAnd($sqlfilters)
11682{
11683 $arrayofandtags = array();
11684 $nbofchars = dol_strlen($sqlfilters);
11685
11686 $error = '';
11687 $parenthesislevel = 0;
11688 $result = dolCheckFilters($sqlfilters, $error, $parenthesislevel);
11689 if (!$result) {
11690 return array();
11691 }
11692 if ($parenthesislevel >= 1) {
11693 $sqlfilters = preg_replace('/^\‍(/', '', preg_replace('/\‍)$/', '', $sqlfilters));
11694 }
11695
11696 $i = 0;
11697 $s = '';
11698 $countparenthesis = 0;
11699 while ($i < $nbofchars) {
11700 $char = dol_substr($sqlfilters, $i, 1);
11701
11702 if ($char == '(') {
11703 $countparenthesis++;
11704 } elseif ($char == ')') {
11705 $countparenthesis--;
11706 }
11707
11708 if ($countparenthesis == 0) {
11709 $char2 = dol_substr($sqlfilters, $i + 1, 1);
11710 $char3 = dol_substr($sqlfilters, $i + 2, 1);
11711 if ($char == 'A' && $char2 == 'N' && $char3 == 'D') {
11712 // We found a AND
11713 $s = trim($s);
11714 if (!preg_match('/^\‍(.*\‍)$/', $s)) {
11715 $s = '(' . $s . ')';
11716 }
11717 $arrayofandtags[] = $s;
11718 $s = '';
11719 $i += 2;
11720 } else {
11721 $s .= $char;
11722 }
11723 } else {
11724 $s .= $char;
11725 }
11726 $i++;
11727 }
11728 if ($s) {
11729 $s = trim($s);
11730 if (!preg_match('/^\‍(.*\‍)$/', $s)) {
11731 $s = '(' . $s . ')';
11732 }
11733 $arrayofandtags[] = $s;
11734 }
11735
11736 return $arrayofandtags;
11737}
11738
11748function dolCheckFilters($sqlfilters, &$error = '', &$parenthesislevel = 0)
11749{
11750 //$regexstring='\‍(([^:\'\‍(\‍)]+:[^:\'\‍(\‍)]+:[^:\‍(\‍)]+)\‍)';
11751 //$tmp=preg_replace_all('/'.$regexstring.'/', '', $sqlfilters);
11752 $tmp = $sqlfilters;
11753
11754 $nb = dol_strlen($tmp);
11755 $counter = 0;
11756 $parenthesislevel = 0;
11757
11758 $error = '';
11759
11760 $i = 0;
11761 while ($i < $nb) {
11762 $char = dol_substr($tmp, $i, 1);
11763
11764 if ($char == '(') {
11765 if ($i == $parenthesislevel && $parenthesislevel == $counter) {
11766 // We open a parenthesis and it is the first char
11767 $parenthesislevel++;
11768 }
11769 $counter++;
11770 } elseif ($char == ')') {
11771 $nbcharremaining = ($nb - $i - 1);
11772 if ($nbcharremaining >= $counter) {
11773 $parenthesislevel = min($parenthesislevel, $counter - 1);
11774 }
11775 if ($parenthesislevel > $counter && $nbcharremaining >= $counter) {
11776 $parenthesislevel = $counter;
11777 }
11778 $counter--;
11779 }
11780
11781 if ($counter < 0) {
11782 $error = "Wrong balance of parenthesis in sqlfilters=" . $sqlfilters;
11783 $parenthesislevel = 0;
11784 dol_syslog($error, LOG_WARNING);
11785 return false;
11786 }
11787
11788 $i++;
11789 }
11790
11791 if ($counter > 0) {
11792 $error = "Wrong balance of parenthesis in sqlfilters=" . $sqlfilters;
11793 $parenthesislevel = 0;
11794 dol_syslog($error, LOG_WARNING);
11795 return false;
11796 }
11797
11798 return true;
11799}
11800
11808function dolForgeDummyCriteriaCallback($matches)
11809{
11810 //dol_syslog("Convert matches ".$matches[1]);
11811 if (empty($matches[1])) {
11812 return '';
11813 }
11814 $tmp = explode(':', $matches[1]);
11815 if (count($tmp) < 3) {
11816 return '';
11817 }
11818
11819 return '()'; // An empty criteria
11820}
11821
11831function dolForgeSQLCriteriaCallback($matches)
11832{
11833 global $db;
11834 global $globalforbiddenfields;
11835
11836 //dol_syslog("Convert matches ".$matches[1]);
11837 if (empty($matches[1])) {
11838 return '';
11839 }
11840 $tmp = explode(':', $matches[1], 3);
11841 if (count($tmp) < 3) {
11842 return '';
11843 }
11844
11845 // Add fields that are forbidden by the caller when using USF search criteria
11846 // so we can't guess them using sequantial comparisons
11847 $newforbiddenfields = $globalforbiddenfields;
11848 if (!is_array($newforbiddenfields)) {
11849 $newforbiddenfields = array();
11850 }
11851 // Add fields that are ALWAYS forbidden when using USF search criteria
11852 $newforbiddenfields[] = 'pass';
11853 $newforbiddenfields[] = 'pass_crypted';
11854 $newforbiddenfields[] = 'pass_temp';
11855 $newforbiddenfields[] = 'api_key';
11856
11857 $operand = preg_replace('/[^a-z0-9\._]/i', '', trim($tmp[0]));
11858
11859 // An operand with more than one level of prefix (example: dbprefix.table.field) is not valid into a USF criteria,
11860 // we neutralize it like a forbidden field to avoid any leak or SQL error based on db prefix existence
11861 if (substr_count($operand, '.') > 1) {
11862 return '1=1';
11863 }
11864
11865 // Test that operand is not a forbidden search field
11866 if (!empty($newforbiddenfields)) {
11867 $operandwithoutprefix = preg_replace('/^[a-z0-9_]+\./i', '', $operand); // Remove prefix like t. or o. or s. or u. or d. or ...
11868 if (in_array(strtolower($operandwithoutprefix), $newforbiddenfields)) {
11869 return '1=1';
11870 }
11871 }
11872
11873 $operator = strtoupper(preg_replace('/[^a-z<>!=]/i', '', trim($tmp[1])));
11874
11875 $realOperator = [
11876 'NOTLIKE' => 'NOT LIKE',
11877 'ISNOT' => 'IS NOT',
11878 'NOTIN' => 'NOT IN',
11879 '!=' => '<>',
11880 ];
11881
11882 if (array_key_exists($operator, $realOperator)) {
11883 $operator = $realOperator[$operator];
11884 }
11885
11886 $tmpescaped = $tmp[2];
11887
11888 //print "Case: ".$operator." ".$operand." ".$tmpescaped."\n";
11889
11890 $regbis = array();
11891
11892 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)
11893 global $dolibarr_allow_unsecured_select_in_extrafields_filter;
11894
11895 //if (!preg_match('/^\‍(.*\‍)$/', $tmpescaped)) {
11896 $tmpescaped2 = '(';
11897 // Explode and sanitize each element in list
11898 $tmpelemarray = explode(',', $tmpescaped);
11899 foreach ($tmpelemarray as $tmpkey => $tmpelem) {
11900 $reg = array();
11901 $tmpelem = trim($tmpelem);
11902 if (preg_match('/^\'(.*)\'$/', $tmpelem, $reg)) {
11903 $tmpelemarray[$tmpkey] = "'".$db->escape($db->sanitize($reg[1], 2, 1, 1, 1))."'";
11904 } elseif (preg_match('/^[0-9]+$/', (string) $tmpelem)) { // if only 0-9 chars, no .
11905 $tmpelemarray[$tmpkey] = (int) $tmpelem;
11906 } elseif (is_numeric((string) $tmpelem)) { // it can be a float with a .
11907 $tmpelemarray[$tmpkey] = (float) $tmpelem;
11908 } elseif (!empty($dolibarr_allow_unsecured_select_in_extrafields_filter)) {
11909 $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)
11910 } else {
11911 $tmpelemarray[$tmpkey] = preg_replace('/[^a-z0-9_]/i', '', $tmpelem); // it can be a name of field or a substitution variable like '__NOW__'
11912 }
11913 }
11914 $tmpescaped2 .= implode(',', $tmpelemarray);
11915 $tmpescaped2 .= ')';
11916
11917 $tmpescaped = $tmpescaped2;
11918 } elseif ($operator == 'LIKE' || $operator == 'NOT LIKE') {
11919 if (preg_match('/^\'([^\']*)\'$/', $tmpescaped, $regbis)) {
11920 $tmpescaped = $regbis[1];
11921 }
11922 //$tmpescaped = "'".$db->escape($db->escapeforlike($regbis[1]))."'";
11923 $tmpescaped = "'" . $db->escape($tmpescaped) . "'"; // We do not escape the _ and % so the LIKE will work as expected
11924 } elseif (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) {
11925 // TODO Retrieve type of field for $operand field name.
11926 // So we can complete format. For example we could complete a year with month and day.
11927 $tmpescaped = "'" . $db->escape($regbis[1]) . "'";
11928 } else {
11929 if (strtoupper($tmpescaped) == 'NULL') {
11930 $tmpescaped = 'NULL';
11931 } elseif (preg_match('/^[0-9]+$/', (string) $tmpescaped)) { // if only 0-9 chars, no .
11932 $tmpescaped = (int) $tmpescaped;
11933 } elseif (is_numeric((string) $tmpescaped)) { // it can be a float with a .
11934 $tmpescaped = (float) $tmpescaped;
11935 } else {
11936 $tmpescaped = preg_replace('/[^a-z0-9_]/i', '', $tmpescaped); // it can be a name of field or a substitution variable like '__NOW__'
11937 }
11938 }
11939
11940 return '(' . $db->escape($operand) . ' ' . strtoupper($operator) . ' ' . $tmpescaped . ')';
11941}
11942
11943
11953function getTimelineIcon($actionstatic, &$histo, $key)
11954{
11955 dol_syslog('getTimelineIcon::begin', LOG_DEBUG);
11956 global $langs;
11957
11958 $out = '<!-- timeline icon -->' . "\n";
11959 $iconClass = 'fa fa-comments';
11960 $img_picto = '';
11961 $colorClass = '';
11962 $pictoTitle = '';
11963
11964 if ($histo[$key]['percent'] == -1) {
11965 $colorClass = 'timeline-icon-not-applicble';
11966 $pictoTitle = $langs->trans('StatusNotApplicable');
11967 } elseif ($histo[$key]['percent'] == 0) {
11968 $colorClass = 'timeline-icon-todo';
11969 $pictoTitle = $langs->trans('StatusActionToDo') . ' (0%)';
11970 } elseif ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100) {
11971 $colorClass = 'timeline-icon-in-progress';
11972 $pictoTitle = $langs->trans('StatusActionInProcess') . ' (' . $histo[$key]['percent'] . '%)';
11973 } elseif ($histo[$key]['percent'] >= 100) {
11974 $colorClass = 'timeline-icon-done';
11975 $pictoTitle = $langs->trans('StatusActionDone') . ' (100%)';
11976 }
11977
11978 if ($actionstatic->code == 'AC_TICKET_CREATE') {
11979 $iconClass = 'fa fa-ticket';
11980 } elseif ($actionstatic->code == 'AC_TICKET_MODIFY') {
11981 $iconClass = 'fa fa-pencilxxx';
11982 } elseif (preg_match('/^TICKET_MSG/', $actionstatic->code)) {
11983 $iconClass = 'fa fa-comments';
11984 } elseif (preg_match('/^TICKET_MSG_PRIVATE/', $actionstatic->code)) {
11985 $iconClass = 'fa fa-mask';
11986 } elseif (getDolGlobalString('AGENDA_USE_EVENT_TYPE')) {
11987 if ($actionstatic->type_picto) {
11988 $img_picto = img_picto('', $actionstatic->type_picto);
11989 } else {
11990 if ($actionstatic->type_code == 'AC_RDV') {
11991 $iconClass = 'fa fa-handshake';
11992 } elseif ($actionstatic->type_code == 'AC_TEL') {
11993 $iconClass = 'fa fa-phone';
11994 } elseif ($actionstatic->type_code == 'AC_FAX') {
11995 $iconClass = 'fa fa-fax';
11996 } elseif ($actionstatic->type_code == 'AC_EMAIL') {
11997 $iconClass = 'fa fa-envelope';
11998 } elseif ($actionstatic->type_code == 'AC_INT') {
11999 $iconClass = 'fa fa-shipping-fast';
12000 } elseif ($actionstatic->type_code == 'AC_OTH_AUTO') {
12001 $iconClass = 'fa fa-robot';
12002 } elseif (!preg_match('/_AUTO/', $actionstatic->type_code)) {
12003 $iconClass = 'fa fa-robot';
12004 }
12005 }
12006 }
12007
12008 $out .= '<i class="' . $iconClass . ' ' . $colorClass . '" title="' . $pictoTitle . '">' . $img_picto . '</i>' . "\n";
12009 return $out;
12010}
12011
12019{
12020 global $db;
12021
12022 $documents = array();
12023
12024 $sql = 'SELECT ecm.rowid as id, ecm.src_object_type, ecm.src_object_id, ecm.filepath, ecm.filename, ecm.agenda_id';
12025 $sql .= ' FROM ' . MAIN_DB_PREFIX . 'ecm_files ecm';
12026 $sql .= " WHERE ecm.filepath = 'agenda/" . ((int) $object->id) . "'";
12027 //$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
12028 $sql .= ' OR ecm.agenda_id = ' . (int) $object->id;
12029 $sql .= ' ORDER BY ecm.position ASC';
12030
12031 $resql = $db->query($sql);
12032 if ($resql) {
12033 if ($db->num_rows($resql)) {
12034 while ($obj = $db->fetch_object($resql)) {
12035 $documents[$obj->id] = $obj;
12036 }
12037 }
12038 }
12039
12040 return $documents;
12041}
12042
12043
12055function buildParamDate($prefix, $timestamp = null, $hourTime = '', $gm = 'auto')
12056{
12057 if ($timestamp === null) {
12058 $timestamp = GETPOSTDATE($prefix, $hourTime, $gm);
12059 }
12060 $TParam = array(
12061 $prefix . 'day' => intval(dol_print_date($timestamp, '%d')),
12062 $prefix . 'month' => intval(dol_print_date($timestamp, '%m')),
12063 $prefix . 'year' => intval(dol_print_date($timestamp, '%Y')),
12064 );
12065 if ($hourTime === 'getpost' || ($timestamp !== null && dol_print_date($timestamp, '%H:%M:%S') !== '00:00:00')) {
12066 $TParam = array_merge($TParam, array(
12067 $prefix . 'hour' => intval(dol_print_date($timestamp, '%H')),
12068 $prefix . 'min' => intval(dol_print_date($timestamp, '%M')),
12069 $prefix . 'sec' => intval(dol_print_date($timestamp, '%S'))
12070 ));
12071 }
12072
12073 return '&' . http_build_query($TParam);
12074}
12075
12094function recordNotFound($message = '', $printheader = 1, $printfooter = 1, $showonlymessage = 0, $params = null)
12095{
12096 global $conf, $db, $langs, $hookmanager;
12097 global $action, $object;
12098
12099 if (!is_object($langs)) {
12100 include_once DOL_DOCUMENT_ROOT . '/core/class/translate.class.php';
12101 $langs = new Translate('', $conf);
12102 $langs->setDefaultLang();
12103 }
12104
12105 $langs->load("errors");
12106
12107 if ($printheader) {
12108 if (function_exists("llxHeader")) {
12109 llxHeader('');
12110 } elseif (function_exists("llxHeaderVierge")) {
12111 llxHeaderVierge('');
12112 }
12113 }
12114
12115 print '<div class="error">';
12116 if (empty($message)) {
12117 print $langs->trans("ErrorRecordNotFound");
12118 } else {
12119 print $langs->trans($message);
12120 }
12121 print '</div>';
12122 print '<br>';
12123
12124 if (empty($showonlymessage)) {
12125 if (empty($hookmanager)) {
12126 include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
12127 $hookmanager = new HookManager($db);
12128 // Initialize a technical object to manage hooks of page. Note that conf->hooks_modules contains an array of hook context
12129 $hookmanager->initHooks(array('main'));
12130 }
12131
12132 $parameters = array('message' => $message, 'params' => $params);
12133 $reshook = $hookmanager->executeHooks('getErrorRecordNotFound', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
12134 print $hookmanager->resPrint;
12135 }
12136
12137 if ($printfooter && function_exists("llxFooter")) {
12138 llxFooter();
12139 if (is_object($db)) {
12140 $db->close();
12141 }
12142 }
12143 exit(0);
12144}
12145
12176function array_merge_recursive_distinct(array $array1, array $array2): array
12177{
12178 $merged = $array1;
12179
12180 foreach ($array2 as $key => $value) {
12181 if (is_array($value) && isset($merged[$key]) && is_array($merged[$key])) {
12182 $merged[$key] = array_merge_recursive_distinct($merged[$key], $value);
12183 } else {
12184 $merged[$key] = $value;
12185 }
12186 }
12187
12188 return $merged;
12189}
12190
12199function dolRemoveDefaultParameters(array $parameters): array
12200{
12201 foreach ($parameters as $key => $value) {
12202 if ($value == '' || $value == '-1') {
12203 unset($parameters[$key]);
12204 }
12205 }
12206
12207 return $parameters;
12208}
12209
12236{
12237 if (getDolGlobalInt("MAIN_REDIRECT_POST_AS_GET_IF_POSSIBLE") &&
12238 preg_match('/list$/', $context) &&
12239 GETPOST('action') == 'list' &&
12240 in_array(GETPOST('formfilteraction'), array('list', 'listafterchangingselectedfields')) &&
12241 $_SERVER['REQUEST_METHOD'] == 'POST'
12242 ) {
12243 // Detect if it is a simple search (not an massaction)
12244 if (!GETPOST('massaction')) {
12245 $postData = $_POST;
12246
12247 // Remove useless data for a simple search list request
12248 unset($postData['massaction']);
12249 unset($postData['confirmmassactioninvisible']);
12250 unset($postData['token']);
12251
12252 $postData = dolRemoveDefaultParameters($postData);
12253
12254 // Prepare redirection URL
12255 $newLocationUrl = $_SERVER['SCRIPT_NAME'];
12256 $urlParams = http_build_query($postData);
12257 if ($urlParams !== '') {
12258 $newLocationUrl .= '?' . $urlParams;
12259 }
12260
12261 // Make a GET redirection if URL is not too long
12262 $maxUrlLength = getDolGlobalInt("MAIN_REDIRECT_POST_AS_GET_IF_POSSIBLE");
12263 if (strlen($newLocationUrl) <= $maxUrlLength) {
12264 header('Location: ' . $newLocationUrl);
12265 exit();
12266 }
12267 }
12268 }
12269}
12270
12277function getObjectSocId($obj)
12278{
12279 if (!empty($obj->socid)) {
12280 return (int) $obj->socid;
12281 } elseif (!empty($obj->soc_id)) {
12282 return (int) $obj->soc_id;
12283 } elseif (!empty($obj->societe_id)) {
12284 return (int) $obj->societe_id;
12285 }
12286 return null;
12287}
12288
12295{
12296 $default = 10;
12297 if (!empty($_SESSION['dol_screenheight']) && $_SESSION['dol_screenheight'] < 700) {
12298 $default = 8;
12299 } elseif (!empty($_SESSION['dol_screenheight']) && $_SESSION['dol_screenheight'] < 950) {
12300 $default = 10;
12301 } elseif (!empty($_SESSION['dol_screenheight']) && $_SESSION['dol_screenheight'] > 1130) {
12302 $default = 15;
12303 }
12304
12305 return $default;
12306}
$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.
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:353
$object ref
Definition info.php:90
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
static getValidAddress($address, $format, $encode=0, $maxnumberofemail=0)
Return a formatted address string for SMTP protocol.
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 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.
if(! $sortfield) if(! $sortorder) $module
Definition list.php:193
$context
@method int call_trigger(string $triggerName, ?User $user)
Definition command.php:209
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:545
dol_get_next_day($day, $month, $year)
Return next day.
Definition date.lib.php:530
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:514
dol_get_next_month($month, $year)
Return next month.
Definition date.lib.php:564
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.
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:66
dol_is_dir($folder)
Test if filename is a directory.
$date_start
Variables from include:
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.
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.
getExecutableContent()
Return array of extension for executable files of text files that can contains executable code.
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 ...
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.
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.
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.
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
dolExplodeIntoArray($string, $delimiter=';', $kv='=')
Split a string with 2 keys into key array.
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.
dol_ucfirst($string, $encoding="UTF-8")
Convert first character of the first word of a string to upper.
dol_print_phone($phone, $countrycode='', $contactid=0, $socid=0, $addlink='', $separ="&nbsp;", $withpicto='', $titlealt='', $adddivfloat=0, $morecss='paddingright')
Format phone numbers according to country.
dol_strtolower($string, $encoding="UTF-8")
Convert a string to lower.
dol_htmlentitiesbr_decode($stringtodecode, $pagecodeto='UTF-8')
This function is called to decode a HTML string (it decodes entities and br tags)
getDoliDBInstance($type, $host, $user, $pass, $name, $port, $forcenew=false)
Return a DoliDB instance (database handler).
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
isVisibleToUserType($type_user, &$menuentry, &$listofmodulesforexternal)
Function to test if an entry is enabled or not.
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.
dol_strlen($string, $stringencoding='UTF-8', $binarycount=0)
Make a strlen call.
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.
isASecretKey($keyname)
Return if string has a name dedicated to store a secret.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
dol_string_onlythesehtmlattributes($stringtoclean, $allowed_attributes=null, $ishtml=null)
Clean a string from some undesirable HTML tags.
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.
roundUpToNextMultiple($n, $x=5)
Round to next multiple.
dol_user_country()
Return country code for current user.
dol_getThemeFilePath($file, $theme='')
Return the full filesystem path of a file located in the currently selected theme directory.
getLabelSpecialCode($idcode)
Make content of an input box selected when we click into input field.
getMultidirTemp($object, $module='', $forobject=0)
Return the full path of the directory where a module (or an object of a module) stores its temporary ...
currentToken()
Return the value of token currently saved into session with name 'token'.
dolBuildUrl($url, $params=[], $addtoken=false, $anchor='')
Return path of url.
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.
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.
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.
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.
utf8_valid($str)
Check if a string is in UTF8.
getDolUserString($key, $default='', $tmpuser=null)
Return Dolibarr user constant string value.
getDolOptimizeSmallScreen()
Return if render must be optimized for small screen.
isValidMXRecord($domain)
Return if the domain name has a valid MX record.
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.
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...
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.
getElementProperties($elementType)
Get an array with properties of an element.
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.
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.
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.
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.
GETPOSTFLOAT($paramname, $rounding='', $option=2)
Return the value of a $_GET or $_POST supervariable, converted into float.
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.
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.
getBrowserInfo($user_agent)
Return information about user browser.
dolGetFirstLetters($s, $nbofchar=1)
Return first letters of a strings.
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, or into a js string that is a locat...
getImageFileNameForSize($file, $extName, $extImgTarget='')
Return the filename of file to get the thumbs.
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...
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...)
dolGetCountryCodeFromIp($ip)
Return a country code from IP.
dol_textishtml($msg, $option=0)
Return if a text is a html content.
colorIsLight($stringcolor)
Return true if the color is light.
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.
dolRemoveDefaultParameters(array $parameters)
Function to remove parameters having their default value.
dolExplodeKeepIfQuotes($input)
Explode a search string into an array but do not explode when keys are inside quotes.
readfileLowMemory($fullpath_original_file_osencoded, $method=-1)
Return a file on output using a low memory.
dolIsAllowedForPreview($file)
Return if a file is qualified for preview.
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.
dolEvalSimpleCondition($s)
Evaluate a condition made of simple terms, without eval().
dolRedirectPostSearchListRequestToGetIfPossible(string $context)
Function to redirect search list forms from POST to GET request.
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.
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).
dolGetCityFromIp($ip)
Return a city name from IP.
getDolGlobalBool($key, $default=false)
Return a Dolibarr global constant boolean value.
getTimelineIcon($actionstatic, &$histo, $key)
Get timeline icon.
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,...
isAFileWithExecutableContent($filename)
Return if a file can contains executable content.
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).
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...
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.
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.
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.
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...
getDictionaryValue($tablename, $field, $id, $checkentity=false, $rowidfield='rowid')
Return the value of a filed into a dictionary for the record $id.
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.
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)
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...
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.
picto_from_langcode($codelang, $moreatt='', $notitlealt=0)
Return img flag of country for a language code or country code.
showValueWithClipboardCPButton($valuetocopy, $showonlyonhover=1, $texttoshow='')
Create a button to copy $valuetocopy in the clipboard (for copy and paste feature).
showSimpleHTMLTable($outputlangs, $object)
Returns simple order table template as string.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Definition html.lib.php:183
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.
dolGetRandomBytes($length)
Return a string of random bytes (hexa string) with length = $length for cryptographic purposes.
isHTTPS()
Return if we are using a HTTPS connection Check HTTPS (no way to be modified by user but may be empty...
div refaddress div address
realCharForNumericEntities($matches)
Return the real char for a numeric entities.
Definition waf.inc.php:66