main.inc.php 148 KB

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