main.inc.php 170 KB

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