main.inc.php 173 KB

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