dolibarr 25.0.0-alpha
utils.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2016 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2021 Regis Houssin <regis.houssin@inodbox.com>
4 * Copyright (C) 2022 Anthony Berton <anthony.berton@bb2a.fr>
5 * Copyright (C) 2023-2024 William Mead <william.mead@manchenumerique.fr>
6 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
7 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 */
22
33class Utils
34{
38 public $db;
39
44 public $error;
45
49 public $errors;
50
54 public $output;
55
59 public $result;
60
66 public function __construct($db)
67 {
68 $this->db = $db;
69 }
70
71
80 public function purgeFiles($choices = 'tempfilesold+logfiles', $nbsecondsold = 86400)
81 {
82 global $conf, $langs, $user;
83 global $dolibarr_main_data_root;
84
85 $langs->load("admin");
86
87 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
88
89 if (empty($choices)) {
90 $choices = 'tempfilesold+logfiles';
91 }
92 if ($choices == 'allfiles' && $nbsecondsold > 0) {
93 $choices = 'allfilesold';
94 }
95
96 dol_syslog("Utils::purgeFiles choice=".$choices, LOG_DEBUG);
97
98 // For dangerous action, we check the user is admin
99 if (in_array($choices, array('allfiles', 'allfilesold'))) {
100 if (empty($user->admin)) {
101 $this->output = 'Error: to erase data files, user running the batch (currently '.$user->login.') must be an admin user';
102 return 1;
103 }
104 }
105
106 $count = 0;
107 $countdeleted = 0;
108 $counterror = 0;
109 $filelog = '';
110
111 $choicesarray = preg_split('/[\+,]/', $choices);
112 foreach ($choicesarray as $choice) {
113 $now = dol_now();
114 $filesarray = array();
115
116 if ($choice == 'tempfiles' || $choice == 'tempfilesold') {
117 // Delete temporary files
118 if ($dolibarr_main_data_root) {
119 $filesarray = dol_dir_list($dolibarr_main_data_root, "directories", 1, '^temp$', '', 'name', SORT_ASC, 2, 0, '', 1); // Do not follow symlinks
120
121 if ($choice == 'tempfilesold') {
122 foreach ($filesarray as $key => $val) {
123 if ($val['date'] > ($now - ($nbsecondsold))) {
124 unset($filesarray[$key]); // Discard temp dir not older than $nbsecondsold
125 }
126 }
127 }
128 }
129 }
130
131 if ($choice == 'allfiles') {
132 // Delete all files (except .lock and .unlock files, do not follow symbolic links)
133 if ($dolibarr_main_data_root) {
134 $filesarray = dol_dir_list($dolibarr_main_data_root, "all", 0, '', '(\.lock|\.unlock)$', 'name', SORT_ASC, 0, 0, '', 1); // No need to use recursive, we will delete directory
135 }
136 }
137
138 if ($choice == 'allfilesold') {
139 // Delete all files (except .lock and .unlock files, do not follow symbolic links)
140 if ($dolibarr_main_data_root) {
141 $filesarray = dol_dir_list($dolibarr_main_data_root, "files", 1, '', '(\.lock|\.unlock)$', 'name', SORT_ASC, 0, 0, '', 1, $nbsecondsold); // No need to use recursive, we will delete directory
142 }
143 }
144
145 if ($choice == 'logfile' || $choice == 'logfiles') {
146 // Define files log
147 if ($dolibarr_main_data_root) {
148 $filesarray = dol_dir_list($dolibarr_main_data_root, "files", 0, '.*\.log[\.0-9]*(\.gz)?$', '(\.lock|\.unlock)$', 'name', SORT_ASC, 0, 0, '', 1);
149 }
150
151 if (isModEnabled('syslog')) {
152 $filelog = getDolGlobalString('SYSLOG_FILE');
153 $filelog = preg_replace('/DOL_DATA_ROOT/i', DOL_DATA_ROOT, $filelog);
154
155 $alreadyincluded = false;
156 foreach ($filesarray as $tmpcursor) {
157 if ($tmpcursor['fullname'] == $filelog) {
158 $alreadyincluded = true;
159 }
160 }
161 if (!$alreadyincluded) {
162 $filesarray[] = array('fullname' => $filelog, 'type' => 'file');
163 }
164 }
165 }
166
167 if (is_array($filesarray) && count($filesarray)) {
168 foreach ($filesarray as $key => $value) {
169 //print "x ".$filesarray[$key]['fullname']."-".$filesarray[$key]['type']."<br>\n";
170 if ($filesarray[$key]['type'] == 'dir') {
171 $startcount = 0;
172 $tmpcountdeleted = 0;
173
174 $result = dol_delete_dir_recursive($filesarray[$key]['fullname'], $startcount, 1, 0, $tmpcountdeleted);
175
176 $excluded = [
177 $conf->user->dir_temp,
178 ];
179 if (isModEnabled('api')) {
180 $excluded[] = $conf->api->dir_temp;
181 }
182 // The 2 directories $conf->api->dir_temp and $conf->user->dir_temp are recreated at end, so we do not count them
183 if (!in_array($filesarray[$key]['fullname'], $excluded)) {
184 $count += $result;
185 $countdeleted += $tmpcountdeleted;
186 }
187 } elseif ($filesarray[$key]['type'] == 'file') {
188 if ($choice != 'allfilesold' || $filesarray[$key]['date'] < ($now - $nbsecondsold)) {
189 // If (file that is not logfile) or (if mode is logfile)
190 if ($filesarray[$key]['fullname'] != $filelog || $choice == 'logfile' || $choice == 'logfiles') {
191 $result = dol_delete_file($filesarray[$key]['fullname'], 1, 1);
192 if ($result) {
193 $count++;
194 $countdeleted++;
195 } else {
196 $counterror++;
197 }
198 }
199 }
200 }
201 }
202
203 // Update cachenbofdoc
204 if (isModEnabled('ecm') && $choice == 'allfiles') {
205 require_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmdirectory.class.php';
206 $ecmdirstatic = new EcmDirectory($this->db);
207 $result = $ecmdirstatic->refreshcachenboffile(1);
208 }
209 }
210 }
211
212 if ($count > 0) {
213 $langs->load("admin");
214 $this->output = $langs->trans("PurgeNDirectoriesDeleted", $countdeleted);
215 if ($count > $countdeleted) {
216 $this->output .= '<br>'.$langs->trans("PurgeNDirectoriesFailed", ($count - $countdeleted));
217 }
218 } else {
219 $this->output = $langs->trans("PurgeNothingToDelete").(in_array('tempfilesold', $choicesarray) ? ' (older than 24h for temp files)' : '');
220 }
221
222 // Recreate temp dir that are not automatically recreated by core code, we need them
223 if (isModEnabled('api')) {
224 // We should create also dir x/api/temp for multicompany dirs, but this has become useless because dir is now recreated by constructor of api.class.php
225 dol_mkdir($conf->api->dir_temp);
226 }
227 dol_mkdir($conf->user->dir_temp);
228
229 //return $count;
230 return 0; // This function can be called by cron so must return 0 if OK
231 }
232
233
247 public function dumpDatabase($compression = 'none', $type = 'auto', $usedefault = 1, $file = 'auto', $keeplastnfiles = 0, $execmethod = 0, $lowmemorydump = 0)
248 {
249 global $db, $conf, $langs;
250 global $dolibarr_main_db_name, $dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_port, $dolibarr_main_db_pass;
251 global $dolibarr_main_db_character_set;
252 global $dolibarr_main_restrict_os_commands;
253
254 $langs->load("admin");
255
256 dol_syslog("Utils::dumpDatabase type=".$type." compression=".$compression." file=".$file, LOG_DEBUG);
257 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
258
259 // Clean data
260 $file = dol_sanitizeFileName($file);
261
262 // Check compression parameter
263 if (!in_array($compression, array('none', 'gz', 'bz', 'zip', 'zstd'))) {
264 $langs->load("errors");
265 $this->error = $langs->transnoentitiesnoconv("ErrorBadValueForParameter", $compression, "Compression");
266 return -1;
267 }
268
269 // Check type parameter
270 if ($type == 'auto') {
271 $type = $this->db->type;
272 }
273 if (!in_array($type, array('postgresql', 'pgsql', 'mysql', 'mysqli', 'mysqlnobin'))) {
274 $langs->load("errors");
275 $this->error = $langs->transnoentitiesnoconv("ErrorBadValueForParameter", $type, "Basetype");
276 return -1;
277 }
278
279 // Check file parameter
280 if ($file == 'auto') {
281 $prefix = 'dump';
282 $ext = 'sql';
283 if (in_array($type, array('mysql', 'mysqli'))) {
284 $prefix = 'mysqldump';
285 }
286 //if ($label == 'PostgreSQL') { $prefix='pg_dump'; $ext='dump'; }
287 if (in_array($type, array('pgsql'))) {
288 $prefix = 'pg_dump';
289 }
290 $file = $prefix.'_'.$dolibarr_main_db_name.'_'.dol_sanitizeFileName(DOL_VERSION).'_'.dol_print_date(dol_now('gmt'), "dayhourlogsmall", 'tzuser').'.'.$ext;
291 }
292
293 $outputdir = $conf->admin->dir_output.'/backup';
294 $result = dol_mkdir($outputdir);
295 $errormsg = '';
296
297 // MYSQL
298 if ($type == 'mysql' || $type == 'mysqli') {
299 if (!getDolGlobalString('SYSTEMTOOLS_MYSQLDUMP')) {
300 $cmddump = $db->getPathOfDump();
301 } else {
302 $cmddump = getDolGlobalString('SYSTEMTOOLS_MYSQLDUMP');
303 }
304 if (empty($cmddump)) {
305 $this->error = "Failed to detect command to use for mysqldump. Try a manual backup before to set path of command.";
306 return -1;
307 }
308
309 $outputfile = $outputdir.'/'.$file;
310 // for compression format, we add extension
311 $compression = $compression ? $compression : 'none';
312 if ($compression == 'gz') {
313 $outputfile .= '.gz';
314 } elseif ($compression == 'bz') {
315 $outputfile .= '.bz2';
316 } elseif ($compression == 'zstd') {
317 $outputfile .= '.zst';
318 }
319 $outputerror = $outputfile.'.err';
320 dol_mkdir($conf->admin->dir_output.'/backup');
321
322 $cmddump = dol_sanitizePathName($cmddump); // Sanitize path
323 $cmddump = dol_string_nospecial($cmddump, '', array("|", ";", "<", ">", "&", "+")); // Sanitize command
324 $basenamecmddump = basename(str_replace('\\', '/', $cmddump));
325
326 // Sanitize and validate $cmddump
327 if (!empty($dolibarr_main_restrict_os_commands)) {
328 $arrayofallowedcommand = explode(',', $dolibarr_main_restrict_os_commands);
329 $arrayofallowedcommand = array_map('trim', $arrayofallowedcommand);
330 dol_syslog("Command are restricted to ".$dolibarr_main_restrict_os_commands.". We check that one of this command is inside ".$cmddump);
331 if (!in_array($basenamecmddump, $arrayofallowedcommand)) { // the provided command $cmddump must be an allowed command
332 $langs->load("errors");
333 $this->error = $langs->trans('CommandIsNotInsideAllowedCommands');
334 $this->error .= '<br>'.$langs->trans('ErrorCheckTheCommandInsideTheAdvancedOptions');
335 return -1;
336 }
337 }
338
339 // Parameters execution
340 $command = $cmddump;
341 $command = preg_replace('/(\$|%)/', '', $command); // We removed chars that can be used to inject vars that contains space inside path of command without seeing there is a space to bypass the escapeshellarg.
342 if (preg_match("/\s/", $command)) {
343 $command = escapeshellarg($command); // If there is spaces, we add quotes on command to be sure $command is only a program and not a program+parameters
344 }
345
346 //$param=escapeshellarg($dolibarr_main_db_name)." -h ".escapeshellarg($dolibarr_main_db_host)." -u ".escapeshellarg($dolibarr_main_db_user)." -p".escapeshellarg($dolibarr_main_db_pass);
347 $param = $dolibarr_main_db_name." -h ".$dolibarr_main_db_host;
348 $param .= " -u ".$dolibarr_main_db_user;
349 if (!empty($dolibarr_main_db_port)) {
350 $param .= " -P ".$dolibarr_main_db_port." --protocol=tcp";
351 }
352 if (GETPOST("use_transaction", "alpha")) {
353 $param .= " --single-transaction";
354 }
355 if (GETPOST("disable_fk", "alpha") || $usedefault) {
356 $param .= " -K";
357 }
358 if (GETPOST("sql_compat", "alpha") && GETPOST("sql_compat", "alpha") != 'NONE') {
359 $param .= " --compatible=".escapeshellarg(GETPOST("sql_compat", "alpha"));
360 }
361 if (GETPOST("drop_database", "alpha")) {
362 $param .= " --add-drop-database";
363 }
364 if (GETPOST("use_mysql_quick_param", "alpha")) {
365 $param .= " --quick";
366 }
367 if (GETPOST("use_force", "alpha")) {
368 $param .= " -f";
369 }
370 if (GETPOST("sql_structure", "alpha") || $usedefault) {
371 if (GETPOST("drop", "alpha") || $usedefault) {
372 $param .= " --add-drop-table=TRUE";
373 } else {
374 $param .= " --add-drop-table=FALSE";
375 }
376 } else {
377 $param .= " -t";
378 }
379 if (GETPOST("disable-add-locks", "alpha")) {
380 $param .= " --add-locks=FALSE";
381 }
382 if (GETPOST("sql_data", "alpha") || $usedefault) {
383 $param .= " --tables";
384 if (GETPOST("showcolumns", "alpha") || $usedefault) {
385 $param .= " -c";
386 }
387 if (GETPOST("extended_ins", "alpha") || $usedefault) {
388 $param .= " -e";
389 } else {
390 $param .= " --skip-extended-insert";
391 }
392 if (GETPOST("delayed", "alpha")) {
393 $param .= " --delayed-insert";
394 }
395 if (GETPOST("sql_ignore", "alpha")) {
396 $param .= " --insert-ignore";
397 }
398 if (GETPOST("hexforbinary", "alpha") || $usedefault) {
399 $param .= " --hex-blob";
400 }
401 } else {
402 $param .= " -d"; // No row information (no data)
403 }
404 if ($dolibarr_main_db_character_set == 'utf8mb4') {
405 // We save output into utf8mb4 charset
406 $param .= " --default-character-set=utf8mb4 --no-tablespaces";
407 } else {
408 $param .= " --default-character-set=utf8 --no-tablespaces"; // We always save output into utf8 charset
409 }
410 $paramcrypted = $param;
411 $paramclear = $param;
412 if (!empty($dolibarr_main_db_pass)) {
413 $paramcrypted .= ' -p"'.preg_replace('/./i', '*', $dolibarr_main_db_pass).'"';
414 $paramclear .= ' -p"'.str_replace(array('"', '`', '$'), array('\"', '\`', '\$'), $dolibarr_main_db_pass).'"';
415 }
416
417 $handle = '';
418
419 // Start call method to execute dump
420 $fullcommandcrypted = $command." ".$paramcrypted." 2>&1";
421 $fullcommandclear = $command." ".$paramclear." 2>&1";
422 if (!$lowmemorydump) {
423 if ($compression == 'none') {
424 $handle = fopen($outputfile, 'w');
425 } elseif ($compression == 'gz') {
426 $handle = gzopen($outputfile, 'w');
427 } elseif ($compression == 'bz') {
428 $handle = bzopen($outputfile, 'w');
429 } elseif ($compression == 'zstd') {
430 $handle = fopen($outputfile, 'w');
431 }
432 } else {
433 // TODO Add a pipe into script to decrypt dolCrypted values
434
435 if ($compression == 'none') {
436 $fullcommandclear .= ' | grep -v "Warning: Using a password on the command line interface can be insecure." > "'.dol_sanitizePathName($outputfile).'"';
437 $fullcommandcrypted .= ' | grep -v "Warning: Using a password on the command line interface can be insecure." > "'.dol_sanitizePathName($outputfile).'"';
438 $handle = 1;
439 } elseif ($compression == 'gz') {
440 $fullcommandclear .= ' | grep -v "Warning: Using a password on the command line interface can be insecure." | gzip > "'.dol_sanitizePathName($outputfile).'"';
441 $fullcommandcrypted .= ' | grep -v "Warning: Using a password on the command line interface can be insecure." | gzip > "'.dol_sanitizePathName($outputfile).'"';
442 $paramcrypted .= ' | grep -v "Warning: Using a password on the command line interface can be insecure." | gzip';
443 $handle = 1;
444 } elseif ($compression == 'bz') {
445 $fullcommandclear .= ' | grep -v "Warning: Using a password on the command line interface can be insecure." | bzip2 > "'.dol_sanitizePathName($outputfile).'"';
446 $fullcommandcrypted .= ' | grep -v "Warning: Using a password on the command line interface can be insecure." | bzip2 > "'.dol_sanitizePathName($outputfile).'"';
447 $paramcrypted .= ' | grep -v "Warning: Using a password on the command line interface can be insecure." | bzip2';
448 $handle = 1;
449 } elseif ($compression == 'zstd') {
450 $fullcommandclear .= ' | grep -v "Warning: Using a password on the command line interface can be insecure." | zstd > "'.dol_sanitizePathName($outputfile).'"';
451 $fullcommandcrypted .= ' | grep -v "Warning: Using a password on the command line interface can be insecure." | zstd > "'.dol_sanitizePathName($outputfile).'"';
452 $paramcrypted .= ' | grep -v "Warning: Using a password on the command line interface can be insecure." | zstd';
453 $handle = 1;
454 }
455 }
456
457 $ok = 0;
458 if ($handle) {
459 if (getDolGlobalString('MAIN_EXEC_USE_POPEN')) {
460 $execmethod = getDolGlobalString('MAIN_EXEC_USE_POPEN');
461 }
462 if (empty($execmethod)) {
463 $execmethod = 1;
464 }
465
466 dol_syslog("Utils::dumpDatabase execmethod=".$execmethod.", lowmemorydump=".$lowmemorydump.", command=".$fullcommandcrypted, LOG_INFO);
467
468
469 /* If value has been forced with a php_admin_value, this has no effect. Example of value: '512M' */
470 $MemoryLimit = getDolGlobalString('MAIN_MEMORY_LIMIT_DUMP');
471 if (!empty($MemoryLimit)) {
472 @ini_set('memory_limit', $MemoryLimit);
473 }
474
475
476 if ($execmethod == 1) {
477 $output_arr = array();
478 $retval = null;
479
480 exec($fullcommandclear, $output_arr, $retval); // @phan-suppress-current-line PhanPluginConstantVariableNull
481 // TODO Replace this exec with Utils->executeCLI() function.
482 // We must check that the case for $lowmemorydump works too...
483 //$utils = new Utils($db);
484 //$outputfile = $conf->admin->dir_temp.'/dump.tmp';
485 //$utils->executeCLI($fullcommandclear, $outputfile, 0);
486
487 if ($retval != 0) {
488 $langs->load("errors");
489 dol_syslog("Datadump retval after exec=".$retval, LOG_ERR);
490 $errormsg = 'Error '.$retval;
491 $ok = 0;
492 } else {
493 $i = 0;
494 if (!empty($output_arr)) {
495 foreach ($output_arr as $key => $read) {
496 $i++; // output line number
497 if ($i == 1 && preg_match('/Warning.*Using a password/i', $read)) {
498 continue;
499 }
500 // Now check into the result file, that the file end with "-- Dump completed"
501 // This is possible only if $output_arr is the clear dump file, so not possible with $lowmemorydump set because file is already compressed.
502 if (!$lowmemorydump) {
503 // TODO decrypt dolCrypted values from $read
504
505 fwrite($handle, $read.($execmethod == 2 ? '' : "\n"));
506 if (preg_match('/'.preg_quote('-- Dump completed', '/').'/i', $read)) {
507 $ok = 1;
508 } elseif (preg_match('/'.preg_quote('SET SQL_NOTES=@OLD_SQL_NOTES', '/').'/i', $read)) {
509 $ok = 1;
510 }
511 } else {
512 // If we have a result here in lowmemorydump mode, something is strange
513 }
514 }
515 } elseif ($lowmemorydump) {
516 $ok = 1;
517 }
518 }
519 }
520
521 if ($execmethod == 2) { // With this method, there is no way to get the return code, only output
522 $handlein = popen($fullcommandclear, 'r');
523 $i = 0;
524 if ($handlein) {
525 while (!feof($handlein)) {
526 $i++; // output line number
527 $read = fgets($handlein);
528 // Exclude warning line we don't want
529 if ($i == 1 && preg_match('/Warning.*Using a password/i', $read)) {
530 continue;
531 }
532 fwrite($handle, $read);
533 if (preg_match('/'.preg_quote('-- Dump completed', '/').'/i', $read)) {
534 $ok = 1;
535 } elseif (preg_match('/'.preg_quote('SET SQL_NOTES=@OLD_SQL_NOTES', '/').'/i', $read)) {
536 $ok = 1;
537 }
538 }
539 pclose($handlein);
540 }
541 }
542
543 if (!$lowmemorydump) {
544 if ($compression == 'none') {
545 fclose($handle);
546 } elseif ($compression == 'gz') {
547 gzclose($handle);
548 } elseif ($compression == 'bz') {
549 fclose($handle);
550 } elseif ($compression == 'zstd') {
551 fclose($handle);
552 }
553 }
554
555 dolChmod($outputfile);
556 } else {
557 $langs->load("errors");
558 dol_syslog("Failed to open file ".$outputfile, LOG_ERR);
559 $errormsg = $langs->trans("ErrorFailedToWriteInDir");
560 }
561
562 // Get errorstring
563 if ($compression == 'none') {
564 $handle = fopen($outputfile, 'r');
565 } elseif ($compression == 'gz') {
566 $handle = gzopen($outputfile, 'r');
567 } elseif ($compression == 'bz') {
568 $handle = bzopen($outputfile, 'r');
569 } elseif ($compression == 'zstd') {
570 $handle = fopen($outputfile, 'r');
571 }
572 if ($handle) {
573 // Get 2048 first chars of error message.
574 $errormsg = fgets($handle, 2048);
575 //$ok=0;$errormsg=''; To force error
576
577 // Close file
578 if ($compression == 'none') {
579 fclose($handle);
580 } elseif ($compression == 'gz') {
581 gzclose($handle);
582 } elseif ($compression == 'bz') {
583 fclose($handle);
584 } elseif ($compression == 'zstd') {
585 fclose($handle);
586 }
587 if ($ok && preg_match('/^-- (MySql|MariaDB)/i', $errormsg) || preg_match('/^\/\*M?!999999/', $errormsg)) { // Start of file is ok, NOT an error
588 $errormsg = '';
589 } else {
590 // Rename file out into a file error
591 //print "$outputfile -> $outputerror";
592 @dol_delete_file($outputerror, 1, 0, 0, null, false, 0);
593 @dol_move($outputfile, $outputerror, '0', 1, 0, 0);
594 // Si safe_mode on et command hors du parameter exec, on a un fichier out vide donc errormsg vide
595 if (!$errormsg) {
596 $langs->load("errors");
597 $errormsg = $langs->trans("ErrorFailedToRunExternalCommand");
598 }
599 }
600 }
601 // Fin execution commande
602
603 $this->output = $errormsg;
604 $this->error = $errormsg;
605 $this->result = array("commandbackuplastdone" => $command." ".$paramcrypted, "commandbackuptorun" => "");
606 //if (empty($this->output)) $this->output=$this->result['commandbackuplastdone'];
607 }
608
609 // MYSQL NO BIN
610 if ($type == 'mysqlnobin') {
611 $outputfile = $outputdir.'/'.$file;
612 $outputfiletemp = $outputfile.'-TMP.sql';
613 // for compression format, we add extension
614 $compression = $compression ? $compression : 'none';
615 if ($compression == 'gz') {
616 $outputfile .= '.gz';
617 }
618 if ($compression == 'bz') {
619 $outputfile .= '.bz2';
620 }
621 $outputerror = $outputfile.'.err';
622 dol_mkdir($conf->admin->dir_output.'/backup');
623
624 if ($compression == 'gz' or $compression == 'bz') {
625 $this->backupTables($outputfiletemp);
626 dol_compress_file($outputfiletemp, $outputfile, $compression);
627 unlink($outputfiletemp);
628 } else {
629 $this->backupTables($outputfile);
630 }
631
632 $this->output = "";
633 $this->result = array("commandbackuplastdone" => "", "commandbackuptorun" => "");
634 }
635
636 // POSTGRESQL
637 if ($type == 'postgresql' || $type == 'pgsql') {
638 $cmddump = getDolGlobalString('SYSTEMTOOLS_POSTGRESQLDUMP');
639
640 $outputfile = $outputdir.'/'.$file;
641 // for compression format, we add extension
642 $compression = $compression ? $compression : 'none';
643 if ($compression == 'gz') {
644 $outputfile .= '.gz';
645 }
646 if ($compression == 'bz') {
647 $outputfile .= '.bz2';
648 }
649 $outputerror = $outputfile.'.err';
650 dol_mkdir($conf->admin->dir_output.'/backup');
651
652 // Sanitize and validate $cmddump
653 $cmddump = dol_sanitizePathName($cmddump); // Sanitize path
654 $cmddump = dol_string_nospecial($cmddump, '', array("|", ";", "<", ">", "&", "+")); // Sanitize command
655 $basenamecmddump = basename(str_replace('\\', '/', $cmddump));
656
657 if (!empty($dolibarr_main_restrict_os_commands)) {
658 $arrayofallowedcommand = explode(',', $dolibarr_main_restrict_os_commands);
659 $arrayofallowedcommand = array_map('trim', $arrayofallowedcommand);
660 dol_syslog("Command are restricted to ".$dolibarr_main_restrict_os_commands.". We check that one of this command is inside ".$cmddump);
661 if (!in_array($basenamecmddump, $arrayofallowedcommand)) { // the provided command $cmddump must be an allowed command
662 $langs->load("errors");
663 $this->error = $langs->trans('CommandIsNotInsideAllowedCommands');
664 $this->error .= '<br>'.$langs->trans('ErrorCheckTheCommandInsideTheAdvancedOptions');
665 return -1;
666 }
667 }
668
669 // Parameters execution
670 $command = $cmddump;
671 $command = preg_replace('/(\$|%)/', '', $command); // We removed chars that can be used to inject vars that contains space inside path of command without seeing there is a space to bypass the escapeshellarg.
672 if (preg_match("/\s/", $command)) {
673 $command = escapeshellarg($command); // If there is spaces, we add quotes on command to be sure $command is only a program and not a program+parameters
674 }
675
676 //$param=escapeshellarg($dolibarr_main_db_name)." -h ".escapeshellarg($dolibarr_main_db_host)." -u ".escapeshellarg($dolibarr_main_db_user)." -p".escapeshellarg($dolibarr_main_db_pass);
677 //$param="-F c";
678 $param = "-F p";
679 $param .= " --no-tablespaces --inserts -h ".$dolibarr_main_db_host;
680 $param .= " -U ".$dolibarr_main_db_user;
681 if (!empty($dolibarr_main_db_port)) {
682 $param .= " -p ".$dolibarr_main_db_port;
683 }
684 if (GETPOST("sql_compat") && GETPOST("sql_compat") == 'ANSI') {
685 $param .= " --disable-dollar-quoting";
686 }
687 if (GETPOST("drop_database")) {
688 $param .= " -c -C";
689 }
690 if (GETPOST("sql_structure")) {
691 if (GETPOST("drop")) {
692 $param .= " --add-drop-table";
693 }
694 if (!GETPOST("sql_data")) {
695 $param .= " -s";
696 }
697 }
698 if (GETPOST("sql_data")) {
699 if (!GETPOST("sql_structure")) {
700 $param .= " -a";
701 }
702 if (GETPOST("showcolumns")) {
703 $param .= " -c";
704 }
705 }
706 $param .= ' -f "'.$outputfile.'"';
707 //if ($compression == 'none')
708 if ($compression == 'gz') {
709 $param .= ' -Z 9';
710 }
711 //if ($compression == 'bz')
712 $paramcrypted = $param;
713 $paramclear = $param;
714 /*if (!empty($dolibarr_main_db_pass))
715 {
716 $paramcrypted.=" -W".preg_replace('/./i','*',$dolibarr_main_db_pass);
717 $paramclear.=" -W".$dolibarr_main_db_pass;
718 }*/
719 $paramcrypted .= " -w ".$dolibarr_main_db_name;
720 $paramclear .= " -w ".$dolibarr_main_db_name;
721
722 $this->output = "";
723 $this->result = array("commandbackuplastdone" => "", "commandbackuptorun" => $command." ".$paramcrypted);
724 }
725
726 // Clean old files
727 if (!$errormsg && $keeplastnfiles > 0) {
728 $tmpfiles = dol_dir_list($conf->admin->dir_output.'/backup', 'files', 0, '', '(\.err|\.old|\.sav)$', 'date', SORT_DESC);
729 $i = 0;
730 if (is_array($tmpfiles)) {
731 foreach ($tmpfiles as $key => $val) {
732 $i++;
733 if ($i <= $keeplastnfiles) {
734 continue;
735 }
736 dol_delete_file($val['fullname'], 0, 0, 0, null, false, 0);
737 }
738 }
739 }
740
741 return ($errormsg ? -1 : 0);
742 }
743
744
745
759 public function executeCLI($command, $outputfile, $execmethod = 0, $redirectionfile = null, $noescapecommand = 0, $redirectionfileerr = null)
760 {
761 global $langs;
762
763 $result = 0;
764 $output = '';
765 $error = '';
766
767 if (empty($noescapecommand)) {
768 $command = escapeshellcmd($command);
769 }
770
771 if ($redirectionfile) {
772 $command .= " > ".dol_sanitizePathName($redirectionfile);
773 }
774
775 if ($redirectionfileerr && ($redirectionfileerr != $redirectionfile)) {
776 // If we ask a redirect of stderr on a given file not already used for stdout
777 $command .= " 2> ".dol_sanitizePathName($redirectionfileerr);
778 } else {
779 $command .= " 2>&1";
780 }
781
782 if (getDolGlobalString('MAIN_EXEC_USE_POPEN')) {
783 $execmethod = getDolGlobalString('MAIN_EXEC_USE_POPEN');
784 }
785 if (empty($execmethod)) {
786 $execmethod = 1;
787 }
788 //$execmethod=1;
789 dol_syslog("Utils::executeCLI execmethod=".$execmethod." command=".$command, LOG_DEBUG);
790 $output_arr = array();
791
792 if ($execmethod == 1) {
793 $retval = null;
794 exec($command, $output_arr, $retval); // @phan-suppress-current-line PhanPluginConstantVariableNull
795 $result = $retval;
796 if ($retval != 0) {
797 $langs->load("errors");
798 dol_syslog("Utils::executeCLI retval after exec=".$retval, LOG_ERR);
799 $error = 'Error '.$retval;
800 }
801 }
802 if ($execmethod == 2) { // With this method, there is no way to get the return code, only output
803 $handle = fopen($outputfile, 'w+b');
804 if ($handle) {
805 dol_syslog("Utils::executeCLI run command ".$command);
806 $handlein = popen($command, 'r');
807 while (!feof($handlein)) {
808 $read = fgets($handlein);
809 fwrite($handle, $read);
810 $output_arr[] = $read;
811 }
812 pclose($handlein);
813 fclose($handle);
814 }
815 dolChmod($outputfile);
816 }
817
818 // Update with result
819 if (is_array($output_arr) && count($output_arr) > 0) {
820 foreach ($output_arr as $val) {
821 $output .= $val.($execmethod == 2 ? '' : "\n");
822 }
823 }
824
825 dol_syslog("Utils::executeCLI result=".$result." output=".$output." error=".$error, LOG_DEBUG);
826
827 return array('result' => $result, 'output' => $output, 'error' => $error);
828 }
829
836 public function generateDoc($module)
837 {
838 global $conf, $langs, $user, $mysoc;
839 global $dirins;
840
841 $error = 0;
842
843 $modulelowercase = strtolower($module);
844 $now = dol_now();
845
846 // Dir for module
847 $dir = $dirins.'/'.$modulelowercase;
848 // Zip file to build
849 $FILENAMEDOC = '';
850
851 // Load module
852 dol_include_once($modulelowercase.'/core/modules/mod'.$module.'.class.php');
853 $class = 'mod'.$module;
854
855 $moduleobj = null;
856 if (class_exists($class)) {
857 try {
858 $moduleobj = new $class($this->db);
859 } catch (Exception $e) {
860 $error++;
861 dol_print_error(null, $e->getMessage());
862 }
863 } else {
864 $error++;
865 $langs->load("errors");
866 dol_print_error(null, $langs->trans("ErrorFailedToLoadModuleDescriptorForXXX", $module));
867 exit;
868 }
869
870 $arrayversion = $moduleobj === null ? array() : explode('.', $moduleobj->version, 3);
871 if (count($arrayversion)) {
872 $FILENAMEASCII = strtolower($module).'.asciidoc';
873 $FILENAMEDOC = strtolower($module).'.html';
874 $FILENAMEDOCPDF = strtolower($module).'.pdf';
875
876 $dirofmodule = dol_buildpath(strtolower($module), 0);
877 $dirofmoduledoc = dol_buildpath(strtolower($module), 0).'/doc';
878 $dirofmoduletmp = dol_buildpath(strtolower($module), 0).'/doc/temp';
879 $outputfiledoc = $dirofmoduledoc.'/'.$FILENAMEDOC;
880 if ($dirofmoduledoc) {
881 if (!dol_is_dir($dirofmoduledoc)) {
882 dol_mkdir($dirofmoduledoc);
883 }
884 if (!dol_is_dir($dirofmoduletmp)) {
885 dol_mkdir($dirofmoduletmp);
886 }
887 if (!is_writable($dirofmoduletmp)) {
888 $this->error = 'Dir '.$dirofmoduletmp.' does not exists or is not writable';
889 return -1;
890 }
891
892 if (!getDolGlobalString('MODULEBUILDER_ASCIIDOCTOR') && !getDolGlobalString('MODULEBUILDER_ASCIIDOCTORPDF')) {
893 $this->error = 'Setup of module ModuleBuilder not complete';
894 return -1;
895 }
896
897 // Copy some files into temp directory, so instruction include::ChangeLog.md[] will works inside the asciidoc file.
898 dol_copy($dirofmodule.'/README.md', $dirofmoduletmp.'/README.md', '0', 1);
899 dol_copy($dirofmodule.'/ChangeLog.md', $dirofmoduletmp.'/ChangeLog.md', '0', 1);
900
901 // Replace into README.md and ChangeLog.md (in case they are included into documentation with tag __README__ or __CHANGELOG__)
902 $arrayreplacement = array();
903 $arrayreplacement['/^#\s.*/m'] = ''; // Remove first level of title into .md files
904 $arrayreplacement['/^#/m'] = '##'; // Add on # to increase level
905
906 dolReplaceInFile($dirofmoduletmp.'/README.md', $arrayreplacement, '', '0', 0, 1);
907 dolReplaceInFile($dirofmoduletmp.'/ChangeLog.md', $arrayreplacement, '', '0', 0, 1);
908
909
910 $destfile = $dirofmoduletmp.'/'.$FILENAMEASCII;
911
912 $fhandle = fopen($destfile, 'w+');
913 if ($fhandle) {
914 $specs = dol_dir_list(dol_buildpath(strtolower($module).'/doc', 0), 'files', 1, '(\.md|\.asciidoc)$', array('\/temp\/'));
915
916 $i = 0;
917 foreach ($specs as $spec) {
918 if (preg_match('/notindoc/', $spec['relativename'])) {
919 continue; // Discard file
920 }
921 if (preg_match('/example/', $spec['relativename'])) {
922 continue; // Discard file
923 }
924 if (preg_match('/disabled/', $spec['relativename'])) {
925 continue; // Discard file
926 }
927
928 $pathtofile = strtolower($module).'/doc/'.$spec['relativename'];
929 $format = 'asciidoc';
930 if (preg_match('/\.md$/i', $spec['name'])) {
931 $format = 'markdown';
932 }
933
934 $filecursor = @file_get_contents($spec['fullname']);
935 if ($filecursor) {
936 fwrite($fhandle, ($i ? "\n<<<\n\n" : "").$filecursor."\n");
937 } else {
938 $this->error = 'Failed to concat content of file '.$spec['fullname'];
939 return -1;
940 }
941
942 $i++;
943 }
944
945 fclose($fhandle);
946
947 $contentreadme = file_get_contents($dirofmoduletmp.'/README.md');
948 $contentchangelog = file_get_contents($dirofmoduletmp.'/ChangeLog.md');
949
950 include DOL_DOCUMENT_ROOT.'/core/lib/parsemd.lib.php';
951
952 //var_dump($phpfileval['fullname']);
953 $arrayreplacement = array(
954 'mymodule' => strtolower($module),
955 'MyModule' => $module,
956 'MYMODULE' => strtoupper($module),
957 'My module' => $module,
958 'my module' => $module,
959 'Mon module' => $module,
960 'mon module' => $module,
961 'htdocs/modulebuilder/template' => strtolower($module),
962 '__MYCOMPANY_NAME__' => $mysoc->name,
963 '__KEYWORDS__' => $module,
964 '__USER_FULLNAME__' => $user->getFullName($langs),
965 '__USER_EMAIL__' => $user->email,
966 '__YYYY-MM-DD__' => dol_print_date($now, 'dayrfc'),
967 '---Put here your own copyright and developer email---' => dol_print_date($now, 'dayrfc').' '.$user->getFullName($langs).($user->email ? ' <'.$user->email.'>' : ''),
968 '__DATA_SPECIFICATION__' => 'Not yet available',
969 '__README__' => dolMd2Asciidoc($contentreadme),
970 '__CHANGELOG__' => dolMd2Asciidoc($contentchangelog),
971 );
972
973 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
974 dolReplaceInFile($destfile, $arrayreplacement);
975 }
976
977 // Launch doc generation
978 $currentdir = getcwd();
979 chdir($dirofmodule);
980
981 require_once DOL_DOCUMENT_ROOT.'/core/class/utils.class.php';
982 $utils = new Utils($this->db);
983
984 // Build HTML doc
985 $command = getDolGlobalString('MODULEBUILDER_ASCIIDOCTOR') . ' '.$destfile.' -n -o '.$dirofmoduledoc.'/'.$FILENAMEDOC;
986 $outfile = $dirofmoduletmp.'/out.tmp';
987
988 $resarray = $utils->executeCLI($command, $outfile);
989 if ($resarray['result'] != '0') {
990 $this->error = $resarray['error'].' '.$resarray['output'];
991 $this->errors[] = $this->error;
992 }
993 $result = ($resarray['result'] == 0) ? 1 : 0;
994 if ($result < 0 && empty($this->errors)) {
995 $this->error = $langs->trans("ErrorFailToGenerateFile", $FILENAMEDOC);
996 $this->errors[] = $this->error;
997 }
998
999 // Build PDF doc
1000 $command = getDolGlobalString('MODULEBUILDER_ASCIIDOCTORPDF') . ' '.$destfile.' -n -o '.$dirofmoduledoc.'/'.$FILENAMEDOCPDF;
1001 $outfile = $dirofmoduletmp.'/outpdf.tmp';
1002 $resarray = $utils->executeCLI($command, $outfile);
1003 if ($resarray['result'] != '0') {
1004 $this->error = $resarray['error'].' '.$resarray['output'];
1005 $this->errors[] = $this->error;
1006 }
1007 $result = ($resarray['result'] == 0) ? 1 : 0;
1008 if ($result < 0 && empty($this->errors)) {
1009 $this->error = $langs->trans("ErrorFailToGenerateFile", $FILENAMEDOCPDF);
1010 $this->errors[] = $this->error;
1011 }
1012
1013 chdir($currentdir);
1014 } else {
1015 $result = 0;
1016 }
1017
1018 if ($result > 0) {
1019 return 1;
1020 } else {
1021 $error++;
1022 }
1023 } else {
1024 $error++;
1025 $langs->load("errors");
1026 $this->error = $langs->trans("ErrorCheckVersionIsDefined");
1027 }
1028
1029 return -1;
1030 }
1031
1039 public function compressSyslogs()
1040 {
1041 global $conf;
1042
1043 if (empty($conf->loghandlers['mod_syslog_file'])) { // File Syslog disabled
1044 return 0;
1045 }
1046
1047 if (!function_exists('gzopen')) {
1048 $this->error = 'Support for gzopen not available in this PHP';
1049 return -1;
1050 }
1051
1052 require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
1053
1054 $nbSaves = intval(getDolGlobalString('SYSLOG_FILE_SAVES', 10));
1055
1056 if (!getDolGlobalString('SYSLOG_FILE')) {
1057 $mainlogdir = DOL_DATA_ROOT;
1058 $mainlog = 'dolibarr.log';
1059 } else {
1060 $mainlogfull = str_replace('DOL_DATA_ROOT', DOL_DATA_ROOT, $conf->global->SYSLOG_FILE);
1061 $mainlogdir = dirname($mainlogfull);
1062 $mainlog = basename($mainlogfull);
1063 }
1064
1065 $tabfiles = dol_dir_list(DOL_DATA_ROOT, 'files', 0, '^(dolibarr_.+|odt2pdf)\.log$'); // Also handle other log files like dolibarr_install.log
1066 $tabfiles[] = array('name' => $mainlog, 'path' => $mainlogdir);
1067
1068 foreach ($tabfiles as $file) {
1069 $logname = $file['name'];
1070 $logpath = $file['path'];
1071
1072 if (dol_is_file($logpath.'/'.$logname) && dol_filesize($logpath.'/'.$logname) > 0) { // If log file exists and is not empty
1073 // Handle already compressed files to rename them and add +1
1074
1075 $filter = '^'.preg_quote($logname, '/').'\.([0-9]+)\.gz$';
1076
1077 $gzfilestmp = dol_dir_list($logpath, 'files', 0, $filter);
1078 $gzfiles = array();
1079
1080 foreach ($gzfilestmp as $gzfile) {
1081 $tabmatches = array();
1082 preg_match('/'.$filter.'/i', $gzfile['name'], $tabmatches);
1083
1084 $numsave = intval($tabmatches[1]);
1085
1086 $gzfiles[$numsave] = $gzfile;
1087 }
1088
1089 krsort($gzfiles, SORT_NUMERIC);
1090
1091 foreach ($gzfiles as $numsave => $dummy) {
1092 if (dol_is_file($logpath.'/'.$logname.'.'.($numsave + 1).'.gz')) {
1093 return -2;
1094 }
1095
1096 if ($numsave >= $nbSaves) {
1097 dol_delete_file($logpath.'/'.$logname.'.'.$numsave.'.gz', 0, 0, 0, null, false, 0);
1098 } else {
1099 dol_move($logpath.'/'.$logname.'.'.$numsave.'.gz', $logpath.'/'.$logname.'.'.($numsave + 1).'.gz', '0', 1, 0, 0);
1100 }
1101 }
1102
1103 // Compress current file and recreate it
1104
1105 if ($nbSaves > 0) { // If $nbSaves is 1, we keep 1 archive .gz file, If 2, we keep 2 .gz files
1106 $gzfilehandle = gzopen($logpath.'/'.$logname.'.1.gz', 'wb9');
1107
1108 if (empty($gzfilehandle)) {
1109 $this->error = 'Failted to open file '.$logpath.'/'.$logname.'.1.gz';
1110 return -3;
1111 }
1112
1113 $sourcehandle = fopen($logpath.'/'.$logname, 'r');
1114
1115 if (empty($sourcehandle)) {
1116 $this->error = 'Failed to open file '.$logpath.'/'.$logname;
1117 return -4;
1118 }
1119
1120 while (!feof($sourcehandle)) {
1121 gzwrite($gzfilehandle, fread($sourcehandle, 512 * 1024)); // Read 512 kB at a time
1122 }
1123
1124 fclose($sourcehandle);
1125 gzclose($gzfilehandle);
1126
1127 dolChmod($logpath.'/'.$logname.'.1.gz');
1128 }
1129
1130 dol_delete_file($logpath.'/'.$logname, 0, 0, 0, null, false, 0);
1131
1132 // Create empty file
1133 $newlog = fopen($logpath.'/'.$logname, 'a+');
1134 fclose($newlog);
1135
1136 //var_dump($logpath.'/'.$logname." - ".octdec(empty($conf->global->MAIN_UMASK)?'0664':$conf->global->MAIN_UMASK));
1137 dolChmod($logpath.'/'.$logname);
1138 }
1139 }
1140
1141 $this->output = 'Archive log files (keeping last SYSLOG_FILE_SAVES='.$nbSaves.' files) done.';
1142 return 0;
1143 }
1144
1155 public function backupTables($outputfile, $tables = '*')
1156 {
1157 global $db, $langs;
1158 global $errormsg;
1159
1160 // Set to UTF-8
1161 if (is_a($db, 'DoliDBMysqli')) {
1163 $db->db->set_charset('utf8');
1164 } else {
1166 $db->query('SET NAMES utf8');
1167 $db->query('SET CHARACTER SET utf8');
1168 }
1169
1170 //get all of the tables
1171 if ($tables == '*') {
1172 $tables = array();
1173 $result = $db->query('SHOW FULL TABLES WHERE Table_type = \'BASE TABLE\'');
1174 while ($row = $db->fetch_row($result)) {
1175 $tables[] = $row[0];
1176 }
1177 } else {
1178 $tables = is_array($tables) ? $tables : explode(',', $tables);
1179 }
1180
1181 //cycle through
1182 $handle = fopen($outputfile, 'w+');
1183 if (fwrite($handle, '') === false) {
1184 $langs->load("errors");
1185 dol_syslog("Failed to open file ".$outputfile, LOG_ERR);
1186 $errormsg = $langs->trans("ErrorFailedToWriteInDir");
1187 return -1;
1188 }
1189
1190 // Print headers and global mysql config vars
1191 $sqlhead = '';
1192 $sqlhead .= "-- ".$db::LABEL." dump via php with Dolibarr ".DOL_VERSION."
1193--
1194-- Host: ".$db->db->host_info." Database: ".$db->database_name."
1195-- ------------------------------------------------------
1196-- Server version ".$db->db->server_info."
1197
1198;
1199;
1200;
1201;
1202;
1203;
1204;
1205;
1206;
1207;
1208
1209";
1210
1211 if (GETPOST("nobin_disable_fk")) {
1212 $sqlhead .= "SET FOREIGN_KEY_CHECKS=0;\n";
1213 }
1214 //$sqlhead .= "SET SQL_MODE=\"NO_AUTO_VALUE_ON_ZERO\";\n";
1215 if (GETPOST("nobin_use_transaction")) {
1216 $sqlhead .= "SET AUTOCOMMIT=0;\nSTART TRANSACTION;\n";
1217 }
1218
1219 fwrite($handle, $sqlhead);
1220
1221 $ignore = '';
1222 if (GETPOST("nobin_sql_ignore")) {
1223 $ignore = 'IGNORE ';
1224 }
1225 $delayed = '';
1226 if (GETPOST("nobin_delayed")) {
1227 $delayed = 'DELAYED ';
1228 }
1229
1230 // Process each table and print their definition + their datas
1231 foreach ($tables as $table) {
1232 // Saving the table structure
1233 fwrite($handle, "\n--\n-- Table structure for table `".$table."`\n--\n");
1234
1235 if (GETPOST("nobin_drop")) {
1236 fwrite($handle, "DROP TABLE IF EXISTS `".$table."`;\n"); // Dropping table if exists prior to re create it
1237 }
1238 fwrite($handle, "/*!40101 SET @saved_cs_client = @@character_set_client */;\n");
1239 fwrite($handle, "/*!40101 SET character_set_client = utf8 */;\n");
1240 $resqldrop = $db->query('SHOW CREATE TABLE '.$table);
1241 $row2 = $db->fetch_row($resqldrop);
1242 if (empty($row2[1])) {
1243 fwrite($handle, "\n-- WARNING: Show create table ".$table." return empty string when it should not.\n");
1244 } else {
1245 fwrite($handle, $row2[1].";\n");
1246 //fwrite($handle,"/*!40101 SET character_set_client = @saved_cs_client */;\n\n");
1247
1248 // Dumping the data (locking the table and disabling the keys check while doing the process)
1249 fwrite($handle, "\n--\n-- Dumping data for table `".$table."`\n--\n");
1250 if (!GETPOST("nobin_nolocks")) {
1251 fwrite($handle, "LOCK TABLES `".$table."` WRITE;\n"); // Lock the table before inserting data (when the data will be imported back)
1252 }
1253 if (GETPOST("nobin_disable_fk")) {
1254 fwrite($handle, "ALTER TABLE `".$table."` DISABLE KEYS;\n");
1255 } else {
1256 fwrite($handle, "/*!40000 ALTER TABLE `".$table."` DISABLE KEYS */;\n");
1257 }
1258
1259 $sql = "SELECT * FROM ".$table; // Here SELECT * is allowed because we don't have definition of columns to take
1260 $result = $db->query($sql);
1261 while ($row = $db->fetch_row($result)) {
1262 // For each row of data we print a line of INSERT
1263 fwrite($handle, "INSERT ".$delayed.$ignore."INTO ".$table." VALUES (");
1264 $columns = count($row);
1265 for ($j = 0; $j < $columns; $j++) {
1266 // Processing each columns of the row to ensure that we correctly save the value (eg: add quotes for string - in fact we add quotes for everything, it's easier)
1267 if ($row[$j] == null && !is_string($row[$j])) {
1268 // IMPORTANT: if the field is NULL we set it NULL
1269 $row[$j] = 'NULL';
1270 } elseif (is_string($row[$j]) && $row[$j] == '') {
1271 // if it's an empty string, we set it as an empty string
1272 $row[$j] = "''";
1273 } elseif (is_numeric($row[$j]) && !strcmp((string) $row[$j], (string) ((float) $row[$j] + 0))) { // test if it's a numeric type and the numeric version ($nb+0) == string version (eg: if we have 01, it's probably not a number but rather a string, else it would not have any leading 0)
1274 // if it's a number, we return it as-is
1275 // $row[$j] = $row[$j];
1276 } else { // else for all other cases we escape the value and put quotes around
1277 $row[$j] = addslashes($row[$j]);
1278 $row[$j] = preg_replace("#\n#", "\\n", $row[$j]);
1279 $row[$j] = "'".$row[$j]."'";
1280 }
1281 }
1282 fwrite($handle, implode(',', $row).");\n");
1283 }
1284 if (GETPOST("nobin_disable_fk")) {
1285 fwrite($handle, "ALTER TABLE `".$table."` ENABLE KEYS;\n"); // Enabling back the keys/index checking
1286 }
1287 if (!GETPOST("nobin_nolocks")) {
1288 fwrite($handle, "UNLOCK TABLES;\n"); // Unlocking the table
1289 }
1290 fwrite($handle, "\n\n\n");
1291 }
1292 }
1293
1294 /* Backup Procedure structure*/
1295 /*
1296 $result = $db->query('SHOW PROCEDURE STATUS');
1297 if ($db->num_rows($result) > 0)
1298 {
1299 while ($row = $db->fetch_row($result)) { $procedures[] = $row[1]; }
1300 foreach($procedures as $proc)
1301 {
1302 fwrite($handle,"DELIMITER $$\n\n");
1303 fwrite($handle,"DROP PROCEDURE IF EXISTS '$name'.'$proc'$$\n");
1304 $resqlcreateproc=$db->query("SHOW CREATE PROCEDURE '$proc'");
1305 $row2 = $db->fetch_row($resqlcreateproc);
1306 fwrite($handle,"\n".$row2[2]."$$\n\n");
1307 fwrite($handle,"DELIMITER ;\n\n");
1308 }
1309 }
1310 */
1311 /* Backup Procedure structure*/
1312
1313 // Write the footer (restore the previous database settings)
1314 $sqlfooter = "\n\n";
1315 if (GETPOST("nobin_use_transaction")) {
1316 $sqlfooter .= "COMMIT;\n";
1317 }
1318 if (GETPOST("nobin_disable_fk")) {
1319 $sqlfooter .= "SET FOREIGN_KEY_CHECKS=1;\n";
1320 }
1321 $sqlfooter .= "\n\n-- Dump completed on ".date('Y-m-d G-i-s');
1322 fwrite($handle, $sqlfooter);
1323
1324 fclose($handle);
1325
1326 return 1;
1327 }
1328
1342 public function sendBackup($sendto = '', $from = '', $subject = '', $message = '', $filename = '', $filter = '', $sizelimit = 100000000)
1343 {
1344 global $conf, $langs;
1346
1347 $filepath = '';
1348 $filesize = -1;
1349 $output = '';
1350 $error = 0;
1351 $mimetype = '';
1352
1353 if (!empty($from)) {
1354 $from = dol_escape_htmltag($from);
1355 } elseif (getDolGlobalString('MAIN_MAIL_EMAIL_FROM')) {
1356 $from = dol_escape_htmltag(getDolGlobalString('MAIN_MAIL_EMAIL_FROM'));
1357 } else {
1358 $error++;
1359 }
1360
1361 if (!empty($sendto)) {
1362 $sendto = dol_escape_htmltag($sendto);
1363 } elseif (getDolGlobalString('MAIN_INFO_SOCIETE_MAIL')) {
1364 $sendto = dol_escape_htmltag(getDolGlobalString('MAIN_INFO_SOCIETE_MAIL'));
1365 } else {
1366 $error++;
1367 }
1368
1369 if (!empty($subject)) {
1370 $subject = dol_escape_htmltag($subject);
1371 } else {
1372 $subject = dol_escape_htmltag($langs->trans('MakeSendLocalDatabaseDumpShort'));
1373 }
1374
1375 if (empty($message)) {
1376 $message = dol_escape_htmltag($langs->trans('MakeSendLocalDatabaseDumpShort'));
1377 }
1378
1379 $tmpfiles = array();
1380 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1381 if ($filename) {
1382 if (dol_is_file($conf->admin->dir_output.'/backup/'.$filename)) {
1383 $tmpfiles = dol_most_recent_file($conf->admin->dir_output.'/backup', $filename);
1384 }
1385 } else {
1386 $tmpfiles = dol_most_recent_file($conf->admin->dir_output.'/backup', $filter);
1387 }
1388 if ($tmpfiles && is_array($tmpfiles)) {
1389 foreach ($tmpfiles as $key => $val) {
1390 if ($key == 'fullname') {
1391 $filepath = array($val);
1392 $filesize = dol_filesize($val);
1393 }
1394 if ($key == 'type') {
1395 $mimetype = array($val);
1396 }
1397 if ($key == 'relativename') {
1398 $filename = array($val);
1399 }
1400 }
1401 }
1402
1403 if ($filepath) {
1404 if ($filesize > $sizelimit) {
1405 $message .= '<br>'.$langs->trans("BackupIsTooLargeSend");
1406 $documenturl = $dolibarr_main_url_root.'/document.php?modulepart=systemtools&atachement=1&file=backup/'.urlencode($filename[0]);
1407 $message .= '<br><a href='.$documenturl.'>Download link</a>';
1408 $filepath = '';
1409 $mimetype = '';
1410 $filename = '';
1411 }
1412 } else {
1413 $output = 'No backup file found';
1414 $error++;
1415 }
1416
1417 $mailfile = null;
1418 if (!$error) {
1419 include_once DOL_DOCUMENT_ROOT . '/core/class/CMailFile.class.php';
1420 $mailfile = new CMailFile($subject, $sendto, $from, $message, $filepath, $mimetype, $filename, '', '', 0, 1);
1421 // $mailfile = new CMailFile($subject, $sendto, $from, $message, $filepath, $mimetype, $filename, '', '', 0, 1);
1422 if ($mailfile->error) {
1423 $error++;
1424 $output = $mailfile->error;
1425 }
1426 }
1427
1428 $result = false;
1429 $output = '';
1430 if (!$error && $mailfile !== null) {
1431 $result = $mailfile->sendfile();
1432 if (!$result) {
1433 $error++;
1434 $output = $mailfile->error;
1435 }
1436 }
1437
1438 dol_syslog(__METHOD__, LOG_DEBUG);
1439
1440 $this->error = "Error sending backup file ".((string) $error);
1441 $this->output = $output;
1442
1443 if ($result) {
1444 return 0;
1445 } else {
1446 return -1;
1447 }
1448 }
1449
1457 public function cleanUnfinishedCronjob()
1458 {
1459 global $db, $user;
1460 dol_syslog("Utils::cleanUnfinishedCronjob Starting cleaning");
1461
1462 // Import Cronjob class if not present
1463 require_once DOL_DOCUMENT_ROOT . '/cron/class/cronjob.class.php';
1464
1465 // Get this job object
1466 $this_job = new Cronjob($db);
1467 $this_job->fetch(-1, 'Utils', 'cleanUnfinishedCronjob');
1468 if (empty($this_job->id) || !empty($this_job->error)) {
1469 dol_syslog("Utils::cleanUnfinishedCronjob Unable to fetch himself: ".$this_job->error, LOG_ERR);
1470 return -1;
1471 }
1472
1473 // Set this job processing to 0 to avoid being locked by his processing state
1474 $this_job->processing = 0;
1475 if ($this_job->update($user) < 0) {
1476 dol_syslog("Utils::cleanUnfinishedCronjob Unable to update himself: ".implode(', ', $this_job->errors), LOG_ERR);
1477 return -1;
1478 }
1479
1480 $cron_job = new Cronjob($db);
1481 $cron_job->fetchAll('DESC', 't.rowid', 100, 0, 1, [], 1); // Fetch jobs that are currently running
1482
1483 // Iterate over all jobs in processing (this can't be this job since his state is set to 0 before)
1484 foreach ($cron_job->lines as $job_line) {
1485 // Avoid job with no PID
1486 if (empty($job_line->pid)) {
1487 dol_syslog("Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id." don't have a PID", LOG_DEBUG);
1488 continue;
1489 }
1490
1491 $job = new Cronjob($db);
1492 $job->fetch($job_line->id);
1493 if (empty($job->id) || !empty($job->error)) {
1494 dol_syslog("Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id." can't be fetch: ".$job->error, LOG_ERR);
1495 continue;
1496 }
1497
1498 // Calling posix_kill with the 0 kill signal will return true if the process is running, false otherwise.
1499 if (! posix_kill($job->pid, 0)) {
1500 // Clean processing and pid values
1501 $job->processing = 0;
1502 $job->pid = null;
1503
1504 // Set last result as an error and add the reason on the last output
1505 $job->lastresult = strval(-1);
1506 $job->lastoutput = 'Job killed by job cleanUnfinishedCronjob';
1507
1508 if ($job->update($user) < 0) {
1509 dol_syslog("Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id." can't be updated: ".implode(', ', $job->errors), LOG_ERR);
1510 continue;
1511 }
1512 dol_syslog("Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id." cleaned");
1513 }
1514 }
1515
1516 dol_syslog("Utils::cleanUnfinishedCronjob Cleaning completed");
1517 return 0;
1518 }
1519}
global $dolibarr_main_url_root
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Cron Job class.
Class to manage ECM directories.
Class to manage utility methods.
executeCLI($command, $outputfile, $execmethod=0, $redirectionfile=null, $noescapecommand=0, $redirectionfileerr=null)
Execute a CLI command.
__construct($db)
Constructor.
generateDoc($module)
Generate documentation of a Module.
compressSyslogs()
This saves syslog files and compresses older ones.
sendBackup($sendto='', $from='', $subject='', $message='', $filename='', $filter='', $sizelimit=100000000)
Make a send last backup of database or fil in param CAN BE A CRON TASK.
dumpDatabase($compression='none', $type='auto', $usedefault=1, $file='auto', $keeplastnfiles=0, $execmethod=0, $lowmemorydump=0)
Make a backup of database CAN BE A CRON TASK.
cleanUnfinishedCronjob()
Clean unfinished cronjob in processing when pid is no longer present in the system CAN BE A CRON TASK...
purgeFiles($choices='tempfilesold+logfiles', $nbsecondsold=86400)
Purge files into directory of data files.
global $mysoc
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
dol_move($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array(), $entity=null)
Move a file into another name.
dol_filesize($pathoffile)
Return size of a file.
dol_copy($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=0)
Copy a file to another file.
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_is_file($pathoffile)
Return if path is a file.
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:64
dol_most_recent_file($dir, $regexfilter='', $excludefilter=array('(\.meta|_preview.*\.png) $', '^\.'), $nohook=0, $mode=0)
Return file(s) into a directory (by default most recent)
dol_is_dir($folder)
Test if filename is a directory.
dolReplaceInFile($srcfile, $arrayreplacement, $destfile='', $newmask='0', $indexdatabase=0, $arrayreplacementisregex=0)
Make replacement of strings into a file.
dol_now($mode='gmt')
Return date for now.
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='', $keepspaces=0)
Clean a string from all punctuation characters to use it as a ref or login.
dol_sanitizePathName($str, $newstr='_', $unaccent=0, $allowdash=0)
Clean a string to use it as a path name.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
dolChmod($filepath, $newmask='')
Change mod of a file.
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
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.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
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...
$moduleobj
Definition index.php:3492
dolMd2Asciidoc($content, $parser='dolibarr', $replaceimagepath=null)
Function to parse MD content into ASCIIDOC.