main.inc.php 149 KB

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