main.inc.php 174 KB

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