admin.lib.php 67 KB

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