main.inc.php 173 KB

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