admin.lib.php 72 KB

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