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