admin.lib.php 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095
  1. <?php
  2. /* Copyright (C) 2008-2011 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2005-2016 Regis Houssin <regis.houssin@inodbox.com>
  4. * Copyright (C) 2012 J. Fernando Lagrange <fernando@demo-tic.org>
  5. * Copyright (C) 2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  6. * Copyright (C) 2023 Eric Seigne <eric.seigne@cap-rel.fr>
  7. *
  8. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. * or see https://www.gnu.org/
  21. */
  22. /**
  23. * \file htdocs/core/lib/admin.lib.php
  24. * \brief Library of admin functions
  25. */
  26. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  27. /**
  28. * Renvoi une version en chaine depuis une version en tableau
  29. *
  30. * @param array $versionarray Tableau de version (vermajeur,vermineur,autre)
  31. * @return string Chaine version
  32. * @see versioncompare()
  33. */
  34. function versiontostring($versionarray)
  35. {
  36. $string = '?';
  37. if (isset($versionarray[0])) {
  38. $string = $versionarray[0];
  39. }
  40. if (isset($versionarray[1])) {
  41. $string .= '.'.$versionarray[1];
  42. }
  43. if (isset($versionarray[2])) {
  44. $string .= '.'.$versionarray[2];
  45. }
  46. return $string;
  47. }
  48. /**
  49. * Compare 2 versions (stored into 2 arrays).
  50. * To check if Dolibarr version is lower than (x,y,z), do "if versioncompare(versiondolibarrarray(), array(x.y.z)) <= 0"
  51. * For example: if (versioncompare(versiondolibarrarray(),array(4,0,-5)) >= 0) is true if version is 4.0 alpha or higher.
  52. * For example: if (versioncompare(versiondolibarrarray(),array(4,0,0)) >= 0) is true if version is 4.0 final or higher.
  53. * For example: if (versioncompare(versiondolibarrarray(),array(4,0,1)) >= 0) is true if version is 4.0.1 or higher.
  54. * Alternative way to compare: if ((float) DOL_VERSION >= 4.0) is true if version is 4.0 alpha or higher (works only to compare first and second level)
  55. *
  56. * @param array $versionarray1 Array of version (vermajor,verminor,patch)
  57. * @param array $versionarray2 Array of version (vermajor,verminor,patch)
  58. * @return int -4,-3,-2,-1 if versionarray1<versionarray2 (value depends on level of difference)
  59. * 0 if same
  60. * 1,2,3,4 if versionarray1>versionarray2 (value depends on level of difference)
  61. * @see versiontostring()
  62. */
  63. function versioncompare($versionarray1, $versionarray2)
  64. {
  65. $ret = 0;
  66. $level = 0;
  67. $count1 = count($versionarray1);
  68. $count2 = count($versionarray2);
  69. $maxcount = max($count1, $count2);
  70. while ($level < $maxcount) {
  71. $operande1 = isset($versionarray1[$level]) ? $versionarray1[$level] : 0;
  72. $operande2 = isset($versionarray2[$level]) ? $versionarray2[$level] : 0;
  73. if (preg_match('/alpha|dev/i', $operande1)) {
  74. $operande1 = -5;
  75. }
  76. if (preg_match('/alpha|dev/i', $operande2)) {
  77. $operande2 = -5;
  78. }
  79. if (preg_match('/beta$/i', $operande1)) {
  80. $operande1 = -4;
  81. }
  82. if (preg_match('/beta$/i', $operande2)) {
  83. $operande2 = -4;
  84. }
  85. if (preg_match('/beta([0-9])+/i', $operande1)) {
  86. $operande1 = -3;
  87. }
  88. if (preg_match('/beta([0-9])+/i', $operande2)) {
  89. $operande2 = -3;
  90. }
  91. if (preg_match('/rc$/i', $operande1)) {
  92. $operande1 = -2;
  93. }
  94. if (preg_match('/rc$/i', $operande2)) {
  95. $operande2 = -2;
  96. }
  97. if (preg_match('/rc([0-9])+/i', $operande1)) {
  98. $operande1 = -1;
  99. }
  100. if (preg_match('/rc([0-9])+/i', $operande2)) {
  101. $operande2 = -1;
  102. }
  103. $level++;
  104. //print 'level '.$level.' '.$operande1.'-'.$operande2.'<br>';
  105. if ($operande1 < $operande2) {
  106. $ret = -$level;
  107. break;
  108. }
  109. if ($operande1 > $operande2) {
  110. $ret = $level;
  111. break;
  112. }
  113. }
  114. //print join('.',$versionarray1).'('.count($versionarray1).') / '.join('.',$versionarray2).'('.count($versionarray2).') => '.$ret.'<br>'."\n";
  115. return $ret;
  116. }
  117. /**
  118. * Return version PHP
  119. *
  120. * @return array Tableau de version (vermajeur,vermineur,autre)
  121. * @see versioncompare()
  122. */
  123. function versionphparray()
  124. {
  125. return explode('.', PHP_VERSION);
  126. }
  127. /**
  128. * Return version Dolibarr
  129. *
  130. * @return array Tableau de version (vermajeur,vermineur,autre)
  131. * @see versioncompare()
  132. */
  133. function versiondolibarrarray()
  134. {
  135. return explode('.', DOL_VERSION);
  136. }
  137. /**
  138. * Launch a sql file. Function is used by:
  139. * - Migrate process (dolibarr-xyz-abc.sql)
  140. * - Loading sql menus (auguria)
  141. * - Running specific Sql by a module init
  142. * - Loading sql file of website import package
  143. * Install process however does not use it.
  144. * Note that Sql files must have all comments at start of line. Also this function take ';' as the char to detect end of sql request
  145. *
  146. * @param string $sqlfile Full path to sql file
  147. * @param int $silent 1=Do not output anything, 0=Output line for update page
  148. * @param int $entity Entity targeted for multicompany module
  149. * @param int $usesavepoint 1=Run a savepoint before each request and a rollback to savepoint if error (this allow to have some request with errors inside global transactions).
  150. * @param string $handler Handler targeted for menu (replace __HANDLER__ with this value between quotes)
  151. * @param string $okerror Family of errors we accept ('default', 'none')
  152. * @param int $linelengthlimit Limit for length of each line (Use 0 if unknown, may be faster if defined)
  153. * @param int $nocommentremoval Do no try to remove comments (in such a case, we consider that each line is a request, so use also $linelengthlimit=0)
  154. * @param int $offsetforchartofaccount Offset to use to load chart of account table to update sql on the fly to add offset to rowid and account_parent value
  155. * @param int $colspan 2=Add a colspan=2 on td
  156. * @param int $onlysqltoimportwebsite Only sql resquests used to import a website template are allowed
  157. * @param string $database Database (replace __DATABASE__ with this value)
  158. * @return int <=0 if KO, >0 if OK
  159. */
  160. function run_sql($sqlfile, $silent = 1, $entity = 0, $usesavepoint = 1, $handler = '', $okerror = 'default', $linelengthlimit = 32768, $nocommentremoval = 0, $offsetforchartofaccount = 0, $colspan = 0, $onlysqltoimportwebsite = 0, $database = '')
  161. {
  162. global $db, $conf, $langs, $user;
  163. dol_syslog("Admin.lib::run_sql run sql file ".$sqlfile." silent=".$silent." entity=".$entity." usesavepoint=".$usesavepoint." handler=".$handler." okerror=".$okerror, LOG_DEBUG);
  164. if (!is_numeric($linelengthlimit)) {
  165. dol_syslog("Admin.lib::run_sql param linelengthlimit is not a numeric", LOG_ERR);
  166. return -1;
  167. }
  168. $ok = 0;
  169. $error = 0;
  170. $i = 0;
  171. $buffer = '';
  172. $arraysql = array();
  173. // Get version of database
  174. $versionarray = $db->getVersionArray();
  175. $fp = fopen($sqlfile, "r");
  176. if ($fp) {
  177. while (!feof($fp)) {
  178. // Warning fgets with second parameter that is null or 0 hang.
  179. if ($linelengthlimit > 0) {
  180. $buf = fgets($fp, $linelengthlimit);
  181. } else {
  182. $buf = fgets($fp);
  183. }
  184. // Test if request must be ran only for particular database or version (if yes, we must remove the -- comment)
  185. $reg = array();
  186. if (preg_match('/^--\sV(MYSQL|PGSQL)([^\s]*)/i', $buf, $reg)) {
  187. $qualified = 1;
  188. // restrict on database type
  189. if (!empty($reg[1])) {
  190. if (!preg_match('/'.preg_quote($reg[1]).'/i', $db->type)) {
  191. $qualified = 0;
  192. }
  193. }
  194. // restrict on version
  195. if ($qualified) {
  196. if (!empty($reg[2])) {
  197. if (is_numeric($reg[2])) { // This is a version
  198. $versionrequest = explode('.', $reg[2]);
  199. //var_dump($versionrequest);
  200. //var_dump($versionarray);
  201. if (!count($versionrequest) || !count($versionarray) || versioncompare($versionrequest, $versionarray) > 0) {
  202. $qualified = 0;
  203. }
  204. } else // This is a test on a constant. For example when we have -- VMYSQLUTF8UNICODE, we test constant $conf->global->UTF8UNICODE
  205. {
  206. $dbcollation = strtoupper(preg_replace('/_/', '', $conf->db->dolibarr_main_db_collation));
  207. //var_dump($reg[2]);
  208. //var_dump($dbcollation);
  209. if (empty($conf->db->dolibarr_main_db_collation) || ($reg[2] != $dbcollation)) {
  210. $qualified = 0;
  211. }
  212. //var_dump($qualified);
  213. }
  214. }
  215. }
  216. if ($qualified) {
  217. // Version qualified, delete SQL comments
  218. $buf = preg_replace('/^--\sV(MYSQL|PGSQL)([^\s]*)/i', '', $buf);
  219. //print "Ligne $i qualifi?e par version: ".$buf.'<br>';
  220. }
  221. }
  222. // Add line buf to buffer if not a comment
  223. if ($nocommentremoval || !preg_match('/^\s*--/', $buf)) {
  224. if (empty($nocommentremoval)) {
  225. $buf = preg_replace('/([,;ERLT\)])\s*--.*$/i', '\1', $buf); //remove comment from a line that not start with -- before add it to the buffer
  226. }
  227. if ($buffer) $buffer .= ' ';
  228. $buffer .= trim($buf);
  229. }
  230. //print $buf.'<br>';exit;
  231. if (preg_match('/;/', $buffer)) { // If string contains ';', it's end of a request string, we save it in arraysql.
  232. // Found new request
  233. if ($buffer) {
  234. $arraysql[$i] = $buffer;
  235. }
  236. $i++;
  237. $buffer = '';
  238. }
  239. }
  240. if ($buffer) {
  241. $arraysql[$i] = $buffer;
  242. }
  243. fclose($fp);
  244. } else {
  245. dol_syslog("Admin.lib::run_sql failed to open file ".$sqlfile, LOG_ERR);
  246. }
  247. // Loop on each request to see if there is a __+MAX_table__ key
  248. $listofmaxrowid = array(); // This is a cache table
  249. foreach ($arraysql as $i => $sql) {
  250. $newsql = $sql;
  251. // Replace __+MAX_table__ with max of table
  252. while (preg_match('/__\+MAX_([A-Za-z0-9_]+)__/i', $newsql, $reg)) {
  253. $table = $reg[1];
  254. if (!isset($listofmaxrowid[$table])) {
  255. //var_dump($db);
  256. $sqlgetrowid = 'SELECT MAX(rowid) as max from '.preg_replace('/^llx_/', MAIN_DB_PREFIX, $table);
  257. $resql = $db->query($sqlgetrowid);
  258. if ($resql) {
  259. $obj = $db->fetch_object($resql);
  260. $listofmaxrowid[$table] = $obj->max;
  261. if (empty($listofmaxrowid[$table])) {
  262. $listofmaxrowid[$table] = 0;
  263. }
  264. } else {
  265. if (!$silent) {
  266. print '<tr><td class="tdtop"'.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
  267. print '<div class="error">'.$langs->trans("Failed to get max rowid for ".$table)."</div>";
  268. print '</td></tr>';
  269. }
  270. $error++;
  271. break;
  272. }
  273. }
  274. // Replace __+MAX_llx_table__ with +999
  275. $from = '__+MAX_'.$table.'__';
  276. $to = '+'.$listofmaxrowid[$table];
  277. $newsql = str_replace($from, $to, $newsql);
  278. dol_syslog('Admin.lib::run_sql New Request '.($i + 1).' (replacing '.$from.' to '.$to.')', LOG_DEBUG);
  279. $arraysql[$i] = $newsql;
  280. }
  281. if ($offsetforchartofaccount > 0) {
  282. // Replace lines
  283. // 'INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 1401, 'PCG99-ABREGE', 'CAPIT', '1234', 1400,...'
  284. // with
  285. // 'INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 1401 + 200100000, 'PCG99-ABREGE','CAPIT', '1234', 1400 + 200100000,...'
  286. // Note: string with 'PCG99-ABREGE','CAPIT', 1234 instead of 'PCG99-ABREGE','CAPIT', '1234' is also supported
  287. $newsql = preg_replace('/VALUES\s*\(__ENTITY__, \s*(\d+)\s*,(\s*\'[^\',]*\'\s*,\s*\'[^\',]*\'\s*,\s*\'?[^\',]*\'?\s*),\s*\'?([^\',]*)\'?/ims', 'VALUES (__ENTITY__, \1 + '.((int) $offsetforchartofaccount).', \2, \3 + '.((int) $offsetforchartofaccount), $newsql);
  288. $newsql = preg_replace('/([,\s])0 \+ '.((int) $offsetforchartofaccount).'/ims', '\1 0', $newsql);
  289. //var_dump($newsql);
  290. $arraysql[$i] = $newsql;
  291. // FIXME Because we force the rowid during insert, we must also update the sequence with postgresql by running
  292. // SELECT dol_util_rebuild_sequences();
  293. }
  294. }
  295. // Loop on each request to execute request
  296. $cursorinsert = 0;
  297. $listofinsertedrowid = array();
  298. $keyforsql = md5($sqlfile);
  299. foreach ($arraysql as $i => $sql) {
  300. if ($sql) {
  301. // Test if th SQL is allowed SQL
  302. if ($onlysqltoimportwebsite) {
  303. $newsql = str_replace(array("\'"), '__BACKSLASHQUOTE__', $sql); // Replace the \' char
  304. // Remove all strings contents including the ' so we can analyse SQL instruction only later
  305. $l = strlen($newsql);
  306. $is = 0;
  307. $quoteopen = 0;
  308. $newsqlclean = '';
  309. while ($is < $l) {
  310. $char = $newsql[$is];
  311. if ($char == "'") {
  312. if ($quoteopen) {
  313. $quoteopen--;
  314. } else {
  315. $quoteopen++;
  316. }
  317. } elseif (empty($quoteopen)) {
  318. $newsqlclean .= $char;
  319. }
  320. $is++;
  321. }
  322. $newsqlclean = str_replace(array("null"), '__000__', $newsqlclean);
  323. //print $newsqlclean."<br>\n";
  324. $qualified = 0;
  325. // A very small control. This can still by bypassed by adding a second SQL request concatenated
  326. if (preg_match('/^--/', $newsqlclean)) {
  327. $qualified = 1;
  328. } elseif (preg_match('/^UPDATE llx_website SET \w+ = \d+\+\d+ WHERE rowid = \d+;$/', $newsqlclean)) {
  329. $qualified = 1;
  330. } elseif (preg_match('/^INSERT INTO llx_website_page\([a-z0-9_\s,]+\) VALUES\([0-9_\s,\+]+\);$/', $newsqlclean)) {
  331. // Insert must match
  332. // INSERT INTO llx_website_page(rowid, fk_page, fk_website, pageurl, aliasalt, title, description, lang, image, keywords, status, date_creation, tms, import_key, grabbed_from, type_container, htmlheader, content, author_alias) VALUES(1+123, null, 17, , , , , , , , , , , null, , , , , );
  333. $qualified = 1;
  334. }
  335. // Another check to allow some legitimate original urls
  336. if (!$qualified) {
  337. if (preg_match('/^UPDATE llx_website SET \w+ = \'[a-zA-Z,\s]*\' WHERE rowid = \d+;$/', $sql)) {
  338. $qualified = 1;
  339. }
  340. }
  341. if (!$qualified) {
  342. $error++;
  343. //print 'Request '.($i + 1)." contains non allowed instructions.<br>\n";
  344. //print "newsqlclean = ".$newsqlclean."<br>\n";
  345. dol_syslog('Admin.lib::run_sql Request '.($i + 1)." contains non allowed instructions.", LOG_WARNING);
  346. dol_syslog('$newsqlclean='.$newsqlclean, LOG_DEBUG);
  347. break;
  348. }
  349. }
  350. // Replace the prefix tables
  351. if (MAIN_DB_PREFIX != 'llx_') {
  352. $sql = preg_replace('/llx_/i', MAIN_DB_PREFIX, $sql);
  353. }
  354. if (!empty($handler)) {
  355. $sql = preg_replace('/__HANDLER__/i', "'".$db->escape($handler)."'", $sql);
  356. }
  357. if (!empty($database)) {
  358. $sql = preg_replace('/__DATABASE__/i', $db->escape($database), $sql);
  359. }
  360. $newsql = preg_replace('/__ENTITY__/i', (!empty($entity) ? $entity : $conf->entity), $sql);
  361. // Add log of request
  362. if (!$silent) {
  363. print '<tr class="trforrunsql'.$keyforsql.'"><td class="tdtop opacitymedium"'.($colspan ? ' colspan="'.$colspan.'"' : '').'>'.$langs->trans("Request").' '.($i + 1)." sql='".dol_htmlentities($newsql, ENT_NOQUOTES)."'</td></tr>\n";
  364. }
  365. dol_syslog('Admin.lib::run_sql Request '.($i + 1), LOG_DEBUG);
  366. $sqlmodified = 0;
  367. // Replace for encrypt data
  368. if (preg_match_all('/__ENCRYPT\(\'([^\']+)\'\)__/i', $newsql, $reg)) {
  369. $num = count($reg[0]);
  370. for ($j = 0; $j < $num; $j++) {
  371. $from = $reg[0][$j];
  372. $to = $db->encrypt($reg[1][$j]);
  373. $newsql = str_replace($from, $to, $newsql);
  374. }
  375. $sqlmodified++;
  376. }
  377. // Replace for decrypt data
  378. if (preg_match_all('/__DECRYPT\(\'([A-Za-z0-9_]+)\'\)__/i', $newsql, $reg)) {
  379. $num = count($reg[0]);
  380. for ($j = 0; $j < $num; $j++) {
  381. $from = $reg[0][$j];
  382. $to = $db->decrypt($reg[1][$j]);
  383. $newsql = str_replace($from, $to, $newsql);
  384. }
  385. $sqlmodified++;
  386. }
  387. // Replace __x__ with the rowid of the result of the insert number x
  388. while (preg_match('/__([0-9]+)__/', $newsql, $reg)) {
  389. $cursor = $reg[1];
  390. if (empty($listofinsertedrowid[$cursor])) {
  391. if (!$silent) {
  392. print '<tr><td class="tdtop"'.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
  393. print '<div class="error">'.$langs->trans("FileIsNotCorrect")."</div>";
  394. print '</td></tr>';
  395. }
  396. $error++;
  397. break;
  398. }
  399. $from = '__'.$cursor.'__';
  400. $to = $listofinsertedrowid[$cursor];
  401. $newsql = str_replace($from, $to, $newsql);
  402. $sqlmodified++;
  403. }
  404. if ($sqlmodified) {
  405. dol_syslog('Admin.lib::run_sql New Request '.($i + 1), LOG_DEBUG);
  406. }
  407. $result = $db->query($newsql, $usesavepoint);
  408. if ($result) {
  409. if (!$silent) {
  410. print '<!-- Result = OK -->'."\n";
  411. }
  412. if (preg_replace('/insert into ([^\s]+)/i', $newsql, $reg)) {
  413. $cursorinsert++;
  414. // It's an insert
  415. $table = preg_replace('/([^a-zA-Z_]+)/i', '', $reg[1]);
  416. $insertedrowid = $db->last_insert_id($table);
  417. $listofinsertedrowid[$cursorinsert] = $insertedrowid;
  418. dol_syslog('Admin.lib::run_sql Insert nb '.$cursorinsert.', done in table '.$table.', rowid is '.$listofinsertedrowid[$cursorinsert], LOG_DEBUG);
  419. }
  420. // print '<td class="right">OK</td>';
  421. } else {
  422. $errno = $db->errno();
  423. if (!$silent) {
  424. print '<!-- Result = '.$errno.' -->'."\n";
  425. }
  426. // Define list of errors we accept (array $okerrors)
  427. $okerrors = array( // By default
  428. 'DB_ERROR_TABLE_ALREADY_EXISTS',
  429. 'DB_ERROR_COLUMN_ALREADY_EXISTS',
  430. 'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
  431. 'DB_ERROR_TABLE_OR_KEY_ALREADY_EXISTS', // PgSql use same code for table and key already exist
  432. 'DB_ERROR_RECORD_ALREADY_EXISTS',
  433. 'DB_ERROR_NOSUCHTABLE',
  434. 'DB_ERROR_NOSUCHFIELD',
  435. 'DB_ERROR_NO_FOREIGN_KEY_TO_DROP',
  436. 'DB_ERROR_NO_INDEX_TO_DROP',
  437. 'DB_ERROR_CANNOT_CREATE', // Qd contrainte deja existante
  438. 'DB_ERROR_CANT_DROP_PRIMARY_KEY',
  439. 'DB_ERROR_PRIMARY_KEY_ALREADY_EXISTS',
  440. 'DB_ERROR_22P02'
  441. );
  442. if ($okerror == 'none') {
  443. $okerrors = array();
  444. }
  445. // Is it an error we accept
  446. if (!in_array($errno, $okerrors)) {
  447. if (!$silent) {
  448. print '<tr><td class="tdtop"'.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
  449. print '<div class="error">'.$langs->trans("Error")." ".$db->errno()." (Req ".($i + 1)."): ".$newsql."<br>".$db->error()."</div>";
  450. print '</td></tr>'."\n";
  451. }
  452. dol_syslog('Admin.lib::run_sql Request '.($i + 1)." Error ".$db->errno()." ".$newsql."<br>".$db->error(), LOG_ERR);
  453. $error++;
  454. }
  455. }
  456. }
  457. }
  458. if (!$silent) {
  459. print '<tr><td>'.$langs->trans("ProcessMigrateScript").'</td>';
  460. print '<td class="right">';
  461. if ($error == 0) {
  462. print '<span class="ok">'.$langs->trans("OK").'</span>';
  463. } else {
  464. print '<span class="error">'.$langs->trans("Error").'</span>';
  465. }
  466. //if (!empty($conf->use_javascript_ajax)) { // use_javascript_ajax is not defined
  467. print '<script type="text/javascript">
  468. jQuery(document).ready(function() {
  469. function init_trrunsql'.$keyforsql.'()
  470. {
  471. console.log("toggle .trforrunsql'.$keyforsql.'");
  472. jQuery(".trforrunsql'.$keyforsql.'").toggle();
  473. }
  474. init_trrunsql'.$keyforsql.'();
  475. jQuery(".trforrunsqlshowhide'.$keyforsql.'").click(function() {
  476. init_trrunsql'.$keyforsql.'();
  477. });
  478. });
  479. </script>';
  480. if (count($arraysql)) {
  481. print ' - <a class="trforrunsqlshowhide'.$keyforsql.'" href="#" title="'.($langs->trans("ShowHideTheNRequests", count($arraysql))).'">'.$langs->trans("ShowHideDetails").'</a>';
  482. } else {
  483. print ' - <span class="opacitymedium">'.$langs->trans("ScriptIsEmpty").'</span>';
  484. }
  485. //}
  486. print '</td></tr>'."\n";
  487. }
  488. if ($error == 0) {
  489. $ok = 1;
  490. } else {
  491. $ok = 0;
  492. }
  493. return $ok;
  494. }
  495. /**
  496. * Delete a constant
  497. *
  498. * @param DoliDB $db Database handler
  499. * @param string|int $name Name of constant or rowid of line
  500. * @param int $entity Multi company id, -1 for all entities
  501. * @return int <0 if KO, >0 if OK
  502. *
  503. * @see dolibarr_get_const(), dolibarr_set_const(), dol_set_user_param()
  504. */
  505. function dolibarr_del_const($db, $name, $entity = 1)
  506. {
  507. global $conf;
  508. if (empty($name)) {
  509. dol_print_error('', 'Error call dolibar_del_const with parameter name empty');
  510. return -1;
  511. }
  512. $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
  513. $sql .= " WHERE (".$db->decrypt('name')." = '".$db->escape($name)."'";
  514. if (is_numeric($name)) {
  515. $sql .= " OR rowid = ".((int) $name);
  516. }
  517. $sql .= ")";
  518. if ($entity >= 0) {
  519. $sql .= " AND entity = ".((int) $entity);
  520. }
  521. dol_syslog("admin.lib::dolibarr_del_const", LOG_DEBUG);
  522. $resql = $db->query($sql);
  523. if ($resql) {
  524. $conf->global->$name = '';
  525. return 1;
  526. } else {
  527. dol_print_error($db);
  528. return -1;
  529. }
  530. }
  531. /**
  532. * Get the value of a setup constant from database
  533. *
  534. * @param DoliDB $db Database handler
  535. * @param string $name Name of constant
  536. * @param int $entity Multi company id
  537. * @return string Value of constant
  538. *
  539. * @see dolibarr_del_const(), dolibarr_set_const(), dol_set_user_param()
  540. */
  541. function dolibarr_get_const($db, $name, $entity = 1)
  542. {
  543. $value = '';
  544. $sql = "SELECT ".$db->decrypt('value')." as value";
  545. $sql .= " FROM ".MAIN_DB_PREFIX."const";
  546. $sql .= " WHERE name = ".$db->encrypt($name);
  547. $sql .= " AND entity = ".((int) $entity);
  548. dol_syslog("admin.lib::dolibarr_get_const", LOG_DEBUG);
  549. $resql = $db->query($sql);
  550. if ($resql) {
  551. $obj = $db->fetch_object($resql);
  552. if ($obj) {
  553. include_once DOL_DOCUMENT_ROOT.'/core/lib/security.lib.php';
  554. $value = dolDecrypt($obj->value);
  555. }
  556. }
  557. return $value;
  558. }
  559. /**
  560. * Insert a parameter (key,value) into database (delete old key then insert it again).
  561. *
  562. * @param DoliDB $db Database handler
  563. * @param string $name Name of constant
  564. * @param string $value Value of constant
  565. * @param string $type Type of constant. Deprecated, only strings are allowed for $value. Caller must json encode/decode to store other type of data.
  566. * @param int $visible Is constant visible in Setup->Other page (0 by default)
  567. * @param string $note Note on parameter
  568. * @param int $entity Multi company id (0 means all entities)
  569. * @return int -1 if KO, 1 if OK
  570. *
  571. * @see dolibarr_del_const(), dolibarr_get_const(), dol_set_user_param()
  572. */
  573. function dolibarr_set_const($db, $name, $value, $type = 'chaine', $visible = 0, $note = '', $entity = 1)
  574. {
  575. global $conf;
  576. // Clean parameters
  577. $name = trim($name);
  578. // Check parameters
  579. if (empty($name)) {
  580. dol_print_error($db, "Error: Call to function dolibarr_set_const with wrong parameters", LOG_ERR);
  581. exit;
  582. }
  583. //dol_syslog("dolibarr_set_const name=$name, value=$value type=$type, visible=$visible, note=$note entity=$entity");
  584. $db->begin();
  585. $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
  586. $sql .= " WHERE name = ".$db->encrypt($name);
  587. if ($entity >= 0) {
  588. $sql .= " AND entity = ".((int) $entity);
  589. }
  590. dol_syslog("admin.lib::dolibarr_set_const", LOG_DEBUG);
  591. $resql = $db->query($sql);
  592. if (strcmp($value, '')) { // true if different. Must work for $value='0' or $value=0
  593. if (!preg_match('/^(MAIN_LOGEVENTS|MAIN_AGENDA_ACTIONAUTO)/', $name) && (preg_match('/(_KEY|_EXPORTKEY|_SECUREKEY|_SERVERKEY|_PASS|_PASSWORD|_PW|_PW_TICKET|_PW_EMAILING|_SECRET|_SECURITY_TOKEN|_WEB_TOKEN)$/', $name))) {
  594. // This seems a sensitive constant, we encrypt its value
  595. // To list all sensitive constant, you can make a
  596. // WHERE name like '%\_KEY' or name like '%\_EXPORTKEY' or name like '%\_SECUREKEY' or name like '%\_SERVERKEY' or name like '%\_PASS' or name like '%\_PASSWORD' or name like '%\_SECRET'
  597. // or name like '%\_SECURITY_TOKEN' or name like '%\WEB_TOKEN'
  598. include_once DOL_DOCUMENT_ROOT.'/core/lib/security.lib.php';
  599. $newvalue = dolEncrypt($value);
  600. } else {
  601. $newvalue = $value;
  602. }
  603. $sql = "INSERT INTO ".MAIN_DB_PREFIX."const(name, value, type, visible, note, entity)";
  604. $sql .= " VALUES (";
  605. $sql .= $db->encrypt($name);
  606. $sql .= ", ".$db->encrypt($newvalue);
  607. $sql .= ", '".$db->escape($type)."', ".((int) $visible).", '".$db->escape($note)."', ".((int) $entity).")";
  608. //print "sql".$value."-".pg_escape_string($value)."-".$sql;exit;
  609. //print "xx".$db->escape($value);
  610. dol_syslog("admin.lib::dolibarr_set_const", LOG_DEBUG);
  611. $resql = $db->query($sql);
  612. }
  613. if ($resql) {
  614. $db->commit();
  615. $conf->global->$name = $value;
  616. return 1;
  617. } else {
  618. $error = $db->lasterror();
  619. $db->rollback();
  620. return -1;
  621. }
  622. }
  623. /**
  624. * Prepare array with list of tabs
  625. *
  626. * @param int $nbofactivatedmodules Number if activated modules
  627. * @param int $nboftotalmodules Nb of total modules
  628. * @param int $nbmodulesnotautoenabled Nb of modules not auto enabled that are activated
  629. * @return array Array of tabs to show
  630. */
  631. function modules_prepare_head($nbofactivatedmodules, $nboftotalmodules, $nbmodulesnotautoenabled)
  632. {
  633. global $langs, $conf, $user, $form;
  634. $desc = $langs->trans("ModulesDesc", '{picto}');
  635. $desc = str_replace('{picto}', img_picto('', 'switch_off'), $desc);
  636. $h = 0;
  637. $head = array();
  638. $mode = empty($conf->global->MAIN_MODULE_SETUP_ON_LIST_BY_DEFAULT) ? 'commonkanban' : $conf->global->MAIN_MODULE_SETUP_ON_LIST_BY_DEFAULT;
  639. $head[$h][0] = DOL_URL_ROOT."/admin/modules.php?mode=".$mode;
  640. if ($nbmodulesnotautoenabled <= getDolGlobalInt('MAIN_MIN_NB_ENABLED_MODULE_FOR_WARNING', 1)) { // If only minimal initial modules enabled)
  641. //$head[$h][1] = $form->textwithpicto($langs->trans("AvailableModules"), $desc);
  642. $head[$h][1] = $langs->trans("AvailableModules");
  643. $head[$h][1] .= $form->textwithpicto('', $langs->trans("YouMustEnableOneModule").'.<br><br><span class="opacitymedium">'.$desc.'</span>', 1, 'warning');
  644. } else {
  645. //$head[$h][1] = $langs->trans("AvailableModules").$form->textwithpicto('<span class="badge marginleftonly">'.$nbofactivatedmodules.' / '.$nboftotalmodules.'</span>', $desc, 1, 'help', '', 1, 3);
  646. $head[$h][1] = $langs->trans("AvailableModules").'<span class="badge marginleftonly">'.$nbofactivatedmodules.' / '.$nboftotalmodules.'</span>';
  647. }
  648. $head[$h][2] = 'modules';
  649. $h++;
  650. $head[$h][0] = DOL_URL_ROOT."/admin/modules.php?mode=marketplace";
  651. $head[$h][1] = $langs->trans("ModulesMarketPlaces");
  652. $head[$h][2] = 'marketplace';
  653. $h++;
  654. $head[$h][0] = DOL_URL_ROOT."/admin/modules.php?mode=deploy";
  655. $head[$h][1] = $langs->trans("AddExtensionThemeModuleOrOther");
  656. $head[$h][2] = 'deploy';
  657. $h++;
  658. $head[$h][0] = DOL_URL_ROOT."/admin/modules.php?mode=develop";
  659. $head[$h][1] = $langs->trans("ModulesDevelopYourModule");
  660. $head[$h][2] = 'develop';
  661. $h++;
  662. return $head;
  663. }
  664. /**
  665. * Prepare array with list of tabs
  666. *
  667. * @return array Array of tabs to show
  668. */
  669. function ihm_prepare_head()
  670. {
  671. global $langs, $conf, $user;
  672. $h = 0;
  673. $head = array();
  674. $head[$h][0] = DOL_URL_ROOT."/admin/ihm.php?mode=other";
  675. $head[$h][1] = $langs->trans("LanguageAndPresentation");
  676. $head[$h][2] = 'other';
  677. $h++;
  678. $head[$h][0] = DOL_URL_ROOT."/admin/ihm.php?mode=template";
  679. $head[$h][1] = $langs->trans("SkinAndColors");
  680. $head[$h][2] = 'template';
  681. $h++;
  682. $head[$h][0] = DOL_URL_ROOT."/admin/ihm.php?mode=dashboard";
  683. $head[$h][1] = $langs->trans("Dashboard");
  684. $head[$h][2] = 'dashboard';
  685. $h++;
  686. $head[$h][0] = DOL_URL_ROOT."/admin/ihm.php?mode=login";
  687. $head[$h][1] = $langs->trans("LoginPage");
  688. $head[$h][2] = 'login';
  689. $h++;
  690. $head[$h][0] = DOL_URL_ROOT."/admin/ihm.php?mode=css";
  691. $head[$h][1] = $langs->trans("CSSPage");
  692. $head[$h][2] = 'css';
  693. $h++;
  694. complete_head_from_modules($conf, $langs, null, $head, $h, 'ihm_admin');
  695. complete_head_from_modules($conf, $langs, null, $head, $h, 'ihm_admin', 'remove');
  696. return $head;
  697. }
  698. /**
  699. * Prepare array with list of tabs
  700. *
  701. * @return array Array of tabs to show
  702. */
  703. function security_prepare_head()
  704. {
  705. global $db, $langs, $conf, $user;
  706. $h = 0;
  707. $head = array();
  708. $head[$h][0] = DOL_URL_ROOT."/admin/security_other.php";
  709. $head[$h][1] = $langs->trans("Miscellaneous");
  710. $head[$h][2] = 'misc';
  711. $h++;
  712. $head[$h][0] = DOL_URL_ROOT."/admin/security.php";
  713. $head[$h][1] = $langs->trans("Passwords");
  714. $head[$h][2] = 'passwords';
  715. $h++;
  716. $head[$h][0] = DOL_URL_ROOT."/admin/security_file.php";
  717. $head[$h][1] = $langs->trans("Files").' ('.$langs->trans("Upload").')';
  718. $head[$h][2] = 'file';
  719. $h++;
  720. /*
  721. $head[$h][0] = DOL_URL_ROOT."/admin/security_file_download.php";
  722. $head[$h][1] = $langs->trans("Files").' ('.$langs->trans("Download").')';
  723. $head[$h][2] = 'filedownload';
  724. $h++;
  725. */
  726. $head[$h][0] = DOL_URL_ROOT."/admin/proxy.php";
  727. $head[$h][1] = $langs->trans("ExternalAccess");
  728. $head[$h][2] = 'proxy';
  729. $h++;
  730. $head[$h][0] = DOL_URL_ROOT."/admin/events.php";
  731. $head[$h][1] = $langs->trans("Audit");
  732. $head[$h][2] = 'audit';
  733. $h++;
  734. // Show permissions lines
  735. $nbPerms = 0;
  736. $sql = "SELECT COUNT(r.id) as nb";
  737. $sql .= " FROM ".MAIN_DB_PREFIX."rights_def as r";
  738. $sql .= " WHERE r.libelle NOT LIKE 'tou%'"; // On ignore droits "tous"
  739. $sql .= " AND entity = ".((int) $conf->entity);
  740. $sql .= " AND bydefault = 1";
  741. if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) {
  742. $sql .= " AND r.perms NOT LIKE '%_advance'"; // Hide advanced perms if option is not enabled
  743. }
  744. $resql = $db->query($sql);
  745. if ($resql) {
  746. $obj = $db->fetch_object($resql);
  747. if ($obj) {
  748. $nbPerms = $obj->nb;
  749. }
  750. } else {
  751. dol_print_error($db);
  752. }
  753. $head[$h][0] = DOL_URL_ROOT."/admin/perms.php";
  754. $head[$h][1] = $langs->trans("DefaultRights");
  755. if ($nbPerms > 0) {
  756. $head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? '<span class="badge marginleftonlyshort">'.$nbPerms.'</span>' : '');
  757. }
  758. $head[$h][2] = 'default';
  759. $h++;
  760. return $head;
  761. }
  762. /**
  763. * Prepare array with list of tabs
  764. * @param object $object descriptor class
  765. * @return array Array of tabs to show
  766. */
  767. function modulehelp_prepare_head($object)
  768. {
  769. global $langs, $conf, $user;
  770. $h = 0;
  771. $head = array();
  772. // FIX for compatibity habitual tabs
  773. $object->id = $object->numero;
  774. $head[$h][0] = DOL_URL_ROOT."/admin/modulehelp.php?id=".$object->id.'&mode=desc';
  775. $head[$h][1] = $langs->trans("Description");
  776. $head[$h][2] = 'desc';
  777. $h++;
  778. $head[$h][0] = DOL_URL_ROOT."/admin/modulehelp.php?id=".$object->id.'&mode=feature';
  779. $head[$h][1] = $langs->trans("TechnicalServicesProvided");
  780. $head[$h][2] = 'feature';
  781. $h++;
  782. if ($object->isCoreOrExternalModule() == 'external') {
  783. $head[$h][0] = DOL_URL_ROOT."/admin/modulehelp.php?id=".$object->id.'&mode=changelog';
  784. $head[$h][1] = $langs->trans("ChangeLog");
  785. $head[$h][2] = 'changelog';
  786. $h++;
  787. }
  788. complete_head_from_modules($conf, $langs, $object, $head, $h, 'modulehelp_admin');
  789. complete_head_from_modules($conf, $langs, $object, $head, $h, 'modulehelp_admin', 'remove');
  790. return $head;
  791. }
  792. /**
  793. * Prepare array with list of tabs
  794. *
  795. * @return array Array of tabs to show
  796. */
  797. function translation_prepare_head()
  798. {
  799. global $langs, $conf, $user;
  800. $h = 0;
  801. $head = array();
  802. $head[$h][0] = DOL_URL_ROOT."/admin/translation.php?mode=searchkey";
  803. $head[$h][1] = $langs->trans("TranslationKeySearch");
  804. $head[$h][2] = 'searchkey';
  805. $h++;
  806. $head[$h][0] = DOL_URL_ROOT."/admin/translation.php?mode=overwrite";
  807. $head[$h][1] = '<span class="valignmiddle">'.$langs->trans("TranslationOverwriteKey").'</span><span class="fa fa-plus-circle valignmiddle paddingleft"></span>';
  808. $head[$h][2] = 'overwrite';
  809. $h++;
  810. complete_head_from_modules($conf, $langs, null, $head, $h, 'translation_admin');
  811. complete_head_from_modules($conf, $langs, null, $head, $h, 'translation_admin', 'remove');
  812. return $head;
  813. }
  814. /**
  815. * Prepare array with list of tabs
  816. *
  817. * @return array Array of tabs to show
  818. */
  819. function defaultvalues_prepare_head()
  820. {
  821. global $langs, $conf, $user;
  822. $h = 0;
  823. $head = array();
  824. $head[$h][0] = DOL_URL_ROOT."/admin/defaultvalues.php?mode=createform";
  825. $head[$h][1] = $langs->trans("DefaultCreateForm");
  826. $head[$h][2] = 'createform';
  827. $h++;
  828. $head[$h][0] = DOL_URL_ROOT."/admin/defaultvalues.php?mode=filters";
  829. $head[$h][1] = $langs->trans("DefaultSearchFilters");
  830. $head[$h][2] = 'filters';
  831. $h++;
  832. $head[$h][0] = DOL_URL_ROOT."/admin/defaultvalues.php?mode=sortorder";
  833. $head[$h][1] = $langs->trans("DefaultSortOrder");
  834. $head[$h][2] = 'sortorder';
  835. $h++;
  836. if (!empty($conf->use_javascript_ajax)) {
  837. $head[$h][0] = DOL_URL_ROOT."/admin/defaultvalues.php?mode=focus";
  838. $head[$h][1] = $langs->trans("DefaultFocus");
  839. $head[$h][2] = 'focus';
  840. $h++;
  841. $head[$h][0] = DOL_URL_ROOT."/admin/defaultvalues.php?mode=mandatory";
  842. $head[$h][1] = $langs->trans("DefaultMandatory");
  843. $head[$h][2] = 'mandatory';
  844. $h++;
  845. }
  846. /*$head[$h][0] = DOL_URL_ROOT."/admin/translation.php?mode=searchkey";
  847. $head[$h][1] = $langs->trans("TranslationKeySearch");
  848. $head[$h][2] = 'searchkey';
  849. $h++;*/
  850. complete_head_from_modules($conf, $langs, null, $head, $h, 'defaultvalues_admin');
  851. complete_head_from_modules($conf, $langs, null, $head, $h, 'defaultvalues_admin', 'remove');
  852. return $head;
  853. }
  854. /**
  855. * Return list of session
  856. *
  857. * @return array Array list of sessions
  858. */
  859. function listOfSessions()
  860. {
  861. global $conf;
  862. $arrayofSessions = array();
  863. // session.save_path can be returned empty so we set a default location and work from there
  864. $sessPath = '/tmp';
  865. $iniPath = ini_get("session.save_path");
  866. if ($iniPath) {
  867. $sessPath = $iniPath;
  868. }
  869. $sessPath .= '/'; // We need the trailing slash
  870. dol_syslog('admin.lib:listOfSessions sessPath='.$sessPath);
  871. $dh = @opendir(dol_osencode($sessPath));
  872. if ($dh) {
  873. while (($file = @readdir($dh)) !== false) {
  874. if (preg_match('/^sess_/i', $file) && $file != "." && $file != "..") {
  875. $fullpath = $sessPath.$file;
  876. if (!@is_dir($fullpath) && is_readable($fullpath)) {
  877. $sessValues = file_get_contents($fullpath); // get raw session data
  878. // Example of possible value
  879. //$sessValues = 'newtoken|s:32:"1239f7a0c4b899200fe9ca5ea394f307";dol_loginmesg|s:0:"";newtoken|s:32:"1236457104f7ae0f328c2928973f3cb5";dol_loginmesg|s:0:"";token|s:32:"123615ad8d650c5cc4199b9a1a76783f";
  880. // dol_login|s:5:"admin";dol_authmode|s:8:"dolibarr";dol_tz|s:1:"1";dol_tz_string|s:13:"Europe/Berlin";dol_dst|i:0;dol_dst_observed|s:1:"1";dol_dst_first|s:0:"";dol_dst_second|s:0:"";dol_screenwidth|s:4:"1920";
  881. // dol_screenheight|s:3:"971";dol_company|s:12:"MyBigCompany";dol_entity|i:1;mainmenu|s:4:"home";leftmenuopened|s:10:"admintools";idmenu|s:0:"";leftmenu|s:10:"admintools";';
  882. if (preg_match('/dol_login/i', $sessValues) && // limit to dolibarr session
  883. (preg_match('/dol_entity\|i:'.$conf->entity.';/i', $sessValues) || preg_match('/dol_entity\|s:([0-9]+):"'.$conf->entity.'"/i', $sessValues)) && // limit to current entity
  884. preg_match('/dol_company\|s:([0-9]+):"('.getDolGlobalString('MAIN_INFO_SOCIETE_NOM').')"/i', $sessValues)) { // limit to company name
  885. $tmp = explode('_', $file);
  886. $idsess = $tmp[1];
  887. $regs = array();
  888. $loginfound = preg_match('/dol_login\|s:[0-9]+:"([A-Za-z0-9]+)"/i', $sessValues, $regs);
  889. if ($loginfound) {
  890. $arrayofSessions[$idsess]["login"] = $regs[1];
  891. }
  892. $arrayofSessions[$idsess]["age"] = time() - filectime($fullpath);
  893. $arrayofSessions[$idsess]["creation"] = filectime($fullpath);
  894. $arrayofSessions[$idsess]["modification"] = filemtime($fullpath);
  895. $arrayofSessions[$idsess]["raw"] = $sessValues;
  896. }
  897. }
  898. }
  899. }
  900. @closedir($dh);
  901. }
  902. return $arrayofSessions;
  903. }
  904. /**
  905. * Purge existing sessions
  906. *
  907. * @param int $mysessionid To avoid to try to delete my own session
  908. * @return int >0 if OK, <0 if KO
  909. */
  910. function purgeSessions($mysessionid)
  911. {
  912. global $conf;
  913. $sessPath = ini_get("session.save_path")."/";
  914. dol_syslog('admin.lib:purgeSessions mysessionid='.$mysessionid.' sessPath='.$sessPath);
  915. $error = 0;
  916. $dh = @opendir(dol_osencode($sessPath));
  917. if ($dh) {
  918. while (($file = @readdir($dh)) !== false) {
  919. if ($file != "." && $file != "..") {
  920. $fullpath = $sessPath.$file;
  921. if (!@is_dir($fullpath)) {
  922. $sessValues = file_get_contents($fullpath); // get raw session data
  923. if (preg_match('/dol_login/i', $sessValues) && // limit to dolibarr session
  924. preg_match('/dol_entity\|s:([0-9]+):"('.$conf->entity.')"/i', $sessValues) && // limit to current entity
  925. preg_match('/dol_company\|s:([0-9]+):"('.$conf->global->MAIN_INFO_SOCIETE_NOM.')"/i', $sessValues)) { // limit to company name
  926. $tmp = explode('_', $file);
  927. $idsess = $tmp[1];
  928. // We remove session if it's not ourself
  929. if ($idsess != $mysessionid) {
  930. $res = @unlink($fullpath);
  931. if (!$res) {
  932. $error++;
  933. }
  934. }
  935. }
  936. }
  937. }
  938. }
  939. @closedir($dh);
  940. }
  941. if (!$error) {
  942. return 1;
  943. } else {
  944. return -$error;
  945. }
  946. }
  947. /**
  948. * Enable a module
  949. *
  950. * @param string $value Name of module to activate
  951. * @param int $withdeps Activate/Disable also all dependencies
  952. * @param int $noconfverification Remove verification of $conf variable for module
  953. * @return array array('nbmodules'=>nb modules activated with success, 'errors=>array of error messages, 'nbperms'=>Nb permission added);
  954. */
  955. function activateModule($value, $withdeps = 1, $noconfverification = 0)
  956. {
  957. global $db, $langs, $conf, $mysoc;
  958. $ret = array();
  959. // Check parameters
  960. if (empty($value)) {
  961. $ret['errors'][] = 'ErrorBadParameter';
  962. return $ret;
  963. }
  964. $ret = array('nbmodules'=>0, 'errors'=>array(), 'nbperms'=>0);
  965. $modName = $value;
  966. $modFile = $modName.".class.php";
  967. // Loop on each directory to fill $modulesdir
  968. $modulesdir = dolGetModulesDirs();
  969. // Loop on each modulesdir directories
  970. $found = false;
  971. foreach ($modulesdir as $dir) {
  972. if (file_exists($dir.$modFile)) {
  973. $found = @include_once $dir.$modFile;
  974. if ($found) {
  975. break;
  976. }
  977. }
  978. }
  979. $objMod = new $modName($db);
  980. // Test if PHP version ok
  981. $verphp = versionphparray();
  982. $vermin = isset($objMod->phpmin) ? $objMod->phpmin : 0;
  983. if (is_array($vermin) && versioncompare($verphp, $vermin) < 0) {
  984. $ret['errors'][] = $langs->trans("ErrorModuleRequirePHPVersion", versiontostring($vermin));
  985. return $ret;
  986. }
  987. // Test if Dolibarr version ok
  988. $verdol = versiondolibarrarray();
  989. $vermin = isset($objMod->need_dolibarr_version) ? $objMod->need_dolibarr_version : 0;
  990. //print 'version: '.versioncompare($verdol,$vermin).' - '.join(',',$verdol).' - '.join(',',$vermin);exit;
  991. if (is_array($vermin) && versioncompare($verdol, $vermin) < 0) {
  992. $ret['errors'][] = $langs->trans("ErrorModuleRequireDolibarrVersion", versiontostring($vermin));
  993. return $ret;
  994. }
  995. // Test if javascript requirement ok
  996. if (!empty($objMod->need_javascript_ajax) && empty($conf->use_javascript_ajax)) {
  997. $ret['errors'][] = $langs->trans("ErrorModuleRequireJavascript");
  998. return $ret;
  999. }
  1000. $const_name = $objMod->const_name;
  1001. if ($noconfverification == 0) {
  1002. if (!empty($conf->global->$const_name)) {
  1003. return $ret;
  1004. }
  1005. }
  1006. $result = $objMod->init(); // Enable module
  1007. if ($result <= 0) {
  1008. $ret['errors'][] = $objMod->error;
  1009. } else {
  1010. if ($withdeps) {
  1011. if (isset($objMod->depends) && is_array($objMod->depends) && !empty($objMod->depends)) {
  1012. // Activation of modules this module depends on
  1013. // this->depends may be array('modModule1', 'mmodModule2') or array('always'=>array('modModule1'), 'FR'=>array('modModule2"))
  1014. foreach ($objMod->depends as $key => $modulestringorarray) {
  1015. //var_dump((! is_numeric($key)) && ! preg_match('/^always/', $key) && $mysoc->country_code && ! preg_match('/^'.$mysoc->country_code.'/', $key));exit;
  1016. if ((!is_numeric($key)) && !preg_match('/^always/', $key) && $mysoc->country_code && !preg_match('/^'.$mysoc->country_code.'/', $key)) {
  1017. dol_syslog("We are not concerned by dependency with key=".$key." because our country is ".$mysoc->country_code);
  1018. continue;
  1019. }
  1020. if (!is_array($modulestringorarray)) {
  1021. $modulestringorarray = array($modulestringorarray);
  1022. }
  1023. foreach ($modulestringorarray as $modulestring) {
  1024. $activate = false;
  1025. $activateerr = '';
  1026. foreach ($modulesdir as $dir) {
  1027. if (file_exists($dir.$modulestring.".class.php")) {
  1028. $resarray = activateModule($modulestring);
  1029. if (empty($resarray['errors'])) {
  1030. $activate = true;
  1031. } else {
  1032. $activateerr = join(', ', $resarray['errors']);
  1033. foreach ($resarray['errors'] as $errorMessage) {
  1034. dol_syslog($errorMessage, LOG_ERR);
  1035. }
  1036. }
  1037. break;
  1038. }
  1039. }
  1040. if ($activate) {
  1041. $ret['nbmodules'] += $resarray['nbmodules'];
  1042. $ret['nbperms'] += $resarray['nbperms'];
  1043. } else {
  1044. if ($activateerr) {
  1045. $ret['errors'][] = $activateerr;
  1046. }
  1047. $ret['errors'][] = $langs->trans('activateModuleDependNotSatisfied', $objMod->name, $modulestring);
  1048. }
  1049. }
  1050. }
  1051. }
  1052. if (isset($objMod->conflictwith) && is_array($objMod->conflictwith) && !empty($objMod->conflictwith)) {
  1053. // Desactivation des modules qui entrent en conflit
  1054. $num = count($objMod->conflictwith);
  1055. for ($i = 0; $i < $num; $i++) {
  1056. foreach ($modulesdir as $dir) {
  1057. if (file_exists($dir.$objMod->conflictwith[$i].".class.php")) {
  1058. unActivateModule($objMod->conflictwith[$i], 0);
  1059. }
  1060. }
  1061. }
  1062. }
  1063. }
  1064. }
  1065. if (!count($ret['errors'])) {
  1066. $ret['nbmodules']++;
  1067. $ret['nbperms'] += (is_array($objMod->rights)?count($objMod->rights):0);
  1068. }
  1069. return $ret;
  1070. }
  1071. /**
  1072. * Disable a module
  1073. *
  1074. * @param string $value Nom du module a desactiver
  1075. * @param int $requiredby 1=Desactive aussi modules dependants
  1076. * @return string Error message or '';
  1077. */
  1078. function unActivateModule($value, $requiredby = 1)
  1079. {
  1080. global $db, $modules, $conf;
  1081. // Check parameters
  1082. if (empty($value)) {
  1083. return 'ErrorBadParameter';
  1084. }
  1085. $ret = '';
  1086. $modName = $value;
  1087. $modFile = $modName.".class.php";
  1088. // Loop on each directory to fill $modulesdir
  1089. $modulesdir = dolGetModulesDirs();
  1090. // Loop on each modulesdir directories
  1091. $found = false;
  1092. foreach ($modulesdir as $dir) {
  1093. if (file_exists($dir.$modFile)) {
  1094. $found = @include_once $dir.$modFile;
  1095. if ($found) {
  1096. break;
  1097. }
  1098. }
  1099. }
  1100. if ($found) {
  1101. $objMod = new $modName($db);
  1102. $result = $objMod->remove();
  1103. if ($result <= 0) {
  1104. $ret = $objMod->error;
  1105. }
  1106. } else // We come here when we try to unactivate a module when module does not exists anymore in sources
  1107. {
  1108. //print $dir.$modFile;exit;
  1109. // TODO Replace this after DolibarrModules is moved as abstract class with a try catch to show module we try to disable has not been found or could not be loaded
  1110. include_once DOL_DOCUMENT_ROOT.'/core/modules/DolibarrModules.class.php';
  1111. $genericMod = new DolibarrModules($db);
  1112. $genericMod->name = preg_replace('/^mod/i', '', $modName);
  1113. $genericMod->rights_class = strtolower(preg_replace('/^mod/i', '', $modName));
  1114. $genericMod->const_name = 'MAIN_MODULE_'.strtoupper(preg_replace('/^mod/i', '', $modName));
  1115. dol_syslog("modules::unActivateModule Failed to find module file, we use generic function with name ".$modName);
  1116. $genericMod->remove('');
  1117. }
  1118. // Disable modules that depends on module we disable
  1119. if (!$ret && $requiredby && is_object($objMod) && is_array($objMod->requiredby)) {
  1120. $countrb = count($objMod->requiredby);
  1121. for ($i = 0; $i < $countrb; $i++) {
  1122. //var_dump($objMod->requiredby[$i]);
  1123. unActivateModule($objMod->requiredby[$i]);
  1124. }
  1125. }
  1126. return $ret;
  1127. }
  1128. /**
  1129. * Add external modules to list of dictionaries.
  1130. * Addition is done into var $taborder, $tabname, etc... that are passed with pointers.
  1131. *
  1132. * @param array $taborder Taborder
  1133. * @param array $tabname Tabname
  1134. * @param array $tablib Tablib
  1135. * @param array $tabsql Tabsql
  1136. * @param array $tabsqlsort Tabsqlsort
  1137. * @param array $tabfield Tabfield
  1138. * @param array $tabfieldvalue Tabfieldvalue
  1139. * @param array $tabfieldinsert Tabfieldinsert
  1140. * @param array $tabrowid Tabrowid
  1141. * @param array $tabcond Tabcond
  1142. * @param array $tabhelp Tabhelp
  1143. * @param array $tabcomplete Tab complete (will replace all other in future). Key is table name.
  1144. * @return int 1
  1145. */
  1146. function complete_dictionary_with_modules(&$taborder, &$tabname, &$tablib, &$tabsql, &$tabsqlsort, &$tabfield, &$tabfieldvalue, &$tabfieldinsert, &$tabrowid, &$tabcond, &$tabhelp, &$tabcomplete)
  1147. {
  1148. global $db, $modules, $conf, $langs;
  1149. dol_syslog("complete_dictionary_with_modules Search external modules to complete the list of dictionnary tables", LOG_DEBUG, 1);
  1150. // Search modules
  1151. $modulesdir = dolGetModulesDirs();
  1152. $i = 0; // is a sequencer of modules found
  1153. $j = 0; // j is module number. Automatically affected if module number not defined.
  1154. foreach ($modulesdir as $dir) {
  1155. // Load modules attributes in arrays (name, numero, orders) from dir directory
  1156. //print $dir."\n<br>";
  1157. dol_syslog("Scan directory ".$dir." for modules");
  1158. $handle = @opendir(dol_osencode($dir));
  1159. if (is_resource($handle)) {
  1160. while (($file = readdir($handle)) !== false) {
  1161. //print "$i ".$file."\n<br>";
  1162. if (is_readable($dir.$file) && substr($file, 0, 3) == 'mod' && substr($file, dol_strlen($file) - 10) == '.class.php') {
  1163. $modName = substr($file, 0, dol_strlen($file) - 10);
  1164. if ($modName) {
  1165. include_once $dir.$file;
  1166. $objMod = new $modName($db);
  1167. if ($objMod->numero > 0) {
  1168. $j = $objMod->numero;
  1169. } else {
  1170. $j = 1000 + $i;
  1171. }
  1172. $modulequalified = 1;
  1173. // We discard modules according to features level (PS: if module is activated we always show it)
  1174. $const_name = 'MAIN_MODULE_'.strtoupper(preg_replace('/^mod/i', '', get_class($objMod)));
  1175. if ($objMod->version == 'development' && getDolGlobalInt('MAIN_FEATURES_LEVEL') < 2 && empty(getDolGlobalString($const_name))) {
  1176. $modulequalified = 0;
  1177. }
  1178. if ($objMod->version == 'experimental' && getDolGlobalInt('MAIN_FEATURES_LEVEL') < 1 && empty(getDolGlobalString($const_name))) {
  1179. $modulequalified = 0;
  1180. }
  1181. //If module is not activated disqualified
  1182. if (empty(getDolGlobalString($const_name))) {
  1183. $modulequalified = 0;
  1184. }
  1185. if ($modulequalified) {
  1186. // Load languages files of module
  1187. if (isset($objMod->langfiles) && is_array($objMod->langfiles)) {
  1188. foreach ($objMod->langfiles as $langfile) {
  1189. $langs->load($langfile);
  1190. }
  1191. }
  1192. // Complete the arrays &$tabname,&$tablib,&$tabsql,&$tabsqlsort,&$tabfield,&$tabfieldvalue,&$tabfieldinsert,&$tabrowid,&$tabcond
  1193. if (empty($objMod->dictionaries) && !empty($objMod->dictionnaries)) {
  1194. $objMod->dictionaries = $objMod->dictionnaries; // For backward compatibility
  1195. }
  1196. if (!empty($objMod->dictionaries)) {
  1197. //var_dump($objMod->dictionaries['tabname']);
  1198. $nbtabname = $nbtablib = $nbtabsql = $nbtabsqlsort = $nbtabfield = $nbtabfieldvalue = $nbtabfieldinsert = $nbtabrowid = $nbtabcond = $nbtabfieldcheck = $nbtabhelp = 0;
  1199. $tabnamerelwithkey = array();
  1200. foreach ($objMod->dictionaries['tabname'] as $key => $val) {
  1201. $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $val);
  1202. $nbtabname++;
  1203. $taborder[] = max($taborder) + 1;
  1204. $tabname[] = $val;
  1205. $tabnamerelwithkey[$key] = $val;
  1206. $tabcomplete[$tmptablename]['picto'] = $objMod->picto;
  1207. } // Position
  1208. foreach ($objMod->dictionaries['tablib'] as $key => $val) {
  1209. $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]);
  1210. $nbtablib++;
  1211. $tablib[] = $val;
  1212. $tabcomplete[$tmptablename]['lib'] = $val;
  1213. }
  1214. foreach ($objMod->dictionaries['tabsql'] as $key => $val) {
  1215. $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]);
  1216. $nbtabsql++;
  1217. $tabsql[] = $val;
  1218. $tabcomplete[$tmptablename]['sql'] = $val;
  1219. }
  1220. foreach ($objMod->dictionaries['tabsqlsort'] as $key => $val) {
  1221. $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]);
  1222. $nbtabsqlsort++;
  1223. $tabsqlsort[] = $val;
  1224. $tabcomplete[$tmptablename]['sqlsort'] = $val;
  1225. }
  1226. foreach ($objMod->dictionaries['tabfield'] as $key => $val) {
  1227. $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]);
  1228. $nbtabfield++;
  1229. $tabfield[] = $val;
  1230. $tabcomplete[$tmptablename]['field'] = $val;
  1231. }
  1232. foreach ($objMod->dictionaries['tabfieldvalue'] as $key => $val) {
  1233. $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]);
  1234. $nbtabfieldvalue++;
  1235. $tabfieldvalue[] = $val;
  1236. $tabcomplete[$tmptablename]['value'] = $val;
  1237. }
  1238. foreach ($objMod->dictionaries['tabfieldinsert'] as $key => $val) {
  1239. $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]);
  1240. $nbtabfieldinsert++;
  1241. $tabfieldinsert[] = $val;
  1242. $tabcomplete[$tmptablename]['fieldinsert'] = $val;
  1243. }
  1244. foreach ($objMod->dictionaries['tabrowid'] as $key => $val) {
  1245. $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]);
  1246. $nbtabrowid++;
  1247. $tabrowid[] = $val;
  1248. $tabcomplete[$tmptablename]['rowid'] = $val;
  1249. }
  1250. foreach ($objMod->dictionaries['tabcond'] as $key => $val) {
  1251. $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]);
  1252. $nbtabcond++;
  1253. $tabcond[] = $val;
  1254. $tabcomplete[$tmptablename]['rowid'] = $val;
  1255. }
  1256. if (!empty($objMod->dictionaries['tabhelp'])) {
  1257. foreach ($objMod->dictionaries['tabhelp'] as $key => $val) {
  1258. $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]);
  1259. $nbtabhelp++;
  1260. $tabhelp[] = $val;
  1261. $tabcomplete[$tmptablename]['help'] = $val;
  1262. }
  1263. }
  1264. if (!empty($objMod->dictionaries['tabfieldcheck'])) {
  1265. foreach ($objMod->dictionaries['tabfieldcheck'] as $key => $val) {
  1266. $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]);
  1267. $nbtabfieldcheck++;
  1268. $tabcomplete[$tmptablename]['fieldcheck'] = $val;
  1269. }
  1270. }
  1271. if ($nbtabname != $nbtablib || $nbtablib != $nbtabsql || $nbtabsql != $nbtabsqlsort) {
  1272. print 'Error in descriptor of module '.$const_name.'. Array ->dictionaries has not same number of record for key "tabname", "tablib", "tabsql" and "tabsqlsort"';
  1273. //print "$const_name: $nbtabname=$nbtablib=$nbtabsql=$nbtabsqlsort=$nbtabfield=$nbtabfieldvalue=$nbtabfieldinsert=$nbtabrowid=$nbtabcond=$nbtabfieldcheck=$nbtabhelp\n";
  1274. } else {
  1275. $taborder[] = 0; // Add an empty line
  1276. }
  1277. }
  1278. $j++;
  1279. $i++;
  1280. } else {
  1281. dol_syslog("Module ".get_class($objMod)." not qualified");
  1282. }
  1283. }
  1284. }
  1285. }
  1286. closedir($handle);
  1287. } else {
  1288. dol_syslog("htdocs/admin/modules.php: Failed to open directory ".$dir.". See permission and open_basedir option.", LOG_WARNING);
  1289. }
  1290. }
  1291. dol_syslog("", LOG_DEBUG, -1);
  1292. return 1;
  1293. }
  1294. /**
  1295. * Activate external modules mandatory when country is country_code
  1296. *
  1297. * @param string $country_code CountryCode
  1298. * @return int 1
  1299. */
  1300. function activateModulesRequiredByCountry($country_code)
  1301. {
  1302. global $db, $conf, $langs;
  1303. $modulesdir = dolGetModulesDirs();
  1304. foreach ($modulesdir as $dir) {
  1305. // Load modules attributes in arrays (name, numero, orders) from dir directory
  1306. dol_syslog("Scan directory ".$dir." for modules");
  1307. $handle = @opendir(dol_osencode($dir));
  1308. if (is_resource($handle)) {
  1309. while (($file = readdir($handle)) !== false) {
  1310. if (is_readable($dir.$file) && substr($file, 0, 3) == 'mod' && substr($file, dol_strlen($file) - 10) == '.class.php') {
  1311. $modName = substr($file, 0, dol_strlen($file) - 10);
  1312. if ($modName) {
  1313. include_once $dir.$file;
  1314. $objMod = new $modName($db);
  1315. $modulequalified = 1;
  1316. // We discard modules according to features level (PS: if module is activated we always show it)
  1317. $const_name = 'MAIN_MODULE_'.strtoupper(preg_replace('/^mod/i', '', get_class($objMod)));
  1318. if ($objMod->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) {
  1319. $modulequalified = 0;
  1320. }
  1321. if ($objMod->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) {
  1322. $modulequalified = 0;
  1323. }
  1324. if (!empty($conf->global->$const_name)) {
  1325. $modulequalified = 0; // already activated
  1326. }
  1327. if ($modulequalified) {
  1328. // Load languages files of module
  1329. if (isset($objMod->automatic_activation) && is_array($objMod->automatic_activation) && isset($objMod->automatic_activation[$country_code])) {
  1330. activateModule($modName);
  1331. setEventMessages($objMod->automatic_activation[$country_code], null, 'warnings');
  1332. }
  1333. } else {
  1334. dol_syslog("Module ".get_class($objMod)." not qualified");
  1335. }
  1336. }
  1337. }
  1338. }
  1339. closedir($handle);
  1340. } else {
  1341. dol_syslog("htdocs/admin/modules.php: Failed to open directory ".$dir.". See permission and open_basedir option.", LOG_WARNING);
  1342. }
  1343. }
  1344. return 1;
  1345. }
  1346. /**
  1347. * Search external modules to complete the list of contact element
  1348. *
  1349. * @param array $elementList elementList
  1350. * @return int 1
  1351. */
  1352. function complete_elementList_with_modules(&$elementList)
  1353. {
  1354. global $db, $modules, $conf, $langs;
  1355. // Search modules
  1356. $filename = array();
  1357. $modules = array();
  1358. $orders = array();
  1359. $categ = array();
  1360. $dirmod = array();
  1361. $i = 0; // is a sequencer of modules found
  1362. $j = 0; // j is module number. Automatically affected if module number not defined.
  1363. dol_syslog("complete_elementList_with_modules Search external modules to complete the list of contact element", LOG_DEBUG, 1);
  1364. $modulesdir = dolGetModulesDirs();
  1365. foreach ($modulesdir as $dir) {
  1366. // Load modules attributes in arrays (name, numero, orders) from dir directory
  1367. //print $dir."\n<br>";
  1368. dol_syslog("Scan directory ".$dir." for modules");
  1369. $handle = @opendir(dol_osencode($dir));
  1370. if (is_resource($handle)) {
  1371. while (($file = readdir($handle)) !== false) {
  1372. //print "$i ".$file."\n<br>";
  1373. if (is_readable($dir.$file) && substr($file, 0, 3) == 'mod' && substr($file, dol_strlen($file) - 10) == '.class.php') {
  1374. $modName = substr($file, 0, dol_strlen($file) - 10);
  1375. if ($modName) {
  1376. include_once $dir.$file;
  1377. $objMod = new $modName($db);
  1378. if ($objMod->numero > 0) {
  1379. $j = $objMod->numero;
  1380. } else {
  1381. $j = 1000 + $i;
  1382. }
  1383. $modulequalified = 1;
  1384. // We discard modules according to features level (PS: if module is activated we always show it)
  1385. $const_name = 'MAIN_MODULE_'.strtoupper(preg_replace('/^mod/i', '', get_class($objMod)));
  1386. if ($objMod->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2 && getDolGlobalString($const_name)) {
  1387. $modulequalified = 0;
  1388. }
  1389. if ($objMod->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1 && getDolGlobalString($const_name)) {
  1390. $modulequalified = 0;
  1391. }
  1392. //If module is not activated disqualified
  1393. if (empty($conf->global->$const_name)) {
  1394. $modulequalified = 0;
  1395. }
  1396. if ($modulequalified) {
  1397. // Load languages files of module
  1398. if (isset($objMod->langfiles) && is_array($objMod->langfiles)) {
  1399. foreach ($objMod->langfiles as $langfile) {
  1400. $langs->load($langfile);
  1401. }
  1402. }
  1403. $modules[$i] = $objMod;
  1404. $filename[$i] = $modName;
  1405. $orders[$i] = $objMod->family."_".$j; // Sort on family then module number
  1406. $dirmod[$i] = $dir;
  1407. //print "x".$modName." ".$orders[$i]."\n<br>";
  1408. if (!empty($objMod->module_parts['contactelement'])) {
  1409. if (is_array($objMod->module_parts['contactelement'])) {
  1410. foreach ($objMod->module_parts['contactelement'] as $elem => $title) {
  1411. $elementList[$elem] = $langs->trans($title);
  1412. }
  1413. } else {
  1414. $elementList[$objMod->name] = $langs->trans($objMod->name);
  1415. }
  1416. }
  1417. $j++;
  1418. $i++;
  1419. } else {
  1420. dol_syslog("Module ".get_class($objMod)." not qualified");
  1421. }
  1422. }
  1423. }
  1424. }
  1425. closedir($handle);
  1426. } else {
  1427. dol_syslog("htdocs/admin/modules.php: Failed to open directory ".$dir.". See permission and open_basedir option.", LOG_WARNING);
  1428. }
  1429. }
  1430. dol_syslog("", LOG_DEBUG, -1);
  1431. return 1;
  1432. }
  1433. /**
  1434. * Show array with constants to edit
  1435. *
  1436. * @param array $tableau Array of constants array('key'=>array('type'=>type, 'label'=>label)
  1437. * where type can be 'string', 'text', 'textarea', 'html', 'yesno', 'emailtemplate:xxx', ...
  1438. * @param int $strictw3c 0=Include form into table (deprecated), 1=Form is outside table to respect W3C (deprecated), 2=No form nor button at all, 3=No form nor button at all and each field has a unique name (form is output by caller, recommended)
  1439. * @param string $helptext Tooltip help to use for the column name of values
  1440. * @param string $text Text to use for the column name of values
  1441. * @return void
  1442. */
  1443. function form_constantes($tableau, $strictw3c = 0, $helptext = '', $text = 'Value')
  1444. {
  1445. global $db, $langs, $conf, $user;
  1446. global $_Avery_Labels;
  1447. $form = new Form($db);
  1448. if (empty($strictw3c)) {
  1449. dol_syslog("Warning: Function form_constantes is calle with parameter strictw3c = 0, this is deprecated. Value must be 2 now.", LOG_DEBUG);
  1450. }
  1451. if (!empty($strictw3c) && $strictw3c == 1) {
  1452. print "\n".'<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
  1453. print '<input type="hidden" name="token" value="'.newToken().'">';
  1454. print '<input type="hidden" name="action" value="updateall">';
  1455. }
  1456. print '<div class="div-table-responsive-no-min">';
  1457. print '<table class="noborder centpercent">';
  1458. print '<tr class="liste_titre">';
  1459. print '<td class="">'.$langs->trans("Description").'</td>';
  1460. print '<td>';
  1461. $text = $langs->trans($text);
  1462. print $form->textwithpicto($text, $helptext, 1, 'help', '', 0, 2, 'idhelptext');
  1463. print '</td>';
  1464. if (empty($strictw3c)) {
  1465. print '<td class="center" width="80">'.$langs->trans("Action").'</td>';
  1466. }
  1467. print "</tr>\n";
  1468. $label = '';
  1469. foreach ($tableau as $key => $const) { // Loop on each param
  1470. $label = '';
  1471. // $const is a const key like 'MYMODULE_ABC'
  1472. if (is_numeric($key)) { // Very old behaviour
  1473. $type = 'string';
  1474. } else {
  1475. if (is_array($const)) {
  1476. $type = $const['type'];
  1477. $label = $const['label'];
  1478. $const = $key;
  1479. } else {
  1480. $type = $const;
  1481. $const = $key;
  1482. }
  1483. }
  1484. $sql = "SELECT ";
  1485. $sql .= "rowid";
  1486. $sql .= ", ".$db->decrypt('name')." as name";
  1487. $sql .= ", ".$db->decrypt('value')." as value";
  1488. $sql .= ", type";
  1489. $sql .= ", note";
  1490. $sql .= " FROM ".MAIN_DB_PREFIX."const";
  1491. $sql .= " WHERE ".$db->decrypt('name')." = '".$db->escape($const)."'";
  1492. $sql .= " AND entity IN (0, ".$conf->entity.")";
  1493. $sql .= " ORDER BY name ASC, entity DESC";
  1494. $result = $db->query($sql);
  1495. dol_syslog("List params", LOG_DEBUG);
  1496. if ($result) {
  1497. $obj = $db->fetch_object($result); // Take first result of select
  1498. if (empty($obj)) { // If not yet into table
  1499. $obj = (object) array('rowid'=>'', 'name'=>$const, 'value'=>'', 'type'=>$type, 'note'=>'');
  1500. }
  1501. if (empty($strictw3c)) {
  1502. print "\n".'<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
  1503. print '<input type="hidden" name="token" value="'.newToken().'">';
  1504. print '<input type="hidden" name="page_y" value="'.newToken().'">';
  1505. }
  1506. print '<tr class="oddeven">';
  1507. // Show label of parameter
  1508. print '<td>';
  1509. if (empty($strictw3c)) {
  1510. print '<input type="hidden" name="action" value="update">';
  1511. }
  1512. print '<input type="hidden" name="rowid'.(empty($strictw3c) ? '' : '[]').'" value="'.$obj->rowid.'">';
  1513. print '<input type="hidden" name="constname'.(empty($strictw3c) ? '' : '[]').'" value="'.$const.'">';
  1514. print '<input type="hidden" name="constnote_'.$obj->name.'" value="'.nl2br(dol_escape_htmltag($obj->note)).'">';
  1515. print '<input type="hidden" name="consttype_'.$obj->name.'" value="'.($obj->type ? $obj->type : 'string').'">';
  1516. if (!empty($tableau[$key]['tooltip'])) {
  1517. print $form->textwithpicto($label ? $label : $langs->trans('Desc'.$const), $tableau[$key]['tooltip']);
  1518. } else {
  1519. print ($label ? $label : $langs->trans('Desc'.$const));
  1520. }
  1521. if ($const == 'ADHERENT_MAILMAN_URL') {
  1522. print '. '.$langs->trans("Example").': <a href="#" id="exampleclick1">'.img_down().'</a><br>';
  1523. //print 'http://lists.exampe.com/cgi-bin/mailman/admin/%LISTE%/members?adminpw=%MAILMAN_ADMINPW%&subscribees=%EMAIL%&send_welcome_msg_to_this_batch=1';
  1524. print '<div id="example1" class="hidden">';
  1525. print 'http://lists.example.com/cgi-bin/mailman/admin/%LISTE%/members/add?subscribees_upload=%EMAIL%&amp;adminpw=%MAILMAN_ADMINPW%&amp;subscribe_or_invite=0&amp;send_welcome_msg_to_this_batch=0&amp;notification_to_list_owner=0';
  1526. print '</div>';
  1527. } elseif ($const == 'ADHERENT_MAILMAN_UNSUB_URL') {
  1528. print '. '.$langs->trans("Example").': <a href="#" id="exampleclick2">'.img_down().'</a><br>';
  1529. print '<div id="example2" class="hidden">';
  1530. print 'http://lists.example.com/cgi-bin/mailman/admin/%LISTE%/members/remove?unsubscribees_upload=%EMAIL%&amp;adminpw=%MAILMAN_ADMINPW%&amp;send_unsub_ack_to_this_batch=0&amp;send_unsub_notifications_to_list_owner=0';
  1531. print '</div>';
  1532. //print 'http://lists.example.com/cgi-bin/mailman/admin/%LISTE%/members/remove?adminpw=%MAILMAN_ADMINPW%&unsubscribees=%EMAIL%';
  1533. } elseif ($const == 'ADHERENT_MAILMAN_LISTS') {
  1534. print '. '.$langs->trans("Example").': <a href="#" id="exampleclick3">'.img_down().'</a><br>';
  1535. print '<div id="example3" class="hidden">';
  1536. print 'mymailmanlist<br>';
  1537. print 'mymailmanlist1,mymailmanlist2<br>';
  1538. print 'TYPE:Type1:mymailmanlist1,TYPE:Type2:mymailmanlist2<br>';
  1539. if (isModEnabled('categorie')) {
  1540. print 'CATEG:Categ1:mymailmanlist1,CATEG:Categ2:mymailmanlist2<br>';
  1541. }
  1542. print '</div>';
  1543. //print 'http://lists.example.com/cgi-bin/mailman/admin/%LISTE%/members/remove?adminpw=%MAILMAN_ADMINPW%&unsubscribees=%EMAIL%';
  1544. } elseif (in_array($const, ['ADHERENT_MAIL_FROM', 'ADHERENT_CC_MAIL_FROM'])) {
  1545. print ' '.img_help(1, $langs->trans("EMailHelpMsgSPFDKIM"));
  1546. }
  1547. print "</td>\n";
  1548. // Value
  1549. if ($const == 'ADHERENT_CARD_TYPE' || $const == 'ADHERENT_ETIQUETTE_TYPE') {
  1550. print '<td>';
  1551. // List of possible labels (defined into $_Avery_Labels variable set into format_cards.lib.php)
  1552. require_once DOL_DOCUMENT_ROOT.'/core/lib/format_cards.lib.php';
  1553. $arrayoflabels = array();
  1554. foreach (array_keys($_Avery_Labels) as $codecards) {
  1555. $arrayoflabels[$codecards] = $_Avery_Labels[$codecards]['name'];
  1556. }
  1557. print $form->selectarray('constvalue'.(empty($strictw3c) ? '' : ($strictw3c == 3 ? '_'.$const : '[]')), $arrayoflabels, ($obj->value ? $obj->value : 'CARD'), 1, 0, 0);
  1558. print '<input type="hidden" name="consttype" value="yesno">';
  1559. print '<input type="hidden" name="constnote'.(empty($strictw3c) ? '' : '[]').'" value="'.nl2br(dol_escape_htmltag($obj->note)).'">';
  1560. print '</td>';
  1561. } else {
  1562. print '<td>';
  1563. print '<input type="hidden" name="consttype'.(empty($strictw3c) ? '' : ($strictw3c == 3 ? '_'.$const : '[]')).'" value="'.($obj->type ? $obj->type : 'string').'">';
  1564. print '<input type="hidden" name="constnote'.(empty($strictw3c) ? '' : ($strictw3c == 3 ? '_'.$const : '[]')).'" value="'.nl2br(dol_escape_htmltag($obj->note)).'">';
  1565. if ($obj->type == 'textarea' || in_array($const, array('ADHERENT_CARD_TEXT', 'ADHERENT_CARD_TEXT_RIGHT', 'ADHERENT_ETIQUETTE_TEXT'))) {
  1566. print '<textarea class="flat" name="constvalue'.(empty($strictw3c) ? '' : ($strictw3c == 3 ? '_'.$const : '[]')).'" cols="50" rows="5" wrap="soft">'."\n";
  1567. print $obj->value;
  1568. print "</textarea>\n";
  1569. } elseif ($obj->type == 'html') {
  1570. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  1571. $doleditor = new DolEditor('constvalue'.(empty($strictw3c) ? '' : ($strictw3c == 3 ? '_'.$const : '[]')), $obj->value, '', 160, 'dolibarr_notes', '', false, false, isModEnabled('fckeditor'), ROWS_5, '90%');
  1572. $doleditor->Create();
  1573. } elseif ($obj->type == 'yesno') {
  1574. print $form->selectyesno('constvalue'.(empty($strictw3c) ? '' : ($strictw3c == 3 ? '_'.$const : '[]')), $obj->value, 1);
  1575. } elseif (preg_match('/emailtemplate/', $obj->type)) {
  1576. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  1577. $formmail = new FormMail($db);
  1578. $tmp = explode(':', $obj->type);
  1579. $nboftemplates = $formmail->fetchAllEMailTemplate($tmp[1], $user, null, -1); // We set lang=null to get in priority record with no lang
  1580. //$arraydefaultmessage = $formmail->getEMailTemplate($db, $tmp[1], $user, null, 0, 1, '');
  1581. $arrayofmessagename = array();
  1582. if (is_array($formmail->lines_model)) {
  1583. foreach ($formmail->lines_model as $modelmail) {
  1584. //var_dump($modelmail);
  1585. $moreonlabel = '';
  1586. if (!empty($arrayofmessagename[$modelmail->label])) {
  1587. $moreonlabel = ' <span class="opacitymedium">('.$langs->trans("SeveralLangugeVariatFound").')</span>';
  1588. }
  1589. // The 'label' is the key that is unique if we exclude the language
  1590. $arrayofmessagename[$modelmail->label.':'.$tmp[1]] = $langs->trans(preg_replace('/\(|\)/', '', $modelmail->label)).$moreonlabel;
  1591. }
  1592. }
  1593. //var_dump($arraydefaultmessage);
  1594. //var_dump($arrayofmessagename);
  1595. print $form->selectarray('constvalue'.(empty($strictw3c) ? '' : ($strictw3c == 3 ? '_'.$const : '[]')), $arrayofmessagename, $obj->value.':'.$tmp[1], 'None', 0, 0, '', 0, 0, 0, '', '', 1);
  1596. } elseif (preg_match('/MAIL_FROM$/i', $const)) {
  1597. print img_picto('', 'email', 'class="pictofixedwidth"').'<input type="text" class="flat minwidth300" name="constvalue'.(empty($strictw3c) ? '' : ($strictw3c == 3 ? '_'.$const : '[]')).'" value="'.dol_escape_htmltag($obj->value).'">';
  1598. } else { // type = 'string' ou 'chaine'
  1599. print '<input type="text" class="flat minwidth300" name="constvalue'.(empty($strictw3c) ? '' : ($strictw3c == 3 ? '_'.$const : '[]')).'" value="'.dol_escape_htmltag($obj->value).'">';
  1600. }
  1601. print '</td>';
  1602. }
  1603. // Submit
  1604. if (empty($strictw3c)) {
  1605. print '<td class="center">';
  1606. print '<input type="submit" class="button small reposition" value="'.$langs->trans("Update").'" name="update">';
  1607. print "</td>";
  1608. }
  1609. print "</tr>\n";
  1610. if (empty($strictw3c)) {
  1611. print "</form>\n";
  1612. }
  1613. }
  1614. }
  1615. print '</table>';
  1616. print '</div>';
  1617. if (!empty($strictw3c) && $strictw3c == 1) {
  1618. print '<div align="center"><input type="submit" class="button small reposition" value="'.$langs->trans("Update").'" name="update"></div>';
  1619. print "</form>\n";
  1620. }
  1621. }
  1622. /**
  1623. * Show array with constants to edit
  1624. *
  1625. * @param array $modules Array of all modules
  1626. * @return string HTML string with warning
  1627. */
  1628. function showModulesExludedForExternal($modules)
  1629. {
  1630. global $conf, $langs;
  1631. $text = $langs->trans("OnlyFollowingModulesAreOpenedToExternalUsers");
  1632. $listofmodules = explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL); // List of modules qualified for external user management
  1633. $i = 0;
  1634. if (!empty($modules)) {
  1635. $tmpmodules = dol_sort_array($modules, 'module_position');
  1636. foreach ($tmpmodules as $module) { // Loop on array of modules
  1637. $moduleconst = $module->const_name;
  1638. $modulename = strtolower($module->name);
  1639. //print 'modulename='.$modulename;
  1640. //if (empty($conf->global->$moduleconst)) continue;
  1641. if (!in_array($modulename, $listofmodules)) {
  1642. continue;
  1643. }
  1644. //var_dump($modulename.' - '.$langs->trans('Module'.$module->numero.'Name'));
  1645. if ($i > 0) {
  1646. $text .= ', ';
  1647. } else {
  1648. $text .= ' ';
  1649. }
  1650. $i++;
  1651. $tmptext = $langs->trans('Module'.$module->numero.'Name');
  1652. if ($tmptext != 'Module'.$module->numero.'Name') {
  1653. $text .= $langs->trans('Module'.$module->numero.'Name');
  1654. } else {
  1655. $text .= $langs->trans($module->name);
  1656. }
  1657. }
  1658. }
  1659. return $text;
  1660. }
  1661. /**
  1662. * Add document model used by doc generator
  1663. *
  1664. * @param string $name Model name
  1665. * @param string $type Model type
  1666. * @param string $label Model label
  1667. * @param string $description Model description
  1668. * @return int <0 if KO, >0 if OK
  1669. */
  1670. function addDocumentModel($name, $type, $label = '', $description = '')
  1671. {
  1672. global $db, $conf;
  1673. $db->begin();
  1674. $sql = "INSERT INTO ".MAIN_DB_PREFIX."document_model (nom, type, entity, libelle, description)";
  1675. $sql .= " VALUES ('".$db->escape($name)."','".$db->escape($type)."',".((int) $conf->entity).", ";
  1676. $sql .= ($label ? "'".$db->escape($label)."'" : 'null').", ";
  1677. $sql .= (!empty($description) ? "'".$db->escape($description)."'" : "null");
  1678. $sql .= ")";
  1679. dol_syslog("admin.lib::addDocumentModel", LOG_DEBUG);
  1680. $resql = $db->query($sql);
  1681. if ($resql) {
  1682. $db->commit();
  1683. return 1;
  1684. } else {
  1685. dol_print_error($db);
  1686. $db->rollback();
  1687. return -1;
  1688. }
  1689. }
  1690. /**
  1691. * Delete document model used by doc generator
  1692. *
  1693. * @param string $name Model name
  1694. * @param string $type Model type
  1695. * @return int <0 if KO, >0 if OK
  1696. */
  1697. function delDocumentModel($name, $type)
  1698. {
  1699. global $db, $conf;
  1700. $db->begin();
  1701. $sql = "DELETE FROM ".MAIN_DB_PREFIX."document_model";
  1702. $sql .= " WHERE nom = '".$db->escape($name)."'";
  1703. $sql .= " AND type = '".$db->escape($type)."'";
  1704. $sql .= " AND entity = ".((int) $conf->entity);
  1705. dol_syslog("admin.lib::delDocumentModel", LOG_DEBUG);
  1706. $resql = $db->query($sql);
  1707. if ($resql) {
  1708. $db->commit();
  1709. return 1;
  1710. } else {
  1711. dol_print_error($db);
  1712. $db->rollback();
  1713. return -1;
  1714. }
  1715. }
  1716. /**
  1717. * Return the php_info into an array
  1718. *
  1719. * @return array Array with PHP infos
  1720. */
  1721. function phpinfo_array()
  1722. {
  1723. ob_start();
  1724. phpinfo();
  1725. $phpinfostring = ob_get_contents();
  1726. ob_end_clean();
  1727. $info_arr = array();
  1728. $info_lines = explode("\n", strip_tags($phpinfostring, "<tr><td><h2>"));
  1729. $cat = "General";
  1730. foreach ($info_lines as $line) {
  1731. // new cat?
  1732. $title = array();
  1733. preg_match("~<h2>(.*)</h2>~", $line, $title) ? $cat = $title[1] : null;
  1734. $val = array();
  1735. if (preg_match("~<tr><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td></tr>~", $line, $val)) {
  1736. $info_arr[trim($cat)][trim($val[1])] = $val[2];
  1737. } elseif (preg_match("~<tr><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td></tr>~", $line, $val)) {
  1738. $info_arr[trim($cat)][trim($val[1])] = array("local" => $val[2], "master" => $val[3]);
  1739. }
  1740. }
  1741. return $info_arr;
  1742. }
  1743. /**
  1744. * Return array head with list of tabs to view object informations.
  1745. *
  1746. * @return array head array with tabs
  1747. */
  1748. function company_admin_prepare_head()
  1749. {
  1750. global $langs, $conf;
  1751. $h = 0;
  1752. $head = array();
  1753. $head[$h][0] = DOL_URL_ROOT."/admin/company.php";
  1754. $head[$h][1] = $langs->trans("Company");
  1755. $head[$h][2] = 'company';
  1756. $h++;
  1757. $head[$h][0] = DOL_URL_ROOT."/admin/openinghours.php";
  1758. $head[$h][1] = $langs->trans("OpeningHours");
  1759. $head[$h][2] = 'openinghours';
  1760. $h++;
  1761. $head[$h][0] = DOL_URL_ROOT."/admin/accountant.php";
  1762. $head[$h][1] = $langs->trans("Accountant");
  1763. $head[$h][2] = 'accountant';
  1764. $h++;
  1765. $head[$h][0] = DOL_URL_ROOT."/admin/company_socialnetworks.php";
  1766. $head[$h][1] = $langs->trans("SocialNetworksInformation");
  1767. $head[$h][2] = 'socialnetworks';
  1768. $h++;
  1769. complete_head_from_modules($conf, $langs, null, $head, $h, 'mycompany_admin', 'add');
  1770. complete_head_from_modules($conf, $langs, null, $head, $h, 'mycompany_admin', 'remove');
  1771. return $head;
  1772. }
  1773. /**
  1774. * Return array head with list of tabs to view object informations.
  1775. *
  1776. * @return array head array with tabs
  1777. */
  1778. function email_admin_prepare_head()
  1779. {
  1780. global $langs, $conf, $user;
  1781. $h = 0;
  1782. $head = array();
  1783. if (!empty($user->admin) && (empty($_SESSION['leftmenu']) || $_SESSION['leftmenu'] != 'email_templates')) {
  1784. $head[$h][0] = DOL_URL_ROOT."/admin/mails.php";
  1785. $head[$h][1] = $langs->trans("OutGoingEmailSetup");
  1786. $head[$h][2] = 'common';
  1787. $h++;
  1788. if (isModEnabled('mailing')) {
  1789. $head[$h][0] = DOL_URL_ROOT."/admin/mails_emailing.php";
  1790. $head[$h][1] = $langs->trans("OutGoingEmailSetupForEmailing", $langs->transnoentitiesnoconv("EMailing"));
  1791. $head[$h][2] = 'common_emailing';
  1792. $h++;
  1793. }
  1794. if (isModEnabled('ticket')) {
  1795. $head[$h][0] = DOL_URL_ROOT."/admin/mails_ticket.php";
  1796. $head[$h][1] = $langs->trans("OutGoingEmailSetupForEmailing", $langs->transnoentitiesnoconv("Ticket"));
  1797. $head[$h][2] = 'common_ticket';
  1798. $h++;
  1799. }
  1800. }
  1801. // admin and non admin can view this menu entry, but it is not shown yet when we on user menu "Email templates"
  1802. if (empty($_SESSION['leftmenu']) || $_SESSION['leftmenu'] != 'email_templates') {
  1803. $head[$h][0] = DOL_URL_ROOT."/admin/mails_senderprofile_list.php";
  1804. $head[$h][1] = $langs->trans("EmailSenderProfiles");
  1805. $head[$h][2] = 'senderprofiles';
  1806. $h++;
  1807. }
  1808. $head[$h][0] = DOL_URL_ROOT."/admin/mails_templates.php";
  1809. $head[$h][1] = $langs->trans("EMailTemplates");
  1810. $head[$h][2] = 'templates';
  1811. $h++;
  1812. $head[$h][0] = DOL_URL_ROOT."/admin/mails_ingoing.php";
  1813. $head[$h][1] = $langs->trans("InGoingEmailSetup", $langs->transnoentitiesnoconv("EMailing"));
  1814. $head[$h][2] = 'common_ingoing';
  1815. $h++;
  1816. complete_head_from_modules($conf, $langs, null, $head, $h, 'email_admin', 'remove');
  1817. return $head;
  1818. }