dolibarr  13.0.2
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-2015 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-2015 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 Charlene Benke <charlie@patas-monkey.com>
16  *
17  * This program is free software; you can redistribute it and/or modify
18  * it under the terms of the GNU General Public License as published by
19  * the Free Software Foundation; either version 3 of the License, or
20  * (at your option) any later version.
21  *
22  * This program is distributed in the hope that it will be useful,
23  * but WITHOUT ANY WARRANTY; without even the implied warranty of
24  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25  * GNU General Public License for more details.
26  *
27  * You should have received a copy of the GNU General Public License
28  * along with this program. If not, see <https://www.gnu.org/licenses/>.
29  */
30 
37 //@ini_set('memory_limit', '128M'); // This may be useless if memory is hard limited by your PHP
38 
39 // For optional tuning. Enabled if environment variable MAIN_SHOW_TUNING_INFO is defined.
40 $micro_start_time = 0;
41 if (!empty($_SERVER['MAIN_SHOW_TUNING_INFO']))
42 {
43  list($usec, $sec) = explode(" ", microtime());
44  $micro_start_time = ((float) $usec + (float) $sec);
45  // Add Xdebug code coverage
46  //define('XDEBUGCOVERAGE',1);
47  if (defined('XDEBUGCOVERAGE')) {
48  xdebug_start_code_coverage();
49  }
50 }
51 
61 function testSqlAndScriptInject($val, $type)
62 {
63  // Decode string first
64  // So <svg o&#110;load='console.log(&quot;123&quot;)' become <svg onload='console.log(&quot;123&quot;)'
65  // So "&colon;&apos;" become ":'" (due to ENT_HTML5)
66  $val = html_entity_decode($val, ENT_QUOTES | ENT_HTML5);
67 
68  // TODO loop to decode until no more thing to decode ?
69 
70  // We clean string because some hacks try to obfuscate evil strings by inserting non printable chars. Example: 'java(ascci09)scr(ascii00)ipt' is processed like 'javascript' (whatever is place of evil ascii char)
71  // We should use dol_string_nounprintableascii but function is not yet loaded/available
72  $val = preg_replace('/[\x00-\x1F\x7F]/u', '', $val); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
73  // We clean html comments because some hacks try to obfuscate evil strings by inserting HTML comments. Example: on<!-- -->error=alert(1)
74  $val = preg_replace('/<!--[^>]*-->/', '', $val);
75 
76  $inj = 0;
77  // For SQL Injection (only GET are used to be included into bad escaped SQL requests)
78  if ($type == 1 || $type == 3)
79  {
80  $inj += preg_match('/delete\s+from/i', $val);
81  $inj += preg_match('/create\s+table/i', $val);
82  $inj += preg_match('/insert\s+into/i', $val);
83  $inj += preg_match('/select\s+from/i', $val);
84  $inj += preg_match('/into\s+(outfile|dumpfile)/i', $val);
85  $inj += preg_match('/user\s*\(/i', $val); // avoid to use function user() that return current database login
86  $inj += preg_match('/information_schema/i', $val); // avoid to use request that read information_schema database
87  $inj += preg_match('/<svg/i', $val); // <svg can be allowed in POST
88  }
89  if ($type == 3)
90  {
91  $inj += preg_match('/select|update|delete|truncate|replace|group\s+by|concat|count|from|union/i', $val);
92  }
93  if ($type != 2) // Not common key strings, so we can check them both on GET and POST
94  {
95  $inj += preg_match('/updatexml\(/i', $val);
96  $inj += preg_match('/update.+set.+=/i', $val);
97  $inj += preg_match('/union.+select/i', $val);
98  $inj += preg_match('/(\.\.%2f)+/i', $val);
99  }
100  // For XSS Injection done by closing textarea to execute content into a textarea field
101  $inj += preg_match('/<\/textarea/i', $val);
102  // For XSS Injection done by adding javascript with script
103  // This is all cases a browser consider text is javascript:
104  // When it found '<script', 'javascript:', '<style', 'onload\s=' on body tag, '="&' on a tag size with old browsers
105  // All examples on page: http://ha.ckers.org/xss.html#XSScalc
106  // More on https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
107  $inj += preg_match('/<audio/i', $val);
108  $inj += preg_match('/<embed/i', $val);
109  $inj += preg_match('/<iframe/i', $val);
110  $inj += preg_match('/<object/i', $val);
111  $inj += preg_match('/<script/i', $val);
112  $inj += preg_match('/Set\.constructor/i', $val); // ECMA script 6
113  if (!defined('NOSTYLECHECK')) $inj += preg_match('/<style/i', $val);
114  $inj += preg_match('/base\s+href/si', $val);
115  $inj += preg_match('/=data:/si', $val);
116  // List of dom events is on https://www.w3schools.com/jsref/dom_obj_event.asp
117  $inj += preg_match('/onmouse([a-z]*)\s*=/i', $val); // onmousexxx can be set on img or any html tag like <img title='...' onmouseover=alert(1)>
118  $inj += preg_match('/ondrag([a-z]*)\s*=/i', $val); //
119  $inj += preg_match('/ontouch([a-z]*)\s*=/i', $val); //
120  $inj += preg_match('/on(abort|afterprint|beforeprint|beforeunload|blur|canplay|canplaythrough|change|click|contextmenu|copy|cut)\s*=/i', $val);
121  $inj += preg_match('/on(dblclick|drop|durationchange|ended|error|focus|focusin|focusout|hashchange|input|invalid)\s*=/i', $val);
122  $inj += preg_match('/on(keydown|keypress|keyup|load|loadeddata|loadedmetadata|loadstart|offline|online|pagehide|pageshow)\s*=/i', $val);
123  $inj += preg_match('/on(paste|pause|play|playing|progress|ratechange|resize|reset|scroll|search|seeking|select|show|stalled|start|submit|suspend)\s*=/i', $val);
124  $inj += preg_match('/on(timeupdate|toggle|unload|volumechange|waiting)\s*=/i', $val);
125 
126  // We refuse html into html because some hacks try to obfuscate evil strings by inserting HTML into HTML. Example: <img on<a>error=alert(1) to bypass test on onerror
127  $tmpval = preg_replace('/<[^<]+>/', '', $val);
128  // List of dom events is on https://www.w3schools.com/jsref/dom_obj_event.asp
129  $inj += preg_match('/onmouse([a-z]*)\s*=/i', $tmpval); // onmousexxx can be set on img or any html tag like <img title='...' onmouseover=alert(1)>
130  $inj += preg_match('/ondrag([a-z]*)\s*=/i', $tmpval); //
131  $inj += preg_match('/ontouch([a-z]*)\s*=/i', $tmpval); //
132  $inj += preg_match('/on(abort|afterprint|beforeprint|beforeunload|blur|canplay|canplaythrough|change|click|contextmenu|copy|cut)\s*=/i', $tmpval);
133  $inj += preg_match('/on(dblclick|drop|durationchange|ended|error|focus|focusin|focusout|hashchange|input|invalid)\s*=/i', $tmpval);
134  $inj += preg_match('/on(keydown|keypress|keyup|load|loadeddata|loadedmetadata|loadstart|offline|online|pagehide|pageshow)\s*=/i', $tmpval);
135  $inj += preg_match('/on(paste|pause|play|playing|progress|ratechange|resize|reset|scroll|search|seeking|select|show|stalled|start|submit|suspend)\s*=/i', $tmpval);
136  $inj += preg_match('/on(timeupdate|toggle|unload|volumechange|waiting)\s*=/i', $tmpval);
137 
138  //$inj += preg_match('/on[A-Z][a-z]+\*=/', $val); // To lock event handlers onAbort(), ...
139  $inj += preg_match('/&#58;|&#0000058|&#x3A/i', $val); // refused string ':' encoded (no reason to have it encoded) to lock 'javascript:...'
140  $inj += preg_match('/javascript\s*:/i', $val);
141  $inj += preg_match('/vbscript\s*:/i', $val);
142  // For XSS Injection done by adding javascript closing html tags like with onmousemove, etc... (closing a src or href tag with not cleaned param)
143  if ($type == 1) {
144  $val = str_replace('enclosure="', 'enclosure=X', $val); // We accept enclosure="
145  $inj += preg_match('/"/i', $val); // We refused " in GET parameters value.
146  }
147  if ($type == 2) $inj += preg_match('/[;"]/', $val); // PHP_SELF is a file system path. It can contains spaces.
148  return $inj;
149 }
150 
159 {
160  if (is_array($var))
161  {
162  foreach ($var as $key => $value) // Warning, $key may also be used for attacks
163  {
165  {
166  //$var[$key] = $value; // This is useless
167  } else {
168  // Get remote IP: PS: We do not use getRemoteIP(), function is not yet loaded and we need a value that can't be spoofed
169  $ip = (empty($_SERVER['REMOTE_ADDR']) ? 'unknown' : $_SERVER['REMOTE_ADDR']);
170  $errormessage = 'Access refused to '.$ip.' by SQL or Script injection protection in main.inc.php (type='.htmlentities($type).' key='.htmlentities($key).' value='.htmlentities($value).' page='.htmlentities($_SERVER["REQUEST_URI"]).')';
171  print $errormessage;
172  // Add entry into error log
173  if (function_exists('error_log')) {
174  error_log($errormessage);
175  }
176  // TODO Add entry into security audit table
177  exit;
178  }
179  }
180  return true;
181  } else {
182  return (testSqlAndScriptInject($var, $type) <= 0);
183  }
184 }
185 
186 
187 // Check consistency of NOREQUIREXXX DEFINES
188 if ((defined('NOREQUIREDB') || defined('NOREQUIRETRAN')) && !defined('NOREQUIREMENU'))
189 {
190  print 'If define NOREQUIREDB or NOREQUIRETRAN are set, you must also set NOREQUIREMENU or not set them';
191  exit;
192 }
193 
194 // Sanity check on URL
195 if (!empty($_SERVER["PHP_SELF"]))
196 {
197  $morevaltochecklikepost = array($_SERVER["PHP_SELF"]);
198  analyseVarsForSqlAndScriptsInjection($morevaltochecklikepost, 2);
199 }
200 // Sanity check on GET parameters
201 if (!defined('NOSCANGETFORINJECTION') && !empty($_SERVER["QUERY_STRING"]))
202 {
203  // Note: QUERY_STRING is url encoded, but $_GET and $_POST are already decoded
204  // Because the analyseVarsForSqlAndScriptsInjection is designed for already url decoded value, we must decode QUERY_STRING
205  // Another solution is to provide $_GET as parameter
206  $morevaltochecklikeget = array(urldecode($_SERVER["QUERY_STRING"]));
207  analyseVarsForSqlAndScriptsInjection($morevaltochecklikeget, 1);
208 }
209 // Sanity check on POST
210 if (!defined('NOSCANPOSTFORINJECTION'))
211 {
213 }
214 
215 // This is to make Dolibarr working with Plesk
216 if (!empty($_SERVER['DOCUMENT_ROOT']) && substr($_SERVER['DOCUMENT_ROOT'], -6) !== 'htdocs')
217 {
218  set_include_path($_SERVER['DOCUMENT_ROOT'].'/htdocs');
219 }
220 
221 // Include the conf.php and functions.lib.php. This defined the constants like DOL_DOCUMENT_ROOT, DOL_DATA_ROOT, DOL_URL_ROOT...
222 require_once 'filefunc.inc.php';
223 
224 // If there is a POST parameter to tell to save automatically some POST parameters into cookies, we do it.
225 // This is used for example by form of boxes to save personalization of some options.
226 // DOL_AUTOSET_COOKIE=cookiename:val1,val2 and cookiename_val1=aaa cookiename_val2=bbb will set cookie_name with value json_encode(array('val1'=> , ))
227 if (!empty($_POST["DOL_AUTOSET_COOKIE"]))
228 {
229  $tmpautoset = explode(':', $_POST["DOL_AUTOSET_COOKIE"], 2);
230  $tmplist = explode(',', $tmpautoset[1]);
231  $cookiearrayvalue = array();
232  foreach ($tmplist as $tmpkey)
233  {
234  $postkey = $tmpautoset[0].'_'.$tmpkey;
235  //var_dump('tmpkey='.$tmpkey.' postkey='.$postkey.' value='.$_POST[$postkey]);
236  if (!empty($_POST[$postkey])) $cookiearrayvalue[$tmpkey] = $_POST[$postkey];
237  }
238  $cookiename = $tmpautoset[0];
239  $cookievalue = json_encode($cookiearrayvalue);
240  //var_dump('setcookie cookiename='.$cookiename.' cookievalue='.$cookievalue);
241  setcookie($cookiename, empty($cookievalue) ? '' : $cookievalue, empty($cookievalue) ? 0 : (time() + (86400 * 354)), '/', null, false, true); // keep cookie 1 year and add tag httponly
242  if (empty($cookievalue)) unset($_COOKIE[$cookiename]);
243 }
244 
245 
246 // Set the handler of session
247 if (ini_get('session.save_handler') == 'user') {
248  require_once 'core/lib/phpsessionindb.lib.php';
249 }
250 
251 // Init session. Name of session is specific to Dolibarr instance.
252 // 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).
253 // 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.
254 $prefix = dol_getprefix('');
255 $sessionname = 'DOLSESSID_'.$prefix;
256 $sessiontimeout = 'DOLSESSTIMEOUT_'.$prefix;
257 if (!empty($_COOKIE[$sessiontimeout])) ini_set('session.gc_maxlifetime', $_COOKIE[$sessiontimeout]);
258 // This create lock, released by session_write_close() or end of page.
259 // We need this lock as long as we read/write $_SESSION ['vars']. We can remove lock when finished.
260 if (!defined('NOSESSION'))
261 {
262  session_set_cookie_params(0, '/', null, (empty($dolibarr_main_force_https) ? false : true), 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.
263  session_name($sessionname);
264  session_start();
265 }
266 
267 
268 // Init the 5 global objects, this include will make the 'new Xxx()' and set properties for: $conf, $db, $langs, $user, $mysoc
269 require_once 'master.inc.php';
270 
271 
272 // If software has been locked. Only login $conf->global->MAIN_ONLY_LOGIN_ALLOWED is allowed.
273 if (!empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED))
274 {
275  $ok = 0;
276  if ((!session_id() || !isset($_SESSION["dol_login"])) && !isset($_POST["username"]) && !empty($_SERVER["GATEWAY_INTERFACE"])) $ok = 1; // We let working pages if not logged and inside a web browser (login form, to allow login by admin)
277  elseif (isset($_POST["username"]) && $_POST["username"] == $conf->global->MAIN_ONLY_LOGIN_ALLOWED) $ok = 1; // We let working pages that is a login submission (login submit, to allow login by admin)
278  elseif (defined('NOREQUIREDB')) $ok = 1; // We let working pages that don't need database access (xxx.css.php)
279  elseif (defined('EVEN_IF_ONLY_LOGIN_ALLOWED')) $ok = 1; // We let working pages that ask to work even if only login enabled (logout.php)
280  elseif (session_id() && isset($_SESSION["dol_login"]) && $_SESSION["dol_login"] == $conf->global->MAIN_ONLY_LOGIN_ALLOWED) $ok = 1; // We let working if user is allowed admin
281  if (!$ok)
282  {
283  if (session_id() && isset($_SESSION["dol_login"]) && $_SESSION["dol_login"] != $conf->global->MAIN_ONLY_LOGIN_ALLOWED)
284  {
285  print 'Sorry, your application is offline.'."\n";
286  print 'You are logged with user "'.$_SESSION["dol_login"].'" and only administrator user "'.$conf->global->MAIN_ONLY_LOGIN_ALLOWED.'" is allowed to connect for the moment.'."\n";
287  $nexturl = DOL_URL_ROOT.'/user/logout.php';
288  print 'Please try later or <a href="'.$nexturl.'">click here to disconnect and change login user</a>...'."\n";
289  } else {
290  print 'Sorry, your application is offline. Only administrator user "'.$conf->global->MAIN_ONLY_LOGIN_ALLOWED.'" is allowed to connect for the moment.'."\n";
291  $nexturl = DOL_URL_ROOT.'/';
292  print 'Please try later or <a href="'.$nexturl.'">click here to change login user</a>...'."\n";
293  }
294  exit;
295  }
296 }
297 
298 
299 // Activate end of page function
300 register_shutdown_function('dol_shutdown');
301 
302 // Load debugbar
303 if (!empty($conf->debugbar->enabled) && !GETPOST('dol_use_jmobile') && empty($_SESSION['dol_use_jmobile']))
304 {
305  global $debugbar;
306  include_once DOL_DOCUMENT_ROOT.'/debugbar/class/DebugBar.php';
307  $debugbar = new DolibarrDebugBar();
308  $renderer = $debugbar->getRenderer();
309  if (empty($conf->global->MAIN_HTML_HEADER)) $conf->global->MAIN_HTML_HEADER = '';
310  $conf->global->MAIN_HTML_HEADER .= $renderer->renderHead();
311 
312  $debugbar['time']->startMeasure('pageaftermaster', 'Page generation (after environment init)');
313 }
314 
315 // Detection browser
316 if (isset($_SERVER["HTTP_USER_AGENT"]))
317 {
318  $tmp = getBrowserInfo($_SERVER["HTTP_USER_AGENT"]);
319  $conf->browser->name = $tmp['browsername'];
320  $conf->browser->os = $tmp['browseros'];
321  $conf->browser->version = $tmp['browserversion'];
322  $conf->browser->layout = $tmp['layout']; // 'classic', 'phone', 'tablet'
323  //var_dump($conf->browser);
324 
325  if ($conf->browser->layout == 'phone') $conf->dol_no_mouse_hover = 1;
326 }
327 
328 // Set global MAIN_OPTIMIZEFORTEXTBROWSER (must be before login part)
329 if (GETPOST('textbrowser', 'int') || (!empty($conf->browser->name) && $conf->browser->name == 'lynxlinks')) // If we must enable text browser
330 {
331  $conf->global->MAIN_OPTIMIZEFORTEXTBROWSER = 1;
332 }
333 
334 // Force HTTPS if required ($conf->file->main_force_https is 0/1 or 'https dolibarr root url')
335 // $_SERVER["HTTPS"] is 'on' when link is https, otherwise $_SERVER["HTTPS"] is empty or 'off'
336 if (!empty($conf->file->main_force_https) && (empty($_SERVER["HTTPS"]) || $_SERVER["HTTPS"] != 'on'))
337 {
338  $newurl = '';
339  if (is_numeric($conf->file->main_force_https))
340  {
341  if ($conf->file->main_force_https == '1' && !empty($_SERVER["SCRIPT_URI"])) // If SCRIPT_URI supported by server
342  {
343  if (preg_match('/^http:/i', $_SERVER["SCRIPT_URI"]) && !preg_match('/^https:/i', $_SERVER["SCRIPT_URI"])) // If link is http
344  {
345  $newurl = preg_replace('/^http:/i', 'https:', $_SERVER["SCRIPT_URI"]);
346  }
347  } else {
348  // Check HTTPS environment variable (Apache/mod_ssl only)
349  $newurl = preg_replace('/^http:/i', 'https:', DOL_MAIN_URL_ROOT).$_SERVER["REQUEST_URI"];
350  }
351  } else {
352  // Check HTTPS environment variable (Apache/mod_ssl only)
353  $newurl = $conf->file->main_force_https.$_SERVER["REQUEST_URI"];
354  }
355  // Start redirect
356  if ($newurl)
357  {
358  header_remove(); // Clean header already set to be sure to remove any header like "Set-Cookie: DOLSESSID_..." from non HTTPS answers
359  dol_syslog("main.inc: dolibarr_main_force_https is on, we make a redirect to ".$newurl);
360  header("Location: ".$newurl);
361  exit;
362  } else {
363  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);
364  }
365 }
366 
367 if (!defined('NOLOGIN') && !defined('NOIPCHECK') && !empty($dolibarr_main_restrict_ip))
368 {
369  $listofip = explode(',', $dolibarr_main_restrict_ip);
370  $found = false;
371  foreach ($listofip as $ip)
372  {
373  $ip = trim($ip);
374  if ($ip == $_SERVER['REMOTE_ADDR'])
375  {
376  $found = true;
377  break;
378  }
379  }
380  if (!$found)
381  {
382  print 'Access refused by IP protection. Your detected IP is '.$_SERVER['REMOTE_ADDR'];
383  exit;
384  }
385 }
386 
387 // Loading of additional presentation includes
388 if (!defined('NOREQUIREHTML')) require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; // Need 660ko memory (800ko in 2.2)
389 require_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; // Need 22ko memory
390 
391 // If install or upgrade process not done or not completely finished, we call the install page.
392 if (!empty($conf->global->MAIN_NOT_INSTALLED) || !empty($conf->global->MAIN_NOT_UPGRADED))
393 {
394  dol_syslog("main.inc: A previous install or upgrade was not complete. Redirect to install page.", LOG_WARNING);
395  header("Location: ".DOL_URL_ROOT."/install/index.php");
396  exit;
397 }
398 // If an upgrade process is required, we call the install page.
399 if ((!empty($conf->global->MAIN_VERSION_LAST_UPGRADE) && ($conf->global->MAIN_VERSION_LAST_UPGRADE != DOL_VERSION))
400 || (empty($conf->global->MAIN_VERSION_LAST_UPGRADE) && !empty($conf->global->MAIN_VERSION_LAST_INSTALL) && ($conf->global->MAIN_VERSION_LAST_INSTALL != DOL_VERSION)))
401 {
402  $versiontocompare = empty($conf->global->MAIN_VERSION_LAST_UPGRADE) ? $conf->global->MAIN_VERSION_LAST_INSTALL : $conf->global->MAIN_VERSION_LAST_UPGRADE;
403  require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
404  $dolibarrversionlastupgrade = preg_split('/[.-]/', $versiontocompare);
405  $dolibarrversionprogram = preg_split('/[.-]/', DOL_VERSION);
406  $rescomp = versioncompare($dolibarrversionprogram, $dolibarrversionlastupgrade);
407  if ($rescomp > 0) // Programs have a version higher than database. We did not add "&& $rescomp < 3" because we want upgrade process for build upgrades
408  {
409  dol_syslog("main.inc: database version ".$versiontocompare." is lower than programs version ".DOL_VERSION.". Redirect to install page.", LOG_WARNING);
410  header("Location: ".DOL_URL_ROOT."/install/index.php");
411  exit;
412  }
413 }
414 
415 // Creation of a token against CSRF vulnerabilities
416 if (!defined('NOTOKENRENEWAL'))
417 {
418  // Rolling token at each call ($_SESSION['token'] contains token of previous page)
419  if (isset($_SESSION['newtoken'])) $_SESSION['token'] = $_SESSION['newtoken'];
420 
421  // Save in $_SESSION['newtoken'] what will be next token. Into forms, we will add param token = $_SESSION['newtoken']
422  $token = dol_hash(uniqid(mt_rand(), true)); // Generates a hash of a random number
423  $_SESSION['newtoken'] = $token;
424  dol_syslog("NEW TOKEN reclaimed by : " . $_SERVER['PHP_SELF'], LOG_DEBUG);
425 }
426 
427 //dol_syslog("aaaa - ".defined('NOCSRFCHECK')." - ".$dolibarr_nocsrfcheck." - ".$conf->global->MAIN_SECURITY_CSRF_WITH_TOKEN." - ".$_SERVER['REQUEST_METHOD']." - ".GETPOST('token', 'alpha').' '.$_SESSION['token']);
428 //$dolibarr_nocsrfcheck=1;
429 // Check token
430 if ((!defined('NOCSRFCHECK') && empty($dolibarr_nocsrfcheck) && !empty($conf->global->MAIN_SECURITY_CSRF_WITH_TOKEN))
431  || defined('CSRFCHECK_WITH_TOKEN')) // Check validity of token, only if option MAIN_SECURITY_CSRF_WITH_TOKEN enabled or if constant CSRFCHECK_WITH_TOKEN is set into page
432 {
433  // Check all cases that need a token (all POST actions, all actions and mass actions on pages with CSRFCHECK_WITH_TOKEN set, all sensitive GET actions)
434  if ($_SERVER['REQUEST_METHOD'] == 'POST' ||
435  ((GETPOSTISSET('action') || GETPOSTISSET('massaction')) && defined('CSRFCHECK_WITH_TOKEN')) ||
436  in_array(GETPOST('action', 'aZ09'), array('add', 'addtimespent', 'update', 'install', 'delete', 'deletefilter', 'deleteoperation', 'deleteprof', 'deletepayment', 'confirm_create_user', 'confirm_create_thirdparty', 'confirm_reject_check')))
437  {
438  if (!GETPOSTISSET('token')) {
439  if (GETPOST('uploadform', 'int')) {
440  dol_syslog("--- Access to ".$_SERVER["PHP_SELF"]." refused. File size too large.");
441  $langs->loadLangs(array("errors", "install"));
442  print $langs->trans("ErrorFileSizeTooLarge").' ';
443  print $langs->trans("ErrorGoBackAndCorrectParameters");
444  die;
445  } else {
446  dol_syslog("--- Access to ".$_SERVER["PHP_SELF"]." refused by CSRFCHECK_WITH_TOKEN protection. Token not provided.");
447  if (defined('CSRFCHECK_WITH_TOKEN')) {
448  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";
449  } else {
450  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";
451  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 into setup).\n";
452  }
453  die;
454  }
455  }
456  }
457 
458  if (GETPOSTISSET('token') && GETPOST('token', 'alpha') != $_SESSION['token'])
459  {
460  dol_syslog("--- Access to ".$_SERVER["PHP_SELF"]." refused due to invalid token, so we disable POST and some GET parameters - referer=".$_SERVER['HTTP_REFERER'].", action=".GETPOST('action', 'aZ09').", _GET|POST['token']=".GETPOST('token', 'alpha').", _SESSION['token']=".$_SESSION['token'], LOG_WARNING);
461  //print 'Unset POST by CSRF protection in main.inc.php.'; // Do not output anything because this create problems when using the BACK button on browsers.
462  setEventMessages('SecurityTokenHasExpiredSoActionHasBeenCanceledPleaseRetry', null, 'warnings');
463  //if ($conf->global->MAIN_FEATURES_LEVEL >= 1) setEventMessages('Unset POST and GET params by CSRF protection in main.inc.php (Token provided was not generated by the previous page).'."<br>\n".'$_SERVER[REQUEST_URI] = '.$_SERVER['REQUEST_URI'].' $_SERVER[REQUEST_METHOD] = '.$_SERVER['REQUEST_METHOD'].' GETPOST(token) = '.GETPOST('token', 'alpha').' $_SESSION[token] = '.$_SESSION['token'], null, 'warnings');
464  $savid = ((int) $_POST['id']);
465  unset($_POST);
466  //unset($_POST['action']); unset($_POST['massaction']);
467  //unset($_POST['confirm']); unset($_POST['confirmmassaction']);
468  unset($_GET['confirm']);
469  unset($_GET['action']);
470  unset($_GET['confirmmassaction']);
471  unset($_GET['massaction']);
472  $_POST['id'] = ((int) $savid);
473  }
474 }
475 
476 // Disable modules (this must be after session_start and after conf has been loaded)
477 if (GETPOSTISSET('disablemodules')) $_SESSION["disablemodules"] = GETPOST('disablemodules', 'alpha');
478 if (!empty($_SESSION["disablemodules"]))
479 {
480  $modulepartkeys = array('css', 'js', 'tabs', 'triggers', 'login', 'substitutions', 'menus', 'theme', 'sms', 'tpl', 'barcode', 'models', 'societe', 'hooks', 'dir', 'syslog', 'tpllinkable', 'contactelement', 'moduleforexternal');
481 
482  $disabled_modules = explode(',', $_SESSION["disablemodules"]);
483  foreach ($disabled_modules as $module)
484  {
485  if ($module)
486  {
487  if (empty($conf->$module)) $conf->$module = new stdClass(); // To avoid warnings
488  $conf->$module->enabled = false;
489  foreach ($modulepartkeys as $modulepartkey)
490  {
491  unset($conf->modules_parts[$modulepartkey][$module]);
492  }
493  if ($module == 'fournisseur') // Special case
494  {
495  $conf->supplier_order->enabled = 0;
496  $conf->supplier_invoice->enabled = 0;
497  }
498  }
499  }
500 }
501 
502 // Set current modulepart
503 $modulepart = explode("/", $_SERVER["PHP_SELF"]);
504 if (is_array($modulepart) && count($modulepart) > 0)
505 {
506  foreach ($conf->modules as $module)
507  {
508  if (in_array($module, $modulepart))
509  {
510  $conf->modulepart = $module;
511  break;
512  }
513  }
514 }
515 
516 /*
517  * Phase authentication / login
518  */
519 $login = '';
520 if (!defined('NOLOGIN'))
521 {
522  // $authmode lists the different method of identification to be tested in order of preference.
523  // Example: 'http', 'dolibarr', 'ldap', 'http,forceuser', '...'
524 
525  if (defined('MAIN_AUTHENTICATION_MODE'))
526  {
527  $dolibarr_main_authentication = constant('MAIN_AUTHENTICATION_MODE');
528  } else {
529  // Authentication mode
530  if (empty($dolibarr_main_authentication)) $dolibarr_main_authentication = 'http,dolibarr';
531  // Authentication mode: forceuser
532  if ($dolibarr_main_authentication == 'forceuser' && empty($dolibarr_auto_user)) $dolibarr_auto_user = 'auto';
533  }
534  // Set authmode
535  $authmode = explode(',', $dolibarr_main_authentication);
536 
537  // No authentication mode
538  if (!count($authmode))
539  {
540  $langs->load('main');
541  dol_print_error('', $langs->trans("ErrorConfigParameterNotDefined", 'dolibarr_main_authentication'));
542  exit;
543  }
544 
545  // If login request was already post, we retrieve login from the session
546  // Call module if not realized that his request.
547  // At the end of this phase, the variable $login is defined.
548  $resultFetchUser = '';
549  $test = true;
550  if (!isset($_SESSION["dol_login"]))
551  {
552  // It is not already authenticated and it requests the login / password
553  include_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
554 
555  $dol_dst_observed = GETPOST("dst_observed", 'int', 3);
556  $dol_dst_first = GETPOST("dst_first", 'int', 3);
557  $dol_dst_second = GETPOST("dst_second", 'int', 3);
558  $dol_screenwidth = GETPOST("screenwidth", 'int', 3);
559  $dol_screenheight = GETPOST("screenheight", 'int', 3);
560  $dol_hide_topmenu = GETPOST('dol_hide_topmenu', 'int', 3);
561  $dol_hide_leftmenu = GETPOST('dol_hide_leftmenu', 'int', 3);
562  $dol_optimize_smallscreen = GETPOST('dol_optimize_smallscreen', 'int', 3);
563  $dol_no_mouse_hover = GETPOST('dol_no_mouse_hover', 'int', 3);
564  $dol_use_jmobile = GETPOST('dol_use_jmobile', 'int', 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
565  //dol_syslog("POST key=".join(array_keys($_POST),',').' value='.join($_POST,','));
566 
567  // If in demo mode, we check we go to home page through the public/demo/index.php page
568  if (!empty($dolibarr_main_demo) && $_SERVER['PHP_SELF'] == DOL_URL_ROOT.'/index.php') // We ask index page
569  {
570  if (empty($_SERVER['HTTP_REFERER']) || !preg_match('/public/', $_SERVER['HTTP_REFERER']))
571  {
572  dol_syslog("Call index page from another url than demo page (call is done from page ".$_SERVER['HTTP_REFERER'].")");
573  $url = '';
574  $url .= ($url ? '&' : '').($dol_hide_topmenu ? 'dol_hide_topmenu='.$dol_hide_topmenu : '');
575  $url .= ($url ? '&' : '').($dol_hide_leftmenu ? 'dol_hide_leftmenu='.$dol_hide_leftmenu : '');
576  $url .= ($url ? '&' : '').($dol_optimize_smallscreen ? 'dol_optimize_smallscreen='.$dol_optimize_smallscreen : '');
577  $url .= ($url ? '&' : '').($dol_no_mouse_hover ? 'dol_no_mouse_hover='.$dol_no_mouse_hover : '');
578  $url .= ($url ? '&' : '').($dol_use_jmobile ? 'dol_use_jmobile='.$dol_use_jmobile : '');
579  $url = DOL_URL_ROOT.'/public/demo/index.php'.($url ? '?'.$url : '');
580  header("Location: ".$url);
581  exit;
582  }
583  }
584 
585  // Hooks for security access
586  $action = '';
587  $hookmanager->initHooks(array('login'));
588  $parameters = array();
589  $reshook = $hookmanager->executeHooks('beforeLoginAuthentication', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks
590  if ($reshook < 0) {
591  $test = false;
592  $error++;
593  }
594 
595  // Verification security graphic code
596  if ($test && GETPOST("username", "alpha", 2) && !empty($conf->global->MAIN_SECURITY_ENABLECAPTCHA) && !isset($_SESSION['dol_bypass_antispam']))
597  {
598  $sessionkey = 'dol_antispam_value';
599  $ok = (array_key_exists($sessionkey, $_SESSION) === true && (strtolower($_SESSION[$sessionkey]) == strtolower($_POST['code'])));
600 
601  // Check code
602  if (!$ok)
603  {
604  dol_syslog('Bad value for code, connexion refused');
605  // Load translation files required by page
606  $langs->loadLangs(array('main', 'errors'));
607 
608  $_SESSION["dol_loginmesg"] = $langs->trans("ErrorBadValueForCode");
609  $test = false;
610 
611  // Call trigger for the "security events" log
612  $user->trigger_mesg = 'ErrorBadValueForCode - login='.GETPOST("username", "alpha", 2);
613 
614  // Call trigger
615  $result = $user->call_trigger('USER_LOGIN_FAILED', $user);
616  if ($result < 0) $error++;
617  // End call triggers
618 
619  // Hooks on failed login
620  $action = '';
621  $hookmanager->initHooks(array('login'));
622  $parameters = array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
623  $reshook = $hookmanager->executeHooks('afterLoginFailed', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks
624  if ($reshook < 0) $error++;
625 
626  // Note: exit is done later
627  }
628  }
629 
630  $allowedmethodtopostusername = 2;
631  if (defined('MAIN_AUTHENTICATION_POST_METHOD')) $allowedmethodtopostusername = constant('MAIN_AUTHENTICATION_POST_METHOD');
632  $usertotest = (!empty($_COOKIE['login_dolibarr']) ? preg_replace('/[^a-zA-Z0-9_\-]/', '', $_COOKIE['login_dolibarr']) : GETPOST("username", "alpha", $allowedmethodtopostusername));
633  $passwordtotest = GETPOST('password', 'none', $allowedmethodtopostusername);
634  $entitytotest = (GETPOST('entity', 'int') ? GETPOST('entity', 'int') : (!empty($conf->entity) ? $conf->entity : 1));
635 
636  // Define if we received data to test the login.
637  $goontestloop = false;
638  if (isset($_SERVER["REMOTE_USER"]) && in_array('http', $authmode)) $goontestloop = true;
639  if ($dolibarr_main_authentication == 'forceuser' && !empty($dolibarr_auto_user)) $goontestloop = true;
640  if (GETPOST("username", "alpha", $allowedmethodtopostusername) || !empty($_COOKIE['login_dolibarr']) || GETPOST('openid_mode', 'alpha', 1)) $goontestloop = true;
641 
642  if (!is_object($langs)) // This can occurs when calling page with NOREQUIRETRAN defined, however we need langs for error messages.
643  {
644  include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
645  $langs = new Translate("", $conf);
646  $langcode = (GETPOST('lang', 'aZ09', 1) ?GETPOST('lang', 'aZ09', 1) : (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT));
647  if (defined('MAIN_LANG_DEFAULT')) $langcode = constant('MAIN_LANG_DEFAULT');
648  $langs->setDefaultLang($langcode);
649  }
650 
651  // Validation of login/pass/entity
652  // If ok, the variable login will be returned
653  // If error, we will put error message in session under the name dol_loginmesg
654  if ($test && $goontestloop && (GETPOST('actionlogin', 'aZ09') == 'login' || $dolibarr_main_authentication != 'dolibarr'))
655  {
656  $login = checkLoginPassEntity($usertotest, $passwordtotest, $entitytotest, $authmode);
657  if ($login === '--bad-login-validity--') {
658  $login = '';
659  }
660 
661  if ($login)
662  {
663  $dol_authmode = $conf->authmode; // This properties is defined only when logged, to say what mode was successfully used
664  $dol_tz = $_POST["tz"];
665  $dol_tz_string = $_POST["tz_string"];
666  $dol_tz_string = preg_replace('/\s*\(.+\)$/', '', $dol_tz_string);
667  $dol_tz_string = preg_replace('/,/', '/', $dol_tz_string);
668  $dol_tz_string = preg_replace('/\s/', '_', $dol_tz_string);
669  $dol_dst = 0;
670  // Keep $_POST here. Do not use GETPOSTISSET
671  if (isset($_POST["dst_first"]) && isset($_POST["dst_second"]))
672  {
673  include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
674  $datenow = dol_now();
675  $datefirst = dol_stringtotime($_POST["dst_first"]);
676  $datesecond = dol_stringtotime($_POST["dst_second"]);
677  if ($datenow >= $datefirst && $datenow < $datesecond) $dol_dst = 1;
678  }
679  //print $datefirst.'-'.$datesecond.'-'.$datenow.'-'.$dol_tz.'-'.$dol_tzstring.'-'.$dol_dst; exit;
680  }
681 
682  if (!$login)
683  {
684  dol_syslog('Bad password, connexion refused', LOG_DEBUG);
685  // Load translation files required by page
686  $langs->loadLangs(array('main', 'errors'));
687 
688  // Bad password. No authmode has found a good password.
689  // We set a generic message if not defined inside function checkLoginPassEntity or subfunctions
690  if (empty($_SESSION["dol_loginmesg"])) $_SESSION["dol_loginmesg"] = $langs->trans("ErrorBadLoginPassword");
691 
692  // Call trigger for the "security events" log
693  $user->trigger_mesg = $langs->trans("ErrorBadLoginPassword").' - login='.GETPOST("username", "alpha", 2);
694 
695  // Call trigger
696  $result = $user->call_trigger('USER_LOGIN_FAILED', $user);
697  if ($result < 0) $error++;
698  // End call triggers
699 
700  // Hooks on failed login
701  $action = '';
702  $hookmanager->initHooks(array('login'));
703  $parameters = array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
704  $reshook = $hookmanager->executeHooks('afterLoginFailed', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks
705  if ($reshook < 0) $error++;
706 
707  // Note: exit is done in next chapter
708  }
709  }
710 
711  // End test login / passwords
712  if (!$login || (in_array('ldap', $authmode) && empty($passwordtotest))) // With LDAP we refused empty password because some LDAP are "opened" for anonymous access so connexion is a success.
713  {
714  // No data to test login, so we show the login page.
715  dol_syslog("--- Access to ".$_SERVER["PHP_SELF"]." - action=".GETPOST('action', 'aZ09')." - actionlogin=".GETPOST('actionlogin', 'aZ09')." - showing the login form and exit");
716  if (defined('NOREDIRECTBYMAINTOLOGIN')) return 'ERROR_NOT_LOGGED';
717  else {
718  if ($_SERVER["HTTP_USER_AGENT"] == 'securitytest') {
719  http_response_code(401); // It makes easier to understand if session was broken during security tests
720  }
721  dol_loginfunction($langs, $conf, (!empty($mysoc) ? $mysoc : ''));
722  }
723  exit;
724  }
725 
726  $resultFetchUser = $user->fetch('', $login, '', 1, ($entitytotest > 0 ? $entitytotest : -1)); // login was retrieved previously when checking password.
727  if ($resultFetchUser <= 0)
728  {
729  dol_syslog('User not found, connexion refused');
730  session_destroy();
731  session_set_cookie_params(0, '/', null, (empty($dolibarr_main_force_https) ? false : true), true); // Add tag secure and httponly on session cookie
732  session_name($sessionname);
733  session_start();
734 
735  if ($resultFetchUser == 0)
736  {
737  // Load translation files required by page
738  $langs->loadLangs(array('main', 'errors'));
739 
740  $_SESSION["dol_loginmesg"] = $langs->trans("ErrorCantLoadUserFromDolibarrDatabase", $login);
741 
742  $user->trigger_mesg = 'ErrorCantLoadUserFromDolibarrDatabase - login='.$login;
743  }
744  if ($resultFetchUser < 0)
745  {
746  $_SESSION["dol_loginmesg"] = $user->error;
747 
748  $user->trigger_mesg = $user->error;
749  }
750 
751  // Call trigger
752  $result = $user->call_trigger('USER_LOGIN_FAILED', $user);
753  if ($result < 0) $error++;
754  // End call triggers
755 
756 
757  // Hooks on failed login
758  $action = '';
759  $hookmanager->initHooks(array('login'));
760  $parameters = array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
761  $reshook = $hookmanager->executeHooks('afterLoginFailed', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks
762  if ($reshook < 0) $error++;
763 
764  $paramsurl = array();
765  if (GETPOST('textbrowser', 'int')) $paramsurl[] = 'textbrowser='.GETPOST('textbrowser', 'int');
766  if (GETPOST('nojs', 'int')) $paramsurl[] = 'nojs='.GETPOST('nojs', 'int');
767  if (GETPOST('lang', 'aZ09')) $paramsurl[] = 'lang='.GETPOST('lang', 'aZ09');
768  header('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl) ? '?'.implode('&', $paramsurl) : ''));
769  exit;
770  } else {
771  // User is loaded, we may need to change language for him according to its choice
772  if (!empty($user->conf->MAIN_LANG_DEFAULT)) {
773  $langs->setDefaultLang($user->conf->MAIN_LANG_DEFAULT);
774  }
775  }
776  } else {
777  // We are already into an authenticated session
778  $login = $_SESSION["dol_login"];
779  $entity = $_SESSION["dol_entity"];
780  dol_syslog("- This is an already logged session. _SESSION['dol_login']=".$login." _SESSION['dol_entity']=".$entity, LOG_DEBUG);
781 
782  $resultFetchUser = $user->fetch('', $login, '', 1, ($entity > 0 ? $entity : -1));
783  if ($resultFetchUser <= 0)
784  {
785  // Account has been removed after login
786  dol_syslog("Can't load user even if session logged. _SESSION['dol_login']=".$login, LOG_WARNING);
787  session_destroy();
788  session_set_cookie_params(0, '/', null, (empty($dolibarr_main_force_https) ? false : true), true); // Add tag secure and httponly on session cookie
789  session_name($sessionname);
790  session_start();
791 
792  if ($resultFetchUser == 0)
793  {
794  // Load translation files required by page
795  $langs->loadLangs(array('main', 'errors'));
796 
797  $_SESSION["dol_loginmesg"] = $langs->trans("ErrorCantLoadUserFromDolibarrDatabase", $login);
798 
799  $user->trigger_mesg = 'ErrorCantLoadUserFromDolibarrDatabase - login='.$login;
800  }
801  if ($resultFetchUser < 0)
802  {
803  $_SESSION["dol_loginmesg"] = $user->error;
804 
805  $user->trigger_mesg = $user->error;
806  }
807 
808  // Call trigger
809  $result = $user->call_trigger('USER_LOGIN_FAILED', $user);
810  if ($result < 0) $error++;
811  // End call triggers
812 
813  // Hooks on failed login
814  $action = '';
815  $hookmanager->initHooks(array('login'));
816  $parameters = array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
817  $reshook = $hookmanager->executeHooks('afterLoginFailed', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks
818  if ($reshook < 0) $error++;
819 
820  $paramsurl = array();
821  if (GETPOST('textbrowser', 'int')) $paramsurl[] = 'textbrowser='.GETPOST('textbrowser', 'int');
822  if (GETPOST('nojs', 'int')) $paramsurl[] = 'nojs='.GETPOST('nojs', 'int');
823  if (GETPOST('lang', 'aZ09')) $paramsurl[] = 'lang='.GETPOST('lang', 'aZ09');
824  header('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl) ? '?'.implode('&', $paramsurl) : ''));
825  exit;
826  } else {
827  // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
828  $hookmanager->initHooks(array('main'));
829 
830  // Code for search criteria persistence.
831  if (!empty($_GET['save_lastsearch_values'])) // We must use $_GET here
832  {
833  $relativepathstring = preg_replace('/\?.*$/', '', $_SERVER["HTTP_REFERER"]);
834  $relativepathstring = preg_replace('/^https?:\/\/[^\/]*/', '', $relativepathstring); // Get full path except host server
835  // Clean $relativepathstring
836  if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
837  $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
838  $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
839  //var_dump($relativepathstring);
840 
841  // We click on a link that leave a page we have to save search criteria, contextpage, limit and page. We save them from tmp to no tmp
842  if (!empty($_SESSION['lastsearch_values_tmp_'.$relativepathstring]))
843  {
844  $_SESSION['lastsearch_values_'.$relativepathstring] = $_SESSION['lastsearch_values_tmp_'.$relativepathstring];
845  unset($_SESSION['lastsearch_values_tmp_'.$relativepathstring]);
846  }
847  if (!empty($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]))
848  {
849  $_SESSION['lastsearch_contextpage_'.$relativepathstring] = $_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring];
850  unset($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]);
851  }
852  if (!empty($_SESSION['lastsearch_page_tmp_'.$relativepathstring]) && $_SESSION['lastsearch_page_tmp_'.$relativepathstring] > 0)
853  {
854  $_SESSION['lastsearch_page_'.$relativepathstring] = $_SESSION['lastsearch_page_tmp_'.$relativepathstring];
855  unset($_SESSION['lastsearch_page_tmp_'.$relativepathstring]);
856  }
857  if (!empty($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]) && $_SESSION['lastsearch_limit_tmp_'.$relativepathstring] != $conf->liste_limit)
858  {
859  $_SESSION['lastsearch_limit_'.$relativepathstring] = $_SESSION['lastsearch_limit_tmp_'.$relativepathstring];
860  unset($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]);
861  }
862  }
863 
864  $action = '';
865  $reshook = $hookmanager->executeHooks('updateSession', array(), $user, $action);
866  if ($reshook < 0) {
867  setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
868  }
869  }
870  }
871 
872  // Is it a new session that has started ?
873  // If we are here, this means authentication was successfull.
874  if (!isset($_SESSION["dol_login"]))
875  {
876  // New session for this login has started.
877  $error = 0;
878 
879  // Store value into session (values always stored)
880  $_SESSION["dol_login"] = $user->login;
881  $_SESSION["dol_authmode"] = isset($dol_authmode) ? $dol_authmode : '';
882  $_SESSION["dol_tz"] = isset($dol_tz) ? $dol_tz : '';
883  $_SESSION["dol_tz_string"] = isset($dol_tz_string) ? $dol_tz_string : '';
884  $_SESSION["dol_dst"] = isset($dol_dst) ? $dol_dst : '';
885  $_SESSION["dol_dst_observed"] = isset($dol_dst_observed) ? $dol_dst_observed : '';
886  $_SESSION["dol_dst_first"] = isset($dol_dst_first) ? $dol_dst_first : '';
887  $_SESSION["dol_dst_second"] = isset($dol_dst_second) ? $dol_dst_second : '';
888  $_SESSION["dol_screenwidth"] = isset($dol_screenwidth) ? $dol_screenwidth : '';
889  $_SESSION["dol_screenheight"] = isset($dol_screenheight) ? $dol_screenheight : '';
890  $_SESSION["dol_company"] = $conf->global->MAIN_INFO_SOCIETE_NOM;
891  $_SESSION["dol_entity"] = $conf->entity;
892  // Store value into session (values stored only if defined)
893  if (!empty($dol_hide_topmenu)) $_SESSION['dol_hide_topmenu'] = $dol_hide_topmenu;
894  if (!empty($dol_hide_leftmenu)) $_SESSION['dol_hide_leftmenu'] = $dol_hide_leftmenu;
895  if (!empty($dol_optimize_smallscreen)) $_SESSION['dol_optimize_smallscreen'] = $dol_optimize_smallscreen;
896  if (!empty($dol_no_mouse_hover)) $_SESSION['dol_no_mouse_hover'] = $dol_no_mouse_hover;
897  if (!empty($dol_use_jmobile)) $_SESSION['dol_use_jmobile'] = $dol_use_jmobile;
898 
899  dol_syslog("This is a new started user session. _SESSION['dol_login']=".$_SESSION["dol_login"]." Session id=".session_id());
900 
901  $db->begin();
902 
903  $user->update_last_login_date();
904 
905  $loginfo = 'TZ='.$_SESSION["dol_tz"].';TZString='.$_SESSION["dol_tz_string"].';Screen='.$_SESSION["dol_screenwidth"].'x'.$_SESSION["dol_screenheight"];
906 
907  // Call triggers for the "security events" log
908  $user->trigger_mesg = $loginfo;
909 
910  // Call trigger
911  $result = $user->call_trigger('USER_LOGIN', $user);
912  if ($result < 0) $error++;
913  // End call triggers
914 
915  // Hooks on successfull login
916  $action = '';
917  $hookmanager->initHooks(array('login'));
918  $parameters = array('dol_authmode'=>$dol_authmode, 'dol_loginfo'=>$loginfo);
919  $reshook = $hookmanager->executeHooks('afterLogin', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks
920  if ($reshook < 0) $error++;
921 
922  if ($error)
923  {
924  $db->rollback();
925  session_destroy();
926  dol_print_error($db, 'Error in some triggers USER_LOGIN or in some hooks afterLogin');
927  exit;
928  } else {
929  $db->commit();
930  }
931 
932  // Change landing page if defined.
933  $landingpage = (empty($user->conf->MAIN_LANDING_PAGE) ? (empty($conf->global->MAIN_LANDING_PAGE) ? '' : $conf->global->MAIN_LANDING_PAGE) : $user->conf->MAIN_LANDING_PAGE);
934  if (!empty($landingpage)) // Example: /index.php
935  {
936  $newpath = dol_buildpath($landingpage, 1);
937  if ($_SERVER["PHP_SELF"] != $newpath) // not already on landing page (avoid infinite loop)
938  {
939  header('Location: '.$newpath);
940  exit;
941  }
942  }
943  }
944 
945 
946  // If user admin, we force the rights-based modules
947  if ($user->admin)
948  {
949  $user->rights->user->user->lire = 1;
950  $user->rights->user->user->creer = 1;
951  $user->rights->user->user->password = 1;
952  $user->rights->user->user->supprimer = 1;
953  $user->rights->user->self->creer = 1;
954  $user->rights->user->self->password = 1;
955  }
956 
957  /*
958  * Overwrite some configs globals (try to avoid this and have code to use instead $user->conf->xxx)
959  */
960 
961  // Set liste_limit
962  if (isset($user->conf->MAIN_SIZE_LISTE_LIMIT)) $conf->liste_limit = $user->conf->MAIN_SIZE_LISTE_LIMIT; // Can be 0
963  if (isset($user->conf->PRODUIT_LIMIT_SIZE)) $conf->product->limit_size = $user->conf->PRODUIT_LIMIT_SIZE; // Can be 0
964 
965  // Replace conf->css by personalized value if theme not forced
966  if (empty($conf->global->MAIN_FORCETHEME) && !empty($user->conf->MAIN_THEME))
967  {
968  $conf->theme = $user->conf->MAIN_THEME;
969  $conf->css = "/theme/".$conf->theme."/style.css.php";
970  }
971 }
972 
973 // Case forcing style from url
974 if (GETPOST('theme', 'alpha'))
975 {
976  $conf->theme = GETPOST('theme', 'alpha', 1);
977  $conf->css = "/theme/".$conf->theme."/style.css.php";
978 }
979 
980 // Set javascript option
981 if (GETPOST('nojs', 'int')) { // If javascript was not disabled on URL
982  $conf->use_javascript_ajax = 0;
983 } else {
984  if (!empty($user->conf->MAIN_DISABLE_JAVASCRIPT)) {
985  $conf->use_javascript_ajax = !$user->conf->MAIN_DISABLE_JAVASCRIPT;
986  }
987 }
988 
989 // Set MAIN_OPTIMIZEFORTEXTBROWSER for user (must be after login part)
990 if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && !empty($user->conf->MAIN_OPTIMIZEFORTEXTBROWSER)) {
991  $conf->global->MAIN_OPTIMIZEFORTEXTBROWSER = $user->conf->MAIN_OPTIMIZEFORTEXTBROWSER;
992 }
993 
994 // set MAIN_OPTIMIZEFORCOLORBLIND for user
995 $conf->global->MAIN_OPTIMIZEFORCOLORBLIND = empty($user->conf->MAIN_OPTIMIZEFORCOLORBLIND) ? '' : $user->conf->MAIN_OPTIMIZEFORCOLORBLIND;
996 
997 // Set terminal output option according to conf->browser.
998 if (GETPOST('dol_hide_leftmenu', 'int') || !empty($_SESSION['dol_hide_leftmenu'])) $conf->dol_hide_leftmenu = 1;
999 if (GETPOST('dol_hide_topmenu', 'int') || !empty($_SESSION['dol_hide_topmenu'])) $conf->dol_hide_topmenu = 1;
1000 if (GETPOST('dol_optimize_smallscreen', 'int') || !empty($_SESSION['dol_optimize_smallscreen'])) $conf->dol_optimize_smallscreen = 1;
1001 if (GETPOST('dol_no_mouse_hover', 'int') || !empty($_SESSION['dol_no_mouse_hover'])) $conf->dol_no_mouse_hover = 1;
1002 if (GETPOST('dol_use_jmobile', 'int') || !empty($_SESSION['dol_use_jmobile'])) $conf->dol_use_jmobile = 1;
1003 if (!empty($conf->browser->layout) && $conf->browser->layout != 'classic') $conf->dol_no_mouse_hover = 1;
1004 if ((!empty($conf->browser->layout) && $conf->browser->layout == 'phone')
1005  || (!empty($_SESSION['dol_screenwidth']) && $_SESSION['dol_screenwidth'] < 400)
1006  || (!empty($_SESSION['dol_screenheight']) && $_SESSION['dol_screenheight'] < 400)
1007 )
1008 {
1009  $conf->dol_optimize_smallscreen = 1;
1010 }
1011 // If we force to use jmobile, then we reenable javascript
1012 if (!empty($conf->dol_use_jmobile)) $conf->use_javascript_ajax = 1;
1013 // Replace themes bugged with jmobile with eldy
1014 if (!empty($conf->dol_use_jmobile) && in_array($conf->theme, array('bureau2crea', 'cameleo', 'amarok')))
1015 {
1016  $conf->theme = 'eldy';
1017  $conf->css = "/theme/".$conf->theme."/style.css.php";
1018 }
1019 
1020 if (!defined('NOREQUIRETRAN'))
1021 {
1022  if (!GETPOST('lang', 'aZ09')) // If language was not forced on URL
1023  {
1024  // If user has chosen its own language
1025  if (!empty($user->conf->MAIN_LANG_DEFAULT))
1026  {
1027  // If different than current language
1028  //print ">>>".$langs->getDefaultLang()."-".$user->conf->MAIN_LANG_DEFAULT;
1029  if ($langs->getDefaultLang() != $user->conf->MAIN_LANG_DEFAULT)
1030  {
1031  $langs->setDefaultLang($user->conf->MAIN_LANG_DEFAULT);
1032  }
1033  }
1034  }
1035 }
1036 
1037 if (!defined('NOLOGIN'))
1038 {
1039  // If the login is not recovered, it is identified with an account that does not exist.
1040  // Hacking attempt?
1041  if (!$user->login) accessforbidden();
1042 
1043  // Check if user is active
1044  if ($user->statut < 1)
1045  {
1046  // If not active, we refuse the user
1047  $langs->load("other");
1048  dol_syslog("Authentication KO as login is disabled", LOG_NOTICE);
1049  accessforbidden($langs->trans("ErrorLoginDisabled"));
1050  exit;
1051  }
1052 
1053  // Load permissions
1054  $user->getrights();
1055 }
1056 
1057 dol_syslog("--- Access to ".(empty($_SERVER["REQUEST_METHOD"])?'':$_SERVER["REQUEST_METHOD"].' ').$_SERVER["PHP_SELF"].' - action='.GETPOST('action', 'aZ09').', massaction='.GETPOST('massaction', 'aZ09').' NOTOKENRENEWAL='.(defined('NOTOKENRENEWAL') ?constant('NOTOKENRENEWAL') : ''));
1058 //Another call for easy debugg
1059 //dol_syslog("Access to ".$_SERVER["PHP_SELF"].' GET='.join(',',array_keys($_GET)).'->'.join(',',$_GET).' POST:'.join(',',array_keys($_POST)).'->'.join(',',$_POST));
1060 
1061 // Load main languages files
1062 if (!defined('NOREQUIRETRAN'))
1063 {
1064  // Load translation files required by page
1065  $langs->loadLangs(array('main', 'dict'));
1066 }
1067 
1068 // Define some constants used for style of arrays
1069 $bc = array(0=>'class="impair"', 1=>'class="pair"');
1070 $bcdd = array(0=>'class="drag drop oddeven"', 1=>'class="drag drop oddeven"');
1071 $bcnd = array(0=>'class="nodrag nodrop nohover"', 1=>'class="nodrag nodrop nohoverpair"'); // Used for tr to add new lines
1072 $bctag = array(0=>'class="impair tagtr"', 1=>'class="pair tagtr"');
1073 
1074 // Define messages variables
1075 $mesg = ''; $warning = ''; $error = 0;
1076 // deprecated, see setEventMessages() and dol_htmloutput_events()
1077 $mesgs = array(); $warnings = array(); $errors = array();
1078 
1079 // Constants used to defined number of lines in textarea
1080 if (empty($conf->browser->firefox))
1081 {
1082  define('ROWS_1', 1);
1083  define('ROWS_2', 2);
1084  define('ROWS_3', 3);
1085  define('ROWS_4', 4);
1086  define('ROWS_5', 5);
1087  define('ROWS_6', 6);
1088  define('ROWS_7', 7);
1089  define('ROWS_8', 8);
1090  define('ROWS_9', 9);
1091 } else {
1092  define('ROWS_1', 0);
1093  define('ROWS_2', 1);
1094  define('ROWS_3', 2);
1095  define('ROWS_4', 3);
1096  define('ROWS_5', 4);
1097  define('ROWS_6', 5);
1098  define('ROWS_7', 6);
1099  define('ROWS_8', 7);
1100  define('ROWS_9', 8);
1101 }
1102 
1103 $heightforframes = 50;
1104 
1105 // Init menu manager
1106 if (!defined('NOREQUIREMENU'))
1107 {
1108  if (empty($user->socid)) // If internal user or not defined
1109  {
1110  $conf->standard_menu = (empty($conf->global->MAIN_MENU_STANDARD_FORCED) ? (empty($conf->global->MAIN_MENU_STANDARD) ? 'eldy_menu.php' : $conf->global->MAIN_MENU_STANDARD) : $conf->global->MAIN_MENU_STANDARD_FORCED);
1111  } else {
1112  // If external user
1113  $conf->standard_menu = (empty($conf->global->MAIN_MENUFRONT_STANDARD_FORCED) ? (empty($conf->global->MAIN_MENUFRONT_STANDARD) ? 'eldy_menu.php' : $conf->global->MAIN_MENUFRONT_STANDARD) : $conf->global->MAIN_MENUFRONT_STANDARD_FORCED);
1114  }
1115 
1116  // Load the menu manager (only if not already done)
1117  $file_menu = $conf->standard_menu;
1118  if (GETPOST('menu', 'alpha')) $file_menu = GETPOST('menu', 'alpha'); // example: menu=eldy_menu.php
1119  if (!class_exists('MenuManager'))
1120  {
1121  $menufound = 0;
1122  $dirmenus = array_merge(array("/core/menus/"), (array) $conf->modules_parts['menus']);
1123  foreach ($dirmenus as $dirmenu)
1124  {
1125  $menufound = dol_include_once($dirmenu."standard/".$file_menu);
1126  if (class_exists('MenuManager')) break;
1127  }
1128  if (!class_exists('MenuManager')) // If failed to include, we try with standard eldy_menu.php
1129  {
1130  dol_syslog("You define a menu manager '".$file_menu."' that can not be loaded.", LOG_WARNING);
1131  $file_menu = 'eldy_menu.php';
1132  include_once DOL_DOCUMENT_ROOT."/core/menus/standard/".$file_menu;
1133  }
1134  }
1135  $menumanager = new MenuManager($db, empty($user->socid) ? 0 : 1);
1136  $menumanager->loadMenu();
1137 }
1138 
1139 
1140 
1141 // Functions
1142 
1143 if (!function_exists("llxHeader"))
1144 {
1164  function llxHeader($head = '', $title = '', $help_url = '', $target = '', $disablejs = 0, $disablehead = 0, $arrayofjs = '', $arrayofcss = '', $morequerystring = '', $morecssonbody = '', $replacemainareaby = '', $disablenofollow = 0)
1165  {
1166  global $conf;
1167 
1168  // html header
1169  top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss, 0, $disablenofollow);
1170 
1171  $tmpcsstouse = 'sidebar-collapse'.($morecssonbody ? ' '.$morecssonbody : '');
1172  // If theme MD and classic layer, we open the menulayer by default.
1173  if ($conf->theme == 'md' && !in_array($conf->browser->layout, array('phone', 'tablet')) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1174  {
1175  global $mainmenu;
1176  if ($mainmenu != 'website') $tmpcsstouse = $morecssonbody; // We do not use sidebar-collpase by default to have menuhider open by default.
1177  }
1178 
1179  if (!empty($conf->global->MAIN_OPTIMIZEFORCOLORBLIND)) {
1180  $tmpcsstouse .= ' colorblind-'.strip_tags($conf->global->MAIN_OPTIMIZEFORCOLORBLIND);
1181  }
1182 
1183  print '<body id="mainbody" class="'.$tmpcsstouse.'">'."\n";
1184 
1185  // top menu and left menu area
1186  if (empty($conf->dol_hide_topmenu) || GETPOST('dol_invisible_topmenu', 'int'))
1187  {
1188  top_menu($head, $title, $target, $disablejs, $disablehead, $arrayofjs, $arrayofcss, $morequerystring, $help_url);
1189  }
1190 
1191  if (empty($conf->dol_hide_leftmenu))
1192  {
1193  left_menu('', $help_url, '', '', 1, $title, 1); // $menumanager is retrieved with a global $menumanager inside this function
1194  }
1195 
1196  // main area
1197  if ($replacemainareaby)
1198  {
1199  print $replacemainareaby;
1200  return;
1201  }
1202  main_area($title);
1203  }
1204 }
1205 
1206 
1214 function top_httphead($contenttype = 'text/html', $forcenocache = 0)
1215 {
1216  global $db, $conf, $hookmanager;
1217 
1218  if ($contenttype == 'text/html') header("Content-Type: text/html; charset=".$conf->file->character_set_client);
1219  else header("Content-Type: ".$contenttype);
1220 
1221  // Security options
1222  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)
1223  if (!defined('XFRAMEOPTIONS_ALLOWALL')) header("X-Frame-Options: SAMEORIGIN"); // Frames allowed only if on same domain (stop some XSS attacks)
1224  else header("X-Frame-Options: ALLOWALL");
1225  //header("X-XSS-Protection: 1"); // XSS filtering protection of some browsers (note: use of Content-Security-Policy is more efficient). Disabled as deprecated.
1226  if (!defined('FORCECSP'))
1227  {
1228  //if (! isset($conf->global->MAIN_HTTP_CONTENT_SECURITY_POLICY))
1229  //{
1230  // // A default security policy that keep usage of js external component like ckeditor, stripe, google, working
1231  // $contentsecuritypolicy = "font-src *; img-src *; style-src * 'unsafe-inline' 'unsafe-eval'; default-src 'self' *.stripe.com 'unsafe-inline' 'unsafe-eval'; script-src 'self' *.stripe.com 'unsafe-inline' 'unsafe-eval'; frame-src 'self' *.stripe.com; connect-src 'self';";
1232  //}
1233  //else
1234  $contentsecuritypolicy = empty($conf->global->MAIN_HTTP_CONTENT_SECURITY_POLICY) ? '' : $conf->global->MAIN_HTTP_CONTENT_SECURITY_POLICY;
1235 
1236  if (!is_object($hookmanager)) $hookmanager = new HookManager($db);
1237  $hookmanager->initHooks(array("main"));
1238 
1239  $parameters = array('contentsecuritypolicy'=>$contentsecuritypolicy);
1240  $result = $hookmanager->executeHooks('setContentSecurityPolicy', $parameters); // Note that $action and $object may have been modified by some hooks
1241  if ($result > 0) $contentsecuritypolicy = $hookmanager->resPrint; // Replace CSP
1242  else $contentsecuritypolicy .= $hookmanager->resPrint; // Concat CSP
1243 
1244  if (!empty($contentsecuritypolicy))
1245  {
1246  // For example, to restrict 'script', 'object', 'frames' or 'img' to some domains:
1247  // script-src https://api.google.com https://anotherhost.com; object-src https://youtube.com; frame-src https://youtube.com; img-src: https://static.example.com
1248  // For example, to restrict everything to one domain, except 'object', ...:
1249  // default-src https://cdn.example.net; object-src 'none'
1250  // For example, to restrict everything to itself except img that can be on other servers:
1251  // default-src 'self'; img-src *;
1252  // Pre-existing site that uses too much inline code to fix but wants to ensure resources are loaded only over https and disable plugins:
1253  // default-src http: https: 'unsafe-eval' 'unsafe-inline'; object-src 'none'
1254  header("Content-Security-Policy: ".$contentsecuritypolicy);
1255  }
1256  } elseif (constant('FORCECSP'))
1257  {
1258  header("Content-Security-Policy: ".constant('FORCECSP'));
1259  }
1260  if ($forcenocache)
1261  {
1262  header("Cache-Control: no-cache, no-store, must-revalidate, max-age=0");
1263  }
1264 }
1265 
1280 function top_htmlhead($head, $title = '', $disablejs = 0, $disablehead = 0, $arrayofjs = '', $arrayofcss = '', $disablejmobile = 0, $disablenofollow = 0)
1281 {
1282  global $db, $conf, $langs, $user, $mysoc, $hookmanager;
1283 
1284  top_httphead();
1285 
1286  if (empty($conf->css)) $conf->css = '/theme/eldy/style.css.php'; // If not defined, eldy by default
1287 
1288  print '<!doctype html>'."\n";
1289 
1290  if (!empty($conf->global->MAIN_USE_CACHE_MANIFEST)) print '<html lang="'.substr($langs->defaultlang, 0, 2).'" manifest="'.DOL_URL_ROOT.'/cache.manifest">'."\n";
1291  else print '<html lang="'.substr($langs->defaultlang, 0, 2).'">'."\n";
1292  //print '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr">'."\n";
1293  if (empty($disablehead))
1294  {
1295  if (!is_object($hookmanager)) $hookmanager = new HookManager($db);
1296  $hookmanager->initHooks(array("main"));
1297 
1298  $ext = 'layout='.$conf->browser->layout.'&amp;version='.urlencode(DOL_VERSION);
1299 
1300  print "<head>\n";
1301 
1302  if (GETPOST('dol_basehref', 'alpha')) print '<base href="'.dol_escape_htmltag(GETPOST('dol_basehref', 'alpha')).'">'."\n";
1303 
1304  // Displays meta
1305  print '<meta charset="utf-8">'."\n";
1306  print '<meta name="robots" content="noindex'.($disablenofollow ? '' : ',nofollow').'">'."\n"; // Do not index
1307  print '<meta name="viewport" content="width=device-width, initial-scale=1.0">'."\n"; // Scale for mobile device
1308  print '<meta name="author" content="Dolibarr Development Team">'."\n";
1309 
1310  // Favicon
1311  $favicon = DOL_URL_ROOT.'/theme/dolibarr_256x256_color.png';
1312  if (!empty($mysoc->logo_squarred_mini)) $favicon = DOL_URL_ROOT.'/viewimage.php?cache=1&modulepart=mycompany&file='.urlencode('logos/thumbs/'.$mysoc->logo_squarred_mini);
1313  if (!empty($conf->global->MAIN_FAVICON_URL)) $favicon = $conf->global->MAIN_FAVICON_URL;
1314  if (empty($conf->dol_use_jmobile)) print '<link rel="shortcut icon" type="image/x-icon" href="'.$favicon.'"/>'."\n"; // Not required into an Android webview
1315 
1316  //if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) print '<link rel="top" title="'.$langs->trans("Home").'" href="'.(DOL_URL_ROOT?DOL_URL_ROOT:'/').'">'."\n";
1317  //if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) print '<link rel="copyright" title="GNU General Public License" href="https://www.gnu.org/copyleft/gpl.html#SEC1">'."\n";
1318  //if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) print '<link rel="author" title="Dolibarr Development Team" href="https://www.dolibarr.org">'."\n";
1319 
1320  // Mobile appli like icon
1321  $manifest = DOL_URL_ROOT.'/theme/'.$conf->theme.'/manifest.json.php';
1322  if (!empty($manifest)) {
1323  print '<link rel="manifest" href="'.$manifest.'" />'."\n";
1324  }
1325 
1326  if (!empty($conf->global->THEME_ELDY_TOPMENU_BACK1)) {
1327  // TODO: use auto theme color switch
1328  print '<meta name="theme-color" content="rgb('.$conf->global->THEME_ELDY_TOPMENU_BACK1.')">'."\n";
1329  }
1330 
1331  // Auto refresh page
1332  if (GETPOST('autorefresh', 'int') > 0) print '<meta http-equiv="refresh" content="'.GETPOST('autorefresh', 'int').'">';
1333 
1334  // Displays title
1335  $appli = constant('DOL_APPLICATION_TITLE');
1336  if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $appli = $conf->global->MAIN_APPLICATION_TITLE;
1337 
1338  print '<title>';
1339  $titletoshow = '';
1340  if ($title && !empty($conf->global->MAIN_HTML_TITLE) && preg_match('/noapp/', $conf->global->MAIN_HTML_TITLE)) $titletoshow = dol_htmlentities($title);
1341  elseif ($title) $titletoshow = dol_htmlentities($appli.' - '.$title);
1342  else $titletoshow = dol_htmlentities($appli);
1343 
1344  $parameters = array('title'=>$titletoshow);
1345  $result = $hookmanager->executeHooks('setHtmlTitle', $parameters); // Note that $action and $object may have been modified by some hooks
1346  if ($result > 0) $titletoshow = $hookmanager->resPrint; // Replace Title to show
1347  else $titletoshow .= $hookmanager->resPrint; // Concat to Title to show
1348 
1349  print $titletoshow;
1350  print '</title>';
1351 
1352  print "\n";
1353 
1354  if (GETPOST('version', 'int')) $ext = 'version='.GETPOST('version', 'int'); // usefull to force no cache on css/js
1355 
1356  $themeparam = '?lang='.$langs->defaultlang.'&amp;theme='.$conf->theme.(GETPOST('optioncss', 'aZ09') ? '&amp;optioncss='.GETPOST('optioncss', 'aZ09', 1) : '').'&amp;userid='.$user->id.'&amp;entity='.$conf->entity;
1357  $themeparam .= ($ext ? '&amp;'.$ext : '').'&amp;revision='.$conf->global->MAIN_IHM_PARAMS_REV;
1358  if (!empty($_SESSION['dol_resetcache'])) $themeparam .= '&amp;dol_resetcache='.$_SESSION['dol_resetcache'];
1359  if (GETPOSTISSET('dol_hide_topmenu')) { $themeparam .= '&amp;dol_hide_topmenu='.GETPOST('dol_hide_topmenu', 'int'); }
1360  if (GETPOSTISSET('dol_hide_leftmenu')) { $themeparam .= '&amp;dol_hide_leftmenu='.GETPOST('dol_hide_leftmenu', 'int'); }
1361  if (GETPOSTISSET('dol_optimize_smallscreen')) { $themeparam .= '&amp;dol_optimize_smallscreen='.GETPOST('dol_optimize_smallscreen', 'int'); }
1362  if (GETPOSTISSET('dol_no_mouse_hover')) { $themeparam .= '&amp;dol_no_mouse_hover='.GETPOST('dol_no_mouse_hover', 'int'); }
1363  if (GETPOSTISSET('dol_use_jmobile')) { $themeparam .= '&amp;dol_use_jmobile='.GETPOST('dol_use_jmobile', 'int'); $conf->dol_use_jmobile = GETPOST('dol_use_jmobile', 'int'); }
1364  if (GETPOSTISSET('THEME_DARKMODEENABLED')) { $themeparam .= '&amp;THEME_DARKMODEENABLED='.GETPOST('THEME_DARKMODEENABLED', 'int'); }
1365  if (GETPOSTISSET('THEME_SATURATE_RATIO')) { $themeparam .= '&amp;THEME_SATURATE_RATIO='.GETPOST('THEME_SATURATE_RATIO', 'int'); }
1366 
1367  if (!empty($conf->global->MAIN_ENABLE_FONT_ROBOTO)) {
1368  print '<link rel="preconnect" href="https://fonts.gstatic.com">'."\n";
1369  print '<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@200;300;400;500;600&display=swap" rel="stylesheet">'."\n";
1370  }
1371 
1372  if (!defined('DISABLE_JQUERY') && !$disablejs && $conf->use_javascript_ajax)
1373  {
1374  print '<!-- Includes CSS for JQuery (Ajax library) -->'."\n";
1375  $jquerytheme = 'base';
1376  if (!empty($conf->global->MAIN_USE_JQUERY_THEME)) $jquerytheme = $conf->global->MAIN_USE_JQUERY_THEME;
1377  if (constant('JS_JQUERY_UI')) print '<link rel="stylesheet" type="text/css" href="'.JS_JQUERY_UI.'css/'.$jquerytheme.'/jquery-ui.min.css'.($ext ? '?'.$ext : '').'">'."\n"; // Forced JQuery
1378  else print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/css/'.$jquerytheme.'/jquery-ui.css'.($ext ? '?'.$ext : '').'">'."\n"; // JQuery
1379  if (!defined('DISABLE_JQUERY_JNOTIFY')) print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify-alt.min.css'.($ext ? '?'.$ext : '').'">'."\n"; // JNotify
1380  if (!defined('DISABLE_SELECT2') && (!empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT'))) // jQuery plugin "mutiselect", "multiple-select", "select2"...
1381  {
1382  $tmpplugin = empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) ?constant('REQUIRE_JQUERY_MULTISELECT') : $conf->global->MAIN_USE_JQUERY_MULTISELECT;
1383  print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/'.$tmpplugin.'/dist/css/'.$tmpplugin.'.css'.($ext ? '?'.$ext : '').'">'."\n";
1384  }
1385  }
1386 
1387  if (!defined('DISABLE_FONT_AWSOME'))
1388  {
1389  print '<!-- Includes CSS for font awesome -->'."\n";
1390  print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/theme/common/fontawesome-5/css/all.min.css'.($ext ? '?'.$ext : '').'">'."\n";
1391  print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/theme/common/fontawesome-5/css/v4-shims.min.css'.($ext ? '?'.$ext : '').'">'."\n";
1392  }
1393 
1394  print '<!-- Includes CSS for Dolibarr theme -->'."\n";
1395  // Output style sheets (optioncss='print' or ''). Note: $conf->css looks like '/theme/eldy/style.css.php'
1396  $themepath = dol_buildpath($conf->css, 1);
1397  $themesubdir = '';
1398  if (!empty($conf->modules_parts['theme'])) // This slow down
1399  {
1400  foreach ($conf->modules_parts['theme'] as $reldir)
1401  {
1402  if (file_exists(dol_buildpath($reldir.$conf->css, 0)))
1403  {
1404  $themepath = dol_buildpath($reldir.$conf->css, 1);
1405  $themesubdir = $reldir;
1406  break;
1407  }
1408  }
1409  }
1410 
1411  //print 'themepath='.$themepath.' themeparam='.$themeparam;exit;
1412  print '<link rel="stylesheet" type="text/css" href="'.$themepath.$themeparam.'">'."\n";
1413  if (!empty($conf->global->MAIN_FIX_FLASH_ON_CHROME)) 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";
1414 
1415  // CSS forced by modules (relative url starting with /)
1416  if (!empty($conf->modules_parts['css']))
1417  {
1418  $arraycss = (array) $conf->modules_parts['css'];
1419  foreach ($arraycss as $modcss => $filescss)
1420  {
1421  $filescss = (array) $filescss; // To be sure filecss is an array
1422  foreach ($filescss as $cssfile)
1423  {
1424  if (empty($cssfile)) dol_syslog("Warning: module ".$modcss." declared a css path file into its descriptor that is empty.", LOG_WARNING);
1425  // cssfile is a relative path
1426  print '<!-- Includes CSS added by module '.$modcss.' -->'."\n".'<link rel="stylesheet" type="text/css" href="'.dol_buildpath($cssfile, 1);
1427  // 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.
1428  if (!preg_match('/\.css$/i', $cssfile)) print $themeparam;
1429  print '">'."\n";
1430  }
1431  }
1432  }
1433  // CSS forced by page in top_htmlhead call (relative url starting with /)
1434  if (is_array($arrayofcss))
1435  {
1436  foreach ($arrayofcss as $cssfile)
1437  {
1438  if (preg_match('/^(http|\/\/)/i', $cssfile))
1439  {
1440  $urltofile = $cssfile;
1441  } else {
1442  $urltofile = dol_buildpath($cssfile, 1);
1443  }
1444  print '<!-- Includes CSS added by page -->'."\n".'<link rel="stylesheet" type="text/css" title="default" href="'.$urltofile;
1445  // 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.
1446  if (!preg_match('/\.css$/i', $cssfile)) print $themeparam;
1447  print '">'."\n";
1448  }
1449  }
1450 
1451  // Output standard javascript links
1452  if (!defined('DISABLE_JQUERY') && !$disablejs && !empty($conf->use_javascript_ajax))
1453  {
1454  // JQuery. Must be before other includes
1455  print '<!-- Includes JS for JQuery -->'."\n";
1456  if (defined('JS_JQUERY') && constant('JS_JQUERY')) print '<script src="'.JS_JQUERY.'jquery.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1457  else print '<script src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1458  /*if (! empty($conf->global->MAIN_FEATURES_LEVEL) && ! defined('JS_JQUERY_MIGRATE_DISABLED'))
1459  {
1460  if (defined('JS_JQUERY_MIGRATE') && constant('JS_JQUERY_MIGRATE')) print '<script src="'.JS_JQUERY_MIGRATE.'jquery-migrate.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1461  else print '<script src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery-migrate.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1462  }*/
1463  if (defined('JS_JQUERY_UI') && constant('JS_JQUERY_UI')) print '<script src="'.JS_JQUERY_UI.'jquery-ui.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1464  else print '<script src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery-ui.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1465  if (!defined('DISABLE_JQUERY_TABLEDND')) print '<script src="'.DOL_URL_ROOT.'/includes/jquery/plugins/tablednd/jquery.tablednd.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1466  // jQuery jnotify
1467  if (empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && !defined('DISABLE_JQUERY_JNOTIFY')) {
1468  print '<script src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1469  }
1470  // Chart
1471  if (empty($conf->global->MAIN_JS_GRAPH) || $conf->global->MAIN_JS_GRAPH == 'chart') {
1472  print '<script src="'.DOL_URL_ROOT.'/includes/nnnick/chartjs/dist/Chart.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1473  }
1474 
1475  // jQuery jeditable for Edit In Place features
1476  if (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && !defined('DISABLE_JQUERY_JEDITABLE')) {
1477  print '<!-- JS to manage editInPlace feature -->'."\n";
1478  print '<script src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1479  print '<script src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ui-datepicker.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1480  print '<script src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ui-autocomplete.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1481  print '<script>'."\n";
1482  print 'var urlSaveInPlace = \''.DOL_URL_ROOT.'/core/ajax/saveinplace.php\';'."\n";
1483  print 'var urlLoadInPlace = \''.DOL_URL_ROOT.'/core/ajax/loadinplace.php\';'."\n";
1484  print 'var tooltipInPlace = \''.$langs->transnoentities('ClickToEdit').'\';'."\n"; // Added in title attribute of span
1485  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 ?
1486  print 'var cancelInPlace = \''.$langs->trans("Cancel").'\';'."\n";
1487  print 'var submitInPlace = \''.$langs->trans('Ok').'\';'."\n";
1488  print 'var indicatorInPlace = \'<img src="'.DOL_URL_ROOT."/theme/".$conf->theme."/img/working.gif".'">\';'."\n";
1489  print 'var withInPlace = 300;'; // width in pixel for default string edit
1490  print '</script>'."\n";
1491  print '<script src="'.DOL_URL_ROOT.'/core/js/editinplace.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1492  print '<script src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ckeditor.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1493  }
1494  // jQuery Timepicker
1495  if (!empty($conf->global->MAIN_USE_JQUERY_TIMEPICKER) || defined('REQUIRE_JQUERY_TIMEPICKER')) {
1496  print '<script src="'.DOL_URL_ROOT.'/includes/jquery/plugins/timepicker/jquery-ui-timepicker-addon.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1497  print '<script src="'.DOL_URL_ROOT.'/core/js/timepicker.js.php?lang='.$langs->defaultlang.($ext ? '&amp;'.$ext : '').'"></script>'."\n";
1498  }
1499  if (!defined('DISABLE_SELECT2') && (!empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT'))) {
1500  // jQuery plugin "mutiselect", "multiple-select", "select2", ...
1501  $tmpplugin = empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) ?constant('REQUIRE_JQUERY_MULTISELECT') : $conf->global->MAIN_USE_JQUERY_MULTISELECT;
1502  print '<script src="'.DOL_URL_ROOT.'/includes/jquery/plugins/'.$tmpplugin.'/dist/js/'.$tmpplugin.'.full.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n"; // We include full because we need the support of containerCssClass
1503  }
1504  if (!defined('DISABLE_MULTISELECT')) // jQuery plugin "mutiselect" to select with checkboxes. Can be removed once we have an enhanced search tool
1505  {
1506  print '<script src="'.DOL_URL_ROOT.'/includes/jquery/plugins/multiselect/jquery.multi-select.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1507  }
1508  }
1509 
1510  if (!$disablejs && !empty($conf->use_javascript_ajax)) {
1511  // CKEditor
1512  if ((!empty($conf->fckeditor->enabled) && (empty($conf->global->FCKEDITOR_EDITORNAME) || $conf->global->FCKEDITOR_EDITORNAME == 'ckeditor') && !defined('DISABLE_CKEDITOR')) || defined('FORCE_CKEDITOR'))
1513  {
1514  print '<!-- Includes JS for CKEditor -->'."\n";
1515  $pathckeditor = DOL_URL_ROOT.'/includes/ckeditor/ckeditor/';
1516  $jsckeditor = 'ckeditor.js';
1517  if (constant('JS_CKEDITOR')) {
1518  // To use external ckeditor 4 js lib
1519  $pathckeditor = constant('JS_CKEDITOR');
1520  }
1521  print '<script>';
1522  print '/* enable ckeditor by main.inc.php */';
1523  print 'var CKEDITOR_BASEPATH = \''.$pathckeditor.'\';'."\n";
1524  print 'var ckeditorConfig = \''.dol_buildpath($themesubdir.'/theme/'.$conf->theme.'/ckeditor/config.js'.($ext ? '?'.$ext : ''), 1).'\';'."\n"; // $themesubdir='' in standard usage
1525  print 'var ckeditorFilebrowserBrowseUrl = \''.DOL_URL_ROOT.'/core/filemanagerdol/browser/default/browser.php?Connector='.DOL_URL_ROOT.'/core/filemanagerdol/connectors/php/connector.php\';'."\n";
1526  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";
1527  print '</script>'."\n";
1528  print '<script src="'.$pathckeditor.$jsckeditor.($ext ? '?'.$ext : '').'"></script>'."\n";
1529  print '<script>';
1530  if (GETPOST('mode', 'aZ09') == 'Full_inline') {
1531  print 'CKEDITOR.disableAutoInline = false;'."\n";
1532  } else {
1533  print 'CKEDITOR.disableAutoInline = true;'."\n";
1534  }
1535  print '</script>'."\n";
1536  }
1537 
1538  // 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).
1539  if (!defined('NOBROWSERNOTIF') && !defined('NOREQUIREMENU') && !defined('NOLOGIN'))
1540  {
1541  $enablebrowsernotif = false;
1542  if (!empty($conf->agenda->enabled) && !empty($conf->global->AGENDA_REMINDER_BROWSER)) $enablebrowsernotif = true;
1543  if ($conf->browser->layout == 'phone') $enablebrowsernotif = false;
1544  if ($enablebrowsernotif)
1545  {
1546  print '<!-- Includes JS of Dolibarr (browser layout = '.$conf->browser->layout.')-->'."\n";
1547  print '<script src="'.DOL_URL_ROOT.'/core/js/lib_notification.js.php'.($ext ? '?'.$ext : '').'"></script>'."\n";
1548  }
1549  }
1550 
1551  // Global js function
1552  print '<!-- Includes JS of Dolibarr -->'."\n";
1553  print '<script src="'.DOL_URL_ROOT.'/core/js/lib_head.js.php?lang='.$langs->defaultlang.($ext ? '&'.$ext : '').'"></script>'."\n";
1554 
1555  // JS forced by modules (relative url starting with /)
1556  if (!empty($conf->modules_parts['js'])) // $conf->modules_parts['js'] is array('module'=>array('file1','file2'))
1557  {
1558  $arrayjs = (array) $conf->modules_parts['js'];
1559  foreach ($arrayjs as $modjs => $filesjs)
1560  {
1561  $filesjs = (array) $filesjs; // To be sure filejs is an array
1562  foreach ($filesjs as $jsfile)
1563  {
1564  // jsfile is a relative path
1565  print '<!-- Include JS added by module '.$modjs.'-->'."\n".'<script src="'.dol_buildpath($jsfile, 1).'"></script>'."\n";
1566  }
1567  }
1568  }
1569  // JS forced by page in top_htmlhead (relative url starting with /)
1570  if (is_array($arrayofjs))
1571  {
1572  print '<!-- Includes JS added by page -->'."\n";
1573  foreach ($arrayofjs as $jsfile)
1574  {
1575  if (preg_match('/^(http|\/\/)/i', $jsfile))
1576  {
1577  print '<script src="'.$jsfile.'"></script>'."\n";
1578  } else {
1579  print '<script src="'.dol_buildpath($jsfile, 1).'"></script>'."\n";
1580  }
1581  }
1582  }
1583  }
1584 
1585  if (!empty($head)) print $head."\n";
1586  if (!empty($conf->global->MAIN_HTML_HEADER)) print $conf->global->MAIN_HTML_HEADER."\n";
1587 
1588  $parameters = array();
1589  $result = $hookmanager->executeHooks('addHtmlHeader', $parameters); // Note that $action and $object may have been modified by some hooks
1590  print $hookmanager->resPrint; // Replace Title to show
1591 
1592  print "</head>\n\n";
1593  }
1594 
1595  $conf->headerdone = 1; // To tell header was output
1596 }
1597 
1598 
1615 function top_menu($head, $title = '', $target = '', $disablejs = 0, $disablehead = 0, $arrayofjs = '', $arrayofcss = '', $morequerystring = '', $helppagename = '')
1616 {
1617  global $user, $conf, $langs, $db;
1618  global $dolibarr_main_authentication, $dolibarr_main_demo;
1619  global $hookmanager, $menumanager;
1620 
1621  $searchform = '';
1622  $bookmarks = '';
1623 
1624  // Instantiate hooks for external modules
1625  $hookmanager->initHooks(array('toprightmenu'));
1626 
1627  $toprightmenu = '';
1628 
1629  // For backward compatibility with old modules
1630  if (empty($conf->headerdone))
1631  {
1632  $disablenofollow = 0;
1633  top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss, 0, $disablenofollow);
1634  print '<body id="mainbody">';
1635  }
1636 
1637  /*
1638  * Top menu
1639  */
1640  if ((empty($conf->dol_hide_topmenu) || GETPOST('dol_invisible_topmenu', 'int')) && (!defined('NOREQUIREMENU') || !constant('NOREQUIREMENU')))
1641  {
1642  if (!isset($form) || !is_object($form)) {
1643  include_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
1644  $form = new Form($db);
1645  }
1646 
1647  print "\n".'<!-- Start top horizontal -->'."\n";
1648 
1649  print '<div class="side-nav-vert'.(GETPOST('dol_invisible_topmenu', 'int') ? ' hidden' : '').'"><div id="id-top">'; // dol_invisible_topmenu differs from dol_hide_topmenu: dol_invisible_topmenu means we output menu but we make it invisible.
1650 
1651  // Show menu entries
1652  print '<div id="tmenu_tooltip'.(empty($conf->global->MAIN_MENU_INVERT) ? '' : 'invert').'" class="tmenu">'."\n";
1653  $menumanager->atarget = $target;
1654  $menumanager->showmenu('top', array('searchform'=>$searchform, 'bookmarks'=>$bookmarks)); // This contains a \n
1655  print "</div>\n";
1656 
1657  // Define link to login card
1658  $appli = constant('DOL_APPLICATION_TITLE');
1659  if (!empty($conf->global->MAIN_APPLICATION_TITLE))
1660  {
1661  $appli = $conf->global->MAIN_APPLICATION_TITLE;
1662  if (preg_match('/\d\.\d/', $appli))
1663  {
1664  if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core
1665  } else $appli .= " ".DOL_VERSION;
1666  } else $appli .= " ".DOL_VERSION;
1667 
1668  if (!empty($conf->global->MAIN_FEATURES_LEVEL)) $appli .= "<br>".$langs->trans("LevelOfFeature").': '.$conf->global->MAIN_FEATURES_LEVEL;
1669 
1670  $logouttext = '';
1671  $logouthtmltext = '';
1672  if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1673  {
1674  //$logouthtmltext=$appli.'<br>';
1675  if ($_SESSION["dol_authmode"] != 'forceuser' && $_SESSION["dol_authmode"] != 'http')
1676  {
1677  $logouthtmltext .= $langs->trans("Logout").'<br>';
1678 
1679  $logouttext .= '<a accesskey="l" href="'.DOL_URL_ROOT.'/user/logout.php">';
1680  $logouttext .= img_picto($langs->trans('Logout'), 'sign-out', '', false, 0, 0, '', 'atoplogin');
1681  $logouttext .= '</a>';
1682  } else {
1683  $logouthtmltext .= $langs->trans("NoLogoutProcessWithAuthMode", $_SESSION["dol_authmode"]);
1684  $logouttext .= img_picto($langs->trans('Logout'), 'sign-out', '', false, 0, 0, '', 'atoplogin opacitymedium');
1685  }
1686  }
1687 
1688  print '<div class="login_block usedropdown">'."\n";
1689 
1690  $toprightmenu .= '<div class="login_block_other">';
1691 
1692  // Execute hook printTopRightMenu (hooks should output string like '<div class="login"><a href="">mylink</a></div>')
1693  $parameters = array();
1694  $result = $hookmanager->executeHooks('printTopRightMenu', $parameters); // Note that $action and $object may have been modified by some hooks
1695  if (is_numeric($result))
1696  {
1697  if ($result == 0)
1698  $toprightmenu .= $hookmanager->resPrint; // add
1699  else {
1700  $toprightmenu = $hookmanager->resPrint; // replace
1701  }
1702  } else {
1703  $toprightmenu .= $result; // For backward compatibility
1704  }
1705 
1706  // Link to module builder
1707  if (!empty($conf->modulebuilder->enabled))
1708  {
1709  $text = '<a href="'.DOL_URL_ROOT.'/modulebuilder/index.php?mainmenu=home&leftmenu=admintools" target="modulebuilder">';
1710  //$text.= img_picto(":".$langs->trans("ModuleBuilder"), 'printer_top.png', 'class="printer"');
1711  $text .= '<span class="fa fa-bug atoplogin valignmiddle"></span>';
1712  $text .= '</a>';
1713  $toprightmenu .= $form->textwithtooltip('', $langs->trans("ModuleBuilder"), 2, 1, $text, 'login_block_elem', 2);
1714  }
1715 
1716  // Link to print main content area
1717  if (empty($conf->global->MAIN_PRINT_DISABLELINK) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $conf->browser->layout != 'phone')
1718  {
1719  $qs = dol_escape_htmltag($_SERVER["QUERY_STRING"]);
1720 
1721  if (is_array($_POST))
1722  {
1723  foreach ($_POST as $key=>$value) {
1724  if ($key !== 'action' && $key !== 'password' && !is_array($value)) $qs .= '&'.$key.'='.urlencode($value);
1725  }
1726  }
1727  $qs .= (($qs && $morequerystring) ? '&' : '').$morequerystring;
1728  $text = '<a href="'.dol_escape_htmltag($_SERVER["PHP_SELF"]).'?'.$qs.($qs ? '&' : '').'optioncss=print" target="_blank">';
1729  //$text.= img_picto(":".$langs->trans("PrintContentArea"), 'printer_top.png', 'class="printer"');
1730  $text .= '<span class="fa fa-print atoplogin valignmiddle"></span>';
1731  $text .= '</a>';
1732  $toprightmenu .= $form->textwithtooltip('', $langs->trans("PrintContentArea"), 2, 1, $text, 'login_block_elem', 2);
1733  }
1734 
1735  // Link to Dolibarr wiki pages
1736  if (empty($conf->global->MAIN_HELP_DISABLELINK) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1737  {
1738  $langs->load("help");
1739 
1740  $helpbaseurl = '';
1741  $helppage = '';
1742  $mode = '';
1743  $helppresent = '';
1744 
1745  if (empty($helppagename)) {
1746  $helppagename = 'EN:User_documentation|FR:Documentation_utilisateur|ES:Documentación_usuarios';
1747  } else {
1748  $helppresent = 'helppresent';
1749  }
1750 
1751  // Get helpbaseurl, helppage and mode from helppagename and langs
1752  $arrayres = getHelpParamFor($helppagename, $langs);
1753  $helpbaseurl = $arrayres['helpbaseurl'];
1754  $helppage = $arrayres['helppage'];
1755  $mode = $arrayres['mode'];
1756 
1757  // Link to help pages
1758  if ($helpbaseurl && $helppage)
1759  {
1760  $text = '';
1761  $title = $langs->trans($mode == 'wiki' ? 'GoToWikiHelpPage' : 'GoToHelpPage').'...';
1762  if ($mode == 'wiki') {
1763  $title .= '<br>'.$langs->trans("PageWiki").' '.dol_escape_htmltag('"'.strtr($helppage, '_', ' ').'"');
1764  if ($helppresent) $title .= ' <span class="opacitymedium">('.$langs->trans("DedicatedPageAvailable").')</span>';
1765  else $title .= ' <span class="opacitymedium">('.$langs->trans("HomePage").')</span>';
1766  }
1767  $text .= '<a class="help" target="_blank" rel="noopener" href="';
1768  if ($mode == 'wiki') $text .= sprintf($helpbaseurl, urlencode(html_entity_decode($helppage)));
1769  else $text .= sprintf($helpbaseurl, $helppage);
1770  $text .= '">';
1771  $text .= '<span class="fa fa-question-circle atoplogin valignmiddle'.($helppresent ? ' '.$helppresent : '').'"></span>';
1772  if ($helppresent) $text .= '<span class="fa fa-circle helppresentcircle"></span>';
1773  $text .= '</a>';
1774  $toprightmenu .= $form->textwithtooltip('', $title, 2, 1, $text, 'login_block_elem', 2);
1775  }
1776 
1777  // Version
1778  if (!empty($conf->global->MAIN_SHOWDATABASENAMEINHELPPAGESLINK)) {
1779  $langs->load('admin');
1780  $appli .= '<br>'.$langs->trans("Database").': '.$db->database_name;
1781  }
1782  }
1783 
1784  if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
1785  $text = '<span class="aversion"><span class="hideonsmartphone small">'.DOL_VERSION.'</span></span>';
1786  $toprightmenu .= $form->textwithtooltip('', $appli, 2, 1, $text, 'login_block_elem', 2);
1787  }
1788 
1789  // Logout link
1790  $toprightmenu .= $form->textwithtooltip('', $logouthtmltext, 2, 1, $logouttext, 'login_block_elem logout-btn', 2);
1791 
1792  $toprightmenu .= '</div>'; // end div class="login_block_other"
1793 
1794 
1795  // Add login user link
1796  $toprightmenu .= '<div class="login_block_user">';
1797 
1798  // Login name with photo and tooltip
1799  $mode = -1;
1800  $toprightmenu .= '<div class="inline-block nowrap"><div class="inline-block login_block_elem login_block_elem_name" style="padding: 0px;">';
1801 
1802  if (!empty($conf->global->MAIN_USE_TOP_MENU_SEARCH_DROPDOWN)) {
1803  // Add search dropdown
1804  $toprightmenu .= top_menu_search();
1805  }
1806 
1807  if (!empty($conf->global->MAIN_USE_TOP_MENU_QUICKADD_DROPDOWN)) {
1808  // Add search dropdown
1809  $toprightmenu .= top_menu_quickadd();
1810  }
1811 
1812  // Add bookmark dropdown
1813  $toprightmenu .= top_menu_bookmark();
1814 
1815  // Add user dropdown
1816  $toprightmenu .= top_menu_user();
1817 
1818  $toprightmenu .= '</div></div>';
1819 
1820  $toprightmenu .= '</div>'."\n";
1821 
1822 
1823  print $toprightmenu;
1824 
1825  print "</div>\n"; // end div class="login_block"
1826 
1827  print '</div></div>';
1828 
1829  print '<div style="clear: both;"></div>';
1830  print "<!-- End top horizontal menu -->\n\n";
1831  }
1832 
1833  if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print '<!-- Begin div id-container --><div id="id-container" class="id-container">';
1834 }
1835 
1836 
1844 function top_menu_user($hideloginname = 0, $urllogout = '')
1845 {
1846  global $langs, $conf, $db, $hookmanager, $user;
1847  global $dolibarr_main_authentication, $dolibarr_main_demo;
1848  global $menumanager;
1849 
1850  $userImage = $userDropDownImage = '';
1851  if (!empty($user->photo))
1852  {
1853  $userImage = Form::showphoto('userphoto', $user, 0, 0, 0, 'photouserphoto userphoto', 'small', 0, 1);
1854  $userDropDownImage = Form::showphoto('userphoto', $user, 0, 0, 0, 'dropdown-user-image', 'small', 0, 1);
1855  } else {
1856  $nophoto = '/public/theme/common/user_anonymous.png';
1857  if ($user->gender == 'man') $nophoto = '/public/theme/common/user_man.png';
1858  if ($user->gender == 'woman') $nophoto = '/public/theme/common/user_woman.png';
1859 
1860  $userImage = '<img class="photo photouserphoto userphoto" alt="No photo" src="'.DOL_URL_ROOT.$nophoto.'">';
1861  $userDropDownImage = '<img class="photo dropdown-user-image" alt="No photo" src="'.DOL_URL_ROOT.$nophoto.'">';
1862  }
1863 
1864  $dropdownBody = '';
1865  $dropdownBody .= '<span id="topmenuloginmoreinfo-btn"><i class="fa fa-caret-right"></i> '.$langs->trans("ShowMoreInfos").'</span>';
1866  $dropdownBody .= '<div id="topmenuloginmoreinfo" >';
1867 
1868  // login infos
1869  if (!empty($user->admin)) {
1870  $dropdownBody .= '<br><b>'.$langs->trans("Administrator").'</b>: '.yn($user->admin);
1871  }
1872  if (!empty($user->socid)) // Add thirdparty for external users
1873  {
1874  $thirdpartystatic = new Societe($db);
1875  $thirdpartystatic->fetch($user->socid);
1876  $companylink = ' '.$thirdpartystatic->getNomUrl(2); // picto only of company
1877  $company = ' ('.$langs->trans("Company").': '.$thirdpartystatic->name.')';
1878  }
1879  $type = ($user->socid ? $langs->trans("External").$company : $langs->trans("Internal"));
1880  $dropdownBody .= '<br><b>'.$langs->trans("Type").':</b> '.$type;
1881  $dropdownBody .= '<br><b>'.$langs->trans("Status").'</b>: '.$user->getLibStatut(0);
1882  $dropdownBody .= '<br>';
1883 
1884  $dropdownBody .= '<br><u>'.$langs->trans("Session").'</u>';
1885  $dropdownBody .= '<br><b>'.$langs->trans("IPAddress").'</b>: '.dol_escape_htmltag($_SERVER["REMOTE_ADDR"]);
1886  if (!empty($conf->global->MAIN_MODULE_MULTICOMPANY)) $dropdownBody .= '<br><b>'.$langs->trans("ConnectedOnMultiCompany").':</b> '.$conf->entity.' (user entity '.$user->entity.')';
1887  $dropdownBody .= '<br><b>'.$langs->trans("AuthenticationMode").':</b> '.$_SESSION["dol_authmode"].(empty($dolibarr_main_demo) ? '' : ' (demo)');
1888  $dropdownBody .= '<br><b>'.$langs->trans("ConnectedSince").':</b> '.dol_print_date($user->datelastlogin, "dayhour", 'tzuser');
1889  $dropdownBody .= '<br><b>'.$langs->trans("PreviousConnexion").':</b> '.dol_print_date($user->datepreviouslogin, "dayhour", 'tzuser');
1890  $dropdownBody .= '<br><b>'.$langs->trans("CurrentTheme").':</b> '.$conf->theme;
1891  $dropdownBody .= '<br><b>'.$langs->trans("CurrentMenuManager").':</b> '.$menumanager->name;
1892  $langFlag = picto_from_langcode($langs->getDefaultLang());
1893  $dropdownBody .= '<br><b>'.$langs->trans("CurrentUserLanguage").':</b> '.($langFlag ? $langFlag.' ' : '').$langs->getDefaultLang();
1894 
1895  $tz = (int) $_SESSION['dol_tz'] + (int) $_SESSION['dol_dst'];
1896  $dropdownBody .= '<br><b>'.$langs->trans("ClientTZ").':</b> '.($tz ? ($tz >= 0 ? '+' : '').$tz : '');
1897  $dropdownBody .= ' ('.$_SESSION['dol_tz_string'].')';
1898  //$dropdownBody .= ' &nbsp; &nbsp; &nbsp; '.$langs->trans("DaylingSavingTime").': ';
1899  //if ($_SESSION['dol_dst'] > 0) $dropdownBody .= yn(1);
1900  //else $dropdownBody .= yn(0);
1901 
1902  $dropdownBody .= '<br><b>'.$langs->trans("Browser").':</b> '.$conf->browser->name.($conf->browser->version ? ' '.$conf->browser->version : '').' ('.dol_escape_htmltag($_SERVER['HTTP_USER_AGENT']).')';
1903  $dropdownBody .= '<br><b>'.$langs->trans("Layout").':</b> '.$conf->browser->layout;
1904  $dropdownBody .= '<br><b>'.$langs->trans("Screen").':</b> '.$_SESSION['dol_screenwidth'].' x '.$_SESSION['dol_screenheight'];
1905  if ($conf->browser->layout == 'phone') $dropdownBody .= '<br><b>'.$langs->trans("Phone").':</b> '.$langs->trans("Yes");
1906  if (!empty($_SESSION["disablemodules"])) $dropdownBody .= '<br><b>'.$langs->trans("DisabledModules").':</b> <br>'.join(', ', explode(',', $_SESSION["disablemodules"]));
1907  $dropdownBody .= '</div>';
1908 
1909  // Execute hook
1910  $parameters = array('user'=>$user, 'langs' => $langs);
1911  $result = $hookmanager->executeHooks('printTopRightMenuLoginDropdownBody', $parameters); // Note that $action and $object may have been modified by some hooks
1912  if (is_numeric($result))
1913  {
1914  if ($result == 0) {
1915  $dropdownBody .= $hookmanager->resPrint; // add
1916  } else {
1917  $dropdownBody = $hookmanager->resPrint; // replace
1918  }
1919  }
1920 
1921  if (empty($urllogout)) {
1922  $urllogout = DOL_URL_ROOT.'/user/logout.php';
1923  }
1924  $logoutLink = '<a accesskey="l" href="'.$urllogout.'" class="button-top-menu-dropdown" ><i class="fa fa-sign-out-alt"></i> '.$langs->trans("Logout").'</a>';
1925  $profilLink = '<a accesskey="l" href="'.DOL_URL_ROOT.'/user/card.php?id='.$user->id.'" class="button-top-menu-dropdown" ><i class="fa fa-user"></i> '.$langs->trans("Card").'</a>';
1926 
1927 
1928  $profilName = $user->getFullName($langs).' ('.$user->login.')';
1929 
1930  if (!empty($user->admin)) {
1931  $profilName = '<i class="far fa-star classfortooltip" title="'.$langs->trans("Administrator").'" ></i> '.$profilName;
1932  }
1933 
1934  // Define version to show
1935  $appli = constant('DOL_APPLICATION_TITLE');
1936  if (!empty($conf->global->MAIN_APPLICATION_TITLE))
1937  {
1938  $appli = $conf->global->MAIN_APPLICATION_TITLE;
1939  if (preg_match('/\d\.\d/', $appli))
1940  {
1941  if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core
1942  } else $appli .= " ".DOL_VERSION;
1943  } else $appli .= " ".DOL_VERSION;
1944 
1945  if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
1946  $btnUser = '<!-- div for user link -->
1947  <div id="topmenu-login-dropdown" class="userimg atoplogin dropdown user user-menu inline-block">
1948  <a href="'.DOL_URL_ROOT.'/user/card.php?id='.$user->id.'" class="dropdown-toggle login-dropdown-a" data-toggle="dropdown">
1949  '.$userImage.'
1950  <span class="hidden-xs maxwidth200 atoploginusername hideonsmartphone paddingleft">'.dol_trunc($user->firstname ? $user->firstname : $user->login, 10).'</span>
1951  </a>
1952  <div class="dropdown-menu">
1953  <!-- User image -->
1954  <div class="user-header">
1955  '.$userDropDownImage.'
1956  <p>
1957  '.$profilName.'<br>';
1958  if ($user->datepreviouslogin) {
1959  $btnUser .= '<small class="classfortooltip" title="'.$langs->trans("PreviousConnexion").'" ><i class="fa fa-user-clock"></i> '.dol_print_date($user->datepreviouslogin, "dayhour", 'tzuser').'</small><br>';
1960  }
1961  //$btnUser .= '<small class="classfortooltip"><i class="fa fa-cog"></i> '.$langs->trans("Version").' '.$appli.'</small>';
1962  $btnUser .= '
1963  </p>
1964  </div>
1965 
1966  <!-- Menu Body -->
1967  <div class="user-body">'.$dropdownBody.'</div>
1968 
1969  <!-- Menu Footer-->
1970  <div class="user-footer">
1971  <div class="pull-left">
1972  '.$profilLink.'
1973  </div>
1974  <div class="pull-right">
1975  '.$logoutLink.'
1976  </div>
1977  <div style="clear:both;"></div>
1978  </div>
1979 
1980  </div>
1981  </div>';
1982  } else {
1983  $btnUser = '<!-- div for user link -->
1984  <div id="topmenu-login-dropdown" class="userimg atoplogin dropdown user user-menu inline-block">
1985  <a href="'.DOL_URL_ROOT.'/user/card.php?id='.$user->id.'">
1986  '.$userImage.'
1987  <span class="hidden-xs maxwidth200 atoploginusername hideonsmartphone">'.dol_trunc($user->firstname ? $user->firstname : $user->login, 10).'</span>
1988  </a>
1989  </div>';
1990  }
1991 
1992  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
1993  {
1994  $btnUser .= '
1995  <!-- Code to show/hide the user drop-down -->
1996  <script>
1997  $( document ).ready(function() {
1998  $(document).on("click", function(event) {
1999  if (!$(event.target).closest("#topmenu-login-dropdown").length) {
2000  //console.log("close login dropdown");
2001  // Hide the menus.
2002  $("#topmenu-login-dropdown").removeClass("open");
2003  }
2004  });
2005  ';
2006 
2007  if ($conf->theme != 'md') {
2008  $btnUser .= '
2009  $("#topmenu-login-dropdown .dropdown-toggle").on("click", function(event) {
2010  console.log("toggle login dropdown");
2011  event.preventDefault();
2012  $("#topmenu-login-dropdown").toggleClass("open");
2013  });
2014 
2015  $("#topmenuloginmoreinfo-btn").on("click", function() {
2016  $("#topmenuloginmoreinfo").slideToggle();
2017  });';
2018  }
2019 
2020  $btnUser .= '
2021  });
2022  </script>
2023  ';
2024  }
2025 
2026  return $btnUser;
2027 }
2028 
2035 {
2036  global $langs, $conf, $db, $hookmanager, $user;
2037  global $menumanager;
2038  $html = '';
2039  // Define $dropDownQuickAddHtml
2040  $dropDownQuickAddHtml = '<div class="dropdown-header bookmark-header center">';
2041  $dropDownQuickAddHtml .= $langs->trans('QuickAdd');
2042  $dropDownQuickAddHtml .= '</div>';
2043 
2044  $dropDownQuickAddHtml .= '<div class="quickadd-body dropdown-body">';
2045  $dropDownQuickAddHtml .= '<div class="quickadd">';
2046  if (!empty($conf->societe->enabled) && $user->rights->societe->creer) {
2047  $langs->load("companies");
2048  $dropDownQuickAddHtml .= '
2049  <!-- Thirdparty link -->
2050  <div class="quickaddblock center">
2051  <a class="quickadddropdown-icon-link" href="'.DOL_URL_ROOT.'/societe/card.php?action=create" title="'.$langs->trans("MenuNewThirdParty").'">
2052  <i class="fa fa-building"></i><br>
2053  '.$langs->trans("ThirdParty").'
2054  </a>
2055  </div>
2056  ';
2057  }
2058 
2059  if (!empty($conf->societe->enabled) && $user->rights->societe->contact->creer) {
2060  $langs->load("companies");
2061  $dropDownQuickAddHtml .= '
2062  <!-- Contact link -->
2063  <div class="quickaddblock center">
2064  <a class="quickadddropdown-icon-link" href="'.DOL_URL_ROOT.'/contact/card.php?action=create" title="'.$langs->trans("NewContactAddress").'">
2065  <i class="fa fa-address-book"></i><br>
2066  '.$langs->trans("Contact").'
2067  </a>
2068  </div>
2069  ';
2070  }
2071 
2072  if (!empty($conf->propal->enabled) && $user->rights->propale->creer) {
2073  $langs->load("propal");
2074  $dropDownQuickAddHtml .= '
2075  <!-- Propal link -->
2076  <div class="quickaddblock center">
2077  <a class="quickadddropdown-icon-link" href="'.DOL_URL_ROOT.'/comm/propal/card.php?action=create" title="'.$langs->trans("NewPropal").'">
2078  <i class="fa fa-suitcase"></i><br>
2079  '.$langs->trans("Proposal").'
2080  </a>
2081  </div>
2082  ';
2083  }
2084 
2085  if (!empty($conf->commande->enabled) && $user->rights->commande->creer) {
2086  $langs->load("orders");
2087  $dropDownQuickAddHtml .= '
2088  <!-- Order link -->
2089  <div class="quickaddblock center">
2090  <a class="quickadddropdown-icon-link" href="'.DOL_URL_ROOT.'/commande/card.php?action=create" title="'.$langs->trans("NewOrder").'">
2091  <i class="fa fa-file-alt"></i><br>
2092  '.$langs->trans("Order").'
2093  </a>
2094  </div>
2095  ';
2096  }
2097 
2098  if (!empty($conf->facture->enabled) && $user->rights->facture->creer) {
2099  $langs->load("bills");
2100  $dropDownQuickAddHtml .= '
2101  <!-- Invoice link -->
2102  <div class="quickaddblock center">
2103  <a class="quickadddropdown-icon-link" href="'.DOL_URL_ROOT.'/compta/facture/card.php?action=create" title="'.$langs->trans("NewBill").'">
2104  <i class="fa fa-coins"></i><br>
2105  '.$langs->trans("Bill").'
2106  </a>
2107  </div>
2108  ';
2109  }
2110 
2111  if (!empty($conf->contrat->enabled) && $user->rights->contrat->creer) {
2112  $langs->load("contracts");
2113  $dropDownQuickAddHtml .= '
2114  <!-- Contract link -->
2115  <div class="quickaddblock center">
2116  <a class="quickadddropdown-icon-link" href="'.DOL_URL_ROOT.'/compta/facture/card.php?action=create" title="'.$langs->trans("NewContractSubscription").'">
2117  <i class="fa fa-file-contract"></i><br>
2118  '.$langs->trans("Contract").'
2119  </a>
2120  </div>
2121  ';
2122  }
2123 
2124  if (!empty($conf->supplier_proposal->enabled) && $user->rights->supplier_proposal->creer) {
2125  $langs->load("supplier_proposal");
2126  $dropDownQuickAddHtml .= '
2127  <!-- Supplier proposal link -->
2128  <div class="quickaddblock center">
2129  <a class="quickadddropdown-icon-link" href="'.DOL_URL_ROOT.'/supplier_proposal/card.php?action=create" title="'.$langs->trans("NewAskPrice").'">
2130  <i class="fa fa-suitcase"></i><br>
2131  '.$langs->trans("AskPrice").'
2132  </a>
2133  </div>
2134  ';
2135  }
2136 
2137  if (!empty($conf->fournisseur->enabled) && $user->rights->fournisseur->commande->creer) {
2138  $langs->load("orders");
2139  $dropDownQuickAddHtml .= '
2140  <!-- Supplier order link -->
2141  <div class="quickaddblock center">
2142  <a class="quickadddropdown-icon-link" href="'.DOL_URL_ROOT.'/fourn/commande/card.php?action=create" title="'.$langs->trans("NewOrder").'">
2143  <i class="fa fa-file-alt"></i><br>
2144  '.$langs->trans("SupplierOrder").'
2145  </a>
2146  </div>
2147  ';
2148  }
2149 
2150  if (!empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture->creer) {
2151  $langs->load("bills");
2152  $dropDownQuickAddHtml .= '
2153  <!-- Supplier invoice link -->
2154  <div class="quickaddblock center">
2155  <a class="quickadddropdown-icon-link" href="'.DOL_URL_ROOT.'/fourn/facture/card.php?action=create" title="'.$langs->trans("NewBill").'">
2156  <i class="fa fa-coins"></i><br>
2157  '.$langs->trans("SupplierBill").'
2158  </a>
2159  </div>
2160  ';
2161  }
2162 
2163  if (!empty($conf->product->enabled) && $user->rights->produit->creer) {
2164  $langs->load("products");
2165  $dropDownQuickAddHtml .= '
2166  <!-- Product link -->
2167  <div class="quickaddblock center">
2168  <a class="quickadddropdown-icon-link" href="'.DOL_URL_ROOT.'/product/card.php?action=create&amp;type=0" title="'.$langs->trans("NewProduct").'">
2169  <i class="fa fa-cube"></i><br>
2170  '.$langs->trans("Product").'
2171  </a>
2172  </div>
2173  ';
2174  }
2175 
2176  if (!empty($conf->service->enabled) && $user->rights->service->creer) {
2177  $langs->load("products");
2178  $dropDownQuickAddHtml .= '
2179  <!-- Service link -->
2180  <div class="quickaddblock center">
2181  <a class="quickadddropdown-icon-link" href="'.DOL_URL_ROOT.'/product/card.php?action=create&amp;type=1" title="'.$langs->trans("NewService").'">
2182  <i class="fa fa-concierge-bell"></i><br>
2183  '.$langs->trans("Service").'
2184  </a>
2185  </div>
2186  ';
2187  }
2188 
2189  // Execute hook printTopRightMenu (hooks should output string like '<div class="login"><a href="">mylink</a></div>')
2190  $parameters = array();
2191  $result = $hookmanager->executeHooks('printQuickAddBlock', $parameters); // Note that $action and $object may have been modified by some hooks
2192  if (is_numeric($result)) {
2193  if ($result == 0) {
2194  $dropDownQuickAddHtml .= $hookmanager->resPrint; // add
2195  } else {
2196  $dropDownQuickAddHtml = $hookmanager->resPrint; // replace
2197  }
2198  } else {
2199  $dropDownQuickAddHtml .= $result; // For backward compatibility
2200  }
2201 
2202  $dropDownQuickAddHtml .= '</div>';
2203  $dropDownQuickAddHtml .= '</div>';
2204 
2205  $html .= '<!-- div for quick add link -->
2206  <div id="topmenu-quickadd-dropdown" class="atoplogin dropdown inline-block">
2207  <a class="dropdown-toggle login-dropdown-a" data-toggle="dropdown" href="#" title="'.$langs->trans('QuickAdd').' ('.$langs->trans('QuickAddMenuShortCut').')">
2208  <i class="fa fa-plus-circle" ></i>
2209  </a>
2210 
2211  <div class="dropdown-menu">
2212  '.$dropDownQuickAddHtml.'
2213  </div>
2214  </div>';
2215  $html .= '
2216  <!-- Code to show/hide the user drop-down -->
2217  <script>
2218  $( document ).ready(function() {
2219  $(document).on("click", function(event) {
2220  if (!$(event.target).closest("#topmenu-quickadd-dropdown").length) {
2221  // Hide the menus.
2222  $("#topmenu-quickadd-dropdown").removeClass("open");
2223  }
2224  });
2225  $("#topmenu-quickadd-dropdown .dropdown-toggle").on("click", function(event) {
2226  openQuickAddDropDown();
2227  });
2228  // Key map shortcut
2229  $(document).keydown(function(e){
2230  if( e.which === 76 && e.ctrlKey && e.shiftKey ){
2231  console.log(\'control + shift + l : trigger open quick add dropdown\');
2232  openQuickAddDropDown();
2233  }
2234  });
2235 
2236 
2237  var openQuickAddDropDown = function() {
2238  event.preventDefault();
2239  $("#topmenu-quickadd-dropdown").toggleClass("open");
2240  //$("#top-quickadd-search-input").focus();
2241  }
2242  });
2243  </script>
2244  ';
2245  return $html;
2246 }
2247 
2254 {
2255  global $langs, $conf, $db, $user;
2256 
2257  $html = '';
2258 
2259  // Define $bookmarks
2260  if (empty($conf->bookmark->enabled) || empty($user->rights->bookmark->lire)) return $html;
2261 
2262  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
2263  {
2264  include_once DOL_DOCUMENT_ROOT.'/bookmarks/bookmarks.lib.php';
2265  $langs->load("bookmarks");
2266 
2267  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
2268  $html .= '<div id="topmenu-bookmark-dropdown" class="dropdown inline-block">';
2269  $html .= printDropdownBookmarksList();
2270  $html .= '</div>';
2271  } else {
2272  $html .= '<!-- div for bookmark link -->
2273  <div id="topmenu-bookmark-dropdown" class="dropdown inline-block">
2274  <a class="dropdown-toggle login-dropdown-a" data-toggle="dropdown" href="#" title="'.$langs->trans('Bookmarks').' ('.$langs->trans('BookmarksMenuShortCut').')">
2275  <i class="fa fa-star" ></i>
2276  </a>
2277  <div class="dropdown-menu">
2279  </div>
2280  </div>';
2281 
2282  $html .= '
2283  <!-- Code to show/hide the bookmark drop-down -->
2284  <script>
2285  $( document ).ready(function() {
2286  $(document).on("click", function(event) {
2287  if (!$(event.target).closest("#topmenu-bookmark-dropdown").length) {
2288  //console.log("close bookmark dropdown - we click outside");
2289  // Hide the menus.
2290  $("#topmenu-bookmark-dropdown").removeClass("open");
2291  }
2292  });
2293 
2294  $("#topmenu-bookmark-dropdown .dropdown-toggle").on("click", function(event) {
2295  console.log("toggle bookmark dropdown");
2296  openBookMarkDropDown();
2297  });
2298 
2299  // Key map shortcut
2300  $(document).keydown(function(e){
2301  if( e.which === 77 && e.ctrlKey && e.shiftKey ){
2302  console.log(\'control + shift + m : trigger open bookmark dropdown\');
2303  openBookMarkDropDown();
2304  }
2305  });
2306 
2307 
2308  var openBookMarkDropDown = function() {
2309  event.preventDefault();
2310  $("#topmenu-bookmark-dropdown").toggleClass("open");
2311  $("#top-bookmark-search-input").focus();
2312  }
2313 
2314  });
2315  </script>
2316  ';
2317  }
2318  }
2319  return $html;
2320 }
2321 
2328 {
2329  global $langs, $conf, $db, $user, $hookmanager;
2330 
2331  $html = '';
2332 
2333  $usedbyinclude = 1;
2334  $arrayresult = null;
2335  include DOL_DOCUMENT_ROOT.'/core/ajax/selectsearchbox.php'; // This set $arrayresult
2336 
2337  $defaultAction = '';
2338  $buttonList = '<div class="dropdown-global-search-button-list" >';
2339  // Menu with all searchable items
2340  foreach ($arrayresult as $keyItem => $item)
2341  {
2342  if (empty($defaultAction)) {
2343  $defaultAction = $item['url'];
2344  }
2345  $buttonList .= '<button class="dropdown-item global-search-item" data-target="'.dol_escape_htmltag($item['url']).'" >';
2346  $buttonList .= $item['text'];
2347  $buttonList .= '</button>';
2348  }
2349  $buttonList .= '</div>';
2350 
2351 
2352  $searchInput = '<input name="sall" id="top-global-search-input" class="dropdown-search-input" placeholder="'.$langs->trans('Search').'" autocomplete="off" >';
2353 
2354  $dropDownHtml = '<form id="top-menu-action-search" name="actionsearch" method="GET" action="'.$defaultAction.'" >';
2355 
2356  $dropDownHtml .= '
2357  <!-- search input -->
2358  <div class="dropdown-header search-dropdown-header">
2359  ' . $searchInput.'
2360  </div>
2361  ';
2362 
2363  $dropDownHtml .= '
2364  <!-- Menu Body -->
2365  <div class="dropdown-body search-dropdown-body">
2366  '.$buttonList.'
2367  </div>
2368  ';
2369 
2370  $dropDownHtml .= '</form>';
2371 
2372 
2373  $html .= '<!-- div for Global Search -->
2374  <div id="topmenu-global-search-dropdown" class="atoplogin dropdown inline-block">
2375  <a class="dropdown-toggle login-dropdown-a" data-toggle="dropdown" href="#" title="'.$langs->trans('Search').' ('.$langs->trans('SearchMenuShortCut').')">
2376  <i class="fa fa-search" ></i>
2377  </a>
2378  <div class="dropdown-search">
2379  '.$dropDownHtml.'
2380  </div>
2381  </div>';
2382 
2383  $html .= '
2384  <!-- Code to show/hide the user drop-down -->
2385  <script>
2386  $( document ).ready(function() {
2387 
2388  // prevent submiting form on press ENTER
2389  $("#top-global-search-input").keydown(function (e) {
2390  if (e.keyCode == 13) {
2391  var inputs = $(this).parents("form").eq(0).find(":button");
2392  if (inputs[inputs.index(this) + 1] != null) {
2393  inputs[inputs.index(this) + 1].focus();
2394  }
2395  e.preventDefault();
2396  return false;
2397  }
2398  });
2399 
2400 
2401  // submit form action
2402  $(".dropdown-global-search-button-list .global-search-item").on("click", function(event) {
2403  $("#top-menu-action-search").attr("action", $(this).data("target"));
2404  $("#top-menu-action-search").submit();
2405  });
2406 
2407  // close drop down
2408  $(document).on("click", function(event) {
2409  if (!$(event.target).closest("#topmenu-global-search-dropdown").length) {
2410  console.log("click close search - we click outside");
2411  // Hide the menus.
2412  $("#topmenu-global-search-dropdown").removeClass("open");
2413  }
2414  });
2415 
2416  // Open drop down
2417  $("#topmenu-global-search-dropdown .dropdown-toggle").on("click", function(event) {
2418  console.log("toggle search dropdown");
2419  openGlobalSearchDropDown();
2420  });
2421 
2422  // Key map shortcut
2423  $(document).keydown(function(e){
2424  if( e.which === 70 && e.ctrlKey && e.shiftKey ){
2425  console.log(\'control + shift + f : trigger open global-search dropdown\');
2426  openGlobalSearchDropDown();
2427  }
2428  });
2429 
2430 
2431  var openGlobalSearchDropDown = function() {
2432  event.preventDefault();
2433  $("#topmenu-global-search-dropdown").toggleClass("open");
2434  $("#top-global-search-input").focus();
2435  }
2436 
2437  });
2438  </script>
2439  ';
2440 
2441  return $html;
2442 }
2443 
2458 function left_menu($menu_array_before, $helppagename = '', $notused = '', $menu_array_after = '', $leftmenuwithoutmainarea = 0, $title = '', $acceptdelayedhtml = 0)
2459 {
2460  global $user, $conf, $langs, $db, $form;
2461  global $hookmanager, $menumanager;
2462 
2463  $searchform = '';
2464  $bookmarks = '';
2465 
2466  if (!empty($menu_array_before)) 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);
2467 
2468  if (empty($conf->dol_hide_leftmenu) && (!defined('NOREQUIREMENU') || !constant('NOREQUIREMENU')))
2469  {
2470  // Instantiate hooks for external modules
2471  $hookmanager->initHooks(array('searchform', 'leftblock'));
2472 
2473  print "\n".'<!-- Begin side-nav id-left -->'."\n".'<div class="side-nav"><div id="id-left">'."\n";
2474 
2475  if ($conf->browser->layout == 'phone') $conf->global->MAIN_USE_OLD_SEARCH_FORM = 1; // Select into select2 is awfull on smartphone. TODO Is this still true with select2 v4 ?
2476 
2477  print "\n";
2478 
2479  if (!is_object($form)) $form = new Form($db);
2480  $selected = -1;
2481  if (empty($conf->global->MAIN_USE_TOP_MENU_SEARCH_DROPDOWN)) {
2482  $usedbyinclude = 1;
2483  $arrayresult = null;
2484  include DOL_DOCUMENT_ROOT.'/core/ajax/selectsearchbox.php'; // This set $arrayresult
2485 
2486  if ($conf->use_javascript_ajax && empty($conf->global->MAIN_USE_OLD_SEARCH_FORM)) {
2487  $searchform .= $form->selectArrayFilter('searchselectcombo', $arrayresult, $selected, '', 1, 0, (empty($conf->global->MAIN_SEARCHBOX_CONTENT_LOADED_BEFORE_KEY) ? 1 : 0), 'vmenusearchselectcombo', 1, $langs->trans("Search"), 1);
2488  } else {
2489  if (is_array($arrayresult)) {
2490  foreach ($arrayresult as $key => $val) {
2491  $searchform .= printSearchForm($val['url'], $val['url'], $val['label'], 'maxwidth125', 'sall', $val['shortcut'], 'searchleft'.$key, $val['img']);
2492  }
2493  }
2494  }
2495 
2496  // Execute hook printSearchForm
2497  $parameters = array('searchform' => $searchform);
2498  $reshook = $hookmanager->executeHooks('printSearchForm', $parameters); // Note that $action and $object may have been modified by some hooks
2499  if (empty($reshook)) {
2500  $searchform .= $hookmanager->resPrint;
2501  } else $searchform = $hookmanager->resPrint;
2502 
2503  // Force special value for $searchform
2504  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) || empty($conf->use_javascript_ajax)) {
2505  $urltosearch = DOL_URL_ROOT.'/core/search_page.php?showtitlebefore=1';
2506  $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>';
2507  } elseif ($conf->use_javascript_ajax && !empty($conf->global->MAIN_USE_OLD_SEARCH_FORM)) {
2508  $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>';
2509  $searchform .= '<script>
2510  jQuery(document).ready(function () {
2511  jQuery("#divsearchforms1").click(function(){
2512  jQuery("#divsearchforms2").toggle();
2513  });
2514  });
2515  </script>' . "\n";
2516  $searchform .= '</div>';
2517  }
2518  }
2519 
2520  // Left column
2521  print '<!-- Begin left menu -->'."\n";
2522 
2523  print '<div class="vmenu"'.(empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? '' : ' title="Left menu"').'>'."\n\n";
2524 
2525  // Show left menu with other forms
2526  $menumanager->menu_array = $menu_array_before;
2527  $menumanager->menu_array_after = $menu_array_after;
2528  $menumanager->showmenu('left', array('searchform'=>$searchform, 'bookmarks'=>$bookmarks)); // output menu_array and menu found in database
2529 
2530  // Dolibarr version + help + bug report link
2531  print "\n";
2532  print "<!-- Begin Help Block-->\n";
2533  print '<div id="blockvmenuhelp" class="blockvmenuhelp">'."\n";
2534 
2535  // Version
2536  if (!empty($conf->global->MAIN_SHOW_VERSION)) // Version is already on help picto and on login page.
2537  {
2538  $doliurl = 'https://www.dolibarr.org';
2539  //local communities
2540  if (preg_match('/fr/i', $langs->defaultlang)) $doliurl = 'https://www.dolibarr.fr';
2541  if (preg_match('/es/i', $langs->defaultlang)) $doliurl = 'https://www.dolibarr.es';
2542  if (preg_match('/de/i', $langs->defaultlang)) $doliurl = 'https://www.dolibarr.de';
2543  if (preg_match('/it/i', $langs->defaultlang)) $doliurl = 'https://www.dolibarr.it';
2544  if (preg_match('/gr/i', $langs->defaultlang)) $doliurl = 'https://www.dolibarr.gr';
2545 
2546  $appli = constant('DOL_APPLICATION_TITLE');
2547  if (!empty($conf->global->MAIN_APPLICATION_TITLE))
2548  {
2549  $appli = $conf->global->MAIN_APPLICATION_TITLE; $doliurl = '';
2550  if (preg_match('/\d\.\d/', $appli))
2551  {
2552  if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core
2553  } else $appli .= " ".DOL_VERSION;
2554  } else $appli .= " ".DOL_VERSION;
2555  print '<div id="blockvmenuhelpapp" class="blockvmenuhelp">';
2556  if ($doliurl) print '<a class="help" target="_blank" rel="noopener" href="'.$doliurl.'">';
2557  else print '<span class="help">';
2558  print $appli;
2559  if ($doliurl) print '</a>';
2560  else print '</span>';
2561  print '</div>'."\n";
2562  }
2563 
2564  // Link to bugtrack
2565  if (!empty($conf->global->MAIN_BUGTRACK_ENABLELINK))
2566  {
2567  require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
2568 
2569  $bugbaseurl = 'https://github.com/Dolibarr/dolibarr/issues/new?labels=Bug';
2570  $bugbaseurl .= '&title=';
2571  $bugbaseurl .= urlencode("Bug: ");
2572  $bugbaseurl .= '&body=';
2573  $bugbaseurl .= urlencode("# Instructions\n");
2574  $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");
2575  $bugbaseurl .= urlencode("*Please:*\n");
2576  $bugbaseurl .= urlencode("- *replace the bracket enclosed texts with meaningful information*\n");
2577  $bugbaseurl .= urlencode("- *remove any unused sub-section*\n");
2578  $bugbaseurl .= urlencode("\n");
2579  $bugbaseurl .= urlencode("\n");
2580  $bugbaseurl .= urlencode("# Bug\n");
2581  $bugbaseurl .= urlencode("[*Short description*]\n");
2582  $bugbaseurl .= urlencode("\n");
2583  $bugbaseurl .= urlencode("## Environment\n");
2584  $bugbaseurl .= urlencode("- **Version**: ".DOL_VERSION."\n");
2585  $bugbaseurl .= urlencode("- **OS**: ".php_uname('s')."\n");
2586  $bugbaseurl .= urlencode("- **Web server**: ".$_SERVER["SERVER_SOFTWARE"]."\n");
2587  $bugbaseurl .= urlencode("- **PHP**: ".php_sapi_name().' '.phpversion()."\n");
2588  $bugbaseurl .= urlencode("- **Database**: ".$db::LABEL.' '.$db->getVersion()."\n");
2589  $bugbaseurl .= urlencode("- **URL(s)**: ".$_SERVER["REQUEST_URI"]."\n");
2590  $bugbaseurl .= urlencode("\n");
2591  $bugbaseurl .= urlencode("## Expected and actual behavior\n");
2592  $bugbaseurl .= urlencode("[*Verbose description*]\n");
2593  $bugbaseurl .= urlencode("\n");
2594  $bugbaseurl .= urlencode("## Steps to reproduce the behavior\n");
2595  $bugbaseurl .= urlencode("[*Verbose description*]\n");
2596  $bugbaseurl .= urlencode("\n");
2597  $bugbaseurl .= urlencode("## [Attached files](https://help.github.com/articles/issue-attachments) (Screenshots, screencasts, dolibarr.log, debugging informations…)\n");
2598  $bugbaseurl .= urlencode("[*Files*]\n");
2599  $bugbaseurl .= urlencode("\n");
2600 
2601 
2602  // Execute hook printBugtrackInfo
2603  $parameters = array('bugbaseurl'=>$bugbaseurl);
2604  $reshook = $hookmanager->executeHooks('printBugtrackInfo', $parameters); // Note that $action and $object may have been modified by some hooks
2605  if (empty($reshook))
2606  {
2607  $bugbaseurl .= $hookmanager->resPrint;
2608  } else $bugbaseurl = $hookmanager->resPrint;
2609 
2610  $bugbaseurl .= urlencode("\n");
2611  $bugbaseurl .= urlencode("## Report\n");
2612  print '<div id="blockvmenuhelpbugreport" class="blockvmenuhelp">';
2613  print '<a class="help" target="_blank" rel="noopener" href="'.$bugbaseurl.'">'.$langs->trans("FindBug").'</a>';
2614  print '</div>';
2615  }
2616 
2617  print "</div>\n";
2618  print "<!-- End Help Block-->\n";
2619  print "\n";
2620 
2621  print "</div>\n";
2622  print "<!-- End left menu -->\n";
2623  print "\n";
2624 
2625  // Execute hook printLeftBlock
2626  $parameters = array();
2627  $reshook = $hookmanager->executeHooks('printLeftBlock', $parameters); // Note that $action and $object may have been modified by some hooks
2628  print $hookmanager->resPrint;
2629 
2630  print '</div></div> <!-- End side-nav id-left -->'; // End div id="side-nav" div id="id-left"
2631  }
2632 
2633  print "\n";
2634  print '<!-- Begin right area -->'."\n";
2635 
2636  if (empty($leftmenuwithoutmainarea)) main_area($title);
2637 }
2638 
2639 
2646 function main_area($title = '')
2647 {
2648  global $conf, $langs;
2649 
2650  if (empty($conf->dol_hide_leftmenu)) print '<div id="id-right">';
2651 
2652  print "\n";
2653 
2654  print '<!-- Begin div class="fiche" -->'."\n".'<div class="fiche">'."\n";
2655 
2656  if (!empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED)) print info_admin($langs->trans("WarningYouAreInMaintenanceMode", $conf->global->MAIN_ONLY_LOGIN_ALLOWED), 0, 0, 1, 'warning maintenancemode');
2657 
2658  // Permit to add user company information on each printed document by setting SHOW_SOCINFO_ON_PRINT
2659  if (!empty($conf->global->SHOW_SOCINFO_ON_PRINT) && GETPOST('optioncss', 'aZ09') == 'print' && empty(GETPOST('disable_show_socinfo_on_print', 'az09')))
2660  {
2661  global $hookmanager;
2662  $hookmanager->initHooks(array('main'));
2663  $parameters = array();
2664  $reshook = $hookmanager->executeHooks('showSocinfoOnPrint', $parameters);
2665  if (empty($reshook))
2666  {
2667  print '<!-- Begin show mysoc info header -->'."\n";
2668  print '<div id="mysoc-info-header">'."\n";
2669  print '<table class="centpercent div-table-responsive">'."\n";
2670  print '<tbody>';
2671  print '<tr><td rowspan="0" class="width20p">';
2672  if ($conf->global->MAIN_SHOW_LOGO && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && !empty($conf->global->MAIN_INFO_SOCIETE_LOGO)) {
2673  print '<img id="mysoc-info-header-logo" style="max-width:100%" alt="" src="'.DOL_URL_ROOT.'/viewimage.php?cache=1&amp;modulepart=mycompany&amp;file='.urlencode('logos/'.dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_LOGO)).'">';
2674  }
2675  print '</td><td rowspan="0" class="width50p"></td></tr>'."\n";
2676  print '<tr><td class="titre bold">'.dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_NOM).'</td></tr>'."\n";
2677  print '<tr><td>'.dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_ADDRESS).'<br>'.dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_ZIP).' '.dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_TOWN).'</td></tr>'."\n";
2678  if (!empty($conf->global->MAIN_INFO_SOCIETE_TEL)) print '<tr><td style="padding-left: 1em" class="small">'.$langs->trans("Phone").' : '.dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_TEL).'</td></tr>';
2679  if (!empty($conf->global->MAIN_INFO_SOCIETE_MAIL)) print '<tr><td style="padding-left: 1em" class="small">'.$langs->trans("Email").' : '.dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_MAIL).'</td></tr>';
2680  if (!empty($conf->global->MAIN_INFO_SOCIETE_WEB)) print '<tr><td style="padding-left: 1em" class="small">'.$langs->trans("Web").' : '.dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_WEB).'</td></tr>';
2681  print '</tbody>';
2682  print '</table>'."\n";
2683  print '</div>'."\n";
2684  print '<!-- End show mysoc info header -->'."\n";
2685  }
2686  }
2687 }
2688 
2689 
2697 function getHelpParamFor($helppagename, $langs)
2698 {
2699  $helpbaseurl = '';
2700  $helppage = '';
2701  $mode = '';
2702 
2703  if (preg_match('/^http/i', $helppagename))
2704  {
2705  // If complete URL
2706  $helpbaseurl = '%s';
2707  $helppage = $helppagename;
2708  $mode = 'local';
2709  } else {
2710  // If WIKI URL
2711  $reg = array();
2712  if (preg_match('/^es/i', $langs->defaultlang))
2713  {
2714  $helpbaseurl = 'http://wiki.dolibarr.org/index.php/%s';
2715  if (preg_match('/ES:([^|]+)/i', $helppagename, $reg)) $helppage = $reg[1];
2716  }
2717  if (preg_match('/^fr/i', $langs->defaultlang))
2718  {
2719  $helpbaseurl = 'http://wiki.dolibarr.org/index.php/%s';
2720  if (preg_match('/FR:([^|]+)/i', $helppagename, $reg)) $helppage = $reg[1];
2721  }
2722  if (empty($helppage)) // If help page not already found
2723  {
2724  $helpbaseurl = 'http://wiki.dolibarr.org/index.php/%s';
2725  if (preg_match('/EN:([^|]+)/i', $helppagename, $reg)) $helppage = $reg[1];
2726  }
2727  $mode = 'wiki';
2728  }
2729  return array('helpbaseurl'=>$helpbaseurl, 'helppage'=>$helppage, 'mode'=>$mode);
2730 }
2731 
2732 
2749 function printSearchForm($urlaction, $urlobject, $title, $htmlmorecss, $htmlinputname, $accesskey = '', $prefhtmlinputname = '', $img = '', $showtitlebefore = 0, $autofocus = 0)
2750 {
2751  global $conf, $langs, $user;
2752 
2753  $ret = '';
2754  $ret .= '<form action="'.$urlaction.'" method="post" class="searchform nowraponall tagtr">';
2755  $ret .= '<input type="hidden" name="token" value="'.newToken().'">';
2756  $ret .= '<input type="hidden" name="mode" value="search">';
2757  $ret .= '<input type="hidden" name="savelogin" value="'.dol_escape_htmltag($user->login).'">';
2758  if ($showtitlebefore) $ret .= '<div class="tagtd left">'.$title.'</div> ';
2759  $ret .= '<div class="tagtd">';
2760  $ret .= img_picto('', $img, '', false, 0, 0, '', 'paddingright width20');
2761  $ret .= '<input type="text" class="flat '.$htmlmorecss.'"';
2762  $ret .= ' style="background-repeat: no-repeat; background-position: 3px;"';
2763  $ret .= ($accesskey ? ' accesskey="'.$accesskey.'"' : '');
2764  $ret .= ' placeholder="'.strip_tags($title).'"';
2765  $ret .= ($autofocus ? ' autofocus' : '');
2766  $ret .= ' name="'.$htmlinputname.'" id="'.$prefhtmlinputname.$htmlinputname.'" />';
2767  $ret .= '<button type="submit" class="button bordertransp" style="padding-top: 4px; padding-bottom: 4px; padding-left: 6px; padding-right: 6px">';
2768  $ret .= '<span class="fa fa-search"></span>';
2769  $ret .= '</button>';
2770  $ret .= '</div>';
2771  $ret .= "</form>\n";
2772  return $ret;
2773 }
2774 
2775 
2776 if (!function_exists("llxFooter"))
2777 {
2788  function llxFooter($comment = '', $zone = 'private', $disabledoutputofmessages = 0)
2789  {
2790  global $conf, $db, $langs, $user, $mysoc, $object;
2791  global $delayedhtmlcontent;
2792  global $contextpage, $page, $limit;
2793  global $dolibarr_distrib;
2794 
2795  $ext = 'layout='.$conf->browser->layout.'&version='.urlencode(DOL_VERSION);
2796 
2797  // Global html output events ($mesgs, $errors, $warnings)
2798  dol_htmloutput_events($disabledoutputofmessages);
2799 
2800  // Code for search criteria persistence.
2801  // $user->lastsearch_values was set by the GETPOST when form field search_xxx exists
2802  if (is_object($user) && !empty($user->lastsearch_values_tmp) && is_array($user->lastsearch_values_tmp))
2803  {
2804  // Clean and save data
2805  foreach ($user->lastsearch_values_tmp as $key => $val)
2806  {
2807  unset($_SESSION['lastsearch_values_tmp_'.$key]); // Clean array to rebuild it just after
2808  if (count($val) && empty($_POST['button_removefilter'])) // If there is search criteria to save and we did not click on 'Clear filter' button
2809  {
2810  if (empty($val['sortfield'])) unset($val['sortfield']);
2811  if (empty($val['sortorder'])) unset($val['sortorder']);
2812  dol_syslog('Save lastsearch_values_tmp_'.$key.'='.json_encode($val, 0)." (systematic recording of last search criterias)");
2813  $_SESSION['lastsearch_values_tmp_'.$key] = json_encode($val);
2814  unset($_SESSION['lastsearch_values_'.$key]);
2815  }
2816  }
2817  }
2818 
2819 
2820  $relativepathstring = $_SERVER["PHP_SELF"];
2821  // Clean $relativepathstring
2822  if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
2823  $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
2824  $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
2825  if (preg_match('/list\.php$/', $relativepathstring))
2826  {
2827  unset($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]);
2828  unset($_SESSION['lastsearch_page_tmp_'.$relativepathstring]);
2829  unset($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]);
2830 
2831  if (!empty($contextpage)) $_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring] = $contextpage;
2832  if (!empty($page) && $page > 0) $_SESSION['lastsearch_page_tmp_'.$relativepathstring] = $page;
2833  if (!empty($limit) && $limit != $conf->liste_limit) $_SESSION['lastsearch_limit_tmp_'.$relativepathstring] = $limit;
2834 
2835  unset($_SESSION['lastsearch_contextpage_'.$relativepathstring]);
2836  unset($_SESSION['lastsearch_page_'.$relativepathstring]);
2837  unset($_SESSION['lastsearch_limit_'.$relativepathstring]);
2838  }
2839 
2840  // Core error message
2841  if (!empty($conf->global->MAIN_CORE_ERROR))
2842  {
2843  // Ajax version
2844  if ($conf->use_javascript_ajax)
2845  {
2846  $title = img_warning().' '.$langs->trans('CoreErrorTitle');
2847  print ajax_dialog($title, $langs->trans('CoreErrorMessage'));
2848  } else {
2849  // html version
2850  $msg = img_warning().' '.$langs->trans('CoreErrorMessage');
2851  print '<div class="error">'.$msg.'</div>';
2852  }
2853 
2854  //define("MAIN_CORE_ERROR",0); // Constant was defined and we can't change value of a constant
2855  }
2856 
2857  print "\n\n";
2858 
2859  print '</div> <!-- End div class="fiche" -->'."\n"; // End div fiche
2860 
2861  if (empty($conf->dol_hide_leftmenu)) print '</div> <!-- End div id-right -->'."\n"; // End div id-right
2862 
2863  if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print '</div> <!-- End div id-container -->'."\n"; // End div container
2864 
2865  print "\n";
2866  if ($comment) print '<!-- '.$comment.' -->'."\n";
2867 
2868  printCommonFooter($zone);
2869 
2870  if (!empty($delayedhtmlcontent)) print $delayedhtmlcontent;
2871 
2872  if (!empty($conf->use_javascript_ajax))
2873  {
2874  print "\n".'<!-- Includes JS Footer of Dolibarr -->'."\n";
2875  print '<script src="'.DOL_URL_ROOT.'/core/js/lib_foot.js.php?lang='.$langs->defaultlang.($ext ? '&'.$ext : '').'"></script>'."\n";
2876  }
2877 
2878  // Wrapper to add log when clicking on download or preview
2879  if (!empty($conf->blockedlog->enabled) && is_object($object) && $object->id > 0 && $object->statut > 0)
2880  {
2881  if (in_array($object->element, array('facture'))) // Restrict for the moment to element 'facture'
2882  {
2883  print "\n<!-- JS CODE TO ENABLE log when making a download or a preview of a document -->\n";
2884  ?>
2885  <script>
2886  jQuery(document).ready(function () {
2887  $('a.documentpreview').click(function() {
2888  $.post('<?php echo DOL_URL_ROOT."/blockedlog/ajax/block-add.php" ?>'
2889  , {
2890  id:<?php echo $object->id; ?>
2891  , element:'<?php echo $object->element ?>'
2892  , action:'DOC_PREVIEW'
2893  }
2894  );
2895  });
2896  $('a.documentdownload').click(function() {
2897  $.post('<?php echo DOL_URL_ROOT."/blockedlog/ajax/block-add.php" ?>'
2898  , {
2899  id:<?php echo $object->id; ?>
2900  , element:'<?php echo $object->element ?>'
2901  , action:'DOC_DOWNLOAD'
2902  }
2903  );
2904  });
2905  });
2906  </script>
2907  <?php
2908  }
2909  }
2910 
2911  // A div for the address popup
2912  print "\n<!-- A div to allow dialog popup -->\n";
2913  print '<div id="dialogforpopup" style="display: none;"></div>'."\n";
2914 
2915  // Add code for the asynchronous anonymous first ping (for telemetry)
2916  // You can use &forceping=1 in parameters to force the ping if the ping was already sent.
2917  $forceping = GETPOST('forceping', 'alpha');
2918  if (($_SERVER["PHP_SELF"] == DOL_URL_ROOT.'/index.php') || $forceping)
2919  {
2920  //print '<!-- instance_unique_id='.$conf->file->instance_unique_id.' MAIN_FIRST_PING_OK_ID='.$conf->global->MAIN_FIRST_PING_OK_ID.' -->';
2921  $hash_unique_id = md5('dolibarr'.$conf->file->instance_unique_id);
2922  if (empty($conf->global->MAIN_FIRST_PING_OK_DATE)
2923  || (!empty($conf->file->instance_unique_id) && ($hash_unique_id != $conf->global->MAIN_FIRST_PING_OK_ID) && ($conf->global->MAIN_FIRST_PING_OK_ID != 'disabled'))
2924  || $forceping)
2925  {
2926  // No ping done if we are into an alpha version
2927  if (strpos('alpha', DOL_VERSION) > 0 && !$forceping) {
2928  print "\n<!-- NO JS CODE TO ENABLE the anonymous Ping. It is an alpha version -->\n";
2929  } elseif (empty($_COOKIE['DOLINSTALLNOPING_'.$hash_unique_id]) || $forceping) // Cookie is set when we uncheck the checkbox in the installation wizard.
2930  {
2931  // MAIN_LAST_PING_KO_DATE
2932  // Disable ping if MAIN_LAST_PING_KO_DATE is set and is recent
2933  if (!empty($conf->global->MAIN_LAST_PING_KO_DATE) && substr($conf->global->MAIN_LAST_PING_KO_DATE, 0, 6) == dol_print_date(dol_now(), '%Y%m') && !$forceping) {
2934  print "\n<!-- NO JS CODE TO ENABLE the anonymous Ping. An error already occured this month, we will try later. -->\n";
2935  } else {
2936  include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
2937 
2938  print "\n".'<!-- Includes JS for Ping of Dolibarr forceping='.$forceping.' MAIN_FIRST_PING_OK_DATE='.$conf->global->MAIN_FIRST_PING_OK_DATE.' MAIN_FIRST_PING_OK_ID='.$conf->global->MAIN_FIRST_PING_OK_ID.' MAIN_LAST_PING_KO_DATE='.$conf->global->MAIN_LAST_PING_KO_DATE.' -->'."\n";
2939  print "\n<!-- JS CODE TO ENABLE the anonymous Ping -->\n";
2940  $url_for_ping = (empty($conf->global->MAIN_URL_FOR_PING) ? "https://ping.dolibarr.org/" : $conf->global->MAIN_URL_FOR_PING);
2941  // Try to guess the distrib used
2942  $distrib = 'standard';
2943  if ($_SERVER["SERVER_ADMIN"] == 'doliwamp@localhost') $distrib = 'doliwamp';
2944  if (!empty($dolibarr_distrib)) $distrib = $dolibarr_distrib;
2945  ?>
2946  <script>
2947  jQuery(document).ready(function (tmp) {
2948  $.ajax({
2949  method: "POST",
2950  url: "<?php echo $url_for_ping ?>",
2951  timeout: 500, // timeout milliseconds
2952  cache: false,
2953  data: {
2954  hash_algo: 'md5',
2955  hash_unique_id: '<?php echo dol_escape_js($hash_unique_id); ?>',
2956  action: 'dolibarrping',
2957  version: '<?php echo (float) DOL_VERSION; ?>',
2958  entity: '<?php echo (int) $conf->entity; ?>',
2959  dbtype: '<?php echo dol_escape_js($db->type); ?>',
2960  country_code: '<?php echo $mysoc->country_code ? dol_escape_js($mysoc->country_code) : 'unknown'; ?>',
2961  php_version: '<?php echo dol_escape_js(phpversion()); ?>',
2962  os_version: '<?php echo dol_escape_js(version_os('smr')); ?>',
2963  distrib: '<?php echo $distrib ? dol_escape_js($distrib) : 'unknown'; ?>'
2964  },
2965  success: function (data, status, xhr) { // success callback function (data contains body of response)
2966  console.log("Ping ok");
2967  $.ajax({
2968  method: 'GET',
2969  url: '<?php echo DOL_URL_ROOT.'/core/ajax/pingresult.php'; ?>',
2970  timeout: 500, // timeout milliseconds
2971  cache: false,
2972  data: { hash_algo: 'md5', hash_unique_id: '<?php echo dol_escape_js($hash_unique_id); ?>', action: 'firstpingok' }, // for update
2973  });
2974  },
2975  error: function (data,status,xhr) { // error callback function
2976  console.log("Ping ko: " + data);
2977  $.ajax({
2978  method: 'GET',
2979  url: '<?php echo DOL_URL_ROOT.'/core/ajax/pingresult.php'; ?>',
2980  timeout: 500, // timeout milliseconds
2981  cache: false,
2982  data: { hash_algo: 'md5', hash_unique_id: '<?php echo dol_escape_js($hash_unique_id); ?>', action: 'firstpingko' },
2983  });
2984  }
2985  });
2986  });
2987  </script>
2988  <?php
2989  }
2990  } else {
2991  $now = dol_now();
2992  print "\n<!-- NO JS CODE TO ENABLE the anonymous Ping. It was disabled -->\n";
2993  include_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
2994  dolibarr_set_const($db, 'MAIN_FIRST_PING_OK_DATE', dol_print_date($now, 'dayhourlog', 'gmt'));
2995  dolibarr_set_const($db, 'MAIN_FIRST_PING_OK_ID', 'disabled');
2996  }
2997  }
2998  }
2999 
3000  print "</body>\n";
3001  print "</html>\n";
3002  }
3003 }
if(!function_exists('dol_getprefix')) dol_include_once($relpath, $classname= '')
Make an include_once using default root and alternate root if it fails.
GETPOST($paramname, $check= 'alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
dol_hash($chain, $type= '0')
Returns a hash of a string.
dol_htmloutput_events($disabledoutputofmessages=0)
Print formated messages to output (Used to show messages on html output).
yn($yesno, $case=1, $color=0)
Return yes or no in current language.
printCommonFooter($zone= 'private')
Print common footer : conf-&gt;global-&gt;MAIN_HTML_FOOTER js for switch of menu hider js for conf-&gt;global-...
top_menu($head, $title= '', $target= '', $disablejs=0, $disablehead=0, $arrayofjs= '', $arrayofcss= '', $morequerystring= '', $helppagename= '')
Show an HTML header + a BODY + The top menu bar.
Definition: main.inc.php:1615
dol_now($mode= 'auto')
Return date for now.
if(!empty($_SERVER['MAIN_SHOW_TUNING_INFO'])) testSqlAndScriptInject($val, $type)
Security: WAF layer for SQL Injection and XSS Injection (scripts) protection (Filters on GET...
Definition: main.inc.php:61
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).
Definition: admin.lib.php:575
dol_htmlentities($string, $flags=null, $encoding= 'UTF-8', $double_encode=false)
Replace htmlentities functions.
Class to manage menu Auguria.
dol_stringtotime($string, $gm=1)
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:319
top_htmlhead($head, $title= '', $disablejs=0, $disablehead=0, $arrayofjs= '', $arrayofcss= '', $disablejmobile=0, $disablenofollow=0)
Ouput html header of a page.
Definition: main.inc.php:1280
top_menu_search()
Build the tooltip on top menu tsearch.
Definition: main.inc.php:2327
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
img_warning($titlealt= 'default', $moreatt= '', $morecss= 'pictowarning')
Show warning logo.
if(!defined('NOREQUIREMENU')) if(!function_exists("llxHeader")) top_httphead($contenttype= 'text/html', $forcenocache=0)
Show HTTP header.
Definition: main.inc.php:1214
llxHeader()
Empty header.
Definition: wrapper.php:45
Class to manage hooks.
setEventMessages($mesg, $mesgs, $style= 'mesgs', $messagekey= '')
Set event messages in dol_events session object.
Class to manage generation of HTML components Only common components must be here.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname.
Class to manage third parties objects (customers, suppliers, prospects...)
DolibarrDebugBar class.
Definition: DebugBar.php:23
top_menu_bookmark()
Build the tooltip on top menu bookmark.
Definition: main.inc.php:2253
img_picto($titlealt, $picto, $moreatt= '', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt= '', $morecss= '', $marginleftonlyshort=2)
Show picto whatever it&#39;s its name (generic function)
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename= '', $restricttologhandler= '', $logcontext=null)
Write log message into outputs.
accessforbidden($message= '', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program Calling this function terminate execution ...
versioncompare($versionarray1, $versionarray2)
Compare 2 versions (stored into 2 arrays).
Definition: admin.lib.php:66
getBrowserInfo($user_agent)
Return information about user browser.
Class to manage translations.
loadMenu($forcemainmenu= '', $forceleftmenu= '')
Load this-&gt;tabMenu.
ajax_dialog($title, $message, $w=350, $h=150)
Show an ajax dialog.
Definition: ajax.lib.php:348
left_menu($menu_array_before, $helppagename= '', $notused= '', $menu_array_after= '', $leftmenuwithoutmainarea=0, $title= '', $acceptdelayedhtml=0)
Show left menu bar.
Definition: main.inc.php:2458
getHelpParamFor($helppagename, $langs)
Return helpbaseurl, helppage and mode.
Definition: main.inc.php:2697
static showphoto($modulepart, $object, $width=100, $height=0, $caneditfield=0, $cssclass= 'photowithmargin', $imagesize= '', $addlinktofullsize=1, $cache=0, $forcecapture= '', $noexternsourceoverwrite=0)
Return HTML code to output a photo.
print $_SERVER["PHP_SELF"]
Edit parameters.
top_menu_user($hideloginname=0, $urllogout= '')
Build the tooltip on user login.
Definition: main.inc.php:1844
div float
Buy price without taxes.
Definition: style.css.php:650
print
Draft customers invoices.
Definition: index.php:89
dol_print_date($time, $format= '', $tzoutput= 'auto', $outputlangs= '', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
checkLoginPassEntity($usertotest, $passwordtotest, $entitytotest, $authmode, $context= '')
Return a login if login/pass was successfull.
dol_print_error($db= '', $error= '', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_trunc($string, $size=40, $trunc= 'right', $stringencoding= 'UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding &#39;...&#39; if string larger than length.
main_area($title= '')
Begin main area.
Definition: main.inc.php:2646
llxFooter()
Empty footer.
Definition: wrapper.php:59
printSearchForm($urlaction, $urlobject, $title, $htmlmorecss, $htmlinputname, $accesskey= '', $prefhtmlinputname= '', $img= '', $showtitlebefore=0, $autofocus=0)
Show a search area.
Definition: main.inc.php:2749
printDropdownBookmarksList()
Add area with bookmarks in top menu.
if(!defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN'
Draft customers invoices.
info_admin($text, $infoonimgalt=0, $nodiv=0, $admin= '1', $morecss= '', $textfordropdown= '')
Show information for admin users or standard users.
top_menu_quickadd()
Build the tooltip on top menu quick add.
Definition: main.inc.php:2034
picto_from_langcode($codelang, $moreatt= '')
Return img flag of country for a language code or country code.
analyseVarsForSqlAndScriptsInjection(&$var, $type)
Return true if security check on parameters are OK, false otherwise.
Definition: main.inc.php:158
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $keepmoretags= '', $escapeonlyhtmltags=0)
Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields...