dolibarr 22.0.5
admin.lib.php
Go to the documentation of this file.
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 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
8 * Copyright (C) 2024-2025 Frédéric France <frederic.france@free.fr>
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 3 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 * or see https://www.gnu.org/
23 */
24
30require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
31
39function versiontostring($versionarray)
40{
41 $string = '?';
42 if (isset($versionarray[0])) {
43 $string = $versionarray[0];
44 }
45 if (isset($versionarray[1])) {
46 $string .= '.'.$versionarray[1];
47 }
48 if (isset($versionarray[2])) {
49 $string .= '.'.$versionarray[2];
50 }
51 return $string;
52}
53
71function versioncompare($versionarray1, $versionarray2)
72{
73 $ret = 0;
74 $level = 0;
75 $count1 = count($versionarray1);
76 $count2 = count($versionarray2);
77 $maxcount = max($count1, $count2);
78 while ($level < $maxcount) {
79 $operande1 = isset($versionarray1[$level]) ? $versionarray1[$level] : 0;
80 $operande2 = isset($versionarray2[$level]) ? $versionarray2[$level] : 0;
81 if (preg_match('/alpha|dev/i', $operande1)) {
82 $operande1 = -5;
83 }
84 if (preg_match('/alpha|dev/i', $operande2)) {
85 $operande2 = -5;
86 }
87 if (preg_match('/beta$/i', $operande1)) {
88 $operande1 = -4;
89 }
90 if (preg_match('/beta$/i', $operande2)) {
91 $operande2 = -4;
92 }
93 if (preg_match('/beta([0-9])+/i', $operande1)) {
94 $operande1 = -3;
95 }
96 if (preg_match('/beta([0-9])+/i', $operande2)) {
97 $operande2 = -3;
98 }
99 if (preg_match('/rc$/i', $operande1)) {
100 $operande1 = -2;
101 }
102 if (preg_match('/rc$/i', $operande2)) {
103 $operande2 = -2;
104 }
105 if (preg_match('/rc([0-9])+/i', $operande1)) {
106 $operande1 = -1;
107 }
108 if (preg_match('/rc([0-9])+/i', $operande2)) {
109 $operande2 = -1;
110 }
111 $level++;
112 //print 'level '.$level.' '.$operande1.'-'.$operande2.'<br>';
113 if ($operande1 < $operande2) {
114 $ret = -$level;
115 break;
116 }
117 if ($operande1 > $operande2) {
118 $ret = $level;
119 break;
120 }
121 }
122 //print join('.',$versionarray1).'('.count($versionarray1).') / '.join('.',$versionarray2).'('.count($versionarray2).') => '.$ret.'<br>'."\n";
123 return $ret; // return level=1 if difference is on the main version, level=2 on minor version, level=3 on maintenance version, level=4 on development phase version
124}
125
126
134{
135 return explode('.', PHP_VERSION);
136}
137
145{
146 return preg_split('/[\-\.]/', DOL_VERSION);
147}
148
149
173function run_sql($sqlfile, $silent = 1, $entity = 0, $usesavepoint = 1, $handler = '', $okerror = 'default', $linelengthlimit = 32768, $nocommentremoval = 0, $offsetforchartofaccount = 0, $colspan = 0, $onlysqltoimportwebsite = 0, $database = '')
174{
175 global $db, $conf, $langs;
176
177 dol_syslog("Admin.lib::run_sql run sql file ".$sqlfile." silent=".$silent." entity=".$entity." usesavepoint=".$usesavepoint." handler=".$handler." okerror=".$okerror, LOG_DEBUG);
178
179 if (!is_numeric($linelengthlimit)) {
180 dol_syslog("Admin.lib::run_sql param linelengthlimit is not a numeric", LOG_ERR);
181 return -1;
182 }
183
184 $ok = 0;
185 $error = 0;
186 $i = 0;
187 $buffer = '';
188 $arraysql = array();
189
190 // Get version of database
191 $versionarray = $db->getVersionArray();
192
193 // TODO Restore all sequences "/* new line */\n" into "" in $sqlfile.
194
195 $fp = fopen($sqlfile, "r");
196 if ($fp) {
197 while (!feof($fp)) {
198 // Warning fgets with second parameter that is null or 0 hang.
199 if ($linelengthlimit > 0) {
200 $buf = fgets($fp, $linelengthlimit);
201 } else {
202 $buf = fgets($fp);
203 }
204
205 // Test if request must be ran only for particular database or version (if yes, we must remove the -- comment)
206 $reg = array();
207 if (preg_match('/^--\sV(MYSQL|PGSQL)([^\s]*)/i', $buf, $reg)) {
208 $qualified = 1;
209
210 // restrict on database type
211 if (!empty($reg[1])) {
212 if (!preg_match('/'.preg_quote($reg[1]).'/i', $db->type)) {
213 $qualified = 0;
214 }
215 }
216
217 // restrict on version
218 if ($qualified) {
219 if (!empty($reg[2])) {
220 if (is_numeric($reg[2])) { // This is a version
221 $versionrequest = explode('.', $reg[2]);
222 //var_dump($versionrequest);
223 //var_dump($versionarray);
224 if (!count($versionrequest) || !count($versionarray) || versioncompare($versionrequest, $versionarray) > 0) {
225 $qualified = 0;
226 }
227 } else { // This is a test on a constant. For example when we have -- VMYSQLUTF8UNICODE, we test constant $conf->global->UTF8UNICODE
228 $dbcollation = strtoupper(preg_replace('/_/', '', $conf->db->dolibarr_main_db_collation));
229 //var_dump($reg[2]);
230 //var_dump($dbcollation);
231 if (empty($conf->db->dolibarr_main_db_collation) || ($reg[2] != $dbcollation)) {
232 $qualified = 0;
233 }
234 //var_dump($qualified);
235 }
236 }
237 }
238
239 if ($qualified) {
240 // Version qualified, delete SQL comments
241 $buf = preg_replace('/^--\sV(MYSQL|PGSQL)([^\s]*)/i', '', $buf);
242 //print "Ligne $i qualifi?e par version: ".$buf.'<br>';
243 }
244 }
245
246 // Add line buf to buffer if not a comment
247 if ($nocommentremoval || !preg_match('/^\s*--/', $buf)) {
248 if (empty($nocommentremoval)) {
249 $buf = preg_replace('/([,;ERLT0\‍)])\s+--.*$/i', '\1', $buf); //remove comment on lines that does not start with --, before adding it to the buffer
250 }
251 if ($buffer) {
252 $buffer .= ' ';
253 }
254 $buffer .= trim($buf);
255 }
256
257 //print $buf.'<br>';exit;
258
259 if (preg_match('/;\s*$/', $buffer)) {
260 // If string contains the end of request string (';'), we save it into $arraysql.
261 // Found new request
262 if ($buffer) {
263 $arraysql[$i] = $buffer;
264 }
265 $i++;
266 $buffer = '';
267 }
268 }
269
270 if ($buffer) {
271 $arraysql[$i] = $buffer;
272 }
273 fclose($fp);
274 } else {
275 dol_syslog("Admin.lib::run_sql failed to open file ".$sqlfile, LOG_ERR);
276 }
277
278 // Loop on each request to see if there is a __+MAX_table__ key
279 $listofmaxrowid = array(); // This is a cache table
280 foreach ($arraysql as $i => $sql) {
281 $newsql = $sql;
282
283 // Replace __+MAX_table__ with max of table
284 while (preg_match('/__\+MAX_([A-Za-z0-9_]+)__/i', $newsql, $reg)) {
285 $table = $reg[1];
286 if (!isset($listofmaxrowid[$table])) {
287 //var_dump($db);
288 $sqlgetrowid = 'SELECT MAX(rowid) as max from '.preg_replace('/^llx_/', MAIN_DB_PREFIX, $table);
289 $resql = $db->query($sqlgetrowid);
290 if ($resql) {
291 $obj = $db->fetch_object($resql);
292 $listofmaxrowid[$table] = $obj->max;
293 if (empty($listofmaxrowid[$table])) {
294 $listofmaxrowid[$table] = 0;
295 }
296 } else {
297 if (!$silent) {
298 print '<tr><td class="tdtop"'.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
299 print '<div class="error">'.$langs->trans("Failed to get max rowid for ".$table)."</div>";
300 print '</td></tr>';
301 }
302 $error++;
303 break;
304 }
305 }
306 // Replace __+MAX_llx_table__ with +999
307 $from = '__+MAX_'.$table.'__';
308 $to = '+'.$listofmaxrowid[$table];
309 $newsql = str_replace($from, $to, $newsql);
310 dol_syslog('Admin.lib::run_sql New Request '.($i + 1).' (replacing '.$from.' to '.$to.')', LOG_DEBUG);
311
312 $arraysql[$i] = $newsql;
313 }
314
315 if ($offsetforchartofaccount > 0) {
316 // Replace lines
317 // '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,...'
318 // with
319 // '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,...'
320 // Note: string with 'PCG99-ABREGE','CAPIT', 1234 instead of 'PCG99-ABREGE','CAPIT', '1234' is also supported
321 $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);
322 $newsql = preg_replace('/([,\s])0 \+ '.((int) $offsetforchartofaccount).'/ims', '\1 0', $newsql);
323 //var_dump($newsql);
324 $arraysql[$i] = $newsql;
325
326 // FIXME Because we force the rowid during insert, we must also update the sequence with postgresql by running
327 // SELECT dol_util_rebuild_sequences();
328 }
329 }
330
331 // Loop on each request to execute request
332 $cursorinsert = 0;
333 $listofinsertedrowid = array();
334 $keyforsql = md5($sqlfile);
335 foreach ($arraysql as $i => $sql) {
336 if ($sql) {
337 // Test if the SQL is allowed SQL
338 if ($onlysqltoimportwebsite) {
339 $newsql = str_replace(array("\'"), '__BACKSLASHQUOTE__', $sql); // Replace the \' char
340
341 // Remove all strings contents including the ' so we can analyse SQL instruction only later
342 $l = strlen($newsql);
343 $is = 0;
344 $quoteopen = 0;
345 $newsqlclean = '';
346 while ($is < $l) {
347 $char = $newsql[$is];
348 if ($char == "'") {
349 if ($quoteopen) {
350 $quoteopen--;
351 } else {
352 $quoteopen++;
353 }
354 } elseif (empty($quoteopen)) {
355 $newsqlclean .= $char;
356 }
357 $is++;
358 }
359 $newsqlclean = str_replace(array("null"), '__000__', $newsqlclean);
360 //print $newsqlclean."<br>\n";
361
362 $qualified = 0;
363
364 // A very small control. This can still by bypassed by adding a second SQL request concatenated
365 if (preg_match('/^--/', $newsqlclean)) {
366 $qualified = 1;
367 } elseif (preg_match('/^UPDATE llx_website SET \w+ = \d+\+\d+ WHERE rowid = \d+;$/', $newsqlclean)) {
368 $qualified = 1;
369 } elseif (preg_match('/^INSERT INTO llx_website_page\‍([a-z0-9_\s,]+\‍) VALUES\‍([0-9_\s,\+]+\‍);$/', $newsqlclean)) {
370 // Insert must match
371 // 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, , , , , );
372 $qualified = 1;
373 }
374
375 // Another check to allow some legitimate original urls
376 if (!$qualified) {
377 if (preg_match('/^UPDATE llx_website SET \w+ = \'[a-zA-Z,\s]*\' WHERE rowid = \d+;$/', $sql)) {
378 $qualified = 1;
379 }
380 }
381
382 // We also check content
383 $extractphp = dolKeepOnlyPhpCode($sql);
384 $extractphpold = '';
385
386 // Security analysis
387 $errorphpcheck = checkPHPCode($extractphpold, $extractphp); // Contains the setEventMessages
388 if ($errorphpcheck) {
389 $error++;
390 //print 'Request '.($i + 1)." contains non allowed instructions.<br>\n";
391 //print "newsqlclean = ".$newsqlclean."<br>\n";
392 dol_syslog('Admin.lib::run_sql Request '.($i + 1)." contains PHP code and checking this code returns errorphpcheck='.$errorphpcheck.'", LOG_WARNING);
393 dol_syslog("sql=".$sql, LOG_DEBUG);
394 break;
395 }
396
397
398 if (!$qualified) {
399 $error++;
400 //print 'Request '.($i + 1)." contains non allowed instructions.<br>\n";
401 //print "newsqlclean = ".$newsqlclean."<br>\n";
402 dol_syslog('Admin.lib::run_sql Request '.($i + 1)." contains non allowed instructions.", LOG_WARNING);
403 dol_syslog('$newsqlclean='.$newsqlclean, LOG_DEBUG);
404 break;
405 }
406 }
407
408 // Replace the prefix tables
409 if (MAIN_DB_PREFIX != 'llx_') {
410 $sql = preg_replace('/llx_/i', MAIN_DB_PREFIX, $sql);
411 }
412
413 if (!empty($handler)) {
414 $sql = preg_replace('/__HANDLER__/i', "'".$db->escape($handler)."'", $sql);
415 }
416
417 if (!empty($database)) {
418 $sql = preg_replace('/__DATABASE__/i', $db->escape($database), $sql);
419 }
420
421 $newsql = preg_replace('/__ENTITY__/i', (!empty($entity) ? $entity : (string) $conf->entity), $sql);
422
423 // Add log of request
424 if (!$silent) {
425 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";
426 }
427 dol_syslog('Admin.lib::run_sql Request '.($i + 1), LOG_DEBUG);
428 $sqlmodified = 0;
429
430 // Replace for encrypt data
431 if (preg_match_all('/__ENCRYPT\‍(\'([^\']+)\'\‍)__/i', $newsql, $reg)) {
432 $num = count($reg[0]);
433
434 for ($j = 0; $j < $num; $j++) {
435 $from = $reg[0][$j];
436 $to = $db->encrypt($reg[1][$j]);
437 $newsql = str_replace($from, $to, $newsql);
438 }
439 $sqlmodified++;
440 }
441
442 // Replace for decrypt data
443 if (preg_match_all('/__DECRYPT\‍(\'([A-Za-z0-9_]+)\'\‍)__/i', $newsql, $reg)) {
444 $num = count($reg[0]);
445
446 for ($j = 0; $j < $num; $j++) {
447 $from = $reg[0][$j];
448 $to = $db->decrypt($reg[1][$j]);
449 $newsql = str_replace($from, $to, $newsql);
450 }
451 $sqlmodified++;
452 }
453
454 // Replace __x__ with the rowid of the result of the insert number x
455 while (preg_match('/__([0-9]+)__/', $newsql, $reg)) {
456 $cursor = $reg[1];
457 if (empty($listofinsertedrowid[$cursor])) {
458 if (!$silent) {
459 print '<tr><td class="tdtop"'.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
460 print '<div class="error">'.$langs->trans("FileIsNotCorrect")."</div>";
461 print '</td></tr>';
462 }
463 $error++;
464 break;
465 }
466
467 $from = '__'.$cursor.'__';
468 $to = $listofinsertedrowid[$cursor];
469 $newsql = str_replace($from, $to, $newsql);
470 $sqlmodified++;
471 }
472
473 if ($sqlmodified) {
474 dol_syslog('Admin.lib::run_sql New Request '.($i + 1), LOG_DEBUG);
475 }
476
477 $result = $db->query($newsql, $usesavepoint);
478 if ($result) {
479 if (!$silent) {
480 print '<!-- Result = OK -->'."\n";
481 }
482
483 if (preg_replace('/insert into ([^\s]+)/i', $newsql, $reg)) {
484 $cursorinsert++;
485
486 // It's an insert
487 $table = preg_replace('/([^a-zA-Z_]+)/i', '', $reg[1]);
488 $insertedrowid = $db->last_insert_id($table);
489 $listofinsertedrowid[$cursorinsert] = $insertedrowid;
490 dol_syslog('Admin.lib::run_sql Insert nb '.$cursorinsert.', done in table '.$table.', rowid is '.$listofinsertedrowid[$cursorinsert], LOG_DEBUG);
491 }
492 // print '<td class="right">OK</td>';
493 } else {
494 $errno = $db->errno();
495 if (!$silent) {
496 print '<!-- Result = '.$errno.' -->'."\n";
497 }
498
499 // Define list of errors we accept (array $okerrors)
500 $okerrors = array( // By default
501 'DB_ERROR_TABLE_ALREADY_EXISTS',
502 'DB_ERROR_COLUMN_ALREADY_EXISTS',
503 'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
504 'DB_ERROR_TABLE_OR_KEY_ALREADY_EXISTS', // PgSql use same code for table and key already exist
505 'DB_ERROR_RECORD_ALREADY_EXISTS',
506 'DB_ERROR_NOSUCHTABLE',
507 'DB_ERROR_NOSUCHFIELD',
508 'DB_ERROR_NO_FOREIGN_KEY_TO_DROP',
509 'DB_ERROR_NO_INDEX_TO_DROP',
510 'DB_ERROR_CANNOT_CREATE', // Qd contrainte deja existante
511 'DB_ERROR_CANT_DROP_PRIMARY_KEY',
512 'DB_ERROR_PRIMARY_KEY_ALREADY_EXISTS',
513 'DB_ERROR_22P02'
514 );
515 if ($okerror == 'none') {
516 $okerrors = array();
517 }
518
519 // Is it an error we accept
520 if (!in_array($errno, $okerrors)) {
521 if (!$silent) {
522 print '<tr><td class="tdtop"'.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
523 print '<div class="error">'.$langs->trans("Error")." ".$db->errno()." (Req ".($i + 1)."): ".$newsql."<br>".$db->error()."</div>";
524 print '</td></tr>'."\n";
525 }
526 dol_syslog('Admin.lib::run_sql Request '.($i + 1)." Error ".$db->errno()." ".$newsql."<br>".$db->error(), LOG_ERR);
527 $error++;
528 }
529 }
530 }
531 }
532
533 if (!$silent) {
534 print '<tr><td>'.$langs->trans("ProcessMigrateScript").'</td>';
535 print '<td class="right">';
536 if ($error == 0) {
537 print '<span class="ok">'.$langs->trans("OK").'</span>';
538 } else {
539 print '<span class="error">'.$langs->trans("Error").'</span>';
540 }
541
542 //if (!empty($conf->use_javascript_ajax)) { // use_javascript_ajax is not defined
543 print '<script type="text/javascript">
544 jQuery(document).ready(function() {
545 function init_trrunsql'.$keyforsql.'()
546 {
547 console.log("toggle .trforrunsql'.$keyforsql.'");
548 jQuery(".trforrunsql'.$keyforsql.'").toggle();
549 }
550 init_trrunsql'.$keyforsql.'();
551 jQuery(".trforrunsqlshowhide'.$keyforsql.'").click(function() {
552 init_trrunsql'.$keyforsql.'();
553 });
554 });
555 </script>';
556 if (count($arraysql)) {
557 print ' - <a class="trforrunsqlshowhide'.$keyforsql.'" href="#" title="'.($langs->trans("ShowHideTheNRequests", count($arraysql))).'">'.$langs->trans("ShowHideDetails").'</a>';
558 } else {
559 print ' - <span class="opacitymedium">'.$langs->trans("ScriptIsEmpty").'</span>';
560 }
561 //}
562
563 print '</td></tr>'."\n";
564 }
565
566 if ($error == 0) {
567 $ok = 1;
568 } else {
569 $ok = 0;
570 }
571
572 return $ok;
573}
574
575
586function dolibarr_del_const($db, $name, $entity = 1)
587{
588 global $conf, $hookmanager;
589
590 if (empty($name)) {
591 dol_print_error(null, 'Error call dolibar_del_const with parameter name empty');
592 return -1;
593 }
594 if (! is_object($hookmanager)) {
595 require_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
596 $hookmanager = new HookManager($db);
597 }
598
599 $parameters = array(
600 'name' => $name,
601 'entity' => $entity,
602 );
603
604 $reshook = $hookmanager->executeHooks('dolibarrDelConst', $parameters); // Note that $action and $object may have been modified by some hooks
605 if ($reshook != 0) {
606 return $reshook;
607 }
608
609 $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
610 $sql .= " WHERE (".$db->decrypt('name')." = '".$db->escape((string) $name)."'";
611 if (is_numeric($name)) { // This case seems used in the setup of constant page only, to delete a line.
612 $sql .= " OR rowid = ".((int) $name);
613 }
614 $sql .= ")";
615 if ($entity >= 0) {
616 $sql .= " AND entity = ".((int) $entity);
617 }
618
619 dol_syslog("admin.lib::dolibarr_del_const", LOG_DEBUG);
620 $resql = $db->query($sql);
621 if ($resql) {
622 $conf->global->$name = '';
623 return 1;
624 } else {
625 dol_print_error($db);
626 return -1;
627 }
628}
629
640function dolibarr_get_const($db, $name, $entity = 1)
641{
642 $value = '';
643
644 $sql = "SELECT ".$db->decrypt('value')." as value";
645 $sql .= " FROM ".MAIN_DB_PREFIX."const";
646 $sql .= " WHERE name = ".$db->encrypt($name);
647 $sql .= " AND entity = ".((int) $entity);
648
649 dol_syslog("admin.lib::dolibarr_get_const", LOG_DEBUG);
650 $resql = $db->query($sql);
651 if ($resql) {
652 $obj = $db->fetch_object($resql);
653 if ($obj) {
654 include_once DOL_DOCUMENT_ROOT.'/core/lib/security.lib.php';
655 $value = dolDecrypt($obj->value);
656 }
657 }
658 return $value;
659}
660
661
676function dolibarr_set_const($db, $name, $value, $type = 'chaine', $visible = 0, $note = '', $entity = 1)
677{
678 global $conf, $hookmanager;
679
680 // Clean parameters
681 $name = trim($name);
682 $value = (string) $value;
683
684 // Check parameters
685 if (empty($name)) {
686 dol_print_error($db, "Error: Call to function dolibarr_set_const with wrong parameters");
687 exit;
688 }
689 if (! is_object($hookmanager)) {
690 require_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
691 $hookmanager = new HookManager($db);
692 }
693
694 $value = (string) $value; // We force type string (may be int)
695
696 $parameters = array(
697 'name' => $name,
698 'value' => $value,
699 'type' => $type,
700 'visible' => $visible,
701 'note' => $note,
702 'entity' => $entity,
703 );
704
705 $reshook = $hookmanager->executeHooks('dolibarrSetConst', $parameters); // Note that $action and $object may have been modified by some hooks
706 if ($reshook != 0) {
707 return $reshook;
708 }
709
710 //dol_syslog("dolibarr_set_const name=$name, value=$value type=$type, visible=$visible, note=$note entity=$entity");
711
712 $db->begin();
713
714 $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
715 $sql .= " WHERE name = ".$db->encrypt($name);
716 if ($entity >= 0) {
717 $sql .= " AND entity = ".((int) $entity);
718 }
719
720 dol_syslog("admin.lib::dolibarr_set_const", LOG_DEBUG);
721 $resql = $db->query($sql);
722
723 if (strcmp($value, '')) { // true if different. Must work for $value='0' or $value=0
724 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))) {
725 // This seems a sensitive constant, we encrypt its value
726 // To list all sensitive constant, you can make a
727 // 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'
728 // or name like '%\_SECURITY_TOKEN' or name like '%\WEB_TOKEN'
729 include_once DOL_DOCUMENT_ROOT.'/core/lib/security.lib.php';
730 $newvalue = dolEncrypt($value);
731 } else {
732 $newvalue = $value;
733 }
734
735 $sql = "INSERT INTO ".MAIN_DB_PREFIX."const(name, value, type, visible, note, entity)";
736 $sql .= " VALUES (";
737 $sql .= $db->encrypt($name);
738 $sql .= ", ".$db->encrypt($newvalue);
739 $sql .= ", '".$db->escape($type)."', ".((int) $visible).", '".$db->escape($note)."', ".((int) $entity).")";
740
741 //print "sql".$value."-".pg_escape_string($value)."-".$sql;exit;
742 //print "xx".$db->escape($value);
743 dol_syslog("admin.lib::dolibarr_set_const", LOG_DEBUG);
744 $resql = $db->query($sql);
745 }
746
747 if ($resql) {
748 $db->commit();
749 $conf->global->$name = $value;
750 return 1;
751 } else {
752 $db->rollback();
753 return -1;
754 }
755}
756
757
758
759
768function modules_prepare_head($nbofactivatedmodules, $nboftotalmodules, $nbmodulesnotautoenabled)
769{
770 global $langs, $form;
771
772 $desc = $langs->trans("ModulesDesc", '{picto}');
773 $desc = str_replace('{picto}', img_picto('', 'switch_off'), $desc);
774
775 $h = 0;
776 $head = array();
777 $mode = getDolGlobalString('MAIN_MODULE_SETUP_ON_LIST_BY_DEFAULT', 'commonkanban');
778 $head[$h][0] = DOL_URL_ROOT."/admin/modules.php?mode=".$mode;
779 if ($nbmodulesnotautoenabled < getDolGlobalInt('MAIN_MIN_NB_ENABLED_MODULE_FOR_WARNING', 1)) { // If only minimal initial modules enabled)
780 //$head[$h][1] = $form->textwithpicto($langs->trans("AvailableModules"), $desc);
781 $head[$h][1] = $langs->trans("AvailableModules");
782 $head[$h][1] .= $form->textwithpicto('', $langs->trans("YouMustEnableOneModule").'.<br><br><span class="opacitymedium">'.$desc.'</span>', 1, 'warning');
783 } else {
784 //$head[$h][1] = $langs->trans("AvailableModules").$form->textwithpicto('<span class="badge marginleftonly">'.$nbofactivatedmodules.' / '.$nboftotalmodules.'</span>', $desc, 1, 'help', '', 1, 3);
785 $head[$h][1] = $langs->trans("AvailableModules").'<span class="badge marginleftonly">'.$nbofactivatedmodules.' / '.$nboftotalmodules.'</span>';
786 }
787 $head[$h][2] = 'modules';
788 $h++;
789
790 $head[$h][0] = DOL_URL_ROOT."/admin/modules.php?mode=marketplace";
791 $head[$h][1] = $langs->trans("ModulesMarketPlaces");
792 $head[$h][2] = 'marketplace';
793 $h++;
794
795 $head[$h][0] = DOL_URL_ROOT."/admin/modules.php?mode=deploy";
796 $head[$h][1] = $langs->trans("AddExtensionThemeModuleOrOther");
797 $head[$h][2] = 'deploy';
798 $h++;
799
800 $head[$h][0] = DOL_URL_ROOT."/admin/modules.php?mode=develop";
801 $head[$h][1] = $langs->trans("ModulesDevelopYourModule");
802 $head[$h][2] = 'develop';
803 $h++;
804
805 return $head;
806}
807
814{
815 global $langs, $conf;
816 $h = 0;
817 $head = array();
818
819 $head[$h][0] = DOL_URL_ROOT."/admin/ihm.php?mode=other";
820 $head[$h][1] = $langs->trans("LanguageAndPresentation");
821 $head[$h][2] = 'other';
822 $h++;
823
824 $head[$h][0] = DOL_URL_ROOT."/admin/ihm.php?mode=template";
825 $head[$h][1] = $langs->trans("SkinAndColors");
826 $head[$h][2] = 'template';
827 $h++;
828
829 $head[$h][0] = DOL_URL_ROOT."/admin/ihm.php?mode=dashboard";
830 $head[$h][1] = $langs->trans("Dashboard");
831 $head[$h][2] = 'dashboard';
832 $h++;
833
834 $head[$h][0] = DOL_URL_ROOT."/admin/ihm.php?mode=login";
835 $head[$h][1] = $langs->trans("LoginPage");
836 $head[$h][2] = 'login';
837 $h++;
838
839 $head[$h][0] = DOL_URL_ROOT."/admin/ihm.php?mode=css";
840 $head[$h][1] = $langs->trans("CSSPage");
841 $head[$h][2] = 'css';
842 $h++;
843
844 $head[$h][0] = DOL_URL_ROOT."/admin/tools/ui/index.php";
845 $head[$h][1] = $langs->trans("UxComponentsDoc").' '.img_picto('', 'external-link-square-alt');
846 $head[$h][2] = 'ux';
847 $h++;
848
849 complete_head_from_modules($conf, $langs, null, $head, $h, 'ihm_admin');
850
851 complete_head_from_modules($conf, $langs, null, $head, $h, 'ihm_admin', 'remove');
852
853
854 return $head;
855}
856
857
864{
865 global $db, $langs, $conf;
866 $h = 0;
867 $head = array();
868
869 $head[$h][0] = DOL_URL_ROOT."/admin/security_other.php";
870 $head[$h][1] = $langs->trans("Miscellaneous");
871 $head[$h][2] = 'misc';
872 $h++;
873
874 $head[$h][0] = DOL_URL_ROOT."/admin/security_captcha.php";
875 $head[$h][1] = $langs->trans("Captcha");
876 $head[$h][2] = 'captcha';
877 $h++;
878
879 $head[$h][0] = DOL_URL_ROOT."/admin/security.php";
880 $head[$h][1] = $langs->trans("Passwords");
881 $head[$h][2] = 'passwords';
882 $h++;
883
884 $head[$h][0] = DOL_URL_ROOT."/admin/security_file.php";
885 $head[$h][1] = $langs->trans("Files").' ('.$langs->trans("UploadName").' | '.$langs->trans("Download").')';
886 $head[$h][2] = 'file';
887 $h++;
888
889 /*
890 $head[$h][0] = DOL_URL_ROOT."/admin/security_file_download.php";
891 $head[$h][1] = $langs->trans("Files").' ('.$langs->trans("Download").')';
892 $head[$h][2] = 'filedownload';
893 $h++;
894 */
895
896 $head[$h][0] = DOL_URL_ROOT."/admin/proxy.php";
897 $head[$h][1] = $langs->trans("ExternalAccess");
898 $head[$h][2] = 'proxy';
899 $h++;
900
901 $head[$h][0] = DOL_URL_ROOT."/admin/events.php";
902 $head[$h][1] = $langs->trans("Audit");
903 $head[$h][2] = 'audit';
904 $h++;
905
906
907 // Show permissions lines
908 $nbPerms = 0;
909 $sql = "SELECT COUNT(r.id) as nb";
910 $sql .= " FROM ".MAIN_DB_PREFIX."rights_def as r";
911 $sql .= " WHERE r.libelle NOT LIKE 'tou%'"; // On ignore droits "tous"
912 $sql .= " AND entity = ".((int) $conf->entity);
913 $sql .= " AND bydefault = 1";
914 if (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) {
915 $sql .= " AND r.perms NOT LIKE '%_advance'"; // Hide advanced perms if option is not enabled
916 }
917 $resql = $db->query($sql);
918 if ($resql) {
919 $obj = $db->fetch_object($resql);
920 if ($obj) {
921 $nbPerms = $obj->nb;
922 }
923 } else {
924 dol_print_error($db);
925 }
926
927 if (getDolGlobalString('MAIN_SECURITY_USE_DEFAULT_PERMISSIONS')) {
928 $head[$h][0] = DOL_URL_ROOT."/admin/perms.php";
929 $head[$h][1] = $langs->trans("DefaultRights");
930 if ($nbPerms > 0) {
931 $head[$h][1] .= (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') ? '<span class="badge marginleftonlyshort">'.$nbPerms.'</span>' : '');
932 }
933 $head[$h][2] = 'default';
934 $h++;
935 }
936
937 return $head;
938}
939
947{
948 global $langs, $conf;
949 $h = 0;
950 $head = array();
951
952 // FIX for compatibility habitual tabs
953 $object->id = $object->numero;
954
955 $head[$h][0] = DOL_URL_ROOT."/admin/modulehelp.php?id=".$object->id.'&mode=desc';
956 $head[$h][1] = $langs->trans("Description");
957 $head[$h][2] = 'desc';
958 $h++;
959
960 $head[$h][0] = DOL_URL_ROOT."/admin/modulehelp.php?id=".$object->id.'&mode=feature';
961 $head[$h][1] = $langs->trans("TechnicalServicesProvided");
962 $head[$h][2] = 'feature';
963 $h++;
964
965 if ($object->isCoreOrExternalModule() == 'external') {
966 $head[$h][0] = DOL_URL_ROOT."/admin/modulehelp.php?id=".$object->id.'&mode=changelog';
967 $head[$h][1] = $langs->trans("ChangeLog");
968 $head[$h][2] = 'changelog';
969 $h++;
970 }
971
972 complete_head_from_modules($conf, $langs, $object, $head, $h, 'modulehelp_admin');
973
974 complete_head_from_modules($conf, $langs, $object, $head, $h, 'modulehelp_admin', 'remove');
975
976
977 return $head;
978}
985{
986 global $langs, $conf;
987 $h = 0;
988 $head = array();
989
990 $head[$h][0] = DOL_URL_ROOT."/admin/translation.php?mode=searchkey";
991 $head[$h][1] = $langs->trans("TranslationKeySearch");
992 $head[$h][2] = 'searchkey';
993 $h++;
994
995 $head[$h][0] = DOL_URL_ROOT."/admin/translation.php?mode=overwrite";
996 $head[$h][1] = '<span class="valignmiddle">'.$langs->trans("TranslationOverwriteKey").'</span><span class="fa fa-plus-circle valignmiddle paddingleft"></span>';
997 $head[$h][2] = 'overwrite';
998 $h++;
999
1000 complete_head_from_modules($conf, $langs, null, $head, $h, 'translation_admin');
1001
1002 complete_head_from_modules($conf, $langs, null, $head, $h, 'translation_admin', 'remove');
1003
1004
1005 return $head;
1006}
1007
1008
1015{
1016 global $langs, $conf;
1017 $h = 0;
1018 $head = array();
1019
1020 $head[$h][0] = DOL_URL_ROOT."/admin/defaultvalues.php?mode=createform";
1021 $head[$h][1] = $langs->trans("DefaultCreateForm");
1022 $head[$h][2] = 'createform';
1023 $h++;
1024
1025 $head[$h][0] = DOL_URL_ROOT."/admin/defaultvalues.php?mode=filters";
1026 $head[$h][1] = $langs->trans("DefaultSearchFilters");
1027 $head[$h][2] = 'filters';
1028 $h++;
1029
1030 $head[$h][0] = DOL_URL_ROOT."/admin/defaultvalues.php?mode=sortorder";
1031 $head[$h][1] = $langs->trans("DefaultSortOrder");
1032 $head[$h][2] = 'sortorder';
1033 $h++;
1034
1035 if (!empty($conf->use_javascript_ajax)) {
1036 $head[$h][0] = DOL_URL_ROOT."/admin/defaultvalues.php?mode=focus";
1037 $head[$h][1] = $langs->trans("DefaultFocus");
1038 $head[$h][2] = 'focus';
1039 $h++;
1040
1041 $head[$h][0] = DOL_URL_ROOT."/admin/defaultvalues.php?mode=mandatory";
1042 $head[$h][1] = $langs->trans("DefaultMandatory");
1043 $head[$h][2] = 'mandatory';
1044 $h++;
1045 }
1046
1047 /*$head[$h][0] = DOL_URL_ROOT."/admin/translation.php?mode=searchkey";
1048 $head[$h][1] = $langs->trans("TranslationKeySearch");
1049 $head[$h][2] = 'searchkey';
1050 $h++;*/
1051
1052 complete_head_from_modules($conf, $langs, null, $head, $h, 'defaultvalues_admin');
1053
1054 complete_head_from_modules($conf, $langs, null, $head, $h, 'defaultvalues_admin', 'remove');
1055
1056
1057 return $head;
1058}
1059
1060
1067{
1068 global $conf, $php_session_save_handler;
1069
1070 $arrayofSessions = array();
1071 // Set the handler of session
1072 if (!empty($php_session_save_handler) && $php_session_save_handler == 'db') {
1073 require_once DOL_DOCUMENT_ROOT.'/core/lib/phpsessionin'.$php_session_save_handler.'.lib.php';
1074 return dolListSessions();
1075 }
1076 // session.save_path can be returned empty so we set a default location and work from there
1077 $sessPath = '/tmp';
1078 $iniPath = ini_get("session.save_path");
1079 if ($iniPath) {
1080 $sessPath = $iniPath;
1081 }
1082 $sessPath .= '/'; // We need the trailing slash
1083 dol_syslog('admin.lib:listOfSessions sessPath='.$sessPath);
1084
1085 $dh = @opendir(dol_osencode($sessPath));
1086 if ($dh) {
1087 while (($file = @readdir($dh)) !== false) {
1088 if (preg_match('/^sess_/i', $file) && $file != "." && $file != "..") {
1089 $fullpath = $sessPath.$file;
1090 if (!@is_dir($fullpath) && is_readable($fullpath)) {
1091 $sessValues = file_get_contents($fullpath); // get raw session data
1092 // Example of possible value
1093 //$sessValues = 'newtoken|s:32:"1239f7a0c4b899200fe9ca5ea394f307";dol_loginmesg|s:0:"";newtoken|s:32:"1236457104f7ae0f328c2928973f3cb5";dol_loginmesg|s:0:"";token|s:32:"123615ad8d650c5cc4199b9a1a76783f";
1094 // 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";
1095 // 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";';
1096
1097 if (preg_match('/dol_login/i', $sessValues) && // limit to dolibarr session
1098 (preg_match('/dol_entity\|i:'.$conf->entity.';/i', $sessValues) || preg_match('/dol_entity\|s:([0-9]+):"'.$conf->entity.'"/i', $sessValues)) && // limit to current entity
1099 preg_match('/dol_company\|s:([0-9]+):"('.getDolGlobalString('MAIN_INFO_SOCIETE_NOM').')"/i', $sessValues)) { // limit to company name
1100 $tmp = explode('_', $file);
1101 $idsess = $tmp[1];
1102 $regs = array();
1103 $arrayofSessions[$idsess]["login"] = '';
1104 $loginfound = preg_match('/dol_login\|s:[0-9]+:"([A-Za-z0-9]+)"/i', $sessValues, $regs);
1105 if ($loginfound) {
1106 $arrayofSessions[$idsess]["login"] = (string) $regs[1];
1107 }
1108 $arrayofSessions[$idsess]["age"] = time() - filectime($fullpath);
1109 $arrayofSessions[$idsess]["creation"] = filectime($fullpath);
1110 $arrayofSessions[$idsess]["modification"] = filemtime($fullpath);
1111 $arrayofSessions[$idsess]["user_agent"] = null;
1112 $arrayofSessions[$idsess]["remote_ip"] = null;
1113 $arrayofSessions[$idsess]["raw"] = $sessValues;
1114 }
1115 }
1116 }
1117 }
1118 @closedir($dh);
1119 }
1120
1121 return $arrayofSessions;
1122}
1123
1130function purgeSessions($mysessionid)
1131{
1132 global $conf;
1133
1134 $sessPath = ini_get("session.save_path")."/";
1135 dol_syslog('admin.lib:purgeSessions mysessionid='.$mysessionid.' sessPath='.$sessPath);
1136
1137 $error = 0;
1138
1139 $dh = @opendir(dol_osencode($sessPath));
1140 if ($dh) {
1141 while (($file = @readdir($dh)) !== false) {
1142 if ($file != "." && $file != "..") {
1143 $fullpath = $sessPath.$file;
1144 if (!@is_dir($fullpath)) {
1145 $sessValues = file_get_contents($fullpath); // get raw session data
1146
1147 if (preg_match('/dol_login/i', $sessValues) && // limit to dolibarr session
1148 (preg_match('/dol_entity\|i:('.$conf->entity.')/', $sessValues) || preg_match('/dol_entity\|s:([0-9]+):"('.$conf->entity.')"/i', $sessValues)) && // limit to current entity
1149 preg_match('/dol_company\|s:([0-9]+):"(' . getDolGlobalString('MAIN_INFO_SOCIETE_NOM').')"/i', $sessValues)) { // limit to company name
1150 $tmp = explode('_', $file);
1151 $idsess = $tmp[1];
1152 // We remove session if it's not ourself
1153 if ($idsess != $mysessionid) {
1154 $res = @unlink($fullpath);
1155 if (!$res) {
1156 $error++;
1157 }
1158 }
1159 }
1160 }
1161 }
1162 }
1163 @closedir($dh);
1164 }
1165
1166 if (!$error) {
1167 return 1;
1168 } else {
1169 return -$error;
1170 }
1171}
1172
1173
1174
1183function activateModule($value, $withdeps = 1, $noconfverification = 0)
1184{
1185 global $db, $langs, $conf, $mysoc;
1186
1187 $ret = array();
1188
1189 // Check parameters
1190 if (empty($value)) {
1191 $ret['errors'] = array('ErrorBadParameter');
1192 return $ret;
1193 }
1194
1195 $ret = array('nbmodules' => 0, 'errors' => array(), 'nbperms' => 0);
1196 $modName = $value;
1197 $modFile = $modName.".class.php";
1198
1199 // Loop on each directory to fill $modulesdir
1200 $modulesdir = dolGetModulesDirs();
1201
1202 // Loop on each modulesdir directories
1203 $found = false;
1204 foreach ($modulesdir as $dir) {
1205 if (file_exists($dir.$modFile)) {
1206 $found = @include_once $dir.$modFile;
1207 if ($found) {
1208 break;
1209 }
1210 }
1211 }
1212
1213 $objMod = new $modName($db);
1214 '@phan-var-force DolibarrModules $objMod';
1215
1216 // Test if PHP version ok
1217 $verphp = versionphparray();
1218 $vermin = isset($objMod->phpmin) ? $objMod->phpmin : 0;
1219 if (is_array($vermin) && versioncompare($verphp, $vermin) < 0) {
1220 $ret['errors'][] = $langs->trans("ErrorModuleRequirePHPVersion", versiontostring($vermin));
1221 return $ret;
1222 }
1223
1224 // Test if Dolibarr version ok
1225 $verdol = versiondolibarrarray();
1226 $vermin = isset($objMod->need_dolibarr_version) ? $objMod->need_dolibarr_version : 0;
1227 //print 'version: '.versioncompare($verdol,$vermin).' - '.join(',',$verdol).' - '.join(',',$vermin);exit;
1228 if (is_array($vermin) && versioncompare($verdol, $vermin) < 0) {
1229 $ret['errors'][] = $langs->trans("ErrorModuleRequireDolibarrVersion", versiontostring($vermin));
1230 return $ret;
1231 }
1232
1233 // Test if javascript requirement ok
1234 if (!empty($objMod->need_javascript_ajax) && empty($conf->use_javascript_ajax)) {
1235 $ret['errors'][] = $langs->trans("ErrorModuleRequireJavascript");
1236 return $ret;
1237 }
1238
1239 $const_name = $objMod->const_name;
1240 if ($noconfverification == 0) {
1241 if (getDolGlobalString($const_name)) {
1242 return $ret;
1243 }
1244 }
1245
1246 $result = $objMod->init(); // Enable module
1247
1248 if ($result <= 0) {
1249 $ret['errors'][] = $objMod->error;
1250 } else {
1251 if ($withdeps) {
1252 if (isset($objMod->depends) && is_array($objMod->depends) && !empty($objMod->depends)) {
1253 // Activation of modules this module depends on
1254 // this->depends may be array('modModule1', 'mmodModule2') or array('always'=>array('modModule1'), 'FR'=>array('modModule2"))
1255 foreach ($objMod->depends as $key => $modulestringorarray) {
1256 //var_dump((! is_numeric($key)) && ! preg_match('/^always/', $key) && $mysoc->country_code && ! preg_match('/^'.$mysoc->country_code.'/', $key));exit;
1257 if ((!is_numeric($key)) && !preg_match('/^always/', $key) && $mysoc->country_code && !preg_match('/^'.$mysoc->country_code.'/', $key)) {
1258 dol_syslog("We are not concerned by dependency with key=".$key." because our country is ".$mysoc->country_code);
1259 continue;
1260 }
1261
1262 if (!is_array($modulestringorarray)) {
1263 $modulestringorarray = array($modulestringorarray);
1264 }
1265
1266 foreach ($modulestringorarray as $modulestring) {
1267 $activate = false;
1268 $activateerr = '';
1269 foreach ($modulesdir as $dir) {
1270 if (file_exists($dir.$modulestring.".class.php")) {
1271 $resarray = activateModule($modulestring);
1272 if (empty($resarray['errors'])) {
1273 $activate = true;
1274 } else {
1275 $activateerr = implode(', ', $resarray['errors']);
1276 foreach ($resarray['errors'] as $errorMessage) {
1277 dol_syslog($errorMessage, LOG_ERR);
1278 }
1279 }
1280 break;
1281 }
1282 }
1283
1284 if ($activate) {
1285 $ret['nbmodules'] += $resarray['nbmodules'];
1286 $ret['nbperms'] += $resarray['nbperms'];
1287 } else {
1288 if ($activateerr) {
1289 $ret['errors'][] = $activateerr;
1290 }
1291 $ret['errors'][] = $langs->trans('activateModuleDependNotSatisfied', $objMod->name, $modulestring, $objMod->name).'<br>'.$langs->trans('activateModuleDependNotSatisfied2', $modulestring, $objMod->name);
1292 }
1293 }
1294 }
1295 }
1296
1297 if (isset($objMod->conflictwith) && is_array($objMod->conflictwith) && !empty($objMod->conflictwith)) {
1298 // Deactivation des modules qui entrent en conflict
1299 $num = count($objMod->conflictwith);
1300 for ($i = 0; $i < $num; $i++) {
1301 foreach ($modulesdir as $dir) {
1302 if (file_exists($dir.$objMod->conflictwith[$i].".class.php")) {
1303 unActivateModule($objMod->conflictwith[$i], 0);
1304 }
1305 }
1306 }
1307 }
1308 }
1309 }
1310
1311 if (!count($ret['errors'])) {
1312 $ret['nbmodules']++;
1313 $ret['nbperms'] += (is_array($objMod->rights) ? count($objMod->rights) : 0);
1314 }
1315
1316 return $ret;
1317}
1318
1319
1327function unActivateModule($value, $requiredby = 1)
1328{
1329 global $db, $modules, $conf;
1330
1331 // Check parameters
1332 if (empty($value)) {
1333 return 'ErrorBadParameter';
1334 }
1335
1336 $ret = '';
1337 $modName = $value;
1338 $modFile = $modName.".class.php";
1339
1340 // Loop on each directory to fill $modulesdir
1341 $modulesdir = dolGetModulesDirs();
1342
1343 // Loop on each modulesdir directories
1344 $found = false;
1345 foreach ($modulesdir as $dir) {
1346 if (file_exists($dir.$modFile)) {
1347 $found = @include_once $dir.$modFile;
1348 if ($found) {
1349 break;
1350 }
1351 }
1352 }
1353
1354 if ($found) {
1355 $objMod = new $modName($db);
1356 '@phan-var-force DolibarrModules $objMod';
1357 $result = $objMod->remove();
1358 if ($result <= 0) {
1359 $ret = $objMod->error;
1360 }
1361 } else { // We come here when we try to unactivate a module when module does not exists anymore in sources
1362 //print $dir.$modFile;exit;
1363 // 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
1364 include_once DOL_DOCUMENT_ROOT.'/core/modules/DolibarrModules.class.php';
1365 $genericMod = new DolibarrModules($db);
1366 $genericMod->name = preg_replace('/^mod/i', '', $modName);
1367 $genericMod->rights_class = strtolower(preg_replace('/^mod/i', '', $modName));
1368 $genericMod->const_name = 'MAIN_MODULE_'.strtoupper(preg_replace('/^mod/i', '', $modName));
1369 dol_syslog("modules::unActivateModule Failed to find module file, we use generic function with name ".$modName);
1370 $genericMod->remove('');
1371 }
1372
1373 // Disable modules that depends on module we disable
1374 if (!$ret && $requiredby && isset($objMod) && is_object($objMod) && is_array($objMod->requiredby)) {
1375 $countrb = count($objMod->requiredby);
1376 for ($i = 0; $i < $countrb; $i++) {
1377 //var_dump($objMod->requiredby[$i]);
1378 unActivateModule($objMod->requiredby[$i]);
1379 }
1380 }
1381
1382 return $ret;
1383}
1384
1385
1404function complete_dictionary_with_modules(&$taborder, &$tabname, &$tablib, &$tabsql, &$tabsqlsort, &$tabfield, &$tabfieldvalue, &$tabfieldinsert, &$tabrowid, &$tabcond, &$tabhelp, &$tabcomplete)
1405{
1406 global $db, $langs;
1407
1408 dol_syslog("complete_dictionary_with_modules Search external modules to complete the list of dictionary tables", LOG_DEBUG, 1);
1409
1410 // Search modules
1411 $modulesdir = dolGetModulesDirs();
1412 $i = 0; // is a sequencer of modules found
1413 $j = 0; // j is module number. Automatically affected if module number not defined.
1414
1415 foreach ($modulesdir as $dir) {
1416 // Load modules attributes in arrays (name, numero, orders) from dir directory
1417 //print $dir."\n<br>";
1418 dol_syslog("Scan directory ".$dir." for modules");
1419 $handle = @opendir(dol_osencode($dir));
1420 if (is_resource($handle)) {
1421 while (($file = readdir($handle)) !== false) {
1422 //print "$i ".$file."\n<br>";
1423 if (is_readable($dir.$file) && substr($file, 0, 3) == 'mod' && substr($file, dol_strlen($file) - 10) == '.class.php') {
1424 $modName = substr($file, 0, dol_strlen($file) - 10);
1425
1426 if ($modName) {
1427 include_once $dir.$file;
1428 $objMod = new $modName($db);
1429 '@phan-var-force DolibarrModules $objMod';
1430
1431 if ($objMod->numero > 0) {
1432 $j = $objMod->numero;
1433 } else {
1434 $j = 1000 + $i;
1435 }
1436
1437 $modulequalified = 1;
1438
1439 // We discard modules according to features level (PS: if module is activated we always show it)
1440 $const_name = 'MAIN_MODULE_'.strtoupper(preg_replace('/^mod/i', '', get_class($objMod)));
1441 if ($objMod->version == 'development' && getDolGlobalInt('MAIN_FEATURES_LEVEL') < 2 && !getDolGlobalString($const_name)) {
1442 $modulequalified = 0;
1443 }
1444 if ($objMod->version == 'experimental' && getDolGlobalInt('MAIN_FEATURES_LEVEL') < 1 && !getDolGlobalString($const_name)) {
1445 $modulequalified = 0;
1446 }
1447 // If module is not activated disqualified
1448 if (!getDolGlobalString($const_name)) {
1449 $modulequalified = 0;
1450 }
1451
1452 if ($modulequalified) {
1453 // Load languages files of module
1454 if (isset($objMod->langfiles) && is_array($objMod->langfiles)) {
1455 foreach ($objMod->langfiles as $langfile) {
1456 $langs->load($langfile);
1457 }
1458 }
1459
1460 // phpcs:disable
1461 // Complete the arrays &$tabname,&$tablib,&$tabsql,&$tabsqlsort,&$tabfield,&$tabfieldvalue,&$tabfieldinsert,&$tabrowid,&$tabcond
1462 // @phan-suppress-next-line PhanUndeclaredProperty
1463 if (empty($objMod->dictionaries) && !empty($objMod->{"dictionnaries"})) {
1464 // @phan-suppress-next-line PhanUndeclaredProperty
1465 $objMod->dictionaries = $objMod->{"dictionnaries"}; // For backward compatibility
1466 }
1467 // phpcs:enable
1468
1469 if (!empty($objMod->dictionaries)) {
1470 //var_dump($objMod->dictionaries['tabname']);
1471 $nbtabname = $nbtablib = $nbtabsql = $nbtabsqlsort = $nbtabfield = $nbtabfieldvalue = $nbtabfieldinsert = $nbtabrowid = $nbtabcond = $nbtabfieldcheck = $nbtabhelp = 0;
1472 $tabnamerelwithkey = array();
1473 foreach ($objMod->dictionaries['tabname'] as $key => $val) {
1474 $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $val);
1475 $nbtabname++;
1476 $taborder[] = max($taborder) + 1;
1477 $tabname[] = $val;
1478 $tabnamerelwithkey[$key] = $val;
1479 $tabcomplete[$tmptablename]['picto'] = $objMod->picto;
1480 } // Position
1481 foreach ($objMod->dictionaries['tablib'] as $key => $val) {
1482 $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]);
1483 $nbtablib++;
1484 $tablib[] = $val;
1485 $tabcomplete[$tmptablename]['lib'] = $val;
1486 }
1487 foreach ($objMod->dictionaries['tabsql'] as $key => $val) {
1488 $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]);
1489 $nbtabsql++;
1490 $tabsql[] = $val;
1491 $tabcomplete[$tmptablename]['sql'] = $val;
1492 }
1493 foreach ($objMod->dictionaries['tabsqlsort'] as $key => $val) {
1494 $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]);
1495 $nbtabsqlsort++;
1496 $tabsqlsort[] = $val;
1497 $tabcomplete[$tmptablename]['sqlsort'] = $val;
1498 }
1499 foreach ($objMod->dictionaries['tabfield'] as $key => $val) {
1500 $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]);
1501 $nbtabfield++;
1502 $tabfield[] = $val;
1503 $tabcomplete[$tmptablename]['field'] = $val;
1504 }
1505 foreach ($objMod->dictionaries['tabfieldvalue'] as $key => $val) {
1506 $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]);
1507 $nbtabfieldvalue++;
1508 $tabfieldvalue[] = $val;
1509 $tabcomplete[$tmptablename]['value'] = $val;
1510 }
1511 foreach ($objMod->dictionaries['tabfieldinsert'] as $key => $val) {
1512 $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]);
1513 $nbtabfieldinsert++;
1514 $tabfieldinsert[] = $val;
1515 $tabcomplete[$tmptablename]['fieldinsert'] = $val;
1516 }
1517 foreach ($objMod->dictionaries['tabrowid'] as $key => $val) {
1518 $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]);
1519 $nbtabrowid++;
1520 $tabrowid[] = $val;
1521 $tabcomplete[$tmptablename]['rowid'] = $val;
1522 }
1523 foreach ($objMod->dictionaries['tabcond'] as $key => $val) {
1524 $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]);
1525 $nbtabcond++;
1526 $tabcond[] = $val;
1527 $tabcomplete[$tmptablename]['cond'] = $val;
1528 }
1529 if (!empty($objMod->dictionaries['tabhelp'])) {
1530 foreach ($objMod->dictionaries['tabhelp'] as $key => $val) {
1531 $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]);
1532 $nbtabhelp++;
1533 $tabhelp[] = $val;
1534 $tabcomplete[$tmptablename]['help'] = $val;
1535 }
1536 }
1537 if (!empty($objMod->dictionaries['tabfieldcheck'])) {
1538 foreach ($objMod->dictionaries['tabfieldcheck'] as $key => $val) {
1539 $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]);
1540 $nbtabfieldcheck++;
1541 $tabcomplete[$tmptablename]['fieldcheck'] = $val;
1542 }
1543 }
1544
1545 if ($nbtabname != $nbtablib || $nbtablib != $nbtabsql || $nbtabsql != $nbtabsqlsort) {
1546 print 'Error in descriptor of module '.$const_name.'. Array ->dictionaries has not same number of record for key "tabname", "tablib", "tabsql" and "tabsqlsort"';
1547 //print "$const_name: $nbtabname=$nbtablib=$nbtabsql=$nbtabsqlsort=$nbtabfield=$nbtabfieldvalue=$nbtabfieldinsert=$nbtabrowid=$nbtabcond=$nbtabfieldcheck=$nbtabhelp\n";
1548 } else {
1549 $taborder[] = 0; // Add an empty line
1550 }
1551 }
1552
1553 $j++;
1554 $i++;
1555 } else {
1556 dol_syslog("Module ".get_class($objMod)." not qualified");
1557 }
1558 }
1559 }
1560 }
1561 closedir($handle);
1562 } else {
1563 dol_syslog("htdocs/admin/modules.php: Failed to open directory ".$dir.". See permission and open_basedir option.", LOG_WARNING);
1564 }
1565 }
1566
1567 dol_syslog("", LOG_DEBUG, -1);
1568
1569 return 1;
1570}
1571
1579{
1580 global $db;
1581
1582 $modulesdir = dolGetModulesDirs();
1583
1584 foreach ($modulesdir as $dir) {
1585 // Load modules attributes in arrays (name, numero, orders) from dir directory
1586 dol_syslog("Scan directory ".$dir." for modules");
1587 $handle = @opendir(dol_osencode($dir));
1588 if (is_resource($handle)) {
1589 while (($file = readdir($handle)) !== false) {
1590 if (is_readable($dir.$file) && substr($file, 0, 3) == 'mod' && substr($file, dol_strlen($file) - 10) == '.class.php') {
1591 $modName = substr($file, 0, dol_strlen($file) - 10);
1592
1593 if ($modName) {
1594 include_once $dir.$file;
1595 $objMod = new $modName($db);
1596 '@phan-var-force DolibarrModules $objMod';
1597
1598 $modulequalified = 1;
1599
1600 // We discard modules according to features level (PS: if module is activated we always show it)
1601 $const_name = 'MAIN_MODULE_'.strtoupper(preg_replace('/^mod/i', '', get_class($objMod)));
1602
1603 if ($objMod->version == 'development' && getDolGlobalInt('MAIN_FEATURES_LEVEL') < 2) {
1604 $modulequalified = 0;
1605 }
1606 if ($objMod->version == 'experimental' && getDolGlobalInt('MAIN_FEATURES_LEVEL') < 1) {
1607 $modulequalified = 0;
1608 }
1609 if (getDolGlobalString($const_name)) {
1610 $modulequalified = 0; // already activated
1611 }
1612
1613 if ($modulequalified) {
1614 // Load languages files of module
1615 if (property_exists($objMod, 'automatic_activation') && isset($objMod->automatic_activation) && is_array($objMod->automatic_activation) && isset($objMod->automatic_activation[$country_code])) {
1616 activateModule($modName);
1617
1618 setEventMessages($objMod->automatic_activation[$country_code], null, 'warnings');
1619 }
1620 } else {
1621 dol_syslog("Module ".get_class($objMod)." not qualified");
1622 }
1623 }
1624 }
1625 }
1626 closedir($handle);
1627 } else {
1628 dol_syslog("htdocs/admin/modules.php: Failed to open directory ".$dir.". See permission and open_basedir option.", LOG_WARNING);
1629 }
1630 }
1631
1632 return 1;
1633}
1634
1642{
1643 global $db, $modules, $conf, $langs;
1644
1645 // Search modules
1646 $filename = array();
1647 $modules = array();
1648 $orders = array();
1649 $categ = array();
1650 $dirmod = array();
1651
1652 $i = 0; // is a sequencer of modules found
1653 $j = 0; // j is module number. Automatically affected if module number not defined.
1654
1655 dol_syslog("complete_elementList_with_modules Search external modules to complete the list of contact element", LOG_DEBUG, 1);
1656
1657 $modulesdir = dolGetModulesDirs();
1658
1659 foreach ($modulesdir as $dir) {
1660 // Load modules attributes in arrays (name, numero, orders) from dir directory
1661 //print $dir."\n<br>";
1662 dol_syslog("Scan directory ".$dir." for modules");
1663 $handle = @opendir(dol_osencode($dir));
1664 if (is_resource($handle)) {
1665 while (($file = readdir($handle)) !== false) {
1666 //print "$i ".$file."\n<br>";
1667 if (is_readable($dir.$file) && substr($file, 0, 3) == 'mod' && substr($file, dol_strlen($file) - 10) == '.class.php') {
1668 $modName = substr($file, 0, dol_strlen($file) - 10);
1669
1670 if ($modName) {
1671 include_once $dir.$file;
1672 $objMod = new $modName($db);
1673
1674 if ($objMod->numero > 0) {
1675 $j = $objMod->numero;
1676 } else {
1677 $j = 1000 + $i;
1678 }
1679
1680 $modulequalified = 1;
1681
1682 // We discard modules according to features level (PS: if module is activated we always show it)
1683 $const_name = 'MAIN_MODULE_'.strtoupper(preg_replace('/^mod/i', '', get_class($objMod)));
1684 if ($objMod->version == 'development' && getDolGlobalInt('MAIN_FEATURES_LEVEL') < 2 && getDolGlobalString($const_name)) {
1685 $modulequalified = 0;
1686 }
1687 if ($objMod->version == 'experimental' && getDolGlobalInt('MAIN_FEATURES_LEVEL') < 1 && getDolGlobalString($const_name)) {
1688 $modulequalified = 0;
1689 }
1690 // If module is not activated disqualified
1691 if (!getDolGlobalString($const_name)) {
1692 $modulequalified = 0;
1693 }
1694
1695 if ($modulequalified) {
1696 // Load languages files of module
1697 if (isset($objMod->langfiles) && is_array($objMod->langfiles)) {
1698 foreach ($objMod->langfiles as $langfile) {
1699 $langs->load($langfile);
1700 }
1701 }
1702
1703 $modules[$i] = $objMod;
1704 $filename[$i] = $modName;
1705 $orders[$i] = $objMod->family."_".$j; // Sort on family then module number
1706 $dirmod[$i] = $dir;
1707 //print "x".$modName." ".$orders[$i]."\n<br>";
1708
1709 if (!empty($objMod->module_parts['contactelement'])) {
1710 if (is_array($objMod->module_parts['contactelement'])) {
1711 foreach ($objMod->module_parts['contactelement'] as $elem => $title) {
1712 $elementList[$elem] = $langs->trans($title);
1713 }
1714 } else {
1715 $elementList[$objMod->name] = $langs->trans($objMod->name);
1716 }
1717 }
1718
1719 $j++;
1720 $i++;
1721 } else {
1722 dol_syslog("Module ".get_class($objMod)." not qualified");
1723 }
1724 }
1725 }
1726 }
1727 closedir($handle);
1728 } else {
1729 dol_syslog("htdocs/admin/modules.php: Failed to open directory ".$dir.". See permission and open_basedir option.", LOG_WARNING);
1730 }
1731 }
1732
1733 dol_syslog("", LOG_DEBUG, -1);
1734
1735 return 1;
1736}
1737
1748function form_constantes($tableau, $strictw3c = 2, $helptext = '', $text = 'Value')
1749{
1750 global $db, $langs, $conf, $user;
1751 global $_Avery_Labels;
1752
1753 $form = new Form($db);
1754
1755 if (empty($strictw3c)) {
1756 dol_syslog("Warning: Function 'form_constantes' was called with parameter strictw3c = 0, this is deprecated. Value must be 2 now.", LOG_WARNING);
1757 }
1758 if (!empty($strictw3c) && $strictw3c == 1) {
1759 print "\n".'<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
1760 print '<input type="hidden" name="token" value="'.newToken().'">';
1761 print '<input type="hidden" name="action" value="updateall">';
1762 }
1763
1764 print '<div class="div-table-responsive-no-min">';
1765 print '<table class="noborder centpercent">';
1766 print '<tr class="liste_titre">';
1767 print '<td class="">'.$langs->trans("Description").'</td>';
1768 print '<td>';
1769 $text = $langs->trans($text);
1770 print $form->textwithpicto($text, $helptext, 1, 'help', '', 0, 2, 'idhelptext');
1771 print '</td>';
1772 if (empty($strictw3c)) {
1773 print '<td class="center" width="80">'.$langs->trans("Action").'</td>';
1774 }
1775 print "</tr>\n";
1776
1777 $label = '';
1778 foreach ($tableau as $key => $const) { // Loop on each param
1779 $label = '';
1780 // $const is a const key like 'MYMODULE_ABC'
1781 if (is_numeric($key)) { // Very old behaviour
1782 $type = 'string';
1783 } else {
1784 if (is_array($const)) {
1785 $type = $const['type'];
1786 $label = $const['label'];
1787 $const = $key;
1788 } else {
1789 $type = $const;
1790 $const = $key;
1791 }
1792 }
1793 $sql = "SELECT ";
1794 $sql .= "rowid";
1795 $sql .= ", ".$db->decrypt('name')." as name";
1796 $sql .= ", ".$db->decrypt('value')." as value";
1797 $sql .= ", type";
1798 $sql .= ", note";
1799 $sql .= " FROM ".MAIN_DB_PREFIX."const";
1800 $sql .= " WHERE ".$db->decrypt('name')." = '".$db->escape($const)."'";
1801 $sql .= " AND entity IN (0, ".$conf->entity.")";
1802 $sql .= " ORDER BY name ASC, entity DESC";
1803 $result = $db->query($sql);
1804
1805 dol_syslog("List params", LOG_DEBUG);
1806
1807 if ($result) {
1808 $obj = $db->fetch_object($result); // Take first result of select
1809
1810 if (empty($obj)) { // If not yet into table
1811 $obj = (object) array('rowid' => '', 'name' => $const, 'value' => '', 'type' => $type, 'note' => '');
1812 }
1813
1814 if (empty($strictw3c)) { // deprecated. must be always true.
1815 print "\n".'<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
1816 print '<input type="hidden" name="token" value="'.newToken().'">';
1817 print '<input type="hidden" name="page_y" value="'.newToken().'">';
1818 print '<input type="hidden" name="action" value="update">';
1819 }
1820
1821 print '<tr class="oddeven">';
1822
1823 // Show label of parameter
1824 print '<td>';
1825 print '<input type="hidden" name="rowid'.(empty($strictw3c) ? '' : '[]').'" value="'.$obj->rowid.'">';
1826 print '<input type="hidden" name="constname'.(empty($strictw3c) ? '' : '[]').'" value="'.$const.'">';
1827 print '<input type="hidden" name="constnote_'.$obj->name.'" value="'.nl2br(dol_escape_htmltag($obj->note)).'">';
1828 print '<input type="hidden" name="consttype_'.$obj->name.'" value="'.($obj->type ? $obj->type : 'string').'">';
1829
1830 $picto = 'generic';
1831 $tmparray = explode(':', $obj->type);
1832 if (!empty($tmparray[1])) {
1833 $picto = preg_replace('/_send$/', '', $tmparray[1]);
1834 }
1835 print img_picto('', $picto, 'class="pictofixedwidth"');
1836
1837 if (!empty($tableau[$key]['tooltip'])) {
1838 print $form->textwithpicto($label ? $label : $langs->trans('Desc'.$const), $tableau[$key]['tooltip']);
1839 } else {
1840 print($label ? $label : $langs->trans('Desc'.$const));
1841 }
1842
1843 if ($const == 'ADHERENT_MAILMAN_URL') {
1844 print '. '.$langs->trans("Example").': <a href="#" id="exampleclick1">'.img_down().'</a><br>';
1845 //print 'http://lists.example.com/cgi-bin/mailman/admin/%LISTE%/members?adminpw=%MAILMAN_ADMINPW%&subscribees=%EMAIL%&send_welcome_msg_to_this_batch=1';
1846 print '<div id="example1" class="hidden">';
1847 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';
1848 print '</div>';
1849 } elseif ($const == 'ADHERENT_MAILMAN_UNSUB_URL') {
1850 print '. '.$langs->trans("Example").': <a href="#" id="exampleclick2">'.img_down().'</a><br>';
1851 print '<div id="example2" class="hidden">';
1852 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';
1853 print '</div>';
1854 //print 'http://lists.example.com/cgi-bin/mailman/admin/%LISTE%/members/remove?adminpw=%MAILMAN_ADMINPW%&unsubscribees=%EMAIL%';
1855 } elseif ($const == 'ADHERENT_MAILMAN_LISTS') {
1856 print '. '.$langs->trans("Example").': <a href="#" id="exampleclick3">'.img_down().'</a><br>';
1857 print '<div id="example3" class="hidden">';
1858 print 'mymailmanlist<br>';
1859 print 'mymailmanlist1,mymailmanlist2<br>';
1860 print 'TYPE:Type1:mymailmanlist1,TYPE:Type2:mymailmanlist2<br>';
1861 if (isModEnabled('category')) {
1862 print 'CATEG:Categ1:mymailmanlist1,CATEG:Categ2:mymailmanlist2<br>';
1863 }
1864 print '</div>';
1865 //print 'http://lists.example.com/cgi-bin/mailman/admin/%LISTE%/members/remove?adminpw=%MAILMAN_ADMINPW%&unsubscribees=%EMAIL%';
1866 } elseif (in_array($const, ['ADHERENT_MAIL_FROM', 'ADHERENT_CC_MAIL_FROM'])) {
1867 print ' '.img_help(1, $langs->trans("EMailHelpMsgSPFDKIM"));
1868 }
1869
1870 print "</td>\n";
1871
1872 // Value
1873 if ($const == 'ADHERENT_CARD_TYPE' || $const == 'ADHERENT_ETIQUETTE_TYPE') {
1874 print '<td>';
1875 // List of possible labels (defined into $_Avery_Labels variable set into format_cards.lib.php)
1876 require_once DOL_DOCUMENT_ROOT.'/core/lib/format_cards.lib.php';
1877 $arrayoflabels = array();
1878 foreach (array_keys($_Avery_Labels) as $codecards) {
1879 $arrayoflabels[$codecards] = $_Avery_Labels[$codecards]['name'];
1880 }
1881 print $form->selectarray('constvalue'.(empty($strictw3c) ? '' : ($strictw3c == 3 ? '_'.$const : '[]')), $arrayoflabels, ($obj->value ? $obj->value : 'CARD'), 1, 0, 0);
1882 print '<input type="hidden" name="consttype" value="yesno">';
1883 print '<input type="hidden" name="constnote'.(empty($strictw3c) ? '' : '[]').'" value="'.nl2br(dol_escape_htmltag($obj->note)).'">';
1884 print '</td>';
1885 } else {
1886 print '<td>';
1887 print '<input type="hidden" name="consttype'.(empty($strictw3c) ? '' : ($strictw3c == 3 ? '_'.$const : '[]')).'" value="'.($obj->type ? $obj->type : 'string').'">';
1888 print '<input type="hidden" name="constnote'.(empty($strictw3c) ? '' : ($strictw3c == 3 ? '_'.$const : '[]')).'" value="'.nl2br(dol_escape_htmltag($obj->note)).'">';
1889 if ($obj->type == 'textarea' || in_array($const, array('ADHERENT_CARD_TEXT', 'ADHERENT_CARD_TEXT_RIGHT', 'ADHERENT_ETIQUETTE_TEXT'))) {
1890 print '<textarea class="flat" name="constvalue'.(empty($strictw3c) ? '' : ($strictw3c == 3 ? '_'.$const : '[]')).'" cols="50" rows="5" wrap="soft">'."\n";
1891 print $obj->value;
1892 print "</textarea>\n";
1893 } elseif ($obj->type == 'html') {
1894 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
1895 $doleditor = new DolEditor('constvalue'.(empty($strictw3c) ? '' : ($strictw3c == 3 ? '_'.$const : '[]')), $obj->value, '', 160, 'dolibarr_notes', '', false, false, isModEnabled('fckeditor'), ROWS_5, '90%');
1896 $doleditor->Create();
1897 } elseif ($obj->type == 'yesno') {
1898 print $form->selectyesno('constvalue'.(empty($strictw3c) ? '' : ($strictw3c == 3 ? '_'.$const : '[]')), $obj->value, 1, false, 0, 1);
1899 } elseif (preg_match('/emailtemplate/', $obj->type)) {
1900 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
1901 $formmail = new FormMail($db);
1902
1903 $tmp = explode(':', $obj->type);
1904
1905 $nboftemplates = $formmail->fetchAllEMailTemplate($tmp[1], $user, null, -1); // We set lang=null to get in priority record with no lang
1906 //$arraydefaultmessage = $formmail->getEMailTemplate($db, $tmp[1], $user, null, 0, 1, '');
1907 $arrayofmessagename = array();
1908 if (is_array($formmail->lines_model)) {
1909 foreach ($formmail->lines_model as $modelmail) {
1910 //var_dump($modelmail);
1911 $moreonlabel = '';
1912 if (!empty($arrayofmessagename[$modelmail->label])) {
1913 $moreonlabel = ' <span class="opacitymedium">('.$langs->trans("SeveralLangugeVariatFound").')</span>';
1914 }
1915 // The 'label' is the key that is unique if we exclude the language
1916 $arrayofmessagename[$modelmail->label.':'.$tmp[1]] = $langs->trans(preg_replace('/\‍(|\‍)/', '', $modelmail->label)).$moreonlabel;
1917 }
1918 }
1919 //var_dump($arraydefaultmessage);
1920 //var_dump($arrayofmessagename);
1921 print $form->selectarray('constvalue'.(empty($strictw3c) ? '' : ($strictw3c == 3 ? '_'.$const : '[]')), $arrayofmessagename, $obj->value.':'.$tmp[1], 'None', 0, 0, '', 0, 0, 0, '', '', 1);
1922
1923 print '<a href="'.DOL_URL_ROOT.'/admin/mails_templates.php?action=create&type_template='.urlencode($tmp[1]).'&backtopage='.urlencode($_SERVER["PHP_SELF"]).'">'.img_picto('', 'add').'</a>';
1924 } elseif (preg_match('/MAIL_FROM$/i', $const)) {
1925 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).'">';
1926 } else { // type = 'string' ou 'chaine'
1927 print '<input type="text" class="flat minwidth300" name="constvalue'.(empty($strictw3c) ? '' : ($strictw3c == 3 ? '_'.$const : '[]')).'" value="'.dol_escape_htmltag($obj->value).'">';
1928 }
1929 print '</td>';
1930 }
1931
1932 // Submit button
1933 if (empty($strictw3c)) { // deprecated. must be always true.
1934 print '<td class="center">';
1935 print '<input type="submit" class="button small reposition" value="'.$langs->trans("Update").'" name="update">';
1936 print "</td>";
1937 }
1938
1939 print "</tr>\n";
1940
1941 if (empty($strictw3c)) {
1942 print "</form>\n";
1943 }
1944 }
1945 }
1946 print '</table>';
1947 print '</div>';
1948
1949 if (!empty($strictw3c) && $strictw3c == 1) {
1950 print '<div align="center"><input type="submit" class="button small reposition" value="'.$langs->trans("Update").'" name="update"></div>';
1951 print "</form>\n";
1952 }
1953}
1954
1955
1963{
1964 global $langs;
1965
1966 $text = $langs->transnoentitiesnoconv("OnlyFollowingModulesAreOpenedToExternalUsers");
1967 $listofmodules = explode(',', getDolGlobalString('MAIN_MODULES_FOR_EXTERNAL')); // List of modules qualified for external user management
1968
1969 $i = 0;
1970 if (!empty($modules)) {
1971 $tmpmodules = dol_sort_array($modules, 'module_position');
1972 foreach ($tmpmodules as $module) { // Loop on array of modules
1973 $moduleconst = $module->const_name;
1974 $modulename = strtolower($module->name);
1975 //print 'modulename='.$modulename;
1976
1977 //if (empty($conf->global->$moduleconst)) continue;
1978 if (!in_array($modulename, $listofmodules)) {
1979 continue;
1980 }
1981 //var_dump($modulename.' - '.$langs->trans('Module'.$module->numero.'Name'));
1982
1983 if ($i > 0) {
1984 $text .= ', ';
1985 } else {
1986 $text .= ' ';
1987 }
1988 $i++;
1989
1990 $tmptext = $langs->transnoentitiesnoconv('Module'.$module->numero.'Name');
1991 if ($tmptext != 'Module'.$module->numero.'Name') {
1992 $text .= $langs->transnoentitiesnoconv('Module'.$module->numero.'Name');
1993 } else {
1994 $text .= $langs->transnoentitiesnoconv($module->name);
1995 }
1996 }
1997 }
1998
1999 return $text;
2000}
2001
2002
2012function addDocumentModel($name, $type, $label = '', $description = '')
2013{
2014 global $db, $conf;
2015
2016 $db->begin();
2017
2018 $sql = "INSERT INTO ".MAIN_DB_PREFIX."document_model (nom, type, entity, libelle, description)";
2019 $sql .= " VALUES ('".$db->escape($name)."','".$db->escape($type)."',".((int) $conf->entity).", ";
2020 $sql .= ($label ? "'".$db->escape($label)."'" : 'null').", ";
2021 $sql .= (!empty($description) ? "'".$db->escape($description)."'" : "null");
2022 $sql .= ")";
2023
2024 dol_syslog("admin.lib::addDocumentModel", LOG_DEBUG);
2025 $resql = $db->query($sql);
2026 if ($resql) {
2027 $db->commit();
2028 return 1;
2029 } else {
2030 dol_print_error($db);
2031 $db->rollback();
2032 return -1;
2033 }
2034}
2035
2043function delDocumentModel($name, $type)
2044{
2045 global $db, $conf;
2046
2047 $db->begin();
2048
2049 $sql = "DELETE FROM ".MAIN_DB_PREFIX."document_model";
2050 $sql .= " WHERE nom = '".$db->escape($name)."'";
2051 $sql .= " AND type = '".$db->escape($type)."'";
2052 $sql .= " AND entity = ".((int) $conf->entity);
2053
2054 dol_syslog("admin.lib::delDocumentModel", LOG_DEBUG);
2055 $resql = $db->query($sql);
2056 if ($resql) {
2057 $db->commit();
2058 return 1;
2059 } else {
2060 dol_print_error($db);
2061 $db->rollback();
2062 return -1;
2063 }
2064}
2065
2066
2073{
2074 ob_start();
2075 phpinfo();
2076 $phpinfostring = ob_get_contents();
2077 ob_end_clean();
2078
2079 $info_arr = array();
2080 $info_lines = explode("\n", strip_tags($phpinfostring, "<tr><td><h2>"));
2081 $cat = "General";
2082 foreach ($info_lines as $line) {
2083 // new cat?
2084 $title = array();
2085 preg_match("~<h2>(.*)</h2>~", $line, $title) ? $cat = $title[1] : null;
2086 $val = array();
2087 if (preg_match("~<tr><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td></tr>~", $line, $val)) {
2088 $info_arr[trim($cat)][trim($val[1])] = $val[2];
2089 } elseif (preg_match("~<tr><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td></tr>~", $line, $val)) {
2090 $info_arr[trim($cat)][trim($val[1])] = array("local" => $val[2], "master" => $val[3]);
2091 }
2092 }
2093 return $info_arr;
2094}
2095
2102{
2103 global $langs, $conf;
2104
2105 $h = 0;
2106 $head = array();
2107
2108 $head[$h][0] = DOL_URL_ROOT."/admin/company.php";
2109 $head[$h][1] = $langs->trans("Company");
2110 $head[$h][2] = 'company';
2111 $h++;
2112
2113 $head[$h][0] = DOL_URL_ROOT."/admin/company_socialnetworks.php";
2114 $head[$h][1] = $langs->trans("SocialNetworksInformation");
2115 $head[$h][2] = 'socialnetworks';
2116
2117 $h++;
2118 $head[$h][0] = DOL_URL_ROOT."/admin/openinghours.php";
2119 $head[$h][1] = $langs->trans("OpeningHours");
2120 $head[$h][2] = 'openinghours';
2121 $h++;
2122
2123 $head[$h][0] = DOL_URL_ROOT."/admin/accountant.php";
2124 $head[$h][1] = $langs->trans("Accountant");
2125 $head[$h][2] = 'accountant';
2126 $h++;
2127
2128 complete_head_from_modules($conf, $langs, null, $head, $h, 'mycompany_admin', 'add');
2129
2130 complete_head_from_modules($conf, $langs, null, $head, $h, 'mycompany_admin', 'remove');
2131
2132 return $head;
2133}
2134
2141{
2142 global $langs, $conf, $user;
2143
2144 $h = 0;
2145 $head = array();
2146
2147 if (!empty($user->admin) && (empty($_SESSION['leftmenu']) || $_SESSION['leftmenu'] != 'email_templates')) {
2148 $head[$h][0] = DOL_URL_ROOT."/admin/mails.php";
2149 $head[$h][1] = $langs->trans("OutGoingEmailSetup");
2150 $head[$h][2] = 'common';
2151 $h++;
2152
2153 if (isModEnabled('mailing')) {
2154 $head[$h][0] = DOL_URL_ROOT."/admin/mails_emailing.php";
2155 $head[$h][1] = $langs->trans("OutGoingEmailSetupForEmailing", $langs->transnoentitiesnoconv("EMailing"));
2156 $head[$h][2] = 'common_emailing';
2157 $h++;
2158 }
2159
2160 if (isModEnabled('ticket')) {
2161 $head[$h][0] = DOL_URL_ROOT."/admin/mails_ticket.php";
2162 $head[$h][1] = $langs->trans("OutGoingEmailSetupForEmailing", $langs->transnoentitiesnoconv("Ticket"));
2163 $head[$h][2] = 'common_ticket';
2164 $h++;
2165 }
2166
2167 if (!getDolGlobalString('MAIN_MAIL_HIDE_CUSTOM_SENDING_METHOD_FOR_PASSWORD_RESET')) {
2168 $head[$h][0] = DOL_URL_ROOT."/admin/mails_passwordreset.php";
2169 $head[$h][1] = $langs->trans("OutGoingEmailSetupForEmailing", $langs->transnoentitiesnoconv("PasswordReset"));
2170 $head[$h][2] = 'common_passwordreset';
2171 $h++;
2172 }
2173 }
2174
2175 // Admin and non admin can view this menu entry, but it is not shown yet when we on user menu "Email templates"
2176 if (empty($_SESSION['leftmenu']) || $_SESSION['leftmenu'] != 'email_templates') {
2177 $head[$h][0] = DOL_URL_ROOT."/admin/mails_senderprofile_list.php";
2178 $head[$h][1] = $langs->trans("EmailSenderProfiles");
2179 $head[$h][2] = 'senderprofiles';
2180 $h++;
2181 }
2182
2183 $head[$h][0] = DOL_URL_ROOT."/admin/mails_templates.php";
2184 $head[$h][1] = $langs->trans("EMailTemplates");
2185 $head[$h][2] = 'templates';
2186 $h++;
2187
2188 $head[$h][0] = DOL_URL_ROOT."/admin/mails_ingoing.php";
2189 $head[$h][1] = $langs->trans("InGoingEmailSetup", $langs->transnoentitiesnoconv("EMailing"));
2190 $head[$h][2] = 'common_ingoing';
2191 $h++;
2192
2193 complete_head_from_modules($conf, $langs, null, $head, $h, 'email_admin', 'remove');
2194
2195 return $head;
2196}
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:67
versiontostring($versionarray)
Renvoi une version en chaine depuis une version en tableau.
Definition admin.lib.php:39
security_prepare_head()
Prepare array with list of tabs.
run_sql($sqlfile, $silent=1, $entity=0, $usesavepoint=1, $handler='', $okerror='default', $linelengthlimit=32768, $nocommentremoval=0, $offsetforchartofaccount=0, $colspan=0, $onlysqltoimportwebsite=0, $database='')
Launch a sql file.
addDocumentModel($name, $type, $label='', $description='')
Add document model used by doc generator.
dolibarr_set_const($db, $name, $value, $type='chaine', $visible=0, $note='', $entity=1)
Insert a parameter (key,value) into database (delete old key then insert it again).
purgeSessions($mysessionid)
Purge existing sessions.
unActivateModule($value, $requiredby=1)
Disable a module.
form_constantes($tableau, $strictw3c=2, $helptext='', $text='Value')
Show array with constants to edit.
activateModule($value, $withdeps=1, $noconfverification=0)
Enable a module.
dolibarr_del_const($db, $name, $entity=1)
Delete a constant.
complete_dictionary_with_modules(&$taborder, &$tabname, &$tablib, &$tabsql, &$tabsqlsort, &$tabfield, &$tabfieldvalue, &$tabfieldinsert, &$tabrowid, &$tabcond, &$tabhelp, &$tabcomplete)
Add external modules to list of dictionaries.
versiondolibarrarray()
Return version Dolibarr.
activateModulesRequiredByCountry($country_code)
Activate external modules mandatory when country is country_code.
delDocumentModel($name, $type)
Delete document model used by doc generator.
showModulesExludedForExternal($modules)
Show array with constants to edit.
versionphparray()
Return version PHP.
ihm_prepare_head()
Prepare array with list of tabs.
versioncompare($versionarray1, $versionarray2)
Compare 2 versions (stored into 2 arrays), to know if a version (a,b,c) is lower than (x,...
Definition admin.lib.php:71
modulehelp_prepare_head($object)
Prepare array with list of tabs.
listOfSessions()
Return list of session.
phpinfo_array()
Return the php_info into an array.
dolibarr_get_const($db, $name, $entity=1)
Get the value of a setup constant from database.
modules_prepare_head($nbofactivatedmodules, $nboftotalmodules, $nbmodulesnotautoenabled)
Prepare array with list of tabs.
complete_elementList_with_modules(&$elementList)
Search external modules to complete the list of contact element.
email_admin_prepare_head()
Return array head with list of tabs to view object information.
translation_prepare_head()
Prepare array with list of tabs.
company_admin_prepare_head()
Return array head with list of tabs to view object information.
defaultvalues_prepare_head()
Prepare array with list of tabs.
Class to manage a WYSIWYG editor.
Class DolibarrModules.
Class to manage generation of HTML components Only common components must be here.
Class permettant la generation du formulaire html d'envoi de mail unitaire Usage: $formail = new Form...
Class to manage hooks.
dolKeepOnlyPhpCode($str)
Keep only PHP code part from a HTML string page.
dolGetModulesDirs($subdir='')
Return list of directories that contain modules.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
img_down($titlealt='default', $selected=0, $moreclass='')
Show down arrow logo.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_sort_array(&$array, $index, $order='asc', $natsort=0, $case_sensitive=0, $keepindex=0)
Advanced sort array by the value of a given key, which produces ascending (default) or descending out...
dol_htmlentities($string, $flags=ENT_QUOTES|ENT_SUBSTITUTE, $encoding='UTF-8', $double_encode=false)
Replace htmlentities functions.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
complete_head_from_modules($conf, $langs, $object, &$head, &$h, $type, $mode='add', $filterorigmodule='')
Complete or removed entries into a head array (used to build tabs).
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79
dolListSessions()
List sessions in db.
dolEncrypt($chain, $key='', $ciphering='', $forceseed='')
Encode a string with a symmetric encryption.
dolDecrypt($chain, $key='')
Decode a string with a symmetric encryption.
checkPHPCode(&$phpfullcodestringold, &$phpfullcodestring)
Check a new string containing only php code (including <php tag)