main.inc.php 132 KB

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