main.inc.php 148 KB

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