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