main.inc.php 168 KB

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