main.inc.php 150 KB

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