dolibarr 25.0.0-alpha
main.inc.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2002-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2003 Xavier Dutoit <doli@sydesy.com>
4 * Copyright (C) 2004-2021 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) 2005-2021 Regis Houssin <regis.houssin@inodbox.com>
8 * Copyright (C) 2011-2014 Philippe Grand <philippe.grand@atoo-net.com>
9 * Copyright (C) 2008 Matteli
10 * Copyright (C) 2011-2016 Juanjo Menent <jmenent@2byte.es>
11 * Copyright (C) 2012 Christophe Battarel <christophe.battarel@altairis.fr>
12 * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
13 * Copyright (C) 2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
14 * Copyright (C) 2020 Demarest Maxime <maxime@indelog.fr>
15 * Copyright (C) 2020-2024 Charlene Benke <charlene@patas-monkey.com>
16 * Copyright (C) 2021-2026 Frédéric France <frederic.france@free.fr>
17 * Copyright (C) 2021 Alexandre Spangaro <aspangaro@open-dsi.fr>
18 * Copyright (C) 2023 Joachim Küter <git-jk@bloxera.com>
19 * Copyright (C) 2023 Eric Seigne <eric.seigne@cap-rel.fr>
20 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
21 * Copyright (C) 2026 William Mead <william@m34d.com>
22 * Copyright (C) 2026 Jose MARTINEZ <jose.martinez@pichinov.com>
23 *
24 * This program is free software; you can redistribute it and/or modify
25 * it under the terms of the GNU General Public License as published by
26 * the Free Software Foundation; either version 3 of the License, or
27 * (at your option) any later version.
28 *
29 * This program is distributed in the hope that it will be useful,
30 * but WITHOUT ANY WARRANTY; without even the implied warranty of
31 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
32 * GNU General Public License for more details.
33 *
34 * You should have received a copy of the GNU General Public License
35 * along with this program. If not, see <https://www.gnu.org/licenses/>.
36 */
37
44//@ini_set('memory_limit', '128M'); // This may be useless if memory is hard limited by your PHP
45
46// For optional tuning. Enabled if environment variable MAIN_SHOW_TUNING_INFO is defined.
47$micro_start_time = 0; // Used as global var into printCommonFooter()
48if (!empty($_SERVER['MAIN_SHOW_TUNING_INFO'])) {
49 [$usec, $sec] = explode(" ", microtime());
50 $micro_start_time = ((float) $usec + (float) $sec);
51 // Add Xdebug code coverage
52 //define('XDEBUGCOVERAGE',1);
53 if (defined('XDEBUGCOVERAGE')) {
54 xdebug_start_code_coverage();
55 }
56}
57
58require __DIR__.'/waf.inc.php';
59
60// Check consistency of NOREQUIREXXX DEFINES
61if ((defined('NOREQUIREDB') || defined('NOREQUIRETRAN')) && !defined('NOREQUIREMENU')) {
62 print 'If define NOREQUIREDB or NOREQUIRETRAN are set, you must also set NOREQUIREMENU or not set them.';
63 exit;
64}
65if (defined('NOREQUIREUSER') && !defined('NOREQUIREMENU')) {
66 print 'If define NOREQUIREUSER is set, you must also set NOREQUIREMENU or not set it.';
67 exit;
68}
69
70// This is to make Dolibarr working with Plesk
71if (!empty($_SERVER['DOCUMENT_ROOT']) && substr($_SERVER['DOCUMENT_ROOT'], -6) !== 'htdocs') {
72 set_include_path($_SERVER['DOCUMENT_ROOT'].'/htdocs');
73}
74
75// Include the conf.php and functions.lib.php and security.lib.php. This defined the constants like DOL_DOCUMENT_ROOT, DOL_DATA_ROOT, DOL_URL_ROOT...
76require_once 'filefunc.inc.php';
91include_once DOL_DOCUMENT_ROOT.'/blockedlog/lib/securitycore.lib.php';
92
93// If there is a POST parameter to tell to save automatically some POST parameters into cookies, we do it.
94// This is used for example by form of boxes to save personalization of some options.
95// DOL_AUTOSET_COOKIE=cookiename:val1,val2 and cookiename_val1=aaa cookiename_val2=bbb will set cookie_name with value json_encode(array('val1'=> , ))
96if (GETPOST("DOL_AUTOSET_COOKIE")) {
97 $tmpautoset = explode(':', GETPOST("DOL_AUTOSET_COOKIE"), 2);
98 $tmplist = explode(',', $tmpautoset[1]);
99 $cookiearrayvalue = array();
100 foreach ($tmplist as $tmpkey) {
101 $postkey = $tmpautoset[0].'_'.$tmpkey;
102 //var_dump('tmpkey='.$tmpkey.' postkey='.$postkey.' value='.GETPOST($postkey);
103 if (GETPOST($postkey)) {
104 $cookiearrayvalue[$tmpkey] = GETPOST($postkey);
105 }
106 }
107 $cookiename = $tmpautoset[0];
108 $cookievalue = json_encode($cookiearrayvalue);
109
110 dolSetCookie($cookiename, $cookievalue);
111}
112
113// Set the handler of session
114// if (ini_get('session.save_handler') == 'user')
115if (!empty($php_session_save_handler) && $php_session_save_handler == 'db') {
116 require_once 'core/lib/phpsessionin'.$php_session_save_handler.'.lib.php';
117}
118
119// Init session. Name of session is specific to Dolibarr instance.
120// Must be done after the include of filefunc.inc.php so global variables of conf file are defined (like $dolibarr_main_instance_unique_id or $dolibarr_main_force_https).
121// Note: the function dol_getprefix() is defined into functions.lib.php but may have been defined to return a different key to manage another area to protect.
122$prefix = dol_getprefix('');
123$sessionname = 'DOLSESSID_'.$prefix;
124$sessiontimeout = 'DOLSESSTIMEOUT_'.$prefix;
125if (!empty($_COOKIE[$sessiontimeout])) {
126 ini_set('session.gc_maxlifetime', max(120, min(3600 * 24, (int) $_COOKIE[$sessiontimeout]))); // Between 120 and 86400
127}
128
129// This create lock, released by session_write_close() or end of page.
130// We need this lock as long as we read/write $_SESSION ['vars']. We can remove lock when finished.
131if (!defined('NOSESSION')) {
132 if (PHP_VERSION_ID < 70300) {
133 session_set_cookie_params(0, '/', null, !(empty($dolibarr_main_force_https) && isHTTPS() === false), true); // Add tag secure and httponly on session cookie (same as setting session.cookie_httponly into php.ini). Must be called before the session_start.
134 } else {
135 // Only available for php >= 7.3
136 $sessioncookieparams = array(
137 'lifetime' => 0,
138 'path' => '/',
139 //'domain' => '.mywebsite.com', // the dot at the beginning allows compatibility with subdomains
140 'secure' => !(empty($dolibarr_main_force_https) && isHTTPS() === false),
141 'httponly' => true,
142 'samesite' => 'Lax' // None || Lax || Strict
143 );
144 session_set_cookie_params($sessioncookieparams);
145 }
146 session_name($sessionname);
147 dol_session_start(); // This call the open and read of session handler
148 //exit; // this exist generates a call to write and close
149}
150
151
152// Init the 7 global objects, this include will make the 'new Xxx()' and set properties for: $conf, $db, $langs, $user, $mysoc, $hookmanager, $extrafields
153require_once 'master.inc.php';
165'
166@phan-var-force Conf $conf
167@phan-var-force ?DoliDB $db
168@phan-var-force ?HookManager $hookmanager
169@phan-var-force ?Translate $langs
170@phan-var-force ?User $user
171';
172
173// Uncomment this and set session.save_handler = user to use local session storing
174// include DOL_DOCUMENT_ROOT.'/core/lib/phpsessionindb.inc.php
175
176// If software has been locked. Only login getDolGlobalString('MAIN_ONLY_LOGIN_ALLOWED') is allowed.
177if (getDolGlobalString('MAIN_ONLY_LOGIN_ALLOWED')) {
178 $ok = 0;
179 if ((!session_id() || !isset($_SESSION["dol_login"])) && !isset($_POST["username"]) && !empty($_SERVER["GATEWAY_INTERFACE"])) {
180 $ok = 1; // We let working pages if not logged and inside a web browser (login form, to allow login by admin)
181 } elseif (isset($_POST["username"]) && in_array($_POST["username"], explode(';', getDolGlobalString('MAIN_ONLY_LOGIN_ALLOWED')))) {
182 $ok = 1; // We let working pages that is a login submission (login submit, to allow login by admin)
183 } elseif (defined('NOREQUIREDB')) {
184 $ok = 1; // We let working pages that don't need database access (xxx.css.php)
185 } elseif (defined('EVEN_IF_ONLY_LOGIN_ALLOWED')) {
186 $ok = 1; // We let working pages that ask to work even if only login enabled (logout.php)
187 } elseif (session_id() && isset($_SESSION["dol_login"]) && in_array($_SESSION["dol_login"], explode(';', getDolGlobalString('MAIN_ONLY_LOGIN_ALLOWED')))) {
188 $ok = 1; // We let working if user is allowed admin
189 }
190 if (!$ok) {
191 if (session_id() && isset($_SESSION["dol_login"]) && !in_array($_SESSION["dol_login"], explode(';', getDolGlobalString('MAIN_ONLY_LOGIN_ALLOWED')))) {
192 print 'Sorry, your application is offline.'."\n";
193 print 'You are logged with user "'.$_SESSION["dol_login"].'" and only administrator users (' . str_replace(';', ', ', getDolGlobalString('MAIN_ONLY_LOGIN_ALLOWED')).') is allowed to connect for the moment.'."\n";
194 $nexturl = dolBuildUrl(DOL_URL_ROOT . '/user/logout.php', [], true);
195 print 'Please try later or <a href="'.$nexturl.'">click here to disconnect and change login user</a>...'."\n";
196 } else {
197 print 'Sorry, your application is offline. Only administrator users (' . str_replace(';', ', ', getDolGlobalString('MAIN_ONLY_LOGIN_ALLOWED')).') is allowed to connect for the moment.'."\n";
198 $nexturl = dolBuildUrl(DOL_URL_ROOT . '/');
199 print 'Please try later or <a href="'.$nexturl.'">click here to change login user</a>...'."\n";
200 }
201 exit;
202 }
203}
204
205
206// Activate end of page function
207register_shutdown_function('dol_shutdown');
208
209// Load debugbar
210if (isModEnabled('debugbar') && !GETPOST('dol_use_jmobile') && empty($_SESSION['dol_use_jmobile'])) {
211 global $debugbar;
212 include_once DOL_DOCUMENT_ROOT.'/debugbar/class/DebugBar.php';
213 $debugbar = new DolibarrDebugBar();
214 $renderer = $debugbar->getJavascriptRenderer();
215 if (!getDolGlobalString('MAIN_HTML_HEADER')) {
216 $conf->global->MAIN_HTML_HEADER = '';
217 }
218 $conf->global->MAIN_HTML_HEADER .= $renderer->renderHead();
219
220 '@phan-var-force array{time:DebugBar\DataCollector\TimeDataCollector} $debugbar';
221 $debugbar['time']->startMeasure('pageaftermaster', 'Page generation (after environment init)');
222}
223
224// Detection browser. A request without User-Agent header (script, monitoring tool...) gets the
225// default values ('unknown' browser, 'classic' layout), so $conf->browser is always complete.
226$tmp = getBrowserInfo((string) ($_SERVER["HTTP_USER_AGENT"] ?? ''));
227$conf->browser->name = $tmp['browsername'];
228$conf->browser->os = $tmp['browseros'];
229$conf->browser->version = $tmp['browserversion'];
230$conf->browser->ua = $tmp['browserua'];
231$conf->browser->layout = $tmp['layout']; // 'classic', 'phone', 'tablet'
232//var_dump($conf->browser);
233
234if ($conf->browser->layout == 'phone') {
235 $conf->dol_no_mouse_hover = 1;
236}
237
238// If theme is forced
239if (GETPOST('theme', 'aZ09')) {
240 $conf->theme = GETPOST('theme', 'aZ09');
241 $conf->css = "/theme/".$conf->theme."/style.css.php";
242}
243
244// Set global MAIN_OPTIMIZEFORTEXTBROWSER (must be before login part)
245if (GETPOSTINT('textbrowser') || (!empty($conf->browser->name) && $conf->browser->name == 'textbrowser')) { // If we must enable text browser
246 $conf->global->MAIN_OPTIMIZEFORTEXTBROWSER = 2;
247}
248
249// Force HTTPS if required ($conf->file->main_force_https is 0/1 or 'https dolibarr root url')
250// $_SERVER["HTTPS"] is 'on' when link is https, otherwise $_SERVER["HTTPS"] is empty or 'off'
251if (!empty($conf->file->main_force_https) && !isHTTPS() && !defined('NOHTTPSREDIRECT')) {
252 $newurl = '';
253 if (is_numeric($conf->file->main_force_https)) {
254 if ($conf->file->main_force_https == '1' && !empty($_SERVER["SCRIPT_URI"])) { // If SCRIPT_URI supported by server
255 if (preg_match('/^http:/i', $_SERVER["SCRIPT_URI"]) && !preg_match('/^https:/i', $_SERVER["SCRIPT_URI"])) { // If link is http
256 $newurl = preg_replace('/^http:/i', 'https:', $_SERVER["SCRIPT_URI"]);
257 }
258 } else {
259 // If HTTPS is not defined in DOL_MAIN_URL_ROOT,
260 // Check HTTPS environment variable (Apache/mod_ssl only)
261 $newurl = preg_replace('/^http:/i', 'https:', DOL_MAIN_URL_ROOT).$_SERVER["REQUEST_URI"];
262 }
263 } else {
264 // Check HTTPS environment variable (Apache/mod_ssl only)
265 $newurl = $conf->file->main_force_https.$_SERVER["REQUEST_URI"];
266 }
267 // Start redirect
268 if ($newurl) {
269 header_remove(); // Clean header already set to be sure to remove any header like "Set-Cookie: DOLSESSID_..." from non HTTPS answers
270 dol_syslog("main.inc: dolibarr_main_force_https is on, we make a redirect to ".$newurl);
271 header("Location: ".$newurl);
272 exit;
273 } else {
274 dol_syslog("main.inc: dolibarr_main_force_https is on but we failed to forge new https url so no redirect is done", LOG_WARNING);
275 }
276}
277
278if (!defined('NOLOGIN') && !defined('NOIPCHECK') && !empty($dolibarr_main_restrict_ip)) {
279 $listofip = explode(',', $dolibarr_main_restrict_ip);
280 $found = false;
281 $user_ip = $_SERVER['REMOTE_ADDR'];
282 foreach ($listofip as $ip) {
283 $authorized_ip = trim($ip);
284 if (strpos($authorized_ip, '/')) { // Check if IP with CIDR notation
285 if (checkIPInCidr($user_ip, $authorized_ip) > 0) {
286 $found = true;
287 break;
288 }
289 } elseif ($user_ip == $authorized_ip) {
290 $found = true;
291 break;
292 }
293 }
294 if (!$found) {
295 print 'Access refused by IP protection. Your detected IP is: '.dol_escape_htmltag($user_ip);
296 exit;
297 }
298}
299
300// Loading of additional presentation includes
301if (!defined('NOREQUIREHTML')) {
302 require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; // Need 660ko memory (800ko in 2.2)
303}
304if (!defined('NOREQUIREAJAX')) {
305 require_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; // Need 22ko memory
306}
307
308// If install or upgrade process not done or not completely finished, we call the install page.
309if (getDolGlobalString('MAIN_NOT_INSTALLED') || getDolGlobalString('MAIN_NOT_UPGRADED')) {
310 dol_syslog("main.inc: A previous install or upgrade was not complete. Redirect to install page.", LOG_WARNING);
311 header("Location: ".DOL_URL_ROOT."/install/index.php");
312 exit;
313}
314// If an upgrade process is required, we call the install page.
315$checkifupgraderequired = false;
316if (getDolGlobalString('MAIN_VERSION_LAST_UPGRADE') && getDolGlobalString('MAIN_VERSION_LAST_UPGRADE') != DOL_VERSION) {
317 $checkifupgraderequired = true;
318}
319if (!getDolGlobalString('MAIN_VERSION_LAST_UPGRADE') && getDolGlobalString('MAIN_VERSION_LAST_INSTALL') && getDolGlobalString('MAIN_VERSION_LAST_INSTALL') != DOL_VERSION) {
320 $checkifupgraderequired = true;
321}
322if ($checkifupgraderequired && !defined('MAIN_VERSION_DISABLE_DB_CHECK')) {
323 $versiontocompare = getDolGlobalString('MAIN_VERSION_LAST_UPGRADE', getDolGlobalString('MAIN_VERSION_LAST_INSTALL'));
324 require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
325 $dolibarrversionlastupgrade = preg_split('/[.-]/', $versiontocompare);
326 $dolibarrversionprogram = preg_split('/[.-]/', DOL_VERSION);
327 $rescomp = versioncompare($dolibarrversionprogram, $dolibarrversionlastupgrade);
328 if ($rescomp > 0) { // Programs have a version higher than database.
329 if (!getDolGlobalString('MAIN_NO_UPGRADE_REDIRECT_ON_LEVEL_3_CHANGE') || $rescomp < 3) {
330 // We did not add "&& $rescomp < 3" because we want upgrade process for build upgrades
331 dol_syslog("main.inc: database version ".$versiontocompare." is lower than programs version ".DOL_VERSION.". Redirect to install/upgrade page.", LOG_WARNING);
332 if (php_sapi_name() === "cli") {
333 print "main.inc: database version ".$versiontocompare." is lower than programs version ".DOL_VERSION.". Try to run upgrade process.\n";
334 } else {
335 header("Location: ".DOL_URL_ROOT."/install/index.php");
336 }
337 exit;
338 }
339 }
340}
341
342// Creation of a token against CSRF vulnerabilities
343if (!defined('NOTOKENRENEWAL') && !defined('NOSESSION')) {
344 // No token renewal on .css.php, .js.php and .json.php (even if the NOTOKENRENEWAL was not provided)
345 if (!preg_match('/\.(css|js|json)\.php$/', $_SERVER["PHP_SELF"])) {
346 // Rolling token at each call ($_SESSION['token'] contains token of previous page)
347 if (isset($_SESSION['newtoken'])) {
348 $_SESSION['token'] = $_SESSION['newtoken'];
349 }
350
351 if (!isset($_SESSION['newtoken']) || getDolGlobalInt('MAIN_SECURITY_CSRF_TOKEN_RENEWAL_ON_EACH_CALL')) {
352 // Note: Using MAIN_SECURITY_CSRF_TOKEN_RENEWAL_ON_EACH_CALL is not recommended: if a user succeed in entering a data from
353 // a public page with a link that make a token regeneration, it can make use of the backoffice no more possible !
354 // Save in $_SESSION['newtoken'] what will be next token. Into forms, we will add param token = $_SESSION['newtoken']
355 $token = bin2hex(random_bytes(32));
356 $_SESSION['newtoken'] = $token;
357 dol_syslog("NEW TOKEN generated by : ".$_SERVER['PHP_SELF'], LOG_DEBUG);
358 }
359 }
360}
361
362//dol_syslog("CSRF info: ".defined('NOCSRFCHECK')." - ".$dolibarr_nocsrfcheck." - ".getDolGlobalString('MAIN_SECURITY_CSRF_WITH_TOKEN')." - ".$_SERVER['REQUEST_METHOD']." - ".GETPOST('token', 'alpha'));
363
364// Check validity of token, only if option MAIN_SECURITY_CSRF_WITH_TOKEN enabled or if constant CSRFCHECK_WITH_TOKEN is set into page
365if ((!defined('NOCSRFCHECK') && empty($dolibarr_nocsrfcheck) && getDolGlobalInt('MAIN_SECURITY_CSRF_WITH_TOKEN')) || defined('CSRFCHECK_WITH_TOKEN')) {
366 $tmpaction = GETPOST('action', 'aZ09');
367 // Array of action code where CSRFCHECK with token will be forced (so token must be provided on url request)
368 $sensitiveget = false;
369 if ((GETPOSTISSET('massaction') || $tmpaction) && getDolGlobalInt('MAIN_SECURITY_CSRF_WITH_TOKEN') >= 3) {
370 // All GET actions (except the listed exceptions that are usually post for pre-actions and not real action) and mass actions are processed as sensitive.
371 // We exclude some action that are not sensitive so legitimate
372 $legitimate_actions = array(
373 'check',
374 'create',
375 'create2',
376 'createsite',
377 'createcard',
378 'edit',
379 'editcss',
380 'editcontract',
381 'editfile',
382 'editsecurity',
383 'editvalidator',
384 'file_manager',
385 'getCategories',
386 'history',
387 'presend',
388 'presend_addmessage',
389 'preview',
390 'reconcile',
391 'showsummary',
392 'specimen',
393 'testsetup',
394 'undeployconfirmed',
395 'validatenewpassword',
396 'view'
397 );
398 if (GETPOSTISSET('massaction') || (strpos($tmpaction, 'display') !== 0 && !in_array($tmpaction, $legitimate_actions))) {
399 // Note: 'create' is for form to ask creattion, realcreation is action 'add'
400 // Note: 'check' if for the feature to control an archive.
401 $sensitiveget = true;
402 }
403 } elseif (getDolGlobalInt('MAIN_SECURITY_CSRF_WITH_TOKEN') >= 2) {
404 // We need a valid token for action that are strictly equals to these values.
405 $arrayofactiontoforcetokencheck = array(
406 'activate',
407 'doprev', 'donext', 'dvprev', 'dvnext',
408 'freezone', 'install',
409 'reopen', 'swapstatut'
410 );
411 if (in_array($tmpaction, $arrayofactiontoforcetokencheck)) {
412 $sensitiveget = true;
413 }
414 // We also need a valid token for actions matching one of these values
415 if (preg_match('/^(confirm_)?(add|classify|close|confirm|copy|del|disable|enable|remove|set|unset|update|save)/', $tmpaction)) {
416 $sensitiveget = true;
417 }
418 }
419
420 // Check a token is provided for all cases that need a mandatory token
421 // (all POST actions + all sensitive GET actions + all mass actions + all login/actions/logout on pages with CSRFCHECK_WITH_TOKEN set)
422 if (
423 (!empty($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == 'POST') ||
424 $sensitiveget ||
425 GETPOSTISSET('massaction') ||
426 ((GETPOSTISSET('actionlogin') || GETPOSTISSET('action')) && defined('CSRFCHECK_WITH_TOKEN'))
427 ) {
428 // If token is not provided or empty, error (we are in case it is mandatory)
429 if (!GETPOST('token', 'alpha') || GETPOST('token', 'alpha') == 'notrequired') {
430 top_httphead();
431 if (GETPOSTINT('uploadform')) {
432 dol_syslog("--- Access to ".(empty($_SERVER["REQUEST_METHOD"]) ? '' : $_SERVER["REQUEST_METHOD"].' ').$_SERVER["PHP_SELF"]." refused. File size too large or not provided.");
433 $langs->loadLangs(array("errors", "install"));
434 print $langs->trans("ErrorFileSizeTooLarge").' ';
435 print $langs->trans("ErrorGoBackAndCorrectParameters");
436 } else {
437 http_response_code(403);
438 if (defined('CSRFCHECK_WITH_TOKEN')) {
439 dol_syslog("--- Access to ".(empty($_SERVER["REQUEST_METHOD"]) ? '' : $_SERVER["REQUEST_METHOD"].' ').$_SERVER["PHP_SELF"]." refused by CSRF protection (CSRFCHECK_WITH_TOKEN protection) in main.inc.php. Token not provided.", LOG_WARNING);
440 print "Access to a page that needs a token (constant CSRFCHECK_WITH_TOKEN is defined) is refused by CSRF protection in main.inc.php. Token not provided.\n";
441 } else {
442 dol_syslog("--- Access to ".(empty($_SERVER["REQUEST_METHOD"]) ? '' : $_SERVER["REQUEST_METHOD"].' ').$_SERVER["PHP_SELF"]." refused by CSRF protection (POST method or GET with a sensible value for 'action' parameter) in main.inc.php. Token not provided.", LOG_WARNING);
443 print "Access to this page this way (POST method or GET with a sensible value for 'action' parameter) is refused by CSRF protection in main.inc.php. Token not provided.\n";
444 print "If you access your server behind a proxy using url rewriting and the parameter is provided by caller, you might check that all HTTP header are propagated (or add the line \$dolibarr_nocsrfcheck=1 into your conf.php file or MAIN_SECURITY_CSRF_WITH_TOKEN to 0";
445 if (getDolGlobalString('MAIN_SECURITY_CSRF_WITH_TOKEN')) {
446 print " instead of " . getDolGlobalString('MAIN_SECURITY_CSRF_WITH_TOKEN');
447 }
448 print " into setup).\n";
449 }
450 }
451 die;
452 }
453 }
454
455 $sessiontokenforthisurl = (empty($_SESSION['token']) ? '' : $_SESSION['token']);
456 // TODO Get the sessiontokenforthisurl into an array of session token (one array per base URL so we can use the CSRF per page and we keep ability for several tabs per url in a browser)
457 if (GETPOSTISSET('token') && GETPOST('token') != 'notrequired' && !hash_equals((string) $sessiontokenforthisurl, (string) GETPOST('token', 'alpha'))) {
458 dol_syslog("--- Access to ".(empty($_SERVER["REQUEST_METHOD"]) ? '' : $_SERVER["REQUEST_METHOD"].' ').$_SERVER["PHP_SELF"]." refused by CSRF protection (invalid token), so we disable POST and some GET parameters - referrer=".(empty($_SERVER['HTTP_REFERER']) ? '' : $_SERVER['HTTP_REFERER']).", action=".GETPOST('action', 'aZ09').", _GET|POST['token']=".GETPOST('token', 'alpha'), LOG_WARNING);
459 //dol_syslog("_SESSION['token']=".$sessiontokenforthisurl, LOG_DEBUG);
460 // Do not output anything on standard output because this create problems when using the BACK button on browsers. So we just set a message into session.
461 if (!defined('NOTOKENRENEWAL')) {
462 // If the page is not a page that disable the token renewal, we report a warning message to explain token has expired.
463 setEventMessages('SecurityTokenHasExpiredSoActionHasBeenCanceledPleaseRetry', null, 'warnings', '', 1);
464 }
465 $savid = null;
466 if (isset($_POST['id'])) {
467 $savid = ((int) $_POST['id']);
468 }
469 unset($_POST);
470 unset($_GET['confirm']);
471 unset($_GET['action']);
472 unset($_GET['confirmmassaction']);
473 unset($_GET['massaction']);
474 unset($_GET['token']); // TODO Make a redirect if we have a token in url to remove it ?
475 if (isset($savid)) {
476 $_POST['id'] = ((int) $savid);
477 }
478 // So rest of code can know something was wrong here
479 $_GET['errorcode'] = 'InvalidToken';
480 }
481
482 // Note: There is another CSRF protection into the filefunc.inc.php
483}
484
485if (!empty($dolibarr_main_demo)) {
486 // Disable modules (this must be after session_start and after conf has been loaded)
487 if (GETPOSTISSET('disablemodules')) {
488 $_SESSION["disablemodules"] = GETPOST('disablemodules', 'alpha');
489 }
490 if (!empty($_SESSION["disablemodules"])) {
491 $modulepartkeys = array('css', 'js', 'tabs', 'triggers', 'login', 'substitutions', 'menus', 'theme', 'sms', 'tpl', 'barcode', 'models', 'societe', 'hooks', 'dir', 'syslog', 'tpllinkable', 'contactelement', 'moduleforexternal', 'websitetemplates');
492
493 $disabled_modules = explode(',', $_SESSION["disablemodules"]);
494 foreach ($disabled_modules as $module) {
495 if ($module) {
496 if (empty($conf->$module)) {
497 $conf->$module = new stdClass(); // To avoid warnings
498 }
499
500 $conf->$module->enabled = false; // Old usage
501 unset($conf->modules[$module]);
502
503 foreach ($modulepartkeys as $modulepartkey) {
504 unset($conf->modules_parts[$modulepartkey][$module]);
505 }
506 if ($module == 'fournisseur') { // Special case
507 $conf->supplier_order->enabled = 0; // Old usage
508 $conf->supplier_invoice->enabled = 0; // Old usage
509 unset($conf->modules['supplier_order']);
510 unset($conf->modules['supplier_invoice']);
511 }
512 }
513 }
514 }
515}
516
517// Set current modulepart
518$modulepart = explode("/", $_SERVER["PHP_SELF"]);
519if (is_array($modulepart) && count($modulepart) > 0) {
520 foreach ($conf->modules as $module) {
521 if (in_array($module, $modulepart)) {
522 $modulepart = $module;
523 break;
524 }
525 }
526}
527if (is_array($modulepart)) {
528 $modulepart = '';
529}
530
531
532/*
533 * Phase authentication / login
534 */
535
536$login = '';
537$error = 0;
538if (!defined('NOLOGIN')) {
539 // $authmode lists the different method of identification to be tested in order of preference.
540 // Example: 'http', 'dolibarr', 'ldap', 'http,forceuser', '...'
541
542 if (defined('MAIN_AUTHENTICATION_MODE')) {
543 $dolibarr_main_authentication = constant('MAIN_AUTHENTICATION_MODE');
544 } else {
545 // Authentication mode
546 if (empty($dolibarr_main_authentication)) {
547 $dolibarr_main_authentication = 'dolibarr';
548 }
549 // Authentication mode: forceuser
550 if ($dolibarr_main_authentication == 'forceuser' && empty($dolibarr_auto_user)) {
551 $dolibarr_auto_user = 'auto';
552 }
553 }
554 // Set authmode
555 $authmode = explode(',', $dolibarr_main_authentication);
556
557 // No authentication mode
558 if (!count($authmode)) {
559 $langs->load('main');
560 dol_print_error(null, $langs->trans("ErrorConfigParameterNotDefined", 'dolibarr_main_authentication'));
561 exit;
562 }
563
564 // If login request was already post, we retrieve login from the session
565 // Call module if not realized that his request.
566 // At the end of this phase, the variable $login is defined.
567 $resultFetchUser = '';
568 $test = true;
569 $dol_authmode = null;
570
571 if (!isset($_SESSION["dol_login"])) {
572 // It is not already authenticated and it requests the login / password
573 include_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
574
575 $dol_dst_observed = GETPOSTINT("dst_observed", 3);
576 $dol_dst_first = GETPOSTINT("dst_first", 3);
577 $dol_dst_second = GETPOSTINT("dst_second", 3);
578 $dol_screenwidth = GETPOSTINT("screenwidth", 3);
579 $dol_screenheight = GETPOSTINT("screenheight", 3);
580 $dol_hide_topmenu = GETPOSTINT('dol_hide_topmenu', 3);
581 $dol_hide_leftmenu = GETPOSTINT('dol_hide_leftmenu', 3);
582 $dol_optimize_smallscreen = GETPOSTINT('dol_optimize_smallscreen', 3);
583 $dol_no_mouse_hover = GETPOSTINT('dol_no_mouse_hover', 3);
584 $dol_use_jmobile = GETPOSTINT('dol_use_jmobile', 3); // 0=default, 1=to say we use app from a webview app, 2=to say we use app from a webview app and keep ajax
585
586 // If in demo mode, we check we go to home page through the public/demo/index.php page
587 if (!empty($dolibarr_main_demo) && $_SERVER['PHP_SELF'] == DOL_URL_ROOT.'/index.php') { // We ask index page
588 if (empty($_SERVER['HTTP_REFERER']) || !preg_match('/public/', $_SERVER['HTTP_REFERER'])) {
589 dol_syslog("Call index page from another url than demo page (call is done from page ".(empty($_SERVER['HTTP_REFERER']) ? '' : $_SERVER['HTTP_REFERER']).")");
590 $query = [];
591 if ($dol_hide_topmenu) {
592 $query += ['dol_hide_topmenu' => $dol_hide_topmenu];
593 }
594 if ($dol_hide_leftmenu) {
595 $query += ['dol_hide_leftmenu' => $dol_hide_leftmenu];
596 }
597 if ($dol_optimize_smallscreen) {
598 $query += ['dol_optimize_smallscreen' => $dol_optimize_smallscreen];
599 }
600 if ($dol_no_mouse_hover) {
601 $query += ['dol_no_mouse_hover='.$dol_no_mouse_hover];
602 }
603 if ($dol_use_jmobile) {
604 $query += ['dol_use_jmobile='.$dol_use_jmobile];
605 }
606 header("Location: " . dolBuildUrl(DOL_URL_ROOT . '/public/demo/index.php', $query));
607 exit;
608 }
609 }
610
611 // Hooks for security access
612 $action = '';
613 $hookmanager->initHooks(array('login'));
614 $parameters = array();
615 $reshook = $hookmanager->executeHooks('beforeLoginAuthentication', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks
616 if ($reshook < 0) {
617 $test = false;
618 $error++;
619 }
620
621 // Verification security graphic code
622 if ($test && GETPOST('actionlogin', 'aZ09') == 'login' && GETPOST("username", "alpha", 2) && getDolGlobalString('MAIN_SECURITY_ENABLECAPTCHA') && !isset($_SESSION['dol_bypass_antispam'])) {
623 $ok = false;
624
625 // Use the captcha handler to validate
626 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
627 $captcha = getDolGlobalString('MAIN_SECURITY_ENABLECAPTCHA_HANDLER', 'standard');
628
629 // List of directories where we can find captcha handlers
630 $dirModCaptcha = array_merge(array('main' => '/core/modules/security/captcha/'), isset($conf->modules_parts['captcha']) && is_array($conf->modules_parts['captcha']) ? $conf->modules_parts['captcha'] : array());
631 $fullpathclassfile = '';
632 foreach ($dirModCaptcha as $dir) {
633 $fullpathclassfile = dol_buildpath($dir."modCaptcha".ucfirst($captcha).'.class.php', 0, 2);
634 if ($fullpathclassfile) {
635 break;
636 }
637 }
638
639 // The file for captcha check has been found
640 if ($fullpathclassfile) {
641 include_once $fullpathclassfile;
642 $captchaobj = null;
643
644 // Charging the numbering class
645 $classname = "modCaptcha".ucfirst($captcha);
646 if (class_exists($classname)) {
648 $captchaobj = new $classname($db, $conf, $langs, $user);
649 '@phan-var-force ModeleCaptcha $captchaobj';
650
651 if (is_object($captchaobj) && method_exists($captchaobj, 'validateCodeAfterLoginSubmit')) {
652 $ok = $captchaobj->validateCodeAfterLoginSubmit(); // @phan-suppress-current-line PhanUndeclaredMethod
653 } else {
654 $_SESSION["dol_loginmesg"] = 'Error, the captcha handler '.get_class($captchaobj).' does not have any method validateCodeAfterLoginSubmit()';
655 $test = false;
656 $error++;
657 }
658 } else {
659 $_SESSION["dol_loginmesg"] = 'Error, the captcha handler class '.$classname.' was not found after the include';
660 $test = false;
661 $error++;
662 }
663 } else {
664 $_SESSION["dol_loginmesg"] = 'Error, the captcha handler '.$captcha.' has no class file found modCaptcha'.ucfirst($captcha);
665 $test = false;
666 $error++;
667 }
668
669 // Process error of captcha validation
670 if (!$ok) {
671 dol_syslog('--- Security warning: Bad value for code, connection refused', LOG_NOTICE);
672 // Load translation files required by page
673 $langs->loadLangs(array('main', 'errors'));
674
675 $_SESSION["dol_loginmesg"] = (empty($_SESSION["dol_loginmesg"]) ? "" : $_SESSION["dol_loginmesg"]."<br>\n").$langs->transnoentitiesnoconv("ErrorBadValueForCode");
676 $test = false;
677
678 // Call trigger for the "security events" log
679 $user->context['audit'] = 'ErrorBadValueForCode - login='.GETPOST("username", "alpha", 2);
680
681 // Call trigger
682 $result = $user->call_trigger('USER_LOGIN_FAILED', $user);
683 if ($result < 0) {
684 $error++;
685 }
686 // End call triggers
687
688 // Hooks on failed login
689 $action = '';
690 $hookmanager->initHooks(array('login'));
691 $parameters = array('dol_authmode' => $authmode, 'dol_loginmesg' => $_SESSION["dol_loginmesg"]);
692 $reshook = $hookmanager->executeHooks('afterLoginFailed', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks
693 if ($reshook < 0) {
694 $error++;
695 }
696
697 // Note: exit is done later ($test is false)
698 }
699 }
700
701 $allowedmethodtopostusername = 3;
702 if (defined('MAIN_AUTHENTICATION_POST_METHOD')) {
703 $allowedmethodtopostusername = constant('MAIN_AUTHENTICATION_POST_METHOD'); // Note a value of 2 is not compatible with some authentication methods that put username as GET parameter
704 }
705 // Here, we are not already logged
706 // TODO Remove use of $_COOKIE['login_dolibarr'] by replacing line with $usertotest = GETPOST("username", "alpha", $allowedmethodtopostusername); ?
707 $usertotest = (!empty($_COOKIE['login_dolibarr']) ? preg_replace('/[^a-zA-Z0-9_@\-\.]/', '', $_COOKIE['login_dolibarr']) : GETPOST("username", "alpha", $allowedmethodtopostusername));
708 if (!is_string($usertotest)) {
709 // An array-shaped username (ex: ?username[]=x) is not sanitized by GETPOST('alpha')
710 // (sanitizeVal only processes scalars for this check) and would otherwise flow unchanged into
711 // checkLoginPassEntity() -> User::fetch(), crashing on trim() with a TypeError (see user.class.php).
712 $usertotest = '';
713 }
714 $passwordtotest = GETPOST('password', 'password', $allowedmethodtopostusername);
715 $entitytotest = (GETPOSTINT('entity') ? GETPOSTINT('entity') : (!empty($conf->entity) ? $conf->entity : 1));
716
717 // Define if we received the correct data to go into the test of the login with the checkLoginPassEntity().
718 $goontestloop = false;
719 if (isset($_SERVER["REMOTE_USER"]) && in_array('http', $authmode)) { // For http basic login test
720 $goontestloop = true;
721 }
722 if ($dolibarr_main_authentication == 'forceuser' && !empty($dolibarr_auto_user)) { // For automatic login with a forced user
723 $goontestloop = true;
724 }
725 if (GETPOST("username", "alpha", $allowedmethodtopostusername)) { // For posting the login form
726 $goontestloop = true;
727 }
728 if (GETPOST('openid_mode', 'alpha')) { // For openid_connect ?
729 $goontestloop = true;
730 }
731 if (GETPOST('beforeoauthloginredirect') || GETPOST('afteroauthloginreturn')) { // For oauth login
732 $goontestloop = true;
733 }
734 if (!empty($_COOKIE['login_dolibarr'])) { // TODO For ? Remove this ?
735 $goontestloop = true;
736 }
737
738 if (!is_object($langs)) { // This can occurs when calling page with NOREQUIRETRAN defined, however we need langs for error messages.
739 include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
740 $langs = new Translate("", $conf);
741 $langcode = (GETPOST('lang', 'aZ09', 1) ? GETPOST('lang', 'aZ09', 1) : getDolGlobalString('MAIN_LANG_DEFAULT', 'auto'));
742 if (defined('MAIN_LANG_DEFAULT')) {
743 $langcode = constant('MAIN_LANG_DEFAULT');
744 }
745 $langs->setDefaultLang($langcode);
746 }
747
748 // Test HTTP header
749 if (!empty($_SERVER['HTTP_EXPOSED_CREDENTIAL_CHECK'])) {
750 // TODO Read option $dolibarr_main_no_leaked_credentials with value 1, 2, ... and return
751 //dol_syslog("--- Access to ".(empty($_SERVER["REQUEST_METHOD"]) ? '' : $_SERVER["REQUEST_METHOD"].' ').$_SERVER["PHP_SELF"].' refused by option $dolibarr_main_no_leaked_credentials='.$dolibarr_main_no_leaked_credentials, LOG_NOTICE);
752 dol_syslog('--- Security warning: credentials reported as leaked were used to try to login. HTTP_EXPOSED_CREDENTIAL_CHECK='.((int) $_SERVER['HTTP_EXPOSED_CREDENTIAL_CHECK']), LOG_NOTICE);
753 }
754
755 // Refuse a login submission that carries a password in a GET query string.
756 // This avoids the password ending up in web server access logs,
757 // the browser history, the Referrer header or any HTTP proxy log (CWE-598).
758 // OAuth callbacks legitimately use GET but use afteroauthloginreturn.
759 // Other external pluginn using login_hashin GET are also legitimate.
760 if (GETPOST('actionlogin', 'aZ09') == 'login' && !GETPOST('afteroauthloginreturn', 'alphanohtml', 1) && GETPOST('password', 'password', 1)) {
761 dol_syslog("--- Login submission with credentials in the query string refused for ".$_SERVER["PHP_SELF"], LOG_WARNING);
762 $langs->loadLangs(array('main', 'errors'));
763 $_SESSION["dol_loginmesg"] = $langs->transnoentitiesnoconv("ErrorLoginMustBePostMethod");
764 $test = false;
765 }
766
767 // Validation of login/pass/entity
768 // If ok, the variable login will be returned
769 // If error, we will put error message in session under the name dol_loginmesg
770 if ($test && $goontestloop && GETPOST('actionlogin', 'aZ09') != 'disabled' && (GETPOST('actionlogin', 'aZ09') == 'login' || $dolibarr_main_authentication != 'dolibarr')) {
771 // Loop on each test mode defined into $authmode
772 // $authmode is an array for example: array('0'=>'dolibarr', '1'=>'googleoauth');
773 $oauthmodetotestarray = array('google');
774 foreach ($oauthmodetotestarray as $oauthmodetotest) {
775 if (in_array($oauthmodetotest.'oauth', $authmode)) { // This is an authmode that is currently qualified. Do we have to remove it ?
776 // If we click on the link to use OAuth authentication or if we go here after a callback return, we do nothing
777 if (GETPOST('beforeoauthloginredirect') == $oauthmodetotest || GETPOST('afteroauthloginreturn') == $oauthmodetotest) {
778 continue;
779 }
780 dol_syslog("User did not click on link for OAuth mode ".$oauthmodetotest.", param beforeoauthloginredirect is ".GETPOST('beforeoauthloginredirect')." and param afteroauthloginreturn is ".GETPOST('afteroauthloginreturn')." so we disable check of login for mode ".$oauthmodetotest);
781 foreach ($authmode as $tmpkey => $tmpval) {
782 if ($tmpval == $oauthmodetotest.'oauth') {
783 unset($authmode[$tmpkey]);
784 break;
785 }
786 }
787 }
788 }
789
790 // Check login for all qualified modes in array $authmode.
791 if (!empty($_SESSION['dol_totp_pending']) && GETPOSTISSET('totpcode')) {
792 // Second step of a two-factor authentication: the password was validated in the previous request, only the code is checked, against the login and entity kept in session
793 $entitytotest = (int) $_SESSION['dol_totp_pending']['entity'];
794 $login = dolTotpCheckPendingLogin($db);
795 $totpsecondstepdone = ($login ? 1 : 0);
796 $totpsecondstepfailed = ($login ? 0 : 1);
797 } else {
798 unset($_SESSION['dol_totp_pending']); // A new password step cancels any pending second step
799 $login = checkLoginPassEntity($usertotest, $passwordtotest, $entitytotest, $authmode);
800 if ($login === '--bad-login-validity--') {
801 $login = '';
802 }
803 if ($login && in_array($conf->authmode, array('dolibarr', 'ldap'))) {
804 // The password is right, but a user with a two-factor authentication needs a code before any session is opened. Only the modes with a password typed in the form are concerned.
805 $login = dolTotpStartSecondFactor($db, $login, $entitytotest);
806 $totpaskingforcode = ($login ? 0 : 1);
807 }
808 }
809
810 if ($login) {
811 $dol_authmode = $conf->authmode; // This property is defined only when logged, to say what mode was successfully used
812 // Check POST first, then GET (for OIDC callback redirect), then SESSION
813 $dol_tz = empty($_POST["tz"]) ? (empty($_GET["tz"]) ? (empty($_SESSION["tz"]) ? '' : $_SESSION["tz"]) : (int) $_GET["tz"]) : $_POST["tz"];
814 $dol_tz_string = empty($_POST["tz_string"]) ? (empty($_GET["tz_string"]) ? (empty($_SESSION["tz_string"]) ? '' : $_SESSION["tz_string"]) : $_GET["tz_string"]) : $_POST["tz_string"];
815 $dol_tz_string = preg_replace('/\s*\‍(.+\‍)$/', '', $dol_tz_string);
816 $dol_tz_string = preg_replace('/,/', '/', $dol_tz_string);
817 $dol_tz_string = preg_replace('/\s/', '_', $dol_tz_string);
818 $dol_dst = 0;
819 // Check POST first, then GET (for OIDC callback redirect), then SESSION
820 $dol_dst_first = empty($_POST["dst_first"]) ? (empty($_GET["dst_first"]) ? (empty($_SESSION["dst_first"]) ? '' : $_SESSION["dst_first"]) : (int) $_GET["dst_first"]) : $_POST["dst_first"];
821 $dol_dst_second = empty($_POST["dst_second"]) ? (empty($_GET["dst_second"]) ? (empty($_SESSION["dst_second"]) ? '' : $_SESSION["dst_second"]) : (int) $_GET["dst_second"]) : $_POST["dst_second"];
822 if ($dol_dst_first && $dol_dst_second) {
823 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
824 $datenow = dol_now();
825 $datefirst = dol_stringtotime($dol_dst_first);
826 $datesecond = dol_stringtotime($dol_dst_second);
827 if ($datenow >= $datefirst && $datenow < $datesecond) {
828 $dol_dst = 1;
829 }
830 }
831 $dol_screenheight = empty($_POST["screenheight"]) ? (empty($_GET["screenheight"]) ? (empty($_SESSION["dol_screenheight"]) ? '' : $_SESSION["dol_screenheight"]) : (int) $_GET["screenheight"]) : $_POST["screenheight"];
832 $dol_screenwidth = empty($_POST["screenwidth"]) ? (empty($_GET["screenwidth"]) ? (empty($_SESSION["dol_screenwidth"]) ? '' : $_SESSION["dol_screenwidth"]) : (int) $_GET["screenwidth"]) : $_POST["screenwidth"];
833 //print $datefirst.'-'.$datesecond.'-'.$datenow.'-'.$dol_tz.'-'.$dol_tzstring.'-'.$dol_dst.'-'.sdol_screenheight.'-'.sdol_screenwidth; exit;
834 }
835
836 if (!$login && empty($totpaskingforcode)) { // A password accepted but waiting for a 2FA code is not a failed authentication. A wrong code is one.
837 dol_syslog('Bad password, connection refused (see a previous notice message for more info)', LOG_NOTICE);
838 // Load translation files required by page
839 $langs->loadLangs(array('main', 'errors'));
840
841 // Bad password. No authmode has found a good password.
842 // We set a generic message if not defined inside function checkLoginPassEntity or subfunctions
843 if (empty($_SESSION["dol_loginmesg"])) {
844 $_SESSION["dol_loginmesg"] = $langs->transnoentitiesnoconv("ErrorBadLoginPassword");
845 }
846
847 // Call trigger for the "security events" log
848 $user->context['audit'] = (empty($totpsecondstepfailed) ? $langs->trans("ErrorBadLoginPassword") : $langs->trans("TOTPCodeRefused")).' - login='.GETPOST("username", "alpha", 2);
849
850 // Call trigger
851 $result = $user->call_trigger('USER_LOGIN_FAILED', $user);
852 if ($result < 0) {
853 $error++;
854 }
855 // End call triggers
856
857 // Hooks on failed login
858 $action = '';
859 $hookmanager->initHooks(array('login'));
860 $parameters = array('dol_authmode' => $dol_authmode, 'dol_loginmesg' => $_SESSION["dol_loginmesg"]);
861 $reshook = $hookmanager->executeHooks('afterLoginFailed', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks
862 if ($reshook < 0) {
863 $error++;
864 }
865
866 // Note: exit is done in next chapter
867 }
868 }
869
870 // End test login / passwords
871 if (!$login || (empty($totpsecondstepdone) && in_array('ldap', $authmode) && !in_array('openid_connect', $authmode) && empty($passwordtotest))) { // With LDAP we refused empty password because some LDAP are "opened" for anonymous access so connection is a success. The second step of a 2FA posts no password, so it is excluded from this test.
872 // No data to test login, so we show the login page.
873 dol_syslog("--- Access to ".(empty($_SERVER["REQUEST_METHOD"]) ? '' : $_SERVER["REQUEST_METHOD"].' ').$_SERVER["PHP_SELF"]." - action=".GETPOST('action', 'aZ09')." - actionlogin=".GETPOST('actionlogin', 'aZ09')." - showing the login form and exit", LOG_NOTICE);
874 if (defined('NOREDIRECTBYMAINTOLOGIN')) {
875 // When used with NOREDIRECTBYMAINTOLOGIN set, the http header must already be set when including the main.
876 // See example with selectsearchbox.php. This case is reserved for the selectesearchbox.php so we can
877 // report a message to ask to login when search ajax component is used after a timeout.
878 //top_httphead();
879 return 'ERROR_NOT_LOGGED';
880 } else {
881 if (!empty($_SERVER["HTTP_USER_AGENT"]) && $_SERVER["HTTP_USER_AGENT"] == 'securitytest') {
882 http_response_code(401); // It makes easier to understand if session was broken during security tests
883 }
884
885 // Show login form
886 dol_loginfunction($langs, $conf, (!empty($mysoc) ? $mysoc : '')); // This include http headers
887 }
888 exit;
889 }
890
891 $resultFetchUser = $user->fetch(0, $login, '', 1, ($entitytotest > 0 ? $entitytotest : -1)); // value for $login was retrieved previously when checking password.
892
893 if ($resultFetchUser <= 0 || $user->isNotIntoValidityDateRange()) {
894 dol_syslog('User not found or not valid, connection refused');
895 session_destroy();
896 session_set_cookie_params(0, '/', null, !empty($dolibarr_main_force_https), true); // Add tag secure and httponly on session cookie
897 session_name($sessionname);
899
900 if ($resultFetchUser == 0) {
901 // Load translation files required by page
902 $langs->loadLangs(array('main', 'errors'));
903
904 $_SESSION["dol_loginmesg"] = $langs->transnoentitiesnoconv("ErrorCantLoadUserFromDolibarrDatabase", $login);
905
906 $user->context['audit'] = 'ErrorCantLoadUserFromDolibarrDatabase - login='.$login;
907 } elseif ($resultFetchUser < 0) {
908 $_SESSION["dol_loginmesg"] = $user->error;
909
910 $user->context['audit'] = $user->error;
911 } else {
912 // Load translation files required by the page
913 $langs->loadLangs(array('main', 'errors'));
914
915 $_SESSION["dol_loginmesg"] = $langs->transnoentitiesnoconv("ErrorLoginDateValidity");
916
917 $user->context['audit'] = $langs->trans("ErrorLoginDateValidity").' - login='.$login;
918 }
919
920 // Call trigger
921 $result = $user->call_trigger('USER_LOGIN_FAILED', $user);
922 if ($result < 0) {
923 $error++;
924 }
925 // End call triggers
926
927
928 // Hooks on failed login
929 $action = '';
930 $hookmanager->initHooks(array('login'));
931 $parameters = array('dol_authmode' => $dol_authmode, 'dol_loginmesg' => $_SESSION["dol_loginmesg"]);
932 $reshook = $hookmanager->executeHooks('afterLoginFailed', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks
933 if ($reshook < 0) {
934 $error++;
935 }
936
937 $paramsurl = [];
938 if (GETPOSTINT('textbrowser')) {
939 $paramsurl += ['textbrowser' => GETPOSTINT('textbrowser')];
940 }
941 if (GETPOSTINT('nojs')) {
942 $paramsurl += ['nojs' => GETPOSTINT('nojs')];
943 }
944 if (GETPOST('lang', 'aZ09')) {
945 $paramsurl += ['lang' => (string) GETPOST('lang', 'aZ09')];
946 }
947 header('Location: '.dolBuildUrl(DOL_URL_ROOT . '/index.php', $paramsurl));
948 exit;
949 } else {
950 // User is loaded, we may need to change language for him according to its choice
951 if (!empty($user->conf->MAIN_LANG_DEFAULT)) {
952 $langs->setDefaultLang($user->conf->MAIN_LANG_DEFAULT);
953 }
954
955 if ($entitytotest > 0 && $conf->entity != $entitytotest) {
956 // We asked to force login to $entitytotest that differs from default $conf->entity, and we succeed, so
957 // we must force conf->entity to the new value, so the rest of the code that load $user->loadRights() and
958 // set $_SESSION['dol_entity'] will be done in correct environment.
959 $conf->entity = $entitytotest;
960 }
961 }
962 } else {
963 // We are already into an authenticated session
964 $login = $_SESSION["dol_login"];
965 $entity = isset($_SESSION["dol_entity"]) ? $_SESSION["dol_entity"] : 0;
966 dol_syslog("- This is an already logged session. _SESSION['dol_login']=".$login." _SESSION['dol_entity']=".$entity, LOG_DEBUG);
967
968 $resultFetchUser = $user->fetch(0, $login, '', 1, ($entity > 0 ? $entity : -1));
969
970 //var_dump(dol_print_date($user->flagdelsessionsbefore, 'dayhour', 'gmt')." ".dol_print_date($_SESSION["dol_logindate"], 'dayhour', 'gmt'));
971
972 if ($resultFetchUser <= 0
973 || ($user->flagdelsessionsbefore && !empty($_SESSION["dol_logindate"]) && $user->flagdelsessionsbefore > $_SESSION["dol_logindate"])
974 || ($user->status != $user::STATUS_ENABLED)
975 || ($user->isNotIntoValidityDateRange())) {
976 if ($resultFetchUser <= 0) {
977 // Account has been removed after login
978 dol_syslog("Can't load user even if session logged. _SESSION['dol_login']=".$login, LOG_WARNING);
979 } elseif ($user->flagdelsessionsbefore && !empty($_SESSION["dol_logindate"]) && $user->flagdelsessionsbefore > $_SESSION["dol_logindate"]) {
980 // Session is no more valid
981 dol_syslog("The user has a date for session invalidation = ".$user->flagdelsessionsbefore." and a session date = ".$_SESSION["dol_logindate"].". We must invalidate its sessions.");
982 } elseif ($user->status != $user::STATUS_ENABLED) {
983 // User is not enabled
984 dol_syslog("The user login is disabled");
985 } else {
986 // User validity dates are no more valid
987 dol_syslog("The user login has a validity between [".$user->datestartvalidity." and ".$user->dateendvalidity."], current date is ".dol_now());
988 }
989 session_destroy();
990 session_set_cookie_params(0, '/', null, !empty($dolibarr_main_force_https), true); // Add tag secure and httponly on session cookie
991 session_name($sessionname);
993
994 if ($resultFetchUser == 0) {
995 $langs->loadLangs(array('main', 'errors'));
996
997 $_SESSION["dol_loginmesg"] = $langs->transnoentitiesnoconv("ErrorCantLoadUserFromDolibarrDatabase", $login);
998
999 $user->context['audit'] = 'ErrorCantLoadUserFromDolibarrDatabase - login='.$login;
1000 } elseif ($resultFetchUser < 0) {
1001 $_SESSION["dol_loginmesg"] = $user->error;
1002
1003 $user->context['audit'] = $user->error;
1004 } else {
1005 $langs->loadLangs(array('main', 'errors'));
1006
1007 $_SESSION["dol_loginmesg"] = $langs->transnoentitiesnoconv("ErrorSessionInvalidatedAfterPasswordChange");
1008
1009 $user->context['audit'] = 'ErrorUserSessionWasInvalidated - login='.$login;
1010 }
1011
1012 // Call trigger
1013 $result = $user->call_trigger('USER_LOGIN_FAILED', $user);
1014 if ($result < 0) {
1015 $error++;
1016 }
1017 // End call triggers
1018
1019 // Hooks on failed login
1020 $action = '';
1021 $hookmanager->initHooks(array('login'));
1022 $parameters = array('dol_authmode' => (string) $dol_authmode, 'dol_loginmesg' => $_SESSION["dol_loginmesg"]);
1023 $reshook = $hookmanager->executeHooks('afterLoginFailed', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks
1024 if ($reshook < 0) {
1025 $error++;
1026 }
1027
1028 $paramsurl = array();
1029 if (GETPOSTINT('textbrowser')) {
1030 $paramsurl[] = 'textbrowser='.GETPOSTINT('textbrowser');
1031 }
1032 if (GETPOSTINT('nojs')) {
1033 $paramsurl[] = 'nojs='.GETPOSTINT('nojs');
1034 }
1035 if (GETPOST('lang', 'aZ09')) {
1036 $paramsurl[] = 'lang='.GETPOST('lang', 'aZ09');
1037 }
1038
1039 header('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl) ? '?'.implode('&', $paramsurl) : ''));
1040 exit;
1041 } else {
1042 // Initialize a technical object to manage hooks of page. Note that conf->hooks_modules contains an array of hook context
1043 $hookmanager->initHooks(array('main'));
1044
1045 // Code for search criteria persistence.
1046 if (!empty($_GET['save_lastsearch_values']) && !empty($_SERVER["HTTP_REFERER"])) { // We must use $_GET here
1047 $relativepathstring = preg_replace('/\?.*$/', '', $_SERVER["HTTP_REFERER"]);
1048 $relativepathstring = preg_replace('/^https?:\/\/[^\/]*/', '', $relativepathstring); // Get full path except host server
1049 // Clean $relativepathstring
1050 if (constant('DOL_URL_ROOT')) {
1051 $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
1052 }
1053 $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
1054 $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
1055 //var_dump($relativepathstring);
1056
1057 // We click on a link that leave a page we have to save search criteria, contextpage, limit and page and mode. We save them from tmp to no tmp
1058 if (!empty($_SESSION['lastsearch_values_tmp_'.$relativepathstring])) {
1059 $_SESSION['lastsearch_values_'.$relativepathstring] = $_SESSION['lastsearch_values_tmp_'.$relativepathstring];
1060 unset($_SESSION['lastsearch_values_tmp_'.$relativepathstring]);
1061 }
1062 if (!empty($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring])) {
1063 $_SESSION['lastsearch_contextpage_'.$relativepathstring] = $_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring];
1064 unset($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]);
1065 }
1066 if (!empty($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]) && $_SESSION['lastsearch_limit_tmp_'.$relativepathstring] != $conf->liste_limit) {
1067 $_SESSION['lastsearch_limit_'.$relativepathstring] = $_SESSION['lastsearch_limit_tmp_'.$relativepathstring];
1068 unset($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]);
1069 }
1070 if (!empty($_SESSION['lastsearch_page_tmp_'.$relativepathstring]) && $_SESSION['lastsearch_page_tmp_'.$relativepathstring] > 0) {
1071 $_SESSION['lastsearch_page_'.$relativepathstring] = $_SESSION['lastsearch_page_tmp_'.$relativepathstring];
1072 unset($_SESSION['lastsearch_page_tmp_'.$relativepathstring]);
1073 }
1074 if (!empty($_SESSION['lastsearch_mode_tmp_'.$relativepathstring])) {
1075 $_SESSION['lastsearch_mode_'.$relativepathstring] = $_SESSION['lastsearch_mode_tmp_'.$relativepathstring];
1076 unset($_SESSION['lastsearch_mode_tmp_'.$relativepathstring]);
1077 }
1078 }
1079 if (!empty($_GET['save_pageforbacktolist']) && !empty($_SERVER["HTTP_REFERER"])) { // We must use $_GET here
1080 if (empty($_SESSION['pageforbacktolist'])) {
1081 $pageforbacktolistarray = array();
1082 } else {
1083 $pageforbacktolistarray = $_SESSION['pageforbacktolist'];
1084 }
1085 $tmparray = explode(':', $_GET['save_pageforbacktolist'], 2);
1086 if (!empty($tmparray[0]) && !empty($tmparray[1])) {
1087 $pageforbacktolistarray[$tmparray[0]] = $tmparray[1];
1088 $_SESSION['pageforbacktolist'] = $pageforbacktolistarray;
1089 }
1090 }
1091
1092 $action = '';
1093 $parameters = array();
1094 $reshook = $hookmanager->executeHooks('updateSession', $parameters, $user, $action);
1095 if ($reshook < 0) {
1096 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
1097 }
1098 }
1099 }
1100
1101 // Is it a new session that has started ?
1102 // If we are here, this means authentication was successful.
1103 if (!isset($_SESSION["dol_login"])) {
1104 // New session for this login has started.
1105 $error = 0;
1106
1107 // Store value into session (values always stored)
1108 $_SESSION["dol_login"] = $user->login;
1109 $_SESSION["dol_logindate"] = dol_now('gmt');
1110 $_SESSION["dol_authmode"] = isset($dol_authmode) ? $dol_authmode : '';
1111 $_SESSION["dol_tz"] = isset($dol_tz) ? $dol_tz : '';
1112 $_SESSION["dol_tz_string"] = isset($dol_tz_string) ? $dol_tz_string : '';
1113 $_SESSION["dol_dst"] = isset($dol_dst) ? $dol_dst : '';
1114 $_SESSION["dol_dst_observed"] = isset($dol_dst_observed) ? $dol_dst_observed : '';
1115 $_SESSION["dol_dst_first"] = isset($dol_dst_first) ? $dol_dst_first : '';
1116 $_SESSION["dol_dst_second"] = isset($dol_dst_second) ? $dol_dst_second : '';
1117 $_SESSION["dol_screenwidth"] = isset($dol_screenwidth) ? $dol_screenwidth : '';
1118 $_SESSION["dol_screenheight"] = isset($dol_screenheight) ? $dol_screenheight : '';
1119 $_SESSION["dol_company"] = getDolGlobalString("MAIN_INFO_SOCIETE_NOM");
1120 $_SESSION["dol_entity"] = $conf->entity;
1121 // Store value into session (values stored only if defined)
1122 // Note: do not store the hide-menu flags when the login was done from inside a dialog popup iframe
1123 // (dol_openinpopup set, for example after a session timeout inside a popup opened by
1124 // dolButtonToOpenUrlInDialogPopup()), otherwise the whole session loses its menus.
1125 if (!empty($dol_hide_topmenu) && !GETPOST('dol_openinpopup', 'aZ09')) {
1126 $_SESSION['dol_hide_topmenu'] = $dol_hide_topmenu;
1127 }
1128 if (!empty($dol_hide_leftmenu) && !GETPOST('dol_openinpopup', 'aZ09')) {
1129 $_SESSION['dol_hide_leftmenu'] = $dol_hide_leftmenu;
1130 }
1131 if (!empty($dol_optimize_smallscreen)) {
1132 $_SESSION['dol_optimize_smallscreen'] = $dol_optimize_smallscreen;
1133 }
1134 if (!empty($dol_no_mouse_hover)) {
1135 $_SESSION['dol_no_mouse_hover'] = $dol_no_mouse_hover;
1136 }
1137 if (!empty($dol_use_jmobile)) {
1138 $_SESSION['dol_use_jmobile'] = $dol_use_jmobile;
1139 }
1140
1141 dol_syslog("This is a new started user session. _SESSION['dol_login']=".$_SESSION["dol_login"]." Session id=".session_id());
1142
1143 // Enforce the max number of concurrent sessions per user (only when sessions are stored in database).
1144 // Opening this new session evicts the user's oldest sessions above the limit, logging those browsers out.
1145 if (!empty($php_session_save_handler) && $php_session_save_handler == 'db' && !empty($conf->file->main_limit_sessions_per_user) && (int) $conf->file->main_limit_sessions_per_user > 0) {
1146 dolSessionsLimitForUser($user->id, (int) $conf->file->main_limit_sessions_per_user, session_id());
1147 }
1148
1149 $db->begin();
1150
1151 $user->update_last_login_date();
1152
1153 $loginfo = 'TZ='.$_SESSION["dol_tz"].';TZString='.$_SESSION["dol_tz_string"].';Screen='.$_SESSION["dol_screenwidth"].'x'.$_SESSION["dol_screenheight"];
1154 $loginfo .= ' - authmode='.$dol_authmode.' - entity='.$conf->entity;
1155
1156 // Call triggers for the "security events" log
1157 $user->context['audit'] = $loginfo;
1158 $user->context['authentication_method'] = $dol_authmode;
1159
1160 // Call trigger
1161 $result = $user->call_trigger('USER_LOGIN', $user);
1162 if ($result < 0) {
1163 $error++;
1164 }
1165 // End call triggers
1166
1167 // Hooks on successful login
1168 $action = '';
1169 $hookmanager->initHooks(array('login'));
1170 $parameters = array('dol_authmode' => $dol_authmode, 'dol_loginfo' => $loginfo);
1171 $reshook = $hookmanager->executeHooks('afterLogin', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks
1172 if ($reshook < 0) {
1173 $error++;
1174 }
1175
1176 if ($error) {
1177 $db->rollback();
1178 session_destroy();
1179 dol_print_error($db, 'Error in some triggers USER_LOGIN or in some hooks afterLogin');
1180 exit;
1181 } else {
1182 $db->commit();
1183 }
1184
1185 // Change landing page if defined.
1186 $landingpage = getDolUserString('MAIN_LANDING_PAGE', getDolGlobalString('MAIN_LANDING_PAGE'));
1187 if (!empty($landingpage)) { // Example: /index.php
1188 $newpath = dol_buildpath($landingpage, 1);
1189 if ($_SERVER["PHP_SELF"] != $newpath) { // not already on landing page (avoid infinite loop)
1190 header('Location: '.$newpath);
1191 exit;
1192 }
1193 }
1194 }
1195
1196 // Check if user must change password at next login
1197 if (!empty($user->force_pass_change) && $dol_authmode == 'dolibarr') {
1198 // redirect to a simple page with only one action is possible : change your password
1199 $allowedpages = array('/user/changepassword.php', '/user/logout.php');
1200 $currentpage = $_SERVER['PHP_SELF'];
1201 $isallowed = false;
1202 foreach ($allowedpages as $page) {
1203 if (preg_match('/'.preg_quote($page, '/').'$/', $currentpage)) {
1204 $isallowed = true;
1205 break;
1206 }
1207 }
1208 if (!$isallowed) {
1209 header('Location: '.DOL_URL_ROOT.'/user/changepassword.php');
1210 exit;
1211 }
1212 }
1213
1214 // If user admin, we force the rights-based modules
1215 if ($user->admin) {
1216 $user->rights->user->user->lire = 1;
1217 $user->rights->user->user->creer = 1;
1218 $user->rights->user->user->password = 1;
1219 $user->rights->user->user->supprimer = 1;
1220 $user->rights->user->self->creer = 1;
1221 $user->rights->user->self->password = 1;
1222
1223 //Required if advanced permissions are used with MAIN_USE_ADVANCED_PERMS
1224 if (getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) {
1225 if (!$user->hasRight('user', 'user_advance')) {
1226 $user->rights->user->user_advance = new stdClass(); // To avoid warnings
1227 }
1228 if (!$user->hasRight('user', 'self_advance')) {
1229 $user->rights->user->self_advance = new stdClass(); // To avoid warnings
1230 }
1231 if (!$user->hasRight('user', 'group_advance')) {
1232 $user->rights->user->group_advance = new stdClass(); // To avoid warnings
1233 }
1234
1235 $user->rights->user->user_advance->readperms = 1;
1236 $user->rights->user->user_advance->write = 1;
1237 $user->rights->user->self_advance->readperms = 1;
1238 $user->rights->user->self_advance->writeperms = 1;
1239 $user->rights->user->group_advance->read = 1;
1240 $user->rights->user->group_advance->readperms = 1;
1241 $user->rights->user->group_advance->write = 1;
1242 $user->rights->user->group_advance->delete = 1;
1243 }
1244 }
1245
1246 /*
1247 * Overwrite some configs globals (try to avoid this and have code to use instead $user->conf->xxx)
1248 */
1249
1250 // Set liste_limit from user setup
1251 if (isset($user->conf->MAIN_SIZE_LISTE_LIMIT)) { // If a user setup exists
1252 $conf->liste_limit = getDolUserInt('MAIN_SIZE_LISTE_LIMIT'); // Can be 0
1253 }
1254 if ((int) $conf->liste_limit <= 0) {
1255 // Mode automatic.
1256 $conf->liste_limit = getListLimitFromScreenHeight();
1257 }
1258 // Overwrite main_checkbox_left_column from user setup
1259 if (isset($user->conf->MAIN_CHECKBOX_LEFT_COLUMN)) { // If a user setup exists
1260 $conf->main_checkbox_left_column = getDolUserInt('MAIN_CHECKBOX_LEFT_COLUMN'); // Can be 0
1261 }
1262
1263 // Replace conf->css by personalized value if theme not forced
1264 if (!getDolGlobalString('MAIN_FORCETHEME') && getDolUserString('MAIN_THEME')) {
1265 $conf->theme = getDolUserString('MAIN_THEME');
1266 $conf->css = "/theme/".$conf->theme."/style.css.php";
1267 }
1268} else {
1269 // We may have NOLOGIN set, but NOREQUIREUSER not
1270 if (!empty($user) && method_exists($user, 'loadDefaultValues') && !defined('NODEFAULTVALUES')) {
1271 $user->loadDefaultValues(); // Load default values for everybody (works even if $user->id = 0
1272 }
1273}
1274
1275
1276// Case forcing style from url
1277if (GETPOST('theme', 'aZ09')) {
1278 $conf->theme = GETPOST('theme', 'aZ09', 1);
1279 $conf->css = "/theme/".$conf->theme."/style.css.php";
1280}
1281
1282// Set javascript option
1283if (GETPOSTINT('nojs')) { // If javascript was not disabled on URL
1284 $conf->use_javascript_ajax = 0;
1285} else {
1286 if (getDolUserString('MAIN_DISABLE_JAVASCRIPT')) {
1287 $conf->use_javascript_ajax = !getDolUserString('MAIN_DISABLE_JAVASCRIPT') ? 1 : 0;
1288 }
1289}
1290
1291// Set MAIN_OPTIMIZEFORTEXTBROWSER for user (must be after login part)
1292if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') && getDolUserString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
1293 $conf->global->MAIN_OPTIMIZEFORTEXTBROWSER = getDolUserString('MAIN_OPTIMIZEFORTEXTBROWSER');
1294 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') == 1) {
1295 $conf->global->THEME_TOPMENU_DISABLE_IMAGE = 1;
1296 }
1297}
1298//var_dump($conf->global->THEME_TOPMENU_DISABLE_IMAGE);
1299//var_dump($user->conf->THEME_TOPMENU_DISABLE_IMAGE);
1300
1301// set MAIN_OPTIMIZEFORCOLORBLIND for user
1302$conf->global->MAIN_OPTIMIZEFORCOLORBLIND = getDolUserString('MAIN_OPTIMIZEFORCOLORBLIND');
1303
1304// Set terminal output option according to conf->browser.
1305if (GETPOSTINT('dol_hide_leftmenu') || !empty($_SESSION['dol_hide_leftmenu'])) {
1306 $conf->dol_hide_leftmenu = 1;
1307}
1308if (GETPOSTINT('dol_hide_topmenu') || !empty($_SESSION['dol_hide_topmenu'])) {
1309 $conf->dol_hide_topmenu = 1;
1310}
1311if (GETPOSTINT('dol_optimize_smallscreen') || !empty($_SESSION['dol_optimize_smallscreen'])) {
1312 $conf->dol_optimize_smallscreen = 1;
1313}
1314if (GETPOSTINT('dol_no_mouse_hover') || !empty($_SESSION['dol_no_mouse_hover'])) {
1315 $conf->dol_no_mouse_hover = 1;
1316}
1317if (GETPOSTINT('dol_use_jmobile') || !empty($_SESSION['dol_use_jmobile'])) {
1318 $conf->dol_use_jmobile = 1;
1319}
1320// If not on Desktop
1321if (!empty($conf->browser->layout) && $conf->browser->layout != 'classic') {
1322 $conf->dol_no_mouse_hover = 1;
1323}
1324
1325// If on smartphone or optimized for small screen
1326if ((!empty($conf->browser->layout) && $conf->browser->layout == 'phone')
1327 || (!empty($_SESSION['dol_screenwidth']) && $_SESSION['dol_screenwidth'] < 400)
1328 || (!empty($_SESSION['dol_screenheight']) && $_SESSION['dol_screenheight'] < 400
1329 || getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER'))
1330) {
1331 $conf->dol_optimize_smallscreen = 1;
1332
1333 if (getDolGlobalInt('PRODUIT_DESC_IN_FORM') == 1) {
1334 $conf->global->PRODUIT_DESC_IN_FORM_ACCORDING_TO_DEVICE = 0; // This was set to PRODUIT_DESC_IN_FORM and is forced to 0 if smartphone in this case
1335 }
1336}
1337// Replace themes bugged with jmobile with eldy
1338if (!empty($conf->dol_use_jmobile) && in_array($conf->theme, array('bureau2crea', 'cameleo', 'amarok'))) {
1339 $conf->theme = 'eldy';
1340 $conf->css = "/theme/".$conf->theme."/style.css.php";
1341}
1342
1343if (!defined('NOREQUIRETRAN')) {
1344 if (!GETPOST('lang', 'aZ09')) { // If language was not forced on URL
1345 // If user has chosen its own language
1346 if (!empty($user->conf->MAIN_LANG_DEFAULT)) {
1347 // If different than current language
1348 //print ">>>".$langs->getDefaultLang()."-".$user->conf->MAIN_LANG_DEFAULT;
1349 if ($langs->getDefaultLang() != $user->conf->MAIN_LANG_DEFAULT) {
1350 $langs->setDefaultLang($user->conf->MAIN_LANG_DEFAULT);
1351 }
1352 }
1353 }
1354}
1355
1356if (!defined('NOLOGIN')) {
1357 // If the login is not recovered, it is identified with an account that does not exist.
1358 // Hacking attempt?
1359 if (!$user->login) {
1361 }
1362
1363 // Check if user is active
1364 if ($user->status < 1) {
1365 // If not active, we refuse the user
1366 $langs->loadLangs(array("errors", "other"));
1367 dol_syslog("Authentication KO as login is disabled", LOG_NOTICE);
1368 accessforbidden("ErrorLoginDisabled");
1369 }
1370
1371 // Load permissions for entity = $conf->entity
1372 $user->loadRights();
1373}
1374
1375dol_syslog("--- Access to ".(empty($_SERVER["REQUEST_METHOD"]) ? '' : $_SERVER["REQUEST_METHOD"].' ').$_SERVER["PHP_SELF"].' - action='.GETPOST('action', 'aZ09').', massaction='.GETPOST('massaction', 'aZ09').(defined('NOTOKENRENEWAL') ? ' NOTOKENRENEWAL='.constant('NOTOKENRENEWAL') : ''), LOG_NOTICE);
1376//Another call for easy debug
1377//dol_syslog("Access to ".$_SERVER["PHP_SELF"].' '.$_SERVER["HTTP_REFERER"].' GET='.join(',',array_keys($_GET)).'->'.join(',',$_GET).' POST:'.join(',',array_keys($_POST)).'->'.join(',',$_POST));
1378
1379// Load main languages files
1380if (!defined('NOREQUIRETRAN')) {
1381 // Load translation files required by page
1382 $langs->loadLangs(array('main', 'dict'));
1383
1384 // accesskey is for Windows or Linux: ALT + key for chrome, ALT + SHIFT + KEY for firefox
1385 // accesskey is for Mac: CTRL + Option + key for all browsers
1386
1387 // Note: $con->browser->os and $conf->browser->name may not be defined if we are in CLI mode.
1388 $conf->browser->stringforfirstkey = $langs->transnoentities("KeyboardShortcut");
1389 if (!empty($conf->browser->os) && $conf->browser->os == 'macintosh') {
1390 $conf->browser->stringforfirstkey .= ' CTRL + Option +';
1391 } else {
1392 if (!empty($conf->browser->name) && $conf->browser->name == 'chrome') {
1393 $conf->browser->stringforfirstkey .= ' ALT +';
1394 } elseif (!empty($conf->browser->name) && $conf->browser->name == 'firefox') {
1395 $conf->browser->stringforfirstkey .= ' ALT + SHIFT +';
1396 } else {
1397 $conf->browser->stringforfirstkey .= ' CTL +';
1398 }
1399 }
1400}
1401
1402// Define some constants used for style of arrays
1403$bc = array(0 => 'class="impair"', 1 => 'class="pair"');
1404$bcdd = array(0 => 'class="drag drop oddeven"', 1 => 'class="drag drop oddeven"');
1405$bcnd = array(0 => 'class="nodrag nodrop nohover"', 1 => 'class="nodrag nodrop nohoverpair"'); // Used for tr to add new lines
1406
1407// Define messages variables
1408$mesg = '';
1409$warning = '';
1410$error = 0;
1411// deprecated, see setEventMessages() and dol_htmloutput_events()
1412$mesgs = array();
1413$warnings = array();
1414$errors = array();
1415
1416// Constants used to defined number of lines in textarea
1417if (empty($conf->browser->firefox)) {
1418 define('ROWS_1', 1);
1419 define('ROWS_2', 2);
1420 define('ROWS_3', 3);
1421 define('ROWS_4', 4);
1422 define('ROWS_5', 5);
1423 define('ROWS_6', 6);
1424 define('ROWS_7', 7);
1425 define('ROWS_8', 8);
1426 define('ROWS_9', 9);
1427} else {
1428 define('ROWS_1', 0);
1429 define('ROWS_2', 1);
1430 define('ROWS_3', 2);
1431 define('ROWS_4', 3);
1432 define('ROWS_5', 4);
1433 define('ROWS_6', 5);
1434 define('ROWS_7', 6);
1435 define('ROWS_8', 7);
1436 define('ROWS_9', 8);
1437}
1438
1439$heightforframes = 52; // Used by frames.php page
1440
1441// Init menu manager
1442if (!defined('NOREQUIREMENU')) {
1443 if (empty($user->socid)) { // If internal user or not defined
1444 $conf->standard_menu = getDolGlobalString('MAIN_MENU_STANDARD_FORCED', getDolGlobalString('MAIN_MENU_STANDARD', 'eldy_menu.php'));
1445 } else {
1446 // If external user
1447 $conf->standard_menu = getDolGlobalString('MAIN_MENUFRONT_STANDARD_FORCED', getDolGlobalString('MAIN_MENUFRONT_STANDARD', 'eldy_menu.php'));
1448 }
1449
1450 // Load the menu manager (only if not already done)
1451 $file_menu = $conf->standard_menu;
1452 if (GETPOST('menu', 'alpha')) {
1453 $file_menu = GETPOST('menu', 'alpha'); // example: menu=eldy_menu.php
1454 }
1455
1456 if (!class_exists('MenuManager')) {
1457 $menufound = 0;
1458 $dirmenus = array_merge(array("/core/menus/"), (array) $conf->modules_parts['menus']);
1459 foreach ($dirmenus as $dirmenu) {
1460 $menufound = dol_include_once($dirmenu."standard/".$file_menu);
1461 if (class_exists('MenuManager')) {
1462 break;
1463 }
1464 }
1465 if (!class_exists('MenuManager')) { // If failed to include, we try with standard eldy_menu.php
1466 dol_syslog("You define a menu manager '".$file_menu."' that can not be loaded.", LOG_WARNING);
1467 $file_menu = 'eldy_menu.php';
1468 include_once DOL_DOCUMENT_ROOT."/core/menus/standard/".$file_menu;
1469 }
1470 }
1471 // @phan-suppress-next-line PhanRedefinedClassReference
1472 $menumanager = new MenuManager($db, empty($user->socid) ? 0 : 1);
1473 // @phan-suppress-next-line PhanRedefinedClassReference
1474 $menumanager->loadMenu();
1475}
1476
1477if (!empty(GETPOST('seteventmessages', 'alpha'))) {
1478 $message = GETPOST('seteventmessages', 'alpha');
1479 $messages = explode(',', $message);
1480 foreach ($messages as $key => $msg) {
1481 $tmp = explode(':', $msg);
1482 setEventMessages($tmp[0], null, !empty($tmp[1]) ? $tmp[1] : 'mesgs');
1483 }
1484}
1485
1486// Functions
1487
1488if (!function_exists("llxHeader")) {
1512 function llxHeader($head = '', $title = '', $help_url = '', $target = '', $disablejs = 0, $disablehead = 0, $arrayofjs = '', $arrayofcss = '', $morequerystring = '', $morecssonbody = '', $replacemainareaby = '', $disablenofollow = 0, $disablenoindex = 0)
1513 {
1514 global $conf, $hookmanager;
1515
1516 $parameters = array(
1517 'head' => & $head,
1518 'title' => & $title,
1519 'help_url' => & $help_url,
1520 'target' => & $target,
1521 'disablejs' => & $disablejs,
1522 'disablehead' => & $disablehead,
1523 'arrayofjs' => & $arrayofjs,
1524 'arrayofcss' => & $arrayofcss,
1525 'morequerystring' => & $morequerystring,
1526 'morecssonbody' => & $morecssonbody,
1527 'replacemainareaby' => & $replacemainareaby,
1528 'disablenofollow' => & $disablenofollow,
1529 'disablenoindex' => & $disablenoindex
1530
1531 );
1532 $reshook = $hookmanager->executeHooks('llxHeader', $parameters);
1533 if ($reshook > 0) {
1534 print $hookmanager->resPrint;
1535 return;
1536 }
1537
1538 // html header
1539 top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss, 0, $disablenofollow, $disablenoindex);
1540
1541 $tmpcsstouse = 'sidebar-collapse'.($morecssonbody ? ' '.$morecssonbody : '');
1542 // If theme MD and classic layer, we open the menulayer by default.
1543 if ($conf->theme == 'md' && !in_array($conf->browser->layout, array('phone', 'tablet')) && !getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
1544 global $mainmenu;
1545 if ($mainmenu != 'website') {
1546 $tmpcsstouse = $morecssonbody; // We do not use sidebar-collpase by default to have menuhider open by default.
1547 }
1548 }
1549
1550 if (getDolGlobalString('MAIN_OPTIMIZEFORCOLORBLIND')) {
1551 $tmpcsstouse .= ' colorblind-'.strip_tags(getDolGlobalString('MAIN_OPTIMIZEFORCOLORBLIND'));
1552 }
1553
1554 if (GETPOST('dol_openinpopup', 'aZ09')) {
1555 $tmpcsstouse .= ' dol_openinpopup';
1556 }
1557
1558 // The spell checker of the browser is disabled for the whole page (the attribute is inherited by all the
1559 // fields of all the forms). It is enabled back only on the fields where it is useful (free text, see DolEditor).
1560 print '<body id="mainbody" class="'.$tmpcsstouse.'" spellcheck="false">'."\n";
1561
1562 // top menu and left menu area
1563 if ((empty($conf->dol_hide_topmenu) || GETPOSTINT('dol_invisible_topmenu')) && !GETPOST('dol_openinpopup', 'aZ09')) {
1564 top_menu($head, $title, $target, $disablejs, $disablehead, $arrayofjs, $arrayofcss, $morequerystring, $help_url);
1565 }
1566
1567 if (empty($conf->dol_hide_leftmenu) && !GETPOST('dol_openinpopup', 'aZ09')) {
1568 left_menu('', $help_url, '', array(), 1, $title, 1); // $menumanager is retrieved with a global $menumanager inside this function
1569 }
1570
1571 // main area
1572 if ($replacemainareaby) {
1573 print $replacemainareaby;
1574 return;
1575 }
1576
1577 main_area($title);
1578 }
1579}
1580
1581
1589function top_httphead($contenttype = 'text/html', $forcenocache = 0)
1590{
1591 global $db, $conf, $hookmanager;
1592
1593 if ($contenttype != 'none') {
1594 if ($contenttype == 'text/html') {
1595 header("Content-Type: text/html; charset=".$conf->file->character_set_client);
1596 } else {
1597 header("Content-Type: ".$contenttype);
1598 }
1599 }
1600
1601 // Security options
1602
1603 // X-Content-Type-Options
1604 header("X-Content-Type-Options: nosniff"); // With the nosniff option, if the server says the content is text/html, the browser will render it as text/html (note that most browsers now force this option to on)
1605
1606 // X-Frame-Options
1607 if (!defined('XFRAMEOPTIONS_ALLOWALL')) {
1608 header("X-Frame-Options: SAMEORIGIN"); // By default, frames allowed only if on same domain (stop some XSS attacks)
1609 } else {
1610 header("X-Frame-Options: ALLOWALL");
1611 }
1612
1613 if (getDolGlobalString('MAIN_SECURITY_FORCE_ACCESS_CONTROL_ALLOW_ORIGIN')) {
1614 $tmpurl = constant('DOL_MAIN_URL_ROOT');
1615 $tmpurl = preg_replace('/^(https?:\/\/[^\/]+)\/.*$/', '\1', $tmpurl);
1616 header('Access-Control-Allow-Origin: '.$tmpurl);
1617 header('Vary: Origin');
1618 }
1619
1620 // X-XSS-Protection
1621 //header("X-XSS-Protection: 1"); // XSS filtering protection of some browsers (note: use of Content-Security-Policy is more efficient). Disabled as deprecated.
1622
1623 // Content-Security-Policy-Report-Only
1624 if (!defined('MAIN_SECURITY_FORCECSPRO')) {
1625 // If CSP not forced from the page
1626
1627 // A default security policy that keep usage of js external component like ckeditor, stripe, google, working
1628 // For example: to restrict to only local resources, except for css (cloudflare+google), and js (transifex + google tags) and object/iframe (youtube)
1629 // default-src 'self'; style-src: https://cdnjs.cloudflare.com https://fonts.googleapis.com; script-src: https://cdn.transifex.com https://www.googletagmanager.com; object-src https://youtube.com; frame-src https://youtube.com; img-src: *;
1630 // For example, to restrict everything to itself except img that can be on other servers:
1631 // default-src 'self'; img-src *;
1632 // Pre-existing site that uses too much js code to fix but wants to ensure resources are loaded only over https and disable plugins:
1633 // default-src https: 'unsafe-inline' 'unsafe-eval'; object-src 'none'
1634 //
1635 // $contentsecuritypolicy = "frame-ancestors 'self'; img-src * data:; font-src *; default-src 'self' 'unsafe-inline' 'unsafe-eval' *.paypal.com *.stripe.com *.google.com *.googleapis.com *.google-analytics.com *.googletagmanager.com;";
1636 // $contentsecuritypolicy = "frame-ancestors 'self'; img-src * data:; font-src *; default-src *; script-src 'self' 'unsafe-inline' *.paypal.com *.stripe.com *.google.com *.googleapis.com *.google-analytics.com *.googletagmanager.com; style-src 'self' 'unsafe-inline'; connect-src 'self';";
1637 $contentsecuritypolicy = getDolGlobalString('MAIN_SECURITY_FORCECSPRO');
1638
1639 if (!is_object($hookmanager)) {
1640 include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
1641 $hookmanager = new HookManager($db);
1642 }
1643 $hookmanager->initHooks(array("main"));
1644
1645 $parameters = array('contentsecuritypolicy' => $contentsecuritypolicy, 'mode' => 'reportonly');
1646 $result = $hookmanager->executeHooks('setContentSecurityPolicy', $parameters); // Note that $action and $object may have been modified by some hooks
1647 if ($result > 0) {
1648 $contentsecuritypolicy = $hookmanager->resPrint; // Replace CSP
1649 } else {
1650 $contentsecuritypolicy .= $hookmanager->resPrint; // Concat CSP
1651 }
1652
1653 // Add Dolibarr to Content-Security-Policy
1654 $contentsecuritypolicy = preg_replace('/default-src \'self\'/', 'default-src \'self\' *.dolibarr.org', $contentsecuritypolicy);
1655
1656 if (!empty($contentsecuritypolicy)) {
1657 header("Content-Security-Policy-Report-Only: ".$contentsecuritypolicy);
1658 }
1659 } else {
1660 header("Content-Security-Policy-Report-Only: ".constant('MAIN_SECURITY_FORCECSPRO'));
1661 }
1662
1663 // Content-Security-Policy
1664 if (!defined('MAIN_SECURITY_FORCECSP')) {
1665 // If CSP not forced from the page
1666
1667 // A default security policy that keep usage of js external component like ckeditor, stripe, google, working
1668 // For example: to restrict to only local resources, except for css (cloudflare+google), and js (transifex + google tags) and object/iframe (youtube)
1669 // default-src 'self'; style-src: https://cdnjs.cloudflare.com https://fonts.googleapis.com; script-src: https://cdn.transifex.com https://www.googletagmanager.com; object-src https://youtube.com; frame-src https://youtube.com; img-src: *;
1670 // For example, to restrict everything to itself except img that can be on other servers:
1671 // default-src 'self'; img-src *;
1672 // Pre-existing site that uses too much js code to fix but wants to ensure resources are loaded only over https and disable plugins:
1673 // default-src https: 'unsafe-inline' 'unsafe-eval'; object-src 'none'
1674 //
1675 // $contentsecuritypolicy = "frame-ancestors 'self'; img-src * data:; font-src *; default-src 'self' 'unsafe-inline' 'unsafe-eval' *.paypal.com *.stripe.com *.google.com *.googleapis.com *.google-analytics.com *.googletagmanager.com;";
1676 // $contentsecuritypolicy = "frame-ancestors 'self'; img-src * data:; font-src *; default-src *; script-src 'self' 'unsafe-inline' *.paypal.com *.stripe.com *.google.com *.googleapis.com *.google-analytics.com *.googletagmanager.com; style-src 'self' 'unsafe-inline'; connect-src 'self';";
1677 $contentsecuritypolicy = getDolGlobalString('MAIN_SECURITY_FORCECSP');
1678
1679 if (!is_object($hookmanager)) {
1680 include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
1681 $hookmanager = new HookManager($db);
1682 }
1683 $hookmanager->initHooks(array("main"));
1684
1685 $parameters = array('contentsecuritypolicy' => $contentsecuritypolicy, 'mode' => 'active');
1686 $result = $hookmanager->executeHooks('setContentSecurityPolicy', $parameters); // Note that $action and $object may have been modified by some hooks
1687 if ($result > 0) {
1688 $contentsecuritypolicy = $hookmanager->resPrint; // Replace CSP
1689 } else {
1690 $contentsecuritypolicy .= $hookmanager->resPrint; // Concat CSP
1691 }
1692
1693 // Add Dolibarr to Content-Security-Policy
1694 $contentsecuritypolicy = preg_replace('/default-src \'self\'/', 'default-src \'self\' ping.dolibarr.org', $contentsecuritypolicy);
1695
1696 if (!empty($contentsecuritypolicy)) {
1697 header("Content-Security-Policy: ".$contentsecuritypolicy);
1698 }
1699 } else {
1700 header("Content-Security-Policy: ".constant('MAIN_SECURITY_FORCECSP'));
1701 }
1702
1703 // Referrer-Policy
1704 // Say if we must provide the referrer when we jump onto another web page.
1705 // Default browser are 'strict-origin-when-cross-origin' (only domain is sent on other domain switching), we want more so we use 'same-origin' so browser doesn't send any referrer at all when going into another web site domain.
1706 // Note that we do not use 'strict-origin' as this breaks feature to restore filters when clicking on "back to page" link on some cases.
1707 if (!defined('MAIN_SECURITY_FORCERP')) {
1708 $referrerpolicy = getDolGlobalString('MAIN_SECURITY_FORCERP', "same-origin");
1709 if (!empty($referrerpolicy)) {
1710 header("Referrer-Policy: ".$referrerpolicy);
1711 }
1712 } else {
1713 header("Referrer-Policy: ".constant('MAIN_SECURITY_FORCERP'));
1714 }
1715
1716 // Strict-Transport-Security
1717 if (!defined('MAIN_SECURITY_FORCESTS')) {
1718 $sts = getDolGlobalString('MAIN_SECURITY_FORCESTS', "");
1719 if (!empty($sts)) {
1720 header("Strict-Transport-Security: ".$sts);
1721 }
1722 } else {
1723 header("Strict-Transport-Security: ".constant('MAIN_SECURITY_FORCESTS'));
1724 }
1725
1726 // Permissions-Policy (old name was Feature-Policy)
1727 if (!defined('MAIN_SECURITY_FORCEPP')) {
1728 $pp = getDolGlobalString('MAIN_SECURITY_FORCEPP', "");
1729 if (!empty($pp)) {
1730 header("Permissions-Policy: ".$pp);
1731 }
1732 } else {
1733 header("Permissions-Policy: ".constant('MAIN_SECURITY_FORCEPP'));
1734 }
1735
1736 // Cache
1737 if ($forcenocache) {
1738 header("Cache-Control: no-cache, no-store, must-revalidate, max-age=0");
1739 }
1740
1741 // No need to add this token in header, we use instead the one into the forms.
1742 //header("anti-csrf-token: ".newToken());
1743}
1744
1760function top_htmlhead($head, $title = '', $disablejs = 0, $disablehead = 0, $arrayofjs = array(), $arrayofcss = array(), $disableforlogin = 0, $disablenofollow = 0, $disablenoindex = 0)
1761{
1762 global $db, $conf, $langs, $user, $mysoc, $hookmanager;
1763
1764 top_httphead();
1765
1766 if (empty($conf->css)) {
1767 $conf->css = '/theme/eldy/style.css.php'; // If not defined, eldy by default
1768 }
1769
1770 print '<!doctype html>'."\n";
1771
1772 print '<html lang="'.substr($langs->defaultlang, 0, 2).'">'."\n";
1773
1774 //print '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr">'."\n";
1775 if (empty($disablehead)) {
1776 if (!is_object($hookmanager)) {
1777 include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
1778 $hookmanager = new HookManager($db);
1779 }
1780 $hookmanager->initHooks(array("main"));
1781
1782 $ext = 'layout='.(empty($conf->browser->layout) ? '' : $conf->browser->layout).'&version='.urlencode(DOL_VERSION);
1783
1784 print "<head>\n";
1785
1786 if (GETPOST('dol_basehref', 'alpha')) {
1787 print '<base href="'.dol_escape_htmltag(GETPOST('dol_basehref', 'alpha')).'">'."\n";
1788 }
1789
1790 // Displays meta
1791 print '<meta charset="utf-8">'."\n";
1792 print '<meta name="robots" content="'.($disablenoindex ? 'index' : 'noindex').($disablenofollow ? ',follow' : ',nofollow').'">'."\n"; // Do not index
1793 print '<meta name="viewport" content="width=device-width, initial-scale=1.0">'."\n"; // Scale for mobile device
1794 print '<meta name="author" content="Dolibarr Development Team">'."\n";
1795 print '<meta name="anti-csrf-newtoken" content="'.newToken().'">'."\n";
1796 print '<meta name="anti-csrf-currenttoken" content="'.currentToken().'">'."\n";
1797 if (getDolGlobalInt('MAIN_FEATURES_LEVEL')) {
1798 print '<meta name="MAIN_FEATURES_LEVEL" content="'.getDolGlobalInt('MAIN_FEATURES_LEVEL').'">'."\n";
1799 }
1800 // Favicon
1801 $favicon = DOL_URL_ROOT.'/theme/dolibarr_256x256_color.png';
1802 $appletouchicon = DOL_URL_ROOT.'/theme/apple-touch-icon.png';
1803 if (!empty($mysoc->logo_squarred_mini)) {
1804 $favicon = DOL_URL_ROOT.'/viewimage.php?cache=1&modulepart=mycompany&file='.urlencode('logos/thumbs/'.$mysoc->logo_squarred_mini);
1805 }
1806 if (getDolGlobalString('MAIN_FAVICON_URL')) {
1807 $favicon = getDolGlobalString('MAIN_FAVICON_URL');
1808 }
1809 if (empty($conf->dol_use_jmobile)) {
1810 print '<link rel="shortcut icon" type="image/x-icon" href="'.$favicon.'"/>'."\n"; // Not required into an Android webview
1811 print '<link rel="apple-touch-icon" href="'.$appletouchicon.'"/>'."\n";
1812 }
1813
1814 // Mobile appli like icon
1815 $manifest = DOL_URL_ROOT.'/theme/manifest.json.php';
1816 $parameters = array('manifest' => $manifest);
1817 $resHook = $hookmanager->executeHooks('hookSetManifest', $parameters); // Note that $action and $object may have been modified by some hooks
1818 if ($resHook > 0) {
1819 $manifest = $hookmanager->resPrint; // Replace manifest.json
1820 } else {
1821 $manifest .= $hookmanager->resPrint; // Concat to actual manifest declaration
1822 }
1823 if (!empty($manifest)) {
1824 print '<link rel="manifest" href="'.$manifest.'" />'."\n";
1825 }
1826
1827 if (getDolGlobalString('THEME_ELDY_TOPMENU_BACK1')) {
1828 print '<meta name="theme-color" content="rgb(' . getDolGlobalString('THEME_ELDY_TOPMENU_BACK1').')">'."\n";
1829 }
1830
1831 // Auto refresh page
1832 if (GETPOSTINT('autorefresh') > 0) {
1833 print '<meta http-equiv="refresh" content="'.GETPOSTINT('autorefresh').'">';
1834 }
1835
1836 // Displays title
1837 $appli = constant('DOL_APPLICATION_TITLE');
1838 $applicustom = getDolGlobalString('MAIN_APPLICATION_TITLE');
1839 if ($applicustom) {
1840 $appli = (preg_match('/^\+/', $applicustom) ? $appli : '').$applicustom;
1841 }
1842
1843 print '<title>';
1844 $titletoshow = '';
1845 if ($title && preg_match('/showapp/', getDolGlobalString('MAIN_HTML_TITLE'))) {
1846 $titletoshow = dol_htmlentities($appli.' - '.$title);
1847 } elseif ($title) {
1848 $titletoshow = dol_htmlentities($title);
1849 } else {
1850 $titletoshow = dol_htmlentities($appli);
1851 }
1852
1853 $parameters = array('title' => $titletoshow);
1854 $result = $hookmanager->executeHooks('setHtmlTitle', $parameters); // Note that $action and $object may have been modified by some hooks
1855 if ($result > 0) {
1856 $titletoshow = $hookmanager->resPrint; // Replace Title to show
1857 } else {
1858 $titletoshow .= $hookmanager->resPrint; // Concat to Title to show
1859 }
1860
1861 // Add ' + ai' to the title if the AI module is enabled (like multicompany module does with its own hook)
1862 if (isModEnabled('ai')) {
1863 $titletoshow .= ' + ai';
1864 }
1865
1866 print $titletoshow;
1867 print '</title>';
1868
1869 print "\n";
1870
1871 if (GETPOSTINT('version')) {
1872 $ext = 'version='.GETPOSTINT('version'); // useful to force no cache on css/js
1873 }
1874 // Refresh value of MAIN_IHM_PARAMS_REV before forging the parameter line.
1875 if (GETPOST('dol_resetcache')) {
1876 include_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
1877 dolibarr_set_const($db, "MAIN_IHM_PARAMS_REV", getDolGlobalInt('MAIN_IHM_PARAMS_REV') + 1, 'chaine', 0, '', $conf->entity);
1878 }
1879
1880 $themeparam = '?lang='.$langs->defaultlang.'&amp;theme='.$conf->theme.(GETPOST('optioncss', 'aZ09') ? '&amp;optioncss='.GETPOST('optioncss', 'aZ09', 1) : '').(empty($user->id) ? '' : ('&amp;userid='.$user->id)).'&amp;entity='.$conf->entity;
1881
1882 $themeparam .= '&' .$ext . '&revision='.getDolGlobalInt("MAIN_IHM_PARAMS_REV");
1883 if (GETPOSTISSET('dol_hide_topmenu')) {
1884 $themeparam .= '&amp;dol_hide_topmenu='.GETPOSTINT('dol_hide_topmenu');
1885 }
1886 if (GETPOSTISSET('dol_hide_leftmenu')) {
1887 $themeparam .= '&amp;dol_hide_leftmenu='.GETPOSTINT('dol_hide_leftmenu');
1888 }
1889 if (GETPOSTISSET('dol_openinpopup')) {
1890 $themeparam .= '&amp;dol_openinpopup='.GETPOST('dol_openinpopup', 'aZ09');
1891 }
1892 if (GETPOSTISSET('dol_optimize_smallscreen')) {
1893 $themeparam .= '&amp;dol_optimize_smallscreen='.GETPOSTINT('dol_optimize_smallscreen');
1894 }
1895 if (GETPOSTISSET('dol_no_mouse_hover')) {
1896 $themeparam .= '&amp;dol_no_mouse_hover='.GETPOSTINT('dol_no_mouse_hover');
1897 }
1898 if (GETPOSTISSET('dol_use_jmobile')) {
1899 $themeparam .= '&amp;dol_use_jmobile='.GETPOSTINT('dol_use_jmobile');
1900 $conf->dol_use_jmobile = GETPOSTINT('dol_use_jmobile');
1901 }
1902 if (GETPOSTISSET('THEME_DARKMODEENABLED')) {
1903 $themeparam .= '&amp;THEME_DARKMODEENABLED='.GETPOSTINT('THEME_DARKMODEENABLED');
1904 }
1905 if (GETPOSTISSET('THEME_SATURATE_RATIO')) {
1906 $themeparam .= '&amp;THEME_SATURATE_RATIO='.GETPOSTINT('THEME_SATURATE_RATIO');
1907 }
1908
1909
1916 $jsContextVars = [
1917 'DOL_VERSION' => DOL_VERSION,
1918 'DOL_URL_ROOT' => DOL_URL_ROOT,
1919 ];
1920
1921 $jsContextPathUrl = DOL_URL_ROOT . '/public/includes/dolibarr-js-context';
1922 $jsContextFiles = [
1923 'dolibarr-context.umd.js', // The js Dolibarr context definition
1924 ];
1925
1926 // COMPAT-JSCONTEXT @deprecated since 25.0, remove in 27.0 : backward compatibility layer, must be loaded right after the context definition
1927 if (!getDolGlobalInt('MAIN_JS_CONTEXT_DISABLE_COMPAT')) {
1928 $jsContextFiles[] = 'dolibarr-context.compat.js';
1929 }
1930
1931 $jsContextFiles[] = 'dolibarr-tool.seteventmessage.js'; // The first tools to help dev for easy event in js
1932 $jsContextFiles[] = 'dolibarr-tool.fetch.js'; // Ajax requests with anti CSRF token and error handling
1933
1934 if (! defined('NOREQUIRETRAN')) {
1935 // Langs tool see Documentation at admin/tools/ui/dolibarr-context/index.php
1936 $jsContextFiles[] = 'dolibarr-tool.langs.js';
1937 $jsContextVars['MAIN_LANG_DEFAULT'] = $langs->getDefaultLang();// For langs tool
1938 $jsContextVars['DOL_URL_ROOT'] = DOL_URL_ROOT;
1939 $jsContextVars['DOL_LANG_INTERFACE_URL'] = dol_buildpath('public/langs/langs-tool-interface.php', 1);// For langs tool
1940 }
1941
1942 // Context vars added by modules : the hook returns them into ->results, ex: $this->results = array('MYMODULE_VAR' => 'value');
1943 $parameters = array('jsContextVars' => $jsContextVars);
1944 $reshook = $hookmanager->executeHooks('addJsContextVars', $parameters);
1945 if ($reshook >= 0 && !empty($hookmanager->resArray)) {
1946 foreach ($hookmanager->resArray as $key => $value) {
1947 if (array_key_exists($key, $jsContextVars)) {
1948 dol_syslog("JS context var '".$key."' added by a module is already defined, it is ignored", LOG_WARNING);
1949 } elseif (!is_scalar($value)) {
1950 dol_syslog("JS context var '".$key."' added by a module must be a string, a number or a boolean, it is ignored", LOG_WARNING);
1951 } else {
1952 $jsContextVars[$key] = $value;
1953 }
1954 }
1955 }
1956
1957 // Load context and all js tools
1958 foreach ($jsContextFiles as $jsContextFile) {
1959 print '<script nonce="'.getNonce().'" src="'.$jsContextPathUrl.'/'.$jsContextFile.'?' . $ext . '" ></script>'."\n";
1960 }
1961
1962 // DEFINE FIRST NEEDED JS CONTEXT VARS
1963 print '<script nonce="'.getNonce().'">Dolibarr.setContextVars('.json_encode($jsContextVars).');</script>'."\n";
1964
1965 // -- END OF DEFINITION OF DOLIBARR JS CONTEXT AND TOOLS
1966
1967
1968 if (getDolGlobalString('MAIN_ENABLE_FONT_ROBOTO')) {
1969 print '<link rel="preconnect" href="https://fonts.gstatic.com">'."\n";
1970 print '<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@200;300;400;500;600&display=swap" rel="stylesheet">'."\n";
1971 }
1972
1973 if (!defined('DISABLE_JQUERY') && (!$disablejs || $disablejs == 2) && $conf->use_javascript_ajax) {
1974 print '<!-- Includes CSS for JQuery (Ajax library) -->'."\n";
1975 if (!defined('DISABLE_JQUERY_UI')) {
1976 $jquerytheme = 'base';
1977 if (getDolGlobalString('MAIN_USE_JQUERY_THEME')) {
1978 $jquerytheme = getDolGlobalString('MAIN_USE_JQUERY_THEME');
1979 }
1980 if (constant('JS_JQUERY_UI')) {
1981 print '<link rel="stylesheet" type="text/css" href="' . JS_JQUERY_UI . 'css/' . $jquerytheme . '/jquery-ui.min.css?' . $ext . '">' . "\n"; // Forced JQuery
1982 } else {
1983 print '<link rel="stylesheet" type="text/css" href="' . DOL_URL_ROOT . '/public/includes/jquery/css/' . $jquerytheme . '/jquery-ui.css?' . $ext . '">' . "\n"; // JQuery
1984 }
1985 }
1986 if (!defined('DISABLE_JQUERY_JNOTIFY')) {
1987 print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/public/includes/jquery/plugins/jnotify/jquery.jnotify-alt.min.css?' . $ext . '">'."\n"; // JNotify
1988 }
1989 if (!defined('DISABLE_SELECT2') && (getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT') || defined('REQUIRE_JQUERY_MULTISELECT'))) { // jQuery plugin "mutiselect", "multiple-select", "select2"...
1990 $tmpplugin = !getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT') ? constant('REQUIRE_JQUERY_MULTISELECT') : getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT');
1991 print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/public/includes/jquery/plugins/'.$tmpplugin.'/dist/css/'.$tmpplugin.'.css?' . $ext . '">'."\n";
1992 }
1993 }
1994
1995 if (!defined('DISABLE_FONT_AWSOME')) {
1996 print '<!-- Includes CSS for font awesome -->'."\n";
1997 $fontawesome_directory = getDolGlobalString('MAIN_FONTAWESOME_DIRECTORY', '/theme/common/fontawesome-5');
1998 print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.$fontawesome_directory.'/css/all.min.css?' . $ext . '">'."\n";
1999 }
2000
2001 // Output style sheets (optioncss='print' or ''). Note: $conf->css looks like '/theme/eldy/style.css.php'
2002 $themepath = dol_buildpath($conf->css, 1);
2003 $themesubdir = '';
2004 if (!empty($conf->modules_parts['theme'])) { // This slow down
2005 foreach ($conf->modules_parts['theme'] as $reldir) {
2006 if (file_exists(dol_buildpath($reldir.$conf->css, 0))) {
2007 $themepath = dol_buildpath($reldir.$conf->css, 1);
2008 $themesubdir = $reldir;
2009 break;
2010 }
2011 }
2012 }
2013
2014 if (!defined('DISABLE_CSS_DEFAULT_THEME')) {
2015 print '<!-- Includes CSS for Dolibarr theme -->'."\n";
2016 print '<link rel="stylesheet" type="text/css" href="' . $themepath . $themeparam . '">' . "\n";
2017 }
2018
2019 // To fix old chrome bug
2020 /*
2021 if (getDolGlobalString('MAIN_FIX_FLASH_ON_CHROME')) {
2022 print '<!-- Includes CSS that does not exists as a workaround of flash bug of chrome -->'."\n".'<link rel="stylesheet" type="text/css" href="filethatdoesnotexiststosolvechromeflashbug">'."\n";
2023 }
2024 */
2025
2026 // LEAFLET AND GEOMAN
2027 if (getDolGlobalString('MAIN_USE_GEOPHP')) {
2028 print '<link rel="stylesheet" href="'.DOL_URL_ROOT.'/includes/leaflet/leaflet.css?' . $ext . "\">\n";
2029 print '<link rel="stylesheet" href="'.DOL_URL_ROOT.'/includes/leaflet/leaflet-geoman.css?' . $ext . "\">\n";
2030 }
2031
2032 // CSS forced by modules (relative url starting with /)
2033 if (!empty($conf->modules_parts['css'])) {
2034 $arraycss = (array) $conf->modules_parts['css'];
2035 foreach ($arraycss as $modcss => $filescss) {
2036 $filescss = (array) $filescss; // To be sure filecss is an array
2037 foreach ($filescss as $cssfile) {
2038 if (empty($cssfile)) {
2039 dol_syslog("Warning: module ".$modcss." declared a css path file into its descriptor that is empty.", LOG_WARNING);
2040 }
2041 // cssfile is a relative path
2042 $urlforcss = dol_buildpath($cssfile, 1);
2043 if ($urlforcss && $urlforcss != '/') {
2044 print '<!-- Includes CSS added by module '.$modcss.' -->'."\n".'<link rel="stylesheet" type="text/css" href="'.$urlforcss;
2045 // We add params only if page is not static, because some web server setup does not return content type text/css if url has parameters, so browser cache is not used.
2046 if (!preg_match('/\.css$/i', $cssfile)) {
2047 print $themeparam;
2048 }
2049 print '">'."\n";
2050 } else {
2051 dol_syslog("Warning: module ".$modcss." declared a css path file for a file we can't find.", LOG_WARNING);
2052 }
2053 }
2054 }
2055 }
2056 // CSS forced by page in top_htmlhead call (relative url starting with /)
2057 if (is_array($arrayofcss)) {
2058 foreach ($arrayofcss as $cssfile) {
2059 if (preg_match('/^(http|\/\/)/i', $cssfile)) {
2060 $urltofile = $cssfile;
2061 } else {
2062 $urltofile = dol_buildpath($cssfile, 1);
2063 }
2064 print '<!-- Includes CSS added by page -->'."\n".'<link rel="stylesheet" type="text/css" title="default" href="'.$urltofile;
2065 // We add params only if page is not static, because some web server setup does not return content type text/css if url has parameters and browser cache is not used.
2066 if (!preg_match('/\.css$/i', $cssfile)) {
2067 print $themeparam;
2068 }
2069 print '">'."\n";
2070 }
2071 }
2072
2073 // Custom CSS
2074 if (getDolGlobalString('MAIN_IHM_CUSTOM_CSS')) {
2075 // If a custom CSS was set, we add link to the custom css php file
2076 print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/theme/custom.css.php?' . $ext . '&amp;revision='.getDolGlobalInt("MAIN_IHM_PARAMS_REV").'">'."\n";
2077 }
2078
2079 // Output standard javascript links
2080 if (!defined('DISABLE_JQUERY') && (!$disablejs || $disablejs == 2) && !empty($conf->use_javascript_ajax)) {
2081 // JQuery. Must be before other includes
2082 print '<!-- Includes JS for JQuery -->'."\n";
2083 if (defined('JS_JQUERY') && constant('JS_JQUERY')) {
2084 print '<script nonce="'.getNonce().'" src="'.JS_JQUERY.'jquery.min.js?' . $ext . '"></script>'."\n";
2085 } else {
2086 print '<script nonce="'.getNonce().'" src="'.DOL_URL_ROOT.'/public/includes/jquery/js/jquery.min.js?' . $ext . '"></script>'."\n";
2087 }
2088 if (!defined('DISABLE_JQUERY_UI')) {
2089 if (defined('JS_JQUERY_UI') && constant('JS_JQUERY_UI')) {
2090 print '<script nonce="' . getNonce() . '" src="' . JS_JQUERY_UI . 'jquery-ui.min.js?' . $ext . '"></script>' . "\n";
2091 } else {
2092 print '<script nonce="' . getNonce() . '" src="' . DOL_URL_ROOT . '/public/includes/jquery/js/jquery-ui.min.js?' . $ext . '"></script>' . "\n";
2093 }
2094 }
2095 // jQuery jnotify
2096 if (!getDolGlobalString('MAIN_DISABLE_JQUERY_JNOTIFY') && !defined('DISABLE_JQUERY_JNOTIFY')) {
2097 print '<script nonce="'.getNonce().'" src="'.DOL_URL_ROOT.'/public/includes/jquery/plugins/jnotify/jquery.jnotify.min.js?' . $ext . '"></script>'."\n";
2098 }
2099 // Table drag and drop lines
2100 if (empty($disableforlogin) && !defined('DISABLE_JQUERY_TABLEDND')) {
2101 print '<script nonce="'.getNonce().'" src="'.DOL_URL_ROOT.'/public/includes/jquery/plugins/tablednd/jquery.tablednd.min.js?' . $ext . '"></script>'."\n";
2102 }
2103 // Chart
2104 if (empty($disableforlogin) && (!getDolGlobalString('MAIN_JS_GRAPH') || getDolGlobalString('MAIN_JS_GRAPH') == 'chart') && !defined('DISABLE_JS_GRAPH')) {
2105 print '<script nonce="'.getNonce().'" src="'.DOL_URL_ROOT.'/includes/nnnick/chartjs/dist/chart.min.js?' . $ext . '"></script>'."\n";
2106 }
2107
2108 // jQuery jeditable for Edit In Place features
2109 /*if (getDolGlobalString('MAIN_USE_EDIT_IN_PLACE') && !defined('DISABLE_JQUERY_JEDITABLE')) {
2110 print '<!-- JS to manage editInPlace feature -->'."\n";
2111 print '<script nonce="'.getNonce().'" src="'.DOL_URL_ROOT.'/public/includes/jquery/plugins/jeditable/jquery.jeditable.js?' . $ext . '"></script>'."\n";
2112 print '<script nonce="'.getNonce().'" src="'.DOL_URL_ROOT.'/public/includes/jquery/plugins/jeditable/jquery.jeditable.ui-datepicker.js?' . $ext . '"></script>'."\n";
2113 print '<script nonce="'.getNonce().'" src="'.DOL_URL_ROOT.'/public/includes/jquery/plugins/jeditable/jquery.jeditable.ui-autocomplete.js?' . $ext . '"></script>'."\n";
2114 print '<script nonce="'.getNonce().'" >'."\n";
2115 print 'var urlSaveInPlace = \''.DOL_URL_ROOT.'/core/ajax/saveinplace.php\';'."\n";
2116 print 'var urlLoadInPlace = \''.DOL_URL_ROOT.'/core/ajax/loadinplace.php\';'."\n";
2117 print 'var tooltipInPlace = \''.$langs->transnoentities('ClickToEdit').'\';'."\n"; // Added in title attribute of span
2118 print 'var placeholderInPlace = \'&nbsp;\';'."\n"; // If we put another string than $langs->trans("ClickToEdit") here, nothing is shown. If we put empty string, there is error, Why ?
2119 print 'var cancelInPlace = \''.$langs->trans("Cancel").'\';'."\n";
2120 print 'var submitInPlace = \''.$langs->trans('Ok').'\';'."\n";
2121 print 'var indicatorInPlace = \'<img src="'.DOL_URL_ROOT."/theme/".$conf->theme."/img/working.gif".'">\';'."\n";
2122 print 'var withInPlace = 300;'; // width in pixel for default string edit
2123 print '</script>'."\n";
2124 print '<script nonce="'.getNonce().'" src="'.DOL_URL_ROOT.'/core/js/editinplace.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
2125 print '<script nonce="'.getNonce().'" src="'.DOL_URL_ROOT.'/public/includes/jquery/plugins/jeditable/jquery.jeditable.ckeditor.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
2126 }*/
2127 if (!defined('DISABLE_SELECT2') && (getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT') || defined('REQUIRE_JQUERY_MULTISELECT'))) {
2128 // jQuery plugin "mutiselect", "multiple-select", "select2", ...
2129 $tmpplugin = !getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT') ? constant('REQUIRE_JQUERY_MULTISELECT') : getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT');
2130 print '<script nonce="'.getNonce().'" src="'.DOL_URL_ROOT.'/public/includes/jquery/plugins/'.$tmpplugin.'/dist/js/'.$tmpplugin.'.full.min.js?' . $ext . '"></script>'."\n"; // We include full because we need the support of containerCssClass
2131 }
2132 if (!defined('DISABLE_MULTISELECT')) { // jQuery plugin "mutiselect" to select with checkboxes. Can be removed once we have an enhanced search tool
2133 print '<script nonce="'.getNonce().'" src="'.DOL_URL_ROOT.'/public/includes/jquery/plugins/multiselect/jquery.multi-select.js?' . $ext . '"></script>'."\n";
2134 }
2135 }
2136
2137 if (!$disablejs && !empty($conf->use_javascript_ajax)) {
2138 // CKEditor
2139 if (empty($disableforlogin) && (isModEnabled('fckeditor') && (!getDolGlobalString('FCKEDITOR_EDITORNAME') || getDolGlobalString('FCKEDITOR_EDITORNAME') == 'ckeditor') && !defined('DISABLE_CKEDITOR')) || defined('FORCE_CKEDITOR')) {
2140 print '<!-- Includes JS for CKEditor -->'."\n";
2141 $pathckeditor = DOL_URL_ROOT.'/public/includes/ckeditor/ckeditor/';
2142 $jsckeditor = 'ckeditor.js';
2143 if (constant('JS_CKEDITOR')) {
2144 // To use external ckeditor 4 js lib
2145 $pathckeditor = constant('JS_CKEDITOR');
2146 }
2147 print '<script nonce="'.getNonce().'">';
2148 print '/* enable ckeditor by main.inc.php */';
2149 print 'var CKEDITOR_BASEPATH = \''.dol_escape_js($pathckeditor).'\';'."\n";
2150 print 'var ckeditorConfig = \''.dol_escape_js(dol_buildpath($themesubdir.'/theme/'.$conf->theme.'/ckeditor/config.js?' . $ext, 1)).'\';'."\n"; // $themesubdir='' in standard usage
2151 print 'var ckeditorFilebrowserBrowseUrl = \''.DOL_URL_ROOT.'/core/filemanagerdol/browser/default/browser.php?Connector='.DOL_URL_ROOT.'/core/filemanagerdol/connectors/php/connector.php\';'."\n";
2152 print 'var ckeditorFilebrowserImageBrowseUrl = \''.DOL_URL_ROOT.'/core/filemanagerdol/browser/default/browser.php?Type=Image&Connector='.DOL_URL_ROOT.'/core/filemanagerdol/connectors/php/connector.php\';'."\n";
2153 print '</script>'."\n";
2154 print '<script src="'.$pathckeditor.$jsckeditor. '?' . $ext . '"></script>'."\n";
2155 print '<script>';
2156 if (GETPOST('mode', 'aZ09') == 'Full_inline') {
2157 print 'CKEDITOR.disableAutoInline = false;'."\n";
2158 } else {
2159 print 'CKEDITOR.disableAutoInline = true;'."\n";
2160 }
2161 print '</script>'."\n";
2162 }
2163
2164 // TinyMCE (alternative WYSIWYG backend, selected by FCKEDITOR_EDITORNAME='tinymce')
2165 if (empty($disableforlogin) && (isModEnabled('fckeditor') && getDolGlobalString('FCKEDITOR_EDITORNAME') == 'tinymce' && !defined('DISABLE_TINYMCE')) || defined('FORCE_TINYMCE')) {
2166 print '<!-- Includes JS for TinyMCE -->'."\n";
2167 $pathtinymce = DOL_URL_ROOT.'/public/includes/tinymce/tinymce/';
2168 $jstinymce = 'tinymce.min.js';
2169 if (defined('JS_TINYMCE') && constant('JS_TINYMCE')) {
2170 $pathtinymce = constant('JS_TINYMCE');
2171 }
2172 print '<script src="'.$pathtinymce.$jstinymce.'?'.$ext.'"></script>'."\n";
2173 print '<script nonce="'.getNonce().'">';
2174 print '/* enable tinymce by main.inc.php */';
2175 print 'var tinymceBasePath = \''.dol_escape_js($pathtinymce).'\';'."\n";
2176 print 'var tinymceFilebrowserBrowseUrl = \''.DOL_URL_ROOT.'/core/filemanagerdol/browser/default/browser.php?Connector='.DOL_URL_ROOT.'/core/filemanagerdol/connectors/php/connector.php\';'."\n";
2177 print 'var tinymceFilebrowserImageBrowseUrl = \''.DOL_URL_ROOT.'/core/filemanagerdol/browser/default/browser.php?Type=Image&Connector='.DOL_URL_ROOT.'/core/filemanagerdol/connectors/php/connector.php\';'."\n";
2178 print '</script>'."\n";
2179 print '<script nonce="'.getNonce().'" src="'.dol_buildpath($themesubdir.'/theme/'.$conf->theme.'/tinymce/config.js?'.$ext, 1).'"></script>'."\n";
2180 print '<script nonce="'.getNonce().'" src="'.DOL_URL_ROOT.'/core/js/tinymce-ckeditor-compat.js?'.$ext.'"></script>'."\n";
2181 }
2182
2183 // Browser notifications (if NOREQUIREMENU is on, it is mostly a page for popup, so we do not enable notif too. We hide also for public pages).
2184 if (!defined('NOBROWSERNOTIF') && !defined('NOREQUIREMENU') && !defined('NOLOGIN')) {
2185 $enablebrowsernotif = false;
2186 if (isModEnabled('agenda') && getDolGlobalString('AGENDA_REMINDER_BROWSER')) {
2187 $enablebrowsernotif = true;
2188 }
2189 if ($conf->browser->layout == 'phone') {
2190 $enablebrowsernotif = false;
2191 }
2192 if ($enablebrowsernotif) {
2193 print '<!-- Includes JS of Dolibarr (browser layout = '.$conf->browser->layout.')-->'."\n";
2194 print '<script nonce="'.getNonce().'" src="'.DOL_URL_ROOT.'/core/js/lib_notification.js.php?lang='.$langs->defaultlang. '&' . $ext . '"></script>'."\n";
2195 }
2196 }
2197
2198 // Global js function
2199 print '<!-- Includes JS of Dolibarr -->'."\n";
2200 if (!defined('DISABLE_LIB_HEAD_JS')) {
2201 print '<script nonce="' . getNonce() . '" src="' . DOL_URL_ROOT . '/core/js/lib_head.js.php?lang=' . $langs->defaultlang . '&' . $ext . '"></script>' . "\n";
2202 }
2203
2204 // Leaflet
2205 if (getDolGlobalString('MAIN_USE_GEOPHP')) {
2206 print '<script nonce="'.getNonce().'" src="'.DOL_URL_ROOT.'/includes/leaflet/leaflet.js?' . $ext . '"></script>'."\n";
2207 print '<script nonce="'.getNonce().'" src="'.DOL_URL_ROOT.'/includes/leaflet/leaflet-geoman.min.js?' . $ext . '"></script>'."\n";
2208 }
2209
2210 // JS forced by modules (relative url starting with /)
2211 if (!empty($conf->modules_parts['js'])) { // $conf->modules_parts['js'] is array('module'=>array('file1','file2'))
2212 $arrayjs = (array) $conf->modules_parts['js'];
2213 foreach ($arrayjs as $modjs => $filesjs) {
2214 $filesjs = (array) $filesjs; // To be sure filejs is an array
2215 foreach ($filesjs as $jsfile) {
2216 // jsfile is a relative path
2217 $urlforjs = dol_buildpath($jsfile, 1);
2218 if ($urlforjs && $urlforjs != '/') {
2219 print '<!-- Include JS added by module '.$modjs.'-->'."\n";
2220 print '<script nonce="'.getNonce().'" src="'.$urlforjs.((strpos($jsfile, '?') === false) ? '?' : '&amp;').'lang='.$langs->defaultlang.'"></script>'."\n";
2221 } else {
2222 dol_syslog("Warning: module ".$modjs." declared a js path file for a file we can't find.", LOG_WARNING);
2223 }
2224 }
2225 }
2226 }
2227 // JS forced by page in top_htmlhead (relative url starting with /)
2228 if (is_array($arrayofjs)) {
2229 print '<!-- Includes JS added by page -->'."\n";
2230 foreach ($arrayofjs as $jsfile) {
2231 if (preg_match('/^(http|\/\/)/i', $jsfile)) {
2232 print '<script nonce="'.getNonce().'" src="'.$jsfile.((strpos($jsfile, '?') === false) ? '?' : '&amp;').'lang='.$langs->defaultlang.'"></script>'."\n";
2233 } else {
2234 print '<script nonce="'.getNonce().'" src="'.dol_buildpath($jsfile, 1).((strpos($jsfile, '?') === false) ? '?' : '&amp;').'lang='.$langs->defaultlang.'"></script>'."\n";
2235 }
2236 }
2237 }
2238 }
2239
2240 //If you want to load custom javascript file from your selected theme directory
2241 if (getDolGlobalString('ALLOW_THEME_JS')) {
2242 $theme_js = dol_buildpath('/theme/'.$conf->theme.'/'.$conf->theme.'.js', 0);
2243 if (file_exists($theme_js)) {
2244 print '<script nonce="'.getNonce().'" src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/'.$conf->theme.'.js?' . $ext . '"></script>'."\n";
2245 }
2246 }
2247
2248 if (!empty($head)) {
2249 print $head."\n";
2250 }
2251 if (getDolGlobalString('MAIN_HTML_HEADER')) {
2252 print getDolGlobalString('MAIN_HTML_HEADER') . "\n";
2253 }
2254
2255 $parameters = array();
2256 $result = $hookmanager->executeHooks('addHtmlHeader', $parameters); // Note that $action and $object may have been modified by some hooks
2257 print $hookmanager->resPrint; // Replace Title to show
2258
2259 print "</head>\n\n";
2260 }
2261
2262 $conf->headerdone = 1; // To tell header was output
2263}
2264
2265
2282function top_menu($head, $title = '', $target = '', $disablejs = 0, $disablehead = 0, $arrayofjs = array(), $arrayofcss = array(), $morequerystring = '', $helppagename = '')
2283{
2284 global $user, $conf, $langs, $db, $form;
2285 global $dolibarr_main_authentication, $dolibarr_main_demo;
2286 global $hookmanager, $menumanager;
2287
2288 $searchform = '';
2289
2290 // Instantiate hooks for external modules
2291 $hookmanager->initHooks(array('toprightmenu'));
2292
2293 $toprightmenu = '';
2294
2295 // For backward compatibility with old modules
2296 if (empty($conf->headerdone)) {
2297 $disablenofollow = 0;
2298 top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss, 0, $disablenofollow);
2299 print '<body id="mainbody" spellcheck="false">';
2300 }
2301
2302 /*
2303 * Top menu
2304 */
2305 if ((empty($conf->dol_hide_topmenu) || GETPOSTINT('dol_invisible_topmenu')) && (!defined('NOREQUIREMENU') || !constant('NOREQUIREMENU'))) {
2306 if (!isset($form) || !is_object($form)) {
2307 include_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
2308 $form = new Form($db);
2309 }
2310
2311 print "\n".'<!-- Start top horizontal -->'."\n";
2312
2313 print '<header id="id-top" class="side-nav-vert'.(GETPOSTINT('dol_invisible_topmenu') ? ' hidden' : '').'">'; // dol_invisible_topmenu differs from dol_hide_topmenu: dol_invisible_topmenu means we output menu but we make it invisible.
2314
2315 // Show menu entries
2316 print '<div id="tmenu_tooltip'.(!getDolGlobalString('MAIN_MENU_INVERT') ? '' : 'invert').'" class="tmenu">'."\n";
2317 // @phan-suppress-next-line PhanRedefinedClassReference
2318 $menumanager->atarget = $target;
2319 // @phan-suppress-next-line PhanRedefinedClassReference
2320 $menumanager->showmenu('top', array('searchform' => $searchform)); // This contains a \n
2321 print "</div>\n";
2322
2323 // Define link to login card
2324 $appli = constant('DOL_APPLICATION_TITLE');
2325 $applicustom = getDolGlobalString('MAIN_APPLICATION_TITLE');
2326 if ($applicustom) {
2327 $appli = (preg_match('/^\+/', $applicustom) ? $appli : '').$applicustom;
2328 } else {
2329 $appli .= " ".DOL_VERSION;
2330 }
2331
2332 if (getDolGlobalInt('MAIN_FEATURES_LEVEL')) {
2333 $appli .= "<br>".$langs->trans("LevelOfFeature").': '.getDolGlobalInt('MAIN_FEATURES_LEVEL');
2334 }
2335
2336 $logouttext = '';
2337 $logouthtmltext = '';
2338 if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2339 $authmode = (empty($_SESSION["dol_authmode"]) ? '' : $_SESSION["dol_authmode"]);
2340 if ($authmode != 'forceuser' && $authmode != 'http') {
2341 $logouthtmltext .= $langs->trans("Logout").'<br>';
2342 $logouttext .= '<a accesskey="l" href="'.DOL_URL_ROOT.'/user/logout.php?token='.newToken().'">';
2343 $logouttext .= img_picto($langs->trans('Logout').' ('.$conf->browser->stringforfirstkey.' l)', 'sign-out', '', 0, 0, 0, '', 'atoplogin valignmiddle');
2344 $logouttext .= '</a>';
2345 } else {
2346 $logouthtmltext .= $langs->trans("NoLogoutProcessWithAuthMode", $_SESSION["dol_authmode"]);
2347 $logouttext .= img_picto($langs->trans('Logout').' ('.$conf->browser->stringforfirstkey.' l)', 'sign-out', '', 0, 0, 0, '', 'atoplogin valignmiddle opacitymedium');
2348 }
2349 }
2350
2351
2352 print '<div class="login_block usedropdown">'."\n";
2353
2354
2355 // Add block for tools
2356 $toprightmenu .= '<div class="login_block_tools valignmiddle">';
2357
2358 $mode = -1;
2359 $toprightmenu .= '<div class="inline-block nowrap" style="padding: 0px;">';
2360
2361 if (getDolGlobalString('MAIN_USE_TOP_MENU_SEARCH_DROPDOWN')) {
2362 // Add search dropdown
2363 $toprightmenu .= top_menu_search();
2364 }
2365
2366 // Add AI picto
2367 $toprightmenu .= top_menu_ai();
2368
2369 if (getDolGlobalString('MAIN_USE_TOP_MENU_IMPORT_FILE')) {
2370 // Add the import file link
2371 $toprightmenu .= top_menu_importfile();
2372 }
2373
2374 // Add bookmark dropdown
2375 $toprightmenu .= top_menu_bookmark();
2376
2377 if (getDolGlobalString('MAIN_USE_TOP_MENU_QUICKADD_DROPDOWN')) {
2378 // Add the quick add object dropdown
2379 $toprightmenu .= top_menu_quickadd();
2380 }
2381
2382 $toprightmenu .= '</div>';
2383
2384 $toprightmenu .= '</div>'."\n"; // end div class="login_block_tools"
2385
2386
2387 // Add block for other tools
2388 $toprightmenu .= '<div class="login_block_other valignmiddle">';
2389
2390 // Execute hook printTopRightMenu (hooks should output string like '<div class="login"><a href="">mylink</a></div>')
2391 $parameters = array();
2392 $result = $hookmanager->executeHooks('printTopRightMenu', $parameters); // Note that $action and $object may have been modified by some hooks
2393 if (is_numeric($result)) {
2394 if ($result == 0) {
2395 $toprightmenu .= $hookmanager->resPrint; // add
2396 } else {
2397 $toprightmenu = $hookmanager->resPrint; // replace
2398 }
2399 } else {
2400 $toprightmenu .= $result; // For backward compatibility
2401 }
2402
2403 // Link to module builder
2404 if (isModEnabled('modulebuilder')) {
2405 $text = '<a href="' . dolBuildUrl(DOL_URL_ROOT . '/modulebuilder/index.php', ['mainmenu' => 'home', 'leftmenu' => 'admintools']) .'" target="modulebuilder">';
2406 //$text.= img_picto(":".$langs->trans("ModuleBuilder"), 'printer_top.png', 'class="printer"');
2407 $text .= '<span class="fa fa-bug atoplogin valignmiddle"></span>';
2408 $text .= '</a>';
2409 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
2410 $toprightmenu .= $form->textwithtooltip('', $langs->trans("ModuleBuilder"), 2, 1, $text, 'login_block_elem', 2);
2411 }
2412
2413 // Link to print main content area (optioncss=print)
2414 if (!getDolGlobalString('MAIN_PRINT_DISABLELINK') && !getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2415 $qs = dol_escape_htmltag($_SERVER["QUERY_STRING"]);
2416
2417 if (!empty($_POST)) {
2418 foreach ($_POST as $key => $value) {
2419 $key = preg_replace('/[^a-z0-9_\.\-\[\]]/i', '', $key);
2420 if (in_array($key, array('action', 'massaction', 'password'))) {
2421 continue;
2422 }
2423 if (!is_array($value)) {
2424 if ($value !== '') {
2425 $qs .= '&'.urlencode($key).'='.urlencode($value);
2426 }
2427 } else {
2428 foreach ($value as $value2) {
2429 if (($value2 !== '') && (!is_array($value2))) {
2430 $qs .= '&'.urlencode($key).'[]='.urlencode($value2);
2431 }
2432 }
2433 }
2434 }
2435 }
2436 $qs .= (($qs && $morequerystring) ? '&' : '').$morequerystring;
2437 $text = '<a href="'.dol_escape_htmltag($_SERVER["PHP_SELF"]).'?'.$qs.($qs ? '&' : '').'optioncss=print" target="_blank" rel="noopener noreferrer">';
2438 //$text.= img_picto(":".$langs->trans("PrintContentArea"), 'printer_top.png', 'class="printer"');
2439 $text .= '<span class="fa fa-print atoplogin valignmiddle"></span>';
2440 $text .= '</a>';
2441 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
2442 $toprightmenu .= $form->textwithtooltip('', $langs->trans("PrintContentArea"), 2, 1, $text, 'login_block_elem', 2);
2443 }
2444
2445 // Link to Dolibarr wiki pages
2446 if (!getDolGlobalString('MAIN_HELP_DISABLELINK') && !getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2447 $langs->load("help");
2448
2449 $helpbaseurl = '';
2450 $helppage = '';
2451 $mode = '';
2452 $helppresent = '';
2453
2454 if (empty($helppagename)) {
2455 $helppagename = 'EN:User_documentation|FR:Documentation_utilisateur|ES:Documentación_usuarios|DE:Benutzerdokumentation';
2456 } else {
2457 $helppresent = 'helppresent';
2458 }
2459
2460 // Get helpbaseurl, helppage and mode from helppagename and langs
2461 $arrayres = getHelpParamFor($helppagename, $langs);
2462 $helpbaseurl = $arrayres['helpbaseurl'];
2463 $helppage = $arrayres['helppage'];
2464 $mode = $arrayres['mode'];
2465
2466 // Link to help pages
2467 if ($helpbaseurl && $helppage) {
2468 $text = '';
2469 $title = $langs->trans($mode == 'wiki' ? 'GoToWikiHelpPage' : 'GoToHelpPage').', ';
2470 if ($mode == 'wiki') {
2471 $title .= '<br>'.img_picto('', 'globe', 'class="pictofixedwidth"').$langs->trans("PageWiki").' '.dol_escape_htmltag('"'.strtr($helppage, '_', ' ').'"');
2472 if ($helppresent) {
2473 $title .= ' <span class="opacitymedium">('.$langs->trans("DedicatedPageAvailable").')</span>';
2474 } else {
2475 $title .= ' <span class="opacitymedium">('.$langs->trans("HomePage").')</span>';
2476 }
2477 }
2478 $text .= '<a class="help" target="_blank" rel="noopener noreferrer" href="';
2479 if ($mode == 'wiki') {
2480 // @phan-suppress-next-line PhanPluginPrintfVariableFormatString
2481 $text .= sprintf($helpbaseurl, urlencode(html_entity_decode($helppage)));
2482 } else {
2483 // @phan-suppress-next-line PhanPluginPrintfVariableFormatString
2484 $text .= sprintf($helpbaseurl, $helppage);
2485 }
2486 $text .= '">';
2487 $text .= '<span class="fa fa-question-circle atoplogin valignmiddle'.($helppresent ? ' '.$helppresent : '').'"></span>';
2488 $text .= '<span class="fa fa-long-arrow-alt-up helppresentcircle'.($helppresent ? '' : ' unvisible').'"></span>';
2489 $text .= '</a>';
2490 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
2491 $toprightmenu .= $form->textwithtooltip('', $title, 2, 1, $text, 'login_block_elem', 2);
2492 }
2493
2494 // Version
2495 if (getDolGlobalString('MAIN_SHOWDATABASENAMEINHELPPAGESLINK')) {
2496 $langs->load('admin');
2497 $appli .= '<br>'.$langs->trans("Database").': '.$db->database_name;
2498 }
2499 }
2500
2501 // Version
2502 if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') && getDolGlobalInt('MAIN_HIDE_VERSION') == 0) {
2503 $text = '<span class="aversion"><span class="hideonsmartphone small">'.DOL_VERSION.'</span></span>';
2504 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
2505 $toprightmenu .= $form->textwithtooltip('', $appli, 2, 1, $text, 'login_block_elem', 2);
2506 }
2507
2508 // Logout link
2509 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2510 $toprightmenu .= $form->textwithtooltip('', $logouthtmltext, 2, 1, $logouttext, 'login_block_elem logout-btn', 2);
2511 }
2512
2513 $toprightmenu .= '</div>'; // end div class="login_block_other"
2514
2515
2516 // Add block for user photo and name
2517 $toprightmenu .= '<div class="login_block_user">';
2518
2519 $mode = -1;
2520 $toprightmenu .= '<div class="inline-block login_block_elem login_block_elem_name nowrap centpercent" style="padding: 0px;">';
2521
2522 // Add user dropdown
2523 $toprightmenu .= top_menu_user();
2524
2525 $toprightmenu .= '</div>';
2526
2527 $toprightmenu .= '</div>'."\n";
2528
2529
2530 print $toprightmenu;
2531
2532 print "</div>\n"; // end div class="login_block"
2533
2534 print '</header>';
2535 //print '<header class="header2">&nbsp;</header>';
2536
2537 print '<div style="clear: both;"></div>';
2538 print "<!-- End top horizontal menu -->\n\n";
2539 }
2540
2541 if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) {
2542 print '<!-- Begin div id-container --><div id="id-container" class="id-container">';
2543 }
2544}
2545
2546
2554function top_menu_user($hideloginname = 0, $urllogout = '')
2555{
2556 global $langs, $conf, $db, $hookmanager, $user, $mysoc;
2557 global $dolibarr_main_authentication, $dolibarr_main_demo;
2558 global $menumanager, $form;
2559
2560 // Return empty in some case
2561 if ($conf->browser->name == 'textbrowser') {
2562 return '';
2563 }
2564
2565 $langs->load('companies');
2566
2567 $userImage = $userDropDownImage = '';
2568 if (!empty($user->photo) || isModEnabled('gravatar')) {
2569 $userImage = Form::showphoto('userphoto', $user, 0, 0, 0, 'photouserphoto userphoto', 'small', 0, 1);
2570 $userDropDownImage = Form::showphoto('userphoto', $user, 0, 0, 0, 'dropdown-user-image', 'small', 0, 1);
2571 } else {
2572 $nophoto = '/public/theme/common/user_anonymous.png';
2573 if ($user->gender == 'man') {
2574 $nophoto = '/public/theme/common/user_man.png';
2575 }
2576 if ($user->gender == 'woman') {
2577 $nophoto = '/public/theme/common/user_woman.png';
2578 }
2579
2580 $userImage = img_picto('', 'user', 'class="photo photouserphoto userphoto"');
2581 //$userImage = '<img class="photo photouserphoto userphoto" alt="" src="'.DOL_URL_ROOT.$nophoto.'" aria-hidden="true">';
2582 $userDropDownImage = '<img class="photo dropdown-user-image" alt="" src="'.DOL_URL_ROOT.$nophoto.'" aria-hidden="true">';
2583 }
2584
2585 $dropdownBody = '';
2586 $dropdownBody .= '<span id="topmenulogincompanyinfo-btn"><i class="fa fa-caret-right"></i> '.$langs->trans("ShowCompanyInfos").'</span>';
2587 $dropdownBody .= '<div id="topmenulogincompanyinfo" >';
2588
2589 // $mysoc may not be loaded (pages defining NOREQUIRESOC)
2590 $mysocname = (is_object($mysoc) ? $mysoc->name : '');
2591 $mysoccountrycode = (is_object($mysoc) ? $mysoc->country_code : '');
2592
2593 $dropdownBody .= '<br><b>'.$langs->trans("Company").'</b>: <span>'.dol_escape_htmltag($mysocname).'</span>';
2594 $idprofcursor = 0;
2595 while ($idprofcursor < 10) {
2596 $idprofcursor++;
2597 $constkeyforprofid = 'MAIN_INFO_PROFID'.$idprofcursor;
2598 if ($idprofcursor == 1) {
2599 $constkeyforprofid = 'MAIN_INFO_SIREN';
2600 }
2601 if ($idprofcursor == 2) {
2602 $constkeyforprofid = 'MAIN_INFO_SIRET';
2603 }
2604 if ($idprofcursor == 3) {
2605 $constkeyforprofid = 'MAIN_INFO_APE';
2606 }
2607 if ($idprofcursor == 4) {
2608 $constkeyforprofid = 'MAIN_INFO_RCS';
2609 }
2610 $showprofid = (($idprofcursor <= 6) && $langs->transcountry("ProfId".$idprofcursor, $mysoccountrycode) != '-');
2611 if ($idprofcursor > 6 && getDolGlobalString($constkeyforprofid)) {
2612 $showprofid = true;
2613 }
2614 if ($showprofid) {
2615 $dropdownBody .= '<br><b>'.$langs->transcountry("ProfId".$idprofcursor, $mysoccountrycode).'</b>: <span>'.dol_print_profids(getDolGlobalString($constkeyforprofid), '1').'</span>';
2616 }
2617 }
2618 $dropdownBody .= '<br><b>'.$langs->trans("VATIntraShort").'</b>: <span>'.dol_print_profids(getDolGlobalString("MAIN_INFO_TVAINTRA"), 'VAT').'</span>';
2619 $langFlag = picto_from_langcode($langs->getDefaultLang(), 'class="none"');
2620 $dropdownBody .= '<br><b>'.$langs->trans("Country").'</b>: <span>'.($mysoccountrycode ? $langs->trans("Country".$mysoccountrycode).' '.$langFlag : '').'</span>';
2621 if (isModEnabled('multicurrency')) {
2622 $dropdownBody .= '<br><b>'.$langs->trans("Currency").'</b>: <span>'.getDolCurrency().'</span>';
2623 }
2624 $dropdownBody .= '</div>';
2625
2626 $dropdownBody .= '<br>';
2627 $dropdownBody .= '<span id="topmenuloginmoreinfo-btn"><i class="fa fa-caret-right"></i> '.$langs->trans("ShowMoreInfos").'</span>';
2628 $dropdownBody .= '<div id="topmenuloginmoreinfo" >';
2629
2630 // login infos
2631 if (!empty($user->admin)) {
2632 $dropdownBody .= '<br><b>'.$langs->trans("Administrator").'</b>: '.yn($user->admin).' '.img_picto('', 'admin');
2633 }
2634 $company = '';
2635 if (!empty($user->socid)) { // Add third party for external users
2636 $thirdpartystatic = new Societe($db);
2637 $thirdpartystatic->fetch($user->socid);
2638 $companylink = ' '.$thirdpartystatic->getNomUrl(2); // picto only of company
2639 $company = ' ('.$langs->trans("Company").': '.$thirdpartystatic->name.')';
2640 }
2641 $type = ($user->socid ? $langs->trans("External").$company : $langs->trans("Internal"));
2642 $dropdownBody .= '<br><b>'.$langs->trans("Type").':</b> '.$type;
2643 $dropdownBody .= '<br><b>'.$langs->trans("Status").'</b>: '.$user->getLibStatut(0);
2644 $dropdownBody .= '<br>';
2645
2646 $dropdownBody .= '<br><u>'.$langs->trans("Session").'</u>';
2647 $dropdownBody .= '<br><b>'.$langs->trans("IPAddress").'</b>: '.dol_escape_htmltag($_SERVER["REMOTE_ADDR"]);
2648 if (getDolGlobalString('MAIN_MODULE_MULTICOMPANY')) {
2649 $dropdownBody .= '<br><b>'.$langs->trans("ConnectedOnMultiCompany").':</b> '.$conf->entity.' (user entity '.$user->entity.')';
2650 }
2651 $dropdownBody .= '<br><b>'.$langs->trans("AuthenticationMode").':</b> '.(empty($_SESSION["dol_authmode"]) ? '' : $_SESSION["dol_authmode"]).(empty($dolibarr_main_demo) ? '' : ' (demo)');
2652 $dropdownBody .= '<br><b>'.$langs->trans("ConnectedSince").':</b> '.dol_print_date($user->datelastlogin, "dayhour", 'tzuser');
2653 $dropdownBody .= '<br><b>'.$langs->trans("PreviousConnexion").':</b> '.dol_print_date($user->datepreviouslogin, "dayhour", 'tzuser');
2654 $dropdownBody .= '<br><b>'.$langs->trans("CurrentTheme").':</b> '.$conf->theme;
2655 // @phan-suppress-next-line PhanRedefinedClassReference
2656 $dropdownBody .= '<br><b>'.$langs->trans("CurrentMenuManager").':</b> '.(isset($menumanager) ? $menumanager->name : 'unknown');
2657 $langFlag = picto_from_langcode($langs->getDefaultLang(), 'class="none"');
2658 $dropdownBody .= '<br><b>'.$langs->trans("CurrentUserLanguage").':</b> '.$langs->getDefaultLang().($langFlag ? ' '.$langFlag : '');;
2659
2660 $tz = (int) (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) + (int) (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']);
2661 $dropdownBody .= '<br><b>'.$langs->trans("ClientTZ").':</b> '.($tz ? ($tz >= 0 ? '+' : '').$tz : '');
2662 $dropdownBody .= ' <span class="opacitymedium">('.(empty($_SESSION['dol_tz_string']) ? '' : $_SESSION['dol_tz_string']).')</span>';
2663 //$dropdownBody .= ' &nbsp; &nbsp; &nbsp; '.$langs->trans("DaylingSavingTime").': ';
2664 //if ($_SESSION['dol_dst'] > 0) $dropdownBody .= yn(1);
2665 //else $dropdownBody .= yn(0);
2666
2667 $dropdownBody .= '<br><b>'.$langs->trans("Browser").':</b> '.ucfirst($conf->browser->name).($conf->browser->version ? ' '.$conf->browser->version : '');
2668 $dropdownBody .= $form->textwithpicto('', dol_escape_htmltag($_SERVER['HTTP_USER_AGENT'] ?? ''), 1, 'help', 'valignmiddle', 0, 3, 'useragent');
2669 $dropdownBody .= '<br><b>'.$langs->trans("Screen").':</b> '.(empty($_SESSION['dol_screenwidth']) ? '' : $_SESSION['dol_screenwidth']).' x '.(empty($_SESSION['dol_screenheight']) ? '' : $_SESSION['dol_screenheight']);
2670 $dropdownBody .= ' <span class="opacitymedium">('.$conf->browser->layout.')</span>';
2671 if (!empty($_SESSION["disablemodules"])) {
2672 $dropdownBody .= '<br><b>'.$langs->trans("DisabledModules").':</b> <br>'.implode(', ', explode(',', $_SESSION["disablemodules"]));
2673 }
2674 $dropdownBody .= '</div>';
2675
2676 // Execute hook
2677 $parameters = array('user' => $user, 'langs' => $langs);
2678 $result = $hookmanager->executeHooks('printTopRightMenuLoginDropdownBody', $parameters); // Note that $action and $object may have been modified by some hooks
2679 if (is_numeric($result)) {
2680 if ($result == 0) {
2681 $dropdownBody .= $hookmanager->resPrint; // add
2682 } else {
2683 $dropdownBody = $hookmanager->resPrint; // replace
2684 }
2685 }
2686
2687 if (empty($urllogout)) {
2688 $urllogout = dolBuildUrl(DOL_URL_ROOT . '/user/logout.php', [], true);
2689 }
2690
2691 // Defined the links for bottom of card
2692 $profilLink = '<a accesskey="u" href="'.DOL_URL_ROOT.'/user/card.php?id='.$user->id.'" class="button-top-menu-dropdown" title="'.dol_escape_htmltag($langs->trans("YourUserFile").' ('.$conf->browser->stringforfirstkey.' u)').'"><i class="fa fa-user"></i> '.$langs->trans("Card").'</a>';
2693 $urltovirtualcard = '/user/virtualcard.php?id='.((int) $user->id);
2694 $jsonopen = "closeTopMenuLoginDropdown()";
2695 $virtuelcardLink = dolButtonToOpenUrlInDialogPopup('publicvirtualcardmenu', $langs->transnoentitiesnoconv("PublicVirtualCardUrl").(is_object($user) ? ' - '.$user->getFullName($langs) : '').' ('.$conf->browser->stringforfirstkey.' v)', img_picto($langs->trans("PublicVirtualCardUrl").' ('.$conf->browser->stringforfirstkey.' v)', 'card', ''), $urltovirtualcard, '', 'button-top-menu-dropdown marginleftonly nohover', $jsonopen, '', 'v');
2696 $logoutLink = '<a accesskey="l" href="'.$urllogout.'" class="button-top-menu-dropdown" title="'.dol_escape_htmltag($langs->trans("Logout").' ('.$conf->browser->stringforfirstkey.' l)').'"><i class="fa fa-sign-out-alt pictofixedwidth"></i><span class="hideonsmartphone">'.$langs->trans("Logout").'</span></a>';
2697
2698 $profilName = $user->getFullName($langs).' ('.$user->login.')';
2699 if (!empty($user->admin)) {
2700 $profilName = img_picto($langs->trans("Administrator"), 'admin').' '.$profilName;
2701 }
2702
2703 // Define version to show
2704 $appli = constant('DOL_APPLICATION_TITLE');
2705 $applicustom = getDolGlobalString('MAIN_APPLICATION_TITLE');
2706 if ($applicustom) {
2707 $appli = (preg_match('/^\+/', $applicustom) ? $appli : '').$applicustom;
2708 } else {
2709 $appli .= " ".DOL_VERSION;
2710 }
2711
2712 if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2713 $btnUser = '<!-- div for user link -->
2714 <div id="topmenu-login-dropdown" class="userimg atoplogin dropdown user user-menu inline-block">
2715 <a href="'.DOL_URL_ROOT.'/user/card.php?id='.$user->id.'" class="dropdown-toggle login-dropdown-a valignmiddle" data-toggle="dropdown">
2716 '.$userImage.(empty($user->photo) ? '<!-- no photo so show also the login --><span class="hidden-xs maxwidth200 atoploginusername hideonsmartphone paddingleft valignmiddle small">'.dol_trunc($user->firstname ? $user->firstname : $user->login, 10).'</span>' : '').'
2717 </a>
2718 <div class="dropdown-menu">
2719 <!-- User image -->
2720 <div class="user-header">
2721 '.$userDropDownImage.'
2722 <p>
2723 '.$profilName.'<br>';
2724 $title = '';
2725 if ($user->datelastlogin) {
2726 $title = $langs->trans("ConnectedSince").' : '.dol_print_date($user->datelastlogin, "dayhour", 'tzuser');
2727 if ($user->datepreviouslogin) {
2728 $title .= '<br>'.$langs->trans("PreviousConnexion").' : '.dol_print_date($user->datepreviouslogin, "dayhour", 'tzuser');
2729 }
2730 }
2731 $btnUser .= '<small class="classfortooltip" title="'.dol_escape_htmltag($title).'" ><i class="fa fa-user-clock"></i> '.dol_print_date($user->datelastlogin, "dayhour", 'tzuser').'</small><br>';
2732 if ($user->datepreviouslogin) {
2733 $btnUser .= '<small class="classfortooltip" title="'.dol_escape_htmltag($title).'" ><i class="fa fa-user-clock opacitymedium"></i> '.dol_print_date($user->datepreviouslogin, "dayhour", 'tzuser').'</small><br>';
2734 }
2735
2736 //$btnUser .= '<small class="classfortooltip"><i class="fa fa-cog"></i> '.$langs->trans("Version").' '.$appli.'</small>';
2737 $btnUser .= '
2738 </p>
2739 </div>
2740
2741 <!-- Menu Body user-->
2742 <div class="user-body">'.$dropdownBody.'</div>
2743
2744 <!-- Menu Footer-->
2745 <div class="user-footer">
2746 <div class="pull-left">
2747 '.$profilLink.'
2748 </div>
2749 <div class="pull-left">
2750 '.$virtuelcardLink.'
2751 </div>
2752 <div class="pull-right">
2753 '.$logoutLink.'
2754 </div>
2755 <div class="clearboth"></div>
2756 </div>
2757
2758 </div>
2759 </div>';
2760 } else {
2761 $btnUser = '<!-- div for user link text browser -->
2762 <div id="topmenu-login-dropdown" class="userimg atoplogin dropdown user user-menu inline-block">
2763 <a href="'.DOL_URL_ROOT.'/user/card.php?id='.$user->id.'" class="valignmiddle" alt="'.$langs->trans("MyUserCard").'">
2764 '.$userImage.(empty($user->photo) ? '<span class="hidden-xs maxwidth200 atoploginusername hideonsmartphone paddingleft small valignmiddle">'.dol_trunc($user->firstname ? $user->firstname : $user->login, 10).'</span>' : '').'
2765 </a>
2766 </div>';
2767 }
2768
2769 if (!defined('JS_JQUERY_DISABLE_DROPDOWN') && !empty($conf->use_javascript_ajax)) { // This may be set by some pages that use different jquery version to avoid errors
2770 $btnUser .= '
2771 <!-- Code to show/hide the user drop-down -->
2772 <script>
2773 function closeTopMenuLoginDropdown() {
2774 console.log("close login dropdown"); // This is called at each click on page, so we disable the log
2775 // Hide the menus.
2776 jQuery("#topmenu-login-dropdown").removeClass("open");
2777 }
2778 jQuery(document).ready(function() {
2779 jQuery(document).on("click", function(event) {
2780 if (jQuery("#topmenu-login-dropdown").hasClass("open")) {
2781 if (!$(event.target).closest("#topmenu-login-dropdown").length) {
2782 console.log("click close login - we click outside");
2783 // Hide the dropdown.
2784 closeTopMenuLoginDropdown();
2785 }
2786 }
2787 });
2788 ';
2789
2790
2791 $btnUser .= '
2792 jQuery("#topmenu-login-dropdown .dropdown-toggle").on("click", function(event) {
2793 console.log("Click on #topmenu-login-dropdown .dropdown-toggle");
2794 event.preventDefault();
2795 jQuery("#topmenu-login-dropdown").toggleClass("open");
2796 });
2797
2798 jQuery("#topmenulogincompanyinfo-btn").on("click", function() {
2799 console.log("Click on #topmenulogincompanyinfo-btn");
2800 if (!jQuery("#topmenuloginmoreinfo").is(\':hidden\')) {
2801 jQuery("#topmenuloginmoreinfo").slideToggle();
2802 }
2803 jQuery("#topmenulogincompanyinfo").slideToggle();
2804 });
2805
2806 jQuery("#topmenuloginmoreinfo-btn").on("click", function() {
2807 console.log("Click on #topmenuloginmoreinfo-btn");
2808 if (!jQuery("#topmenulogincompanyinfo").is(\':hidden\')) {
2809 jQuery("#topmenulogincompanyinfo").slideToggle();
2810 }
2811 jQuery("#topmenuloginmoreinfo").slideToggle();
2812 });';
2813
2814 $btnUser .= '
2815 });
2816 </script>
2817 ';
2818 }
2819
2820 return $btnUser;
2821}
2822
2831function top_menu_ai()
2832{
2833 global $conf, $langs, $user;
2834
2835 $html = '';
2836
2837 if (!isModEnabled('ai') || !getDolGlobalString('AI_ASSISTANT_ENABLED') || empty($conf->use_javascript_ajax)) {
2838 return $html;
2839 }
2840 // Per-user gate: same right as the assistant page and its endpoints.
2841 // Without the right, show a greyed non clickable icon so the user knows the feature exists.
2842 if (!$user->hasRight('ai', 'assistant', 'use')) {
2843 $html .= '<!-- div for AI Assistant link (disabled, no permission) -->
2844 <div id="topmenu-ai-dropdown" class="atoplogin dropdown inline-block">
2845 <a class="login-dropdown-a nofocusvisible opacitymedium cursornotallowed classfortooltip" title="'.dol_escape_htmltag($langs->trans('AIAssistant').' - '.$langs->trans('NotEnoughPermissions')).'"><i class="fa fa-magic"></i></a>
2846 </div>';
2847 return $html;
2848 }
2849
2850 $ailabel = $langs->trans('AIAssistant').' ('.$conf->browser->stringforfirstkey.' a)';
2851
2852 // On smartphone, no popover: the icon is a direct link to the standalone assistant page.
2853 if (!empty($conf->dol_optimize_smallscreen)) {
2854 $html .= '<!-- div for AI Assistant link (opens the AI assistant page) -->
2855 <div id="topmenu-ai-dropdown" class="atoplogin dropdown inline-block">
2856 <a accesskey="a" href="'.DOL_URL_ROOT.'/ai/assistant/index.php?mainmenu=tools&amp;leftmenu=ai" id="topmenu-ai-toggle" class="login-dropdown-a nofocusvisible" title="'.dol_escape_htmltag($ailabel).'"><i class="fa fa-magic"></i></a>
2857 </div>';
2858 return $html;
2859 }
2860
2861 // Chat CSS is needed on every page showing the icon (link-in-body is valid HTML5,
2862 // the standalone page ai/assistant/index.php uses the same pattern). Same
2863 // filemtime cache-busting as the JS module below: a stylesheet cached for
2864 // 15 minutes otherwise hides every CSS change of the chat behind a reload.
2865 $aicssver = @filemtime(DOL_DOCUMENT_ROOT.'/ai/css/ai_assistant.css');
2866 $html .= '<link rel="stylesheet" href="'.DOL_URL_ROOT.'/ai/css/ai_assistant.css?v='.urlencode((string) ($aicssver ? $aicssver : DOL_VERSION)).'">';
2867
2868 // Toggle icon. The accesskey "a" keeps the Alt+A shortcut: its browser
2869 // activation fires the click handler below, so it toggles the popover.
2870 $html .= '<!-- div for AI Assistant link (opens the AI chat popover) -->
2871 <div id="topmenu-ai-dropdown" class="atoplogin dropdown inline-block">
2872 <a accesskey="a" href="#" id="topmenu-ai-toggle" class="login-dropdown-a nofocusvisible" title="'.dol_escape_htmltag($ailabel).'"><i class="fa fa-magic"></i></a>
2873 </div>';
2874
2875 // Popover shell (hidden by CSS until .open). The chat fragment is fetched on
2876 // first open; afterwards open/close only toggles visibility so the
2877 // conversation survives. Moved to <body> on first use by the script below.
2878 $html .= '<div id="topmenu-ai-popover" class="ai-popover" role="dialog" aria-modal="false" aria-label="'.dol_escape_htmltag($langs->trans('AIAssistant')).'">
2879 <div class="ai-popover-body"><div class="ai-popover-loading"><i class="fa fa-circle-notch fa-spin"></i></div></div>
2880 </div>';
2881
2882 // Cache-busting version for the JS module: filemtime invalidates the browser
2883 // cache whenever the file actually changes (e.g. after a branch switch),
2884 // avoiding a stale module without the initAiAssistant() export.
2885 $aijsfile = DOL_DOCUMENT_ROOT.'/ai/js/ai_assistant.js';
2886 $aijsver = @filemtime($aijsfile);
2887 $aijsurl = DOL_URL_ROOT.'/ai/js/ai_assistant.js?v='.urlencode((string) ($aijsver ? $aijsver : DOL_VERSION));
2888
2889 $html .= '<script nonce="'.getNonce().'">
2890 jQuery(document).ready(function() {
2891 jQuery(document).on("click", function(event) {
2892 if (jQuery("#topmenu-ai-popover").hasClass("open")) {
2893 // A click on a node removed from the DOM while the event was bubbling
2894 // (e.g. a chat action button like "Yes, continue" that removes its own
2895 // message bubble) must not be mistaken for a click outside the popover:
2896 // .closest() cannot reach the popover from a detached node.
2897 if (event.target instanceof Element && !event.target.isConnected) {
2898 return;
2899 }
2900 if (!$(event.target).closest("#topmenu-ai-toggle").length && !$(event.target).closest("#topmenu-ai-popover").length) {
2901 console.log("click close ai dropdown - we click outside");
2902 // Hide the dropdown.
2903 jQuery("#topmenu-ai-popover").removeClass("open");
2904 }
2905 }
2906 });
2907 });
2908
2909 // Clear the AI chat conversations kept in sessionStorage when the user logs out.
2910 document.addEventListener("click", function (event) {
2911 var link = event.target.closest("a[href*=\"/user/logout.php\"]");
2912 if (!link) { return; }
2913 try {
2914 for (var i = sessionStorage.length - 1; i >= 0; i--) {
2915 var key = sessionStorage.key(i);
2916 if (key && key.indexOf("aiChatHistory_") === 0) { sessionStorage.removeItem(key); }
2917 }
2918 } catch (e) { /* storage not available */ }
2919 });
2920
2921 (function () {
2922 var toggle = document.getElementById("topmenu-ai-toggle");
2923 var popover = document.getElementById("topmenu-ai-popover");
2924 if (!toggle || !popover) { return; }
2925 var body = popover.querySelector(".ai-popover-body");
2926 var loaded = false;
2927 var loading = false;
2928
2929 function positionPopover() {
2930 var top = document.getElementById("id-top");
2931 var anchor = (top ? top.getBoundingClientRect().bottom : 44) + 4;
2932 popover.style.setProperty("--ai-popover-top", anchor + "px");
2933 }
2934
2935 function loadChat() {
2936 if (loaded || loading) { return; }
2937 loading = true;
2938 // Resolved against location.origin: fetch() rejects a URL inheriting user:pass@ from the page URL.
2939 fetch(new URL("'.DOL_URL_ROOT.'/ai/assistant/popover.php", window.location.origin).href, { credentials: "same-origin" })
2940 .then(function (resp) {
2941 if (!resp.ok) { throw new Error("HTTP " + resp.status); }
2942 return resp.text();
2943 })
2944 .then(function (htmlcontent) {
2945 body.innerHTML = htmlcontent;
2946 return import(\''.dol_escape_js($aijsurl).'\').then(function (mod) {
2947 mod.initAiAssistant(body.querySelector(".ai-chat-container"));
2948 });
2949 })
2950 .then(function () {
2951 loaded = true;
2952 focusInput();
2953 })
2954 .catch(function (e) {
2955 console.error("AI Assistant popover load failed", e);
2956 body.innerHTML = \'<div class="ai-popover-loading">'.dol_escape_js($langs->trans('Error')).'</div>\';
2957 })
2958 .finally(function () { loading = false; });
2959 }
2960
2961 function focusInput() {
2962 var input = body.querySelector("#user-input");
2963 if (input) { input.focus(); }
2964 }
2965
2966 // The expand button always opens the standalone full page
2967 // (/ai/assistant/index.php) in the current tab. There is no small mode:
2968 // the popover opens and stays in the large ("expanded") state.
2969 toggle.addEventListener("click", function (event) {
2970 console.log("Click on #topmenu-ai-toggle");
2971 event.preventDefault();
2972 // position:fixed can be hijacked by a transformed ancestor: hosting the
2973 // panel directly under <body> guarantees viewport coordinates.
2974 if (popover.parentNode !== document.body) { document.body.appendChild(popover); }
2975 positionPopover();
2976 var isOpen = popover.classList.toggle("open");
2977 if (isOpen) {
2978 // Always open in the large ("expanded") state.
2979 popover.classList.add("expanded");
2980 loadChat();
2981 if (loaded) { focusInput(); }
2982 }
2983 });
2984
2985 popover.addEventListener("click", function (event) {
2986 console.log("Click on #topmenu-ai-popover");
2987 var closeBtn = event.target.closest("#ai-close-btn");
2988 var expandBtn = event.target.closest("#ai-expand-btn");
2989 if (closeBtn) {
2990 popover.classList.remove("open");
2991 } else if (expandBtn) {
2992 // Open the standalone full page in the current tab.
2993 var url = expandBtn.dataset.fullscreenUrl;
2994 if (url) { window.location.href = url; }
2995 }
2996 });
2997
2998 document.addEventListener("keydown", function (event) {
2999 if (event.key === "Escape" && popover.classList.contains("open")) {
3000 popover.classList.remove("open");
3001 }
3002 });
3003 })();
3004 </script>';
3005
3006 return $html;
3007}
3008
3016{
3017 global $conf, $langs;
3018
3019 // Button disabled on text browser
3020 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3021 return '';
3022 }
3023
3024 $html = '';
3025
3026 if (!empty($conf->use_javascript_ajax)) {
3027 $html .= '<!-- div for quick add link -->
3028 <div id="topmenu-quickadd-dropdown" class="atoplogin dropdown inline-block">
3029 <a accesskey="c" class="dropdown-toggle login-dropdown-a nofocusvisible" data-toggle="dropdown" href="#" title="'.$langs->trans('QuickAdd').' ('.$conf->browser->stringforfirstkey.' c)"><i class="fa fa-plus-circle"></i></a>
3030 <div class="dropdown-menu">'.printDropdownQuickadd().'</div>
3031 </div>';
3032 if (!defined('JS_JQUERY_DISABLE_DROPDOWN')) { // This may be set by some pages that use different jquery version to avoid errors
3033 $html .= '
3034 <!-- Code to show/hide the user drop-down for the quick add -->
3035 <script nonce="'.getNonce().'">
3036 jQuery(document).ready(function() {
3037 jQuery(document).on("click", function(event) {
3038 if (jQuery("#topmenu-quickadd-dropdown").hasClass("open")) {
3039 if (!$(event.target).closest("#topmenu-quickadd-dropdown").length) {
3040 console.log("click close quick add - we click outside");
3041 // Hide the dropdown.
3042 $("#topmenu-quickadd-dropdown").removeClass("open");
3043 }
3044 }
3045 });
3046 $("#topmenu-quickadd-dropdown .dropdown-toggle").on("click", function(event) {
3047 console.log("Click on #topmenu-quickadd-dropdown .dropdown-toggle");
3048 openQuickAddDropDown(event);
3049 });
3050
3051 // Key map shortcut
3052 $(document).keydown(function(event){
3053 var ostype = \''.dol_escape_js($conf->browser->os).'\';
3054 if (ostype === "macintosh") {
3055 if ( event.which === 65 && event.ctrlKey ) {
3056 console.log(\'control + a : trigger open quick add dropdown\');
3057 openQuickAddDropDown(event);
3058 }
3059 } else {
3060 if ( event.which === 65 && event.ctrlKey && event.shiftKey ) {
3061 console.log(\'control + shift + a : trigger open quick add dropdown\');
3062 openQuickAddDropDown(event);
3063 }
3064 }
3065 });
3066
3067 var openQuickAddDropDown = function(event) {
3068 event.preventDefault();
3069 $("#topmenu-quickadd-dropdown").toggleClass("open");
3070 }
3071 });
3072 </script>
3073 ';
3074 }
3075 }
3076
3077 return $html;
3078}
3079
3080
3088{
3089 global $conf, $langs;
3090
3091 // Button disabled on text browser
3092 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3093 return '';
3094 }
3095
3096 $html = '';
3097
3098 if (!empty($conf->use_javascript_ajax)) {
3099 $urlforuploadpage = DOL_URL_ROOT.'/core/upload_page.php';
3100 if (!is_numeric(getDolGlobalString('MAIN_USE_TOP_MENU_IMPORT_FILE'))) {
3101 $urlforuploadpage = getDolGlobalString('MAIN_USE_TOP_MENU_IMPORT_FILE');
3102 } elseif (!isModEnabled('ai')) {
3103 // The native upload page uses the AI module to parse the files, so the button is hidden when the module is not enabled
3104 return '';
3105 }
3106
3107 $html .= '<!-- div for link to upload file -->
3108 <div id="topmenu-uploadfile-dropdown" class="atoplogin dropdown inline-block">
3109 <a accesskey="i" class="dropdown-togglex login-dropdown-a nofocusvisible" data-toggle="dropdown" href="'.$urlforuploadpage.'" title="'.$langs->trans('UploadFile').' ('.$conf->browser->stringforfirstkey.' i)"><i class="fa fa-upload"></i></a>
3110 </div>';
3111 }
3112
3113 return $html;
3114}
3115
3116
3123function printDropdownQuickadd($mode = 0)
3124{
3125 global $user, $langs, $hookmanager;
3126
3127 $items = array(
3128 'items' => array(
3129 array(
3130 "url" => "/adherents/card.php?action=create&amp;mainmenu=members",
3131 "title" => "MenuNewMember@members",
3132 "name" => "Adherent@members",
3133 "picto" => "object_member",
3134 "activation" => isModEnabled('member') && $user->hasRight("adherent", "write"), // vs hooking
3135 "position" => 5,
3136 ),
3137 array(
3138 "url" => "/societe/card.php?action=create&amp;mainmenu=companies",
3139 "title" => "MenuNewThirdParty@companies",
3140 "name" => "ThirdParty@companies",
3141 "picto" => "object_company",
3142 "activation" => isModEnabled("societe") && $user->hasRight("societe", "write"), // vs hooking
3143 "position" => 10,
3144 ),
3145 array(
3146 "url" => "/contact/card.php?action=create&amp;mainmenu=companies",
3147 "title" => "NewContactAddress@companies",
3148 "name" => "Contact@companies",
3149 "picto" => "object_contact",
3150 "activation" => isModEnabled("societe") && $user->hasRight("societe", "contact", "write"), // vs hooking
3151 "position" => 20,
3152 ),
3153 array(
3154 "url" => "/comm/propal/card.php?action=create&amp;mainmenu=commercial",
3155 "title" => "NewPropal@propal",
3156 "name" => "Proposal@propal",
3157 "picto" => "object_propal",
3158 "activation" => isModEnabled("propal") && $user->hasRight("propal", "write"), // vs hooking
3159 "position" => 30,
3160 ),
3161
3162 array(
3163 "url" => "/commande/card.php?action=create&amp;mainmenu=commercial",
3164 "title" => "NewOrder@orders",
3165 "name" => "Order@orders",
3166 "picto" => "object_order",
3167 "activation" => isModEnabled('order') && $user->hasRight("commande", "write"), // vs hooking
3168 "position" => 40,
3169 ),
3170 array(
3171 "url" => "/compta/facture/card.php?action=create&amp;mainmenu=billing",
3172 "title" => "NewBill@bills",
3173 "name" => "Bill@bills",
3174 "picto" => "object_bill",
3175 "activation" => isModEnabled('invoice') && $user->hasRight("facture", "write"), // vs hooking
3176 "position" => 50,
3177 ),
3178 array(
3179 "url" => "/contrat/card.php?action=create&amp;mainmenu=commercial",
3180 "title" => "NewContractSubscription@contracts",
3181 "name" => "Contract@contracts",
3182 "picto" => "object_contract",
3183 "activation" => isModEnabled('contract') && $user->hasRight("contrat", "write"), // vs hooking
3184 "position" => 60,
3185 ),
3186 array(
3187 "url" => "/supplier_proposal/card.php?action=create&amp;mainmenu=commercial",
3188 "title" => "SupplierProposalNew@supplier_proposal",
3189 "name" => "SupplierProposal@supplier_proposal",
3190 "picto" => "supplier_proposal",
3191 "activation" => isModEnabled('supplier_proposal') && $user->hasRight("supplier_invoice", "write"), // vs hooking
3192 "position" => 70,
3193 ),
3194 array(
3195 "url" => "/fourn/commande/card.php?action=create&amp;mainmenu=commercial",
3196 "title" => "NewSupplierOrderShort@orders",
3197 "name" => "SupplierOrder@orders",
3198 "picto" => "supplier_order",
3199 "activation" => (isModEnabled("fournisseur") && !getDolGlobalString('MAIN_USE_NEW_SUPPLIERMOD') && $user->hasRight("fournisseur", "commande", "write")) || (isModEnabled("supplier_order") && $user->hasRight("supplier_invoice", "write")), // vs hooking
3200 "position" => 80,
3201 ),
3202 array(
3203 "url" => "/fourn/facture/card.php?action=create&amp;mainmenu=billing",
3204 "title" => "NewBill@bills",
3205 "name" => "SupplierBill@bills",
3206 "picto" => "supplier_invoice",
3207 "activation" => (isModEnabled("fournisseur") && !getDolGlobalString('MAIN_USE_NEW_SUPPLIERMOD') && $user->hasRight("fournisseur", "facture", "write")) || (isModEnabled("supplier_invoice") && $user->hasRight("supplier_invoice", "write")), // vs hooking
3208 "position" => 90,
3209 ),
3210 array(
3211 "url" => "/ticket/card.php?action=create&amp;mainmenu=ticket",
3212 "title" => "NewTicket@ticket",
3213 "name" => "Ticket@ticket",
3214 "picto" => "ticket",
3215 "activation" => isModEnabled('ticket') && $user->hasRight("ticket", "write"), // vs hooking
3216 "position" => 100,
3217 ),
3218 array(
3219 "url" => "/fichinter/card.php?action=create&mainmenu=commercial",
3220 "title" => "NewIntervention@interventions",
3221 "name" => "Intervention@interventions",
3222 "picto" => "intervention",
3223 "activation" => isModEnabled('intervention') && $user->hasRight("ficheinter", "creer"), // vs hooking
3224 "position" => 110,
3225 ),
3226 array(
3227 "url" => "/product/card.php?action=create&amp;type=0&amp;mainmenu=products",
3228 "title" => "NewProduct@products",
3229 "name" => "Product@products",
3230 "picto" => "object_product",
3231 "activation" => isModEnabled("product") && $user->hasRight("produit", "write"), // vs hooking
3232 "position" => 400,
3233 ),
3234 array(
3235 "url" => "/product/card.php?action=create&amp;type=1&amp;mainmenu=products",
3236 "title" => "NewService@products",
3237 "name" => "Service@products",
3238 "picto" => "object_service",
3239 "activation" => isModEnabled("service") && $user->hasRight("service", "write"), // vs hooking
3240 "position" => 410,
3241 ),
3242 array(
3243 "url" => "/product/stock/stocktransfer/stocktransfer_card.php?action=create&amp;mainmenu=products",
3244 "title" => "StockTransferNew@stocks",
3245 "name" => "StockTransfer@stocks",
3246 "picto" => "stock",
3247 "activation" => isModEnabled("stocktransfer") && $user->hasRight("stocktransfer", "stocktransfer", "write"), // vs hooking
3248 "position" => 415,
3249 ),
3250 array(
3251 "url" => "/user/card.php?action=create&amp;type=1&amp;mainmenu=home",
3252 "title" => "AddUser@users",
3253 "name" => "User@users",
3254 "picto" => "user",
3255 "activation" => $user->hasRight("user", "user", "write"), // vs hooking
3256 "position" => 500,
3257 ),
3258 ),
3259 );
3260
3261 $dropDownQuickAddHtml = '';
3262
3263 // Define $dropDownQuickAddHtml
3264 if (empty($mode)) {
3265 $dropDownQuickAddHtml .= '<div class="quickadd-body dropdown-body">';
3266 }
3267 $dropDownQuickAddHtml .= '<div class="dropdown-quickadd-list">';
3268
3269 // Allow the $items of the menu to be manipulated by modules
3270 $parameters = array();
3271 $hook_items = $items;
3272 $reshook = $hookmanager->executeHooks('menuDropdownQuickaddItems', $parameters, $hook_items); // Note that $action and $object may have been modified by some hooks @phan-suppress-current-line PhanTypeMismatchArgument
3273 if (is_numeric($reshook) && !empty($hookmanager->resArray) && is_array($hookmanager->resArray)) {
3274 if ($reshook == 0) {
3275 $items['items'] = array_merge($items['items'], $hookmanager->resArray); // add
3276 } else {
3277 $items = $hookmanager->resArray; // replace
3278 }
3279
3280 // Sort menu items by 'position' value
3281 $position = array();
3282 foreach ($items['items'] as $key => $row) {
3283 $position[$key] = $row['position'];
3284 }
3285 $array1_sort_order = SORT_ASC;
3286 array_multisort($position, $array1_sort_order, $items['items']);
3287 }
3288
3289 foreach ($items['items'] as $item) {
3290 if (!$item['activation']) {
3291 continue;
3292 }
3293 $langs->load(explode('@', $item['title'])[1]);
3294 $langs->load(explode('@', $item['name'])[1]);
3295 $dropDownQuickAddHtml .= '
3296 <a class="dropdown-item quickadd-item" href="'.DOL_URL_ROOT.$item['url'].'" title="'.$langs->trans(explode('@', $item['title'])[0]).'">
3297 '. img_picto('', $item['picto'], 'style="width:18px;"') . ' ' . $langs->trans(explode('@', $item['name'])[0]) . '</a>
3298 ';
3299 }
3300
3301 if (empty($mode)) {
3302 $dropDownQuickAddHtml .= '</div>';
3303 }
3304 $dropDownQuickAddHtml .= '</div>';
3305
3306 return $dropDownQuickAddHtml;
3307}
3308
3315{
3316 global $langs, $conf, $user;
3317
3318 $html = '';
3319
3320 // Return empty in some case
3321 if (!isModEnabled('bookmark') || !$user->hasRight('bookmark', 'lire')) {
3322 return '';
3323 }
3324 /*
3325 if ($conf->browser->name == 'textbrowser') {
3326 return $html;
3327 }
3328 */
3329
3330 if (!defined('JS_JQUERY_DISABLE_DROPDOWN') && !empty($conf->use_javascript_ajax)) { // This may be set by some pages that use different jquery version to avoid errors
3331 include_once DOL_DOCUMENT_ROOT.'/bookmarks/bookmarks.lib.php';
3332 $langs->load("bookmarks");
3333
3334 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
3335 $html .= '<div id="topmenu-bookmark-dropdown" class="atoplogin dropdown inline-block">';
3336 $html .= printDropdownBookmarksList();
3337 $html .= '</div>';
3338 } else {
3339 $html .= '<!-- div for bookmark link -->
3340 <div id="topmenu-bookmark-dropdown" class="atoplogin dropdown inline-block">
3341 <a accesskey="b" class="dropdown-toggle login-dropdown-a nofocusvisible" data-toggle="dropdown" href="#" title="'.$langs->trans('Bookmarks').' ('.$conf->browser->stringforfirstkey.' b)"><i class="fa fa-star"></i></a>
3342 <div class="dropdown-menu">
3344 </div>
3345 </div>';
3346
3347 $html .= '
3348 <!-- Code to show/hide the bookmark drop-down -->
3349 <script>
3350 jQuery(document).ready(function() {
3351 jQuery(document).on("click", function(event) {
3352 if (jQuery("#topmenu-bookmark-dropdown").hasClass("open")) {
3353 if (!$(event.target).closest("#topmenu-bookmark-dropdown").length) {
3354 console.log("close bookmark dropdown - we click outside");
3355 // Hide the menus.
3356 $("#topmenu-bookmark-dropdown").removeClass("open");
3357 }
3358 }
3359 });
3360
3361 jQuery("#topmenu-bookmark-dropdown .dropdown-toggle").on("click", function(event) {
3362 console.log("Click on #topmenu-bookmark-dropdown .dropdown-toggle");
3363 openBookMarkDropDown(event);
3364 });
3365
3366 // Key map shortcut
3367 jQuery(document).keydown(function(event) {
3368 var ostype = \''.dol_escape_js($conf->browser->os).'\';
3369 if (ostype === "macintosh") {
3370 if ( event.which === 66 && event.ctrlKey ) {
3371 console.log("Click on control + b : trigger open bookmark dropdown");
3372 openBookMarkDropDown(event);
3373 }
3374 } else {
3375 if ( event.which === 66 && event.ctrlKey && event.shiftKey ) {
3376 console.log("Click on control + shift + b : trigger open bookmark dropdown");
3377 openBookMarkDropDown(event);
3378 }
3379 }
3380 });
3381
3382 var openBookMarkDropDown = function(event) {
3383 console.log("toggle #topmenu-bookmark-dropdown and force focus");
3384 event.preventDefault();
3385 jQuery("#topmenu-bookmark-dropdown").toggleClass("open");
3386 jQuery("#top-bookmark-search-input").focus();
3387 }
3388
3389 });
3390 </script>
3391 ';
3392 }
3393 }
3394 return $html;
3395}
3396
3402function top_menu_search()
3403{
3404 global $langs, $conf, $db, $user, $hookmanager; // used by htdocs/core/ajax/selectsearchbox.php
3405
3406 $html = '';
3407
3408 $usedbyinclude = 1; // Used by selectsearchbox.php
3409 $arrayresult = array();
3410 include DOL_DOCUMENT_ROOT.'/core/ajax/selectsearchbox.php'; // This sets $arrayresult
3411
3412 $searchInput = '<input type="search" name="search_all" title="'.dol_escape_htmltag($conf->browser->stringforfirstkey.' s').'" id="top-global-search-input" class="dropdown-search-input search_component_input" placeholder="'.$langs->trans('Search').'" autocomplete="off">';
3413
3414 $defaultAction = '';
3415 $buttonList = '<div class="dropdown-global-search-button-list" >';
3416 // Menu with all searchable items
3417 // @phan-suppress-next-line PhanEmptyForeach // array is really empty
3418 foreach ($arrayresult as $keyItem => $item) {
3419 if (empty($defaultAction)) {
3420 $defaultAction = $item['url'];
3421 }
3422 $buttonList .= '<button class="dropdown-item global-search-item '.(empty($conf->dol_optimize_smallscreen) ? 'tdoverflowmax400' : 'tdoverflowmax300').'" data-target="'.dol_escape_htmltag($item['url']).'" >';
3423 $buttonList .= $item['text'];
3424 $buttonList .= '</button>';
3425 }
3426 $buttonList .= '</div>';
3427
3428 $dropDownHtml = '<form role="search" id="top-menu-action-search" name="actionsearch" method="GET" action="'.$defaultAction.'">';
3429
3430 $dropDownHtml .= '
3431 <!-- search input -->
3432 <div class="dropdown-header search-dropdown-header">
3433 ' . $searchInput.'
3434 </div>
3435 ';
3436
3437 $dropDownHtml .= '
3438 <!-- Menu Body search -->
3439 <div class="dropdown-body search-dropdown-body">
3440 '.$buttonList.'
3441 </div>
3442 ';
3443
3444 $dropDownHtml .= '</form>';
3445
3446 $html .= '<!-- div for Global Search -->
3447 <div id="topmenu-global-search-dropdown" class="atoplogin dropdown inline-block">
3448 <a accesskey="s" class="dropdown-toggle login-dropdown-a nofocusvisible" data-toggle="dropdown" href="#" title="'.$langs->trans('Search').' ('.$conf->browser->stringforfirstkey.' s)">
3449 <i class="fa fa-search" aria-hidden="true" ></i>
3450 </a>
3451 <div class="dropdown-menu dropdown-search">
3452 '.$dropDownHtml.'
3453 </div>
3454 </div>';
3455
3456 $html .= '
3457 <!-- Code to show/hide the user drop-down -->
3458 <script>
3459 jQuery(document).ready(function() {
3460
3461 // prevent submitting form on press ENTER
3462 jQuery("#top-global-search-input").keydown(function (e) {
3463 if (e.keyCode == 13 || e.keyCode == 40) {
3464 var inputs = $(this).parents("form").eq(0).find(":button");
3465 if (inputs[inputs.index(this) + 1] != null) {
3466 console.log("Force focus after keydow on #top-global-search-input");
3467 inputs[inputs.index(this) + 1].focus();
3468 if (e.keyCode == 13){
3469 inputs[inputs.index(this) + 1].trigger("click");
3470 }
3471
3472 }
3473 e.preventDefault();
3474 return false;
3475 }
3476 });
3477
3478 // arrow key nav
3479 jQuery(document).keydown(function(e) {
3480 // Get the focused element:
3481 var $focused = $(":focus");
3482 if($focused.length && $focused.hasClass("global-search-item")){
3483
3484 // UP - move to the previous line
3485 if (e.keyCode == 38) {
3486 e.preventDefault();
3487 console.log("Force focus after keycode 38");
3488 $focused.prev().focus();
3489 }
3490
3491 // DOWN - move to the next line
3492 if (e.keyCode == 40) {
3493 e.preventDefault();
3494 console.log("Force focus after keycode 40");
3495 $focused.next().focus();
3496 }
3497 }
3498 });
3499
3500
3501 // submit form action
3502 jQuery(".dropdown-global-search-button-list .global-search-item").on("click", function(event) {
3503 jQuery("#top-menu-action-search").attr("action", $(this).data("target"));
3504 jQuery("#top-menu-action-search").submit();
3505 });
3506
3507 // Close drop down
3508 jQuery(document).on("click", function(event) {
3509 if (jQuery("#topmenu-global-search-dropdown").hasClass("open")) {
3510 if (!$(event.target).closest("#topmenu-global-search-dropdown").length) {
3511 console.log("click close search - we click outside");
3512 // Hide the dropdown.
3513 jQuery("#topmenu-global-search-dropdown").removeClass("open");
3514 }
3515 }
3516 });
3517
3518 // Open drop down
3519 jQuery("#topmenu-global-search-dropdown .dropdown-toggle").on("click", function(event) {
3520 console.log("click on toggle #topmenu-global-search-dropdown .dropdown-toggle");
3521 openGlobalSearchDropDown();
3522 });
3523
3524 // Key map shortcut
3525 jQuery(document).keydown(function(e){
3526 if ( e.which === 70 && e.ctrlKey && e.shiftKey ) {
3527 console.log(\'control + shift + f : trigger open global-search dropdown\');
3528 openGlobalSearchDropDown();
3529 }
3530 if ( e.which === 70 && e.alKey ) {
3531 console.log(\'alt + f : trigger open global-search dropdown\');
3532 openGlobalSearchDropDown();
3533 }
3534 });
3535
3536 var openGlobalSearchDropDown = function() {
3537 jQuery("#topmenu-global-search-dropdown").toggleClass("open");
3538 jQuery("#top-global-search-input").focus();
3539 }
3540
3541 });
3542 </script>
3543 ';
3544
3545 return $html;
3546}
3547
3562function left_menu($menu_array_before, $helppagename = '', $notused = '', $menu_array_after = array(), $leftmenuwithoutmainarea = 0, $title = '', $acceptdelayedhtml = 0)
3563{
3564 global $user, $conf, $langs, $db, $form;
3565 global $hookmanager, $menumanager;
3566
3567 $searchform = '';
3568
3569 if (!empty($menu_array_before)) {
3570 dol_syslog("Deprecated parameter menu_array_before was used when calling main::left_menu function. Menu entries of module should now be defined into module descriptor and not provided when calling left_menu.", LOG_WARNING);
3571 }
3572
3573 if (empty($conf->dol_hide_leftmenu) && (!defined('NOREQUIREMENU') || !constant('NOREQUIREMENU'))) {
3574 // Instantiate hooks for external modules
3575 $hookmanager->initHooks(array('leftblock'));
3576
3577 print "\n".'<!-- Begin side-nav id-left -->'."\n".'<div class="side-nav"><div id="id-left">'."\n";
3578 print "\n";
3579
3580 if (!is_object($form)) {
3581 $form = new Form($db);
3582 }
3583 $selected = -1;
3584 if (!getDolGlobalString('MAIN_USE_TOP_MENU_SEARCH_DROPDOWN')) {
3585 // Select with select2 is awful on smartphone. TODO Is this still true with select2 v4 ?
3586 if ($conf->browser->layout == 'phone') {
3587 $conf->global->MAIN_USE_OLD_SEARCH_FORM = 1;
3588 }
3589
3590 $usedbyinclude = 1;
3591 $arrayresult = array();
3592 include DOL_DOCUMENT_ROOT.'/core/ajax/selectsearchbox.php'; // This make initHooks('searchform') then set $arrayresult
3593
3594 if (!empty($conf->use_javascript_ajax) && !getDolGlobalString('MAIN_USE_OLD_SEARCH_FORM')) {
3595 //$textsearch = $langs->trans("Search");
3596 $textsearch = '<span class="fa fa-search paddingright pictofixedwidth"></span>'.$langs->trans("Search");
3597 $searchform .= $form->selectArrayFilter('searchselectcombo', $arrayresult, (string) $selected, 'accesskey="s"', 1, 0, (getDolGlobalString('MAIN_SEARCHBOX_CONTENT_LOADED_BEFORE_KEY') ? 0 : 1), 'vmenusearchselectcombo', 1, $textsearch, 1, $conf->browser->stringforfirstkey.' s');
3598 } else {
3599 if (is_array($arrayresult)) {
3600 // @phan-suppress-next-line PhanEmptyForeach // array is really empty in else case.
3601 foreach ($arrayresult as $key => $val) {
3602 $searchform .= printSearchForm($val['url'], $val['url'], $val['label'], 'maxwidth125', 'search_all', (empty($val['shortcut']) ? '' : $val['shortcut']), 'searchleft'.$key, $val['img']);
3603 }
3604 }
3605 }
3606
3607 // Execute hook printSearchForm
3608 $parameters = array('searchform' => $searchform);
3609 $reshook = $hookmanager->executeHooks('printSearchForm', $parameters); // Note that $action and $object may have been modified by some hooks
3610 if (empty($reshook)) {
3611 $searchform .= $hookmanager->resPrint;
3612 } else {
3613 $searchform = $hookmanager->resPrint;
3614 }
3615
3616 // Force special value for $searchform for text browsers or very old search form
3617 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') || empty($conf->use_javascript_ajax)) {
3618 $urltosearch = DOL_URL_ROOT.'/core/search_page.php?showtitlebefore=1';
3619 $searchform = '<div class="blockvmenuimpair blockvmenusearchphone"><div id="divsearchforms1"><a href="'.$urltosearch.'" accesskey="s" alt="'.dol_escape_htmltag($langs->trans("ShowSearchFields")).'">'.$langs->trans("Search").'...</a></div></div>';
3620 } elseif ($conf->use_javascript_ajax && getDolGlobalString('MAIN_USE_OLD_SEARCH_FORM')) {
3621 $searchform = '<div class="blockvmenuimpair blockvmenusearchphone"><div id="divsearchforms1"><a href="#" alt="'.dol_escape_htmltag($langs->trans("ShowSearchFields")).'">'.$langs->trans("Search").'...</a></div><div id="divsearchforms2" style="display: none">'.$searchform.'</div>';
3622 $searchform .= '<script>
3623 jQuery(document).ready(function () {
3624 jQuery("#divsearchforms1").click(function(){
3625 jQuery("#divsearchforms2").toggle();
3626 });
3627 });
3628 </script>' . "\n";
3629 $searchform .= '</div>';
3630 }
3631
3632 // Key map shortcut
3633 $searchform .= '<script>
3634 jQuery(document).keydown(function(e){
3635 if( e.which === 70 && e.ctrlKey && e.shiftKey ){
3636 console.log(\'control + shift + f : trigger open global-search dropdown\');
3637 openGlobalSearchDropDown();
3638 }
3639 if( (e.which === 83 || e.which === 115) && e.altKey ){
3640 console.log(\'alt + s : trigger open global-search dropdown\');
3641 openGlobalSearchDropDown();
3642 }
3643 });
3644
3645 var openGlobalSearchDropDown = function() {
3646 jQuery("#searchselectcombo").select2(\'open\');
3647 }
3648 </script>';
3649 }
3650
3651 // Left column
3652 print '<!-- Begin left menu -->'."\n";
3653
3654 print '<div class="vmenu"'.(getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') ? ' alt="Left menu"' : '').'>'."\n\n";
3655
3656 // Show left menu with other forms
3657 // @phan-suppress-next-line PhanRedefinedClassReference
3658 $menumanager->menu_array = $menu_array_before;
3659 // @phan-suppress-next-line PhanRedefinedClassReference
3660 $menumanager->menu_array_after = $menu_array_after;
3661 if (getDolGlobalInt('MAIN_MENU_LEFT_DROPDOWN')) {
3662 // @phan-suppress-next-line PhanRedefinedClassReference
3663 $menumanager->showmenu('leftdropdown', array('searchform' => $searchform)); // output menu_array and menu found in database
3664 } else {
3665 // @phan-suppress-next-line PhanRedefinedClassReference
3666 $menumanager->showmenu('left', array('searchform' => $searchform)); // output menu_array and menu found in database
3667 }
3668
3669 // Dolibarr version + help + bug report link
3670 if (getDolGlobalString('MAIN_SHOW_VERSION') || getDolGlobalString('MAIN_BUGTRACK_ENABLELINK')) {
3671 print "\n";
3672 print "<!-- Begin Help Block-->\n";
3673 print '<div id="blockvmenuhelp" class="blockvmenuhelp">'."\n";
3674
3675 // Version
3676 if (getDolGlobalString('MAIN_SHOW_VERSION')) { // Version is already on help picto and on login page.
3677 $doliurl = 'https://www.dolibarr.org';
3678 //local communities
3679 if (preg_match('/fr/i', $langs->defaultlang)) {
3680 $doliurl = 'https://www.dolibarr.fr';
3681 }
3682 if (preg_match('/es/i', $langs->defaultlang)) {
3683 $doliurl = 'https://www.dolibarr.es';
3684 }
3685 if (preg_match('/de/i', $langs->defaultlang)) {
3686 $doliurl = 'https://www.dolibarr.de';
3687 }
3688 if (preg_match('/it/i', $langs->defaultlang)) {
3689 $doliurl = 'https://www.dolibarr.it';
3690 }
3691 if (preg_match('/gr/i', $langs->defaultlang)) {
3692 $doliurl = 'https://www.dolibarr.gr';
3693 }
3694
3695 $appli = constant('DOL_APPLICATION_TITLE');
3696 $applicustom = getDolGlobalString('MAIN_APPLICATION_TITLE');
3697 if ($applicustom) {
3698 $appli = (preg_match('/^\+/', $applicustom) ? $appli : '').$applicustom;
3699 } else {
3700 $appli .= " ".DOL_VERSION;
3701 }
3702
3703 // Clean doliurl if we use a custom application name
3704 if ($applicustom) {
3705 $doliurl = '';
3706 }
3707
3708 print '<div id="blockvmenuhelpapp" class="blockvmenuhelp">';
3709 if ($doliurl) {
3710 print '<a class="help" target="_blank" rel="noopener noreferrer" href="'.$doliurl.'">';
3711 } else {
3712 print '<span class="help">';
3713 }
3714 print $appli;
3715 if ($doliurl) {
3716 print '</a>';
3717 } else {
3718 print '</span>';
3719 }
3720 print '</div>'."\n";
3721 }
3722
3723 // Link to bugtrack
3724 if (getDolGlobalString('MAIN_BUGTRACK_ENABLELINK')) {
3725 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
3726
3727 if (getDolGlobalString('MAIN_BUGTRACK_ENABLELINK') == 'github') {
3728 $bugbaseurl = 'https://github.com/Dolibarr/dolibarr/issues/new?labels=Bug';
3729 $bugbaseurl .= '&title=';
3730 $bugbaseurl .= urlencode("Bug: ");
3731 $bugbaseurl .= '&body=';
3732 $bugbaseurl .= urlencode("# Instructions\n");
3733 $bugbaseurl .= urlencode("*This is a template to help you report good issues. You may use [Github Markdown](https://help.github.com/articles/getting-started-with-writing-and-formatting-on-github/) syntax to format your issue report.*\n");
3734 $bugbaseurl .= urlencode("*Please:*\n");
3735 $bugbaseurl .= urlencode("- *replace the bracket enclosed texts with meaningful information*\n");
3736 $bugbaseurl .= urlencode("- *remove any unused sub-section*\n");
3737 $bugbaseurl .= urlencode("\n");
3738 $bugbaseurl .= urlencode("\n");
3739 $bugbaseurl .= urlencode("# Bug\n");
3740 $bugbaseurl .= urlencode("[*Short description*]\n");
3741 $bugbaseurl .= urlencode("\n");
3742 $bugbaseurl .= urlencode("## Environment\n");
3743 $bugbaseurl .= urlencode("- **Version**: ".DOL_VERSION."\n");
3744 $bugbaseurl .= urlencode("- **OS**: ".php_uname('s')."\n");
3745 $bugbaseurl .= urlencode("- **Web server**: ".$_SERVER["SERVER_SOFTWARE"]."\n");
3746 $bugbaseurl .= urlencode("- **PHP**: ".php_sapi_name().' '.phpversion()."\n");
3747 $bugbaseurl .= urlencode("- **Database**: ".$db::LABEL.' '.$db->getVersion()."\n");
3748 $bugbaseurl .= urlencode("- **URL(s)**: ".$_SERVER["REQUEST_URI"]."\n");
3749 $bugbaseurl .= urlencode("\n");
3750 $bugbaseurl .= urlencode("## Expected and actual behavior\n");
3751 $bugbaseurl .= urlencode("[*Verbose description*]\n");
3752 $bugbaseurl .= urlencode("\n");
3753 $bugbaseurl .= urlencode("## Steps to reproduce the behavior\n");
3754 $bugbaseurl .= urlencode("[*Verbose description*]\n");
3755 $bugbaseurl .= urlencode("\n");
3756 $bugbaseurl .= urlencode("## [Attached files](https://help.github.com/articles/issue-attachments) (Screenshots, screencasts, dolibarr.log, debugging information…)\n");
3757 $bugbaseurl .= urlencode("[*Files*]\n");
3758 $bugbaseurl .= urlencode("\n");
3759
3760 $bugbaseurl .= urlencode("\n");
3761 $bugbaseurl .= urlencode("## Report\n");
3762 } elseif (getDolGlobalString('MAIN_BUGTRACK_ENABLELINK')) {
3763 $bugbaseurl = getDolGlobalString('MAIN_BUGTRACK_ENABLELINK');
3764 } else {
3765 $bugbaseurl = "";
3766 }
3767
3768 // Execute hook printBugtrackInfo
3769 $parameters = array('bugbaseurl' => $bugbaseurl);
3770 $reshook = $hookmanager->executeHooks('printBugtrackInfo', $parameters); // Note that $action and $object may have been modified by some hooks
3771 if (empty($reshook)) {
3772 $bugbaseurl .= $hookmanager->resPrint;
3773 } else {
3774 $bugbaseurl = $hookmanager->resPrint;
3775 }
3776
3777 print '<div id="blockvmenuhelpbugreport" class="blockvmenuhelp">';
3778 print '<a class="help" target="_blank" rel="noopener noreferrer" href="'.$bugbaseurl.'"><i class="fas fa-bug"></i> '.$langs->trans("FindBug").'</a>';
3779 print '</div>';
3780 }
3781
3782 print "</div>\n";
3783 print "<!-- End Help Block-->\n";
3784 print "\n";
3785 }
3786
3787 print "</div>\n";
3788 print "<!-- End left menu -->\n";
3789 print "\n";
3790
3791 // Execute hook printLeftBlock
3792 $parameters = array();
3793 $reshook = $hookmanager->executeHooks('printLeftBlock', $parameters); // Note that $action and $object may have been modified by some hooks
3794 print $hookmanager->resPrint;
3795
3796 print '</div></div> <!-- End side-nav id-left -->'; // End div id="side-nav" div id="id-left"
3797 }
3798
3799 print "\n";
3800 print '<!-- Begin right area -->'."\n";
3801
3802 if (empty($leftmenuwithoutmainarea)) {
3803 main_area($title);
3804 }
3805}
3806
3807
3814function main_area($title = '')
3815{
3816 global $conf, $langs, $hookmanager;
3817
3818 if (empty($conf->dol_hide_leftmenu) && !GETPOST('dol_openinpopup', 'aZ09')) {
3819 print '<div id="id-right">';
3820 }
3821
3822 print "\n";
3823
3824 print '<!-- Begin div class="fiche" -->'."\n".'<div class="fiche">'."\n";
3825
3826 $hookmanager->initHooks(array('main'));
3827 $parameters = array();
3828 $reshook = $hookmanager->executeHooks('printMainArea', $parameters); // Note that $action and $object may have been modified by some hooks
3829 print $hookmanager->resPrint;
3830
3831 if (getDolGlobalString('MAIN_ONLY_LOGIN_ALLOWED')) {
3832 print info_admin($langs->trans("WarningYouAreInMaintenanceMode", getDolGlobalString('MAIN_ONLY_LOGIN_ALLOWED')), 0, 0, '1', 'warning maintenancemode');
3833 }
3834
3835 // Permit to add user company information on each printed document by setting SHOW_SOCINFO_ON_PRINT
3836 if (getDolGlobalString('SHOW_SOCINFO_ON_PRINT') && GETPOST('optioncss', 'aZ09') == 'print' && empty(GETPOST('disable_show_socinfo_on_print', 'aZ09'))) {
3837 $parameters = array();
3838 $reshook = $hookmanager->executeHooks('showSocinfoOnPrint', $parameters);
3839 if (empty($reshook)) {
3840 print '<!-- Begin show mysoc info header -->'."\n";
3841 print '<div id="mysoc-info-header">'."\n";
3842 print '<table class="centpercent div-table-responsive">'."\n";
3843 print '<tbody>';
3844 print '<tr><td rowspan="0" class="width20p">';
3845 if (getDolGlobalString('MAIN_SHOW_LOGO') && !getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') && getDolGlobalString('MAIN_INFO_SOCIETE_LOGO')) {
3846 print '<img id="mysoc-info-header-logo" style="max-width:100%" alt="" src="'.DOL_URL_ROOT.'/viewimage.php?cache=1&modulepart=mycompany&file='.urlencode('logos/'.dol_escape_htmltag(getDolGlobalString('MAIN_INFO_SOCIETE_LOGO'))).'">';
3847 }
3848 print '</td><td rowspan="0" class="width50p"></td></tr>'."\n";
3849 print '<tr><td class="titre bold">'.dol_escape_htmltag(getDolGlobalString('MAIN_INFO_SOCIETE_NOM')).'</td></tr>'."\n";
3850 print '<tr><td>'.dol_escape_htmltag(getDolGlobalString('MAIN_INFO_SOCIETE_ADDRESS')).'<br>'.dol_escape_htmltag(getDolGlobalString('MAIN_INFO_SOCIETE_ZIP')).' '.dol_escape_htmltag(getDolGlobalString('MAIN_INFO_SOCIETE_TOWN')).'</td></tr>'."\n";
3851 if (getDolGlobalString('MAIN_INFO_SOCIETE_TEL')) {
3852 print '<tr><td style="padding-left: 1em" class="small">'.$langs->trans("Phone").' : '.dol_escape_htmltag(getDolGlobalString('MAIN_INFO_SOCIETE_TEL')).'</td></tr>';
3853 }
3854 if (getDolGlobalString('MAIN_INFO_SOCIETE_MAIL')) {
3855 print '<tr><td style="padding-left: 1em" class="small">'.$langs->trans("Email").' : '.dol_escape_htmltag(getDolGlobalString('MAIN_INFO_SOCIETE_MAIL')).'</td></tr>';
3856 }
3857 if (getDolGlobalString('MAIN_INFO_SOCIETE_WEB')) {
3858 print '<tr><td style="padding-left: 1em" class="small">'.$langs->trans("Web").' : '.dol_escape_htmltag(getDolGlobalString('MAIN_INFO_SOCIETE_WEB')).'</td></tr>';
3859 }
3860 print '</tbody>';
3861 print '</table>'."\n";
3862 print '</div>'."\n";
3863 print '<!-- End show mysoc info header -->'."\n";
3864 }
3865 }
3866}
3867
3868
3876function getHelpParamFor($helppagename, $langs)
3877{
3878 $helpbaseurl = '';
3879 $helppage = '';
3880 $mode = '';
3881
3882 if (preg_match('/^http/i', $helppagename)) {
3883 // If complete URL
3884 $helpbaseurl = '%s';
3885 $helppage = $helppagename;
3886 $mode = 'local';
3887 } else {
3888 // If WIKI URL
3889 $reg = array();
3890 if (preg_match('/^es/i', $langs->defaultlang)) {
3891 $helpbaseurl = 'http://wiki.dolibarr.org/index.php/%s';
3892 if (preg_match('/ES:([^|]+)/i', $helppagename, $reg)) {
3893 $helppage = $reg[1];
3894 }
3895 }
3896 if (preg_match('/^fr/i', $langs->defaultlang)) {
3897 $helpbaseurl = 'http://wiki.dolibarr.org/index.php/%s';
3898 if (preg_match('/FR:([^|]+)/i', $helppagename, $reg)) {
3899 $helppage = $reg[1];
3900 }
3901 }
3902 if (preg_match('/^de/i', $langs->defaultlang)) {
3903 $helpbaseurl = 'http://wiki.dolibarr.org/index.php/%s';
3904 if (preg_match('/DE:([^|]+)/i', $helppagename, $reg)) {
3905 $helppage = $reg[1];
3906 }
3907 }
3908 if (empty($helppage)) { // If help page not already found
3909 $helpbaseurl = 'http://wiki.dolibarr.org/index.php/%s';
3910 if (preg_match('/EN:([^|]+)/i', $helppagename, $reg)) {
3911 $helppage = $reg[1];
3912 }
3913 }
3914 $mode = 'wiki';
3915 }
3916 return array('helpbaseurl' => $helpbaseurl, 'helppage' => $helppage, 'mode' => $mode);
3917}
3918
3919
3936function printSearchForm($urlaction, $urlobject, $title, $htmlmorecss, $htmlinputname, $accesskey = '', $prefhtmlinputname = '', $img = '', $showtitlebefore = 0, $autofocus = 0)
3937{
3938 global $langs, $user;
3939
3940 $ret = '';
3941 $ret .= '<form action="'.$urlaction.'" method="post" class="searchform nowraponall tagtr">';
3942 $ret .= '<input type="hidden" name="token" value="'.newToken().'">';
3943 $ret .= '<input type="hidden" name="savelogin" value="'.dol_escape_htmltag($user->login).'">';
3944 if ($showtitlebefore) {
3945 $ret .= '<div class="tagtd left">'.$title.'</div> ';
3946 }
3947 $ret .= '<div class="tagtd">';
3948 $ret .= img_picto('', $img, '', 0, 0, 0, '', 'paddingright width20');
3949 $ret .= '<input type="text" class="flat '.$htmlmorecss.'"';
3950 $ret .= ' style="background-repeat: no-repeat; background-position: 3px;"';
3951 $ret .= ($accesskey ? ' accesskey="'.$accesskey.'"' : '');
3952 $ret .= ' placeholder="'.strip_tags($title).'"';
3953 $ret .= ($autofocus ? ' autofocus' : '');
3954 $ret .= ' name="'.$htmlinputname.'" id="'.$prefhtmlinputname.$htmlinputname.'" />';
3955 $ret .= '<button type="submit" class="button bordertransp nohover" style="padding-top: 4px; padding-bottom: 4px; padding-left: 6px; padding-right: 6px">';
3956 $ret .= '<span class="fa fa-search"></span>';
3957 $ret .= '</button>';
3958 $ret .= '</div>';
3959 $ret .= "</form>\n";
3960 return $ret;
3961}
3962
3963
3964if (!function_exists("llxFooter")) {
3978 function llxFooter($comment = '', $zone = 'private', $disabledoutputofmessages = 0)
3979 {
3980 global $conf, $db, $langs, $user, $mysoc, $object, $hookmanager, $action;
3981 global $delayedhtmlcontent;
3982 global $contextpage, $page, $limit, $mode;
3983 global $dolibarr_distrib;
3984
3985 $ext = 'layout='.urlencode($conf->browser->layout).'&version='.urlencode(DOL_VERSION);
3986
3987 // Hook to add more things on all pages within fiche DIV
3988 $llxfooter = '';
3989 $parameters = array();
3990 $reshook = $hookmanager->executeHooks('llxFooter', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
3991 if (empty($reshook)) {
3992 $llxfooter .= $hookmanager->resPrint;
3993 } elseif ($reshook > 0) {
3994 $llxfooter = $hookmanager->resPrint;
3995 }
3996 if ($llxfooter) {
3997 print $llxfooter;
3998 }
3999
4000 // Global html output events ($mesgs, $errors, $warnings)
4001 dol_htmloutput_events($disabledoutputofmessages);
4002
4003 // Code for search criteria persistence.
4004 // $user->lastsearch_values was set by the GETPOST when form field search_xxx exists
4005 if (is_object($user) && !empty($user->lastsearch_values_tmp) && is_array($user->lastsearch_values_tmp)) {
4006 // Clean and save data
4007 foreach ($user->lastsearch_values_tmp as $key => $val) {
4008 unset($_SESSION['lastsearch_values_tmp_'.$key]); // Clean array to rebuild it just after
4009 if (count($val) && empty($_POST['button_removefilter']) && empty($_POST['button_removefilter_x'])) {
4010 if (empty($val['sortfield'])) {
4011 unset($val['sortfield']);
4012 }
4013 if (empty($val['sortorder'])) {
4014 unset($val['sortorder']);
4015 }
4016 dol_syslog('Save lastsearch_values_tmp_'.$key.'='.json_encode($val, 0)." (systematic recording of last search criteria)");
4017 $_SESSION['lastsearch_values_tmp_'.$key] = json_encode($val);
4018 unset($_SESSION['lastsearch_values_'.$key]);
4019 } elseif (!empty($_POST['button_removefilter']) || !empty($_POST['button_removefilter_x'])) {
4020 unset($_SESSION['lastsearch_values_'.$key]); // Filters were removed, so previously saved criteria must not be restored later
4021 }
4022 }
4023 }
4024
4025
4026 $relativepathstring = $_SERVER["PHP_SELF"];
4027 // Clean $relativepathstring
4028 if (constant('DOL_URL_ROOT')) {
4029 $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
4030 }
4031 $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
4032 $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
4033 if (preg_match('/list\.php$/', $relativepathstring)) {
4034 unset($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]);
4035 unset($_SESSION['lastsearch_page_tmp_'.$relativepathstring]);
4036 unset($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]);
4037 unset($_SESSION['lastsearch_mode_tmp_'.$relativepathstring]);
4038
4039 if (!empty($contextpage)) {
4040 $_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring] = $contextpage;
4041 }
4042 if (!empty($page) && $page > 0) {
4043 $_SESSION['lastsearch_page_tmp_'.$relativepathstring] = $page;
4044 }
4045 if (!empty($limit) && $limit != $conf->liste_limit) {
4046 $_SESSION['lastsearch_limit_tmp_'.$relativepathstring] = $limit;
4047 }
4048 if (!empty($mode)) {
4049 $_SESSION['lastsearch_mode_tmp_'.$relativepathstring] = $mode;
4050 }
4051
4052 unset($_SESSION['lastsearch_contextpage_'.$relativepathstring]);
4053 unset($_SESSION['lastsearch_page_'.$relativepathstring]);
4054 unset($_SESSION['lastsearch_limit_'.$relativepathstring]);
4055 unset($_SESSION['lastsearch_mode_'.$relativepathstring]);
4056 }
4057
4058 // Core error message
4059 if (getDolGlobalString('MAIN_CORE_ERROR')) {
4060 // Ajax version
4061 if ($conf->use_javascript_ajax) {
4062 $title = img_warning().' '.$langs->trans('CoreErrorTitle');
4063 print ajax_dialog($title, $langs->trans('CoreErrorMessage'));
4064 } else {
4065 // html version
4066 $msg = img_warning().' '.$langs->trans('CoreErrorMessage');
4067 print '<div class="error">'.$msg.'</div>';
4068 }
4069
4070 //define("MAIN_CORE_ERROR",0); // Constant was defined and we can't change value of a constant
4071 }
4072
4073 print "\n\n";
4074
4075 print '</div> <!-- End div class="fiche" -->'."\n"; // End div fiche
4076
4077 if (empty($conf->dol_hide_leftmenu) && !GETPOST('dol_openinpopup', 'aZ09')) {
4078 print '</div> <!-- End div id-right -->'."\n"; // End div id-right
4079 }
4080
4081 if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) {
4082 print '</div> <!-- End div id-container -->'."\n"; // End div container
4083 }
4084
4085 print "\n";
4086 if ($comment) {
4087 print '<!-- '.$comment.' -->'."\n";
4088 }
4089
4090 printCommonFooter($zone);
4091
4092 if (!empty($delayedhtmlcontent)) {
4093 print $delayedhtmlcontent;
4094 }
4095
4096 if (!empty($conf->use_javascript_ajax)) {
4097 print "\n".'<!-- Includes JS Footer of Dolibarr -->'."\n";
4098 print '<script src="'.DOL_URL_ROOT.'/core/js/lib_foot.js.php?lang='.$langs->defaultlang . '&' . $ext .'"></script>'."\n";
4099 }
4100
4101 // A div for the #dialogforpopup popup
4102 print "\n<!-- A div to allow dialog popup by jQuery('#dialogforpopup').dialog() -->\n";
4103 print '<div id="dialogforpopup" style="display: none;"></div>'."\n";
4104
4105 // A div for the #uiblock
4106 print "\n<!-- A div to allow uiblock by dolBlockUI(message) -->\n";
4107 print '<div id="dol-block-ui" style="display: none;"><div class="message">Loading...</div></div>'."\n";
4108
4109
4110 // Add code for the asynchronous anonymous first ping (for telemetry)
4111 // You can use &forceping=1 in parameters to force the ping if the ping was already sent.
4112 $forceping = GETPOSTINT('forceping');
4113
4114 if (($_SERVER["PHP_SELF"] == DOL_URL_ROOT.'/index.php') || $forceping) {
4115 require_once DOL_DOCUMENT_ROOT.'/blockedlog/lib/blockedlog.lib.php';
4116
4117 $hash_unique_id_ping = getHashUniqueIdOfRegistration('sha256');
4118 $constanttosavelastko = 'MAIN_LAST_PING_KO_DATE';
4119 $constanttosavefirstok = 'MAIN_FIRST_PING_OK_DATE';
4120 $constanttosavefirstokid = 'MAIN_FIRST_PING_OK_ID';
4121
4122 if (!getDolGlobalString($constanttosavefirstok)
4123 || (!empty($conf->file->instance_unique_id) && (($hash_unique_id_ping.' - '.DOL_VERSION) != getDolGlobalString($constanttosavefirstokid)) && (getDolGlobalString($constanttosavefirstokid) != 'disabled'))
4124 || $forceping) {
4125 // No ping done if we are into an alpha version
4126 if (strpos('alpha', DOL_VERSION) > 0 && !$forceping) {
4127 print "\n<!-- NO JS CODE TO ENABLE the anonymous Ping. It is an alpha version -->\n";
4128 } elseif (empty($_COOKIE['DOLINSTALLNOPING_'.$hash_unique_id_ping]) || $forceping) { // Cookie is set when we uncheck the checkbox in the installation wizard.
4129 // Output code for ping
4130 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
4131
4132 $arrayofmoredata = array(
4133 'action' => 'dolibarrping',
4134 'datesys' => dol_print_date(dol_now(), 'standard', 'gmt'),
4135
4136 'country_code' => ($mysoc->country_code ? $mysoc->country_code : 'unknown')
4137 );
4138 printCodeForPing($constanttosavelastko, $constanttosavefirstok, $arrayofmoredata, $forceping);
4139 } else {
4140 $now = dol_now();
4141 print "\n<!-- NO JS CODE TO ENABLE the anonymous Ping. It was disabled -->\n";
4142 include_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
4143 dolibarr_set_const($db, $constanttosavefirstok, dol_print_date($now, 'dayhourlog', 'gmt'), 'chaine', 0, '', $conf->entity);
4144 dolibarr_set_const($db, $constanttosavefirstokid, 'disabled', 'chaine', 0, '', $conf->entity);
4145 }
4146 } else {
4147 print "\n<!-- NO JS CODE TO call the ping. It was already done for this couple uniqueid and version -->\n";
4148 }
4149 }
4150
4151 // Add code for the asynchronous registration of the use of the BlockedLog module if not yet done but ready (in case past submission failed)
4152 // You can use &forceregistration=1 in parameters to force also the recall if the call was already sent.
4153 $forceregistration = GETPOSTINT('forceregistration');
4154
4155 if (isModEnabled('blockedlog') && (($_SERVER["PHP_SELF"] == DOL_URL_ROOT.'/index.php') || $forceregistration)) {
4156 require_once DOL_DOCUMENT_ROOT.'/blockedlog/lib/blockedlog.lib.php';
4157
4158 if (!isALNEQualifiedVersion()) {
4159 print "\n<!-- NO JS CODE TO ENABLE the registration. Not a LNE qualified version -->\n";
4160 } elseif (!isRegistrationDataSaved()) {
4161 print "\n<!-- NO JS CODE TO ENABLE the registration. Registration data not saved -->\n";
4162 } else {
4163 $hash_unique_id_registration = getHashUniqueIdOfRegistration();
4164 $constanttosavelastko = 'MAIN_LAST_REGISTRATION_KO_DATE';
4165 $constanttosavefirstok = 'MAIN_FIRST_REGISTRATION_OK_DATE';
4166 $constanttosavefirstokid = 'MAIN_FIRST_REGISTRATION_OK_ID';
4167
4168 if (!getDolGlobalString($constanttosavefirstok)
4169 || (!empty($conf->file->instance_unique_id) && ($hash_unique_id_registration.' - '.DOL_VERSION != getDolGlobalString($constanttosavefirstokid)) && (getDolGlobalString($constanttosavefirstokid) != 'disabled'))
4170 || $forceregistration) {
4171 // No registration done if we are into an alpha or beta version
4172 if ((strpos('alpha', DOL_VERSION) > 0 || strpos('beta', DOL_VERSION) > 0) && !$forceregistration) {
4173 print "\n<!-- NO JS CODE TO ENABLE the registration. It is an alpha or beta version -->\n";
4174 } elseif (empty($_COOKIE['DOLINSTALLNOPING_'.$hash_unique_id_registration]) || $forceregistration) { // Cookie is set when we uncheck the checkbox in the installation wizard.
4175 // Output code for ping
4176 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
4177
4178 $arrayofdata = array(
4179 'action' => 'dolibarrregistration',
4180 'datesys' => dol_print_date(dol_now(), 'standard', 'gmt'),
4181
4182 'company_name' => getDolGlobalString('BLOCKEDLOG_REGISTRATION_NAME', $mysoc->name),
4183 'company_email' => getDolGlobalString('BLOCKEDLOG_REGISTRATION_EMAIL', $mysoc->email),
4184 'company_idprof1' => getDolGlobalString('MAIN_INFO_SIREN', $mysoc->idprof1),
4185 'company_idprof2' => getDolGlobalString('MAIN_INFO_SIRET', $mysoc->idprof2),
4186 'company_address' => getDolGlobalString('BLOCKEDLOG_REGISTRATION_ADDRESS', $mysoc->address),
4187 'company_state' => getDolGlobalString('BLOCKEDLOG_REGISTRATION_STATE', $mysoc->state),
4188 'company_zip' => getDolGlobalString('BLOCKEDLOG_REGISTRATION_ZIP', $mysoc->zip),
4189 'company_town' => getDolGlobalString('BLOCKEDLOG_REGISTRATION_TOWN', $mysoc->town),
4190 'country_code' => $mysoc->country_code,
4191
4192 'provider_name' => getDolGlobalString('MAIN_INFO_ITPROVIDER_NAME'),
4193 'provider_email' => getDolGlobalString('MAIN_INFO_ITPROVIDER_MAIL'),
4194 'provider_phone' => getDolGlobalString('MAIN_INFO_ITPROVIDER_PHONE'),
4195 'provider_address' => getDolGlobalString('MAIN_INFO_ITPROVIDER_ADDRESS'),
4196 'provider_state' => getDolGlobalString('MAIN_INFO_ITPROVIDER_STATE'),
4197 'provider_zip' => getDolGlobalString('MAIN_INFO_ITPROVIDER_ZIP'),
4198 'provider_town' => getDolGlobalString('MAIN_INFO_ITPROVIDER_TOWN'),
4199 'provider_country' => getDolGlobalString('MAIN_INFO_ITPROVIDER_COUNTRY'),
4200 'provider_idprof1' => getDolGlobalString('MAIN_INFO_ITPROVIDER_IDPROF1'),
4201 'provider_idprof2' => getDolGlobalString('MAIN_INFO_ITPROVIDER_IDPROF2')
4202 );
4203 printCodeForPing($constanttosavelastko, $constanttosavefirstok, $arrayofdata, $forceregistration);
4204 } else {
4205 $now = dol_now();
4206 print "\n<!-- NO JS CODE TO ENABLE the registration. It was disabled -->\n";
4207 include_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
4208 dolibarr_set_const($db, $constanttosavefirstok, dol_print_date($now, 'dayhourlog', 'gmt'), 'chaine', 0, '', $conf->entity);
4209 dolibarr_set_const($db, $constanttosavefirstokid, 'disabled', 'chaine', 0, '', $conf->entity);
4210 }
4211 } else {
4212 print "\n<!-- NO JS CODE TO call the registration. It was already done for this couple uniqueid and version -->\n";
4213 }
4214 }
4215 }
4216
4217 // Add code for the asynchronous emulation of pushing a tracking counter of the use of the BlockedLog module trigger(for test purposes)
4218 // You can use &forceregistration=1 in parameters to force also the recall if the call was already sent.
4219 /*
4220 $forcepushcounter = GETPOSTINT('forcepushcounter');
4221
4222 if (isModEnabled('blockedlog') && ($_SERVER["PHP_SELF"] == DOL_URL_ROOT.'/index.php') && $forcepushcounter) {
4223 include_once DOL_DOCUMENT_ROOT.'/blockedlog/lib/blockedlog.lib.php';
4224 $islne = isALNEQualifiedVersion(1, 1);
4225 if (!$islne) {
4226 print "\n<!-- NO CALL TO API TO PUSH COUNTER. Not a LNE qualified version -->\n";
4227 } elseif (!isRegistrationDataSaved()) {
4228 print "\n<!-- NO CALL TO API TO PUSH COUNTER. Registration data not saved -->\n";
4229 } else {
4230 // Get last ID and hash into $tmpresult
4231 include_once DOL_DOCUMENT_ROOT.'/blockedlog/class/blockedlog.class.php';
4232 $tmpblockedlog = new BlockedLog($db);
4233 $tmpresult = $tmpblockedlog->getPreviousHash(0, 0);
4234
4235 if ((int) $tmpresult['previousid']) {
4236 $tmpresult2 = $tmpblockedlog->getPreviousHash(0, (int) $tmpresult['previousid']); // Get previous record
4237
4238 if ((int) $tmpresult2['previousid']) {
4239 // Call remote API service to record the last counter
4240 $resultcall = callApiToPushCounter((int) $tmpresult['previousid'], $tmpresult['previoushash'], $tmpresult['previousdatecreation'], 1, (int) $tmpresult2['previousid'], $tmpresult2['previoushash'], $tmpresult2['previousdatecreation']);
4241
4242 $algo = 'sha256';
4243 $hash_unique_id = getHashUniqueIdOfRegistration($algo); // The hash of the unique IDof instance
4244
4245 print "\n<!-- API TO PUSH COUNTER WAS CALLED. Result is ".$resultcall.". You may have log into dolibarr_dolibarrpushcounter.log for hash_unique_id=".dol_trunc($hash_unique_id, 10)." -->\n";
4246 }
4247 } else {
4248 print "\n<!-- NO CALL TO API TO PUSH COUNTER. Last rowid and signature not found -->\n";
4249 }
4250 }
4251 }
4252 */
4253
4254
4255
4256 $parameters = array();
4257 $reshook = $hookmanager->executeHooks('beforeBodyClose', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
4258 if ($reshook > 0) {
4259 print $hookmanager->resPrint;
4260 }
4261
4262 print "</body>\n";
4263 print "</html>\n";
4264 }
4265}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition propal.php:281
dolibarr_set_const($db, $name, $value, $type='chaine', $visible=0, $note='', $entity=1)
Insert a parameter (key,value) into database (delete old key then insert it again).
versioncompare($versionarray1, $versionarray2)
Compare 2 versions (stored into 2 arrays), to know if a version (a,b,c) is lower than (x,...
Definition admin.lib.php:79
ajax_dialog($title, $message, $w=350, $h=150)
Show an ajax dialog.
Definition ajax.lib.php:444
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Empty footer.
Definition wrapper.php:91
if(!defined('NOREQUIRESOC')) if(!defined( 'NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined( 'NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined( 'NOREQUIREAJAX')) llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='', $disablenofollow=0, $disablenoindex=0)
Empty header.
Definition wrapper.php:73
isALNEQualifiedVersion($ignoredev=0, $ignoremodule=0)
Return if the version is a candidate version to get the LNE certification and if the prerequisites ar...
isRegistrationDataSaved()
Return if the KYC mandatory parameters are set Must be the same fields than the one defined as mandat...
getHashUniqueIdOfRegistration($algo='sha256')
Return a hash unique identifier of the registration (used to identify the registration of instance wi...
printDropdownBookmarksList()
Add area with bookmarks in top menu.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
DolibarrDebugBar class.
Definition DebugBar.php:47
Class to manage generation of HTML components Only common components must be here.
static showphoto($modulepart, $object, $width=100, $height=0, $caneditfield=0, $cssclass='photowithmargin', $imagesize='', $addlinktofullsize=1, $cache=0, $forcecapture='', $noexternsourceoverwrite=0, $usesharelinkifavailable=0)
Return HTML code to output a photo.
Class to manage hooks.
Class to manage left menus.
Class to manage menu Auguria.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage translations.
if(! $sortfield) if(! $sortorder) $module
Definition list.php:193
global $mysoc
dol_stringtotime($string, $gm=1, $processnotimeasnoon=0)
Convert a string date into a GM Timestamps date Warning: YYYY-MM-DDTHH:MM:SS+02:00 (RFC3339) is not s...
Definition date.lib.php:452
if(!defined('LOG_DEBUG')) if(defined( 'DOL_INC_FOR_VERSION_ERROR')) dol_session_start()
Replace session_start()
printCodeForPing($constanttosavelastko, $constanttosavefirstok, $arrayofdata=array(), $forceping=0)
Function to output HTML to make an ajax call to make registration.
dol_now($mode='gmt')
Return date for now.
getDolUserInt($key, $default=0, $tmpuser=null)
Return Dolibarr user constant int value.
getListLimitFromScreenHeight()
Get the limit of list to show according to the screen height.
dolBuildUrl($url, $params=[], $addtoken=false, $anchor='')
Return path of url.
getDolUserString($key, $default='', $tmpuser=null)
Return Dolibarr user constant string value.
dolSetCookie(string $cookiename, string $cookievalue, int $expire=-1)
Set a cookie.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into JavaScript code.
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
dol_htmlentities($string, $flags=ENT_QUOTES|ENT_SUBSTITUTE, $encoding='UTF-8', $double_encode=false)
Replace htmlentities functions.
getBrowserInfo($user_agent)
Return information about user browser.
getDolCurrency()
Return the main currency ('EUR', 'USD', ...)
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_print_profids($profID, $profIDtype, $countrycode='', $addcpButton=1)
Format professional IDs according to their country.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
getNonce()
Return a random string to be used as a nonce value for js.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
picto_from_langcode($codelang, $moreatt='', $notitlealt=0)
Return img flag of country for a language code or country code.
dolButtonToOpenUrlInDialogPopup($name, $label, $buttonstring, $url, $disabled='', $morecss='classlink button bordertransp', $jsonopen='', $jsonclose='', $accesskey='')
Return HTML code to output a button to open a dialog popup box.
Definition html.lib.php:437
printCommonFooter($zone='private')
Print common footer : conf->global->MAIN_HTML_FOOTER js for switch of menu hider js for conf->global-...
dol_htmloutput_events($disabledoutputofmessages=0)
Print formatted messages to output (Used to show messages on html output).
info_admin($text, $infoonimgalt=0, $nodiv=0, $admin='1', $morecss='hideonsmartphone', $textfordropdown='', $picto='', $textonpictotooltip='', $cssfordropdown='info_admin')
Show information in HTML for admin users or standard users.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Definition html.lib.php:183
top_menu_importfile()
Build the tooltip on top menu quick add.
top_menu_quickadd()
Build the tooltip on top menu quick add.
top_htmlhead($head, $title='', $disablejs=0, $disablehead=0, $arrayofjs=array(), $arrayofcss=array(), $disableforlogin=0, $disablenofollow=0, $disablenoindex=0)
Output html header of a page.
top_menu_ai()
Build the HTML for the AI Assistant entry of the top menu: a toggle icon and a floating popover panel...
top_menu_user($hideloginname=0, $urllogout='')
Build the tooltip on user login.
left_menu($menu_array_before, $helppagename='', $notused='', $menu_array_after=array(), $leftmenuwithoutmainarea=0, $title='', $acceptdelayedhtml=0)
Show left menu bar.
if(!defined( 'NOREQUIREMENU')) if(!empty(GETPOST('seteventmessages', 'alpha'))) if(!function_exists("llxHeader")) top_httphead($contenttype='text/html', $forcenocache=0)
Show HTTP header.
main_area($title='')
Begin main area.
getHelpParamFor($helppagename, $langs)
Return helpbaseurl, helppage and mode.
printDropdownQuickadd($mode=0)
Generate list of quickadd items.
printSearchForm($urlaction, $urlobject, $title, $htmlmorecss, $htmlinputname, $accesskey='', $prefhtmlinputname='', $img='', $showtitlebefore=0, $autofocus=0)
Show a search area.
top_menu($head, $title='', $target='', $disablejs=0, $disablehead=0, $arrayofjs=array(), $arrayofcss=array(), $morequerystring='', $helppagename='')
Show an HTML header + a BODY + The top menu bar.
top_menu_search()
Build the tooltip on top menu search.
top_menu_bookmark()
Build the tooltip on top menu bookmark.
dolSessionsLimitForUser($fk_user, $keepcount, $currentsessionid)
Enforce a maximum number of concurrent database sessions for a given user.
$conf db user
Active Directory does not allow anonymous connections.
Definition repair.php:166
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:165
dolTotpCheckPendingLogin($db)
Check the code of the second step of a two-factor authentication.
checkLoginPassEntity($usertotest, $passwordtotest, $entitytotest, $authmode, $context='')
Return a login if login/pass was successful.
dolTotpStartSecondFactor($db, $login, $entity)
Start the second step of a two-factor authentication, just after a password has been validated.
checkIPInCidr($ip, $cidr)
Check if IP address is in CIDR range.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.
isHTTPS()
Return if we are using a HTTPS connection Check HTTPS (no way to be modified by user but may be empty...
multi select button
0 = Do not include form tag and submit button -1 = Do not include form tag but include submit button