main.inc.php 146 KB

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