main.inc.php 132 KB

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