dolibarr 25.0.0-alpha
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-2026 MDW <mdeweerd@users.noreply.github.com>
8 * Copyright (C) 2024-2026 Frédéric France <frederic.france@free.fr>
9 * Copyright (C) 2026 Alexandre Spangaro <alexandre@inovea-conseil.com>
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <https://www.gnu.org/licenses/>.
23 * or see https://www.gnu.org/
24 */
25
31require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
32
40function versiontostring($versionarray)
41{
42 $string = '?';
43 if (isset($versionarray[0])) {
44 $string = $versionarray[0];
45 }
46 if (isset($versionarray[1])) {
47 $string .= '.'.$versionarray[1];
48 }
49 if (isset($versionarray[2])) {
50 $string .= '.'.$versionarray[2];
51 }
52 return $string;
53}
54
72function versioncompare($versionarray1, $versionarray2)
73{
74 $ret = 0;
75 $level = 0;
76 $count1 = count($versionarray1);
77 $count2 = count($versionarray2);
78 $maxcount = max($count1, $count2);
79 while ($level < $maxcount) {
80 $operande1 = isset($versionarray1[$level]) ? $versionarray1[$level] : 0;
81 $operande2 = isset($versionarray2[$level]) ? $versionarray2[$level] : 0;
82 if (preg_match('/alpha|dev/i', $operande1)) {
83 $operande1 = -5;
84 }
85 if (preg_match('/alpha|dev/i', $operande2)) {
86 $operande2 = -5;
87 }
88 if (preg_match('/beta$/i', $operande1)) {
89 $operande1 = -4;
90 }
91 if (preg_match('/beta$/i', $operande2)) {
92 $operande2 = -4;
93 }
94 if (preg_match('/beta([0-9])+/i', $operande1)) {
95 $operande1 = -3;
96 }
97 if (preg_match('/beta([0-9])+/i', $operande2)) {
98 $operande2 = -3;
99 }
100 if (preg_match('/rc$/i', $operande1)) {
101 $operande1 = -2;
102 }
103 if (preg_match('/rc$/i', $operande2)) {
104 $operande2 = -2;
105 }
106 if (preg_match('/rc([0-9])+/i', $operande1)) {
107 $operande1 = -1;
108 }
109 if (preg_match('/rc([0-9])+/i', $operande2)) {
110 $operande2 = -1;
111 }
112 $level++;
113 //print 'level '.$level.' '.$operande1.'-'.$operande2.'<br>';
114 if ($operande1 < $operande2) {
115 $ret = -$level;
116 break;
117 }
118 if ($operande1 > $operande2) {
119 $ret = $level;
120 break;
121 }
122 }
123 //print join('.',$versionarray1).'('.count($versionarray1).') / '.join('.',$versionarray2).'('.count($versionarray2).') => '.$ret.'<br>'."\n";
124 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
125}
126
127
135{
136 return explode('.', PHP_VERSION);
137}
138
146{
147 return preg_split('/[\-\.]/', DOL_VERSION);
148}
149
150
174function run_sql($sqlfile, $silent = 1, $entity = 0, $usesavepoint = 1, $handler = '', $okerror = 'default', $linelengthlimit = 32768, $nocommentremoval = 0, $offsetforchartofaccount = 0, $colspan = 0, $onlysqltoimportwebsite = 0, $database = '')
175{
176 global $db, $conf, $langs;
177
178 dol_syslog("Admin.lib::run_sql run sql file ".$sqlfile." silent=".$silent." entity=".$entity." usesavepoint=".$usesavepoint." handler=".$handler." okerror=".$okerror, LOG_DEBUG);
179
180 if (!is_numeric($linelengthlimit)) {
181 dol_syslog("Admin.lib::run_sql param linelengthlimit is not a numeric", LOG_ERR);
182 return -1;
183 }
184
185 $ok = 0;
186 $error = 0;
187 $i = 0;
188 $buffer = '';
189 $arraysql = array();
190
191 // Get version of database
192 $versionarray = $db->getVersionArray();
193
194 // TODO Restore all sequences "/* new line */\n" into "" in $sqlfile.
195
196 $fp = fopen($sqlfile, "r");
197 if ($fp) {
198 while (!feof($fp)) {
199 // Warning fgets with second parameter that is null or 0 hang.
200 if ($linelengthlimit > 0) {
201 $buf = fgets($fp, $linelengthlimit);
202 } else {
203 $buf = fgets($fp);
204 }
205
206 // Test if request must be ran only for particular database or version (if yes, we must remove the -- comment)
207 $reg = array();
208 if (preg_match('/^--\sV(MYSQL|PGSQL)([^\s]*)/i', $buf, $reg)) {
209 $qualified = 1;
210
211 // restrict on database type
212 if (!empty($reg[1])) {
213 if (!preg_match('/'.preg_quote($reg[1], '/').'/i', $db->type)) {
214 $qualified = 0;
215 }
216 }
217
218 // restrict on version
219 if ($qualified) {
220 if (!empty($reg[2])) {
221 if (is_numeric($reg[2])) { // This is a version
222 $versionrequest = explode('.', $reg[2]);
223 if (!count($versionrequest) || !count($versionarray) || versioncompare($versionrequest, $versionarray) > 0) {
224 $qualified = 0;
225 }
226 } else { // This is a test on a constant. For example when we have -- VMYSQLUTF8UNICODE, we test constant $conf->global->UTF8UNICODE
227 $dbcollation = strtoupper(preg_replace('/_/', '', (string) $conf->db->dolibarr_main_db_collation));
228 if (empty($conf->db->dolibarr_main_db_collation) || ($reg[2] != $dbcollation)) {
229 $qualified = 0;
230 }
231 }
232 }
233 }
234
235 if ($qualified) {
236 // Version qualified, delete SQL comments
237 $buf = preg_replace('/^--\sV(MYSQL|PGSQL)([^\s]*)/i', '', $buf);
238 //print "Line $i qualified by version: ".$buf.'<br>';
239 }
240 }
241
242 // Add line buf to buffer if not a comment
243 if ($nocommentremoval || !preg_match('/^\s*--/', $buf)) {
244 if (empty($nocommentremoval)) {
245 $buf = preg_replace('/([,;ERLT05\‍)])\s+--\s.*$/i', '\1', $buf); // remove comment on lines that does not start with --, like "... -- a comment"
246 $buf = preg_replace('/([,;ERLT05\‍)])\s+--$/i', '\1', $buf); // remove comment on lines that does not start with --, like "... --"
247 }
248 if ($buffer) {
249 $buffer .= ' ';
250 }
251 $buffer .= trim($buf);
252 }
253
254 //print $buf.'<br>';exit;
255
256 if (preg_match('/;\s*$/', $buffer)) {
257 // If string contains the end of request string (';'), we save it into $arraysql.
258 // Found new request
259 if ($buffer) {
260 $arraysql[$i] = $buffer; // @phan-suppress-current-line SqlInjection
261 }
262 $i++;
263 $buffer = '';
264 }
265 }
266
267 if ($buffer) {
268 $arraysql[$i] = $buffer; // @phan-suppress-current-line SqlInjection
269 }
270 fclose($fp);
271 } else {
272 dol_syslog("Admin.lib::run_sql failed to open file ".$sqlfile, LOG_ERR);
273 }
274
275 // Loop on each request to see if there is a __+MAX_table__ key
276 $listofmaxrowid = array(); // This is a cache table
277 foreach ($arraysql as $i => $sql) {
278 $newsql = $sql;
279
280 // Replace __+MAX_table__ with max of table
281 while (preg_match('/__\+MAX_([A-Za-z0-9_]+)__/i', $newsql, $reg)) {
282 $table = $reg[1];
283 if (!isset($listofmaxrowid[$table])) {
284 //var_dump($db);
285 $sqlgetrowid = 'SELECT MAX(rowid) as max from '.preg_replace('/^llx_/', MAIN_DB_PREFIX, $table);
286 $resql = $db->query($sqlgetrowid);
287 if ($resql) {
288 $obj = $db->fetch_object($resql);
289 $listofmaxrowid[$table] = $obj->max;
290 if (empty($listofmaxrowid[$table])) {
291 $listofmaxrowid[$table] = 0;
292 }
293 } else {
294 if (!$silent) {
295 print '<tr><td class="tdtop"'.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
296 print '<div class="error">'.$langs->trans("Failed to get max rowid for ".$table)."</div>";
297 print '</td></tr>';
298 }
299 $error++;
300 break;
301 }
302 }
303 // Replace __+MAX_llx_table__ with +999
304 $from = '__+MAX_'.$table.'__';
305 $to = '+'.$listofmaxrowid[$table];
306 $newsql = str_replace($from, $to, $newsql); // @phan-suppress-current-line SqlInjection
307 dol_syslog('Admin.lib::run_sql New Request '.($i + 1).' (replacing '.$from.' to '.$to.')', LOG_DEBUG);
308
309 $arraysql[$i] = $newsql;
310 }
311
312 if ($offsetforchartofaccount > 0) {
313 // Replace lines
314 // '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,...'
315 // with
316 // '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,...'
317 // Note: string with 'PCG99-ABREGE','CAPIT', 1234 instead of 'PCG99-ABREGE','CAPIT', '1234' is also supported
318 $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);
319 $newsql = preg_replace('/([,\s])0 \+ '.((int) $offsetforchartofaccount).'/ims', '\1 0', $newsql);
320 //var_dump($newsql);
321 $arraysql[$i] = $newsql;
322
323 // FIXME Because we force the rowid during insert, we must also update the sequence with postgresql by running
324 // SELECT dol_util_rebuild_sequences();
325 }
326 }
327
328 // Loop on each request to execute request
329 $cursorinsert = 0;
330 $listofinsertedrowid = array();
331 $keyforsqlfile = md5($sqlfile);
332 foreach ($arraysql as $i => $sql) {
333 if ($sql) {
334 // Test if the SQL is allowed SQL
335 if ($onlysqltoimportwebsite) {
336 $newsql = str_replace(array("\'"), '__BACKSLASHQUOTE__', $sql); // Replace the \' char
337
338 // Remove all strings contents including the ' so we can analyse SQL instruction only later
339 $l = strlen($newsql);
340 $is = 0;
341 $quoteopen = 0;
342 $newsqlclean = '';
343 while ($is < $l) {
344 $char = $newsql[$is];
345 if ($char == "'") {
346 if ($quoteopen) {
347 $quoteopen--;
348 } else {
349 $quoteopen++;
350 }
351 } elseif (empty($quoteopen)) {
352 $newsqlclean .= $char;
353 }
354 $is++;
355 }
356 $newsqlclean = str_replace(array("null"), '__000__', $newsqlclean);
357 //print $newsqlclean."<br>\n";
358
359 $qualified = 0;
360
361 // A very small control. This can still by bypassed by adding a second SQL request concatenated
362 if (preg_match('/^--/', $newsqlclean)) {
363 $qualified = 1;
364 } elseif (preg_match('/^UPDATE llx_website SET \w+ = \d+\+\d+ WHERE rowid = \d+;$/', $newsqlclean)) {
365 $qualified = 1;
366 } elseif (preg_match('/^INSERT INTO llx_website_page\‍([a-z0-9_\s,]+\‍) VALUES\‍([0-9_\s,\+]+\‍);$/', $newsqlclean)) {
367 // Insert must match
368 // 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, , , , , );
369 $qualified = 1;
370 }
371
372 // Another check to allow some legitimate original urls
373 if (!$qualified) {
374 if (preg_match('/^UPDATE llx_website SET \w+ = \'[a-zA-Z,\s]*\' WHERE rowid = \d+;$/', $sql)) {
375 $qualified = 1;
376 }
377 }
378
379 // We also check content
380 $extractphp = dolKeepOnlyPhpCode($sql);
381 $extractphpold = '';
382
383 // Security analysis
384 $errorphpcheck = checkPHPCode($extractphpold, $extractphp); // Contains the setEventMessages
385 if ($errorphpcheck) {
386 $error++;
387 //print 'Request '.($i + 1)." contains non allowed instructions.<br>\n";
388 //print "newsqlclean = ".$newsqlclean."<br>\n";
389 dol_syslog('Admin.lib::run_sql Request '.($i + 1)." contains PHP code and checking this code returns errorphpcheck='.$errorphpcheck.'", LOG_WARNING);
390 dol_syslog("sql=".$sql, LOG_DEBUG);
391 break;
392 }
393
394
395 if (!$qualified) {
396 $error++;
397 //print 'Request '.($i + 1)." contains non allowed instructions.<br>\n";
398 //print "newsqlclean = ".$newsqlclean."<br>\n";
399 dol_syslog('Admin.lib::run_sql Request '.($i + 1)." contains non allowed instructions.", LOG_WARNING);
400 dol_syslog('$newsqlclean='.$newsqlclean, LOG_DEBUG);
401 break;
402 }
403 }
404
405 // Replace the prefix tables
406 if (MAIN_DB_PREFIX != 'llx_') {
407 $sql = preg_replace('/llx_/i', MAIN_DB_PREFIX, $sql);
408 }
409
410 if (!empty($handler)) {
411 $sql = preg_replace('/__HANDLER__/i', "'".$db->escape($handler)."'", $sql);
412 }
413
414 if (!empty($database)) {
415 $sql = preg_replace('/__DATABASE__/i', $db->escape($database), $sql);
416 }
417
418 $newsql = preg_replace('/__ENTITY__/i', (!empty($entity) ? ((int) $entity) : (string) ((int) $conf->entity)), $sql);
419
420 // Add log of request
421 if (!$silent) {
422 print '<tr class="trforrunsql'.$keyforsqlfile.'"><td class="tdtop opacitymedium"'.($colspan ? ' colspan="'.$colspan.'"' : '').'>'.$langs->trans("Request").' '.($i + 1)." sql='".dol_htmlentities($newsql, ENT_NOQUOTES)."'</td></tr>\n";
423 }
424 dol_syslog('Admin.lib::run_sql Request '.($i + 1), LOG_DEBUG);
425 $sqlmodified = 0;
426
427 // Replace for encrypt data
428 if (preg_match_all('/__ENCRYPT\‍(\'([^\']+)\'\‍)__/i', $newsql, $reg)) {
429 $num = count($reg[0]);
430
431 for ($j = 0; $j < $num; $j++) {
432 $from = $reg[0][$j]; // @phan-suppress-current-line SqlInjection
433 $to = $db->encrypt($reg[1][$j]);
434 $newsql = str_replace($from, $to, $newsql); // @phan-suppress-current-line SqlInjection
435 }
436 $sqlmodified++;
437 }
438
439 // Replace for decrypt data
440 if (preg_match_all('/__DECRYPT\‍(\'([A-Za-z0-9_]+)\'\‍)__/i', $newsql, $reg)) {
441 $num = count($reg[0]);
442
443 for ($j = 0; $j < $num; $j++) {
444 $from = $reg[0][$j]; // @phan-suppress-current-line SqlInjection
445 $to = $db->decrypt($reg[1][$j]);
446 $newsql = str_replace($from, $to, $newsql); // @phan-suppress-current-line SqlInjection
447 }
448 $sqlmodified++;
449 }
450
451 // Replace __x__ with the rowid of the result of the insert number x
452 while (preg_match('/__([0-9]+)__/', $newsql, $reg)) {
453 $cursor = $reg[1];
454 if (empty($listofinsertedrowid[$cursor])) {
455 if (!$silent) {
456 print '<tr><td class="tdtop"'.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
457 print '<div class="error">'.$langs->trans("FileIsNotCorrect")."</div>";
458 print '</td></tr>';
459 }
460 $error++;
461 break;
462 }
463
464 $from = '__'.$cursor.'__'; // @phan-suppress-current-line SqlInjection
465 $to = $listofinsertedrowid[$cursor];
466 $newsql = str_replace($from, $to, $newsql); // @phan-suppress-current-line SqlInjection
467 $sqlmodified++;
468 }
469
470 if ($sqlmodified) {
471 dol_syslog('Admin.lib::run_sql New Request '.($i + 1), LOG_DEBUG);
472 }
473
474 $result = $db->query($newsql, $usesavepoint);
475 if ($result) {
476 if (!$silent) {
477 print '<!-- Result = OK -->'."\n";
478 }
479
480 if (preg_replace('/insert into ([^\s]+)/i', $newsql, $reg)) {
481 $cursorinsert++;
482
483 // It's an insert
484 $table = preg_replace('/([^a-zA-Z_]+)/i', '', $reg[1]);
485 $insertedrowid = $db->last_insert_id($table);
486 $listofinsertedrowid[$cursorinsert] = $insertedrowid;
487 dol_syslog('Admin.lib::run_sql Insert nb '.$cursorinsert.', done in table '.$table.', rowid is '.$listofinsertedrowid[$cursorinsert], LOG_DEBUG);
488 }
489 } else {
490 $errno = $db->errno();
491 if (!$silent) {
492 print '<!-- Result = '.$errno.' -->'."\n";
493 }
494
495 // Define list of errors we accept (array $okerrors)
496 $okerrors = array( // By default
497 'DB_ERROR_TABLE_ALREADY_EXISTS',
498 'DB_ERROR_COLUMN_ALREADY_EXISTS',
499 'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
500 'DB_ERROR_TABLE_OR_KEY_ALREADY_EXISTS', // PgSql use same code for table and key already exist
501 'DB_ERROR_RECORD_ALREADY_EXISTS',
502 'DB_ERROR_NOSUCHTABLE',
503 'DB_ERROR_NOSUCHFIELD',
504 'DB_ERROR_NO_FOREIGN_KEY_TO_DROP',
505 'DB_ERROR_NO_INDEX_TO_DROP',
506 'DB_ERROR_CANNOT_CREATE', // Qd contrainte deja existante
507 'DB_ERROR_CANT_DROP_PRIMARY_KEY',
508 'DB_ERROR_PRIMARY_KEY_ALREADY_EXISTS',
509 'DB_ERROR_22P02'
510 );
511 // The foreign key of the category link tables can target a table owned by a module that is not
512 // enabled, llx_categorie_mo referencing llx_mrp_mo for instance, so the key can not be created
513 // yet. The module creates it when it is enabled. Elsewhere this error must stay fatal, since it
514 // is what reports orphans or duplicates when a key is added on corrupted data.
515 if (preg_match('/^\s*ALTER\s+TABLE\s+[^\s]+_categorie_mo\s.*REFERENCES\s+[^\s(]+_mrp_mo\s*\‍(/i', $newsql)) {
516 $okerrors[] = 'DB_ERROR_CANNOT_ADD_FOREIGN_KEY_CONSTRAINT';
517 }
518
519 if ($okerror == 'none') {
520 $okerrors = array();
521 }
522
523 // Is it an error we accept
524 if (!in_array($errno, $okerrors)) {
525 if (!$silent) {
526 print '<tr><td class="tdtop"'.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
527 print '<div class="error">'.$langs->trans("Error")." ".$db->errno()." (Req ".($i + 1)."): ".$newsql."<br>".$db->error()."</div>";
528 print '</td></tr>'."\n";
529 }
530 dol_syslog('Admin.lib::run_sql Request '.($i + 1)." Error ".$db->errno()." ".$newsql."<br>".$db->error(), LOG_ERR);
531 $error++;
532 }
533 }
534 }
535 }
536
537 if (!$silent) {
538 print '<tr><td>'.$langs->trans("ProcessMigrateScript").'</td>';
539 print '<td class="right">';
540 if ($error == 0) {
541 print '<span class="ok">'.$langs->trans("Success").'</span>';
542 } else {
543 print '<span class="error">'.$langs->trans("Error").'</span>';
544 }
545
546 //if (!empty($conf->use_javascript_ajax)) { // use_javascript_ajax is not defined
547 print '<script type="text/javascript">
548 jQuery(document).ready(function() {
549 function init_trrunsql'.$keyforsqlfile.'()
550 {
551 console.log("toggle .trforrunsql'.$keyforsqlfile.'");
552 jQuery(".trforrunsql'.$keyforsqlfile.'").toggle();
553 }
554 init_trrunsql'.$keyforsqlfile.'();
555 jQuery(".trforrunsqlshowhide'.$keyforsqlfile.'").click(function() {
556 init_trrunsql'.$keyforsqlfile.'();
557 });
558 });
559 </script>';
560 if (count($arraysql)) {
561 print ' - <a class="reposition trforrunsqlshowhide'.$keyforsqlfile.' reposition" href="#" title="'.($langs->trans("ShowHideTheNRequests", count($arraysql))).'">'.$langs->trans("ShowHideDetails").'</a>';
562 } else {
563 print ' - <span class="opacitymedium">'.$langs->trans("ScriptIsEmpty").'</span>';
564 }
565 //}
566
567 print '</td></tr>'."\n";
568 }
569
570 if ($error == 0) {
571 $ok = 1;
572 } else {
573 $ok = 0;
574 }
575
576 return $ok;
577}
578
579
590function dolibarr_del_const($db, $name, $entity = 1)
591{
592 global $conf, $hookmanager;
593
594 if (empty($name)) {
595 dol_print_error(null, 'Error call dolibar_del_const with parameter name empty');
596 return -1;
597 }
598 if (! is_object($hookmanager)) {
599 require_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
600 $hookmanager = new HookManager($db);
601 }
602
603 $parameters = array(
604 'name' => $name,
605 'entity' => $entity,
606 );
607
608 $reshook = $hookmanager->executeHooks('dolibarrDelConst', $parameters); // Note that $action and $object may have been modified by some hooks
609 if ($reshook != 0) {
610 return $reshook;
611 }
612
613 $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
614 $sql .= " WHERE (".$db->decrypt('name')." = '".$db->escape((string) $name)."'";
615 if (is_numeric($name)) { // This case seems used in the setup of constant page only, to delete a line.
616 $sql .= " OR rowid = ".((int) $name);
617 }
618 $sql .= ")";
619 if ($entity >= 0) {
620 $sql .= " AND entity = ".((int) $entity);
621 }
622
623 dol_syslog("admin.lib::dolibarr_del_const", LOG_DEBUG);
624 $resql = $db->query($sql);
625 if ($resql) {
626 $conf->global->$name = '';
627 return 1;
628 } else {
629 dol_print_error($db);
630 return -1;
631 }
632}
633
646function dolibarr_get_const($db, $name, $entity = 1)
647{
648 $value = '';
649
650 $sql = "SELECT ".$db->sanitize($db->decrypt('value'))." as value";
651 $sql .= " FROM ".MAIN_DB_PREFIX."const";
652 $sql .= " WHERE name = '".$db->escape($db->encrypt($name, 0))."'";
653 $sql .= " AND entity = ".((int) $entity);
654
655 $resql = $db->query($sql);
656 if ($resql) {
657 $obj = $db->fetch_object($resql);
658 if ($obj) {
659 include_once DOL_DOCUMENT_ROOT.'/core/lib/security.lib.php';
660 $value = dolDecrypt($obj->value);
661 }
662 }
663 return $value;
664}
665
666
681function dolibarr_set_const($db, $name, $value, $type = 'chaine', $visible = 0, $note = '', $entity = 1)
682{
683 global $conf, $hookmanager, $user;
684
685 // Clean parameters
686 $name = trim($name);
687 $value = (string) $value;
688
689 // Check parameters
690 if (empty($name)) {
691 dol_print_error($db, "Error: Call to function dolibarr_set_const with wrong parameters");
692 exit;
693 }
694 if (! is_object($hookmanager)) {
695 require_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
696 $hookmanager = new HookManager($db);
697 }
698
699 $value = (string) $value; // We force type string (may be int)
700
701 $parameters = array(
702 'name' => $name,
703 'value' => $value,
704 'type' => $type,
705 'visible' => $visible,
706 'note' => $note,
707 'entity' => $entity,
708 );
709
710 $reshook = $hookmanager->executeHooks('dolibarrSetConst', $parameters); // Note that $action and $object may have been modified by some hooks
711 if ($reshook != 0) {
712 return $reshook;
713 }
714
715 //dol_syslog("dolibarr_set_const name=$name, value=$value type=$type, visible=$visible, note=$note entity=$entity");
716
717 $userid = (!empty($user) && is_object($user) && $user->id > 0) ? (int) $user->id : 0;
718
719 // Keep the original creator across the delete+recreate done below
720 $fk_user_creat = 0;
721 $sql = "SELECT fk_user_creat FROM ".MAIN_DB_PREFIX."const";
722 $sql .= " WHERE name = ".$db->encrypt($name);
723 if ($entity >= 0) {
724 $sql .= " AND entity = ".((int) $entity);
725 }
726 $resql = $db->query($sql);
727 if ($resql) {
728 $obj = $db->fetch_object($resql);
729 if ($obj && $obj->fk_user_creat > 0) {
730 $fk_user_creat = (int) $obj->fk_user_creat;
731 }
732 }
733 if (empty($fk_user_creat)) {
734 $fk_user_creat = $userid;
735 }
736
737 $db->begin();
738
739 $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
740 $sql .= " WHERE name = ".$db->encrypt($name);
741 if ($entity >= 0) {
742 $sql .= " AND entity = ".((int) $entity);
743 }
744
745 dol_syslog("admin.lib::dolibarr_set_const", LOG_DEBUG);
746 $resql = $db->query($sql);
747
748 if (strcmp($value, '')) { // true if different. Must work for $value='0' or $value=0
749 $tmpname = preg_replace('/(_TEST|_PROD)$/', '', $name);
750 if (!preg_match('/^(MAIN_LOGEVENTS|MAIN_AGENDA_ACTIONAUTO)/', $name)
751 && (preg_match('/(_KEY|_EXPORTKEY|_SECUREKEY|_SERVERKEY|_PASS|_PASSWORD|_PW|_PW_TICKET|_PW_EMAILING|_SECRET|_TOKEN|_REFRESH)$/', $tmpname))) {
752 // This seems a sensitive constant, we encrypt its value
753 // To list all sensitive constant, you can make a
754 // SELECT * from llx_const WHERE name like '%\_KEY' or name like '%\_EXPORTKEY' or name like '%\_SECUREKEY' ...
755 include_once DOL_DOCUMENT_ROOT.'/core/lib/security.lib.php';
756 $newvalue = dolEncrypt($value); // Encode using dolcrypt() function
757 } else {
758 $newvalue = $value;
759 }
760
761 $sql = "INSERT INTO ".MAIN_DB_PREFIX."const(name, value, type, visible, note, entity, fk_user_creat, fk_user_modif)";
762 $sql .= " VALUES (";
763 $sql .= $db->encrypt($name);
764 $sql .= ", ".$db->encrypt($newvalue);
765 $sql .= ", '".$db->escape($type)."', ".((int) $visible).", '".$db->escape($note)."', ".((int) $entity);
766 $sql .= ", ".($fk_user_creat > 0 ? (int) $fk_user_creat : "NULL");
767 $sql .= ", ".($userid > 0 ? (int) $userid : "NULL").")";
768
769 //print "sql".$value."-".pg_escape_string($value)."-".$sql;exit;
770 //print "xx".$db->escape($value);
771 dol_syslog("admin.lib::dolibarr_set_const", LOG_DEBUG);
772 $resql = $db->query($sql);
773
774 if (!$resql) {
775 // This function is also called by very old migration scripts (upgrade of a Dolibarr instance from an
776 // old version), at a point of the upgrade chain where llx_const may not yet have the fk_user_creat/fk_user_modif
777 // columns (added by a later migration). Fall back to the legacy insert so old upgrade paths keep working.
778 $sql = "INSERT INTO ".MAIN_DB_PREFIX."const(name, value, type, visible, note, entity)";
779 $sql .= " VALUES (";
780 $sql .= $db->encrypt($name);
781 $sql .= ", ".$db->encrypt($newvalue);
782 $sql .= ", '".$db->escape($type)."', ".((int) $visible).", '".$db->escape($note)."', ".((int) $entity).")";
783
784 dol_syslog("admin.lib::dolibarr_set_const", LOG_DEBUG);
785 $resql = $db->query($sql);
786 }
787 }
788
789 if ($resql) {
790 $db->commit();
791 $conf->global->$name = $value;
792 return 1;
793 } else {
794 $db->rollback();
795 return -1;
796 }
797}
798
799
800
801
810function modules_prepare_head($nbofactivatedmodules, $nboftotalmodules, $nbmodulesnotautoenabled)
811{
812 global $langs, $form;
813
814 $desc = $langs->trans("ModulesDesc", '{picto}');
815 $desc = str_replace('{picto}', img_picto('', 'switch_off'), $desc);
816
817 $h = 0;
818 $head = array();
819
820 $mode = getDolGlobalString('MAIN_MODULE_SETUP_ON_LIST_BY_DEFAULT', 'commonkanban');
821 $head[$h][0] = dolBuildUrl(DOL_URL_ROOT.'/admin/modules.php', ['mode' => $mode]);
822 if ($nbmodulesnotautoenabled < getDolGlobalInt('MAIN_MIN_NB_ENABLED_MODULE_FOR_WARNING', 1)) { // If only minimal initial modules enabled)
823 //$head[$h][1] = $form->textwithpicto($langs->trans("AvailableModules"), $desc);
824 $head[$h][1] = $langs->trans("AvailableModules");
825 $head[$h][1] .= $form->textwithpicto('', $langs->trans("YouMustEnableOneModule").'.<br><br><span class="opacitymedium">'.$desc.'</span>', 1, 'warning');
826 } else {
827 //$head[$h][1] = $langs->trans("AvailableModules").$form->textwithpicto('<span class="badge marginleftonly">'.$nbofactivatedmodules.' / '.$nboftotalmodules.'</span>', $desc, 1, 'help', '', 1, 3);
828 $head[$h][1] = $langs->trans("AvailableModules").'<span class="badge marginleftonly">'.$nbofactivatedmodules.' / '.$nboftotalmodules.'</span>';
829 }
830 $head[$h][2] = 'modules';
831 $h++;
832
833 $head[$h][0] = dolBuildUrl(DOL_URL_ROOT.'/admin/modules.php', ['mode' => 'marketplace']);
834 $head[$h][1] = $langs->trans("ModulesMarketPlaces");
835 $head[$h][2] = 'marketplace';
836 $h++;
837
838 $head[$h][0] = dolBuildUrl(DOL_URL_ROOT.'/admin/modules.php', ['mode' => 'deploy']);
839 $head[$h][1] = $langs->trans("AddExtensionThemeModuleOrOther");
840 $head[$h][2] = 'deploy';
841 $h++;
842
843 $head[$h][0] = dolBuildUrl(DOL_URL_ROOT.'/admin/modules.php', ['mode' => 'develop']);
844 $head[$h][1] = $langs->trans("ModulesDevelopYourModule");
845 $head[$h][2] = 'develop';
846 $h++;
847
848 return $head;
849}
850
857{
858 global $langs, $conf;
859 $h = 0;
860 $head = array();
861
862 $head[$h][0] = dolBuildUrl(DOL_URL_ROOT.'/admin/ihm.php', ['mode' => 'other']);
863 $head[$h][1] = $langs->trans("LanguageAndPresentation");
864 $head[$h][2] = 'other';
865 $h++;
866
867 $head[$h][0] = dolBuildUrl(DOL_URL_ROOT.'/admin/ihm.php', ['mode' => 'template']);
868 $head[$h][1] = $langs->trans("SkinAndColors");
869 $head[$h][2] = 'template';
870 $h++;
871
872 $head[$h][0] = dolBuildUrl(DOL_URL_ROOT.'/admin/ihm.php', ['mode' => 'dashboard']);
873 $head[$h][1] = $langs->trans("Dashboard");
874 $head[$h][2] = 'dashboard';
875 $h++;
876
877 $head[$h][0] = dolBuildUrl(DOL_URL_ROOT.'/admin/ihm.php', ['mode' => 'login']);
878 $head[$h][1] = $langs->trans("LoginPage");
879 $head[$h][2] = 'login';
880 $h++;
881
882 $head[$h][0] = dolBuildUrl(DOL_URL_ROOT.'/admin/ihm.php', ['mode' => 'css']);
883 $head[$h][1] = $langs->trans("CSSPage");
884 $head[$h][2] = 'css';
885 $h++;
886
887 /* Not a user setup of a feature. Useless for an end users, so has been moved into the Modulebuilder main page (for dev).
888 $head[$h][0] = dolBuildUrl(DOL_URL_ROOT.'/admin/tools/ui/index.php');
889 $head[$h][1] = $langs->trans("UxComponentsDoc").' '.img_picto('', 'external-link-square-alt');
890 $head[$h][2] = 'ux';
891 $h++;
892 */
893
894 complete_head_from_modules($conf, $langs, null, $head, $h, 'ihm_admin');
895
896 complete_head_from_modules($conf, $langs, null, $head, $h, 'ihm_admin', 'remove');
897
898
899 return $head;
900}
901
902
909{
910 global $db, $langs, $conf;
911 $h = 0;
912 $head = array();
913
914 $head[$h][0] = dolBuildUrl(DOL_URL_ROOT."/admin/security_other.php");
915 $head[$h][1] = $langs->trans("Miscellaneous");
916 $head[$h][2] = 'misc';
917 $h++;
918
919 $head[$h][0] = dolBuildUrl(DOL_URL_ROOT."/admin/security_captcha.php");
920 $head[$h][1] = $langs->trans("Captcha");
921 $head[$h][2] = 'captcha';
922 $h++;
923
924 $head[$h][0] = dolBuildUrl(DOL_URL_ROOT."/admin/security.php");
925 $head[$h][1] = $langs->trans("Passwords");
926 $head[$h][2] = 'passwords';
927 $h++;
928
929 $head[$h][0] = dolBuildUrl(DOL_URL_ROOT."/admin/security_file.php");
930 $head[$h][1] = $langs->trans("Files").' ('.$langs->trans("UploadName").' | '.$langs->trans("Download").')';
931 $head[$h][2] = 'file';
932 $h++;
933
934 /*
935 $head[$h][0] = dolBuildUrl(DOL_URL_ROOT."/admin/security_file_download.php");
936 $head[$h][1] = $langs->trans("Files").' ('.$langs->trans("Download").')';
937 $head[$h][2] = 'filedownload';
938 $h++;
939 */
940
941 $head[$h][0] = dolBuildUrl(DOL_URL_ROOT."/admin/proxy.php");
942 $head[$h][1] = $langs->trans("ExternalAccess");
943 $head[$h][2] = 'proxy';
944 $h++;
945
946 $head[$h][0] = dolBuildUrl(DOL_URL_ROOT."/admin/events.php");
947 $head[$h][1] = $langs->trans("Audit");
948 $head[$h][2] = 'audit';
949 $h++;
950
951 $head[$h][0] = dolBuildUrl(DOL_URL_ROOT."/admin/openid_connect.php");
952 $head[$h][1] = $langs->trans("OpenIDconnectSetup");
953 $head[$h][2] = 'openid';
954 $h++;
955
956
957 // Show permissions lines
958 $nbPerms = 0;
959 $sql = "SELECT COUNT(r.id) as nb";
960 $sql .= " FROM ".MAIN_DB_PREFIX."rights_def as r";
961 $sql .= " WHERE r.libelle NOT LIKE 'tou%'"; // On ignore droits "tous"
962 $sql .= " AND entity = ".((int) $conf->entity);
963 $sql .= " AND bydefault = 1";
964 if (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) {
965 $sql .= " AND r.perms NOT LIKE '%_advance'"; // Hide advanced perms if option is not enabled
966 }
967 $resql = $db->query($sql);
968 if ($resql) {
969 $obj = $db->fetch_object($resql);
970 if ($obj) {
971 $nbPerms = $obj->nb;
972 }
973 } else {
974 dol_print_error($db);
975 }
976
977 if (getDolGlobalString('MAIN_SECURITY_USE_DEFAULT_PERMISSIONS')) {
978 $head[$h][0] = dolBuildUrl(DOL_URL_ROOT."/admin/perms.php");
979 $head[$h][1] = $langs->trans("DefaultRights");
980 if ($nbPerms > 0) {
981 $head[$h][1] .= (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') ? '<span class="badge marginleftonlyshort">'.$nbPerms.'</span>' : '');
982 }
983 $head[$h][2] = 'default';
984 $h++;
985 }
986
987 $head[$h][0] = dolBuildUrl(DOL_URL_ROOT."/admin/security_headers_http.php");
988 $head[$h][1] = $langs->trans("MainHttpSecurityHeaders");
989 $head[$h][2] = 'headers_http';
990 $h++;
991
992 return $head;
993}
994
1002{
1003 global $langs, $conf;
1004 $h = 0;
1005 $head = array();
1006
1007 // FIX for compatibility habitual tabs
1008 $object->id = $object->numero;
1009
1010 $head[$h][0] = dolBuildUrl(DOL_URL_ROOT.'/admin/modulehelp.php', ['id' => $object->id, 'mode' => 'desc']);
1011 $head[$h][1] = $langs->trans("Description");
1012 $head[$h][2] = 'desc';
1013 $h++;
1014
1015 $head[$h][0] = dolBuildUrl(DOL_URL_ROOT.'/admin/modulehelp.php', ['id' => $object->id, 'mode' => 'feature']);
1016 $head[$h][1] = $langs->trans("TechnicalServicesProvided");
1017 $head[$h][2] = 'feature';
1018 $h++;
1019
1020 if ($object->isCoreOrExternalModule() == 'external') {
1021 $head[$h][0] = dolBuildUrl(DOL_URL_ROOT.'/admin/modulehelp.php', ['id' => $object->id, 'mode' => 'changelog']);
1022 $head[$h][1] = $langs->trans("ChangeLog");
1023 $head[$h][2] = 'changelog';
1024 $h++;
1025 }
1026
1027 complete_head_from_modules($conf, $langs, $object, $head, $h, 'modulehelp_admin');
1028
1029 complete_head_from_modules($conf, $langs, $object, $head, $h, 'modulehelp_admin', 'remove');
1030
1031
1032 return $head;
1033}
1040{
1041 global $langs, $conf;
1042 $h = 0;
1043 $head = array();
1044
1045 $head[$h][0] = dolBuildUrl(DOL_URL_ROOT.'/admin/translation.php', ['mode' => 'searchkey']);
1046 $head[$h][1] = $langs->trans("TranslationKeySearch");
1047 $head[$h][2] = 'searchkey';
1048 $h++;
1049
1050 $head[$h][0] = dolBuildUrl(DOL_URL_ROOT.'/admin/translation.php', ['mode' => 'overwrite']);
1051 $head[$h][1] = '<span class="valignmiddle">'.$langs->trans("TranslationOverwriteKey").'</span><span class="fa fa-plus-circle valignmiddle paddingleft"></span>';
1052 $head[$h][2] = 'overwrite';
1053 $h++;
1054
1055 complete_head_from_modules($conf, $langs, null, $head, $h, 'translation_admin');
1056
1057 complete_head_from_modules($conf, $langs, null, $head, $h, 'translation_admin', 'remove');
1058
1059
1060 return $head;
1061}
1062
1063
1070{
1071 global $langs, $conf;
1072 $h = 0;
1073 $head = array();
1074
1075 $head[$h][0] = DOL_URL_ROOT."/admin/defaultvalues.php?mode=createform";
1076 $head[$h][1] = $langs->trans("DefaultCreateForm");
1077 $head[$h][2] = 'createform';
1078 $h++;
1079
1080 $head[$h][0] = DOL_URL_ROOT."/admin/defaultvalues.php?mode=filters";
1081 $head[$h][1] = $langs->trans("DefaultSearchFilters");
1082 $head[$h][2] = 'filters';
1083 $h++;
1084
1085 $head[$h][0] = DOL_URL_ROOT."/admin/defaultvalues.php?mode=sortorder";
1086 $head[$h][1] = $langs->trans("DefaultSortOrder");
1087 $head[$h][2] = 'sortorder';
1088 $h++;
1089
1090 if (!empty($conf->use_javascript_ajax)) {
1091 $head[$h][0] = DOL_URL_ROOT."/admin/defaultvalues.php?mode=focus";
1092 $head[$h][1] = $langs->trans("DefaultFocus");
1093 $head[$h][2] = 'focus';
1094 $h++;
1095
1096 $head[$h][0] = DOL_URL_ROOT."/admin/defaultvalues.php?mode=mandatory";
1097 $head[$h][1] = $langs->trans("DefaultMandatory");
1098 $head[$h][2] = 'mandatory';
1099 $h++;
1100 }
1101
1102 /*$head[$h][0] = DOL_URL_ROOT."/admin/translation.php?mode=searchkey";
1103 $head[$h][1] = $langs->trans("TranslationKeySearch");
1104 $head[$h][2] = 'searchkey';
1105 $h++;*/
1106
1107 complete_head_from_modules($conf, $langs, null, $head, $h, 'defaultvalues_admin');
1108
1109 complete_head_from_modules($conf, $langs, null, $head, $h, 'defaultvalues_admin', 'remove');
1110
1111
1112 return $head;
1113}
1114
1115
1122{
1123 global $conf, $php_session_save_handler;
1124
1125 $arrayofSessions = array();
1126 // Set the handler of session
1127 if (!empty($php_session_save_handler) && $php_session_save_handler == 'db') {
1128 require_once DOL_DOCUMENT_ROOT.'/core/lib/phpsessionin'.$php_session_save_handler.'.lib.php';
1129 return dolListSessions();
1130 }
1131 // session.save_path can be returned empty so we set a default location and work from there
1132 $sessPath = '/tmp';
1133 $iniPath = ini_get("session.save_path");
1134 if ($iniPath) {
1135 $sessPath = $iniPath;
1136 }
1137 $sessPath .= '/'; // We need the trailing slash
1138 dol_syslog('admin.lib:listOfSessions sessPath='.$sessPath);
1139
1140 $dh = @opendir(dol_osencode($sessPath));
1141 if ($dh) {
1142 while (($file = @readdir($dh)) !== false) {
1143 if (preg_match('/^sess_/i', $file) && $file != "." && $file != "..") {
1144 $fullpath = $sessPath.$file;
1145 if (!@is_dir($fullpath) && is_readable($fullpath)) {
1146 $sessValues = file_get_contents($fullpath); // get raw session data
1147 // Example of possible value
1148 //$sessValues = 'newtoken|s:32:"1239f7a0c4b899200fe9ca5ea394f307";dol_loginmesg|s:0:"";newtoken|s:32:"1236457104f7ae0f328c2928973f3cb5";dol_loginmesg|s:0:"";token|s:32:"123615ad8d650c5cc4199b9a1a76783f";
1149 // 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";
1150 // 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";';
1151
1152 if (preg_match('/dol_login/i', $sessValues) && // limit to dolibarr session
1153 (preg_match('/dol_entity\|i:'.$conf->entity.';/i', $sessValues) || preg_match('/dol_entity\|s:([0-9]+):"'.$conf->entity.'"/i', $sessValues)) && // limit to current entity
1154 preg_match('/dol_company\|s:([0-9]+):"('.getDolGlobalString('MAIN_INFO_SOCIETE_NOM').')"/i', $sessValues)) { // limit to company name
1155 $tmp = explode('_', $file);
1156 $idsess = $tmp[1];
1157 $regs = array();
1158 $arrayofSessions[$idsess]["login"] = '';
1159 $loginfound = preg_match('/dol_login\|s:[0-9]+:"([^"]+)"/i', $sessValues, $regs);
1160 if ($loginfound) {
1161 $arrayofSessions[$idsess]["login"] = (string) $regs[1];
1162 }
1163 $arrayofSessions[$idsess]["age"] = time() - filectime($fullpath);
1164 $arrayofSessions[$idsess]["creation"] = filectime($fullpath);
1165 $arrayofSessions[$idsess]["modification"] = filemtime($fullpath);
1166 $arrayofSessions[$idsess]["user_agent"] = null;
1167 $arrayofSessions[$idsess]["remote_ip"] = null;
1168 $arrayofSessions[$idsess]["raw"] = $sessValues;
1169 }
1170 }
1171 }
1172 }
1173 @closedir($dh);
1174 }
1175
1176 return $arrayofSessions;
1177}
1178
1185function purgeSessions($mysessionid)
1186{
1187 global $conf;
1188
1189 $sessPath = ini_get("session.save_path")."/";
1190 dol_syslog('admin.lib:purgeSessions mysessionid='.$mysessionid.' sessPath='.$sessPath);
1191
1192 $error = 0;
1193
1194 $dh = @opendir(dol_osencode($sessPath));
1195 if ($dh) {
1196 while (($file = @readdir($dh)) !== false) {
1197 if ($file != "." && $file != "..") {
1198 $fullpath = $sessPath.$file;
1199 if (!@is_dir($fullpath)) {
1200 $sessValues = file_get_contents($fullpath); // get raw session data
1201
1202 if (preg_match('/dol_login/i', $sessValues) && // limit to dolibarr session
1203 (preg_match('/dol_entity\|i:('.$conf->entity.')/', $sessValues) || preg_match('/dol_entity\|s:([0-9]+):"('.$conf->entity.')"/i', $sessValues)) && // limit to current entity
1204 preg_match('/dol_company\|s:([0-9]+):"(' . getDolGlobalString('MAIN_INFO_SOCIETE_NOM').')"/i', $sessValues)) { // limit to company name
1205 $tmp = explode('_', $file);
1206 $idsess = $tmp[1];
1207 // We remove session if it's not ourself
1208 if ($idsess != $mysessionid) {
1209 $res = @unlink($fullpath);
1210 if (!$res) {
1211 $error++;
1212 }
1213 }
1214 }
1215 }
1216 }
1217 }
1218 @closedir($dh);
1219 }
1220
1221 if (!$error) {
1222 return 1;
1223 } else {
1224 return -$error;
1225 }
1226}
1227
1228
1229
1239function activateModule($value, $withdeps = 1, $noconfverification = 0, $options = '')
1240{
1241 global $db, $langs, $conf, $mysoc;
1242
1243 $ret = array();
1244
1245 // Check parameters
1246 if (empty($value)) {
1247 $ret['errors'] = array('ErrorBadParameter');
1248 return $ret;
1249 }
1250
1251 $ret = array('nbmodules' => 0, 'errors' => array(), 'nbperms' => 0);
1252 $modName = $value;
1253 $modFile = $modName.".class.php";
1254
1255 // Loop on each directory to fill $modulesdir
1256 $modulesdir = dolGetModulesDirs();
1257
1258 // Loop on each modulesdir directories
1259 $found = false;
1260 foreach ($modulesdir as $dir) {
1261 if (file_exists($dir.$modFile)) {
1262 $found = @include_once $dir.$modFile;
1263 if ($found) {
1264 break;
1265 }
1266 }
1267 }
1268
1269 $objMod = new $modName($db);
1270 '@phan-var-force DolibarrModules $objMod';
1273 // Test if PHP version ok
1274 $verphp = versionphparray();
1275 $vermin = isset($objMod->phpmin) ? $objMod->phpmin : 0;
1276 if (is_array($vermin) && versioncompare($verphp, $vermin) < 0) {
1277 $ret['errors'][] = $langs->trans("ErrorModuleRequirePHPVersion", versiontostring($vermin));
1278 return $ret;
1279 }
1280
1281 // Test if Dolibarr version ok
1282 $verdol = versiondolibarrarray();
1283 $vermin = isset($objMod->need_dolibarr_version) ? $objMod->need_dolibarr_version : 0;
1284 //print 'version: '.versioncompare($verdol,$vermin).' - '.join(',',$verdol).' - '.join(',',$vermin);exit;
1285 if (is_array($vermin) && versioncompare($verdol, $vermin) < 0) {
1286 $ret['errors'][] = $langs->trans("ErrorModuleRequireDolibarrVersion", versiontostring($vermin));
1287 return $ret;
1288 }
1289
1290 // Test if javascript requirement ok
1291 if (!empty($objMod->need_javascript_ajax) && empty($conf->use_javascript_ajax)) {
1292 $ret['errors'][] = $langs->trans("ErrorModuleRequireJavascript");
1293 return $ret;
1294 }
1295 $const_name = $objMod->const_name;
1296 if ($noconfverification == 0) {
1297 if (getDolGlobalString($const_name)) {
1298 return $ret;
1299 }
1300 }
1301
1302 $result = $objMod->init($options); // Enable module
1303
1304 if ($result <= 0) {
1305 $ret['errors'][] = $objMod->error;
1306 } else {
1307 if ($withdeps) {
1308 if (isset($objMod->depends) && is_array($objMod->depends) && !empty($objMod->depends)) {
1309 // Activation of modules this module depends on
1310 // this->depends may be array('modModule1', 'mmodModule2') or array('always'=>array('modModule1'), 'FR'=>array('modModule2"))
1311 foreach ($objMod->depends as $key => $modulestringorarray) {
1312 //var_dump((! is_numeric($key)) && ! preg_match('/^always/', $key) && $mysoc->country_code && ! preg_match('/^'.$mysoc->country_code.'/', $key));exit;
1313 if ((!is_numeric($key)) && !preg_match('/^always/', $key) && $mysoc->country_code && !preg_match('/^'.$mysoc->country_code.'/', $key)) {
1314 dol_syslog("We are not concerned by dependency with key=".$key." because our country is ".$mysoc->country_code);
1315 continue;
1316 }
1317
1318 if (!is_array($modulestringorarray)) {
1319 $modulestringorarray = array($modulestringorarray);
1320 }
1321
1322 foreach ($modulestringorarray as $modulestring) {
1323 $activate = false;
1324 $activateerr = '';
1325 $resarray = array();
1326 foreach ($modulesdir as $dir) {
1327 if (file_exists($dir.$modulestring.".class.php")) {
1328 $resarray = activateModule($modulestring, 1, 0, $options);
1329 if (empty($resarray['errors'])) {
1330 $activate = true;
1331 } else {
1332 $activateerr = implode(', ', $resarray['errors']);
1333 foreach ($resarray['errors'] as $errorMessage) {
1334 dol_syslog($errorMessage, LOG_ERR);
1335 }
1336 }
1337 break;
1338 }
1339 }
1340
1341 if ($activate) {
1342 $ret['nbmodules'] += $resarray['nbmodules'];
1343 $ret['nbperms'] += $resarray['nbperms'];
1344 } else {
1345 if ($activateerr) {
1346 $ret['errors'][] = $activateerr;
1347 }
1348 $ret['errors'][] = $langs->trans('activateModuleDependNotSatisfied', $objMod->name, $modulestring, $objMod->name).'<br>'.$langs->trans('activateModuleDependNotSatisfied2', $modulestring, $objMod->name);
1349 }
1350 }
1351 }
1352 }
1353
1354 if (isset($objMod->conflictwith) && is_array($objMod->conflictwith) && !empty($objMod->conflictwith)) {
1355 // Deactivation of modules that are in conflict
1356 $num = count($objMod->conflictwith);
1357 for ($i = 0; $i < $num; $i++) {
1358 foreach ($modulesdir as $dir) {
1359 if (file_exists($dir.$objMod->conflictwith[$i].".class.php")) {
1360 unActivateModule($objMod->conflictwith[$i], 0);
1361 }
1362 }
1363 }
1364 }
1365 }
1366 }
1367
1368 if (!count($ret['errors'])) {
1369 $ret['nbmodules']++;
1370 $ret['nbperms'] += (is_array($objMod->rights) ? count($objMod->rights) : 0);
1371 }
1372
1373 return $ret;
1374}
1375
1376
1385function unActivateModule($value, $requiredby = 1, $options = '')
1386{
1387 global $db;
1388
1389 dol_syslog("unActivateModule value=".$value, LOG_INFO);
1390
1391 // Check parameters
1392 if (empty($value)) {
1393 return 'ErrorBadParameter';
1394 }
1395
1396 $ret = '';
1397 $modName = $value;
1398 $modFile = $modName.".class.php";
1399
1400 // Loop on each directory to fill $modulesdir
1401 $modulesdir = dolGetModulesDirs();
1402
1403 // Loop on each modulesdir directories
1404 $found = false;
1405 foreach ($modulesdir as $dir) {
1406 if (file_exists($dir.$modFile)) {
1407 $found = @include_once $dir.$modFile;
1408 if ($found) {
1409 break;
1410 }
1411 }
1412 }
1413
1414 if ($found) {
1415 $objMod = new $modName($db);
1416 '@phan-var-force DolibarrModules $objMod';
1419 $result = $objMod->remove($options);
1420 if ($result <= 0) {
1421 $ret = $objMod->error;
1422 }
1423 } else { // We come here when we try to unactivate a module when module does not exists anymore in sources
1424 //print $dir.$modFile;exit;
1425 // TODO Replace this after DolibarrModules is moved as abstract class with a try catch, to show if the module we try to disable has not been found or could not be loaded
1426 include_once DOL_DOCUMENT_ROOT.'/core/modules/DolibarrModules.class.php';
1427 $genericMod = new DolibarrModules($db);
1428 $genericMod->name = preg_replace('/^mod/i', '', $modName);
1429 $genericMod->rights_class = strtolower(preg_replace('/^mod/i', '', $modName));
1430 $genericMod->const_name = 'MAIN_MODULE_'.strtoupper(preg_replace('/^mod/i', '', $modName));
1431 dol_syslog("modules::unActivateModule Failed to find module file, we use generic function with name ".$modName);
1432 $genericMod->remove('');
1433 }
1434
1435 // Disable modules that depends on module we disable
1436 if (!$ret && $requiredby && isset($objMod) && is_object($objMod) && is_array($objMod->requiredby)) {
1437 $countrb = count($objMod->requiredby);
1438 for ($i = 0; $i < $countrb; $i++) {
1439 //var_dump($objMod->requiredby[$i]);
1440 unActivateModule($objMod->requiredby[$i], $requiredby, $options);
1441 }
1442 }
1443
1444 return $ret;
1445}
1446
1447
1466function complete_dictionary_with_modules(&$taborder, &$tabname, &$tablib, &$tabsql, &$tabsqlsort, &$tabfield, &$tabfieldvalue, &$tabfieldinsert, &$tabrowid, &$tabcond, &$tabhelp, &$tabcomplete)
1467{
1468 global $db, $langs;
1469
1470 dol_syslog("complete_dictionary_with_modules Search external modules to complete the list of dictionary tables", LOG_DEBUG, 1);
1471
1472 // Search modules
1473 $modulesdir = dolGetModulesDirs();
1474 $i = 0; // is a sequencer of modules found
1475 $j = 0; // j is module number. Automatically affected if module number not defined.
1476
1477 foreach ($modulesdir as $dir) {
1478 // Load modules attributes in arrays (name, numero, orders) from dir directory
1479 //print $dir."\n<br>";
1480 dol_syslog("Scan directory ".$dir." for modules");
1481 $handle = @opendir(dol_osencode($dir));
1482 if (is_resource($handle)) {
1483 while (($file = readdir($handle)) !== false) {
1484 //print "$i ".$file."\n<br>";
1485 if (is_readable($dir.$file) && dol_substr($file, 0, 3) == 'mod' && dol_substr($file, dol_strlen($file) - 10) == '.class.php') {
1486 $modName = dol_substr($file, 0, dol_strlen($file) - 10);
1487
1488 if ($modName) {
1489 if ($modName === 'modFournisseur' && getDolGlobalString('MAIN_USE_NEW_SUPPLIERMOD')) {
1490 dol_syslog("Module modFournisseur skipped because MAIN_USE_NEW_SUPPLIERMOD is enabled", LOG_DEBUG);
1491 continue;
1492 }
1493 if (in_array($modName, ['modSupplierInvoice', 'modSupplierOrder']) && !getDolGlobalString('MAIN_USE_NEW_SUPPLIERMOD')) {
1494 dol_syslog("Module ".$modName." skipped because MAIN_USE_NEW_SUPPLIERMOD is disabled", LOG_DEBUG);
1495 continue;
1496 }
1497
1498 include_once $dir.$file;
1499 $objMod = new $modName($db);
1500 '@phan-var-force DolibarrModules $objMod';
1503 if ($objMod->numero > 0) {
1504 $j = $objMod->numero;
1505 } else {
1506 $j = 1000 + $i;
1507 }
1508
1509 $modulequalified = 1;
1510
1511 // We discard modules according to features level (PS: if module is activated we always show it)
1512 $const_name = 'MAIN_MODULE_'.strtoupper(preg_replace('/^mod/i', '', get_class($objMod)));
1513 if ($objMod->version == 'development' && getDolGlobalInt('MAIN_FEATURES_LEVEL') < 2 && !getDolGlobalString($const_name)) {
1514 $modulequalified = 0;
1515 }
1516 if ($objMod->version == 'experimental' && getDolGlobalInt('MAIN_FEATURES_LEVEL') < 1 && !getDolGlobalString($const_name)) {
1517 $modulequalified = 0;
1518 }
1519 // If module is not activated disqualified
1520 if (!getDolGlobalString($const_name)) {
1521 $modulequalified = 0;
1522 }
1523
1524 if ($modulequalified) {
1525 // Load languages files of module
1526 if (isset($objMod->langfiles) && is_array($objMod->langfiles)) {
1527 foreach ($objMod->langfiles as $langfile) {
1528 $langs->load($langfile);
1529 }
1530 }
1531
1532 // phpcs:disable
1533 // Complete the arrays &$tabname,&$tablib,&$tabsql,&$tabsqlsort,&$tabfield,&$tabfieldvalue,&$tabfieldinsert,&$tabrowid,&$tabcond
1534 // @phan-suppress-next-line PhanUndeclaredProperty
1535 if (empty($objMod->dictionaries) && !empty($objMod->{"dictionnaries"})) {
1536 // @phan-suppress-next-line PhanUndeclaredProperty
1537 $objMod->dictionaries = $objMod->{"dictionnaries"}; // For backward compatibility
1538 }
1539 // phpcs:enable
1540
1541 if (!empty($objMod->dictionaries)) {
1542 //var_dump($objMod->dictionaries['tabname']);
1543 $nbtabname = $nbtablib = $nbtabsqlsort = $nbtabfield = $nbtabfieldvalue = $nbtabfieldinsert = $nbtabrowid = $nbtabcond = $nbtabfieldcheck = $nbtabhelp = $nbtabsql = 0;
1544 $tabnamerelwithkey = array();
1545 foreach ($objMod->dictionaries['tabname'] as $key => $val) {
1546 $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $val);
1547 $nbtabname++;
1548 $taborder[] = max($taborder) + 1;
1549 $tabname[] = $val;
1550 $tabnamerelwithkey[$key] = $val;
1551 $tabcomplete[$tmptablename]['picto'] = $objMod->picto;
1552 } // Position
1553 foreach ($objMod->dictionaries['tablib'] as $key => $val) {
1554 $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]);
1555 $nbtablib++;
1556 $tablib[] = $val;
1557 $tabcomplete[$tmptablename]['lib'] = $val;
1558 }
1559 foreach ($objMod->dictionaries['tabsql'] as $key => $val) {
1560 $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]);
1561 $nbtabsql++;
1562 $tabsql[] = $val; // @phan-suppress-current-line SqlInjection
1563 $tabcomplete[$tmptablename]['sql'] = $val; // @phan-suppress-current-line SqlInjection
1564 }
1565 foreach ($objMod->dictionaries['tabsqlsort'] as $key => $val) {
1566 $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]);
1567 $nbtabsqlsort++;
1568 $tabsqlsort[] = $val; // @phan-suppress-current-line SqlInjection
1569 $tabcomplete[$tmptablename]['sqlsort'] = $val; // @phan-suppress-current-line SqlInjection
1570 }
1571 foreach ($objMod->dictionaries['tabfield'] as $key => $val) {
1572 $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]);
1573 $nbtabfield++;
1574 $tabfield[] = $val;
1575 $tabcomplete[$tmptablename]['field'] = $val;
1576 }
1577 foreach ($objMod->dictionaries['tabfieldvalue'] as $key => $val) {
1578 $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]);
1579 $nbtabfieldvalue++;
1580 $tabfieldvalue[] = $val;
1581 $tabcomplete[$tmptablename]['value'] = $val;
1582 }
1583 foreach ($objMod->dictionaries['tabfieldinsert'] as $key => $val) {
1584 $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]);
1585 $nbtabfieldinsert++;
1586 $tabfieldinsert[] = $val; // @phan-suppress-current-line SqlInjection
1587 $tabcomplete[$tmptablename]['fieldinsert'] = $val; // @phan-suppress-current-line SqlInjection
1588 }
1589 foreach ($objMod->dictionaries['tabrowid'] as $key => $val) {
1590 $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]);
1591 $nbtabrowid++;
1592 $tabrowid[] = (int) $val;
1593 $tabcomplete[$tmptablename]['rowid'] = (int) $val;
1594 }
1595 foreach ($objMod->dictionaries['tabcond'] as $key => $val) {
1596 $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]);
1597 $nbtabcond++;
1598 $tabcond[] = $val;
1599 $tabcomplete[$tmptablename]['cond'] = $val;
1600 }
1601 if (!empty($objMod->dictionaries['tabhelp'])) {
1602 foreach ($objMod->dictionaries['tabhelp'] as $key => $val) {
1603 $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]);
1604 $nbtabhelp++;
1605 $tabhelp[] = $val;
1606 $tabcomplete[$tmptablename]['help'] = $val;
1607 }
1608 }
1609 if (!empty($objMod->dictionaries['tabfieldcheck'])) {
1610 foreach ($objMod->dictionaries['tabfieldcheck'] as $key => $val) {
1611 $tmptablename = preg_replace('/'.MAIN_DB_PREFIX.'/', '', $tabnamerelwithkey[$key]);
1612 $nbtabfieldcheck++;
1613 $tabcomplete[$tmptablename]['fieldcheck'] = $val;
1614 }
1615 }
1616
1617 if ($nbtabname != $nbtablib || $nbtablib != $nbtabsql || $nbtabsql != $nbtabsqlsort) {
1618 print 'Error in descriptor of module '.$const_name.'. Array ->dictionaries has not same number of record for key "tabname", "tablib", "tabsql" and "tabsqlsort"';
1619 //print "$const_name: $nbtabname=$nbtablib=$nbtabsql=$nbtabsqlsort=$nbtabfield=$nbtabfieldvalue=$nbtabfieldinsert=$nbtabrowid=$nbtabcond=$nbtabfieldcheck=$nbtabhelp\n";
1620 } else {
1621 $taborder[] = 0; // Add an empty line
1622 }
1623 }
1624
1625 $j++;
1626 $i++;
1627 } else {
1628 dol_syslog("Module ".get_class($objMod)." not qualified");
1629 }
1630 }
1631 }
1632 }
1633 closedir($handle);
1634 } else {
1635 dol_syslog("htdocs/admin/modules.php: Failed to open directory ".$dir.". See permission and open_basedir option.", LOG_WARNING);
1636 }
1637 }
1638
1639 dol_syslog("", LOG_DEBUG, -1);
1640
1641 return 1;
1642}
1643
1650function activateModulesRequiredByCountry($country_code)
1651{
1652 global $db;
1653
1654 $modulesdir = dolGetModulesDirs();
1655
1656 foreach ($modulesdir as $dir) {
1657 // Load modules attributes in arrays (name, numero, orders) from dir directory
1658 dol_syslog("Scan directory ".$dir." for modules");
1659 $handle = @opendir(dol_osencode($dir));
1660 if (is_resource($handle)) {
1661 while (($file = readdir($handle)) !== false) {
1662 if (is_readable($dir.$file) && dol_substr($file, 0, 3) == 'mod' && dol_substr($file, dol_strlen($file) - 10) == '.class.php') {
1663 $modName = dol_substr($file, 0, dol_strlen($file) - 10);
1664
1665 if ($modName) {
1666 if ($modName === 'modFournisseur' && getDolGlobalString('MAIN_USE_NEW_SUPPLIERMOD')) {
1667 dol_syslog("Module modFournisseur skipped because MAIN_USE_NEW_SUPPLIERMOD is enabled", LOG_DEBUG);
1668 continue;
1669 }
1670 if (in_array($modName, ['modSupplierInvoice', 'modSupplierOrder']) && !getDolGlobalString('MAIN_USE_NEW_SUPPLIERMOD')) {
1671 dol_syslog("Module ".$modName." skipped because MAIN_USE_NEW_SUPPLIERMOD is disabled", LOG_DEBUG);
1672 continue;
1673 }
1674
1675 include_once $dir.$file;
1676 $objMod = new $modName($db);
1677 '@phan-var-force DolibarrModules $objMod';
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
1685 if ($objMod->version == 'development' && getDolGlobalInt('MAIN_FEATURES_LEVEL') < 2) {
1686 $modulequalified = 0;
1687 }
1688 if ($objMod->version == 'experimental' && getDolGlobalInt('MAIN_FEATURES_LEVEL') < 1) {
1689 $modulequalified = 0;
1690 }
1691 if (getDolGlobalString($const_name)) {
1692 $modulequalified = 0; // already activated
1693 }
1694
1695 if ($modulequalified) {
1696 // Load languages files of module
1697 if (isset($objMod->automatic_activation[$country_code])) {
1698 activateModule($modName, 1, 0);
1699
1700 setEventMessages($objMod->automatic_activation[$country_code], null, 'warnings');
1701 }
1702 } else {
1703 dol_syslog("Module ".get_class($objMod)." not qualified");
1704 }
1705 }
1706 }
1707 }
1708 closedir($handle);
1709 } else {
1710 dol_syslog("htdocs/admin/modules.php: Failed to open directory ".$dir.". See permission and open_basedir option.", LOG_WARNING);
1711 }
1712 }
1713
1714 return 1;
1715}
1716
1723function complete_elementList_with_modules(&$elementList)
1724{
1725 global $db, $modules, $conf, $langs;
1726
1727 // Search modules
1728 $filename = array();
1729 $modules = array();
1730 $orders = array();
1731 $categ = array();
1732 $dirmod = array();
1733
1734 $i = 0; // is a sequencer of modules found
1735 $j = 0; // j is module number. Automatically affected if module number not defined.
1736
1737 dol_syslog("complete_elementList_with_modules Search external modules to complete the list of contact element", LOG_DEBUG, 1);
1738
1739 $modulesdir = dolGetModulesDirs();
1740
1741 foreach ($modulesdir as $dir) {
1742 // Load modules attributes in arrays (name, numero, orders) from dir directory
1743 //print $dir."\n<br>";
1744 dol_syslog("Scan directory ".$dir." for modules");
1745 $handle = @opendir(dol_osencode($dir));
1746 if (is_resource($handle)) {
1747 while (($file = readdir($handle)) !== false) {
1748 //print "$i ".$file."\n<br>";
1749 if (is_readable($dir.$file) && dol_substr($file, 0, 3) == 'mod' && dol_substr($file, dol_strlen($file) - 10) == '.class.php') {
1750 $modName = dol_substr($file, 0, dol_strlen($file) - 10);
1751
1752 if ($modName) {
1753 include_once $dir.$file;
1754 $objMod = new $modName($db);
1757 if ($objMod->numero > 0) {
1758 $j = $objMod->numero;
1759 } else {
1760 $j = 1000 + $i;
1761 }
1762
1763 $modulequalified = 1;
1764
1765 // We discard modules according to features level (PS: if module is activated we always show it)
1766 $const_name = 'MAIN_MODULE_'.strtoupper(preg_replace('/^mod/i', '', get_class($objMod)));
1767 if ($objMod->version == 'development' && getDolGlobalInt('MAIN_FEATURES_LEVEL') < 2 && getDolGlobalString($const_name)) {
1768 $modulequalified = 0;
1769 }
1770 if ($objMod->version == 'experimental' && getDolGlobalInt('MAIN_FEATURES_LEVEL') < 1 && getDolGlobalString($const_name)) {
1771 $modulequalified = 0;
1772 }
1773 // If module is not activated disqualified
1774 if (!getDolGlobalString($const_name)) {
1775 $modulequalified = 0;
1776 }
1777
1778 if ($modulequalified) {
1779 // Load languages files of module
1780 if (isset($objMod->langfiles) && is_array($objMod->langfiles)) {
1781 foreach ($objMod->langfiles as $langfile) {
1782 $langs->load($langfile);
1783 }
1784 }
1785
1786 $modules[$i] = $objMod;
1787 $filename[$i] = $modName;
1788 $orders[$i] = $objMod->family."_".$j; // Sort on family then module number
1789 $dirmod[$i] = $dir;
1790 //print "x".$modName." ".$orders[$i]."\n<br>";
1791
1792 if (!empty($objMod->module_parts['contactelement'])) {
1793 if (is_array($objMod->module_parts['contactelement'])) {
1794 foreach ($objMod->module_parts['contactelement'] as $elem => $title) {
1795 $elementList[$elem] = $langs->trans($title);
1796 }
1797 } else {
1798 $elementList[$objMod->name] = $langs->trans($objMod->name);
1799 }
1800 }
1801
1802 $j++;
1803 $i++;
1804 } else {
1805 dol_syslog("Module ".get_class($objMod)." not qualified");
1806 }
1807 }
1808 }
1809 }
1810 closedir($handle);
1811 } else {
1812 dol_syslog("htdocs/admin/modules.php: Failed to open directory ".$dir.". See permission and open_basedir option.", LOG_WARNING);
1813 }
1814 }
1815
1816 dol_syslog("", LOG_DEBUG, -1);
1817
1818 return 1;
1819}
1820
1831function form_constantes($tableau, $strictw3c = 2, $helptext = '', $text = '')
1832{
1833 global $db, $langs, $conf, $user;
1834 global $_Avery_Labels;
1835
1836 $form = new Form($db);
1837
1838 print '<div class="div-table-responsive-no-min">';
1839 print '<table class="noborder centpercent">';
1840 print '<tr class="liste_titre">';
1841 print '<td class="">'.$langs->trans("Description").'</td>';
1842 print '<td>';
1843 if ($text) {
1844 $text = $langs->trans($text);
1845 print $form->textwithpicto($text, $helptext, 1, 'help', '', 0, 2, 'idhelptext');
1846 }
1847 print '</td>';
1848 print "</tr>\n";
1849
1850 foreach ($tableau as $key => $const) { // Loop on each param
1851 $label = '';
1852 // $const is a const key like 'MYMODULE_ABC'
1853 if (is_array($const)) {
1854 $type = $const['type'];
1855 $label = $const['label'];
1856 $const = $key;
1857 } else {
1858 $type = $const;
1859 $const = $key;
1860 }
1861
1862 $sql = "SELECT ";
1863 $sql .= "rowid";
1864 $sql .= ", ".$db->decrypt('name')." as name";
1865 $sql .= ", ".$db->decrypt('value')." as value";
1866 $sql .= ", type";
1867 $sql .= ", note";
1868 $sql .= " FROM ".MAIN_DB_PREFIX."const";
1869 $sql .= " WHERE ".$db->decrypt('name')." = '".$db->escape($const)."'";
1870 $sql .= " AND entity IN (0, ".((int) $conf->entity).")";
1871 $sql .= " ORDER BY name ASC, entity DESC";
1872 $result = $db->query($sql);
1873
1874 dol_syslog("List params", LOG_DEBUG);
1875
1876 if ($result) {
1877 $obj = $db->fetch_object($result); // Take first result of select
1878
1879 if (empty($obj)) { // If not yet into table
1880 $obj = (object) array('rowid' => '', 'name' => $const, 'value' => '', 'type' => $type, 'note' => '');
1881 }
1882
1883 print '<tr class="oddeven">';
1884
1885 // Show label of parameter
1886 print '<td>';
1887 print '<input type="hidden" name="rowid[]" value="'.$obj->rowid.'">';
1888 print '<input type="hidden" name="constname[]" value="'.$const.'">';
1889 print '<input type="hidden" name="constnote_'.$obj->name.'" value="'.nl2br(dol_escape_htmltag($obj->note)).'">';
1890 print '<input type="hidden" name="consttype_'.$obj->name.'" value="'.($obj->type ? $obj->type : 'string').'">';
1891
1892 $picto = 'generic';
1893 $tmparray = explode(':', $obj->type);
1894 if (!empty($tmparray[1])) {
1895 $picto = preg_replace('/_send$/', '', $tmparray[1]);
1896 }
1897 print img_picto('', $picto, 'class="pictofixedwidth"');
1898
1899 if (!empty($tableau[$key]['tooltip'])) {
1900 print $form->textwithpicto($label ? $label : $langs->trans('Desc'.$const), $tableau[$key]['tooltip']);
1901 } else {
1902 print($label ? $label : $langs->trans('Desc'.$const));
1903 }
1904
1905 if ($const == 'ADHERENT_MAILMAN_URL') {
1906 print '. '.$langs->trans("Example").': <a href="#" id="exampleclick1">'.img_down().'</a><br>';
1907 //print 'http://lists.example.com/cgi-bin/mailman/admin/%LISTE%/members?adminpw=%MAILMAN_ADMINPW%&subscribees=%EMAIL%&send_welcome_msg_to_this_batch=1';
1908 print '<div id="example1" class="hidden">';
1909 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';
1910 print '</div>';
1911 } elseif ($const == 'ADHERENT_MAILMAN_UNSUB_URL') {
1912 print '. '.$langs->trans("Example").': <a href="#" id="exampleclick2">'.img_down().'</a><br>';
1913 print '<div id="example2" class="hidden">';
1914 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';
1915 print '</div>';
1916 //print 'http://lists.example.com/cgi-bin/mailman/admin/%LISTE%/members/remove?adminpw=%MAILMAN_ADMINPW%&unsubscribees=%EMAIL%';
1917 } elseif ($const == 'ADHERENT_MAILMAN_LISTS') {
1918 print '. '.$langs->trans("Example").': <a href="#" id="exampleclick3">'.img_down().'</a><br>';
1919 print '<div id="example3" class="hidden">';
1920 print 'mymailmanlist<br>';
1921 print 'mymailmanlist1,mymailmanlist2<br>';
1922 print 'TYPE:Type1:mymailmanlist1,TYPE:Type2:mymailmanlist2<br>';
1923 if (isModEnabled('category')) {
1924 print 'CATEG:Categ1:mymailmanlist1,CATEG:Categ2:mymailmanlist2<br>';
1925 }
1926 print '</div>';
1927 //print 'http://lists.example.com/cgi-bin/mailman/admin/%LISTE%/members/remove?adminpw=%MAILMAN_ADMINPW%&unsubscribees=%EMAIL%';
1928 } elseif (in_array($const, ['ADHERENT_MAIL_FROM', 'ADHERENT_CC_MAIL_FROM'])) {
1929 print ' '.img_help(1, $langs->trans("EMailHelpMsgSPFDKIM"));
1930 }
1931
1932 print "</td>\n";
1933
1934 // Value
1935 if ($const == 'ADHERENT_CARD_TYPE' || $const == 'ADHERENT_ETIQUETTE_TYPE') {
1936 print '<td>';
1937 // List of possible labels (defined into $_Avery_Labels variable set into format_cards.lib.php)
1938 require_once DOL_DOCUMENT_ROOT.'/core/lib/format_cards.lib.php';
1939 $arrayoflabels = array();
1940 foreach (array_keys($_Avery_Labels) as $codecards) {
1941 $arrayoflabels[$codecards] = $_Avery_Labels[$codecards]['name'];
1942 }
1943 print $form->selectarray('constvalue'.($strictw3c == 3 ? '_'.$const : '[]'), $arrayoflabels, ($obj->value ? $obj->value : 'CARD'), 1, 0, 0);
1944 print '<input type="hidden" name="consttype" value="yesno">';
1945 print '<input type="hidden" name="constnote[]" value="'.nl2br(dol_escape_htmltag($obj->note)).'">';
1946 print '</td>';
1947 } else {
1948 print '<td>';
1949 print '<input type="hidden" name="consttype'.($strictw3c == 3 ? '_'.$const : '[]').'" value="'.($obj->type ? $obj->type : 'string').'">';
1950 print '<input type="hidden" name="constnote'.($strictw3c == 3 ? '_'.$const : '[]').'" value="'.nl2br(dol_escape_htmltag($obj->note)).'">';
1951 if ($obj->type == 'textarea' || in_array($const, array('ADHERENT_CARD_TEXT', 'ADHERENT_CARD_TEXT_RIGHT', 'ADHERENT_ETIQUETTE_TEXT'))) {
1952 print '<textarea class="flat" name="constvalue'.($strictw3c == 3 ? '_'.$const : '[]').'" cols="50" rows="5" wrap="soft">'."\n";
1953 print $obj->value;
1954 print "</textarea>\n";
1955 } elseif ($obj->type == 'html') {
1956 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
1957 $doleditor = new DolEditor('constvalue'.($strictw3c == 3 ? '_'.$const : '[]'), $obj->value, '', 160, 'dolibarr_notes', '', false, false, isModEnabled('fckeditor'), ROWS_5, '90%');
1958 $doleditor->Create();
1959 } elseif ($obj->type == 'yesno') {
1960 print $form->selectyesno('constvalue'.($strictw3c == 3 ? '_'.$const : '[]'), $obj->value, 1, false, 0, 1);
1961 } elseif (preg_match('/emailtemplate/', $obj->type)) {
1962 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
1963 $formmail = new FormMail($db);
1964
1965 $tmp = explode(':', $obj->type);
1966
1967 $formmail->fetchAllEMailTemplate($tmp[1], $user, null, -1); // We set lang=null to get in priority record with no lang
1968
1969 $arrayofmessagename = array();
1970 if (is_array($formmail->lines_model)) {
1971 foreach ($formmail->lines_model as $modelmail) {
1972 $moreonlabel = '';
1973 if (!empty($arrayofmessagename[$modelmail->label])) {
1974 $moreonlabel = ' <span class="opacitymedium">('.$langs->trans("SeveralLangugeVariatFound").')</span>';
1975 }
1976 // The 'label' is the key that is unique if we exclude the language
1977 $arrayofmessagename[$modelmail->label.':'.$tmp[1]] = $langs->trans(preg_replace('/\‍(|\‍)/', '', $modelmail->label)).$moreonlabel;
1978 }
1979 }
1980
1981 print $form->selectarray('constvalue'.(empty($strictw3c) ? '' : ($strictw3c == 3 ? '_'.$const : '[]')), $arrayofmessagename, $obj->value.':'.$tmp[1], 'None', 0, 0, '', 0, 0, 0, '', '', 1);
1982
1983 print '<a href="'.dolBuildUrl(DOL_URL_ROOT.'/admin/mails_templates.php', ['action' => 'create', 'type_template' => $tmp[1], 'backtopage' => dolBuildUrl($_SERVER["PHP_SELF"])]).'">'.img_picto('', 'add').'</a>';
1984 } elseif (preg_match('/MAIL_FROM$/i', $const)) {
1985 print img_picto('', 'email', 'class="pictofixedwidth"').'<input type="text" class="flat minwidth300" name="constvalue'.($strictw3c == 3 ? '_'.$const : '[]').'" value="'.dol_escape_htmltag($obj->value).'">';
1986 } else { // type = 'string' ou 'chaine'
1987 print '<input type="text" class="flat minwidth300" name="constvalue'.($strictw3c == 3 ? '_'.$const : '[]').'" value="'.dol_escape_htmltag($obj->value).'">';
1988 }
1989 print '</td>';
1990 }
1991
1992 print "</tr>\n";
1993 }
1994 }
1995 print '</table>';
1996 print '</div>';
1997}
1998
1999
2007{
2008 global $langs;
2009
2010 $text = $langs->transnoentitiesnoconv("OnlyFollowingModulesAreOpenedToExternalUsers");
2011 $listofmodules = explode(',', getDolGlobalString('MAIN_MODULES_FOR_EXTERNAL')); // List of modules qualified for external user management
2012
2013 $i = 0;
2014 if (!empty($modules)) {
2015 $tmpmodules = dol_sort_array($modules, 'module_position');
2016 foreach ($tmpmodules as $module) { // Loop on array of modules
2017 $moduleconst = $module->const_name;
2018 $modulename = strtolower($module->name);
2019 //print 'modulename='.$modulename;
2020
2021 //if (empty($conf->global->$moduleconst)) continue;
2022 if (!in_array($modulename, $listofmodules)) {
2023 continue;
2024 }
2025 //var_dump($modulename.' - '.$langs->trans('Module'.$module->numero.'Name'));
2026
2027 if ($i > 0) {
2028 $text .= ', ';
2029 } else {
2030 $text .= ' ';
2031 }
2032 $i++;
2033
2034 $tmptext = $langs->transnoentitiesnoconv('Module'.$module->numero.'Name');
2035 if ($tmptext != 'Module'.$module->numero.'Name') {
2036 $text .= $langs->transnoentitiesnoconv('Module'.$module->numero.'Name');
2037 } else {
2038 $text .= $langs->transnoentitiesnoconv($module->name);
2039 }
2040 }
2041 }
2042
2043 return $text;
2044}
2045
2046
2056function addDocumentModel($name, $type, $label = '', $description = '')
2057{
2058 global $db, $conf;
2059
2060 $db->begin();
2061
2062 $sql = "INSERT INTO ".MAIN_DB_PREFIX."document_model (nom, type, entity, libelle, description)";
2063 $sql .= " VALUES ('".$db->escape($name)."','".$db->escape($type)."',".((int) $conf->entity).", ";
2064 $sql .= ($label ? "'".$db->escape($label)."'" : 'null').", ";
2065 $sql .= (!empty($description) ? "'".$db->escape($description)."'" : "null");
2066 $sql .= ")";
2067
2068 dol_syslog("admin.lib::addDocumentModel", LOG_DEBUG);
2069 $resql = $db->query($sql);
2070 if ($resql) {
2071 $db->commit();
2072 return 1;
2073 } else {
2074 dol_print_error($db);
2075 $db->rollback();
2076 return -1;
2077 }
2078}
2079
2087function delDocumentModel($name, $type)
2088{
2089 global $db, $conf;
2090
2091 $db->begin();
2092
2093 $sql = "DELETE FROM ".MAIN_DB_PREFIX."document_model";
2094 $sql .= " WHERE nom = '".$db->escape($name)."'";
2095 $sql .= " AND type = '".$db->escape($type)."'";
2096 $sql .= " AND entity = ".((int) $conf->entity);
2097
2098 dol_syslog("admin.lib::delDocumentModel", LOG_DEBUG);
2099 $resql = $db->query($sql);
2100 if ($resql) {
2101 $db->commit();
2102 return 1;
2103 } else {
2104 dol_print_error($db);
2105 $db->rollback();
2106 return -1;
2107 }
2108}
2109
2110
2128function printDocumentModelList($type, $moduledir, $constpdf, $title, array $features, $excludedisabled = false, $constpdfdefault = '', $usedefault = 1, $actionunset = '')
2129{
2130 global $db, $langs, $conf;
2131
2132 $form = new Form($db);
2133 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
2134
2135 print load_fiche_titre($title, '', '');
2136
2137 $def = array();
2138 $sql = "SELECT nom";
2139 $sql .= " FROM ".MAIN_DB_PREFIX."document_model";
2140 $sql .= " WHERE type = '".$db->escape($type)."'";
2141 $sql .= " AND entity = ".((int) $conf->entity);
2142 $resql = $db->query($sql);
2143 if ($resql) {
2144 $i = 0;
2145 $num_rows = $db->num_rows($resql);
2146 while ($i < $num_rows) {
2147 $array = $db->fetch_array($resql);
2148 if (is_array($array)) {
2149 array_push($def, $array[0]);
2150 }
2151 $i++;
2152 }
2153 } else {
2154 dol_print_error($db);
2155 }
2156
2157 print '<div class="div-table-responsive-no-min">';
2158 print '<table class="noborder centpercent">';
2159 print '<tr class="liste_titre">';
2160 print '<td>'.$langs->trans("Name").'</td>';
2161 print '<td>'.$langs->trans("Description").'</td>';
2162 print '<td class="center" width="60">'.$langs->trans("Status").'</td>';
2163 if ($usedefault) {
2164 print '<td class="center" width="60">'.$langs->trans("Default").'</td>';
2165 }
2166 print '<td class="center" width="60">'.$langs->trans("ShortInfo").'</td>';
2167 print '<td class="center" width="60">'.$langs->trans("Preview").'</td>';
2168 print "</tr>\n";
2169
2170 clearstatcache();
2171
2172 foreach ($dirmodels as $reldir) {
2173 foreach (array('', '/doc') as $valdir) {
2174 $realpath = $reldir."core/modules/".$moduledir.$valdir;
2175 $dir = dol_buildpath($realpath);
2176
2177 if (is_dir($dir)) {
2178 $handle = opendir($dir);
2179 if (is_resource($handle)) {
2180 $filelist = array();
2181 while (($file = readdir($handle)) !== false) {
2182 $filelist[] = $file;
2183 }
2184 closedir($handle);
2185 arsort($filelist);
2186
2187 foreach ($filelist as $file) {
2188 if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) {
2189 if (file_exists($dir.'/'.$file)) {
2190 $name = dol_substr($file, 4, dol_strlen($file) - 16);
2191 $classname = dol_substr($file, 0, dol_strlen($file) - 12);
2192
2193 require_once $dir.'/'.$file;
2194 $module = new $classname($db);
2195
2196 '@phan-var-force CommonDocGenerator $module';
2199 $modulequalified = 1;
2200 if ($module->version == 'development' && getDolGlobalInt('MAIN_FEATURES_LEVEL') < 2) {
2201 $modulequalified = 0;
2202 }
2203 if ($module->version == 'experimental' && getDolGlobalInt('MAIN_FEATURES_LEVEL') < 1) {
2204 $modulequalified = 0;
2205 }
2206 if ($excludedisabled && $module->version == 'disabled') {
2207 $modulequalified = 0;
2208 }
2209
2210 if ($modulequalified) {
2211 print '<tr class="oddeven"><td>';
2212 print(empty($module->name) ? $name : $module->name);
2213 print "</td><td>\n";
2214 if (method_exists($module, 'info')) {
2215 print $module->info($langs); // @phan-suppress-current-line PhanUndeclaredMethod
2216 } else {
2217 print $module->description;
2218 }
2219 print '</td>';
2220
2221 // Active
2222 if (in_array($name, $def)) {
2223 print '<td class="center">'."\n";
2224 print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?action=del&token='.newToken().'&value='.urlencode($name).'&scan_dir='.$module->scandir.'&label='.urlencode($module->name).'">';
2225 print img_picto($langs->trans("Enabled"), 'switch_on');
2226 print '</a>';
2227 print '</td>';
2228 } else {
2229 if (!empty($module->phpmin) && versioncompare($module->phpmin, versionphparray()) > 0) {
2230 print '<td class="center">'."\n";
2231 print img_picto(dol_escape_htmltag($langs->trans("ErrorModuleRequirePHPVersion", implode('.', $module->phpmin))), 'switch_off', 'class="opacitymedium"');
2232 print "</td>";
2233 } else {
2234 print '<td class="center">'."\n";
2235 print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?action=set&token='.newToken().'&value='.urlencode($name).'&scan_dir='.urlencode($module->scandir).'&label='.urlencode($module->name).'">'.img_picto($langs->trans("Disabled"), 'switch_off').'</a>';
2236 print "</td>";
2237 }
2238 }
2239
2240 // Default
2241 if ($usedefault) {
2242 print '<td class="center">';
2243 if (getDolGlobalString($constpdf, $constpdfdefault) == (string) $name) {
2244 if ($actionunset) {
2245 print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?action='.$actionunset.'&token='.newToken().'&value='.urlencode($name).'&scan_dir='.urlencode($module->scandir).'&label='.urlencode($module->name).'" alt="'.$langs->trans("Disable").'">'.img_picto($langs->trans("Default"), 'on').'</a>';
2246 } else {
2247 print img_picto($langs->trans("Default"), 'on');
2248 }
2249 } else {
2250 print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?action=setdoc&token='.newToken().'&value='.urlencode($name).'&scan_dir='.urlencode($module->scandir).'&label='.urlencode($module->name).'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"), 'off').'</a>';
2251 }
2252 print '</td>';
2253 }
2254
2255 // Info
2256 $htmltooltip = ''.$langs->trans("Name").': '.$module->name;
2257 $htmltooltip .= '<br>'.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown"));
2258 if ($module->type == 'pdf') {
2259 $htmltooltip .= '<br>'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur;
2260 }
2261 $htmltooltip .= '<br>'.$langs->trans("Path").': '.preg_replace('/^\//', '', $realpath).'/'.$file;
2262
2263 $htmltooltip .= '<br><br><u>'.$langs->trans("FeaturesSupported").':</u>';
2264 foreach ($features as $key => $property) {
2265 $htmltooltip .= '<br>'.$langs->trans($key).': '.yn($module->$property, 1, 1);
2266 }
2267
2268 print '<td class="center">';
2269 print $form->textwithpicto('', $htmltooltip, 1, 'info');
2270 print '</td>';
2271
2272 // Preview
2273 print '<td class="center">';
2274 if ($module->type == 'pdf') {
2275 print '<a href="'.dolBuildUrl($_SERVER["PHP_SELF"], array('action' => 'specimen', 'module' => $name), true).'">'.img_object($langs->trans("Preview"), 'pdf').'</a>';
2276 } else {
2277 print img_object($langs->transnoentitiesnoconv("PreviewNotAvailable"), 'generic');
2278 }
2279 print '</td>';
2280
2281 print "</tr>\n";
2282 }
2283 }
2284 }
2285 }
2286 }
2287 }
2288 }
2289 }
2290
2291 print '</table>';
2292 print '</div>';
2293}
2294
2295
2310function printNumberingModuleList($moduledir, $prefix, $constname, $title, $specimenobject, $actionname = 'setmod')
2311{
2312 global $db, $langs, $conf, $mysoc;
2313
2314 $form = new Form($db);
2315 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
2316
2317 print load_fiche_titre($title, '', '');
2318
2319 print '<div class="div-table-responsive-no-min">';
2320 print '<table class="noborder centpercent">';
2321 print '<tr class="liste_titre">';
2322 print '<td>'.$langs->trans("Name").'</td>';
2323 print '<td>'.$langs->trans("Description").'</td>';
2324 print '<td class="nowrap">'.$langs->trans("Example").'</td>';
2325 print '<td class="center" width="60">'.$langs->trans("Status").'</td>';
2326 print '<td class="center" width="60">'.$langs->trans("ShortInfo").'</td>';
2327 print "</tr>\n";
2328
2329 clearstatcache();
2330
2331 $arrayofmodules = array();
2332
2333 foreach ($dirmodels as $reldir) {
2334 $dir = dol_buildpath($reldir."core/modules/".$moduledir);
2335
2336 if (is_dir($dir)) {
2337 $handle = opendir($dir);
2338 if (is_resource($handle)) {
2339 while (($file = readdir($handle)) !== false) {
2340 if (dol_substr($file, 0, dol_strlen($prefix)) == $prefix && dol_substr($file, dol_strlen($file) - 3, 3) == 'php') {
2341 $file = dol_substr($file, 0, dol_strlen($file) - 4);
2342
2343 require_once $dir.'/'.$file.'.php';
2344
2345 $module = new $file();
2346 '@phan-var-force CommonNumRefGenerator $module';
2349 $arrayofmodules[] = $module;
2350 }
2351 }
2352 closedir($handle);
2353 }
2354 }
2355 }
2356
2357 $arrayofmodules = dol_sort_array($arrayofmodules, 'position');
2359 '@phan-var-force CommonNumRefGenerator[] $arrayofmodules';
2360
2361 foreach ($arrayofmodules as $module) {
2362 $file = get_class($module);
2363
2364 if ($module->isEnabled()) {
2365 // Show modules according to features level
2366 if ($module->version == 'development' && getDolGlobalInt('MAIN_FEATURES_LEVEL') < 2) {
2367 continue;
2368 }
2369 if ($module->version == 'experimental' && getDolGlobalInt('MAIN_FEATURES_LEVEL') < 1) {
2370 continue;
2371 }
2372
2373 print '<tr class="oddeven"><td>'.$module->getName($langs)."</td>\n";
2374 print '<td>';
2375 print $module->info($langs);
2376 print '</td>';
2377
2378 // Show example of numbering module
2379 print '<td class="nowrap">';
2380 $tmp = $module->getExample(); // @phan-suppress-current-line PhanUndeclaredMethod
2381 if (preg_match('/^Error/', $tmp)) {
2382 $langs->load("errors");
2383 print '<div class="error">'.$langs->trans($tmp).'</div>';
2384 } elseif ($tmp == 'NotConfigured') {
2385 print '<span class="opacitymedium">'.$langs->trans($tmp).'</span>';
2386 } else {
2387 print $tmp;
2388 }
2389 print '</td>'."\n";
2390
2391 print '<td class="center">';
2392 if (getDolGlobalString($constname) == $file) {
2393 print img_picto($langs->trans("Activated"), 'switch_on');
2394 } else {
2395 print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?action='.$actionname.'&token='.newToken().'&value='.urlencode($file).'">';
2396 print img_picto($langs->trans("Disabled"), 'switch_off');
2397 print '</a>';
2398 }
2399 print '</td>';
2400
2401 // Info
2402 $htmltooltip = '';
2403 $htmltooltip .= ''.$langs->trans("Version").': <b>'.$module->getVersion().'</b><br>';
2404 $nextval = $module->getNextValue($mysoc, $specimenobject); // @phan-suppress-current-line PhanUndeclaredMethod
2405 if ((string) $nextval != $langs->trans("NotAvailable")) { // Keep " on nextval
2406 $htmltooltip .= ''.$langs->trans("NextValue").': ';
2407 if ($nextval) {
2408 if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') {
2409 $nextval = $langs->trans($nextval);
2410 }
2411 $htmltooltip .= $nextval.'<br>';
2412 } else {
2413 $htmltooltip .= $langs->trans($module->error).'<br>';
2414 }
2415 }
2416
2417 print '<td class="center">';
2418 print $form->textwithpicto('', $htmltooltip, 1, 'info');
2419 print '</td>';
2420
2421 print '</tr>';
2422 }
2423 }
2424
2425 print '</table>';
2426 print '</div>';
2427}
2428
2429
2436{
2437 ob_start();
2438 phpinfo();
2439 $phpinfostring = ob_get_contents();
2440 ob_end_clean();
2441
2442 $info_arr = array();
2443 $info_lines = explode("\n", strip_tags($phpinfostring, "<tr><td><h2>"));
2444 $cat = "General";
2445 foreach ($info_lines as $line) {
2446 // new cat?
2447 $title = array();
2448 preg_match("~<h2>(.*)</h2>~", $line, $title) ? $cat = $title[1] : null;
2449 $val = array();
2450 if (preg_match("~<tr><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td></tr>~", $line, $val)) {
2451 $info_arr[trim($cat)][trim($val[1])] = $val[2];
2452 } elseif (preg_match("~<tr><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td></tr>~", $line, $val)) {
2453 $info_arr[trim($cat)][trim($val[1])] = array("local" => $val[2], "master" => $val[3]);
2454 }
2455 }
2456 return $info_arr;
2457}
2458
2465{
2466 global $langs, $conf;
2467
2468 $h = 0;
2469 $head = array();
2470
2471 $head[$h][0] = DOL_URL_ROOT."/admin/company.php";
2472 $head[$h][1] = $langs->trans("MyOrganization");
2473 $head[$h][2] = 'company';
2474 $h++;
2475
2476 $head[$h][0] = DOL_URL_ROOT."/admin/company_socialnetworks.php";
2477 $head[$h][1] = $langs->trans("SocialNetworksInformation");
2478 $head[$h][2] = 'socialnetworks';
2479
2480 $h++;
2481 $head[$h][0] = DOL_URL_ROOT."/admin/openinghours.php";
2482 $head[$h][1] = $langs->trans("OpeningHours");
2483 $head[$h][2] = 'openinghours';
2484 $h++;
2485
2486 $head[$h][0] = DOL_URL_ROOT."/admin/subcontractors.php";
2487 $head[$h][1] = $langs->trans("Subcontractors");
2488 $head[$h][2] = 'subcontractors';
2489 $h++;
2490
2491 complete_head_from_modules($conf, $langs, null, $head, $h, 'mycompany_admin', 'add');
2492
2493 complete_head_from_modules($conf, $langs, null, $head, $h, 'mycompany_admin', 'remove');
2494
2495 return $head;
2496}
2497
2504{
2505 global $langs, $conf, $user;
2506
2507 $h = 0;
2508 $head = array();
2509
2510 if (!empty($user->admin) && (empty($_SESSION['leftmenu']) || $_SESSION['leftmenu'] != 'email_templates')) {
2511 $head[$h][0] = DOL_URL_ROOT."/admin/mails.php";
2512 $head[$h][1] = $langs->trans("OutGoingEmailSetup");
2513 $head[$h][2] = 'common';
2514 $h++;
2515
2516 if (isModEnabled('mailing')) {
2517 $head[$h][0] = DOL_URL_ROOT."/admin/mails_emailing.php";
2518 $head[$h][1] = $langs->trans("OutGoingEmailSetupForEmailing", $langs->transnoentitiesnoconv("EMailing"));
2519 $head[$h][2] = 'common_emailing';
2520 $h++;
2521 }
2522
2523 if (isModEnabled('ticket')) {
2524 $head[$h][0] = DOL_URL_ROOT."/admin/mails_ticket.php";
2525 $head[$h][1] = $langs->trans("OutGoingEmailSetupForEmailing", $langs->transnoentitiesnoconv("Ticket"));
2526 $head[$h][2] = 'common_ticket';
2527 $h++;
2528 }
2529
2530 if (!getDolGlobalString('MAIN_MAIL_HIDE_CUSTOM_SENDING_METHOD_FOR_PASSWORD_RESET')) {
2531 $head[$h][0] = DOL_URL_ROOT."/admin/mails_passwordreset.php";
2532 $head[$h][1] = $langs->trans("OutGoingEmailSetupForEmailing", $langs->transnoentitiesnoconv("PasswordReset"));
2533 $head[$h][2] = 'common_passwordreset';
2534 $h++;
2535 }
2536 }
2537
2538 // Admin and non admin can view this menu entry, but it is not shown yet when we on user menu "Email templates"
2539 if (empty($_SESSION['leftmenu']) || $_SESSION['leftmenu'] != 'email_templates') {
2540 $head[$h][0] = DOL_URL_ROOT."/admin/mails_senderprofile_list.php";
2541 $head[$h][1] = $langs->trans("EmailSenderProfiles");
2542 $head[$h][2] = 'senderprofiles';
2543 $h++;
2544 }
2545
2546 $head[$h][0] = DOL_URL_ROOT."/admin/mails_templates.php";
2547 $head[$h][1] = $langs->trans("EMailTemplates");
2548 $head[$h][2] = 'templates';
2549 $h++;
2550
2551 $head[$h][0] = DOL_URL_ROOT."/admin/mails_ingoing.php";
2552 $head[$h][1] = $langs->trans("InGoingEmailSetup", $langs->transnoentitiesnoconv("EMailing"));
2553 $head[$h][2] = 'common_ingoing';
2554 $h++;
2555
2556 complete_head_from_modules($conf, $langs, null, $head, $h, 'email_admin', 'remove');
2557
2558 return $head;
2559}
2560
2567{
2568 return array(
2569 // Fetch directives
2570 "child-src" => array("label" => "child-src", "data-directivetype" => "fetch"),
2571 "connect-src" => array("label" => "connect-src", "data-directivetype" => "fetch"),
2572 "default-src" => array("label" => "default-src", "data-directivetype" => "fetch"),
2573 "fenced-frame-src" => array("label" => "fenced-frame-src", "data-directivetype" => "fetch"),
2574 "font-src" => array("label" => "font-src", "data-directivetype" => "fetch"),
2575 "frame-src" => array("label" => "frame-src", "data-directivetype" => "fetch"),
2576 "img-src" => array("label" => "img-src", "data-directivetype" => "fetch"),
2577 "manifest-src" => array("label" => "manifest-src", "data-directivetype" => "fetch"),
2578 "media-src" => array("label" => "media-src", "data-directivetype" => "fetch"),
2579 "object-src" => array("label" => "object-src", "data-directivetype" => "fetch"),
2580 "prefetch-src" => array("label" => "prefetch-src", "data-directivetype" => "fetch"),
2581 "script-src" => array("label" => "script-src", "data-directivetype" => "fetch"),
2582 "script-src-elem" => array("label" => "script-src-elem", "data-directivetype" => "fetch"),
2583 "script-src-attr" => array("label" => "script-src-attr", "data-directivetype" => "fetch"),
2584 "style-src" => array("label" => "style-src","data-directivetype" => "fetch"),
2585 "style-src-elem" => array("label" => "style-src-elem", "data-directivetype" => "fetch"),
2586 "style-src-attr" => array("label" => "style-src-attr", "data-directivetype" => "fetch"),
2587 "worker-src" => array("label" => "worker-src", "data-directivetype" => "fetch"),
2588 // Document directives
2589 "base-uri" => array("label" => "base-uri", "data-directivetype" => "document"),
2590 "sandbox" => array("label" => "sandbox", "data-directivetype" => "document"),
2591 // Navigation directives
2592 "form-action" => array("label" => "form-action", "data-directivetype" => "navigation"),
2593 "frame-ancestors" => array("label" => "frame-ancestors", "data-directivetype" => "navigation"),
2594 // Reporting directives
2595 "report-to" => array("label" => "report-to", "data-directivetype" => "reporting"),
2596 // Other directives
2597 "require-trusted-types-for" => array("label" => "require-trusted-types-for", "data-directivetype" => "require-trusted-types-for"),
2598 "trusted-types" => array("label" => "trusted-types", "data-directivetype" => "trusted-types"),
2599 "upgrade-insecure-requests" => array("label" => "upgrade-insecure-requests", "data-directivetype" => "none"),
2600 );
2601}
2602
2609{
2610 return array(
2611 // Fetch directives
2612 "fetch" => array(
2613 "*" => array("label" => "*", "data-sourcetype" => "select"),
2614 "blob" => array("label" => "blob:", "data-sourcetype" => "blob"),
2615 "data" => array("label" => "data:", "data-sourcetype" => "data"),
2616 "self" => array("label" => "self", "data-sourcetype" => "quoted"),
2617 "unsafe-eval" => array("label" => "unsafe-eval", "data-sourcetype" => "quoted"),
2618 "wasm-unsafe-eval" => array("label" => "wasm-unsafe-eval", "data-sourcetype" => "quoted"),
2619 "unsafe-inline" => array("label" => "unsafe-inline", "data-sourcetype" => "quoted"),
2620 "unsafe-hashes" => array("label" => "unsafe-hashes", "data-sourcetype" => "quoted"),
2621 "inline-speculation-rules" => array("label" => "inline-speculation-rules", "data-sourcetype" => "quoted"),
2622 "strict-dynamic" => array("label" => "strict-dynamic", "data-sourcetype" => "quoted"),
2623 "report-sample" => array("label" => "report-sample", "data-sourcetype" => "quoted"),
2624 "host-source" => array("label" => "host-source (*.mydomain.com)", "data-sourcetype" => "input"),
2625 "scheme-source" => array("label" => "scheme-source", "data-sourcetype" => "input"),
2626 ),
2627 // Document directives
2628 "document" => array(
2629 "none" => array("label" => "self", "data-sourcetype" => "quoted"),
2630 "self" => array("label" => "self", "data-sourcetype" => "quoted"),
2631 "host-source" => array("label" => "host-source (*.mydomain.com)", "data-sourcetype" => "input"),
2632 "scheme-source" => array("label" => "scheme-source (*.mydomain.com)", "data-sourcetype" => "input"),
2633 ),
2634 // Navigation directives
2635 "navigation" => array(
2636 "none" => array("label" => "self", "data-sourcetype" => "quoted"),
2637 "self" => array("label" => "self", "data-sourcetype" => "quoted"),
2638 "host-source" => array("label" => "host-source (*.mydomain.com)", "data-sourcetype" => "input"),
2639 "scheme-source" => array("label" => "scheme-source", "data-sourcetype" => "input"),
2640 ),
2641 // Reporting directives
2642 "reporting" => array(
2643 "report-to" => array("label" => "report-to", "data-sourcetype" => "input"),
2644 ),
2645 // Other directives
2646 "require-trusted-types-for" => array(
2647 "script" => array("label" => "script", "data-sourcetype" => "select"),
2648 ),
2649 "trusted-types" => array(
2650 "policyName" => array("label" => "policyName", "data-sourcetype" => "input"),
2651 "none" => array("label" => "none", "data-sourcetype" => "quoted"),
2652 "allow-duplicates" => array("label" => "allow-duplicates", "data-sourcetype" => "quoted"),
2653 ),
2654 );
2655}
2656
2663function GetContentPolicyToArray($forceCSP)
2664{
2665 $forceCSPArr = array();
2666 $sourceCSPArr = GetContentPolicySources();
2667 $sourceCSPArrflatten = array();
2668
2669 // We remove a level for sources array
2670 foreach ($sourceCSPArr as $key => $arr) {
2671 $sourceCSPArrflatten = array_merge($sourceCSPArrflatten, array_keys($arr));
2672 }
2673 // Manage the issue where the data:text/plain;base64,SGVsbG8sIFdvcmxkIQ%3D%3D string is getting split, as well as the issue with the "add" button.
2674 $forceCSP = preg_replace('/;base64,/', "__semicolumnbase64__", $forceCSP);
2675 $securitypolicies = explode(";", $forceCSP);
2676
2677 // Loop on each security policy to create an array
2678 foreach ($securitypolicies as $key => $securitypolicy) {
2679 if ($securitypolicy == "") {
2680 continue;
2681 }
2682 $securitypolicy = preg_replace('/__semicolumnbase64__/', ";base64,", $securitypolicy);
2683 $securitypolicyarr = explode(" ", $securitypolicy);
2684 $directive = array_shift($securitypolicyarr);
2685 // Remove unwanted spaces
2686 while ($directive == "") {
2687 $directive = array_shift($securitypolicyarr);
2688 }
2689 if (empty($directive)) {
2690 continue;
2691 }
2692 $sources = $securitypolicyarr;
2693 if (empty($sources)) {
2694 $forceCSPArr[$directive] = array();
2695 } else {
2696 //Loop on each sources to add to the right directive array key
2697 foreach ($sources as $key2 => $source) {
2698 $source = str_replace("'", "", $source);
2699 if (empty($source)) {
2700 continue;
2701 }
2702 if (empty($forceCSPArr[$directive])) {
2703 $forceCSPArr[$directive] = array($source);
2704 } else {
2705 $forceCSPArr[$directive][] = $source;
2706 }
2707 }
2708 }
2709 }
2710 return $forceCSPArr;
2711}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
versiontostring($versionarray)
Return a version in a string from a version into an array.
Definition admin.lib.php:40
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.
form_constantes($tableau, $strictw3c=2, $helptext='', $text='')
Show array with constants to edit.
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.
dolibarr_del_const($db, $name, $entity=1)
Delete a constant.
versiondolibarrarray()
Return version Dolibarr.
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:72
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.
GetContentPolicySources()
Prepare array of sources for HTTP headers.
GetContentPolicyToArray($forceCSP)
Transform a Content Security Policy to an array.
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.
GetContentPolicyDirectives()
Prepare array of directives for HTTP headers.
Class to manage a WYSIWYG editor.
Class DolibarrModules.
Class to manage generation of HTML components Only common components must be here.
Class to manage a HTML form to send a unitary email Usage: $formail = new FormMail($db) $formmail->pr...
Class to manage hooks.
if(! $sortfield) if(! $sortorder) $module
Definition list.php:193
global $mysoc
dolKeepOnlyPhpCode($str)
Keep only PHP code part from a HTML string page.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
dolGetModulesDirs($subdir='')
Return list of directories that contain modules.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
dolBuildUrl($url, $params=[], $addtoken=false, $anchor='')
Return path of url.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
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...
newToken()
Return the value of token currently saved into session with name 'newtoken'.
dol_htmlentities($string, $flags=ENT_QUOTES|ENT_SUBSTITUTE, $encoding='UTF-8', $double_encode=false)
Replace htmlentities functions.
dol_substr($string, $start, $length=null, $stringencoding='', $trunconbytes=0)
Make a substring.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
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.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
img_down($titlealt='default', $selected=0, $moreclass='')
Show down arrow logo.
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='', $morecssonpicto='widthpictotitle')
Load a title with picto.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Definition html.lib.php:181
dolListSessions()
List sessions in db.
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:140
dolDecrypt($chain, $key='', $patterntotest='')
Decode a string with a symmetric encryption.
dolEncrypt($chain, $key='', $ciphering='', $forceseed='', $obfuscationmode='dolcrypt')
Encode a string with a symmetric encryption.
checkPHPCode(&$phpfullcodestringold, &$phpfullcodestring)
Check that the new string $phpfullcodestring contains only php code (including <php tag)