main.inc.php 123 KB

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