dolibarr 18.0.6
functions.lib.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2000-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2003 Jean-Louis Bergamo <jlb@j1b.org>
4 * Copyright (C) 2004-2022 Laurent Destailleur <eldy@users.sourceforge.net>
5 * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
6 * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
7 * Copyright (C) 2004 Christophe Combelles <ccomb@free.fr>
8 * Copyright (C) 2005-2019 Regis Houssin <regis.houssin@inodbox.com>
9 * Copyright (C) 2008 Raphael Bertrand (Resultic) <raphael.bertrand@resultic.fr>
10 * Copyright (C) 2010-2018 Juanjo Menent <jmenent@2byte.es>
11 * Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr>
12 * Copyright (C) 2013-2021 Alexandre Spangaro <aspangaro@open-dsi.fr>
13 * Copyright (C) 2014 Cédric GROSS <c.gross@kreiz-it.fr>
14 * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
15 * Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
16 * Copyright (C) 2018-2023 Frédéric France <frederic.france@netlogic.fr>
17 * Copyright (C) 2019-2023 Thibault Foucart <support@ptibogxiv.net>
18 * Copyright (C) 2020 Open-Dsi <support@open-dsi.fr>
19 * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
20 * Copyright (C) 2022 Anthony Berton <anthony.berton@bb2a.fr>
21 * Copyright (C) 2022 Ferran Marcet <fmarcet@2byte.es>
22 * Copyright (C) 2022 Charlene Benke <charlene@patas-monkey.com>
23 * Copyright (C) 2023 Joachim Kueter <git-jk@bloxera.com>
24 *
25 * This program is free software; you can redistribute it and/or modify
26 * it under the terms of the GNU General Public License as published by
27 * the Free Software Foundation; either version 3 of the License, or
28 * (at your option) any later version.
29 *
30 * This program is distributed in the hope that it will be useful,
31 * but WITHOUT ANY WARRANTY; without even the implied warranty of
32 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
33 * GNU General Public License for more details.
34 *
35 * You should have received a copy of the GNU General Public License
36 * along with this program. If not, see <https://www.gnu.org/licenses/>.
37 * or see https://www.gnu.org/
38 */
39
46include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
47
48// Function for better PHP x compatibility
49if (!function_exists('utf8_encode')) {
56 function utf8_encode($elements)
57 {
58 return mb_convert_encoding($elements, 'UTF-8', 'ISO-8859-1');
59 }
60}
61
62if (!function_exists('utf8_decode')) {
69 function utf8_decode($elements)
70 {
71 return mb_convert_encoding($elements, 'ISO-8859-1', 'UTF-8');
72 }
73}
74if (!function_exists('str_starts_with')) {
82 function str_starts_with($haystack, $needle)
83 {
84 return (string) $needle !== '' && strncmp($haystack, $needle, strlen($needle)) === 0;
85 }
86}
87if (!function_exists('str_ends_with')) {
95 function str_ends_with($haystack, $needle)
96 {
97 return $needle !== '' && substr($haystack, -strlen($needle)) === (string) $needle;
98 }
99}
100if (!function_exists('str_contains')) {
108 function str_contains($haystack, $needle)
109 {
110 return $needle !== '' && mb_strpos($haystack, $needle) !== false;
111 }
112}
113
114
123function getMultidirOutput($object, $module = '')
124{
125 global $conf;
126 if (!is_object($object) && empty($module)) {
127 return null;
128 }
129 if (empty($module) && !empty($object->element)) {
130 $module = $object->element;
131 }
132 return $conf->$module->multidir_output[(!empty($object->entity) ? $object->entity : $conf->entity)];
133}
134
142function getDolGlobalString($key, $default = '')
143{
144 global $conf;
145 // return $conf->global->$key ?? $default;
146 return (string) (isset($conf->global->$key) ? $conf->global->$key : $default);
147}
148
156function getDolGlobalInt($key, $default = 0)
157{
158 global $conf;
159 // return $conf->global->$key ?? $default;
160 return (int) (isset($conf->global->$key) ? $conf->global->$key : $default);
161}
162
171function getDolUserString($key, $default = '', $tmpuser = null)
172{
173 if (empty($tmpuser)) {
174 global $user;
175 $tmpuser = $user;
176 }
177
178 // return $conf->global->$key ?? $default;
179 return (string) (empty($tmpuser->conf->$key) ? $default : $tmpuser->conf->$key);
180}
181
190function getDolUserInt($key, $default = 0, $tmpuser = null)
191{
192 if (empty($tmpuser)) {
193 global $user;
194 $tmpuser = $user;
195 }
196
197 // return $conf->global->$key ?? $default;
198 return (int) (empty($tmpuser->conf->$key) ? $default : $tmpuser->conf->$key);
199}
200
207function isModEnabled($module)
208{
209 global $conf;
210
211 // Fix special cases
212 $arrayconv = array(
213 'bank' => 'banque',
214 'category' => 'categorie',
215 'contract' => 'contrat',
216 'project' => 'projet',
217 'delivery_note' => 'expedition'
218 );
219 if (empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) {
220 $arrayconv['supplier_order'] = 'fournisseur';
221 $arrayconv['supplier_invoice'] = 'fournisseur';
222 }
223 if (!empty($arrayconv[$module])) {
224 $module = $arrayconv[$module];
225 }
226
227 return !empty($conf->modules[$module]);
228 //return !empty($conf->$module->enabled);
229}
230
242function getDoliDBInstance($type, $host, $user, $pass, $name, $port)
243{
244 require_once DOL_DOCUMENT_ROOT."/core/db/".$type.'.class.php';
245
246 $class = 'DoliDB'.ucfirst($type);
247 $dolidb = new $class($type, $host, $user, $pass, $name, $port);
248 return $dolidb;
249}
250
268function getEntity($element, $shared = 1, $currentobject = null)
269{
270 global $conf, $mc, $hookmanager, $object, $action, $db;
271
272 if (!is_object($hookmanager)) {
273 include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
274 $hookmanager = new HookManager($db);
275 }
276
277 // fix different element names (France to English)
278 switch ($element) {
279 case 'projet':
280 $element = 'project';
281 break;
282 case 'contrat':
283 $element = 'contract';
284 break; // "/contrat/class/contrat.class.php"
285 case 'order_supplier':
286 $element = 'supplier_order';
287 break; // "/fourn/class/fournisseur.commande.class.php"
288 case 'invoice_supplier':
289 $element = 'supplier_invoice';
290 break; // "/fourn/class/fournisseur.facture.class.php"
291 }
292
293 if (is_object($mc)) {
294 $out = $mc->getEntity($element, $shared, $currentobject);
295 } else {
296 $out = '';
297 $addzero = array('user', 'usergroup', 'cronjob', 'c_email_templates', 'email_template', 'default_values', 'overwrite_trans');
298 if (in_array($element, $addzero)) {
299 $out .= '0,';
300 }
301 $out .= ((int) $conf->entity);
302 }
303
304 // Manipulate entities to query on the fly
305 $parameters = array(
306 'element' => $element,
307 'shared' => $shared,
308 'object' => $object,
309 'currentobject' => $currentobject,
310 'out' => $out
311 );
312 $reshook = $hookmanager->executeHooks('hookGetEntity', $parameters, $currentobject, $action); // Note that $action and $object may have been modified by some hooks
313
314 if (is_numeric($reshook)) {
315 if ($reshook == 0 && !empty($hookmanager->resPrint)) {
316 $out .= ','.$hookmanager->resPrint; // add
317 } elseif ($reshook == 1) {
318 $out = $hookmanager->resPrint; // replace
319 }
320 }
321
322 return $out;
323}
324
331function setEntity($currentobject)
332{
333 global $conf, $mc;
334
335 if (is_object($mc) && method_exists($mc, 'setEntity')) {
336 return $mc->setEntity($currentobject);
337 } else {
338 return ((is_object($currentobject) && $currentobject->id > 0 && $currentobject->entity > 0) ? $currentobject->entity : $conf->entity);
339 }
340}
341
348function isASecretKey($keyname)
349{
350 return preg_match('/(_pass|password|_pw|_key|securekey|serverkey|secret\d?|p12key|exportkey|_PW_[a-z]+|token)$/i', $keyname);
351}
352
353
360function num2Alpha($n)
361{
362 for ($r = ""; $n >= 0; $n = intval($n / 26) - 1)
363 $r = chr($n % 26 + 0x41) . $r;
364 return $r;
365}
366
367
384function getBrowserInfo($user_agent)
385{
386 include_once DOL_DOCUMENT_ROOT.'/includes/mobiledetect/mobiledetectlib/Mobile_Detect.php';
387
388 $name = 'unknown';
389 $version = '';
390 $os = 'unknown';
391 $phone = '';
392
393 $user_agent = substr($user_agent, 0, 512); // Avoid to process too large user agent
394
395 $detectmobile = new Mobile_Detect(null, $user_agent);
396 $tablet = $detectmobile->isTablet();
397
398 if ($detectmobile->isMobile()) {
399 $phone = 'unknown';
400
401 // If phone/smartphone, we set phone os name.
402 if ($detectmobile->is('AndroidOS')) {
403 $os = $phone = 'android';
404 } elseif ($detectmobile->is('BlackBerryOS')) {
405 $os = $phone = 'blackberry';
406 } elseif ($detectmobile->is('iOS')) {
407 $os = 'ios';
408 $phone = 'iphone';
409 } elseif ($detectmobile->is('PalmOS')) {
410 $os = $phone = 'palm';
411 } elseif ($detectmobile->is('SymbianOS')) {
412 $os = 'symbian';
413 } elseif ($detectmobile->is('webOS')) {
414 $os = 'webos';
415 } elseif ($detectmobile->is('MaemoOS')) {
416 $os = 'maemo';
417 } elseif ($detectmobile->is('WindowsMobileOS') || $detectmobile->is('WindowsPhoneOS')) {
418 $os = 'windows';
419 }
420 }
421
422 // OS
423 if (preg_match('/linux/i', $user_agent)) {
424 $os = 'linux';
425 } elseif (preg_match('/macintosh/i', $user_agent)) {
426 $os = 'macintosh';
427 } elseif (preg_match('/windows/i', $user_agent)) {
428 $os = 'windows';
429 }
430
431 // Name
432 $reg = array();
433 if (preg_match('/firefox(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
434 $name = 'firefox';
435 $version = empty($reg[2]) ? '' : $reg[2];
436 } elseif (preg_match('/edge(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
437 $name = 'edge';
438 $version = empty($reg[2]) ? '' : $reg[2];
439 } elseif (preg_match('/chrome(\/|\s)([\d\.]+)/i', $user_agent, $reg)) {
440 $name = 'chrome';
441 $version = empty($reg[2]) ? '' : $reg[2];
442 } elseif (preg_match('/chrome/i', $user_agent, $reg)) {
443 // we can have 'chrome (Mozilla...) chrome x.y' in one string
444 $name = 'chrome';
445 } elseif (preg_match('/iceweasel/i', $user_agent)) {
446 $name = 'iceweasel';
447 } elseif (preg_match('/epiphany/i', $user_agent)) {
448 $name = 'epiphany';
449 } elseif (preg_match('/safari(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
450 $name = 'safari';
451 $version = empty($reg[2]) ? '' : $reg[2];
452 } elseif (preg_match('/opera(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
453 // Safari is often present in string for mobile but its not.
454 $name = 'opera';
455 $version = empty($reg[2]) ? '' : $reg[2];
456 } elseif (preg_match('/(MSIE\s([0-9]+\.[0-9]))|.*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
457 $name = 'ie';
458 $version = end($reg);
459 } elseif (preg_match('/(Windows NT\s([0-9]+\.[0-9])).*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
460 // MS products at end
461 $name = 'ie';
462 $version = end($reg);
463 } elseif (preg_match('/l[iy]n(x|ks)(\‍(|\/|\s)*([\d\.]+)/i', $user_agent, $reg)) {
464 // MS products at end
465 $name = 'lynxlinks';
466 $version = empty($reg[3]) ? '' : $reg[3];
467 }
468
469 if ($tablet) {
470 $layout = 'tablet';
471 } elseif ($phone) {
472 $layout = 'phone';
473 } else {
474 $layout = 'classic';
475 }
476
477 return array(
478 'browsername' => $name,
479 'browserversion' => $version,
480 'browseros' => $os,
481 'browserua' => $user_agent,
482 'layout' => $layout, // tablet, phone, classic
483 'phone' => $phone, // deprecated
484 'tablet' => $tablet // deprecated
485 );
486}
487
493function dol_shutdown()
494{
495 global $user, $langs, $db;
496 $disconnectdone = false;
497 $depth = 0;
498 if (is_object($db) && !empty($db->connected)) {
499 $depth = $db->transaction_opened;
500 $disconnectdone = $db->close();
501 }
502 dol_syslog("--- End access to ".$_SERVER["PHP_SELF"].(($disconnectdone && $depth) ? ' (Warn: db disconnection forced, transaction depth was '.$depth.')' : ''), (($disconnectdone && $depth) ? LOG_WARNING : LOG_INFO));
503}
504
514function GETPOSTISSET($paramname)
515{
516 $isset = false;
517
518 $relativepathstring = $_SERVER["PHP_SELF"];
519 // Clean $relativepathstring
520 if (constant('DOL_URL_ROOT')) {
521 $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
522 }
523 $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
524 $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
525 //var_dump($relativepathstring);
526 //var_dump($user->default_values);
527
528 // Code for search criteria persistence.
529 // Retrieve values if restore_lastsearch_values
530 if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
531 if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
532 $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
533 if (is_array($tmp)) {
534 foreach ($tmp as $key => $val) {
535 if ($key == $paramname) { // We are on the requested parameter
536 $isset = true;
537 break;
538 }
539 }
540 }
541 }
542 // If there is saved contextpage, limit, page or mode
543 if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
544 $isset = true;
545 } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
546 $isset = true;
547 } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
548 $isset = true;
549 } elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_'.$relativepathstring])) {
550 $isset = true;
551 }
552 } else {
553 $isset = (isset($_POST[$paramname]) || isset($_GET[$paramname])); // We must keep $_POST and $_GET here
554 }
555
556 return $isset;
557}
558
567function GETPOSTISARRAY($paramname, $method = 0)
568{
569 // for $method test need return the same $val as GETPOST
570 if (empty($method)) {
571 $val = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
572 } elseif ($method == 1) {
573 $val = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
574 } elseif ($method == 2) {
575 $val = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
576 } elseif ($method == 3) {
577 $val = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
578 } else {
579 $val = 'BadFirstParameterForGETPOST';
580 }
581
582 return is_array($val);
583}
584
614function GETPOST($paramname, $check = 'alphanohtml', $method = 0, $filter = null, $options = null, $noreplace = 0)
615{
616 global $mysoc, $user, $conf;
617
618 if (empty($paramname)) {
619 return 'BadFirstParameterForGETPOST';
620 }
621 if (empty($check)) {
622 dol_syslog("Deprecated use of GETPOST, called with 1st param = ".$paramname." and 2nd param is '', when calling page ".$_SERVER["PHP_SELF"], LOG_WARNING);
623 // Enable this line to know who call the GETPOST with '' $check parameter.
624 //var_dump(debug_backtrace()[0]);
625 }
626
627 if (empty($method)) {
628 $out = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
629 } elseif ($method == 1) {
630 $out = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
631 } elseif ($method == 2) {
632 $out = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
633 } elseif ($method == 3) {
634 $out = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
635 } else {
636 return 'BadThirdParameterForGETPOST';
637 }
638
639 if (empty($method) || $method == 3 || $method == 4) {
640 $relativepathstring = $_SERVER["PHP_SELF"];
641 // Clean $relativepathstring
642 if (constant('DOL_URL_ROOT')) {
643 $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
644 }
645 $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
646 $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
647 //var_dump($relativepathstring);
648 //var_dump($user->default_values);
649
650 // Code for search criteria persistence.
651 // Retrieve values if restore_lastsearch_values
652 if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
653 if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
654 $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
655 if (is_array($tmp)) {
656 foreach ($tmp as $key => $val) {
657 if ($key == $paramname) { // We are on the requested parameter
658 $out = $val;
659 break;
660 }
661 }
662 }
663 }
664 // If there is saved contextpage, page or limit
665 if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
666 $out = $_SESSION['lastsearch_contextpage_'.$relativepathstring];
667 } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
668 $out = $_SESSION['lastsearch_limit_'.$relativepathstring];
669 } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
670 $out = $_SESSION['lastsearch_page_'.$relativepathstring];
671 } elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_'.$relativepathstring])) {
672 $out = $_SESSION['lastsearch_mode_'.$relativepathstring];
673 }
674 } elseif (!isset($_GET['sortfield'])) {
675 // Else, retrieve default values if we are not doing a sort
676 // 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
677 if (!empty($_GET['action']) && $_GET['action'] == 'create' && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
678 // Search default value from $object->field
679 global $object;
680 if (is_object($object) && isset($object->fields[$paramname]['default'])) {
681 $out = $object->fields[$paramname]['default'];
682 }
683 }
684 if (!empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES)) {
685 if (!empty($_GET['action']) && (preg_match('/^create/', $_GET['action']) || preg_match('/^presend/', $_GET['action'])) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
686 // Now search in setup to overwrite default values
687 if (!empty($user->default_values)) { // $user->default_values defined from menu 'Setup - Default values'
688 if (isset($user->default_values[$relativepathstring]['createform'])) {
689 foreach ($user->default_values[$relativepathstring]['createform'] as $defkey => $defval) {
690 $qualified = 0;
691 if ($defkey != '_noquery_') {
692 $tmpqueryarraytohave = explode('&', $defkey);
693 $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
694 $foundintru = 0;
695 foreach ($tmpqueryarraytohave as $tmpquerytohave) {
696 if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
697 $foundintru = 1;
698 }
699 }
700 if (!$foundintru) {
701 $qualified = 1;
702 }
703 //var_dump($defkey.'-'.$qualified);
704 } else {
705 $qualified = 1;
706 }
707
708 if ($qualified) {
709 if (isset($user->default_values[$relativepathstring]['createform'][$defkey][$paramname])) {
710 $out = $user->default_values[$relativepathstring]['createform'][$defkey][$paramname];
711 break;
712 }
713 }
714 }
715 }
716 }
717 } elseif (!empty($paramname) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
718 // Management of default search_filters and sort order
719 if (!empty($user->default_values)) {
720 // $user->default_values defined from menu 'Setup - Default values'
721 //var_dump($user->default_values[$relativepathstring]);
722 if ($paramname == 'sortfield' || $paramname == 'sortorder') {
723 // Sorted on which fields ? ASC or DESC ?
724 if (isset($user->default_values[$relativepathstring]['sortorder'])) {
725 // Even if paramname is sortfield, data are stored into ['sortorder...']
726 foreach ($user->default_values[$relativepathstring]['sortorder'] as $defkey => $defval) {
727 $qualified = 0;
728 if ($defkey != '_noquery_') {
729 $tmpqueryarraytohave = explode('&', $defkey);
730 $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
731 $foundintru = 0;
732 foreach ($tmpqueryarraytohave as $tmpquerytohave) {
733 if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
734 $foundintru = 1;
735 }
736 }
737 if (!$foundintru) {
738 $qualified = 1;
739 }
740 //var_dump($defkey.'-'.$qualified);
741 } else {
742 $qualified = 1;
743 }
744
745 if ($qualified) {
746 $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
747 foreach ($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val) {
748 if ($out) {
749 $out .= ', ';
750 }
751 if ($paramname == 'sortfield') {
752 $out .= dol_string_nospecial($key, '', $forbidden_chars_to_replace);
753 }
754 if ($paramname == 'sortorder') {
755 $out .= dol_string_nospecial($val, '', $forbidden_chars_to_replace);
756 }
757 }
758 //break; // No break for sortfield and sortorder so we can cumulate fields (is it realy usefull ?)
759 }
760 }
761 }
762 } elseif (isset($user->default_values[$relativepathstring]['filters'])) {
763 foreach ($user->default_values[$relativepathstring]['filters'] as $defkey => $defval) { // $defkey is a querystring like 'a=b&c=d', $defval is key of user
764 if (!empty($_GET['disabledefaultvalues'])) { // If set of default values has been disabled by a request parameter
765 continue;
766 }
767 $qualified = 0;
768 if ($defkey != '_noquery_') {
769 $tmpqueryarraytohave = explode('&', $defkey);
770 $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
771 $foundintru = 0;
772 foreach ($tmpqueryarraytohave as $tmpquerytohave) {
773 if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
774 $foundintru = 1;
775 }
776 }
777 if (!$foundintru) {
778 $qualified = 1;
779 }
780 //var_dump($defkey.'-'.$qualified);
781 } else {
782 $qualified = 1;
783 }
784
785 if ($qualified && isset($user->default_values[$relativepathstring]['filters'][$defkey][$paramname])) {
786 // We must keep $_POST and $_GET here
787 if (isset($_POST['sall']) || isset($_POST['search_all']) || isset($_GET['sall']) || isset($_GET['search_all'])) {
788 // We made a search from quick search menu, do we still use default filter ?
789 if (empty($conf->global->MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH)) {
790 $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
791 $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
792 }
793 } else {
794 $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
795 $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
796 }
797 break;
798 }
799 }
800 }
801 }
802 }
803 }
804 }
805 }
806
807 // Substitution variables for GETPOST (used to get final url with variable parameters or final default value with variable parameters)
808 // Example of variables: __DAY__, __MONTH__, __YEAR__, __MYCOMPANY_COUNTRY_ID__, __USER_ID__, ...
809 // 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.
810 if (!is_array($out) && empty($_POST[$paramname]) && empty($noreplace)) {
811 $reg = array();
812 $maxloop = 20;
813 $loopnb = 0; // Protection against infinite loop
814 while (preg_match('/__([A-Z0-9]+_?[A-Z0-9]+)__/i', $out, $reg) && ($loopnb < $maxloop)) { // Detect '__ABCDEF__' as key 'ABCDEF' and '__ABC_DEF__' as key 'ABC_DEF'. Detection is also correct when 2 vars are side by side.
815 $loopnb++;
816 $newout = '';
817
818 if ($reg[1] == 'DAY') {
819 $tmp = dol_getdate(dol_now(), true);
820 $newout = $tmp['mday'];
821 } elseif ($reg[1] == 'MONTH') {
822 $tmp = dol_getdate(dol_now(), true);
823 $newout = $tmp['mon'];
824 } elseif ($reg[1] == 'YEAR') {
825 $tmp = dol_getdate(dol_now(), true);
826 $newout = $tmp['year'];
827 } elseif ($reg[1] == 'PREVIOUS_DAY') {
828 $tmp = dol_getdate(dol_now(), true);
829 $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
830 $newout = $tmp2['day'];
831 } elseif ($reg[1] == 'PREVIOUS_MONTH') {
832 $tmp = dol_getdate(dol_now(), true);
833 $tmp2 = dol_get_prev_month($tmp['mon'], $tmp['year']);
834 $newout = $tmp2['month'];
835 } elseif ($reg[1] == 'PREVIOUS_YEAR') {
836 $tmp = dol_getdate(dol_now(), true);
837 $newout = ($tmp['year'] - 1);
838 } elseif ($reg[1] == 'NEXT_DAY') {
839 $tmp = dol_getdate(dol_now(), true);
840 $tmp2 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
841 $newout = $tmp2['day'];
842 } elseif ($reg[1] == 'NEXT_MONTH') {
843 $tmp = dol_getdate(dol_now(), true);
844 $tmp2 = dol_get_next_month($tmp['mon'], $tmp['year']);
845 $newout = $tmp2['month'];
846 } elseif ($reg[1] == 'NEXT_YEAR') {
847 $tmp = dol_getdate(dol_now(), true);
848 $newout = ($tmp['year'] + 1);
849 } elseif ($reg[1] == 'MYCOMPANY_COUNTRY_ID' || $reg[1] == 'MYCOUNTRY_ID' || $reg[1] == 'MYCOUNTRYID') {
850 $newout = $mysoc->country_id;
851 } elseif ($reg[1] == 'USER_ID' || $reg[1] == 'USERID') {
852 $newout = $user->id;
853 } elseif ($reg[1] == 'USER_SUPERVISOR_ID' || $reg[1] == 'SUPERVISOR_ID' || $reg[1] == 'SUPERVISORID') {
854 $newout = $user->fk_user;
855 } elseif ($reg[1] == 'ENTITY_ID' || $reg[1] == 'ENTITYID') {
856 $newout = $conf->entity;
857 } else {
858 $newout = ''; // Key not found, we replace with empty string
859 }
860 //var_dump('__'.$reg[1].'__ -> '.$newout);
861 $out = preg_replace('/__'.preg_quote($reg[1], '/').'__/', $newout, $out);
862 }
863 }
864
865 // Check rule
866 if (preg_match('/^array/', $check)) { // If 'array' or 'array:restricthtml' or 'array:aZ09' or 'array:intcomma'
867 if (!is_array($out) || empty($out)) {
868 $out = array();
869 } else {
870 $tmparray = explode(':', $check);
871 if (!empty($tmparray[1])) {
872 $tmpcheck = $tmparray[1];
873 } else {
874 $tmpcheck = 'alphanohtml';
875 }
876 foreach ($out as $outkey => $outval) {
877 $out[$outkey] = sanitizeVal($outval, $tmpcheck, $filter, $options);
878 }
879 }
880 } else {
881 // If field name is 'search_xxx' then we force the add of space after each < and > (when following char is numeric) because it means
882 // 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
883 if (strpos($paramname, 'search_') === 0) {
884 $out = preg_replace('/([<>])([-+]?\d)/', '\1 \2', $out);
885 }
886
887 $out = sanitizeVal($out, $check, $filter, $options);
888 }
889
890 // Sanitizing for special parameters.
891 // Note: There is no reason to allow the backtopage, backtolist or backtourl parameter to contains an external URL. Only relative URLs are allowed.
892 if ($paramname == 'backtopage' || $paramname == 'backtolist' || $paramname == 'backtourl') {
893 $out = str_replace('\\', '/', $out); // Can be before the loop because only 1 char is replaced. No risk to get it after other replacements.
894 $out = str_replace(array(':', ';', '@', "\t", ' '), '', $out); // Can be before the loop because only 1 char is replaced. No risk to retreive it after other replacements.
895 do {
896 $oldstringtoclean = $out;
897 $out = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $out);
898 $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'
899 $out = preg_replace(array('/^[a-z]*\/\s*\/+/i'), '', $out); // We remove schema*// to remove external URL
900 } while ($oldstringtoclean != $out);
901 }
902
903 // Code for search criteria persistence.
904 // Save data into session if key start with 'search_' or is 'smonth', 'syear', 'month', 'year'
905 if (empty($method) || $method == 3 || $method == 4) {
906 if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder', 'sortfield'))) {
907 //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]);
908
909 // We save search key only if $out not empty that means:
910 // - posted value not empty, or
911 // - 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).
912
913 if ($out != '' && isset($user)) {// $out = '0' or 'abc', it is a search criteria to keep
914 $user->lastsearch_values_tmp[$relativepathstring][$paramname] = $out;
915 }
916 }
917 }
918
919 return $out;
920}
921
931function GETPOSTINT($paramname, $method = 0)
932{
933 return (int) GETPOST($paramname, 'int', $method, null, null, 0);
934}
935
936
947function checkVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
948{
949 return sanitizeVal($out, $check, $filter, $options);
950}
951
961function sanitizeVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
962{
963 // TODO : use class "Validate" to perform tests (and add missing tests) if needed for factorize
964 // Check is done after replacement
965 switch ($check) {
966 case 'none':
967 break;
968 case 'int': // Check param is a numeric value (integer but also float or hexadecimal)
969 if (!is_numeric($out)) {
970 $out = '';
971 }
972 break;
973 case 'intcomma':
974 if (is_array($out)) {
975 $out = implode(',', $out);
976 }
977 if (preg_match('/[^0-9,-]+/i', $out)) {
978 $out = '';
979 }
980 break;
981 case 'san_alpha':
982 $out = filter_var($out, FILTER_SANITIZE_STRING);
983 break;
984 case 'email':
985 $out = filter_var($out, FILTER_SANITIZE_EMAIL);
986 break;
987 case 'aZ':
988 if (!is_array($out)) {
989 $out = trim($out);
990 if (preg_match('/[^a-z]+/i', $out)) {
991 $out = '';
992 }
993 }
994 break;
995 case 'aZ09':
996 if (!is_array($out)) {
997 $out = trim($out);
998 if (preg_match('/[^a-z0-9_\-\.]+/i', $out)) {
999 $out = '';
1000 }
1001 }
1002 break;
1003 case 'aZ09arobase': // great to sanitize $objecttype parameter
1004 if (!is_array($out)) {
1005 $out = trim($out);
1006 if (preg_match('/[^a-z0-9_\-\.@]+/i', $out)) {
1007 $out = '';
1008 }
1009 }
1010 break;
1011 case 'aZ09comma': // great to sanitize $sortfield or $sortorder params that can be 't.abc,t.def_gh'
1012 if (!is_array($out)) {
1013 $out = trim($out);
1014 if (preg_match('/[^a-z0-9_\-\.,]+/i', $out)) {
1015 $out = '';
1016 }
1017 }
1018 break;
1019 case 'alpha': // No html and no ../ and "
1020 case 'alphanohtml': // Recommended for most scalar parameters and search parameters
1021 if (!is_array($out)) {
1022 $out = trim($out);
1023 do {
1024 $oldstringtoclean = $out;
1025 // Remove html tags
1026 $out = dol_string_nohtmltag($out, 0);
1027 // Remove also other dangerous string sequences
1028 // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
1029 // '../' or '..\' is dangerous because it allows dir transversals
1030 // Note &#38, '&#0000038', '&#x26'... is a simple char like '&' alone but there is no reason to accept such way to encode input data.
1031 $out = str_ireplace(array('&#38', '&#0000038', '&#x26', '&quot', '&#34', '&#0000034', '&#x22', '"', '&#47', '&#0000047', '&#92', '&#0000092', '&#x2F', '../', '..\\'), '', $out);
1032 } while ($oldstringtoclean != $out);
1033 // keep lines feed
1034 }
1035 break;
1036 case 'alphawithlgt': // No " and no ../ but we keep balanced < > tags with no special chars inside. Can be used for email string like "Name <email>". Less secured than 'alphanohtml'
1037 if (!is_array($out)) {
1038 $out = trim($out);
1039 do {
1040 $oldstringtoclean = $out;
1041 // Remove html tags
1042 $out = dol_html_entity_decode($out, ENT_COMPAT | ENT_HTML5, 'UTF-8');
1043 // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
1044 // '../' or '..\' is dangerous because it allows dir transversals
1045 // Note &#38, '&#0000038', '&#x26'... is a simple char like '&' alone but there is no reason to accept such way to encode input data.
1046 $out = str_ireplace(array('&#38', '&#0000038', '&#x26', '&quot', '&#34', '&#0000034', '&#x22', '"', '&#47', '&#0000047', '&#92', '&#0000092', '&#x2F', '../', '..\\'), '', $out);
1047 } while ($oldstringtoclean != $out);
1048 }
1049 break;
1050 case 'nohtml': // No html
1051 $out = dol_string_nohtmltag($out, 0);
1052 break;
1053 case 'restricthtmlnolink':
1054 case 'restricthtml': // Recommended for most html textarea
1055 case 'restricthtmlallowclass':
1056 case 'restricthtmlallowunvalid':
1057 $out = dol_htmlwithnojs($out, 1, $check);
1058 break;
1059 case 'custom':
1060 if (!empty($out)) {
1061 if (empty($filter)) {
1062 return 'BadParameterForGETPOST - Param 3 of sanitizeVal()';
1063 }
1064 /*if (empty($options)) {
1065 return 'BadParameterForGETPOST - Param 4 of sanitizeVal()';
1066 }*/
1067 $out = filter_var($out, $filter, $options);
1068 }
1069 break;
1070 }
1071
1072 return $out;
1073}
1074
1075
1076if (!function_exists('dol_getprefix')) {
1086 function dol_getprefix($mode = '')
1087 {
1088 // If prefix is for email (we need to have $conf already loaded for this case)
1089 if ($mode == 'email') {
1090 global $conf;
1091
1092 if (!empty($conf->global->MAIL_PREFIX_FOR_EMAIL_ID)) { // If MAIL_PREFIX_FOR_EMAIL_ID is set
1093 if ($conf->global->MAIL_PREFIX_FOR_EMAIL_ID != 'SERVER_NAME') {
1094 return $conf->global->MAIL_PREFIX_FOR_EMAIL_ID;
1095 } elseif (isset($_SERVER["SERVER_NAME"])) { // If MAIL_PREFIX_FOR_EMAIL_ID is set to 'SERVER_NAME'
1096 return $_SERVER["SERVER_NAME"];
1097 }
1098 }
1099
1100 // The recommended value if MAIL_PREFIX_FOR_EMAIL_ID is not defined (may be not defined for old versions)
1101 if (!empty($conf->file->instance_unique_id)) {
1102 return sha1('dolibarr'.$conf->file->instance_unique_id);
1103 }
1104
1105 // For backward compatibility when instance_unique_id is not set
1106 return sha1(DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
1107 }
1108
1109 // If prefix is for session (no need to have $conf loaded)
1110 global $dolibarr_main_instance_unique_id, $dolibarr_main_cookie_cryptkey; // This is loaded by filefunc.inc.php
1111 $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
1112
1113 // The recommended value (may be not defined for old versions)
1114 if (!empty($tmp_instance_unique_id)) {
1115 return sha1('dolibarr'.$tmp_instance_unique_id);
1116 }
1117
1118 // For backward compatibility when instance_unique_id is not set
1119 if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"])) {
1120 return sha1($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
1121 } else {
1122 return sha1(DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
1123 }
1124 }
1125}
1126
1137function dol_include_once($relpath, $classname = '')
1138{
1139 global $conf, $langs, $user, $mysoc; // Do not remove this. They must be defined for files we include. Other globals var must be retrieved with $GLOBALS['var']
1140
1141 $fullpath = dol_buildpath($relpath);
1142
1143 if (!file_exists($fullpath)) {
1144 dol_syslog('functions::dol_include_once Tried to load unexisting file: '.$relpath, LOG_WARNING);
1145 return false;
1146 }
1147
1148 if (!empty($classname) && !class_exists($classname)) {
1149 return include $fullpath;
1150 } else {
1151 return include_once $fullpath;
1152 }
1153}
1154
1155
1166function dol_buildpath($path, $type = 0, $returnemptyifnotfound = 0)
1167{
1168 global $conf;
1169
1170 $path = preg_replace('/^\//', '', $path);
1171
1172 if (empty($type)) { // For a filesystem path
1173 $res = DOL_DOCUMENT_ROOT.'/'.$path; // Standard default path
1174 if (is_array($conf->file->dol_document_root)) {
1175 foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array("main"=>"/home/main/htdocs", "alt0"=>"/home/dirmod/htdocs", ...)
1176 if ($key == 'main') {
1177 continue;
1178 }
1179 // if (@file_exists($dirroot.'/'.$path)) {
1180 if (@file_exists($dirroot.'/'.$path)) { // avoid [php:warn]
1181 $res = $dirroot.'/'.$path;
1182 return $res;
1183 }
1184 }
1185 }
1186 if ($returnemptyifnotfound) {
1187 // Not found into alternate dir
1188 if ($returnemptyifnotfound == 1 || !file_exists($res)) {
1189 return '';
1190 }
1191 }
1192 } else {
1193 // For an url path
1194 // We try to get local path of file on filesystem from url
1195 // Note that trying to know if a file on disk exist by forging path on disk from url
1196 // works only for some web server and some setup. This is bugged when
1197 // using proxy, rewriting, virtual path, etc...
1198 $res = '';
1199 if ($type == 1) {
1200 $res = DOL_URL_ROOT.'/'.$path; // Standard value
1201 }
1202 if ($type == 2) {
1203 $res = DOL_MAIN_URL_ROOT.'/'.$path; // Standard value
1204 }
1205 if ($type == 3) {
1206 $res = DOL_URL_ROOT.'/'.$path;
1207 }
1208
1209 foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
1210 if ($key == 'main') {
1211 if ($type == 3) {
1212 global $dolibarr_main_url_root;
1213
1214 // Define $urlwithroot
1215 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
1216 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
1217 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
1218
1219 $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : $urlwithroot).'/'.$path; // Test on start with http is for old conf syntax
1220 }
1221 continue;
1222 }
1223 $regs = array();
1224 preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i', $path, $regs); // Take part before '?'
1225 if (!empty($regs[1])) {
1226 //print $key.'-'.$dirroot.'/'.$path.'-'.$conf->file->dol_url_root[$type].'<br>'."\n";
1227 //if (file_exists($dirroot.'/'.$regs[1])) {
1228 if (@file_exists($dirroot.'/'.$regs[1])) { // avoid [php:warn]
1229 if ($type == 1) {
1230 $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
1231 }
1232 if ($type == 2) {
1233 $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_MAIN_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
1234 }
1235 if ($type == 3) {
1236 global $dolibarr_main_url_root;
1237
1238 // Define $urlwithroot
1239 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
1240 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
1241 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
1242
1243 $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
1244 }
1245 break;
1246 }
1247 }
1248 }
1249 }
1250
1251 return $res;
1252}
1253
1265function dol_clone($object, $native = 0)
1266{
1267 if ($native == 0) {
1268 // deprecated method, use the method with native = 2 instead
1269 $tmpsavdb = null;
1270 if (isset($object->db) && isset($object->db->db) && is_object($object->db->db) && get_class($object->db->db) == 'PgSql\Connection') {
1271 $tmpsavdb = $object->db;
1272 unset($object->db); // Such property can not be serialized with pgsl (when object->db->db = 'PgSql\Connection')
1273 }
1274
1275 $myclone = unserialize(serialize($object)); // serialize then unserialize is a hack to be sure to have a new object for all fields
1276
1277 if (!empty($tmpsavdb)) {
1278 $object->db = $tmpsavdb;
1279 }
1280 } elseif ($native == 2) {
1281 // recommended method to have a full isolated cloned object
1282 $myclone = new stdClass();
1283 $tmparray = get_object_vars($object); // return only public properties
1284
1285 if (is_array($tmparray)) {
1286 foreach ($tmparray as $propertykey => $propertyval) {
1287 if (is_scalar($propertyval) || is_array($propertyval)) {
1288 $myclone->$propertykey = $propertyval;
1289 }
1290 }
1291 }
1292 } else {
1293 $myclone = clone $object; // PHP clone is a shallow copy only, not a real clone, so properties of references will keep the reference (refering to the same target/variable)
1294 }
1295
1296 return $myclone;
1297}
1298
1308function dol_size($size, $type = '')
1309{
1310 global $conf;
1311 if (empty($conf->dol_optimize_smallscreen)) {
1312 return $size;
1313 }
1314 if ($type == 'width' && $size > 250) {
1315 return 250;
1316 } else {
1317 return 10;
1318 }
1319}
1320
1321
1333function dol_sanitizeFileName($str, $newstr = '_', $unaccent = 1)
1334{
1335 // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
1336 // Char '>' '<' '|' '$' and ';' are special chars for shells.
1337 // Char '/' and '\' are file delimiters.
1338 // Chars '--' can be used into filename to inject special paramaters like --use-compress-program to make command with file as parameter making remote execution of command
1339 $filesystem_forbidden_chars = array('<', '>', '/', '\\', '?', '*', '|', '"', ':', '°', '$', ';', '`');
1340 $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
1341 $tmp = preg_replace('/\-\-+/', '_', $tmp);
1342 $tmp = preg_replace('/\s+\-([^\s])/', ' _$1', $tmp);
1343 $tmp = preg_replace('/\s+\-$/', '', $tmp);
1344 $tmp = str_replace('..', '', $tmp);
1345 return $tmp;
1346}
1347
1359function dol_sanitizePathName($str, $newstr = '_', $unaccent = 1)
1360{
1361 // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
1362 // Char '>' '<' '|' '$' and ';' are special chars for shells.
1363 // Chars '--' can be used into filename to inject special paramaters like --use-compress-program to make command with file as parameter making remote execution of command
1364 $filesystem_forbidden_chars = array('<', '>', '?', '*', '|', '"', '°', '$', ';', '`');
1365 $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
1366 $tmp = preg_replace('/\-\-+/', '_', $tmp);
1367 $tmp = preg_replace('/\s+\-([^\s])/', ' _$1', $tmp);
1368 $tmp = preg_replace('/\s+\-$/', '', $tmp);
1369 $tmp = str_replace('..', '', $tmp);
1370 return $tmp;
1371}
1372
1380function dol_sanitizeUrl($stringtoclean, $type = 1)
1381{
1382 // 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)
1383 // We should use dol_string_nounprintableascii but function may not be yet loaded/available
1384 $stringtoclean = preg_replace('/[\x00-\x1F\x7F]/u', '', $stringtoclean); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
1385 // We clean html comments because some hacks try to obfuscate evil strings by inserting HTML comments. Example: on<!-- -->error=alert(1)
1386 $stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
1387
1388 $stringtoclean = str_replace('\\', '/', $stringtoclean);
1389 if ($type == 1) {
1390 // removing : should disable links to external url like http:aaa)
1391 // removing ';' should disable "named" html entities encode into an url (we should not have this into an url)
1392 $stringtoclean = str_replace(array(':', ';', '@'), '', $stringtoclean);
1393 }
1394
1395 do {
1396 $oldstringtoclean = $stringtoclean;
1397 // removing '&colon' should disable links to external url like http:aaa)
1398 // removing '&#' should disable "numeric" html entities encode into an url (we should not have this into an url)
1399 $stringtoclean = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $stringtoclean);
1400 } while ($oldstringtoclean != $stringtoclean);
1401
1402 if ($type == 1) {
1403 // removing '//' should disable links to external url like //aaa or http//)
1404 $stringtoclean = preg_replace(array('/^[a-z]*\/\/+/i'), '', $stringtoclean);
1405 }
1406
1407 return $stringtoclean;
1408}
1409
1416function dol_sanitizeEmail($stringtoclean)
1417{
1418 do {
1419 $oldstringtoclean = $stringtoclean;
1420 $stringtoclean = str_ireplace(array('"', ':', '[', ']',"\n", "\r", '\\', '\/'), '', $stringtoclean);
1421 } while ($oldstringtoclean != $stringtoclean);
1422
1423 return $stringtoclean;
1424}
1425
1435{
1436 global $conf;
1437
1438 if (is_null($str)) {
1439 return '';
1440 }
1441
1442 if (utf8_check($str)) {
1443 if (extension_loaded('intl') && !empty($conf->global->MAIN_UNACCENT_USE_TRANSLITERATOR)) {
1444 $transliterator = Transliterator::createFromRules(':: Any-Latin; :: Latin-ASCII; :: NFD; :: [:Nonspacing Mark:] Remove; :: NFC;', Transliterator::FORWARD);
1445 return $transliterator->transliterate($str);
1446 }
1447 // See http://www.utf8-chartable.de/
1448 $string = rawurlencode($str);
1449 $replacements = array(
1450 '%C3%80' => 'A', '%C3%81' => 'A', '%C3%82' => 'A', '%C3%83' => 'A', '%C3%84' => 'A', '%C3%85' => 'A',
1451 '%C3%87' => 'C',
1452 '%C3%88' => 'E', '%C3%89' => 'E', '%C3%8A' => 'E', '%C3%8B' => 'E',
1453 '%C3%8C' => 'I', '%C3%8D' => 'I', '%C3%8E' => 'I', '%C3%8F' => 'I',
1454 '%C3%91' => 'N',
1455 '%C3%92' => 'O', '%C3%93' => 'O', '%C3%94' => 'O', '%C3%95' => 'O', '%C3%96' => 'O',
1456 '%C5%A0' => 'S',
1457 '%C3%99' => 'U', '%C3%9A' => 'U', '%C3%9B' => 'U', '%C3%9C' => 'U',
1458 '%C3%9D' => 'Y', '%C5%B8' => 'y',
1459 '%C3%A0' => 'a', '%C3%A1' => 'a', '%C3%A2' => 'a', '%C3%A3' => 'a', '%C3%A4' => 'a', '%C3%A5' => 'a',
1460 '%C3%A7' => 'c',
1461 '%C3%A8' => 'e', '%C3%A9' => 'e', '%C3%AA' => 'e', '%C3%AB' => 'e',
1462 '%C3%AC' => 'i', '%C3%AD' => 'i', '%C3%AE' => 'i', '%C3%AF' => 'i',
1463 '%C3%B1' => 'n',
1464 '%C3%B2' => 'o', '%C3%B3' => 'o', '%C3%B4' => 'o', '%C3%B5' => 'o', '%C3%B6' => 'o',
1465 '%C5%A1' => 's',
1466 '%C3%B9' => 'u', '%C3%BA' => 'u', '%C3%BB' => 'u', '%C3%BC' => 'u',
1467 '%C3%BD' => 'y', '%C3%BF' => 'y'
1468 );
1469 $string = strtr($string, $replacements);
1470 return rawurldecode($string);
1471 } else {
1472 // See http://www.ascii-code.com/
1473 $string = strtr(
1474 $str,
1475 "\xC0\xC1\xC2\xC3\xC4\xC5\xC7
1476 \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
1477 \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
1478 \xE0\xE1\xE2\xE3\xE4\xE5\xE7\xE8\xE9\xEA\xEB
1479 \xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
1480 \xF9\xFA\xFB\xFC\xFD\xFF",
1481 "AAAAAAC
1482 EEEEIIIIDN
1483 OOOOOUUUY
1484 aaaaaaceeee
1485 iiiidnooooo
1486 uuuuyy"
1487 );
1488 $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"));
1489 return $string;
1490 }
1491}
1492
1506function dol_string_nospecial($str, $newstr = '_', $badcharstoreplace = '', $badcharstoremove = '', $keepspaces = 0)
1507{
1508 $forbidden_chars_to_replace = array("'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°', '$', ';'); // more complete than dol_sanitizeFileName
1509 if (empty($keepspaces)) {
1510 $forbidden_chars_to_replace[] = " ";
1511 }
1512 $forbidden_chars_to_remove = array();
1513 //$forbidden_chars_to_remove=array("(",")");
1514
1515 if (is_array($badcharstoreplace)) {
1516 $forbidden_chars_to_replace = $badcharstoreplace;
1517 }
1518 if (is_array($badcharstoremove)) {
1519 $forbidden_chars_to_remove = $badcharstoremove;
1520 }
1521
1522 return str_replace($forbidden_chars_to_replace, $newstr, str_replace($forbidden_chars_to_remove, "", $str));
1523}
1524
1525
1539function dol_string_nounprintableascii($str, $removetabcrlf = 1)
1540{
1541 if ($removetabcrlf) {
1542 return preg_replace('/[\x00-\x1F\x7F]/u', '', $str); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
1543 } else {
1544 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
1545 }
1546}
1547
1556function dol_escape_js($stringtoescape, $mode = 0, $noescapebackslashn = 0)
1557{
1558 if (is_null($stringtoescape)) {
1559 return '';
1560 }
1561
1562 // escape quotes and backslashes, newlines, etc.
1563 $substitjs = array("&#039;"=>"\\'", "\r"=>'\\r');
1564 //$substitjs['</']='<\/'; // We removed this. Should be useless.
1565 if (empty($noescapebackslashn)) {
1566 $substitjs["\n"] = '\\n';
1567 $substitjs['\\'] = '\\\\';
1568 }
1569 if (empty($mode)) {
1570 $substitjs["'"] = "\\'";
1571 $substitjs['"'] = "\\'";
1572 } elseif ($mode == 1) {
1573 $substitjs["'"] = "\\'";
1574 } elseif ($mode == 2) {
1575 $substitjs['"'] = '\\"';
1576 } elseif ($mode == 3) {
1577 $substitjs["'"] = "\\'";
1578 $substitjs['"'] = "\\\"";
1579 }
1580 return strtr($stringtoescape, $substitjs);
1581}
1582
1589function dol_escape_json($stringtoescape)
1590{
1591 return str_replace('"', '\"', $stringtoescape);
1592}
1593
1601function dolPrintLabel($s)
1602{
1604}
1605
1613function dolPrintHTML($s)
1614{
1615 return dol_escape_htmltag(dol_htmlwithnojs(dol_string_onlythesehtmltags(dol_htmlentitiesbr($s), 1, 1, 1)), 1, 1, 'common', 0, 1);
1616}
1617
1626{
1628}
1629
1630
1647function dol_escape_htmltag($stringtoescape, $keepb = 0, $keepn = 0, $noescapetags = '', $escapeonlyhtmltags = 0, $cleanalsojavascript = 0)
1648{
1649 if ($noescapetags == 'common') {
1650 $noescapetags = 'html,body,a,b,em,hr,i,u,ul,li,br,div,img,font,p,span,strong,table,tr,td,th,tbody';
1651 }
1652 if ($cleanalsojavascript) {
1653 $stringtoescape = dol_string_onlythesehtmltags($stringtoescape, 0, 0, $cleanalsojavascript, 0, array(), 0);
1654 }
1655
1656 // escape quotes and backslashes, newlines, etc.
1657 if ($escapeonlyhtmltags) {
1658 $tmp = htmlspecialchars_decode((string) $stringtoescape, ENT_COMPAT);
1659 } else {
1660 $tmp = html_entity_decode((string) $stringtoescape, ENT_COMPAT, 'UTF-8');
1661 }
1662 if (!$keepb) {
1663 $tmp = strtr($tmp, array("<b>"=>'', '</b>'=>'', '<strong>'=>'', '</strong>'=>''));
1664 }
1665 if (!$keepn) {
1666 $tmp = strtr($tmp, array("\r"=>'\\r', "\n"=>'\\n'));
1667 }
1668
1669 if ($escapeonlyhtmltags) {
1670 return htmlspecialchars($tmp, ENT_COMPAT, 'UTF-8');
1671 } else {
1672 // Escape tags to keep
1673 // TODO Does not works yet when there is attributes into tag
1674 $tmparrayoftags = array();
1675 if ($noescapetags) {
1676 $tmparrayoftags = explode(',', $noescapetags);
1677 }
1678 if (count($tmparrayoftags)) {
1679 foreach ($tmparrayoftags as $tagtoreplace) {
1680 $tmp = str_ireplace('<'.$tagtoreplace.'>', '__BEGINTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
1681 $tmp = str_ireplace('</'.$tagtoreplace.'>', '__ENDTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
1682 $tmp = str_ireplace('<'.$tagtoreplace.' />', '__BEGINENDTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
1683 }
1684 }
1685
1686 $result = htmlentities($tmp, ENT_COMPAT, 'UTF-8');
1687
1688 if (count($tmparrayoftags)) {
1689 foreach ($tmparrayoftags as $tagtoreplace) {
1690 $result = str_ireplace('__BEGINTAGTOREPLACE'.$tagtoreplace.'__', '<'.$tagtoreplace.'>', $result);
1691 $result = str_ireplace('__ENDTAGTOREPLACE'.$tagtoreplace.'__', '</'.$tagtoreplace.'>', $result);
1692 $result = str_ireplace('__BEGINENDTAGTOREPLACE'.$tagtoreplace.'__', '<'.$tagtoreplace.' />', $result);
1693 }
1694 }
1695
1696 return $result;
1697 }
1698}
1699
1707function dol_strtolower($string, $encoding = "UTF-8")
1708{
1709 if (function_exists('mb_strtolower')) {
1710 return mb_strtolower($string, $encoding);
1711 } else {
1712 return strtolower($string);
1713 }
1714}
1715
1724function dol_strtoupper($string, $encoding = "UTF-8")
1725{
1726 if (function_exists('mb_strtoupper')) {
1727 return mb_strtoupper($string, $encoding);
1728 } else {
1729 return strtoupper($string);
1730 }
1731}
1732
1741function dol_ucfirst($string, $encoding = "UTF-8")
1742{
1743 if (function_exists('mb_substr')) {
1744 return mb_strtoupper(mb_substr($string, 0, 1, $encoding), $encoding).mb_substr($string, 1, null, $encoding);
1745 } else {
1746 return ucfirst($string);
1747 }
1748}
1749
1758function dol_ucwords($string, $encoding = "UTF-8")
1759{
1760 if (function_exists('mb_convert_case')) {
1761 return mb_convert_case($string, MB_CASE_TITLE, $encoding);
1762 } else {
1763 return ucwords($string);
1764 }
1765}
1766
1788function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename = '', $restricttologhandler = '', $logcontext = null)
1789{
1790 global $conf, $user, $debugbar;
1791
1792 // If syslog module enabled
1793 if (!isModEnabled('syslog')) {
1794 return;
1795 }
1796
1797 // Check if we are into execution of code of a website
1798 if (defined('USEEXTERNALSERVER') && !defined('USEDOLIBARRSERVER') && !defined('USEDOLIBARREDITOR')) {
1799 global $website, $websitekey;
1800 if (is_object($website) && !empty($website->ref)) {
1801 $suffixinfilename .= '_website_'.$website->ref;
1802 } elseif (!empty($websitekey)) {
1803 $suffixinfilename .= '_website_'.$websitekey;
1804 }
1805 }
1806
1807 // Check if we have a forced suffix
1808 if (defined('USESUFFIXINLOG')) {
1809 $suffixinfilename .= constant('USESUFFIXINLOG');
1810 }
1811
1812 if ($ident < 0) {
1813 foreach ($conf->loghandlers as $loghandlerinstance) {
1814 $loghandlerinstance->setIdent($ident);
1815 }
1816 }
1817
1818 if (!empty($message)) {
1819 // Test log level
1820 $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');
1821
1822 if (!array_key_exists($level, $logLevels)) {
1823 dol_syslog('Error Bad Log Level '.$level, LOG_ERR);
1824 $level = $logLevels[LOG_ERR];
1825 }
1826 if ($level > getDolGlobalInt('SYSLOG_LEVEL')) {
1827 return;
1828 }
1829
1830 if (empty($conf->global->MAIN_SHOW_PASSWORD_INTO_LOG)) {
1831 $message = preg_replace('/password=\'[^\']*\'/', 'password=\'hidden\'', $message); // protection to avoid to have value of password in log
1832 }
1833
1834 // If adding log inside HTML page is required
1835 if ((!empty($_REQUEST['logtohtml']) && !empty($conf->global->MAIN_ENABLE_LOG_TO_HTML))
1836 || (!empty($user->rights->debugbar->read) && is_object($debugbar))) {
1837 $conf->logbuffer[] = dol_print_date(time(), "%Y-%m-%d %H:%M:%S")." ".$logLevels[$level]." ".$message;
1838 }
1839
1840 //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output
1841 // If html log tag enabled and url parameter log defined, we show output log on HTML comments
1842 if (!empty($conf->global->MAIN_ENABLE_LOG_INLINE_HTML) && !empty($_GET["log"])) {
1843 print "\n\n<!-- Log start\n";
1844 print dol_escape_htmltag($message)."\n";
1845 print "Log end -->\n";
1846 }
1847
1848 $data = array(
1849 'message' => $message,
1850 'script' => (isset($_SERVER['PHP_SELF']) ? basename($_SERVER['PHP_SELF'], '.php') : false),
1851 'level' => $level,
1852 'user' => ((is_object($user) && $user->id) ? $user->login : false),
1853 'ip' => false
1854 );
1855
1856 $remoteip = getUserRemoteIP(); // Get ip when page run on a web server
1857 if (!empty($remoteip)) {
1858 $data['ip'] = $remoteip;
1859 // This is when server run behind a reverse proxy
1860 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != $remoteip) {
1861 $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'].' -> '.$data['ip'];
1862 } elseif (!empty($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP'] != $remoteip) {
1863 $data['ip'] = $_SERVER['HTTP_CLIENT_IP'].' -> '.$data['ip'];
1864 }
1865 } elseif (!empty($_SERVER['SERVER_ADDR'])) {
1866 // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
1867 $data['ip'] = $_SERVER['SERVER_ADDR'];
1868 } elseif (!empty($_SERVER['COMPUTERNAME'])) {
1869 // This is when PHP session is ran outside a web server, like from Windows command line (Not always defined, but useful if OS defined it).
1870 $data['ip'] = $_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME']) ? '' : '@'.$_SERVER['USERNAME']);
1871 } elseif (!empty($_SERVER['LOGNAME'])) {
1872 // This is when PHP session is ran outside a web server, like from Linux command line (Not always defined, but usefull if OS defined it).
1873 $data['ip'] = '???@'.$_SERVER['LOGNAME'];
1874 }
1875
1876 // Loop on each log handler and send output
1877 foreach ($conf->loghandlers as $loghandlerinstance) {
1878 if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler) {
1879 continue;
1880 }
1881 $loghandlerinstance->export($data, $suffixinfilename);
1882 }
1883 unset($data);
1884 }
1885
1886 if ($ident > 0) {
1887 foreach ($conf->loghandlers as $loghandlerinstance) {
1888 $loghandlerinstance->setIdent($ident);
1889 }
1890 }
1891}
1892
1909function dolButtonToOpenUrlInDialogPopup($name, $label, $buttonstring, $url, $disabled = '', $morecss = 'classlink button bordertransp', $jsonopen = '', $backtopagejsfields = '', $accesskey = '')
1910{
1911 global $conf;
1912
1913 if (strpos($url, '?') > 0) {
1914 $url .= '&dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup='.urlencode($name);
1915 } else {
1916 $url .= '?dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup='.urlencode($name);
1917 }
1918
1919 $out = '';
1920
1921 $backtopagejsfieldsid = ''; $backtopagejsfieldslabel = '';
1922 if ($backtopagejsfields) {
1923 $tmpbacktopagejsfields = explode(':', $backtopagejsfields);
1924 if (empty($tmpbacktopagejsfields[1])) { // If the part 'keyforpopupid:' is missing, we add $name for it.
1925 $backtopagejsfields = $name.":".$backtopagejsfields;
1926 $tmp2backtopagejsfields = explode(',', $tmpbacktopagejsfields[0]);
1927 } else {
1928 $tmp2backtopagejsfields = explode(',', $tmpbacktopagejsfields[1]);
1929 }
1930 $backtopagejsfieldsid = empty($tmp2backtopagejsfields[0]) ? '' : $tmp2backtopagejsfields[0];
1931 $backtopagejsfieldslabel = empty($tmp2backtopagejsfields[1]) ? '' : $tmp2backtopagejsfields[1];
1932 $url .= '&backtopagejsfields='.urlencode($backtopagejsfields);
1933 }
1934
1935 //print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("MediaFiles")).'" name="file_manager">';
1936 $out .= '<!-- a link for button to open url into a dialog popup with backtopagejsfields = '.$backtopagejsfields.' -->';
1937 $out .= '<a '.($accesskey ? ' accesskey="'.$accesskey.'"' : '').' class="cursorpointer reposition button_'.$name.($morecss ? ' '.$morecss : '').'"'.$disabled.' title="'.dol_escape_htmltag($label).'"';
1938 if (empty($conf->use_javascript_ajax)) {
1939 $out .= ' href="'.DOL_URL_ROOT.$url.'" target="_blank"';
1940 } elseif ($jsonopen) {
1941 $out .= ' href="#" onclick="'.$jsonopen.'"';
1942 } else {
1943 $out .= ' href="#"';
1944 }
1945 $out .= '>'.$buttonstring.'</a>';
1946
1947 if (!empty($conf->use_javascript_ajax)) {
1948 // Add code to open url using the popup. Add also hidden field to retreive the returned variables
1949 $out .= '<!-- code to open popup and variables to retreive returned variables -->';
1950 $out .= '<div id="idfordialog'.$name.'" class="hidden">div for dialog</div>';
1951 $out .= '<div id="varforreturndialogid'.$name.'" class="hidden">div for returned id</div>';
1952 $out .= '<div id="varforreturndialoglabel'.$name.'" class="hidden">div for returned label</div>';
1953 $out .= '<!-- Add js code to open dialog popup on dialog -->';
1954 $out .= '<script nonce="'.getNonce().'" type="text/javascript">
1955 jQuery(document).ready(function () {
1956 jQuery(".button_'.$name.'").click(function () {
1957 console.log(\'Open popup with jQuery(...).dialog() on URL '.dol_escape_js(DOL_URL_ROOT.$url).'\');
1958 var $tmpdialog = $(\'#idfordialog'.$name.'\');
1959 $tmpdialog.html(\'<iframe class="iframedialog" id="iframedialog'.$name.'" style="border: 0px;" src="'.DOL_URL_ROOT.$url.'" width="100%" height="98%"></iframe>\');
1960 $tmpdialog.dialog({
1961 autoOpen: false,
1962 modal: true,
1963 height: (window.innerHeight - 150),
1964 width: \'80%\',
1965 title: \''.dol_escape_js($label).'\',
1966 open: function (event, ui) {
1967 console.log("open popup name='.$name.', backtopagejsfields='.$backtopagejsfields.'");
1968 },
1969 close: function (event, ui) {
1970 var returnedid = jQuery("#varforreturndialogid'.$name.'").text();
1971 var returnedlabel = jQuery("#varforreturndialoglabel'.$name.'").text();
1972 console.log("popup has been closed. returnedid (js var defined into parent page)="+returnedid+" returnedlabel="+returnedlabel);
1973 if (returnedid != "" && returnedid != "div for returned id") {
1974 jQuery("#'.(empty($backtopagejsfieldsid)?"none":$backtopagejsfieldsid).'").val(returnedid);
1975 }
1976 if (returnedlabel != "" && returnedlabel != "div for returned label") {
1977 jQuery("#'.(empty($backtopagejsfieldslabel)?"none":$backtopagejsfieldslabel).'").val(returnedlabel);
1978 }
1979 }
1980 });
1981
1982 $tmpdialog.dialog(\'open\');
1983 return false;
1984 });
1985 });
1986 </script>';
1987 }
1988 return $out;
1989}
1990
2007function dol_fiche_head($links = array(), $active = '0', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
2008{
2009 print dol_get_fiche_head($links, $active, $title, $notab, $picto, $pictoisfullpath, $morehtmlright, $morecss, $limittoshow, $moretabssuffix);
2010}
2011
2028function dol_get_fiche_head($links = array(), $active = '', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '', $dragdropfile = 0)
2029{
2030 global $conf, $langs, $hookmanager;
2031
2032 // Show title
2033 $showtitle = 1;
2034 if (!empty($conf->dol_optimize_smallscreen)) {
2035 $showtitle = 0;
2036 }
2037
2038 $out = "\n".'<!-- dol_fiche_head - dol_get_fiche_head -->';
2039
2040 if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
2041 $out .= '<div class="tabs'.($picto ? '' : ' nopaddingleft').'" data-role="controlgroup" data-type="horizontal">'."\n";
2042 }
2043
2044 // Show right part
2045 if ($morehtmlright) {
2046 $out .= '<div class="inline-block floatright tabsElem">'.$morehtmlright.'</div>'; // Output right area first so when space is missing, text is in front of tabs and not under.
2047 }
2048
2049 // Show title
2050 if (!empty($title) && $showtitle && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
2051 $limittitle = 30;
2052 $out .= '<a class="tabTitle">';
2053 if ($picto) {
2054 $noprefix = $pictoisfullpath;
2055 if (strpos($picto, 'fontawesome_') !== false) {
2056 $noprefix = 1;
2057 }
2058 $out .= img_picto($title, ($noprefix ? '' : 'object_').$picto, '', $pictoisfullpath, 0, 0, '', 'imgTabTitle').' ';
2059 }
2060 $out .= '<span class="tabTitleText">'.dol_escape_htmltag(dol_trunc($title, $limittitle)).'</span>';
2061 $out .= '</a>';
2062 }
2063
2064 // Show tabs
2065
2066 // Define max of key (max may be higher than sizeof because of hole due to module disabling some tabs).
2067 $maxkey = -1;
2068 if (is_array($links) && !empty($links)) {
2069 $keys = array_keys($links);
2070 if (count($keys)) {
2071 $maxkey = max($keys);
2072 }
2073 }
2074
2075 // Show tabs
2076 // if =0 we don't use the feature
2077 if (empty($limittoshow)) {
2078 $limittoshow = (empty($conf->global->MAIN_MAXTABS_IN_CARD) ? 99 : $conf->global->MAIN_MAXTABS_IN_CARD);
2079 }
2080 if (!empty($conf->dol_optimize_smallscreen)) {
2081 $limittoshow = 2;
2082 }
2083
2084 $displaytab = 0;
2085 $nbintab = 0;
2086 $popuptab = 0;
2087 $outmore = '';
2088 for ($i = 0; $i <= $maxkey; $i++) {
2089 if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
2090 // If active tab is already present
2091 if ($i >= $limittoshow) {
2092 $limittoshow--;
2093 }
2094 }
2095 }
2096
2097 for ($i = 0; $i <= $maxkey; $i++) {
2098 if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
2099 $isactive = true;
2100 } else {
2101 $isactive = false;
2102 }
2103
2104 if ($i < $limittoshow || $isactive) {
2105 // Output entry with a visible tab
2106 $out .= '<div class="inline-block tabsElem'.($isactive ? ' tabsElemActive' : '').((!$isactive && !empty($conf->global->MAIN_HIDE_INACTIVETAB_ON_PRINT)) ? ' hideonprint' : '').'"><!-- id tab = '.(empty($links[$i][2]) ? '' : dol_escape_htmltag($links[$i][2])).' -->';
2107
2108 if (isset($links[$i][2]) && $links[$i][2] == 'image') {
2109 if (!empty($links[$i][0])) {
2110 $out .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
2111 } else {
2112 $out .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
2113 }
2114 } elseif (!empty($links[$i][1])) {
2115 //print "x $i $active ".$links[$i][2]." z";
2116 $out .= '<div class="tab tab'.($isactive?'active':'unactive').'" style="margin: 0 !important">';
2117 if (!empty($links[$i][0])) {
2118 $titletoshow = preg_replace('/<.*$/', '', $links[$i][1]);
2119 $out .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="tab inline-block valignmiddle'.($morecss ? ' '.$morecss : '').(!empty($links[$i][5]) ? ' '.$links[$i][5] : '').'" href="'.$links[$i][0].'" title="'.dol_escape_htmltag($titletoshow).'">';
2120 }
2121 $out .= $links[$i][1];
2122 if (!empty($links[$i][0])) {
2123 $out .= '</a>'."\n";
2124 }
2125 $out .= empty($links[$i][4]) ? '' : $links[$i][4];
2126 $out .= '</div>';
2127 }
2128
2129 $out .= '</div>';
2130 } else {
2131 // Add entry into the combo popup with the other tabs
2132 if (!$popuptab) {
2133 $popuptab = 1;
2134 $outmore .= '<div class="popuptabset wordwrap">'; // The css used to hide/show popup
2135 }
2136 $outmore .= '<div class="popuptab wordwrap" style="display:inherit;">';
2137 if (isset($links[$i][2]) && $links[$i][2] == 'image') {
2138 if (!empty($links[$i][0])) {
2139 $outmore .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
2140 } else {
2141 $outmore .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
2142 }
2143 } elseif (!empty($links[$i][1])) {
2144 $outmore .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="wordwrap inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
2145 $outmore .= preg_replace('/([a-z])\|([a-z])/i', '\\1 | \\2', $links[$i][1]); // Replace x|y with x | y to allow wrap on long composed texts.
2146 $outmore .= '</a>'."\n";
2147 }
2148 $outmore .= '</div>';
2149
2150 $nbintab++;
2151 }
2152 $displaytab = $i;
2153 }
2154 if ($popuptab) {
2155 $outmore .= '</div>';
2156 }
2157
2158 if ($popuptab) { // If there is some tabs not shown
2159 $left = ($langs->trans("DIRECTION") == 'rtl' ? 'right' : 'left');
2160 $right = ($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right');
2161 $widthofpopup = 200;
2162
2163 $tabsname = $moretabssuffix;
2164 if (empty($tabsname)) {
2165 $tabsname = str_replace("@", "", $picto);
2166 }
2167 $out .= '<div id="moretabs'.$tabsname.'" class="inline-block tabsElem valignmiddle">';
2168 $out .= '<div class="tab"><a href="#" class="tab moretab inline-block tabunactive"><span class="hideonsmartphone">'.$langs->trans("More").'</span>... ('.$nbintab.')</a></div>'; // Do not use "reposition" class in the "More".
2169 $out .= '<div id="moretabsList'.$tabsname.'" style="width: '.$widthofpopup.'px; position: absolute; '.$left.': -999em; text-align: '.$left.'; margin:0px; padding:2px; z-index:10;">';
2170 $out .= $outmore;
2171 $out .= '</div>';
2172 $out .= '<div></div>';
2173 $out .= "</div>\n";
2174
2175 $out .= '<script nonce="'.getNonce().'">';
2176 $out .= "$('#moretabs".$tabsname."').mouseenter( function() {
2177 var x = this.offsetLeft, y = this.offsetTop;
2178 console.log('mouseenter ".$left." x='+x+' y='+y+' window.innerWidth='+window.innerWidth);
2179 if ((window.innerWidth - x) < ".($widthofpopup + 10).") {
2180 $('#moretabsList".$tabsname."').css('".$right."','8px');
2181 }
2182 $('#moretabsList".$tabsname."').css('".$left."','auto');
2183 });
2184 ";
2185 $out .= "$('#moretabs".$tabsname."').mouseleave( function() { console.log('mouseleave ".$left."'); $('#moretabsList".$tabsname."').css('".$left."','-999em');});";
2186 $out .= "</script>";
2187 }
2188
2189 if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
2190 $out .= "</div>\n";
2191 }
2192
2193 if (!$notab || $notab == -1 || $notab == -2 || $notab == -3) {
2194 $out .= "\n".'<div id="dragDropAreaTabBar" class="tabBar'.($notab == -1 ? '' : ($notab == -2 ? ' tabBarNoTop' : (($notab == -3 ? ' noborderbottom' : '').' tabBarWithBottom'))).'">'."\n";
2195 }
2196 if (!empty($dragdropfile)) {
2197 $out .= dragAndDropFileUpload("dragDropAreaTabBar");
2198 }
2199 $parameters = array('tabname' => $active, 'out' => $out);
2200 $reshook = $hookmanager->executeHooks('printTabsHead', $parameters); // This hook usage is called just before output the head of tabs. Take also a look at "completeTabsHead"
2201 if ($reshook > 0) {
2202 $out = $hookmanager->resPrint;
2203 }
2204
2205 return $out;
2206}
2207
2215function dol_fiche_end($notab = 0)
2216{
2217 print dol_get_fiche_end($notab);
2218}
2219
2226function dol_get_fiche_end($notab = 0)
2227{
2228 if (!$notab || $notab == -1) {
2229 return "\n</div>\n";
2230 } else {
2231 return '';
2232 }
2233}
2234
2254function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $onlybanner = 0, $morehtmlright = '')
2255{
2256 global $conf, $form, $user, $langs, $hookmanager, $action;
2257
2258 $error = 0;
2259
2260 $maxvisiblephotos = 1;
2261 $showimage = 1;
2262 $entity = (empty($object->entity) ? $conf->entity : $object->entity);
2263 $showbarcode = empty($conf->barcode->enabled) ? 0 : (empty($object->barcode) ? 0 : 1);
2264 if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) {
2265 $showbarcode = 0;
2266 }
2267 $modulepart = 'unknown';
2268
2269 if ($object->element == 'societe' || $object->element == 'contact' || $object->element == 'product' || $object->element == 'ticket') {
2270 $modulepart = $object->element;
2271 } elseif ($object->element == 'member') {
2272 $modulepart = 'memberphoto';
2273 } elseif ($object->element == 'user') {
2274 $modulepart = 'userphoto';
2275 }
2276
2277 if (class_exists("Imagick")) {
2278 if ($object->element == 'expensereport' || $object->element == 'propal' || $object->element == 'commande' || $object->element == 'facture' || $object->element == 'supplier_proposal') {
2279 $modulepart = $object->element;
2280 } elseif ($object->element == 'fichinter') {
2281 $modulepart = 'ficheinter';
2282 } elseif ($object->element == 'contrat') {
2283 $modulepart = 'contract';
2284 } elseif ($object->element == 'order_supplier') {
2285 $modulepart = 'supplier_order';
2286 } elseif ($object->element == 'invoice_supplier') {
2287 $modulepart = 'supplier_invoice';
2288 }
2289 }
2290
2291 if ($object->element == 'product') {
2292 $width = 80;
2293 $cssclass = 'photowithmargin photoref';
2294 $showimage = $object->is_photo_available($conf->product->multidir_output[$entity]);
2295 $maxvisiblephotos = (isset($conf->global->PRODUCT_MAX_VISIBLE_PHOTO) ? $conf->global->PRODUCT_MAX_VISIBLE_PHOTO : 5);
2296 if ($conf->browser->layout == 'phone') {
2297 $maxvisiblephotos = 1;
2298 }
2299 if ($showimage) {
2300 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$object->show_photos('product', $conf->product->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, 0, $width, 0, '').'</div>';
2301 } else {
2302 if (!empty($conf->global->PRODUCT_NODISPLAYIFNOPHOTO)) {
2303 $nophoto = '';
2304 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
2305 } else { // Show no photo link
2306 $nophoto = '/public/theme/common/nophoto.png';
2307 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" title="'.dol_escape_htmltag($langs->trans("UploadAnImageToSeeAPhotoHere", $langs->transnoentitiesnoconv("Documents"))).'" alt="No photo"'.($width ? ' style="width: '.$width.'px"' : '').' src="'.DOL_URL_ROOT.$nophoto.'"></div>';
2308 }
2309 }
2310 } elseif ($object->element == 'ticket') {
2311 $width = 80;
2312 $cssclass = 'photoref';
2313 $showimage = $object->is_photo_available($conf->ticket->multidir_output[$entity].'/'.$object->ref);
2314 $maxvisiblephotos = (isset($conf->global->TICKET_MAX_VISIBLE_PHOTO) ? $conf->global->TICKET_MAX_VISIBLE_PHOTO : 2);
2315 if ($conf->browser->layout == 'phone') {
2316 $maxvisiblephotos = 1;
2317 }
2318
2319 if ($showimage) {
2320 $showphoto = $object->show_photos('ticket', $conf->ticket->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0);
2321 if ($object->nbphoto > 0) {
2322 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$showphoto.'</div>';
2323 } else {
2324 $showimage = 0;
2325 }
2326 }
2327 if (!$showimage) {
2328 if (!empty($conf->global->TICKET_NODISPLAYIFNOPHOTO)) {
2329 $nophoto = '';
2330 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
2331 } else { // Show no photo link
2332 $nophoto = img_picto('No photo', 'object_ticket');
2333 $morehtmlleft .= '<!-- No photo to show -->';
2334 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
2335 $morehtmlleft .= $nophoto;
2336 $morehtmlleft .= '</div></div>';
2337 }
2338 }
2339 } else {
2340 if ($showimage) {
2341 if ($modulepart != 'unknown') {
2342 $phototoshow = '';
2343 // Check if a preview file is available
2344 if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice', 'expensereport')) && class_exists("Imagick")) {
2345 $objectref = dol_sanitizeFileName($object->ref);
2346 $dir_output = (empty($conf->$modulepart->multidir_output[$entity]) ? $conf->$modulepart->dir_output : $conf->$modulepart->multidir_output[$entity])."/";
2347 if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice'))) {
2348 $subdir = get_exdir($object->id, 2, 0, 1, $object, $modulepart);
2349 $subdir .= ((!empty($subdir) && !preg_match('/\/$/', $subdir)) ? '/' : '').$objectref; // the objectref dir is not included into get_exdir when used with level=2, so we add it at end
2350 } else {
2351 $subdir = get_exdir($object->id, 0, 0, 1, $object, $modulepart);
2352 }
2353 if (empty($subdir)) {
2354 $subdir = 'errorgettingsubdirofobject'; // Protection to avoid to return empty path
2355 }
2356
2357 $filepath = $dir_output.$subdir."/";
2358
2359 $filepdf = $filepath.$objectref.".pdf";
2360 $relativepath = $subdir.'/'.$objectref.'.pdf';
2361
2362 // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png")
2363 $fileimage = $filepdf.'_preview.png';
2364 $relativepathimage = $relativepath.'_preview.png';
2365
2366 $pdfexists = file_exists($filepdf);
2367
2368 // If PDF file exists
2369 if ($pdfexists) {
2370 // Conversion du PDF en image png si fichier png non existant
2371 if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf))) {
2372 if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) { // If you experience trouble with pdf thumb generation and imagick, you can disable here.
2373 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2374 $ret = dol_convert_file($filepdf, 'png', $fileimage, '0'); // Convert first page of PDF into a file _preview.png
2375 if ($ret < 0) {
2376 $error++;
2377 }
2378 }
2379 }
2380 }
2381
2382 if ($pdfexists && !$error) {
2383 $heightforphotref = 80;
2384 if (!empty($conf->dol_optimize_smallscreen)) {
2385 $heightforphotref = 60;
2386 }
2387 // If the preview file is found
2388 if (file_exists($fileimage)) {
2389 $phototoshow = '<div class="photoref">';
2390 $phototoshow .= '<img height="'.$heightforphotref.'" class="photo photowithborder" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($relativepathimage).'">';
2391 $phototoshow .= '</div>';
2392 }
2393 }
2394 } elseif (!$phototoshow) { // example if modulepart = 'societe' or 'photo'
2395 $phototoshow .= $form->showphoto($modulepart, $object, 0, 0, 0, 'photowithmargin photoref', 'small', 1, 0, $maxvisiblephotos);
2396 }
2397
2398 if ($phototoshow) {
2399 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">';
2400 $morehtmlleft .= $phototoshow;
2401 $morehtmlleft .= '</div>';
2402 }
2403 }
2404
2405 if (empty($phototoshow)) { // Show No photo link (picto of object)
2406 if ($object->element == 'action') {
2407 $width = 80;
2408 $cssclass = 'photorefcenter';
2409 $nophoto = img_picto('No photo', 'title_agenda');
2410 } else {
2411 $width = 14;
2412 $cssclass = 'photorefcenter';
2413 $picto = $object->picto;
2414 $prefix = 'object_';
2415 if ($object->element == 'project' && !$object->public) {
2416 $picto = 'project'; // instead of projectpub
2417 }
2418 if (strpos($picto, 'fontawesome_') !== false) {
2419 $prefix = '';
2420 }
2421 $nophoto = img_picto('No photo', $prefix.$picto);
2422 }
2423 $morehtmlleft .= '<!-- No photo to show -->';
2424 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
2425 $morehtmlleft .= $nophoto;
2426 $morehtmlleft .= '</div></div>';
2427 }
2428 }
2429 }
2430
2431 // Show barcode
2432 if ($showbarcode) {
2433 $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$form->showbarcode($object, 100, 'photoref valignmiddle').'</div>';
2434 }
2435
2436 if ($object->element == 'societe') {
2437 if (!empty($conf->use_javascript_ajax) && $user->hasRight('societe', 'creer') && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
2438 $morehtmlstatus .= ajax_object_onoff($object, 'status', 'status', 'InActivity', 'ActivityCeased');
2439 } else {
2440 $morehtmlstatus .= $object->getLibStatut(6);
2441 }
2442 } elseif ($object->element == 'product') {
2443 //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Sell").') ';
2444 if (!empty($conf->use_javascript_ajax) && $user->hasRight('produit', 'creer') && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
2445 $morehtmlstatus .= ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell');
2446 } else {
2447 $morehtmlstatus .= '<span class="statusrefsell">'.$object->getLibStatut(6, 0).'</span>';
2448 }
2449 $morehtmlstatus .= ' &nbsp; ';
2450 //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Buy").') ';
2451 if (!empty($conf->use_javascript_ajax) && $user->hasRight('produit', 'creer') && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
2452 $morehtmlstatus .= ajax_object_onoff($object, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy');
2453 } else {
2454 $morehtmlstatus .= '<span class="statusrefbuy">'.$object->getLibStatut(6, 1).'</span>';
2455 }
2456 } elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier'))) {
2457 $totalallpayments = $object->getSommePaiement(0);
2458 $totalallpayments += $object->getSumCreditNotesUsed(0);
2459 $totalallpayments += $object->getSumDepositsUsed(0);
2460 $tmptxt = $object->getLibStatut(6, $totalallpayments);
2461 if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
2462 $tmptxt = $object->getLibStatut(5, $totalallpayments);
2463 }
2464 $morehtmlstatus .= $tmptxt;
2465 } elseif (in_array($object->element, array('chargesociales', 'loan', 'tva'))) {
2466 $tmptxt = $object->getLibStatut(6, $object->totalpaid);
2467 if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
2468 $tmptxt = $object->getLibStatut(5, $object->totalpaid);
2469 }
2470 $morehtmlstatus .= $tmptxt;
2471 } elseif ($object->element == 'contrat' || $object->element == 'contract') {
2472 if ($object->statut == 0) {
2473 $morehtmlstatus .= $object->getLibStatut(5);
2474 } else {
2475 $morehtmlstatus .= $object->getLibStatut(4);
2476 }
2477 } elseif ($object->element == 'facturerec') {
2478 if ($object->frequency == 0) {
2479 $morehtmlstatus .= $object->getLibStatut(2);
2480 } else {
2481 $morehtmlstatus .= $object->getLibStatut(5);
2482 }
2483 } elseif ($object->element == 'project_task') {
2484 $object->fk_statut = 1;
2485 if ($object->progress > 0) {
2486 $object->fk_statut = 2;
2487 }
2488 if ($object->progress >= 100) {
2489 $object->fk_statut = 3;
2490 }
2491 $tmptxt = $object->getLibStatut(5);
2492 $morehtmlstatus .= $tmptxt; // No status on task
2493 } elseif (method_exists($object, 'getLibStatut')) { // Generic case for status
2494 $tmptxt = $object->getLibStatut(6);
2495 if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
2496 $tmptxt = $object->getLibStatut(5);
2497 }
2498 $morehtmlstatus .= $tmptxt;
2499 }
2500
2501 // Add if object was dispatched "into accountancy"
2502 if (isModEnabled('accounting') && in_array($object->element, array('bank', 'paiementcharge', 'facture', 'invoice', 'invoice_supplier', 'expensereport', 'payment_various'))) {
2503 // Note: For 'chargesociales', 'salaries'... this is the payments that are dispatched (so element = 'bank')
2504 if (method_exists($object, 'getVentilExportCompta')) {
2505 $accounted = $object->getVentilExportCompta();
2506 $langs->load("accountancy");
2507 $morehtmlstatus .= '</div><div class="statusref statusrefbis"><span class="opacitymedium">'.($accounted > 0 ? $langs->trans("Accounted") : $langs->trans("NotYetAccounted")).'</span>';
2508 }
2509 }
2510
2511 // Add alias for thirdparty
2512 if (!empty($object->name_alias)) {
2513 $morehtmlref .= '<div class="refidno opacitymedium">'.dol_escape_htmltag($object->name_alias).'</div>';
2514 }
2515
2516 // Add label
2517 if (in_array($object->element, array('product', 'bank_account', 'project_task'))) {
2518 if (!empty($object->label)) {
2519 $morehtmlref .= '<div class="refidno opacitymedium">'.$object->label.'</div>';
2520 }
2521 }
2522
2523 // Show address and email
2524 if (method_exists($object, 'getBannerAddress') && !in_array($object->element, array('product', 'bookmark', 'ecm_directories', 'ecm_files'))) {
2525 $moreaddress = $object->getBannerAddress('refaddress', $object);
2526 if ($moreaddress) {
2527 $morehtmlref .= '<div class="refidno refaddress">';
2528 $morehtmlref .= $moreaddress;
2529 $morehtmlref .= '</div>';
2530 }
2531 }
2532 if (!empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && ($conf->global->MAIN_SHOW_TECHNICAL_ID == '1' || preg_match('/'.preg_quote($object->element, '/').'/i', $conf->global->MAIN_SHOW_TECHNICAL_ID)) && !empty($object->id)) {
2533 $morehtmlref .= '<div style="clear: both;"></div>';
2534 $morehtmlref .= '<div class="refidno opacitymedium">';
2535 $morehtmlref .= $langs->trans("TechnicalID").': '.((int) $object->id);
2536 $morehtmlref .= '</div>';
2537 }
2538
2539 $parameters=array('morehtmlref'=>$morehtmlref);
2540 $reshook = $hookmanager->executeHooks('formDolBanner', $parameters, $object, $action);
2541 if ($reshook < 0) {
2542 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
2543 } elseif (empty($reshook)) {
2544 $morehtmlref .= $hookmanager->resPrint;
2545 } elseif ($reshook > 0) {
2546 $morehtmlref = $hookmanager->resPrint;
2547 }
2548
2549
2550 print '<div class="'.($onlybanner ? 'arearefnobottom ' : 'arearef ').'heightref valignmiddle centpercent">';
2551 print $form->showrefnav($object, $paramid, $morehtml, $shownav, $fieldid, $fieldref, $morehtmlref, $moreparam, $nodbprefix, $morehtmlleft, $morehtmlstatus, $morehtmlright);
2552 print '</div>';
2553 print '<div class="underrefbanner clearboth"></div>';
2554}
2555
2565function fieldLabel($langkey, $fieldkey, $fieldrequired = 0)
2566{
2567 global $langs;
2568 $ret = '';
2569 if ($fieldrequired) {
2570 $ret .= '<span class="fieldrequired">';
2571 }
2572 $ret .= '<label for="'.$fieldkey.'">';
2573 $ret .= $langs->trans($langkey);
2574 $ret .= '</label>';
2575 if ($fieldrequired) {
2576 $ret .= '</span>';
2577 }
2578 return $ret;
2579}
2580
2588function dol_bc($var, $moreclass = '')
2589{
2590 global $bc;
2591 $ret = ' '.$bc[$var];
2592 if ($moreclass) {
2593 $ret = preg_replace('/class=\"/', 'class="'.$moreclass.' ', $ret);
2594 }
2595 return $ret;
2596}
2597
2611function dol_format_address($object, $withcountry = 0, $sep = "\n", $outputlangs = '', $mode = 0, $extralangcode = '')
2612{
2613 global $conf, $langs, $hookmanager;
2614
2615 $ret = '';
2616 $countriesusingstate = array('AU', 'CA', 'US', 'IN', 'GB', 'ES', 'UK', 'TR', 'CN'); // See also MAIN_FORCE_STATE_INTO_ADDRESS
2617
2618 // See format of addresses on https://en.wikipedia.org/wiki/Address
2619 // Address
2620 if (empty($mode)) {
2621 $ret .= ($extralangcode ? $object->array_languages['address'][$extralangcode] : (empty($object->address) ? '' : preg_replace('/(\r\n|\r|\n)+/', $sep, $object->address)));
2622 }
2623 // Zip/Town/State
2624 if (isset($object->country_code) && in_array($object->country_code, array('AU', 'CA', 'US', 'CN')) || !empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS)) {
2625 // US: title firstname name \n address lines \n town, state, zip \n country
2626 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
2627 $ret .= (($ret && $town) ? $sep : '').$town;
2628
2629 if (!empty($object->state)) {
2630 $ret .= ($ret ? ($town ? ", " : $sep) : '').$object->state;
2631 }
2632 if (!empty($object->zip)) {
2633 $ret .= ($ret ? (($town || $object->state) ? ", " : $sep) : '').$object->zip;
2634 }
2635 } elseif (isset($object->country_code) && in_array($object->country_code, array('GB', 'UK'))) {
2636 // UK: title firstname name \n address lines \n town state \n zip \n country
2637 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
2638 $ret .= ($ret ? $sep : '').$town;
2639 if (!empty($object->state)) {
2640 $ret .= ($ret ? ", " : '').$object->state;
2641 }
2642 if (!empty($object->zip)) {
2643 $ret .= ($ret ? $sep : '').$object->zip;
2644 }
2645 } elseif (isset($object->country_code) && in_array($object->country_code, array('ES', 'TR'))) {
2646 // ES: title firstname name \n address lines \n zip town \n state \n country
2647 $ret .= ($ret ? $sep : '').$object->zip;
2648 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
2649 $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
2650 if (!empty($object->state)) {
2651 $ret .= $sep.$object->state;
2652 }
2653 } elseif (isset($object->country_code) && in_array($object->country_code, array('JP'))) {
2654 // JP: In romaji, title firstname name\n address lines \n [state,] town zip \n country
2655 // See https://www.sljfaq.org/afaq/addresses.html
2656 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
2657 $ret .= ($ret ? $sep : '').($object->state ? $object->state.', ' : '').$town.($object->zip ? ' ' : '').$object->zip;
2658 } elseif (isset($object->country_code) && in_array($object->country_code, array('IT'))) {
2659 // IT: title firstname name\n address lines \n zip town state_code \n country
2660 $ret .= ($ret ? $sep : '').$object->zip;
2661 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
2662 $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
2663 $ret .= (empty($object->state_code) ? '' : (' '.$object->state_code));
2664 } else {
2665 // Other: title firstname name \n address lines \n zip town[, state] \n country
2666 $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
2667 $ret .= !empty($object->zip) ? (($ret ? $sep : '').$object->zip) : '';
2668 $ret .= ($town ? (($object->zip ? ' ' : ($ret ? $sep : '')).$town) : '');
2669 if (!empty($object->state) && in_array($object->country_code, $countriesusingstate)) {
2670 $ret .= ($ret ? ", " : '').$object->state;
2671 }
2672 }
2673
2674 if (!is_object($outputlangs)) {
2675 $outputlangs = $langs;
2676 }
2677 if ($withcountry) {
2678 $langs->load("dict");
2679 $ret .= (empty($object->country_code) ? '' : ($ret ? $sep : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$object->country_code)));
2680 }
2681 if ($hookmanager) {
2682 $parameters = array('withcountry' => $withcountry, 'sep' => $sep, 'outputlangs' => $outputlangs,'mode' => $mode, 'extralangcode' => $extralangcode);
2683 $reshook = $hookmanager->executeHooks('formatAddress', $parameters, $object);
2684 if ($reshook > 0) {
2685 $ret = '';
2686 }
2687 $ret .= $hookmanager->resPrint;
2688 }
2689
2690 return $ret;
2691}
2692
2693
2694
2703function dol_strftime($fmt, $ts = false, $is_gmt = false)
2704{
2705 if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
2706 return ($is_gmt) ? @gmstrftime($fmt, $ts) : @strftime($fmt, $ts);
2707 } else {
2708 return 'Error date into a not supported range';
2709 }
2710}
2711
2733function dol_print_date($time, $format = '', $tzoutput = 'auto', $outputlangs = '', $encodetooutput = false)
2734{
2735 global $conf, $langs;
2736
2737 // If date undefined or "", we return ""
2738 if (dol_strlen($time) == 0) {
2739 return ''; // $time=0 allowed (it means 01/01/1970 00:00:00)
2740 }
2741
2742 if ($tzoutput === 'auto') {
2743 $tzoutput = (empty($conf) ? 'tzserver' : (isset($conf->tzuserinputkey) ? $conf->tzuserinputkey : 'tzserver'));
2744 }
2745
2746 // Clean parameters
2747 $to_gmt = false;
2748 $offsettz = $offsetdst = 0;
2749 if ($tzoutput) {
2750 $to_gmt = true; // For backward compatibility
2751 if (is_string($tzoutput)) {
2752 if ($tzoutput == 'tzserver') {
2753 $to_gmt = false;
2754 $offsettzstring = @date_default_timezone_get(); // Example 'Europe/Berlin' or 'Indian/Reunion'
2755 $offsettz = 0; // Timezone offset with server timezone (because to_gmt is false), so 0
2756 $offsetdst = 0; // Dst offset with server timezone (because to_gmt is false), so 0
2757 } elseif ($tzoutput == 'tzuser' || $tzoutput == 'tzuserrel') {
2758 $to_gmt = true;
2759 $offsettzstring = (empty($_SESSION['dol_tz_string']) ? 'UTC' : $_SESSION['dol_tz_string']); // Example 'Europe/Berlin' or 'Indian/Reunion'
2760
2761 if (class_exists('DateTimeZone')) {
2762 $user_date_tz = new DateTimeZone($offsettzstring);
2763 $user_dt = new DateTime();
2764 $user_dt->setTimezone($user_date_tz);
2765 $user_dt->setTimestamp($tzoutput == 'tzuser' ? dol_now() : (int) $time);
2766 $offsettz = $user_dt->getOffset(); // should include dst ?
2767 } else { // with old method (The 'tzuser' was processed like the 'tzuserrel')
2768 $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60; // Will not be used anymore
2769 $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60; // Will not be used anymore
2770 }
2771 }
2772 }
2773 }
2774 if (!is_object($outputlangs)) {
2775 $outputlangs = $langs;
2776 }
2777 if (!$format) {
2778 $format = 'daytextshort';
2779 }
2780
2781 // Do we have to reduce the length of date (year on 2 chars) to save space.
2782 // Note: dayinputnoreduce is same than day but no reduction of year length will be done
2783 $reduceformat = (!empty($conf->dol_optimize_smallscreen) && in_array($format, array('day', 'dayhour'))) ? 1 : 0; // Test on original $format param.
2784 $format = preg_replace('/inputnoreduce/', '', $format); // so format 'dayinputnoreduce' is processed like day
2785 $formatwithoutreduce = preg_replace('/reduceformat/', '', $format);
2786 if ($formatwithoutreduce != $format) {
2787 $format = $formatwithoutreduce;
2788 $reduceformat = 1;
2789 } // so format 'dayreduceformat' is processed like day
2790
2791 // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
2792 // TODO Add format daysmallyear and dayhoursmallyear
2793 if ($format == 'day') {
2794 $format = ($outputlangs->trans("FormatDateShort") != "FormatDateShort" ? $outputlangs->trans("FormatDateShort") : $conf->format_date_short);
2795 } elseif ($format == 'hour') {
2796 $format = ($outputlangs->trans("FormatHourShort") != "FormatHourShort" ? $outputlangs->trans("FormatHourShort") : $conf->format_hour_short);
2797 } elseif ($format == 'hourduration') {
2798 $format = ($outputlangs->trans("FormatHourShortDuration") != "FormatHourShortDuration" ? $outputlangs->trans("FormatHourShortDuration") : $conf->format_hour_short_duration);
2799 } elseif ($format == 'daytext') {
2800 $format = ($outputlangs->trans("FormatDateText") != "FormatDateText" ? $outputlangs->trans("FormatDateText") : $conf->format_date_text);
2801 } elseif ($format == 'daytextshort') {
2802 $format = ($outputlangs->trans("FormatDateTextShort") != "FormatDateTextShort" ? $outputlangs->trans("FormatDateTextShort") : $conf->format_date_text_short);
2803 } elseif ($format == 'dayhour') {
2804 $format = ($outputlangs->trans("FormatDateHourShort") != "FormatDateHourShort" ? $outputlangs->trans("FormatDateHourShort") : $conf->format_date_hour_short);
2805 } elseif ($format == 'dayhoursec') {
2806 $format = ($outputlangs->trans("FormatDateHourSecShort") != "FormatDateHourSecShort" ? $outputlangs->trans("FormatDateHourSecShort") : $conf->format_date_hour_sec_short);
2807 } elseif ($format == 'dayhourtext') {
2808 $format = ($outputlangs->trans("FormatDateHourText") != "FormatDateHourText" ? $outputlangs->trans("FormatDateHourText") : $conf->format_date_hour_text);
2809 } elseif ($format == 'dayhourtextshort') {
2810 $format = ($outputlangs->trans("FormatDateHourTextShort") != "FormatDateHourTextShort" ? $outputlangs->trans("FormatDateHourTextShort") : $conf->format_date_hour_text_short);
2811 } elseif ($format == 'dayhourlog') {
2812 // Format not sensitive to language
2813 $format = '%Y%m%d%H%M%S';
2814 } elseif ($format == 'dayhourlogsmall') {
2815 // Format not sensitive to language
2816 $format = '%y%m%d%H%M';
2817 } elseif ($format == 'dayhourldap') {
2818 $format = '%Y%m%d%H%M%SZ';
2819 } elseif ($format == 'dayhourxcard') {
2820 $format = '%Y%m%dT%H%M%SZ';
2821 } elseif ($format == 'dayxcard') {
2822 $format = '%Y%m%d';
2823 } elseif ($format == 'dayrfc') {
2824 $format = '%Y-%m-%d'; // DATE_RFC3339
2825 } elseif ($format == 'dayhourrfc') {
2826 $format = '%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339
2827 } elseif ($format == 'standard') {
2828 $format = '%Y-%m-%d %H:%M:%S';
2829 }
2830
2831 if ($reduceformat) {
2832 $format = str_replace('%Y', '%y', $format);
2833 $format = str_replace('yyyy', 'yy', $format);
2834 }
2835
2836 // Clean format
2837 if (preg_match('/%b/i', $format)) { // There is some text to translate
2838 // We inhibate translation to text made by strftime functions. We will use trans instead later.
2839 $format = str_replace('%b', '__b__', $format);
2840 $format = str_replace('%B', '__B__', $format);
2841 }
2842 if (preg_match('/%a/i', $format)) { // There is some text to translate
2843 // We inhibate translation to text made by strftime functions. We will use trans instead later.
2844 $format = str_replace('%a', '__a__', $format);
2845 $format = str_replace('%A', '__A__', $format);
2846 }
2847
2848 // Analyze date
2849 $reg = array();
2850 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', $time, $reg)) { // Deprecated. Ex: 1970-01-01, 1970-01-01 01:00:00, 19700101010000
2851 dol_print_error('', "Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"]);
2852 return '';
2853 } elseif (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+) ?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i', $time, $reg)) { // Still available to solve problems in extrafields of type date
2854 // This part of code should not be used anymore.
2855 dol_syslog("Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"], LOG_WARNING);
2856 //if (function_exists('debug_print_backtrace')) debug_print_backtrace();
2857 // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
2858 $syear = (!empty($reg[1]) ? $reg[1] : '');
2859 $smonth = (!empty($reg[2]) ? $reg[2] : '');
2860 $sday = (!empty($reg[3]) ? $reg[3] : '');
2861 $shour = (!empty($reg[4]) ? $reg[4] : '');
2862 $smin = (!empty($reg[5]) ? $reg[5] : '');
2863 $ssec = (!empty($reg[6]) ? $reg[6] : '');
2864
2865 $time = dol_mktime($shour, $smin, $ssec, $smonth, $sday, $syear, true);
2866
2867 if ($to_gmt) {
2868 $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
2869 } else {
2870 $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
2871 }
2872 $dtts = new DateTime();
2873 $dtts->setTimestamp($time);
2874 $dtts->setTimezone($tzo);
2875 $newformat = str_replace(
2876 array('%Y', '%y', '%m', '%d', '%H', '%I', '%M', '%S', '%p', 'T', 'Z', '__a__', '__A__', '__b__', '__B__'),
2877 array('Y', 'y', 'm', 'd', 'H', 'h', 'i', 's', 'A', '__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
2878 $format);
2879 $ret = $dtts->format($newformat);
2880 $ret = str_replace(
2881 array('__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
2882 array('T', 'Z', '__a__', '__A__', '__b__', '__B__'),
2883 $ret
2884 );
2885 } else {
2886 // Date is a timestamps
2887 if ($time < 100000000000) { // Protection against bad date values
2888 $timetouse = $time + $offsettz + $offsetdst; // TODO We could be able to disable use of offsettz and offsetdst to use only offsettzstring.
2889
2890 if ($to_gmt) {
2891 $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
2892 } else {
2893 $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
2894 }
2895 $dtts = new DateTime();
2896 $dtts->setTimestamp($timetouse);
2897 $dtts->setTimezone($tzo);
2898 $newformat = str_replace(
2899 array('%Y', '%y', '%m', '%d', '%H', '%I', '%M', '%S', '%p', '%w', 'T', 'Z', '__a__', '__A__', '__b__', '__B__'),
2900 array('Y', 'y', 'm', 'd', 'H', 'h', 'i', 's', 'A', 'w', '__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
2901 $format);
2902 $ret = $dtts->format($newformat);
2903 $ret = str_replace(
2904 array('__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
2905 array('T', 'Z', '__a__', '__A__', '__b__', '__B__'),
2906 $ret
2907 );
2908 //var_dump($ret);exit;
2909 } else {
2910 $ret = 'Bad value '.$time.' for date';
2911 }
2912 }
2913
2914 if (preg_match('/__b__/i', $format)) {
2915 $timetouse = $time + $offsettz + $offsetdst; // TODO We could be able to disable use of offsettz and offsetdst to use only offsettzstring.
2916
2917 if ($to_gmt) {
2918 $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
2919 } else {
2920 $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
2921 }
2922 $dtts = new DateTime();
2923 $dtts->setTimestamp($timetouse);
2924 $dtts->setTimezone($tzo);
2925 $month = $dtts->format("m");
2926 $month = sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'.
2927 if ($encodetooutput) {
2928 $monthtext = $outputlangs->transnoentities('Month'.$month);
2929 $monthtextshort = $outputlangs->transnoentities('MonthShort'.$month);
2930 } else {
2931 $monthtext = $outputlangs->transnoentitiesnoconv('Month'.$month);
2932 $monthtextshort = $outputlangs->transnoentitiesnoconv('MonthShort'.$month);
2933 }
2934 //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
2935 $ret = str_replace('__b__', $monthtextshort, $ret);
2936 $ret = str_replace('__B__', $monthtext, $ret);
2937 //print 'x'.$outputlangs->charset_output.'-'.$ret.'x';
2938 //return $ret;
2939 }
2940 if (preg_match('/__a__/i', $format)) {
2941 //print "time=$time offsettz=$offsettz offsetdst=$offsetdst offsettzstring=$offsettzstring";
2942 $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
2943
2944 if ($to_gmt) {
2945 $tzo = new DateTimeZone('UTC');
2946 } else {
2947 $tzo = new DateTimeZone(date_default_timezone_get());
2948 }
2949 $dtts = new DateTime();
2950 $dtts->setTimestamp($timetouse);
2951 $dtts->setTimezone($tzo);
2952 $w = $dtts->format("w");
2953 $dayweek = $outputlangs->transnoentitiesnoconv('Day'.$w);
2954
2955 $ret = str_replace('__A__', $dayweek, $ret);
2956 $ret = str_replace('__a__', dol_substr($dayweek, 0, 3), $ret);
2957 }
2958
2959 return $ret;
2960}
2961
2962
2983function dol_getdate($timestamp, $fast = false, $forcetimezone = '')
2984{
2985 if ($timestamp === '') {
2986 return array();
2987 }
2988
2989 $datetimeobj = new DateTime();
2990 $datetimeobj->setTimestamp($timestamp); // Use local PHP server timezone
2991 if ($forcetimezone) {
2992 $datetimeobj->setTimezone(new DateTimeZone($forcetimezone == 'gmt' ? 'UTC' : $forcetimezone)); // (add timezone relative to the date entered)
2993 }
2994 $arrayinfo = array(
2995 'year'=>((int) date_format($datetimeobj, 'Y')),
2996 'mon'=>((int) date_format($datetimeobj, 'm')),
2997 'mday'=>((int) date_format($datetimeobj, 'd')),
2998 'wday'=>((int) date_format($datetimeobj, 'w')),
2999 'yday'=>((int) date_format($datetimeobj, 'z')),
3000 'hours'=>((int) date_format($datetimeobj, 'H')),
3001 'minutes'=>((int) date_format($datetimeobj, 'i')),
3002 'seconds'=>((int) date_format($datetimeobj, 's')),
3003 '0'=>$timestamp
3004 );
3005
3006 return $arrayinfo;
3007}
3008
3030function dol_mktime($hour, $minute, $second, $month, $day, $year, $gm = 'auto', $check = 1)
3031{
3032 global $conf;
3033 //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
3034
3035 if ($gm === 'auto') {
3036 $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
3037 }
3038 //print 'gm:'.$gm.' gm === auto:'.($gm === 'auto').'<br>';exit;
3039
3040 // Clean parameters
3041 if ($hour == -1 || empty($hour)) {
3042 $hour = 0;
3043 }
3044 if ($minute == -1 || empty($minute)) {
3045 $minute = 0;
3046 }
3047 if ($second == -1 || empty($second)) {
3048 $second = 0;
3049 }
3050
3051 // Check parameters
3052 if ($check) {
3053 if (!$month || !$day) {
3054 return '';
3055 }
3056 if ($day > 31) {
3057 return '';
3058 }
3059 if ($month > 12) {
3060 return '';
3061 }
3062 if ($hour < 0 || $hour > 24) {
3063 return '';
3064 }
3065 if ($minute < 0 || $minute > 60) {
3066 return '';
3067 }
3068 if ($second < 0 || $second > 60) {
3069 return '';
3070 }
3071 }
3072
3073 if (empty($gm) || ($gm === 'server' || $gm === 'tzserver')) {
3074 $default_timezone = @date_default_timezone_get(); // Example 'Europe/Berlin'
3075 $localtz = new DateTimeZone($default_timezone);
3076 } elseif ($gm === 'user' || $gm === 'tzuser' || $gm === 'tzuserrel') {
3077 // We use dol_tz_string first because it is more reliable.
3078 $default_timezone = (empty($_SESSION["dol_tz_string"]) ? @date_default_timezone_get() : $_SESSION["dol_tz_string"]); // Example 'Europe/Berlin'
3079 try {
3080 $localtz = new DateTimeZone($default_timezone);
3081 } catch (Exception $e) {
3082 dol_syslog("Warning dol_tz_string contains an invalid value ".$_SESSION["dol_tz_string"], LOG_WARNING);
3083 $default_timezone = @date_default_timezone_get();
3084 }
3085 } elseif (strrpos($gm, "tz,") !== false) {
3086 $timezone = str_replace("tz,", "", $gm); // Example 'tz,Europe/Berlin'
3087 try {
3088 $localtz = new DateTimeZone($timezone);
3089 } catch (Exception $e) {
3090 dol_syslog("Warning passed timezone contains an invalid value ".$timezone, LOG_WARNING);
3091 }
3092 }
3093
3094 if (empty($localtz)) {
3095 $localtz = new DateTimeZone('UTC');
3096 }
3097 //var_dump($localtz);
3098 //var_dump($year.'-'.$month.'-'.$day.'-'.$hour.'-'.$minute);
3099 $dt = new DateTime('now', $localtz);
3100 $dt->setDate((int) $year, (int) $month, (int) $day);
3101 $dt->setTime((int) $hour, (int) $minute, (int) $second);
3102 $date = $dt->getTimestamp(); // should include daylight saving time
3103 //var_dump($date);
3104 return $date;
3105}
3106
3107
3118function dol_now($mode = 'auto')
3119{
3120 $ret = 0;
3121
3122 if ($mode === 'auto') {
3123 $mode = 'gmt';
3124 }
3125
3126 if ($mode == 'gmt') {
3127 $ret = time(); // Time for now at greenwich.
3128 } elseif ($mode == 'tzserver') { // Time for now with PHP server timezone added
3129 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
3130 $tzsecond = getServerTimeZoneInt('now'); // Contains tz+dayling saving time
3131 $ret = (int) (dol_now('gmt') + ($tzsecond * 3600));
3132 //} elseif ($mode == 'tzref') {// Time for now with parent company timezone is added
3133 // require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
3134 // $tzsecond=getParentCompanyTimeZoneInt(); // Contains tz+dayling saving time
3135 // $ret=dol_now('gmt')+($tzsecond*3600);
3136 //}
3137 } elseif ($mode == 'tzuser' || $mode == 'tzuserrel') {
3138 // Time for now with user timezone added
3139 //print 'time: '.time();
3140 $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60;
3141 $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60;
3142 $ret = (int) (dol_now('gmt') + ($offsettz + $offsetdst));
3143 }
3144
3145 return $ret;
3146}
3147
3148
3157function dol_print_size($size, $shortvalue = 0, $shortunit = 0)
3158{
3159 global $conf, $langs;
3160 $level = 1024;
3161
3162 if (!empty($conf->dol_optimize_smallscreen)) {
3163 $shortunit = 1;
3164 }
3165
3166 // Set value text
3167 if (empty($shortvalue) || $size < ($level * 10)) {
3168 $ret = $size;
3169 $textunitshort = $langs->trans("b");
3170 $textunitlong = $langs->trans("Bytes");
3171 } else {
3172 $ret = round($size / $level, 0);
3173 $textunitshort = $langs->trans("Kb");
3174 $textunitlong = $langs->trans("KiloBytes");
3175 }
3176 // Use long or short text unit
3177 if (empty($shortunit)) {
3178 $ret .= ' '.$textunitlong;
3179 } else {
3180 $ret .= ' '.$textunitshort;
3181 }
3182
3183 return $ret;
3184}
3185
3196function dol_print_url($url, $target = '_blank', $max = 32, $withpicto = 0, $morecss = 'float')
3197{
3198 global $langs;
3199
3200 if (empty($url)) {
3201 return '';
3202 }
3203
3204 $link = '<a href="';
3205 if (!preg_match('/^http/i', $url)) {
3206 $link .= 'http://';
3207 }
3208 $link .= $url;
3209 $link .= '"';
3210 if ($target) {
3211 $link .= ' target="'.$target.'"';
3212 }
3213 $link .= '>';
3214 if (!preg_match('/^http/i', $url)) {
3215 $link .= 'http://';
3216 }
3217 $link .= dol_trunc($url, $max);
3218 $link .= '</a>';
3219
3220 if ($morecss == 'float') {
3221 return '<div class="nospan'.($morecss ? ' '.$morecss : '').'" style="margin-right: 10px">'.($withpicto ?img_picto($langs->trans("Url"), 'globe').' ' : '').$link.'</div>';
3222 } else {
3223 return '<span class="nospan'.($morecss ? ' '.$morecss : '').'" style="margin-right: 10px">'.($withpicto ?img_picto($langs->trans("Url"), 'globe').' ' : '').$link.'</span>';
3224 }
3225}
3226
3239function dol_print_email($email, $cid = 0, $socid = 0, $addlink = 0, $max = 64, $showinvalid = 1, $withpicto = 0)
3240{
3241 global $conf, $user, $langs, $hookmanager;
3242
3243 $newemail = dol_escape_htmltag($email);
3244
3245 if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpicto) {
3246 $withpicto = 0;
3247 }
3248
3249 if (empty($email)) {
3250 return '&nbsp;';
3251 }
3252
3253 if (!empty($addlink)) {
3254 $newemail = '<a style="text-overflow: ellipsis;" href="';
3255 if (!preg_match('/^mailto:/i', $email)) {
3256 $newemail .= 'mailto:';
3257 }
3258 $newemail .= $email;
3259 $newemail .= '">';
3260 $newemail .= dol_trunc($email, $max);
3261 $newemail .= '</a>';
3262 if ($showinvalid && !isValidEmail($email)) {
3263 $langs->load("errors");
3264 $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
3265 }
3266
3267 if (($cid || $socid) && isModEnabled('agenda') && $user->hasRight("agenda", "myactions", "create")) {
3268 $type = 'AC_EMAIL';
3269 $link = '';
3270 if (!empty($conf->global->AGENDA_ADDACTIONFOREMAIL)) {
3271 $link = '<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create&amp;backtopage=1&amp;actioncode='.$type.'&amp;contactid='.$cid.'&amp;socid='.$socid.'">'.img_object($langs->trans("AddAction"), "calendar").'</a>';
3272 }
3273 if ($link) {
3274 $newemail = '<div>'.$newemail.' '.$link.'</div>';
3275 }
3276 }
3277 } else {
3278 if ($showinvalid && !isValidEmail($email)) {
3279 $langs->load("errors");
3280 $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
3281 }
3282 }
3283
3284 //$rep = '<div class="nospan" style="margin-right: 10px">';
3285 $rep = ($withpicto ? img_picto($langs->trans("EMail").' : '.$email, (is_numeric($withpicto) ? 'email' : $withpicto)).' ' : '').$newemail;
3286 //$rep .= '</div>';
3287 if ($hookmanager) {
3288 $parameters = array('cid' => $cid, 'socid' => $socid, 'addlink' => $addlink, 'picto' => $withpicto);
3289
3290 $reshook = $hookmanager->executeHooks('printEmail', $parameters, $email);
3291 if ($reshook > 0) {
3292 $rep = '';
3293 }
3294 $rep .= $hookmanager->resPrint;
3295 }
3296
3297 return $rep;
3298}
3299
3306{
3307 global $conf, $db;
3308
3309 $socialnetworks = array();
3310 // Enable caching of array
3311 require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php';
3312 $cachekey = 'socialnetworks_' . $conf->entity;
3313 $dataretrieved = dol_getcache($cachekey);
3314 if (!is_null($dataretrieved)) {
3315 $socialnetworks = $dataretrieved;
3316 } else {
3317 $sql = "SELECT rowid, code, label, url, icon, active FROM ".MAIN_DB_PREFIX."c_socialnetworks";
3318 $sql .= " WHERE entity=".$conf->entity;
3319 $resql = $db->query($sql);
3320 if ($resql) {
3321 while ($obj = $db->fetch_object($resql)) {
3322 $socialnetworks[$obj->code] = array(
3323 'rowid' => $obj->rowid,
3324 'label' => $obj->label,
3325 'url' => $obj->url,
3326 'icon' => $obj->icon,
3327 'active' => $obj->active,
3328 );
3329 }
3330 }
3331 dol_setcache($cachekey, $socialnetworks); // If setting cache fails, this is not a problem, so we do not test result.
3332 }
3333
3334 return $socialnetworks;
3335}
3336
3347function dol_print_socialnetworks($value, $cid, $socid, $type, $dictsocialnetworks = array())
3348{
3349 global $conf, $user, $langs;
3350
3351 $htmllink = $value;
3352
3353 if (empty($value)) {
3354 return '&nbsp;';
3355 }
3356
3357 if (!empty($type)) {
3358 $htmllink = '<div class="divsocialnetwork inline-block valignmiddle">';
3359 // Use dictionary definition for picto $dictsocialnetworks[$type]['icon']
3360 $htmllink .= '<span class="fa pictofixedwidth '.($dictsocialnetworks[$type]['icon'] ? $dictsocialnetworks[$type]['icon'] : 'fa-link').'"></span>';
3361 if ($type == 'skype') {
3362 $htmllink .= dol_escape_htmltag($value);
3363 $htmllink .= '&nbsp; <a href="skype:';
3364 $htmllink .= dol_string_nospecial($value, '_', '', array('@'));
3365 $htmllink .= '?call" alt="'.$langs->trans("Call").'&nbsp;'.$value.'" title="'.dol_escape_htmltag($langs->trans("Call").' '.$value).'">';
3366 $htmllink .= '<img src="'.DOL_URL_ROOT.'/theme/common/skype_callbutton.png" border="0">';
3367 $htmllink .= '</a><a href="skype:';
3368 $htmllink .= dol_string_nospecial($value, '_', '', array('@'));
3369 $htmllink .= '?chat" alt="'.$langs->trans("Chat").'&nbsp;'.$value.'" title="'.dol_escape_htmltag($langs->trans("Chat").' '.$value).'">';
3370 $htmllink .= '<img class="paddingleft" src="'.DOL_URL_ROOT.'/theme/common/skype_chatbutton.png" border="0">';
3371 $htmllink .= '</a>';
3372 if (($cid || $socid) && isModEnabled('agenda') && $user->hasRight('agenda', 'myactions', 'create')) {
3373 $addlink = 'AC_SKYPE';
3374 $link = '';
3375 if (!empty($conf->global->AGENDA_ADDACTIONFORSKYPE)) {
3376 $link = '<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create&amp;backtopage=1&amp;actioncode='.$addlink.'&amp;contactid='.$cid.'&amp;socid='.$socid.'">'.img_object($langs->trans("AddAction"), "calendar").'</a>';
3377 }
3378 $htmllink .= ($link ? ' '.$link : '');
3379 }
3380 } else {
3381 if (!empty($dictsocialnetworks[$type]['url'])) {
3382 $tmpvirginurl = preg_replace('/\/?{socialid}/', '', $dictsocialnetworks[$type]['url']);
3383 if ($tmpvirginurl) {
3384 $value = preg_replace('/^www\.'.preg_quote($tmpvirginurl, '/').'\/?/', '', $value);
3385 $value = preg_replace('/^'.preg_quote($tmpvirginurl, '/').'\/?/', '', $value);
3386
3387 $tmpvirginurl3 = preg_replace('/^https:\/\//i', 'https://www.', $tmpvirginurl);
3388 if ($tmpvirginurl3) {
3389 $value = preg_replace('/^www\.'.preg_quote($tmpvirginurl3, '/').'\/?/', '', $value);
3390 $value = preg_replace('/^'.preg_quote($tmpvirginurl3, '/').'\/?/', '', $value);
3391 }
3392
3393 $tmpvirginurl2 = preg_replace('/^https?:\/\//i', '', $tmpvirginurl);
3394 if ($tmpvirginurl2) {
3395 $value = preg_replace('/^www\.'.preg_quote($tmpvirginurl2, '/').'\/?/', '', $value);
3396 $value = preg_replace('/^'.preg_quote($tmpvirginurl2, '/').'\/?/', '', $value);
3397 }
3398 }
3399 $link = str_replace('{socialid}', $value, $dictsocialnetworks[$type]['url']);
3400 if (preg_match('/^https?:\/\//i', $link)) {
3401 $htmllink .= '<a href="'.dol_sanitizeUrl($link, 0).'" target="_blank" rel="noopener noreferrer">'.dol_escape_htmltag($value).'</a>';
3402 } else {
3403 $htmllink .= '<a href="'.dol_sanitizeUrl($link, 1).'" target="_blank" rel="noopener noreferrer">'.dol_escape_htmltag($value).'</a>';
3404 }
3405 } else {
3406 $htmllink .= dol_escape_htmltag($value);
3407 }
3408 }
3409 $htmllink .= '</div>';
3410 } else {
3411 $langs->load("errors");
3412 $htmllink .= img_warning($langs->trans("ErrorBadSocialNetworkValue", $value));
3413 }
3414 return $htmllink;
3415}
3416
3427function dol_print_profids($profID, $profIDtype, $countrycode = '', $addcpButton = 1, $separ = '&nbsp;')
3428{
3429 global $mysoc;
3430
3431 if (empty($profID) || empty($profIDtype)) {
3432 return '';
3433 }
3434 if (empty($countrycode)) $countrycode = $mysoc->country_code;
3435 $newProfID = $profID;
3436 $id = substr($profIDtype, -1);
3437 $ret = '';
3438 if (strtoupper($countrycode) == 'FR') {
3439 // France
3440 if ($id == 1 && dol_strlen($newProfID) == 9) $newProfID = substr($newProfID, 0, 3).$separ.substr($newProfID, 3, 3).$separ.substr($newProfID, 6, 3);
3441 if ($id == 2 && dol_strlen($newProfID) == 14) $newProfID = substr($newProfID, 0, 3).$separ.substr($newProfID, 3, 3).$separ.substr($newProfID, 6, 3).$separ.substr($newProfID, 9, 5);
3442 if ($profIDtype === 'VAT' && dol_strlen($newProfID) == 13) $newProfID = substr($newProfID, 0, 4).$separ.substr($newProfID, 4, 3).$separ.substr($newProfID, 7, 3).$separ.substr($newProfID, 10, 3);
3443 }
3444 if (!empty($addcpButton)) $ret = showValueWithClipboardCPButton(dol_escape_htmltag($profID), ($addcpButton == 1 ? 1 : 0), $newProfID);
3445 else $ret = $newProfID;
3446 return $ret;
3447}
3448
3463function dol_print_phone($phone, $countrycode = '', $cid = 0, $socid = 0, $addlink = '', $separ = "&nbsp;", $withpicto = '', $titlealt = '', $adddivfloat = 0)
3464{
3465 global $conf, $user, $langs, $mysoc, $hookmanager;
3466
3467 // Clean phone parameter
3468 $phone = is_null($phone) ? '' : preg_replace("/[\s.-]/", "", trim($phone));
3469 if (empty($phone)) {
3470 return '';
3471 }
3472 if (!empty($conf->global->MAIN_PHONE_SEPAR)) {
3473 $separ = $conf->global->MAIN_PHONE_SEPAR;
3474 }
3475 if (empty($countrycode) && is_object($mysoc)) {
3476 $countrycode = $mysoc->country_code;
3477 }
3478
3479 // Short format for small screens
3480 if ($conf->dol_optimize_smallscreen) {
3481 $separ = '';
3482 }
3483
3484 $newphone = $phone;
3485 if (strtoupper($countrycode) == "FR") {
3486 // France
3487 if (dol_strlen($phone) == 10) {
3488 $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);
3489 } elseif (dol_strlen($phone) == 7) {
3490 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 2);
3491 } elseif (dol_strlen($phone) == 9) {
3492 $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 2).$separ.substr($newphone, 7, 2);
3493 } elseif (dol_strlen($phone) == 11) {
3494 $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);
3495 } elseif (dol_strlen($phone) == 12) {
3496 $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);
3497 } elseif (dol_strlen($phone) == 13) {
3498 $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);
3499 }
3500 } elseif (strtoupper($countrycode) == "CA") {
3501 if (dol_strlen($phone) == 10) {
3502 $newphone = ($separ != '' ? '(' : '').substr($newphone, 0, 3).($separ != '' ? ')' : '').$separ.substr($newphone, 3, 3).($separ != '' ? '-' : '').substr($newphone, 6, 4);
3503 }
3504 } elseif (strtoupper($countrycode) == "PT") {//Portugal
3505 if (dol_strlen($phone) == 13) {//ex: +351_ABC_DEF_GHI
3506 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
3507 }
3508 } elseif (strtoupper($countrycode) == "SR") {//Suriname
3509 if (dol_strlen($phone) == 10) {//ex: +597_ABC_DEF
3510 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3);
3511 } elseif (dol_strlen($phone) == 11) {//ex: +597_ABC_DEFG
3512 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 4);
3513 }
3514 } elseif (strtoupper($countrycode) == "DE") {//Allemagne
3515 if (dol_strlen($phone) == 14) {//ex: +49_ABCD_EFGH_IJK
3516 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 4).$separ.substr($newphone, 11, 3);
3517 } elseif (dol_strlen($phone) == 13) {//ex: +49_ABC_DEFG_HIJ
3518 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 4).$separ.substr($newphone, 10, 3);
3519 }
3520 } elseif (strtoupper($countrycode) == "ES") {//Espagne
3521 if (dol_strlen($phone) == 12) {//ex: +34_ABC_DEF_GHI
3522 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
3523 }
3524 } elseif (strtoupper($countrycode) == "BF") {// Burkina Faso
3525 if (dol_strlen($phone) == 12) {//ex : +22 A BC_DE_FG_HI
3526 $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);
3527 }
3528 } elseif (strtoupper($countrycode) == "RO") {// Roumanie
3529 if (dol_strlen($phone) == 12) {//ex : +40 AB_CDE_FG_HI
3530 $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);
3531 }
3532 } elseif (strtoupper($countrycode) == "TR") {//Turquie
3533 if (dol_strlen($phone) == 13) {//ex : +90 ABC_DEF_GHIJ
3534 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
3535 }
3536 } elseif (strtoupper($countrycode) == "US") {//Etat-Unis
3537 if (dol_strlen($phone) == 12) {//ex: +1 ABC_DEF_GHIJ
3538 $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
3539 }
3540 } elseif (strtoupper($countrycode) == "MX") {//Mexique
3541 if (dol_strlen($phone) == 12) {//ex: +52 ABCD_EFG_HI
3542 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
3543 } elseif (dol_strlen($phone) == 11) {//ex: +52 AB_CD_EF_GH
3544 $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);
3545 } elseif (dol_strlen($phone) == 13) {//ex: +52 ABC_DEF_GHIJ
3546 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
3547 }
3548 } elseif (strtoupper($countrycode) == "ML") {//Mali
3549 if (dol_strlen($phone) == 12) {//ex: +223 AB_CD_EF_GH
3550 $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);
3551 }
3552 } elseif (strtoupper($countrycode) == "TH") {//Thaïlande
3553 if (dol_strlen($phone) == 11) {//ex: +66_ABC_DE_FGH
3554 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
3555 } elseif (dol_strlen($phone) == 12) {//ex: +66_A_BCD_EF_GHI
3556 $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);
3557 }
3558 } elseif (strtoupper($countrycode) == "MU") {
3559 //Maurice
3560 if (dol_strlen($phone) == 11) {//ex: +230_ABC_DE_FG
3561 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2);
3562 } elseif (dol_strlen($phone) == 12) {//ex: +230_ABCD_EF_GH
3563 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
3564 }
3565 } elseif (strtoupper($countrycode) == "ZA") {//Afrique du sud
3566 if (dol_strlen($phone) == 12) {//ex: +27_AB_CDE_FG_HI
3567 $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);
3568 }
3569 } elseif (strtoupper($countrycode) == "SY") {//Syrie
3570 if (dol_strlen($phone) == 12) {//ex: +963_AB_CD_EF_GH
3571 $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);
3572 } elseif (dol_strlen($phone) == 13) {//ex: +963_AB_CD_EF_GHI
3573 $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);
3574 }
3575 } elseif (strtoupper($countrycode) == "AE") {//Emirats Arabes Unis
3576 if (dol_strlen($phone) == 12) {//ex: +971_ABC_DEF_GH
3577 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
3578 } elseif (dol_strlen($phone) == 13) {//ex: +971_ABC_DEF_GHI
3579 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
3580 } elseif (dol_strlen($phone) == 14) {//ex: +971_ABC_DEF_GHIK
3581 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 4);
3582 }
3583 } elseif (strtoupper($countrycode) == "DZ") {//Algérie
3584 if (dol_strlen($phone) == 13) {//ex: +213_ABC_DEF_GHI
3585 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
3586 }
3587 } elseif (strtoupper($countrycode) == "BE") {//Belgique
3588 if (dol_strlen($phone) == 11) {//ex: +32_ABC_DE_FGH
3589 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
3590 } elseif (dol_strlen($phone) == 12) {//ex: +32_ABC_DEF_GHI
3591 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
3592 }
3593 } elseif (strtoupper($countrycode) == "PF") {//Polynésie française
3594 if (dol_strlen($phone) == 12) {//ex: +689_AB_CD_EF_GH
3595 $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);
3596 }
3597 } elseif (strtoupper($countrycode) == "CO") {//Colombie
3598 if (dol_strlen($phone) == 13) {//ex: +57_ABC_DEF_GH_IJ
3599 $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);
3600 }
3601 } elseif (strtoupper($countrycode) == "JO") {//Jordanie
3602 if (dol_strlen($phone) == 12) {//ex: +962_A_BCD_EF_GH
3603 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 1).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2);
3604 }
3605 } elseif (strtoupper($countrycode) == "JM") {//Jamaïque
3606 if (dol_strlen($newphone) == 12) {//ex: +1867_ABC_DEFG
3607 $newphone = substr($newphone, 0, 5).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
3608 }
3609 } elseif (strtoupper($countrycode) == "MG") {//Madagascar
3610 if (dol_strlen($phone) == 13) {//ex: +261_AB_CD_EFG_HI
3611 $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);
3612 }
3613 } elseif (strtoupper($countrycode) == "GB") {//Royaume uni
3614 if (dol_strlen($phone) == 13) {//ex: +44_ABCD_EFG_HIJ
3615 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
3616 }
3617 } elseif (strtoupper($countrycode) == "CH") {//Suisse
3618 if (dol_strlen($phone) == 12) {//ex: +41_AB_CDE_FG_HI
3619 $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);
3620 } elseif (dol_strlen($phone) == 15) {// +41_AB_CDE_FGH_IJKL
3621 $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);
3622 }
3623 } elseif (strtoupper($countrycode) == "TN") {//Tunisie
3624 if (dol_strlen($phone) == 12) {//ex: +216_AB_CDE_FGH
3625 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
3626 }
3627 } elseif (strtoupper($countrycode) == "GF") {//Guyane francaise
3628 if (dol_strlen($phone) == 13) {//ex: +594_ABC_DE_FG_HI (ABC=594 de nouveau)
3629 $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);
3630 }
3631 } elseif (strtoupper($countrycode) == "GP") {//Guadeloupe
3632 if (dol_strlen($phone) == 13) {//ex: +590_ABC_DE_FG_HI (ABC=590 de nouveau)
3633 $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);
3634 }
3635 } elseif (strtoupper($countrycode) == "MQ") {//Martinique
3636 if (dol_strlen($phone) == 13) {//ex: +596_ABC_DE_FG_HI (ABC=596 de nouveau)
3637 $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);
3638 }
3639 } elseif (strtoupper($countrycode) == "IT") {//Italie
3640 if (dol_strlen($phone) == 12) {//ex: +39_ABC_DEF_GHI
3641 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
3642 } elseif (dol_strlen($phone) == 13) {//ex: +39_ABC_DEF_GH_IJ
3643 $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);
3644 }
3645 } elseif (strtoupper($countrycode) == "AU") {
3646 //Australie
3647 if (dol_strlen($phone) == 12) {
3648 //ex: +61_A_BCDE_FGHI
3649 $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 4);
3650 }
3651 } elseif (strtoupper($countrycode) == "LU") {
3652 // Luxembourg
3653 if (dol_strlen($phone) == 10) {// fixe 6 chiffres +352_AA_BB_CC
3654 $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2);
3655 } elseif (dol_strlen($phone) == 11) {// fixe 7 chiffres +352_AA_BB_CC_D
3656 $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);
3657 } elseif (dol_strlen($phone) == 12) {// fixe 8 chiffres +352_AA_BB_CC_DD
3658 $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);
3659 } elseif (dol_strlen($phone) == 13) {// mobile +352_AAA_BB_CC_DD
3660 $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);
3661 }
3662 }
3663 if (!empty($addlink)) { // Link on phone number (+ link to add action if conf->global->AGENDA_ADDACTIONFORPHONE set)
3664 if ($addlink == 'tel' || $conf->browser->layout == 'phone' || (isModEnabled('clicktodial') && !empty($conf->global->CLICKTODIAL_USE_TEL_LINK_ON_PHONE_NUMBERS))) { // If phone or option for, we use link of phone
3665 $newphoneform = $newphone;
3666 $newphone = '<a href="tel:'.$phone.'"';
3667 $newphone .= '>'.$newphoneform.'</a>';
3668 } elseif (isModEnabled('clicktodial') && $addlink == 'AC_TEL') { // If click to dial, we use click to dial url
3669 if (empty($user->clicktodial_loaded)) {
3670 $user->fetch_clicktodial();
3671 }
3672
3673 // Define urlmask
3674 $urlmask = 'ErrorClickToDialModuleNotConfigured';
3675 if (!empty($conf->global->CLICKTODIAL_URL)) {
3676 $urlmask = $conf->global->CLICKTODIAL_URL;
3677 }
3678 if (!empty($user->clicktodial_url)) {
3679 $urlmask = $user->clicktodial_url;
3680 }
3681
3682 $clicktodial_poste = (!empty($user->clicktodial_poste) ?urlencode($user->clicktodial_poste) : '');
3683 $clicktodial_login = (!empty($user->clicktodial_login) ?urlencode($user->clicktodial_login) : '');
3684 $clicktodial_password = (!empty($user->clicktodial_password) ?urlencode($user->clicktodial_password) : '');
3685 // This line is for backward compatibility
3686 $url = sprintf($urlmask, urlencode($phone), $clicktodial_poste, $clicktodial_login, $clicktodial_password);
3687 // Thoose lines are for substitution
3688 $substitarray = array('__PHONEFROM__'=>$clicktodial_poste,
3689 '__PHONETO__'=>urlencode($phone),
3690 '__LOGIN__'=>$clicktodial_login,
3691 '__PASS__'=>$clicktodial_password);
3692 $url = make_substitutions($url, $substitarray);
3693 $newphonesav = $newphone;
3694 if (empty($conf->global->CLICKTODIAL_DO_NOT_USE_AJAX_CALL)) {
3695 // Default and recommended: New method using ajax without submiting a page making a javascript history.go(-1) back
3696 $newphone = '<a href="'.$url.'" class="cssforclicktodial"'; // Call of ajax is handled by the lib_foot.js.php on class 'cssforclicktodial'
3697 $newphone .= '>'.$newphonesav.'</a>';
3698 } else {
3699 // Old method
3700 $newphone = '<a href="'.$url.'"';
3701 if (!empty($conf->global->CLICKTODIAL_FORCENEWTARGET)) {
3702 $newphone .= ' target="_blank" rel="noopener noreferrer"';
3703 }
3704 $newphone .= '>'.$newphonesav.'</a>';
3705 }
3706 }
3707
3708 //if (($cid || $socid) && isModEnabled('agenda') && $user->hasRight('agenda', 'myactions', 'create'))
3709 if (isModEnabled('agenda') && $user->hasRight("agenda", "myactions", "create")) {
3710 $type = 'AC_TEL';
3711 $link = '';
3712 if ($addlink == 'AC_FAX') {
3713 $type = 'AC_FAX';
3714 }
3715 if (!empty($conf->global->AGENDA_ADDACTIONFORPHONE)) {
3716 $link = '<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create&amp;backtopage='. urlencode($_SERVER['REQUEST_URI']) .'&amp;actioncode='.$type.($cid ? '&amp;contactid='.$cid : '').($socid ? '&amp;socid='.$socid : '').'">'.img_object($langs->trans("AddAction"), "calendar").'</a>';
3717 }
3718 if ($link) {
3719 $newphone = '<div>'.$newphone.' '.$link.'</div>';
3720 }
3721 }
3722 }
3723
3724 if (empty($titlealt)) {
3725 $titlealt = ($withpicto == 'fax' ? $langs->trans("Fax") : $langs->trans("Phone"));
3726 }
3727 $rep = '';
3728
3729 if ($hookmanager) {
3730 $parameters = array('countrycode' => $countrycode, 'cid' => $cid, 'socid' => $socid, 'titlealt' => $titlealt, 'picto' => $withpicto);
3731 $reshook = $hookmanager->executeHooks('printPhone', $parameters, $phone);
3732 $rep .= $hookmanager->resPrint;
3733 }
3734 if (empty($reshook)) {
3735 $picto = '';
3736 if ($withpicto) {
3737 if ($withpicto == 'fax') {
3738 $picto = 'phoning_fax';
3739 } elseif ($withpicto == 'phone') {
3740 $picto = 'phoning';
3741 } elseif ($withpicto == 'mobile') {
3742 $picto = 'phoning_mobile';
3743 } else {
3744 $picto = '';
3745 }
3746 }
3747 if ($adddivfloat == 1) {
3748 $rep .= '<div class="nospan float" style="margin-right: 10px">';
3749 } elseif (empty($adddivfloat)) {
3750 $rep .= '<span style="margin-right: 10px;">';
3751 }
3752 $rep .= ($withpicto ?img_picto($titlealt, 'object_'.$picto.'.png').' ' : '').$newphone;
3753 if ($adddivfloat == 1) {
3754 $rep .= '</div>';
3755 } elseif (empty($adddivfloat)) {
3756 $rep .= '</span>';
3757 }
3758 }
3759
3760 return $rep;
3761}
3762
3770function dol_print_ip($ip, $mode = 0)
3771{
3772 global $conf, $langs;
3773
3774 $ret = '';
3775
3776 if (empty($mode)) {
3777 $ret .= $ip;
3778 }
3779
3780 if ($mode != 2) {
3781 $countrycode = dolGetCountryCodeFromIp($ip);
3782 if ($countrycode) { // If success, countrycode is us, fr, ...
3783 if (file_exists(DOL_DOCUMENT_ROOT.'/theme/common/flags/'.$countrycode.'.png')) {
3784 $ret .= ' '.img_picto($countrycode.' '.$langs->trans("AccordingToGeoIPDatabase"), DOL_URL_ROOT.'/theme/common/flags/'.$countrycode.'.png', '', 1);
3785 } else {
3786 $ret .= ' ('.$countrycode.')';
3787 }
3788 } else {
3789 // Nothing
3790 }
3791 }
3792
3793 return $ret;
3794}
3795
3805{
3806 if (empty($_SERVER['HTTP_X_FORWARDED_FOR']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {
3807 if (empty($_SERVER['HTTP_CLIENT_IP']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_CLIENT_IP'])) {
3808 if (empty($_SERVER["HTTP_CF_CONNECTING_IP"])) {
3809 $ip = (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']); // value may have been the IP of the proxy and not the client
3810 } else {
3811 $ip = $_SERVER["HTTP_CF_CONNECTING_IP"]; // value here may have been forged by client
3812 }
3813 } else {
3814 $ip = $_SERVER['HTTP_CLIENT_IP']; // value is clean here but may have been forged by proxy
3815 }
3816 } else {
3817 $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; // value is clean here but may have been forged by proxy
3818 }
3819 return $ip;
3820}
3821
3830function isHTTPS()
3831{
3832 $isSecure = false;
3833 if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
3834 $isSecure = true;
3835 } elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') {
3836 $isSecure = true;
3837 }
3838 return $isSecure;
3839}
3840
3848{
3849 global $conf;
3850
3851 $countrycode = '';
3852
3853 if (!empty($conf->geoipmaxmind->enabled)) {
3854 $datafile = getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE');
3855 //$ip='24.24.24.24';
3856 //$datafile='/usr/share/GeoIP/GeoIP.dat'; Note that this must be downloaded datafile (not same than datafile provided with ubuntu packages)
3857 include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
3858 $geoip = new DolGeoIP('country', $datafile);
3859 //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
3860 $countrycode = $geoip->getCountryCodeFromIP($ip);
3861 }
3862
3863 return $countrycode;
3864}
3865
3866
3874{
3875 global $conf, $langs, $user;
3876
3877 //$ret=$user->xxx;
3878 $ret = '';
3879 if (!empty($conf->geoipmaxmind->enabled)) {
3880 $ip = getUserRemoteIP();
3881 $datafile = getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE');
3882 //$ip='24.24.24.24';
3883 //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';
3884 include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
3885 $geoip = new DolGeoIP('country', $datafile);
3886 $countrycode = $geoip->getCountryCodeFromIP($ip);
3887 $ret = $countrycode;
3888 }
3889 return $ret;
3890}
3891
3904function dol_print_address($address, $htmlid, $element, $id, $noprint = 0, $charfornl = '')
3905{
3906 global $conf, $user, $langs, $hookmanager;
3907
3908 $out = '';
3909
3910 if ($address) {
3911 if ($hookmanager) {
3912 $parameters = array('element' => $element, 'id' => $id);
3913 $reshook = $hookmanager->executeHooks('printAddress', $parameters, $address);
3914 $out .= $hookmanager->resPrint;
3915 }
3916 if (empty($reshook)) {
3917 if (empty($charfornl)) {
3918 $out .= nl2br($address);
3919 } else {
3920 $out .= preg_replace('/[\r\n]+/', $charfornl, $address);
3921 }
3922
3923 // TODO Remove this block, we can add this using the hook now
3924 $showgmap = $showomap = 0;
3925 if (($element == 'thirdparty' || $element == 'societe') && isModEnabled('google') && !empty($conf->global->GOOGLE_ENABLE_GMAPS)) {
3926 $showgmap = 1;
3927 }
3928 if ($element == 'contact' && isModEnabled('google') && !empty($conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS)) {
3929 $showgmap = 1;
3930 }
3931 if ($element == 'member' && isModEnabled('google') && !empty($conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS)) {
3932 $showgmap = 1;
3933 }
3934 if (($element == 'thirdparty' || $element == 'societe') && isModEnabled('openstreetmap') && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS)) {
3935 $showomap = 1;
3936 }
3937 if ($element == 'contact' && isModEnabled('openstreetmap') && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_CONTACTS)) {
3938 $showomap = 1;
3939 }
3940 if ($element == 'member' && isModEnabled('openstreetmap') && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_MEMBERS)) {
3941 $showomap = 1;
3942 }
3943 if ($showgmap) {
3944 $url = dol_buildpath('/google/gmaps.php?mode='.$element.'&id='.$id, 1);
3945 $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
3946 }
3947 if ($showomap) {
3948 $url = dol_buildpath('/openstreetmap/maps.php?mode='.$element.'&id='.$id, 1);
3949 $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'_openstreetmap" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
3950 }
3951 }
3952 }
3953 if ($noprint) {
3954 return $out;
3955 } else {
3956 print $out;
3957 }
3958}
3959
3960
3970function isValidEmail($address, $acceptsupervisorkey = 0, $acceptuserkey = 0)
3971{
3972 if ($acceptsupervisorkey && $address == '__SUPERVISOREMAIL__') {
3973 return true;
3974 }
3975 if ($acceptuserkey && $address == '__USER_EMAIL__') {
3976 return true;
3977 }
3978 if (filter_var($address, FILTER_VALIDATE_EMAIL)) {
3979 return true;
3980 }
3981
3982 return false;
3983}
3984
3993function isValidMXRecord($domain)
3994{
3995 if (function_exists('idn_to_ascii') && function_exists('checkdnsrr')) {
3996 if (!checkdnsrr(idn_to_ascii($domain), 'MX')) {
3997 return 0;
3998 }
3999 if (function_exists('getmxrr')) {
4000 $mxhosts = array();
4001 $weight = array();
4002 getmxrr(idn_to_ascii($domain), $mxhosts, $weight);
4003 if (count($mxhosts) > 1) {
4004 return 1;
4005 }
4006 if (count($mxhosts) == 1 && !empty($mxhosts[0])) {
4007 return 1;
4008 }
4009
4010 return 0;
4011 }
4012 }
4013
4014 // function idn_to_ascii or checkdnsrr or getmxrr does not exists
4015 return -1;
4016}
4017
4025function isValidPhone($phone)
4026{
4027 return true;
4028}
4029
4030
4040function dolGetFirstLetters($s, $nbofchar = 1)
4041{
4042 $ret = '';
4043 $tmparray = explode(' ', $s);
4044 foreach ($tmparray as $tmps) {
4045 $ret .= dol_substr($tmps, 0, $nbofchar);
4046 }
4047
4048 return $ret;
4049}
4050
4051
4059function dol_strlen($string, $stringencoding = 'UTF-8')
4060{
4061 if (is_null($string)) {
4062 return 0;
4063 }
4064
4065 if (function_exists('mb_strlen')) {
4066 return mb_strlen($string, $stringencoding);
4067 } else {
4068 return strlen($string);
4069 }
4070}
4071
4082function dol_substr($string, $start, $length = null, $stringencoding = '', $trunconbytes = 0)
4083{
4084 global $langs;
4085
4086 if (empty($stringencoding)) {
4087 $stringencoding = $langs->charset_output;
4088 }
4089
4090 $ret = '';
4091 if (empty($trunconbytes)) {
4092 if (function_exists('mb_substr')) {
4093 $ret = mb_substr($string, $start, $length, $stringencoding);
4094 } else {
4095 $ret = substr($string, $start, $length);
4096 }
4097 } else {
4098 if (function_exists('mb_strcut')) {
4099 $ret = mb_strcut($string, $start, $length, $stringencoding);
4100 } else {
4101 $ret = substr($string, $start, $length);
4102 }
4103 }
4104 return $ret;
4105}
4106
4107
4121function dol_trunc($string, $size = 40, $trunc = 'right', $stringencoding = 'UTF-8', $nodot = 0, $display = 0)
4122{
4123 global $conf;
4124
4125 if (empty($size) || !empty($conf->global->MAIN_DISABLE_TRUNC)) {
4126 return $string;
4127 }
4128
4129 if (empty($stringencoding)) {
4130 $stringencoding = 'UTF-8';
4131 }
4132 // reduce for small screen
4133 if ($conf->dol_optimize_smallscreen == 1 && $display == 1) {
4134 $size = round($size / 3);
4135 }
4136
4137 // We go always here
4138 if ($trunc == 'right') {
4139 $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
4140 if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
4141 // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
4142 return dol_substr($newstring, 0, $size, $stringencoding).($nodot ? '' : '…');
4143 } else {
4144 //return 'u'.$size.'-'.$newstring.'-'.dol_strlen($newstring,$stringencoding).'-'.$string;
4145 return $string;
4146 }
4147 } elseif ($trunc == 'middle') {
4148 $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
4149 if (dol_strlen($newstring, $stringencoding) > 2 && dol_strlen($newstring, $stringencoding) > ($size + 1)) {
4150 $size1 = round($size / 2);
4151 $size2 = round($size / 2);
4152 return dol_substr($newstring, 0, $size1, $stringencoding).'…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size2, $size2, $stringencoding);
4153 } else {
4154 return $string;
4155 }
4156 } elseif ($trunc == 'left') {
4157 $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
4158 if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
4159 // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
4160 return '…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size, $size, $stringencoding);
4161 } else {
4162 return $string;
4163 }
4164 } elseif ($trunc == 'wrap') {
4165 $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
4166 if (dol_strlen($newstring, $stringencoding) > ($size + 1)) {
4167 return dol_substr($newstring, 0, $size, $stringencoding)."\n".dol_trunc(dol_substr($newstring, $size, dol_strlen($newstring, $stringencoding) - $size, $stringencoding), $size, $trunc);
4168 } else {
4169 return $string;
4170 }
4171 } else {
4172 return 'BadParam3CallingDolTrunc';
4173 }
4174}
4175
4197function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0, $alt = '', $morecss = '', $marginleftonlyshort = 2)
4198{
4199 global $conf, $langs;
4200
4201 // We forge fullpathpicto for image to $path/img/$picto. By default, we take DOL_URL_ROOT/theme/$conf->theme/img/$picto
4202 $url = DOL_URL_ROOT;
4203 $theme = isset($conf->theme) ? $conf->theme : null;
4204 $path = 'theme/'.$theme;
4205 // Define fullpathpicto to use into src
4206 if ($pictoisfullpath) {
4207 // Clean parameters
4208 if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
4209 $picto .= '.png';
4210 }
4211 $fullpathpicto = $picto;
4212 $reg = array();
4213 if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
4214 $morecss .= ($morecss ? ' ' : '').$reg[1];
4215 $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
4216 }
4217 } else {
4218 $pictowithouttext = preg_replace('/(\.png|\.gif|\.svg)$/', '', $picto);
4219 $pictowithouttext = str_replace('object_', '', $pictowithouttext);
4220 $pictowithouttext = str_replace('_nocolor', '', $pictowithouttext);
4221
4222 if (strpos($pictowithouttext, 'fontawesome_') !== false || preg_match('/^fa-/', $pictowithouttext)) {
4223 // This is a font awesome image 'fonwtawesome_xxx' or 'fa-xxx'
4224 $pictowithouttext = str_replace('fontawesome_', '', $pictowithouttext);
4225 $pictowithouttext = str_replace('fa-', '', $pictowithouttext);
4226
4227 $pictowithouttextarray = explode('_', $pictowithouttext);
4228 $marginleftonlyshort = 0;
4229
4230 if (!empty($pictowithouttextarray[1])) {
4231 // Syntax is 'fontawesome_fakey_faprefix_facolor_fasize' or 'fa-fakey_faprefix_facolor_fasize'
4232 $fakey = 'fa-'.$pictowithouttextarray[0];
4233 $fa = empty($pictowithouttextarray[1]) ? 'fa' : $pictowithouttextarray[1];
4234 $facolor = empty($pictowithouttextarray[2]) ? '' : $pictowithouttextarray[2];
4235 $fasize = empty($pictowithouttextarray[3]) ? '' : $pictowithouttextarray[3];
4236 } else {
4237 $fakey = 'fa-'.$pictowithouttext;
4238 $fa = 'fa';
4239 $facolor = '';
4240 $fasize = '';
4241 }
4242
4243 // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
4244 // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
4245 $morestyle = '';
4246 $reg = array();
4247 if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
4248 $morecss .= ($morecss ? ' ' : '').$reg[1];
4249 $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
4250 }
4251 if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
4252 $morestyle = $reg[1];
4253 $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt);
4254 }
4255 $moreatt = trim($moreatt);
4256
4257 $enabledisablehtml = '<span class="'.$fa.' '.$fakey.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
4258 $enabledisablehtml .= ($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').($morestyle ? ' '.$morestyle : '').'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : '').'>';
4259 /*if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
4260 $enabledisablehtml .= $titlealt;
4261 }*/
4262 $enabledisablehtml .= '</span>';
4263
4264 return $enabledisablehtml;
4265 }
4266
4267 if (empty($srconly) && in_array($pictowithouttext, array(
4268 '1downarrow', '1uparrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected',
4269 'accountancy', 'accounting_account', 'account', 'accountline', 'action', 'add', 'address', 'angle-double-down', 'angle-double-up', 'asset',
4270 'bank_account', 'barcode', 'bank', 'bell', 'bill', 'billa', 'billr', 'billd', 'birthday-cake', 'bookmark', 'bom', 'briefcase-medical', 'bug', 'building',
4271 'card', 'calendarlist', 'calendar', 'calendarmonth', 'calendarweek', 'calendarday', 'calendarperuser', 'calendarpertype',
4272 'cash-register', 'category', 'chart', 'check', 'clock', 'clone', 'close_title', 'cog', 'collab', 'company', 'contact', 'country', 'contract', 'conversation', 'cron', 'cross', 'cubes',
4273 'currency', 'multicurrency',
4274 'delete', 'dolly', 'dollyrevert', 'donation', 'download', 'dynamicprice',
4275 'edit', 'ellipsis-h', 'email', 'entity', 'envelope', 'eraser', 'establishment', 'expensereport', 'external-link-alt', 'external-link-square-alt', 'eye',
4276 'filter', 'file-code', 'file-export', 'file-import', 'file-upload', 'autofill', 'folder', 'folder-open', 'folder-plus',
4277 'gears', 'generate', 'generic', 'globe', 'globe-americas', 'graph', 'grip', 'grip_title', 'group',
4278 'hands-helping', 'help', 'holiday',
4279 'id-card', 'images', 'incoterm', 'info', 'intervention', 'inventory', 'intracommreport', 'jobprofile',
4280 'knowledgemanagement',
4281 'label', 'language', 'line', 'link', 'list', 'list-alt', 'listlight', 'loan', 'lock', 'lot', 'long-arrow-alt-right',
4282 'margin', 'map-marker-alt', 'member', 'meeting', 'money-bill-alt', 'movement', 'mrp', 'note', 'next',
4283 'off', 'on', 'order',
4284 'paiment', 'paragraph', 'play', 'pdf', 'phone', 'phoning', 'phoning_mobile', 'phoning_fax', 'playdisabled', 'previous', 'poll', 'pos', 'printer', 'product', 'propal', 'proposal', 'puce',
4285 'stock', 'resize', 'service', 'stats', 'trip',
4286 'security', 'setup', 'share-alt', 'sign-out', 'split', 'stripe', 'stripe-s', 'switch_off', 'switch_on', 'switch_on_warning', 'switch_on_red', 'tools', 'unlink', 'uparrow', 'user', 'user-tie', 'vcard', 'wrench',
4287 'github', 'google', 'jabber', 'microsoft', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'youtube', 'google-plus-g', 'whatsapp',
4288 'chevron-left', 'chevron-right', 'chevron-down', 'chevron-top', 'commercial', 'companies',
4289 'generic', 'home', 'hrm', 'members', 'products', 'invoicing',
4290 'partnership', 'payment', 'payment_vat', 'pencil-ruler', 'pictoconfirm', 'preview', 'project', 'projectpub', 'projecttask', 'question', 'refresh', 'region',
4291 'salary', 'shipment', 'state', 'supplier_invoice', 'supplier_invoicea', 'supplier_invoicer', 'supplier_invoiced',
4292 'technic', 'ticket',
4293 'error', 'warning',
4294 'recent', 'reception', 'recruitmentcandidature', 'recruitmentjobposition', 'replacement', 'resource', 'recurring','rss',
4295 'shapes', 'skill', 'square', 'stop-circle', 'supplier', 'supplier_proposal', 'supplier_order', 'supplier_invoice',
4296 'timespent', 'title_setup', 'title_accountancy', 'title_bank', 'title_hrm', 'title_agenda',
4297 'uncheck', 'url', 'user-cog', 'user-injured', 'user-md', 'vat', 'website', 'workstation', 'webhook', 'world', 'private',
4298 'conferenceorbooth', 'eventorganization',
4299 'stamp', 'signature'
4300 ))) {
4301 $fakey = $pictowithouttext;
4302 $facolor = '';
4303 $fasize = '';
4304 $fa = 'fas';
4305 if (in_array($pictowithouttext, array('card', 'bell', 'clock', 'establishment', 'generic', 'minus-square', 'object_generic', 'pdf', 'plus-square', 'timespent', 'note', 'off', 'on', 'object_bookmark', 'bookmark', 'vcard'))) {
4306 $fa = 'far';
4307 }
4308 if (in_array($pictowithouttext, array('black-tie', 'github', 'google', 'microsoft', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'stripe', 'stripe-s', 'youtube', 'google-plus-g', 'whatsapp'))) {
4309 $fa = 'fab';
4310 }
4311
4312 $arrayconvpictotofa = array(
4313 'account'=>'university', 'accounting_account'=>'clipboard-list', 'accountline'=>'receipt', 'accountancy'=>'search-dollar', 'action'=>'calendar-alt', 'add'=>'plus-circle', 'address'=> 'address-book', 'asset'=>'money-check-alt', 'autofill'=>'fill',
4314 'bank_account'=>'university',
4315 'bill'=>'file-invoice-dollar', 'billa'=>'file-excel', 'billr'=>'file-invoice-dollar', 'billd'=>'file-medical',
4316 'supplier_invoice'=>'file-invoice-dollar', 'supplier_invoicea'=>'file-excel', 'supplier_invoicer'=>'file-invoice-dollar', 'supplier_invoiced'=>'file-medical',
4317 'bom'=>'shapes',
4318 'card'=>'address-card', 'chart'=>'chart-line', 'company'=>'building', 'contact'=>'address-book', 'contract'=>'suitcase', 'collab'=>'people-arrows', 'conversation'=>'comments', 'country'=>'globe-americas', 'cron'=>'business-time', 'cross'=>'times',
4319 'donation'=>'file-alt', 'dynamicprice'=>'hand-holding-usd',
4320 'setup'=>'cog', 'companies'=>'building', 'products'=>'cube', 'commercial'=>'suitcase', 'invoicing'=>'coins',
4321 'accounting'=>'search-dollar', 'category'=>'tag', 'dollyrevert'=>'dolly',
4322 'generate'=>'plus-square', 'hrm'=>'user-tie', 'incoterm'=>'truck-loading',
4323 'margin'=>'calculator', 'members'=>'user-friends', 'ticket'=>'ticket-alt', 'globe'=>'external-link-alt', 'lot'=>'barcode',
4324 'email'=>'at', 'establishment'=>'building', 'edit'=>'pencil-alt', 'entity'=>'globe',
4325 'graph'=>'chart-line', 'grip_title'=>'arrows-alt', 'grip'=>'arrows-alt', 'help'=>'question-circle',
4326 'generic'=>'file', 'holiday'=>'umbrella-beach',
4327 'info'=>'info-circle', 'inventory'=>'boxes', 'intracommreport'=>'globe-europe', 'jobprofile'=>'cogs',
4328 'knowledgemanagement'=>'ticket-alt', 'label'=>'layer-group', 'line'=>'bars', 'loan'=>'money-bill-alt',
4329 'member'=>'user-alt', 'meeting'=>'chalkboard-teacher', 'mrp'=>'cubes', 'next'=>'arrow-alt-circle-right',
4330 'trip'=>'wallet', 'expensereport'=>'wallet', 'group'=>'users', 'movement'=>'people-carry',
4331 'sign-out'=>'sign-out-alt',
4332 'switch_off'=>'toggle-off', 'switch_on'=>'toggle-on', 'switch_on_warning'=>'toggle-on', 'switch_on_red'=>'toggle-on', 'check'=>'check', 'bookmark'=>'star',
4333 'bank'=>'university', 'close_title'=>'times', 'delete'=>'trash', 'filter'=>'filter',
4334 'list-alt'=>'list-alt', 'calendarlist'=>'bars', 'calendar'=>'calendar-alt', 'calendarmonth'=>'calendar-alt', 'calendarweek'=>'calendar-week', 'calendarday'=>'calendar-day', 'calendarperuser'=>'table',
4335 'intervention'=>'ambulance', 'invoice'=>'file-invoice-dollar', 'currency'=>'dollar-sign', 'multicurrency'=>'dollar-sign', 'order'=>'file-invoice',
4336 'error'=>'exclamation-triangle', 'warning'=>'exclamation-triangle',
4337 'other'=>'square',
4338 'playdisabled'=>'play', 'pdf'=>'file-pdf', 'poll'=>'check-double', 'pos'=>'cash-register', 'preview'=>'binoculars', 'project'=>'project-diagram', 'projectpub'=>'project-diagram', 'projecttask'=>'tasks', 'propal'=>'file-signature', 'proposal'=>'file-signature',
4339 'partnership'=>'handshake', 'payment'=>'money-check-alt', 'payment_vat'=>'money-check-alt', 'pictoconfirm'=>'check-square', 'phoning'=>'phone', 'phoning_mobile'=>'mobile-alt', 'phoning_fax'=>'fax', 'previous'=>'arrow-alt-circle-left', 'printer'=>'print', 'product'=>'cube', 'puce'=>'angle-right',
4340 'recent' => 'check-square', 'reception'=>'dolly', 'recruitmentjobposition'=>'id-card-alt', 'recruitmentcandidature'=>'id-badge',
4341 'resize'=>'crop', 'supplier_order'=>'dol-order_supplier', 'supplier_proposal'=>'file-signature',
4342 'refresh'=>'redo', 'region'=>'map-marked', 'replacement'=>'exchange-alt', 'resource'=>'laptop-house', 'recurring'=>'history',
4343 'service'=>'concierge-bell',
4344 'skill'=>'shapes', 'state'=>'map-marked-alt', 'security'=>'key', 'salary'=>'wallet', 'shipment'=>'dolly', 'stock'=>'box-open', 'stats' => 'chart-bar', 'split'=>'code-branch', 'stripe'=>'stripe-s',
4345 'supplier'=>'building', 'technic'=>'cogs',
4346 'timespent'=>'clock', 'title_setup'=>'tools', 'title_accountancy'=>'money-check-alt', 'title_bank'=>'university', 'title_hrm'=>'umbrella-beach',
4347 'title_agenda'=>'calendar-alt',
4348 'uncheck'=>'times', 'uparrow'=>'share', 'url'=>'external-link-alt', 'vat'=>'money-check-alt', 'vcard'=>'arrow-alt-circle-down',
4349 'jabber'=>'comment-o',
4350 'website'=>'globe-americas', 'workstation'=>'pallet', 'webhook'=>'bullseye', 'world'=>'globe', 'private'=>'user-lock',
4351 'conferenceorbooth'=>'chalkboard-teacher', 'eventorganization'=>'project-diagram'
4352 );
4353 if ($pictowithouttext == 'off') {
4354 $fakey = 'fa-square';
4355 $fasize = '1.3em';
4356 } elseif ($pictowithouttext == 'on') {
4357 $fakey = 'fa-check-square';
4358 $fasize = '1.3em';
4359 } elseif ($pictowithouttext == 'listlight') {
4360 $fakey = 'fa-download';
4361 $marginleftonlyshort = 1;
4362 } elseif ($pictowithouttext == 'printer') {
4363 $fakey = 'fa-print';
4364 $fasize = '1.2em';
4365 } elseif ($pictowithouttext == 'note') {
4366 $fakey = 'fa-sticky-note';
4367 $marginleftonlyshort = 1;
4368 } elseif (in_array($pictowithouttext, array('1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'))) {
4369 $convertarray = array('1uparrow'=>'caret-up', '1downarrow'=>'caret-down', '1leftarrow'=>'caret-left', '1rightarrow'=>'caret-right', '1uparrow_selected'=>'caret-up', '1downarrow_selected'=>'caret-down', '1leftarrow_selected'=>'caret-left', '1rightarrow_selected'=>'caret-right');
4370 $fakey = 'fa-'.$convertarray[$pictowithouttext];
4371 if (preg_match('/selected/', $pictowithouttext)) {
4372 $facolor = '#888';
4373 }
4374 $marginleftonlyshort = 1;
4375 } elseif (!empty($arrayconvpictotofa[$pictowithouttext])) {
4376 $fakey = 'fa-'.$arrayconvpictotofa[$pictowithouttext];
4377 } else {
4378 $fakey = 'fa-'.$pictowithouttext;
4379 }
4380
4381 if (in_array($pictowithouttext, array('dollyrevert', 'member', 'members', 'contract', 'group', 'resource', 'shipment'))) {
4382 $morecss .= ' em092';
4383 }
4384 if (in_array($pictowithouttext, array('conferenceorbooth', 'collab', 'eventorganization', 'holiday', 'info', 'project', 'workstation'))) {
4385 $morecss .= ' em088';
4386 }
4387 if (in_array($pictowithouttext, array('asset', 'intervention', 'payment', 'loan', 'partnership', 'stock', 'technic'))) {
4388 $morecss .= ' em080';
4389 }
4390
4391 // Define $marginleftonlyshort
4392 $arrayconvpictotomarginleftonly = array(
4393 'bank', 'check', 'delete', 'generic', 'grip', 'grip_title', 'jabber',
4394 'grip_title', 'grip', 'listlight', 'note', 'on', 'off', 'playdisabled', 'printer', 'resize', 'sign-out', 'stats', 'switch_on', 'switch_on_red', 'switch_off',
4395 'uparrow', '1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'
4396 );
4397 if (!isset($arrayconvpictotomarginleftonly[$pictowithouttext])) {
4398 $marginleftonlyshort = 0;
4399 }
4400
4401 // Add CSS
4402 $arrayconvpictotomorcess = array(
4403 'action'=>'infobox-action', 'account'=>'infobox-bank_account', 'accounting_account'=>'infobox-bank_account', 'accountline'=>'infobox-bank_account', 'accountancy'=>'infobox-bank_account', 'asset'=>'infobox-bank_account',
4404 'bank_account'=>'infobox-bank_account',
4405 'bill'=>'infobox-commande', 'billa'=>'infobox-commande', 'billr'=>'infobox-commande', 'billd'=>'infobox-commande',
4406 'margin'=>'infobox-bank_account', 'conferenceorbooth'=>'infobox-project',
4407 'cash-register'=>'infobox-bank_account', 'contract'=>'infobox-contrat', 'check'=>'font-status4', 'collab'=>'infobox-action', 'conversation'=>'infobox-contrat',
4408 'donation'=>'infobox-commande', 'dolly'=>'infobox-commande', 'dollyrevert'=>'flip infobox-order_supplier',
4409 'ecm'=>'infobox-action', 'eventorganization'=>'infobox-project',
4410 'hrm'=>'infobox-adherent', 'group'=>'infobox-adherent', 'intervention'=>'infobox-contrat',
4411 'incoterm'=>'infobox-supplier_proposal',
4412 'currency'=>'infobox-bank_account', 'multicurrency'=>'infobox-bank_account',
4413 'members'=>'infobox-adherent', 'member'=>'infobox-adherent', 'money-bill-alt'=>'infobox-bank_account',
4414 'order'=>'infobox-commande',
4415 'user'=>'infobox-adherent', 'users'=>'infobox-adherent',
4416 'error'=>'pictoerror', 'warning'=>'pictowarning', 'switch_on'=>'font-status4', 'switch_on_warning'=>'font-status4 warning', 'switch_on_red'=>'font-status8',
4417 'holiday'=>'infobox-holiday', 'info'=>'opacityhigh', 'invoice'=>'infobox-commande',
4418 'knowledgemanagement'=>'infobox-contrat rotate90', 'loan'=>'infobox-bank_account',
4419 'payment'=>'infobox-bank_account', 'payment_vat'=>'infobox-bank_account', 'poll'=>'infobox-adherent', 'pos'=>'infobox-bank_account', 'project'=>'infobox-project', 'projecttask'=>'infobox-project',
4420 'propal'=>'infobox-propal', 'proposal'=>'infobox-propal','private'=>'infobox-project',
4421 'reception'=>'flip', 'recruitmentjobposition'=>'infobox-adherent', 'recruitmentcandidature'=>'infobox-adherent',
4422 'resource'=>'infobox-action',
4423 'salary'=>'infobox-bank_account', 'shipment'=>'infobox-commande', 'supplier_invoice'=>'infobox-order_supplier', 'supplier_invoicea'=>'infobox-order_supplier', 'supplier_invoiced'=>'infobox-order_supplier',
4424 'supplier'=>'infobox-order_supplier', 'supplier_order'=>'infobox-order_supplier', 'supplier_proposal'=>'infobox-supplier_proposal',
4425 'ticket'=>'infobox-contrat', 'title_accountancy'=>'infobox-bank_account', 'title_hrm'=>'infobox-holiday', 'expensereport'=>'infobox-expensereport', 'trip'=>'infobox-expensereport', 'title_agenda'=>'infobox-action',
4426 'vat'=>'infobox-bank_account',
4427 //'title_setup'=>'infobox-action', 'tools'=>'infobox-action',
4428 'list-alt'=>'imgforviewmode', 'calendar'=>'imgforviewmode', 'calendarweek'=>'imgforviewmode', 'calendarmonth'=>'imgforviewmode', 'calendarday'=>'imgforviewmode', 'calendarperuser'=>'imgforviewmode'
4429 );
4430 if (!empty($arrayconvpictotomorcess[$pictowithouttext]) && strpos($picto, '_nocolor') === false) {
4431 $morecss .= ($morecss ? ' ' : '').$arrayconvpictotomorcess[$pictowithouttext];
4432 }
4433
4434 // Define $color
4435 $arrayconvpictotocolor = array(
4436 'address'=>'#6c6aa8', 'building'=>'#6c6aa8', 'bom'=>'#a69944',
4437 'clone'=>'#999', 'cog'=>'#999', 'companies'=>'#6c6aa8', 'company'=>'#6c6aa8', 'contact'=>'#6c6aa8', 'cron'=>'#555',
4438 'dynamicprice'=>'#a69944',
4439 'edit'=>'#444', 'note'=>'#999', 'error'=>'', 'help'=>'#bbb', 'listlight'=>'#999', 'language'=>'#555',
4440 //'dolly'=>'#a69944', 'dollyrevert'=>'#a69944',
4441 'lock'=>'#ddd', 'lot'=>'#a69944',
4442 'map-marker-alt'=>'#aaa', 'mrp'=>'#a69944', 'product'=>'#a69944', 'service'=>'#a69944', 'inventory'=>'#a69944', 'stock'=>'#a69944', 'movement'=>'#a69944',
4443 'other'=>'#ddd', 'world'=>'#986c6a',
4444 'partnership'=>'#6c6aa8', 'playdisabled'=>'#ccc', 'printer'=>'#444', 'projectpub'=>'#986c6a', 'reception'=>'#a69944', 'resize'=>'#444', 'rss'=>'#cba',
4445 //'shipment'=>'#a69944',
4446 'security'=>'#999', 'square'=>'#888', 'stop-circle'=>'#888', 'stats'=>'#444', 'switch_off'=>'#999', 'technic'=>'#999', 'timespent'=>'#555',
4447 'uncheck'=>'#800', 'uparrow'=>'#555', 'user-cog'=>'#999', 'country'=>'#aaa', 'globe-americas'=>'#aaa', 'region'=>'#aaa', 'state'=>'#aaa',
4448 'website'=>'#304', 'workstation'=>'#a69944'
4449 );
4450 if (isset($arrayconvpictotocolor[$pictowithouttext]) && strpos($picto, '_nocolor') === false) {
4451 $facolor = $arrayconvpictotocolor[$pictowithouttext];
4452 }
4453
4454 // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
4455 // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
4456 $morestyle = '';
4457 $reg = array();
4458 if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
4459 $morecss .= ($morecss ? ' ' : '').$reg[1];
4460 $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
4461 }
4462 if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
4463 $morestyle = $reg[1];
4464 $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt);
4465 }
4466 $moreatt = trim($moreatt);
4467
4468 $enabledisablehtml = '<span class="'.$fa.' '.$fakey.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
4469 $enabledisablehtml .= ($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').($morestyle ? ' '.$morestyle : '').'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : '').'>';
4470 /*if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
4471 $enabledisablehtml .= $titlealt;
4472 }*/
4473 $enabledisablehtml .= '</span>';
4474
4475 return $enabledisablehtml;
4476 }
4477
4478 if (!empty($conf->global->MAIN_OVERWRITE_THEME_PATH)) {
4479 $path = $conf->global->MAIN_OVERWRITE_THEME_PATH.'/theme/'.$theme; // If the theme does not have the same name as the module
4480 } elseif (!empty($conf->global->MAIN_OVERWRITE_THEME_RES)) {
4481 $path = $conf->global->MAIN_OVERWRITE_THEME_RES.'/theme/'.$conf->global->MAIN_OVERWRITE_THEME_RES; // To allow an external module to overwrite image resources whatever is activated theme
4482 } elseif (!empty($conf->modules_parts['theme']) && array_key_exists($theme, $conf->modules_parts['theme'])) {
4483 $path = $theme.'/theme/'.$theme; // If the theme have the same name as the module
4484 }
4485
4486 // If we ask an image into $url/$mymodule/img (instead of default path)
4487 $regs = array();
4488 if (preg_match('/^([^@]+)@([^@]+)$/i', $picto, $regs)) {
4489 $picto = $regs[1];
4490 $path = $regs[2]; // $path is $mymodule
4491 }
4492
4493 // Clean parameters
4494 if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
4495 $picto .= '.png';
4496 }
4497 // If alt path are defined, define url where img file is, according to physical path
4498 // ex: array(["main"]=>"/home/maindir/htdocs", ["alt0"]=>"/home/moddir0/htdocs", ...)
4499 foreach ($conf->file->dol_document_root as $type => $dirroot) {
4500 if ($type == 'main') {
4501 continue;
4502 }
4503 // This need a lot of time, that's why enabling alternative dir like "custom" dir is not recommanded
4504 if (file_exists($dirroot.'/'.$path.'/img/'.$picto)) {
4505 $url = DOL_URL_ROOT.$conf->file->dol_url_root[$type];
4506 break;
4507 }
4508 }
4509
4510 // $url is '' or '/custom', $path is current theme or
4511 $fullpathpicto = $url.'/'.$path.'/img/'.$picto;
4512 }
4513
4514 if ($srconly) {
4515 return $fullpathpicto;
4516 }
4517
4518 // tag title is used for tooltip on <a>, tag alt can be used with very simple text on image for blind people
4519 return '<img src="'.$fullpathpicto.'"'.($notitle ? '' : ' alt="'.dol_escape_htmltag($alt).'"').(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt.($morecss ? ' class="'.$morecss.'"' : '') : ' class="inline-block'.($morecss ? ' '.$morecss : '').'"').'>'; // Alt is used for accessibility, title for popup
4520}
4521
4535function img_object($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0)
4536{
4537 if (strpos($picto, '^') === 0) {
4538 return img_picto($titlealt, str_replace('^', '', $picto), $moreatt, $pictoisfullpath, $srconly, $notitle);
4539 } else {
4540 return img_picto($titlealt, 'object_'.$picto, $moreatt, $pictoisfullpath, $srconly, $notitle);
4541 }
4542}
4543
4555function img_weather($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $morecss = '')
4556{
4557 global $conf;
4558
4559 if (is_numeric($picto)) {
4560 //$leveltopicto = array(0=>'weather-clear.png', 1=>'weather-few-clouds.png', 2=>'weather-clouds.png', 3=>'weather-many-clouds.png', 4=>'weather-storm.png');
4561 //$picto = $leveltopicto[$picto];
4562 return '<i class="fa fa-weather-level'.$picto.'"></i>';
4563 } elseif (!preg_match('/(\.png|\.gif)$/i', $picto)) {
4564 $picto .= '.png';
4565 }
4566
4567 $path = DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/weather/'.$picto;
4568
4569 return img_picto($titlealt, $path, $moreatt, 1, 0, 0, '', $morecss);
4570}
4571
4583function img_picto_common($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $notitle = 0)
4584{
4585 global $conf;
4586
4587 if (!preg_match('/(\.png|\.gif)$/i', $picto)) {
4588 $picto .= '.png';
4589 }
4590
4591 if ($pictoisfullpath) {
4592 $path = $picto;
4593 } else {
4594 $path = DOL_URL_ROOT.'/theme/common/'.$picto;
4595
4596 if (!empty($conf->global->MAIN_MODULE_CAN_OVERWRITE_COMMONICONS)) {
4597 $themepath = DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/'.$picto;
4598
4599 if (file_exists($themepath)) {
4600 $path = $themepath;
4601 }
4602 }
4603 }
4604
4605 return img_picto($titlealt, $path, $moreatt, 1, 0, $notitle);
4606}
4607
4621function img_action($titlealt, $numaction, $picto = '', $moreatt = '')
4622{
4623 global $langs;
4624
4625 if (empty($titlealt) || $titlealt == 'default') {
4626 if ($numaction == '-1' || $numaction == 'ST_NO') {
4627 $numaction = -1;
4628 $titlealt = $langs->transnoentitiesnoconv('ChangeDoNotContact');
4629 } elseif ($numaction == '0' || $numaction == 'ST_NEVER') {
4630 $numaction = 0;
4631 $titlealt = $langs->transnoentitiesnoconv('ChangeNeverContacted');
4632 } elseif ($numaction == '1' || $numaction == 'ST_TODO') {
4633 $numaction = 1;
4634 $titlealt = $langs->transnoentitiesnoconv('ChangeToContact');
4635 } elseif ($numaction == '2' || $numaction == 'ST_PEND') {
4636 $numaction = 2;
4637 $titlealt = $langs->transnoentitiesnoconv('ChangeContactInProcess');
4638 } elseif ($numaction == '3' || $numaction == 'ST_DONE') {
4639 $numaction = 3;
4640 $titlealt = $langs->transnoentitiesnoconv('ChangeContactDone');
4641 } else {
4642 $titlealt = $langs->transnoentitiesnoconv('ChangeStatus '.$numaction);
4643 $numaction = 0;
4644 }
4645 }
4646 if (!is_numeric($numaction)) {
4647 $numaction = 0;
4648 }
4649
4650 return img_picto($titlealt, (empty($picto) ? 'stcomm'.$numaction.'.png' : $picto), $moreatt);
4651}
4652
4660function img_pdf($titlealt = 'default', $size = 3)
4661{
4662 global $langs;
4663
4664 if ($titlealt == 'default') {
4665 $titlealt = $langs->trans('Show');
4666 }
4667
4668 return img_picto($titlealt, 'pdf'.$size.'.png');
4669}
4670
4678function img_edit_add($titlealt = 'default', $other = '')
4679{
4680 global $langs;
4681
4682 if ($titlealt == 'default') {
4683 $titlealt = $langs->trans('Add');
4684 }
4685
4686 return img_picto($titlealt, 'edit_add.png', $other);
4687}
4695function img_edit_remove($titlealt = 'default', $other = '')
4696{
4697 global $langs;
4698
4699 if ($titlealt == 'default') {
4700 $titlealt = $langs->trans('Remove');
4701 }
4702
4703 return img_picto($titlealt, 'edit_remove.png', $other);
4704}
4705
4714function img_edit($titlealt = 'default', $float = 0, $other = '')
4715{
4716 global $langs;
4717
4718 if ($titlealt == 'default') {
4719 $titlealt = $langs->trans('Modify');
4720 }
4721
4722 return img_picto($titlealt, 'edit.png', ($float ? 'style="float: '.($langs->tab_translate["DIRECTION"] == 'rtl' ? 'left' : 'right').'"' : "").($other ? ' '.$other : ''));
4723}
4724
4733function img_view($titlealt = 'default', $float = 0, $other = 'class="valignmiddle"')
4734{
4735 global $langs;
4736
4737 if ($titlealt == 'default') {
4738 $titlealt = $langs->trans('View');
4739 }
4740
4741 $moreatt = ($float ? 'style="float: right" ' : '').$other;
4742
4743 return img_picto($titlealt, 'eye', $moreatt);
4744}
4745
4754function img_delete($titlealt = 'default', $other = 'class="pictodelete"', $morecss = '')
4755{
4756 global $langs;
4757
4758 if ($titlealt == 'default') {
4759 $titlealt = $langs->trans('Delete');
4760 }
4761
4762 return img_picto($titlealt, 'delete.png', $other, false, 0, 0, '', $morecss);
4763}
4764
4772function img_printer($titlealt = "default", $other = '')
4773{
4774 global $langs;
4775 if ($titlealt == "default") {
4776 $titlealt = $langs->trans("Print");
4777 }
4778 return img_picto($titlealt, 'printer.png', $other);
4779}
4780
4788function img_split($titlealt = 'default', $other = 'class="pictosplit"')
4789{
4790 global $langs;
4791
4792 if ($titlealt == 'default') {
4793 $titlealt = $langs->trans('Split');
4794 }
4795
4796 return img_picto($titlealt, 'split.png', $other);
4797}
4798
4806function img_help($usehelpcursor = 1, $usealttitle = 1)
4807{
4808 global $langs;
4809
4810 if ($usealttitle) {
4811 if (is_string($usealttitle)) {
4812 $usealttitle = dol_escape_htmltag($usealttitle);
4813 } else {
4814 $usealttitle = $langs->trans('Info');
4815 }
4816 }
4817
4818 return img_picto($usealttitle, 'info.png', 'style="vertical-align: middle;'.($usehelpcursor == 1 ? ' cursor: help' : ($usehelpcursor == 2 ? ' cursor: pointer' : '')).'"');
4819}
4820
4827function img_info($titlealt = 'default')
4828{
4829 global $langs;
4830
4831 if ($titlealt == 'default') {
4832 $titlealt = $langs->trans('Informations');
4833 }
4834
4835 return img_picto($titlealt, 'info.png', 'style="vertical-align: middle;"');
4836}
4837
4846function img_warning($titlealt = 'default', $moreatt = '', $morecss = 'pictowarning')
4847{
4848 global $langs;
4849
4850 if ($titlealt == 'default') {
4851 $titlealt = $langs->trans('Warning');
4852 }
4853
4854 //return '<div class="imglatecoin">'.img_picto($titlealt, 'warning_white.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): '')).'</div>';
4855 return img_picto($titlealt, 'warning.png', 'class="'.$morecss.'"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt) : ''));
4856}
4857
4864function img_error($titlealt = 'default')
4865{
4866 global $langs;
4867
4868 if ($titlealt == 'default') {
4869 $titlealt = $langs->trans('Error');
4870 }
4871
4872 return img_picto($titlealt, 'error.png');
4873}
4874
4882function img_next($titlealt = 'default', $moreatt = '')
4883{
4884 global $langs;
4885
4886 if ($titlealt == 'default') {
4887 $titlealt = $langs->trans('Next');
4888 }
4889
4890 //return img_picto($titlealt, 'next.png', $moreatt);
4891 return '<span class="fa fa-chevron-right paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
4892}
4893
4901function img_previous($titlealt = 'default', $moreatt = '')
4902{
4903 global $langs;
4904
4905 if ($titlealt == 'default') {
4906 $titlealt = $langs->trans('Previous');
4907 }
4908
4909 //return img_picto($titlealt, 'previous.png', $moreatt);
4910 return '<span class="fa fa-chevron-left paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
4911}
4912
4921function img_down($titlealt = 'default', $selected = 0, $moreclass = '')
4922{
4923 global $langs;
4924
4925 if ($titlealt == 'default') {
4926 $titlealt = $langs->trans('Down');
4927 }
4928
4929 return img_picto($titlealt, ($selected ? '1downarrow_selected.png' : '1downarrow.png'), 'class="imgdown'.($moreclass ? " ".$moreclass : "").'"');
4930}
4931
4940function img_up($titlealt = 'default', $selected = 0, $moreclass = '')
4941{
4942 global $langs;
4943
4944 if ($titlealt == 'default') {
4945 $titlealt = $langs->trans('Up');
4946 }
4947
4948 return img_picto($titlealt, ($selected ? '1uparrow_selected.png' : '1uparrow.png'), 'class="imgup'.($moreclass ? " ".$moreclass : "").'"');
4949}
4950
4959function img_left($titlealt = 'default', $selected = 0, $moreatt = '')
4960{
4961 global $langs;
4962
4963 if ($titlealt == 'default') {
4964 $titlealt = $langs->trans('Left');
4965 }
4966
4967 return img_picto($titlealt, ($selected ? '1leftarrow_selected.png' : '1leftarrow.png'), $moreatt);
4968}
4969
4978function img_right($titlealt = 'default', $selected = 0, $moreatt = '')
4979{
4980 global $langs;
4981
4982 if ($titlealt == 'default') {
4983 $titlealt = $langs->trans('Right');
4984 }
4985
4986 return img_picto($titlealt, ($selected ? '1rightarrow_selected.png' : '1rightarrow.png'), $moreatt);
4987}
4988
4996function img_allow($allow, $titlealt = 'default')
4997{
4998 global $langs;
4999
5000 if ($titlealt == 'default') {
5001 $titlealt = $langs->trans('Active');
5002 }
5003
5004 if ($allow == 1) {
5005 return img_picto($titlealt, 'tick.png');
5006 }
5007
5008 return '-';
5009}
5010
5018function img_credit_card($brand, $morecss = null)
5019{
5020 if (is_null($morecss)) {
5021 $morecss = 'fa-2x';
5022 }
5023
5024 if ($brand == 'visa' || $brand == 'Visa') {
5025 $brand = 'cc-visa';
5026 } elseif ($brand == 'mastercard' || $brand == 'MasterCard') {
5027 $brand = 'cc-mastercard';
5028 } elseif ($brand == 'amex' || $brand == 'American Express') {
5029 $brand = 'cc-amex';
5030 } elseif ($brand == 'discover' || $brand == 'Discover') {
5031 $brand = 'cc-discover';
5032 } elseif ($brand == 'jcb' || $brand == 'JCB') {
5033 $brand = 'cc-jcb';
5034 } elseif ($brand == 'diners' || $brand == 'Diners club') {
5035 $brand = 'cc-diners-club';
5036 } elseif (!in_array($brand, array('cc-visa', 'cc-mastercard', 'cc-amex', 'cc-discover', 'cc-jcb', 'cc-diners-club'))) {
5037 $brand = 'credit-card';
5038 }
5039
5040 return '<span class="fa fa-'.$brand.' fa-fw'.($morecss ? ' '.$morecss : '').'"></span>';
5041}
5042
5051function img_mime($file, $titlealt = '', $morecss = '')
5052{
5053 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
5054
5055 $mimetype = dol_mimetype($file, '', 1);
5056 $mimeimg = dol_mimetype($file, '', 2);
5057 $mimefa = dol_mimetype($file, '', 4);
5058
5059 if (empty($titlealt)) {
5060 $titlealt = 'Mime type: '.$mimetype;
5061 }
5062
5063 //return img_picto_common($titlealt, 'mime/'.$mimeimg, 'class="'.$morecss.'"');
5064 return '<i class="fa fa-'.$mimefa.' paddingright'.($morecss ? ' '.$morecss : '').'"'.($titlealt ? ' title="'.$titlealt.'"' : '').'></i>';
5065}
5066
5067
5075function img_search($titlealt = 'default', $other = '')
5076{
5077 global $conf, $langs;
5078
5079 if ($titlealt == 'default') {
5080 $titlealt = $langs->trans('Search');
5081 }
5082
5083 $img = img_picto($titlealt, 'search.png', $other, false, 1);
5084
5085 $input = '<input type="image" class="liste_titre" name="button_search" src="'.$img.'" ';
5086 $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
5087
5088 return $input;
5089}
5090
5098function img_searchclear($titlealt = 'default', $other = '')
5099{
5100 global $conf, $langs;
5101
5102 if ($titlealt == 'default') {
5103 $titlealt = $langs->trans('Search');
5104 }
5105
5106 $img = img_picto($titlealt, 'searchclear.png', $other, false, 1);
5107
5108 $input = '<input type="image" class="liste_titre" name="button_removefilter" src="'.$img.'" ';
5109 $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
5110
5111 return $input;
5112}
5113
5125function info_admin($text, $infoonimgalt = 0, $nodiv = 0, $admin = '1', $morecss = 'hideonsmartphone', $textfordropdown = '')
5126{
5127 global $conf, $langs;
5128
5129 if ($infoonimgalt) {
5130 $result = img_picto($text, 'info', 'class="'.($morecss ? ' '.$morecss : '').'"');
5131 } else {
5132 if (empty($conf->use_javascript_ajax)) {
5133 $textfordropdown = '';
5134 }
5135
5136 $class = (empty($admin) ? 'undefined' : ($admin == '1' ? 'info' : $admin));
5137 $result = ($nodiv ? '' : '<div class="'.$class.($morecss ? ' '.$morecss : '').($textfordropdown ? ' hidden' : '').'">').'<span class="fa fa-info-circle" title="'.dol_escape_htmltag($admin ? $langs->trans('InfoAdmin') : $langs->trans('Note')).'"></span> '.$text.($nodiv ? '' : '</div>');
5138
5139 if ($textfordropdown) {
5140 $tmpresult = '<span class="'.$class.'text opacitymedium cursorpointer">'.$langs->trans($textfordropdown).' '.img_picto($langs->trans($textfordropdown), '1downarrow').'</span>';
5141 $tmpresult .= '<script nonce="'.getNonce().'" type="text/javascript">
5142 jQuery(document).ready(function() {
5143 jQuery(".'.$class.'text").click(function() {
5144 console.log("toggle text");
5145 jQuery(".'.$class.'").toggle();
5146 });
5147 });
5148 </script>';
5149
5150 $result = $tmpresult.$result;
5151 }
5152 }
5153
5154 return $result;
5155}
5156
5157
5169function dol_print_error($db = '', $error = '', $errors = null)
5170{
5171 global $conf, $langs, $argv;
5172 global $dolibarr_main_prod;
5173
5174 $out = '';
5175 $syslog = '';
5176
5177 // If error occurs before the $lang object was loaded
5178 if (!$langs) {
5179 require_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
5180 $langs = new Translate('', $conf);
5181 $langs->load("main");
5182 }
5183
5184 // Load translation files required by the error messages
5185 $langs->loadLangs(array('main', 'errors'));
5186
5187 if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
5188 $out .= $langs->trans("DolibarrHasDetectedError").".<br>\n";
5189 if (getDolGlobalInt('MAIN_FEATURES_LEVEL') > 0) {
5190 $out .= "You use an experimental or develop level of features, so please do NOT report any bugs or vulnerability, except if problem is confirmed after moving option MAIN_FEATURES_LEVEL back to 0.<br>\n";
5191 }
5192 $out .= $langs->trans("InformationToHelpDiagnose").":<br>\n";
5193
5194 $out .= "<b>".$langs->trans("Date").":</b> ".dol_print_date(time(), 'dayhourlog')."<br>\n";
5195 $out .= "<b>".$langs->trans("Dolibarr").":</b> ".DOL_VERSION." - https://www.dolibarr.org<br>\n";
5196 if (isset($conf->global->MAIN_FEATURES_LEVEL)) {
5197 $out .= "<b>".$langs->trans("LevelOfFeature").":</b> ".getDolGlobalInt('MAIN_FEATURES_LEVEL')."<br>\n";
5198 }
5199 if (function_exists("phpversion")) {
5200 $out .= "<b>".$langs->trans("PHP").":</b> ".phpversion()."<br>\n";
5201 }
5202 $out .= "<b>".$langs->trans("Server").":</b> ".(isset($_SERVER["SERVER_SOFTWARE"]) ? dol_htmlentities($_SERVER["SERVER_SOFTWARE"], ENT_COMPAT) : '')."<br>\n";
5203 if (function_exists("php_uname")) {
5204 $out .= "<b>".$langs->trans("OS").":</b> ".php_uname()."<br>\n";
5205 }
5206 $out .= "<b>".$langs->trans("UserAgent").":</b> ".(isset($_SERVER["HTTP_USER_AGENT"]) ? dol_htmlentities($_SERVER["HTTP_USER_AGENT"], ENT_COMPAT) : '')."<br>\n";
5207 $out .= "<br>\n";
5208 $out .= "<b>".$langs->trans("RequestedUrl").":</b> ".dol_htmlentities($_SERVER["REQUEST_URI"], ENT_COMPAT)."<br>\n";
5209 $out .= "<b>".$langs->trans("Referer").":</b> ".(isset($_SERVER["HTTP_REFERER"]) ? dol_htmlentities($_SERVER["HTTP_REFERER"], ENT_COMPAT) : '')."<br>\n";
5210 $out .= "<b>".$langs->trans("MenuManager").":</b> ".(isset($conf->standard_menu) ? dol_htmlentities($conf->standard_menu, ENT_COMPAT) : '')."<br>\n";
5211 $out .= "<br>\n";
5212 $syslog .= "url=".dol_escape_htmltag($_SERVER["REQUEST_URI"]);
5213 $syslog .= ", query_string=".dol_escape_htmltag($_SERVER["QUERY_STRING"]);
5214 } else { // Mode CLI
5215 $out .= '> '.$langs->transnoentities("ErrorInternalErrorDetected").":\n".$argv[0]."\n";
5216 $syslog .= "pid=".dol_getmypid();
5217 }
5218
5219 if (!empty($conf->modules)) {
5220 $out .= "<b>".$langs->trans("Modules").":</b> ".join(', ', $conf->modules)."<br>\n";
5221 }
5222
5223 if (is_object($db)) {
5224 if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
5225 $out .= "<b>".$langs->trans("DatabaseTypeManager").":</b> ".$db->type."<br>\n";
5226 $lastqueryerror = $db->lastqueryerror();
5227 if (!utf8_check($lastqueryerror)) {
5228 $lastqueryerror = "SQL error string is not a valid UTF8 string. We can't show it.";
5229 }
5230 $out .= "<b>".$langs->trans("RequestLastAccessInError").":</b> ".($lastqueryerror ? dol_escape_htmltag($lastqueryerror) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
5231 $out .= "<b>".$langs->trans("ReturnCodeLastAccessInError").":</b> ".($db->lasterrno() ? dol_escape_htmltag($db->lasterrno()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
5232 $out .= "<b>".$langs->trans("InformationLastAccessInError").":</b> ".($db->lasterror() ? dol_escape_htmltag($db->lasterror()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
5233 $out .= "<br>\n";
5234 } else { // Mode CLI
5235 // No dol_escape_htmltag for output, we are in CLI mode
5236 $out .= '> '.$langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n";
5237 $out .= '> '.$langs->transnoentities("RequestLastAccessInError").":\n".($db->lastqueryerror() ? $db->lastqueryerror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
5238 $out .= '> '.$langs->transnoentities("ReturnCodeLastAccessInError").":\n".($db->lasterrno() ? $db->lasterrno() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
5239 $out .= '> '.$langs->transnoentities("InformationLastAccessInError").":\n".($db->lasterror() ? $db->lasterror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
5240 }
5241 $syslog .= ", sql=".$db->lastquery();
5242 $syslog .= ", db_error=".$db->lasterror();
5243 }
5244
5245 if ($error || $errors) {
5246 $langs->load("errors");
5247
5248 // Merge all into $errors array
5249 if (is_array($error) && is_array($errors)) {
5250 $errors = array_merge($error, $errors);
5251 } elseif (is_array($error)) {
5252 $errors = $error;
5253 } elseif (is_array($errors)) {
5254 $errors = array_merge(array($error), $errors);
5255 } else {
5256 $errors = array_merge(array($error), array($errors));
5257 }
5258
5259 foreach ($errors as $msg) {
5260 if (empty($msg)) {
5261 continue;
5262 }
5263 if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
5264 $out .= "<b>".$langs->trans("Message").":</b> ".dol_escape_htmltag($msg)."<br>\n";
5265 } else // Mode CLI
5266 {
5267 $out .= '> '.$langs->transnoentities("Message").":\n".$msg."\n";
5268 }
5269 $syslog .= ", msg=".$msg;
5270 }
5271 }
5272 if (empty($dolibarr_main_prod) && $_SERVER['DOCUMENT_ROOT'] && function_exists('xdebug_print_function_stack') && function_exists('xdebug_call_file')) {
5273 xdebug_print_function_stack();
5274 $out .= '<b>XDebug informations:</b>'."<br>\n";
5275 $out .= 'File: '.xdebug_call_file()."<br>\n";
5276 $out .= 'Line: '.xdebug_call_line()."<br>\n";
5277 $out .= 'Function: '.xdebug_call_function()."<br>\n";
5278 $out .= "<br>\n";
5279 }
5280
5281 // Return a http header with error code if possible
5282 if (!headers_sent()) {
5283 if (function_exists('top_httphead')) { // In CLI context, the method does not exists
5284 top_httphead();
5285 }
5286 //http_response_code(500); // If we use 500, message is not ouput with some command line tools
5287 http_response_code(202); // If we use 202, this is not really an error message, but this allow to ouput message on command line tools
5288 }
5289
5290 if (empty($dolibarr_main_prod)) {
5291 print $out;
5292 } else {
5293 if (empty($langs->defaultlang)) {
5294 $langs->setDefaultLang();
5295 }
5296 $langs->loadLangs(array("main", "errors")); // Reload main because language may have been set only on previous line so we have to reload files we need.
5297 // This should not happen, except if there is a bug somewhere. Enabled and check log in such case.
5298 print 'This website or feature is currently temporarly not available or failed after a technical error.<br><br>This may be due to a maintenance operation. Current status of operation ('.dol_print_date(dol_now(), 'dayhourrfc').') are on next line...<br><br>'."\n";
5299 print $langs->trans("DolibarrHasDetectedError").'. ';
5300 print $langs->trans("YouCanSetOptionDolibarrMainProdToZero");
5301 if (!defined("MAIN_CORE_ERROR")) {
5302 define("MAIN_CORE_ERROR", 1);
5303 }
5304 }
5305
5306 dol_syslog("Error ".$syslog, LOG_ERR);
5307}
5308
5319function dol_print_error_email($prefixcode, $errormessage = '', $errormessages = array(), $morecss = 'error', $email = '')
5320{
5321 global $langs, $conf;
5322
5323 if (empty($email)) {
5324 $email = $conf->global->MAIN_INFO_SOCIETE_MAIL;
5325 }
5326
5327 $langs->load("errors");
5328 $now = dol_now();
5329
5330 print '<br><div class="center login_main_message"><div class="'.$morecss.'">';
5331 print $langs->trans("ErrorContactEMail", $email, $prefixcode.'-'.dol_print_date($now, '%Y%m%d%H%M%S'));
5332 if ($errormessage) {
5333 print '<br><br>'.$errormessage;
5334 }
5335 if (is_array($errormessages) && count($errormessages)) {
5336 foreach ($errormessages as $mesgtoshow) {
5337 print '<br><br>'.$mesgtoshow;
5338 }
5339 }
5340 print '</div></div>';
5341}
5342
5359function print_liste_field_titre($name, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $tooltip = "", $forcenowrapcolumntitle = 0)
5360{
5361 print getTitleFieldOfList($name, 0, $file, $field, $begin, $moreparam, $moreattrib, $sortfield, $sortorder, $prefix, 0, $tooltip, $forcenowrapcolumntitle);
5362}
5363
5382function getTitleFieldOfList($name, $thead = 0, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $disablesortlink = 0, $tooltip = '', $forcenowrapcolumntitle = 0)
5383{
5384 global $conf, $langs, $form;
5385 //print "$name, $file, $field, $begin, $options, $moreattrib, $sortfield, $sortorder<br>\n";
5386
5387 if ($moreattrib == 'class="right"') {
5388 $prefix .= 'right '; // For backward compatibility
5389 }
5390
5391 $sortorder = strtoupper($sortorder);
5392 $out = '';
5393 $sortimg = '';
5394
5395 $tag = 'th';
5396 if ($thead == 2) {
5397 $tag = 'div';
5398 }
5399
5400 $tmpsortfield = explode(',', $sortfield);
5401 $sortfield1 = trim($tmpsortfield[0]); // If $sortfield is 'd.datep,d.id', it becomes 'd.datep'
5402 $tmpfield = explode(',', $field);
5403 $field1 = trim($tmpfield[0]); // If $field is 'd.datep,d.id', it becomes 'd.datep'
5404
5405 if (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && empty($forcenowrapcolumntitle)) {
5406 $prefix = 'wrapcolumntitle '.$prefix;
5407 }
5408
5409 //var_dump('field='.$field.' field1='.$field1.' sortfield='.$sortfield.' sortfield1='.$sortfield1);
5410 // If field is used as sort criteria we use a specific css class liste_titre_sel
5411 // Example if (sortfield,field)=("nom","xxx.nom") or (sortfield,field)=("nom","nom")
5412 $liste_titre = 'liste_titre';
5413 if ($field1 && ($sortfield1 == $field1 || $sortfield1 == preg_replace("/^[^\.]+\./", "", $field1))) {
5414 $liste_titre = 'liste_titre_sel';
5415 }
5416
5417 $tagstart = '<'.$tag.' class="'.$prefix.$liste_titre.'" '.$moreattrib;
5418 //$out .= (($field && empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && preg_match('/^[a-zA-Z_0-9\s\.\-:&;]*$/', $name)) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '');
5419 $tagstart .= ($name && empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && empty($forcenowrapcolumntitle) && !dol_textishtml($name)) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '';
5420 $tagstart .= '>';
5421
5422 if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
5423 $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
5424 $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
5425 $options = preg_replace('/&+/i', '&', $options);
5426 if (!preg_match('/^&/', $options)) {
5427 $options = '&'.$options;
5428 }
5429
5430 $sortordertouseinlink = '';
5431 if ($field1 != $sortfield1) { // We are on another field than current sorted field
5432 if (preg_match('/^DESC/i', $sortorder)) {
5433 $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
5434 } else { // We reverse the var $sortordertouseinlink
5435 $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
5436 }
5437 } else { // We are on field that is the first current sorting criteria
5438 if (preg_match('/^ASC/i', $sortorder)) { // We reverse the var $sortordertouseinlink
5439 $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
5440 } else {
5441 $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
5442 }
5443 }
5444 $sortordertouseinlink = preg_replace('/,$/', '', $sortordertouseinlink);
5445 $out .= '<a class="reposition" href="'.$file.'?sortfield='.$field.'&sortorder='.$sortordertouseinlink.'&begin='.$begin.$options.'"';
5446 //$out .= (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '');
5447 $out .= '>';
5448 }
5449 if ($tooltip) {
5450 // You can also use 'TranslationString:keyfortooltiponclick' for a tooltip on click.
5451 if (preg_match('/:\w+$/', $tooltip)) {
5452 $tmptooltip = explode(':', $tooltip);
5453 } else {
5454 $tmptooltip = array($tooltip);
5455 }
5456 $out .= $form->textwithpicto($langs->trans($name), $langs->trans($tmptooltip[0]), 1, 'help', '', 0, 3, (empty($tmptooltip[1]) ? '' : 'extra_'.str_replace('.', '_', $field).'_'.$tmptooltip[1]));
5457 } else {
5458 $out .= $langs->trans($name);
5459 }
5460
5461 if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
5462 $out .= '</a>';
5463 }
5464
5465 if (empty($thead) && $field) { // If this is a sort field
5466 $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
5467 $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
5468 $options = preg_replace('/&+/i', '&', $options);
5469 if (!preg_match('/^&/', $options)) {
5470 $options = '&'.$options;
5471 }
5472
5473 if (!$sortorder || ($field1 != $sortfield1)) {
5474 //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
5475 //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
5476 } else {
5477 if (preg_match('/^DESC/', $sortorder)) {
5478 //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
5479 //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",1).'</a>';
5480 $sortimg .= '<span class="nowrap">'.img_up("Z-A", 0, 'paddingright').'</span>';
5481 }
5482 if (preg_match('/^ASC/', $sortorder)) {
5483 //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",1).'</a>';
5484 //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
5485 $sortimg .= '<span class="nowrap">'.img_down("A-Z", 0, 'paddingright').'</span>';
5486 }
5487 }
5488 }
5489
5490 $tagend = '</'.$tag.'>';
5491
5492 $out = $tagstart.$sortimg.$out.$tagend;
5493
5494 return $out;
5495}
5496
5505function print_titre($title)
5506{
5507 dol_syslog(__FUNCTION__." is deprecated", LOG_WARNING);
5508
5509 print '<div class="titre">'.$title.'</div>';
5510}
5511
5523function print_fiche_titre($title, $mesg = '', $picto = 'generic', $pictoisfullpath = 0, $id = '')
5524{
5525 print load_fiche_titre($title, $mesg, $picto, $pictoisfullpath, $id);
5526}
5527
5541function load_fiche_titre($titre, $morehtmlright = '', $picto = 'generic', $pictoisfullpath = 0, $id = '', $morecssontable = '', $morehtmlcenter = '')
5542{
5543 global $conf;
5544
5545 $return = '';
5546
5547 if ($picto == 'setup') {
5548 $picto = 'generic';
5549 }
5550
5551 $return .= "\n";
5552 $return .= '<table '.($id ? 'id="'.$id.'" ' : '').'class="centpercent notopnoleftnoright table-fiche-title'.($morecssontable ? ' '.$morecssontable : '').'">'; // maring bottom must be same than into print_barre_list
5553 $return .= '<tr class="titre">';
5554 if ($picto) {
5555 $return .= '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle widthpictotitle pictotitle"', $pictoisfullpath).'</td>';
5556 }
5557 $return .= '<td class="nobordernopadding valignmiddle col-title">';
5558 $return .= '<div class="titre inline-block">'.$titre.'</div>';
5559 $return .= '</td>';
5560 if (dol_strlen($morehtmlcenter)) {
5561 $return .= '<td class="nobordernopadding center valignmiddle col-center">'.$morehtmlcenter.'</td>';
5562 }
5563 if (dol_strlen($morehtmlright)) {
5564 $return .= '<td class="nobordernopadding titre_right wordbreakimp right valignmiddle col-right">'.$morehtmlright.'</td>';
5565 }
5566 $return .= '</tr></table>'."\n";
5567
5568 return $return;
5569}
5570
5594function print_barre_liste($titre, $page, $file, $options = '', $sortfield = '', $sortorder = '', $morehtmlcenter = '', $num = -1, $totalnboflines = '', $picto = 'generic', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limit = -1, $hideselectlimit = 0, $hidenavigation = 0, $pagenavastextinput = 0, $morehtmlrightbeforearrow = '')
5595{
5596 global $conf, $langs;
5597
5598 $savlimit = $limit;
5599 $savtotalnboflines = $totalnboflines;
5600 $totalnboflines = abs((int) $totalnboflines);
5601
5602 $page = (int) $page;
5603
5604 if ($picto == 'setup') {
5605 $picto = 'title_setup.png';
5606 }
5607 if (($conf->browser->name == 'ie') && $picto == 'generic') {
5608 $picto = 'title.gif';
5609 }
5610 if ($limit < 0) {
5611 $limit = $conf->liste_limit;
5612 }
5613
5614 if ($savlimit != 0 && (($num > $limit) || ($num == -1) || ($limit == 0))) {
5615 $nextpage = 1;
5616 } else {
5617 $nextpage = 0;
5618 }
5619 //print 'totalnboflines='.$totalnboflines.'-savlimit='.$savlimit.'-limit='.$limit.'-num='.$num.'-nextpage='.$nextpage.'-hideselectlimit='.$hideselectlimit.'-hidenavigation='.$hidenavigation;
5620
5621 print "\n";
5622 print "<!-- Begin title -->\n";
5623 print '<table class="centpercent notopnoleftnoright table-fiche-title'.($morecss ? ' '.$morecss : '').'"><tr>'; // maring bottom must be same than into load_fiche_tire
5624
5625 // Left
5626
5627 if ($picto && $titre) {
5628 print '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle pictotitle widthpictotitle"', $pictoisfullpath).'</td>';
5629 }
5630
5631 print '<td class="nobordernopadding valignmiddle col-title">';
5632 print '<div class="titre inline-block">'.$titre;
5633 if (!empty($titre) && $savtotalnboflines >= 0 && (string) $savtotalnboflines != '') {
5634 print '<span class="opacitymedium colorblack paddingleft">('.$totalnboflines.')</span>';
5635 }
5636 print '</div></td>';
5637
5638 // Center
5639 if ($morehtmlcenter && empty($conf->dol_optimize_smallscreen)) {
5640 print '<td class="nobordernopadding center valignmiddle col-center">'.$morehtmlcenter.'</td>';
5641 }
5642
5643 // Right
5644 print '<td class="nobordernopadding valignmiddle right col-right">';
5645 print '<input type="hidden" name="pageplusoneold" value="'.((int) $page + 1).'">';
5646 if ($sortfield) {
5647 $options .= "&sortfield=".urlencode($sortfield);
5648 }
5649 if ($sortorder) {
5650 $options .= "&sortorder=".urlencode($sortorder);
5651 }
5652 // Show navigation bar
5653 $pagelist = '';
5654 if ($savlimit != 0 && ($page > 0 || $num > $limit)) {
5655 if ($totalnboflines) { // If we know total nb of lines
5656 // Define nb of extra page links before and after selected page + ... + first or last
5657 $maxnbofpage = (empty($conf->dol_optimize_smallscreen) ? 4 : 0);
5658
5659 if ($limit > 0) {
5660 $nbpages = ceil($totalnboflines / $limit);
5661 } else {
5662 $nbpages = 1;
5663 }
5664 $cpt = ($page - $maxnbofpage);
5665 if ($cpt < 0) {
5666 $cpt = 0;
5667 }
5668
5669 if ($cpt >= 1) {
5670 if (empty($pagenavastextinput)) {
5671 $pagelist .= '<li class="pagination"><a href="'.$file.'?page=0'.$options.'">1</a></li>';
5672 if ($cpt > 2) {
5673 $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
5674 } elseif ($cpt == 2) {
5675 $pagelist .= '<li class="pagination"><a href="'.$file.'?page=1'.$options.'">2</a></li>';
5676 }
5677 }
5678 }
5679
5680 do {
5681 if ($pagenavastextinput) {
5682 if ($cpt == $page) {
5683 $pagelist .= '<li class="pagination"><input type="text" class="'.($totalnboflines > 100 ? 'width40' : 'width25').' center pageplusone" name="pageplusone" value="'.($page + 1).'"></li>';
5684 $pagelist .= '/';
5685 }
5686 } else {
5687 if ($cpt == $page) {
5688 $pagelist .= '<li class="pagination"><span class="active">'.($page + 1).'</span></li>';
5689 } else {
5690 $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.$cpt.$options.'">'.($cpt + 1).'</a></li>';
5691 }
5692 }
5693 $cpt++;
5694 } while ($cpt < $nbpages && $cpt <= ($page + $maxnbofpage));
5695
5696 if (empty($pagenavastextinput)) {
5697 if ($cpt < $nbpages) {
5698 if ($cpt < $nbpages - 2) {
5699 $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
5700 } elseif ($cpt == $nbpages - 2) {
5701 $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 2).$options.'">'.($nbpages - 1).'</a></li>';
5702 }
5703 $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
5704 }
5705 } else {
5706 //var_dump($page.' '.$cpt.' '.$nbpages);
5707 $pagelist .= '<li class="pagination paginationlastpage"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
5708 }
5709 } else {
5710 $pagelist .= '<li class="pagination"><span class="active">'.($page + 1)."</li>";
5711 }
5712 }
5713
5714 if ($savlimit || $morehtmlright || $morehtmlrightbeforearrow) {
5715 print_fleche_navigation($page, $file, $options, $nextpage, $pagelist, $morehtmlright, $savlimit, $totalnboflines, $hideselectlimit, $morehtmlrightbeforearrow, $hidenavigation); // output the div and ul for previous/last completed with page numbers into $pagelist
5716 }
5717
5718 // js to autoselect page field on focus
5719 if ($pagenavastextinput) {
5720 print ajax_autoselect('.pageplusone');
5721 }
5722
5723 print '</td>';
5724 print '</tr>';
5725
5726 print '</table>'."\n";
5727
5728 // Center
5729 if ($morehtmlcenter && !empty($conf->dol_optimize_smallscreen)) {
5730 print '<div class="nobordernopadding marginbottomonly center valignmiddle col-center centpercent">'.$morehtmlcenter.'</div>';
5731 }
5732
5733 print "<!-- End title -->\n\n";
5734}
5735
5752function print_fleche_navigation($page, $file, $options = '', $nextpage = 0, $betweenarrows = '', $afterarrows = '', $limit = -1, $totalnboflines = 0, $hideselectlimit = 0, $beforearrows = '', $hidenavigation = 0)
5753{
5754 global $conf, $langs;
5755
5756 print '<div class="pagination"><ul>';
5757 if ($beforearrows) {
5758 print '<li class="paginationbeforearrows">';
5759 print $beforearrows;
5760 print '</li>';
5761 }
5762
5763 if (empty($hidenavigation)) {
5764 if ((int) $limit > 0 && empty($hideselectlimit)) {
5765 $pagesizechoices = '10:10,15:15,20:20,30:30,40:40,50:50,100:100,250:250,500:500,1000:1000';
5766 $pagesizechoices .= ',5000:5000,10000:10000,20000:20000';
5767 //$pagesizechoices.=',0:'.$langs->trans("All"); // Not yet supported
5768 //$pagesizechoices.=',2:2';
5769 if (!empty($conf->global->MAIN_PAGESIZE_CHOICES)) {
5770 $pagesizechoices = $conf->global->MAIN_PAGESIZE_CHOICES;
5771 }
5772
5773 print '<li class="pagination">';
5774 print '<select class="flat selectlimit" name="limit" title="'.dol_escape_htmltag($langs->trans("MaxNbOfRecordPerPage")).'">';
5775 $tmpchoice = explode(',', $pagesizechoices);
5776 $tmpkey = $limit.':'.$limit;
5777 if (!in_array($tmpkey, $tmpchoice)) {
5778 $tmpchoice[] = $tmpkey;
5779 }
5780 $tmpkey = $conf->liste_limit.':'.$conf->liste_limit;
5781 if (!in_array($tmpkey, $tmpchoice)) {
5782 $tmpchoice[] = $tmpkey;
5783 }
5784 asort($tmpchoice, SORT_NUMERIC);
5785 foreach ($tmpchoice as $val) {
5786 $selected = '';
5787 $tmp = explode(':', $val);
5788 $key = $tmp[0];
5789 $val = $tmp[1];
5790 if ($key != '' && $val != '') {
5791 if ((int) $key == (int) $limit) {
5792 $selected = ' selected="selected"';
5793 }
5794 print '<option name="'.$key.'"'.$selected.'>'.dol_escape_htmltag($val).'</option>'."\n";
5795 }
5796 }
5797 print '</select>';
5798 if ($conf->use_javascript_ajax) {
5799 print '<!-- JS CODE TO ENABLE select limit to launch submit of page -->
5800 <script>
5801 jQuery(document).ready(function () {
5802 jQuery(".selectlimit").change(function() {
5803 console.log("Change limit. Send submit");
5804 $(this).parents(\'form:first\').submit();
5805 });
5806 });
5807 </script>
5808 ';
5809 }
5810 print '</li>';
5811 }
5812 if ($page > 0) {
5813 print '<li class="pagination paginationpage paginationpageleft"><a class="paginationprevious" href="'.$file.'?page='.($page - 1).$options.'"><i class="fa fa-chevron-left" title="'.dol_escape_htmltag($langs->trans("Previous")).'"></i></a></li>';
5814 }
5815 if ($betweenarrows) {
5816 print '<!--<div class="betweenarrows nowraponall inline-block">-->';
5817 print $betweenarrows;
5818 print '<!--</div>-->';
5819 }
5820 if ($nextpage > 0) {
5821 print '<li class="pagination paginationpage paginationpageright"><a class="paginationnext" href="'.$file.'?page='.($page + 1).$options.'"><i class="fa fa-chevron-right" title="'.dol_escape_htmltag($langs->trans("Next")).'"></i></a></li>';
5822 }
5823 if ($afterarrows) {
5824 print '<li class="paginationafterarrows">';
5825 print $afterarrows;
5826 print '</li>';
5827 }
5828 }
5829 print '</ul></div>'."\n";
5830}
5831
5832
5844function vatrate($rate, $addpercent = false, $info_bits = 0, $usestarfornpr = 0, $html = 0)
5845{
5846 $morelabel = '';
5847
5848 if (preg_match('/%/', $rate)) {
5849 $rate = str_replace('%', '', $rate);
5850 $addpercent = true;
5851 }
5852 $reg = array();
5853 if (preg_match('/\‍((.*)\‍)/', $rate, $reg)) {
5854 $morelabel = ' ('.$reg[1].')';
5855 $rate = preg_replace('/\s*'.preg_quote($morelabel, '/').'/', '', $rate);
5856 $morelabel = ' '.($html ? '<span class="opacitymedium">' : '').'('.$reg[1].')'.($html ? '</span>' : '');
5857 }
5858 if (preg_match('/\*/', $rate)) {
5859 $rate = str_replace('*', '', $rate);
5860 $info_bits |= 1;
5861 }
5862
5863 // If rate is '9/9/9' we don't change it. If rate is '9.000' we apply price()
5864 if (!preg_match('/\//', $rate)) {
5865 $ret = price($rate, 0, '', 0, 0).($addpercent ? '%' : '');
5866 } else {
5867 // TODO Split on / and output with a price2num to have clean numbers without ton of 000.
5868 $ret = $rate.($addpercent ? '%' : '');
5869 }
5870 if (($info_bits & 1) && $usestarfornpr >= 0) {
5871 $ret .= ' *';
5872 }
5873 $ret .= $morelabel;
5874 return $ret;
5875}
5876
5877
5893function price($amount, $form = 0, $outlangs = '', $trunc = 1, $rounding = -1, $forcerounding = -1, $currency_code = '')
5894{
5895 global $langs, $conf;
5896
5897 // Clean parameters
5898 if (empty($amount)) {
5899 $amount = 0; // To have a numeric value if amount not defined or = ''
5900 }
5901 $amount = (is_numeric($amount) ? $amount : 0); // Check if amount is numeric, for example, an error occured when amount value = o (letter) instead 0 (number)
5902 if ($rounding == -1) {
5903 $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
5904 }
5905 $nbdecimal = $rounding;
5906
5907 if ($outlangs === 'none') {
5908 // Use international separators
5909 $dec = '.';
5910 $thousand = '';
5911 } else {
5912 // Output separators by default (french)
5913 $dec = ',';
5914 $thousand = ' ';
5915
5916 // If $outlangs not forced, we use use language
5917 if (!is_object($outlangs)) {
5918 $outlangs = $langs;
5919 }
5920
5921 if ($outlangs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
5922 $dec = $outlangs->transnoentitiesnoconv("SeparatorDecimal");
5923 }
5924 if ($outlangs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
5925 $thousand = $outlangs->transnoentitiesnoconv("SeparatorThousand");
5926 }
5927 if ($thousand == 'None') {
5928 $thousand = '';
5929 } elseif ($thousand == 'Space') {
5930 $thousand = ' ';
5931 }
5932 }
5933 //print "outlangs=".$outlangs->defaultlang." amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
5934
5935 //print "amount=".$amount."-";
5936 $amount = str_replace(',', '.', $amount); // should be useless
5937 //print $amount."-";
5938 $datas = explode('.', $amount);
5939 $decpart = isset($datas[1]) ? $datas[1] : '';
5940 $decpart = preg_replace('/0+$/i', '', $decpart); // Supprime les 0 de fin de partie decimale
5941 //print "decpart=".$decpart."<br>";
5942 $end = '';
5943
5944 // We increase nbdecimal if there is more decimal than asked (to not loose information)
5945 if (dol_strlen($decpart) > $nbdecimal) {
5946 $nbdecimal = dol_strlen($decpart);
5947 }
5948 // Si on depasse max
5949 $max_nbdecimal = (int) str_replace('...', '', getDolGlobalString('MAIN_MAX_DECIMALS_SHOWN'));
5950 if ($trunc && $nbdecimal > $max_nbdecimal) {
5951 $nbdecimal = $max_nbdecimal;
5952 if (preg_match('/\.\.\./i', getDolGlobalString('MAIN_MAX_DECIMALS_SHOWN'))) {
5953 // Si un affichage est tronque, on montre des ...
5954 $end = '...';
5955 }
5956 }
5957
5958 // If force rounding
5959 if ((string) $forcerounding != '-1') {
5960 if ($forcerounding === 'MU') {
5961 $nbdecimal = $conf->global->MAIN_MAX_DECIMALS_UNIT;
5962 } elseif ($forcerounding === 'MT') {
5963 $nbdecimal = $conf->global->MAIN_MAX_DECIMALS_TOT;
5964 } elseif ($forcerounding >= 0) {
5965 $nbdecimal = $forcerounding;
5966 }
5967 }
5968
5969 // Format number
5970 $output = number_format($amount, $nbdecimal, $dec, $thousand);
5971 if ($form) {
5972 $output = preg_replace('/\s/', '&nbsp;', $output);
5973 $output = preg_replace('/\'/', '&#039;', $output);
5974 }
5975 // Add symbol of currency if requested
5976 $cursymbolbefore = $cursymbolafter = '';
5977 if ($currency_code && is_object($outlangs)) {
5978 if ($currency_code == 'auto') {
5979 $currency_code = $conf->currency;
5980 }
5981
5982 $listofcurrenciesbefore = array('AUD', 'CAD', 'CNY', 'COP', 'CLP', 'GBP', 'HKD', 'MXN', 'PEN', 'USD', 'CRC');
5983 $listoflanguagesbefore = array('nl_NL');
5984 if (in_array($currency_code, $listofcurrenciesbefore) || in_array($outlangs->defaultlang, $listoflanguagesbefore)) {
5985 $cursymbolbefore .= $outlangs->getCurrencySymbol($currency_code);
5986 } else {
5987 $tmpcur = $outlangs->getCurrencySymbol($currency_code);
5988 $cursymbolafter .= ($tmpcur == $currency_code ? ' '.$tmpcur : $tmpcur);
5989 }
5990 }
5991 $output = $cursymbolbefore.$output.$end.($cursymbolafter ? ' ' : '').$cursymbolafter;
5992
5993 return $output;
5994}
5995
6020function price2num($amount, $rounding = '', $option = 0)
6021{
6022 global $langs, $conf;
6023
6024 // Clean parameters
6025 if (is_null($amount)) {
6026 $amount = '';
6027 }
6028
6029 // Round PHP function does not allow number like '1,234.56' nor '1.234,56' nor '1 234,56'
6030 // Numbers must be '1234.56'
6031 // Decimal delimiter for PHP and database SQL requests must be '.'
6032 $dec = ',';
6033 $thousand = ' ';
6034 if (is_null($langs)) { // $langs is not defined, we use english values.
6035 $dec = '.';
6036 $thousand = ',';
6037 } else {
6038 if ($langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
6039 $dec = $langs->transnoentitiesnoconv("SeparatorDecimal");
6040 }
6041 if ($langs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
6042 $thousand = $langs->transnoentitiesnoconv("SeparatorThousand");
6043 }
6044 }
6045 if ($thousand == 'None') {
6046 $thousand = '';
6047 } elseif ($thousand == 'Space') {
6048 $thousand = ' ';
6049 }
6050 //print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
6051
6052 // Convert value to universal number format (no thousand separator, '.' as decimal separator)
6053 if ($option != 1) { // If not a PHP number or unknown, we change or clean format
6054 //print "\n".'PP'.$amount.' - '.$dec.' - '.$thousand.' - '.intval($amount).'<br>';
6055 if (!is_numeric($amount)) {
6056 $amount = preg_replace('/[a-zA-Z\/\\\*\‍(\‍)<>\_]/', '', $amount);
6057 }
6058
6059 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
6060 $amount = str_replace($thousand, '', $amount);
6061 }
6062
6063 // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
6064 // to format defined by LC_NUMERIC after a calculation and we want source format to be like defined by Dolibarr setup.
6065 // So if number was already a good number, it is converted into local Dolibarr setup.
6066 if (is_numeric($amount)) {
6067 // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
6068 $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
6069 $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
6070 $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
6071 $amount = number_format($amount, $nbofdec, $dec, $thousand);
6072 }
6073 //print "QQ".$amount."<br>\n";
6074
6075 // Now make replace (the main goal of function)
6076 if ($thousand != ',' && $thousand != '.') {
6077 $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
6078 }
6079
6080 $amount = str_replace(' ', '', $amount); // To avoid spaces
6081 $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
6082 $amount = str_replace($dec, '.', $amount);
6083
6084 $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
6085 }
6086 //print ' XX'.$amount.' '.$rounding;
6087
6088 // Now, $amount is a real PHP float number. We make a rounding if required.
6089 if ($rounding) {
6090 $nbofdectoround = '';
6091 if ($rounding == 'MU') {
6092 $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_UNIT;
6093 } elseif ($rounding == 'MT') {
6094 $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_TOT;
6095 } elseif ($rounding == 'MS') {
6096 $nbofdectoround = isset($conf->global->MAIN_MAX_DECIMALS_STOCK) ? $conf->global->MAIN_MAX_DECIMALS_STOCK : 5;
6097 } elseif ($rounding == 'CU') {
6098 $nbofdectoround = max($conf->global->MAIN_MAX_DECIMALS_UNIT, 8); // TODO Use param of currency
6099 } elseif ($rounding == 'CT') {
6100 $nbofdectoround = max($conf->global->MAIN_MAX_DECIMALS_TOT, 8); // TODO Use param of currency
6101 } elseif (is_numeric($rounding)) {
6102 $nbofdectoround = (int) $rounding;
6103 }
6104
6105 //print " RR".$amount.' - '.$nbofdectoround.'<br>';
6106 if (dol_strlen($nbofdectoround)) {
6107 $amount = round(is_string($amount) ? (float) $amount : $amount, $nbofdectoround); // $nbofdectoround can be 0.
6108 } else {
6109 return 'ErrorBadParameterProvidedToFunction';
6110 }
6111 //print ' SS'.$amount.' - '.$nbofdec.' - '.$dec.' - '.$thousand.' - '.$nbofdectoround.'<br>';
6112
6113 // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
6114 // to format defined by LC_NUMERIC after a calculation and we want source format to be defined by Dolibarr setup.
6115 if (is_numeric($amount)) {
6116 // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
6117 $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
6118 $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
6119 $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
6120 $amount = number_format($amount, min($nbofdec, $nbofdectoround), $dec, $thousand); // Convert amount to format with dolibarr dec and thousand
6121 }
6122 //print "TT".$amount.'<br>';
6123
6124 // Always make replace because each math function (like round) replace
6125 // with local values and we want a number that has a SQL string format x.y
6126 if ($thousand != ',' && $thousand != '.') {
6127 $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
6128 }
6129
6130 $amount = str_replace(' ', '', $amount); // To avoid spaces
6131 $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
6132 $amount = str_replace($dec, '.', $amount);
6133
6134 $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
6135 }
6136
6137 return $amount;
6138}
6139
6152function showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round = -1, $forceunitoutput = 'no', $use_short_label = 0)
6153{
6154 require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
6155
6156 if (($forceunitoutput == 'no' && $dimension < 1 / 10000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -6)) {
6157 $dimension = $dimension * 1000000;
6158 $unit = $unit - 6;
6159 } elseif (($forceunitoutput == 'no' && $dimension < 1 / 10 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -3)) {
6160 $dimension = $dimension * 1000;
6161 $unit = $unit - 3;
6162 } elseif (($forceunitoutput == 'no' && $dimension > 100000000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 6)) {
6163 $dimension = $dimension / 1000000;
6164 $unit = $unit + 6;
6165 } elseif (($forceunitoutput == 'no' && $dimension > 100000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 3)) {
6166 $dimension = $dimension / 1000;
6167 $unit = $unit + 3;
6168 }
6169 // Special case when we want output unit into pound or ounce
6170 /* TODO
6171 if ($unit < 90 && $type == 'weight' && is_numeric($forceunitoutput) && (($forceunitoutput == 98) || ($forceunitoutput == 99))
6172 {
6173 $dimension = // convert dimension from standard unit into ounce or pound
6174 $unit = $forceunitoutput;
6175 }
6176 if ($unit > 90 && $type == 'weight' && is_numeric($forceunitoutput) && $forceunitoutput < 90)
6177 {
6178 $dimension = // convert dimension from standard unit into ounce or pound
6179 $unit = $forceunitoutput;
6180 }*/
6181
6182 $ret = price($dimension, 0, $outputlangs, 0, 0, $round);
6183 $ret .= ' '.measuringUnitString(0, $type, $unit, $use_short_label, $outputlangs);
6184
6185 return $ret;
6186}
6187
6188
6201function get_localtax($vatrate, $local, $thirdparty_buyer = "", $thirdparty_seller = "", $vatnpr = 0)
6202{
6203 global $db, $conf, $mysoc;
6204
6205 if (empty($thirdparty_seller) || !is_object($thirdparty_seller)) {
6206 $thirdparty_seller = $mysoc;
6207 }
6208
6209 dol_syslog("get_localtax tva=".$vatrate." local=".$local." thirdparty_buyer id=".(is_object($thirdparty_buyer) ? $thirdparty_buyer->id : '')."/country_code=".(is_object($thirdparty_buyer) ? $thirdparty_buyer->country_code : '')." thirdparty_seller id=".$thirdparty_seller->id."/country_code=".$thirdparty_seller->country_code." thirdparty_seller localtax1_assuj=".$thirdparty_seller->localtax1_assuj." thirdparty_seller localtax2_assuj=".$thirdparty_seller->localtax2_assuj);
6210
6211 $vatratecleaned = $vatrate;
6212 $reg = array();
6213 if (preg_match('/^(.*)\s*\‍((.*)\‍)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
6214 $vatratecleaned = trim($reg[1]);
6215 $vatratecode = $reg[2];
6216 }
6217
6218 /*if ($thirdparty_buyer->country_code != $thirdparty_seller->country_code)
6219 {
6220 return 0;
6221 }*/
6222
6223 // Some test to guess with no need to make database access
6224 if ($mysoc->country_code == 'ES') { // For spain localtaxes 1 and 2, tax is qualified if buyer use local tax
6225 if ($local == 1) {
6226 if (!$mysoc->localtax1_assuj || (string) $vatratecleaned == "0") {
6227 return 0;
6228 }
6229 if ($thirdparty_seller->id == $mysoc->id) {
6230 if (!$thirdparty_buyer->localtax1_assuj) {
6231 return 0;
6232 }
6233 } else {
6234 if (!$thirdparty_seller->localtax1_assuj) {
6235 return 0;
6236 }
6237 }
6238 }
6239
6240 if ($local == 2) {
6241 //if (! $mysoc->localtax2_assuj || (string) $vatratecleaned == "0") return 0;
6242 if (!$mysoc->localtax2_assuj) {
6243 return 0; // If main vat is 0, IRPF may be different than 0.
6244 }
6245 if ($thirdparty_seller->id == $mysoc->id) {
6246 if (!$thirdparty_buyer->localtax2_assuj) {
6247 return 0;
6248 }
6249 } else {
6250 if (!$thirdparty_seller->localtax2_assuj) {
6251 return 0;
6252 }
6253 }
6254 }
6255 } else {
6256 if ($local == 1 && !$thirdparty_seller->localtax1_assuj) {
6257 return 0;
6258 }
6259 if ($local == 2 && !$thirdparty_seller->localtax2_assuj) {
6260 return 0;
6261 }
6262 }
6263
6264 // For some country MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY is forced to on.
6265 if (in_array($mysoc->country_code, array('ES'))) {
6266 $conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY = 1;
6267 }
6268
6269 // Search local taxes
6270 if (!empty($conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY)) {
6271 if ($local == 1) {
6272 if ($thirdparty_seller != $mysoc) {
6273 if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
6274 return $thirdparty_seller->localtax1_value;
6275 }
6276 } else { // i am the seller
6277 if (!isOnlyOneLocalTax($local)) { // TODO If seller is me, why not always returning this, even if there is only one locatax vat.
6278 return $conf->global->MAIN_INFO_VALUE_LOCALTAX1;
6279 }
6280 }
6281 }
6282 if ($local == 2) {
6283 if ($thirdparty_seller != $mysoc) {
6284 if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
6285 // TODO We should also return value defined on thirdparty only if defined
6286 return $thirdparty_seller->localtax2_value;
6287 }
6288 } else { // i am the seller
6289 if (in_array($mysoc->country_code, array('ES'))) {
6290 return $thirdparty_buyer->localtax2_value;
6291 } else {
6292 return $conf->global->MAIN_INFO_VALUE_LOCALTAX2;
6293 }
6294 }
6295 }
6296 }
6297
6298 // By default, search value of local tax on line of common tax
6299 $sql = "SELECT t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
6300 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
6301 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($thirdparty_seller->country_code)."'";
6302 $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
6303 if (!empty($vatratecode)) {
6304 $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; // If we have the code, we use it in priority
6305 } else {
6306 $sql .= " AND t.recuperableonly = '".$db->escape($vatnpr)."'";
6307 }
6308
6309 $resql = $db->query($sql);
6310
6311 if ($resql) {
6312 $obj = $db->fetch_object($resql);
6313 if ($obj) {
6314 if ($local == 1) {
6315 return $obj->localtax1;
6316 } elseif ($local == 2) {
6317 return $obj->localtax2;
6318 }
6319 }
6320 }
6321
6322 return 0;
6323}
6324
6325
6334function isOnlyOneLocalTax($local)
6335{
6336 $tax = get_localtax_by_third($local);
6337
6338 $valors = explode(":", $tax);
6339
6340 if (count($valors) > 1) {
6341 return false;
6342 } else {
6343 return true;
6344 }
6345}
6346
6354{
6355 global $db, $mysoc;
6356
6357 $sql = " SELECT t.localtax".$local." as localtax";
6358 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t INNER JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = t.fk_pays";
6359 $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND t.active = 1 AND t.taux = (";
6360 $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";
6361 $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND tt.active = 1)";
6362 $sql .= " AND t.localtax".$local."_type <> '0'";
6363 $sql .= " ORDER BY t.rowid DESC";
6364
6365 $resql = $db->query($sql);
6366 if ($resql) {
6367 $obj = $db->fetch_object($resql);
6368 if ($obj) {
6369 return $obj->localtax;
6370 } else {
6371 return '0';
6372 }
6373 }
6374
6375 return 'Error';
6376}
6377
6378
6390function getTaxesFromId($vatrate, $buyer = null, $seller = null, $firstparamisid = 1)
6391{
6392 global $db, $mysoc;
6393
6394 dol_syslog("getTaxesFromId vat id or rate = ".$vatrate);
6395
6396 // Search local taxes
6397 $sql = "SELECT t.rowid, t.code, t.taux as rate, t.recuperableonly as npr, t.accountancy_code_sell, t.accountancy_code_buy,";
6398 $sql .= " t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type";
6399 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
6400 if ($firstparamisid) {
6401 $sql .= " WHERE t.rowid = ".(int) $vatrate;
6402 } else {
6403 $vatratecleaned = $vatrate;
6404 $vatratecode = '';
6405 $reg = array();
6406 if (preg_match('/^(.*)\s*\‍((.*)\‍)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
6407 $vatratecleaned = $reg[1];
6408 $vatratecode = $reg[2];
6409 }
6410
6411 $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
6412 /*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 ??
6413 else $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";*/
6414 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";
6415 $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
6416 if ($vatratecode) {
6417 $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
6418 }
6419 }
6420
6421 $resql = $db->query($sql);
6422 if ($resql) {
6423 $obj = $db->fetch_object($resql);
6424 if ($obj) {
6425 return array(
6426 'rowid'=>$obj->rowid,
6427 'code'=>$obj->code,
6428 'rate'=>$obj->rate,
6429 'localtax1'=>$obj->localtax1,
6430 'localtax1_type'=>$obj->localtax1_type,
6431 'localtax2'=>$obj->localtax2,
6432 'localtax2_type'=>$obj->localtax2_type,
6433 'npr'=>$obj->npr,
6434 'accountancy_code_sell'=>$obj->accountancy_code_sell,
6435 'accountancy_code_buy'=>$obj->accountancy_code_buy
6436 );
6437 } else {
6438 return array();
6439 }
6440 } else {
6441 dol_print_error($db);
6442 }
6443
6444 return array();
6445}
6446
6463function getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid = 0)
6464{
6465 global $db, $mysoc;
6466
6467 dol_syslog("getLocalTaxesFromRate vatrate=".$vatrate." local=".$local);
6468
6469 // Search local taxes
6470 $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";
6471 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
6472 if ($firstparamisid) {
6473 $sql .= " WHERE t.rowid = ".(int) $vatrate;
6474 } else {
6475 $vatratecleaned = $vatrate;
6476 $vatratecode = '';
6477 $reg = array();
6478 if (preg_match('/^(.*)\s*\‍((.*)\‍)$/', $vatrate, $reg)) { // If vat is "x.x (yy)"
6479 $vatratecleaned = $reg[1];
6480 $vatratecode = $reg[2];
6481 }
6482
6483 $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
6484 if (!empty($mysoc) && $mysoc->country_code == 'ES') {
6485 $countrycodetouse = ((empty($buyer) || empty($buyer->country_code)) ? $mysoc->country_code : $buyer->country_code);
6486 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($countrycodetouse)."'"; // local tax in spain use the buyer country ??
6487 } else {
6488 $countrycodetouse = ((empty($seller) || empty($seller->country_code)) ? $mysoc->country_code : $seller->country_code);
6489 $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($countrycodetouse)."'";
6490 }
6491 $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
6492 if ($vatratecode) {
6493 $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
6494 }
6495 }
6496
6497 $resql = $db->query($sql);
6498 if ($resql) {
6499 $obj = $db->fetch_object($resql);
6500
6501 if ($obj) {
6502 $vateratestring = $obj->rate.($obj->code ? ' ('.$obj->code.')' : '');
6503
6504 if ($local == 1) {
6505 return array($obj->localtax1_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
6506 } elseif ($local == 2) {
6507 return array($obj->localtax2_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
6508 } else {
6509 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);
6510 }
6511 }
6512 }
6513
6514 return array();
6515}
6516
6527function get_product_vat_for_country($idprod, $thirdpartytouse, $idprodfournprice = 0)
6528{
6529 global $db, $conf, $mysoc;
6530
6531 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
6532
6533 $ret = 0;
6534 $found = 0;
6535
6536 if ($idprod > 0) {
6537 // Load product
6538 $product = new Product($db);
6539 $product->fetch($idprod);
6540
6541 if ($mysoc->country_code == $thirdpartytouse->country_code) {
6542 // If country to consider is ours
6543 if ($idprodfournprice > 0) { // We want vat for product for a "supplier" object
6544 $result = $product->get_buyprice($idprodfournprice, 0, 0, 0);
6545 if ($result > 0) {
6546 $ret = $product->vatrate_supplier;
6547 if ($product->default_vat_code_supplier) {
6548 $ret .= ' ('.$product->default_vat_code_supplier.')';
6549 }
6550 $found = 1;
6551 }
6552 }
6553 if (!$found) {
6554 $ret = $product->tva_tx; // Default sales vat of product
6555 if ($product->default_vat_code) {
6556 $ret .= ' ('.$product->default_vat_code.')';
6557 }
6558 $found = 1;
6559 }
6560 } else {
6561 // TODO Read default product vat according to product and another countrycode.
6562 // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
6563 }
6564 }
6565
6566 if (!$found) {
6567 if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) {
6568 // 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).
6569 $sql = "SELECT t.taux as vat_rate, t.code as default_vat_code";
6570 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
6571 $sql .= " WHERE t.active = 1 AND t.fk_pays = c.rowid AND c.code = '".$db->escape($thirdpartytouse->country_code)."'";
6572 $sql .= " ORDER BY t.use_default DESC, t.taux DESC, t.code ASC, t.recuperableonly ASC";
6573 $sql .= $db->plimit(1);
6574
6575 $resql = $db->query($sql);
6576 if ($resql) {
6577 $obj = $db->fetch_object($resql);
6578 if ($obj) {
6579 $ret = $obj->vat_rate;
6580 if ($obj->default_vat_code) {
6581 $ret .= ' ('.$obj->default_vat_code.')';
6582 }
6583 }
6584 $db->free($resql);
6585 } else {
6586 dol_print_error($db);
6587 }
6588 } else {
6589 // Forced value if autodetect fails. MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS can be
6590 // '1.23'
6591 // or '1.23 (CODE)'
6592 $defaulttx = '';
6593 if ($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS != 'none') {
6594 $defaulttx = $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS;
6595 }
6596 /*if (preg_match('/\‍((.*)\‍)/', $defaulttx, $reg)) {
6597 $defaultcode = $reg[1];
6598 $defaulttx = preg_replace('/\s*\‍(.*\‍)/', '', $defaulttx);
6599 }*/
6600
6601 $ret = $defaulttx;
6602 }
6603 }
6604
6605 dol_syslog("get_product_vat_for_country: ret=".$ret);
6606 return $ret;
6607}
6608
6618function get_product_localtax_for_country($idprod, $local, $thirdpartytouse)
6619{
6620 global $db, $mysoc;
6621
6622 if (!class_exists('Product')) {
6623 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
6624 }
6625
6626 $ret = 0;
6627 $found = 0;
6628
6629 if ($idprod > 0) {
6630 // Load product
6631 $product = new Product($db);
6632 $result = $product->fetch($idprod);
6633
6634 if ($mysoc->country_code == $thirdpartytouse->country_code) { // If selling country is ours
6635 /* Not defined yet, so we don't use this
6636 if ($local==1) $ret=$product->localtax1_tx;
6637 elseif ($local==2) $ret=$product->localtax2_tx;
6638 $found=1;
6639 */
6640 } else {
6641 // TODO Read default product vat according to product and another countrycode.
6642 // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
6643 }
6644 }
6645
6646 if (!$found) {
6647 // If vat of product for the country not found or not defined, we return higher vat of country.
6648 $sql = "SELECT taux as vat_rate, localtax1, localtax2";
6649 $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
6650 $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$db->escape($thirdpartytouse->country_code)."'";
6651 $sql .= " ORDER BY t.taux DESC, t.recuperableonly ASC";
6652 $sql .= $db->plimit(1);
6653
6654 $resql = $db->query($sql);
6655 if ($resql) {
6656 $obj = $db->fetch_object($resql);
6657 if ($obj) {
6658 if ($local == 1) {
6659 $ret = $obj->localtax1;
6660 } elseif ($local == 2) {
6661 $ret = $obj->localtax2;
6662 }
6663 }
6664 } else {
6665 dol_print_error($db);
6666 }
6667 }
6668
6669 dol_syslog("get_product_localtax_for_country: ret=".$ret);
6670 return $ret;
6671}
6672
6689function