dolibarr 24.0.0-beta
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, $dolibarr_main_data_root;
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
253 $langs->load("admin");
254
255 dol_syslog("Utils::dumpDatabase type=".$type." compression=".$compression." file=".$file, LOG_DEBUG);
256 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
257
258 // Clean data
259 $file = dol_sanitizeFileName($file);
260
261 // Check compression parameter
262 if (!in_array($compression, array('none', 'gz', 'bz', 'zip', 'zstd'))) {
263 $langs->load("errors");
264 $this->error = $langs->transnoentitiesnoconv("ErrorBadValueForParameter", $compression, "Compression");
265 return -1;
266 }
267
268 // Check type parameter
269 if ($type == 'auto') {
270 $type = $this->db->type;
271 }
272 if (!in_array($type, array('postgresql', 'pgsql', 'mysql', 'mysqli', 'mysqlnobin'))) {
273 $langs->load("errors");
274 $this->error = $langs->transnoentitiesnoconv("ErrorBadValueForParameter", $type, "Basetype");
275 return -1;
276 }
277
278 // Check file parameter
279 if ($file == 'auto') {
280 $prefix = 'dump';
281 $ext = 'sql';
282 if (in_array($type, array('mysql', 'mysqli'))) {
283 $prefix = 'mysqldump';
284 }
285 //if ($label == 'PostgreSQL') { $prefix='pg_dump'; $ext='dump'; }
286 if (in_array($type, array('pgsql'))) {
287 $prefix = 'pg_dump';
288 }
289 $file = $prefix.'_'.$dolibarr_main_db_name.'_'.dol_sanitizeFileName(DOL_VERSION).'_'.dol_print_date(dol_now('gmt'), "dayhourlogsmall", 'tzuser').'.'.$ext;
290 }
291
292 $outputdir = $conf->admin->dir_output.'/backup';
293 $result = dol_mkdir($outputdir);
294 $errormsg = '';
295
296 // MYSQL
297 if ($type == 'mysql' || $type == 'mysqli') {
298 if (!getDolGlobalString('SYSTEMTOOLS_MYSQLDUMP')) {
299 $cmddump = $db->getPathOfDump();
300 } else {
301 $cmddump = getDolGlobalString('SYSTEMTOOLS_MYSQLDUMP');
302 }
303 if (empty($cmddump)) {
304 $this->error = "Failed to detect command to use for mysqldump. Try a manual backup before to set path of command.";
305 return -1;
306 }
307
308 $outputfile = $outputdir.'/'.$file;
309 // for compression format, we add extension
310 $compression = $compression ? $compression : 'none';
311 if ($compression == 'gz') {
312 $outputfile .= '.gz';
313 } elseif ($compression == 'bz') {
314 $outputfile .= '.bz2';
315 } elseif ($compression == 'zstd') {
316 $outputfile .= '.zst';
317 }
318 $outputerror = $outputfile.'.err';
319 dol_mkdir($conf->admin->dir_output.'/backup');
320
321 // Parameters execution
322 $command = $cmddump;
323 $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.
324 if (preg_match("/\s/", $command)) {
325 $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
326 }
327
328 //$param=escapeshellarg($dolibarr_main_db_name)." -h ".escapeshellarg($dolibarr_main_db_host)." -u ".escapeshellarg($dolibarr_main_db_user)." -p".escapeshellarg($dolibarr_main_db_pass);
329 $param = $dolibarr_main_db_name." -h ".$dolibarr_main_db_host;
330 $param .= " -u ".$dolibarr_main_db_user;
331 if (!empty($dolibarr_main_db_port)) {
332 $param .= " -P ".$dolibarr_main_db_port." --protocol=tcp";
333 }
334 if (GETPOST("use_transaction", "alpha")) {
335 $param .= " --single-transaction";
336 }
337 if (GETPOST("disable_fk", "alpha") || $usedefault) {
338 $param .= " -K";
339 }
340 if (GETPOST("sql_compat", "alpha") && GETPOST("sql_compat", "alpha") != 'NONE') {
341 $param .= " --compatible=".escapeshellarg(GETPOST("sql_compat", "alpha"));
342 }
343 if (GETPOST("drop_database", "alpha")) {
344 $param .= " --add-drop-database";
345 }
346 if (GETPOST("use_mysql_quick_param", "alpha")) {
347 $param .= " --quick";
348 }
349 if (GETPOST("use_force", "alpha")) {
350 $param .= " -f";
351 }
352 if (GETPOST("sql_structure", "alpha") || $usedefault) {
353 if (GETPOST("drop", "alpha") || $usedefault) {
354 $param .= " --add-drop-table=TRUE";
355 } else {
356 $param .= " --add-drop-table=FALSE";
357 }
358 } else {
359 $param .= " -t";
360 }
361 if (GETPOST("disable-add-locks", "alpha")) {
362 $param .= " --add-locks=FALSE";
363 }
364 if (GETPOST("sql_data", "alpha") || $usedefault) {
365 $param .= " --tables";
366 if (GETPOST("showcolumns", "alpha") || $usedefault) {
367 $param .= " -c";
368 }
369 if (GETPOST("extended_ins", "alpha") || $usedefault) {
370 $param .= " -e";
371 } else {
372 $param .= " --skip-extended-insert";
373 }
374 if (GETPOST("delayed", "alpha")) {
375 $param .= " --delayed-insert";
376 }
377 if (GETPOST("sql_ignore", "alpha")) {
378 $param .= " --insert-ignore";
379 }
380 if (GETPOST("hexforbinary", "alpha") || $usedefault) {
381 $param .= " --hex-blob";
382 }
383 } else {
384 $param .= " -d"; // No row information (no data)
385 }
386 if ($dolibarr_main_db_character_set == 'utf8mb4') {
387 // We save output into utf8mb4 charset
388 $param .= " --default-character-set=utf8mb4 --no-tablespaces";
389 } else {
390 $param .= " --default-character-set=utf8 --no-tablespaces"; // We always save output into utf8 charset
391 }
392 $paramcrypted = $param;
393 $paramclear = $param;
394 if (!empty($dolibarr_main_db_pass)) {
395 $paramcrypted .= ' -p"'.preg_replace('/./i', '*', $dolibarr_main_db_pass).'"';
396 $paramclear .= ' -p"'.str_replace(array('"', '`', '$'), array('\"', '\`', '\$'), $dolibarr_main_db_pass).'"';
397 }
398
399 $handle = '';
400
401 // Start call method to execute dump
402 $fullcommandcrypted = $command." ".$paramcrypted." 2>&1";
403 $fullcommandclear = $command." ".$paramclear." 2>&1";
404 if (!$lowmemorydump) {
405 if ($compression == 'none') {
406 $handle = fopen($outputfile, 'w');
407 } elseif ($compression == 'gz') {
408 $handle = gzopen($outputfile, 'w');
409 } elseif ($compression == 'bz') {
410 $handle = bzopen($outputfile, 'w');
411 } elseif ($compression == 'zstd') {
412 $handle = fopen($outputfile, 'w');
413 }
414 } else {
415 // TODO Add a pipe into script to decrypt dolCrypted values
416
417 if ($compression == 'none') {
418 $fullcommandclear .= ' | grep -v "Warning: Using a password on the command line interface can be insecure." > "'.dol_sanitizePathName($outputfile).'"';
419 $fullcommandcrypted .= ' | grep -v "Warning: Using a password on the command line interface can be insecure." > "'.dol_sanitizePathName($outputfile).'"';
420 $handle = 1;
421 } elseif ($compression == 'gz') {
422 $fullcommandclear .= ' | grep -v "Warning: Using a password on the command line interface can be insecure." | gzip > "'.dol_sanitizePathName($outputfile).'"';
423 $fullcommandcrypted .= ' | grep -v "Warning: Using a password on the command line interface can be insecure." | gzip > "'.dol_sanitizePathName($outputfile).'"';
424 $paramcrypted .= ' | grep -v "Warning: Using a password on the command line interface can be insecure." | gzip';
425 $handle = 1;
426 } elseif ($compression == 'bz') {
427 $fullcommandclear .= ' | grep -v "Warning: Using a password on the command line interface can be insecure." | bzip2 > "'.dol_sanitizePathName($outputfile).'"';
428 $fullcommandcrypted .= ' | grep -v "Warning: Using a password on the command line interface can be insecure." | bzip2 > "'.dol_sanitizePathName($outputfile).'"';
429 $paramcrypted .= ' | grep -v "Warning: Using a password on the command line interface can be insecure." | bzip2';
430 $handle = 1;
431 } elseif ($compression == 'zstd') {
432 $fullcommandclear .= ' | grep -v "Warning: Using a password on the command line interface can be insecure." | zstd > "'.dol_sanitizePathName($outputfile).'"';
433 $fullcommandcrypted .= ' | grep -v "Warning: Using a password on the command line interface can be insecure." | zstd > "'.dol_sanitizePathName($outputfile).'"';
434 $paramcrypted .= ' | grep -v "Warning: Using a password on the command line interface can be insecure." | zstd';
435 $handle = 1;
436 }
437 }
438
439 $ok = 0;
440 if ($handle) {
441 if (getDolGlobalString('MAIN_EXEC_USE_POPEN')) {
442 $execmethod = getDolGlobalString('MAIN_EXEC_USE_POPEN');
443 }
444 if (empty($execmethod)) {
445 $execmethod = 1;
446 }
447
448 dol_syslog("Utils::dumpDatabase execmethod=".$execmethod.", lowmemorydump=".$lowmemorydump.", command=".$fullcommandcrypted, LOG_INFO);
449
450
451 /* If value has been forced with a php_admin_value, this has no effect. Example of value: '512M' */
452 $MemoryLimit = getDolGlobalString('MAIN_MEMORY_LIMIT_DUMP');
453 if (!empty($MemoryLimit)) {
454 @ini_set('memory_limit', $MemoryLimit);
455 }
456
457
458 if ($execmethod == 1) {
459 $output_arr = array();
460 $retval = null;
461
462 exec($fullcommandclear, $output_arr, $retval); // @phan-suppress-current-line PhanPluginConstantVariableNull
463 // TODO Replace this exec with Utils->executeCLI() function.
464 // We must check that the case for $lowmemorydump works too...
465 //$utils = new Utils($db);
466 //$outputfile = $conf->admin->dir_temp.'/dump.tmp';
467 //$utils->executeCLI($fullcommandclear, $outputfile, 0);
468
469 if ($retval != 0) {
470 $langs->load("errors");
471 dol_syslog("Datadump retval after exec=".$retval, LOG_ERR);
472 $errormsg = 'Error '.$retval;
473 $ok = 0;
474 } else {
475 $i = 0;
476 if (!empty($output_arr)) {
477 foreach ($output_arr as $key => $read) {
478 $i++; // output line number
479 if ($i == 1 && preg_match('/Warning.*Using a password/i', $read)) {
480 continue;
481 }
482 // Now check into the result file, that the file end with "-- Dump completed"
483 // This is possible only if $output_arr is the clear dump file, so not possible with $lowmemorydump set because file is already compressed.
484 if (!$lowmemorydump) {
485 // TODO decrypt dolCrypted values from $read
486
487 fwrite($handle, $read.($execmethod == 2 ? '' : "\n"));
488 if (preg_match('/'.preg_quote('-- Dump completed', '/').'/i', $read)) {
489 $ok = 1;
490 } elseif (preg_match('/'.preg_quote('SET SQL_NOTES=@OLD_SQL_NOTES', '/').'/i', $read)) {
491 $ok = 1;
492 }
493 } else {
494 // If we have a result here in lowmemorydump mode, something is strange
495 }
496 }
497 } elseif ($lowmemorydump) {
498 $ok = 1;
499 }
500 }
501 }
502
503 if ($execmethod == 2) { // With this method, there is no way to get the return code, only output
504 $handlein = popen($fullcommandclear, 'r');
505 $i = 0;
506 if ($handlein) {
507 while (!feof($handlein)) {
508 $i++; // output line number
509 $read = fgets($handlein);
510 // Exclude warning line we don't want
511 if ($i == 1 && preg_match('/Warning.*Using a password/i', $read)) {
512 continue;
513 }
514 fwrite($handle, $read);
515 if (preg_match('/'.preg_quote('-- Dump completed', '/').'/i', $read)) {
516 $ok = 1;
517 } elseif (preg_match('/'.preg_quote('SET SQL_NOTES=@OLD_SQL_NOTES', '/').'/i', $read)) {
518 $ok = 1;
519 }
520 }
521 pclose($handlein);
522 }
523 }
524
525 if (!$lowmemorydump) {
526 if ($compression == 'none') {
527 fclose($handle);
528 } elseif ($compression == 'gz') {
529 gzclose($handle);
530 } elseif ($compression == 'bz') {
531 fclose($handle);
532 } elseif ($compression == 'zstd') {
533 fclose($handle);
534 }
535 }
536
537 dolChmod($outputfile);
538 } else {
539 $langs->load("errors");
540 dol_syslog("Failed to open file ".$outputfile, LOG_ERR);
541 $errormsg = $langs->trans("ErrorFailedToWriteInDir");
542 }
543
544 // Get errorstring
545 if ($compression == 'none') {
546 $handle = fopen($outputfile, 'r');
547 } elseif ($compression == 'gz') {
548 $handle = gzopen($outputfile, 'r');
549 } elseif ($compression == 'bz') {
550 $handle = bzopen($outputfile, 'r');
551 } elseif ($compression == 'zstd') {
552 $handle = fopen($outputfile, 'r');
553 }
554 if ($handle) {
555 // Get 2048 first chars of error message.
556 $errormsg = fgets($handle, 2048);
557 //$ok=0;$errormsg=''; To force error
558
559 // Close file
560 if ($compression == 'none') {
561 fclose($handle);
562 } elseif ($compression == 'gz') {
563 gzclose($handle);
564 } elseif ($compression == 'bz') {
565 fclose($handle);
566 } elseif ($compression == 'zstd') {
567 fclose($handle);
568 }
569 if ($ok && preg_match('/^-- (MySql|MariaDB)/i', $errormsg) || preg_match('/^\/\*M?!999999/', $errormsg)) { // Start of file is ok, NOT an error
570 $errormsg = '';
571 } else {
572 // Rename file out into a file error
573 //print "$outputfile -> $outputerror";
574 @dol_delete_file($outputerror, 1, 0, 0, null, false, 0);
575 @dol_move($outputfile, $outputerror, '0', 1, 0, 0);
576 // Si safe_mode on et command hors du parameter exec, on a un fichier out vide donc errormsg vide
577 if (!$errormsg) {
578 $langs->load("errors");
579 $errormsg = $langs->trans("ErrorFailedToRunExternalCommand");
580 }
581 }
582 }
583 // Fin execution commande
584
585 $this->output = $errormsg;
586 $this->error = $errormsg;
587 $this->result = array("commandbackuplastdone" => $command." ".$paramcrypted, "commandbackuptorun" => "");
588 //if (empty($this->output)) $this->output=$this->result['commandbackuplastdone'];
589 }
590
591 // MYSQL NO BIN
592 if ($type == 'mysqlnobin') {
593 $outputfile = $outputdir.'/'.$file;
594 $outputfiletemp = $outputfile.'-TMP.sql';
595 // for compression format, we add extension
596 $compression = $compression ? $compression : 'none';
597 if ($compression == 'gz') {
598 $outputfile .= '.gz';
599 }
600 if ($compression == 'bz') {
601 $outputfile .= '.bz2';
602 }
603 $outputerror = $outputfile.'.err';
604 dol_mkdir($conf->admin->dir_output.'/backup');
605
606 if ($compression == 'gz' or $compression == 'bz') {
607 $this->backupTables($outputfiletemp);
608 dol_compress_file($outputfiletemp, $outputfile, $compression);
609 unlink($outputfiletemp);
610 } else {
611 $this->backupTables($outputfile);
612 }
613
614 $this->output = "";
615 $this->result = array("commandbackuplastdone" => "", "commandbackuptorun" => "");
616 }
617
618 // POSTGRESQL
619 if ($type == 'postgresql' || $type == 'pgsql') {
620 $cmddump = getDolGlobalString('SYSTEMTOOLS_POSTGRESQLDUMP');
621
622 $outputfile = $outputdir.'/'.$file;
623 // for compression format, we add extension
624 $compression = $compression ? $compression : 'none';
625 if ($compression == 'gz') {
626 $outputfile .= '.gz';
627 }
628 if ($compression == 'bz') {
629 $outputfile .= '.bz2';
630 }
631 $outputerror = $outputfile.'.err';
632 dol_mkdir($conf->admin->dir_output.'/backup');
633
634 // Parameters execution
635 $command = $cmddump;
636 $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.
637 if (preg_match("/\s/", $command)) {
638 $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
639 }
640
641 //$param=escapeshellarg($dolibarr_main_db_name)." -h ".escapeshellarg($dolibarr_main_db_host)." -u ".escapeshellarg($dolibarr_main_db_user)." -p".escapeshellarg($dolibarr_main_db_pass);
642 //$param="-F c";
643 $param = "-F p";
644 $param .= " --no-tablespaces --inserts -h ".$dolibarr_main_db_host;
645 $param .= " -U ".$dolibarr_main_db_user;
646 if (!empty($dolibarr_main_db_port)) {
647 $param .= " -p ".$dolibarr_main_db_port;
648 }
649 if (GETPOST("sql_compat") && GETPOST("sql_compat") == 'ANSI') {
650 $param .= " --disable-dollar-quoting";
651 }
652 if (GETPOST("drop_database")) {
653 $param .= " -c -C";
654 }
655 if (GETPOST("sql_structure")) {
656 if (GETPOST("drop")) {
657 $param .= " --add-drop-table";
658 }
659 if (!GETPOST("sql_data")) {
660 $param .= " -s";
661 }
662 }
663 if (GETPOST("sql_data")) {
664 if (!GETPOST("sql_structure")) {
665 $param .= " -a";
666 }
667 if (GETPOST("showcolumns")) {
668 $param .= " -c";
669 }
670 }
671 $param .= ' -f "'.$outputfile.'"';
672 //if ($compression == 'none')
673 if ($compression == 'gz') {
674 $param .= ' -Z 9';
675 }
676 //if ($compression == 'bz')
677 $paramcrypted = $param;
678 $paramclear = $param;
679 /*if (!empty($dolibarr_main_db_pass))
680 {
681 $paramcrypted.=" -W".preg_replace('/./i','*',$dolibarr_main_db_pass);
682 $paramclear.=" -W".$dolibarr_main_db_pass;
683 }*/
684 $paramcrypted .= " -w ".$dolibarr_main_db_name;
685 $paramclear .= " -w ".$dolibarr_main_db_name;
686
687 $this->output = "";
688 $this->result = array("commandbackuplastdone" => "", "commandbackuptorun" => $command." ".$paramcrypted);
689 }
690
691 // Clean old files
692 if (!$errormsg && $keeplastnfiles > 0) {
693 $tmpfiles = dol_dir_list($conf->admin->dir_output.'/backup', 'files', 0, '', '(\.err|\.old|\.sav)$', 'date', SORT_DESC);
694 $i = 0;
695 if (is_array($tmpfiles)) {
696 foreach ($tmpfiles as $key => $val) {
697 $i++;
698 if ($i <= $keeplastnfiles) {
699 continue;
700 }
701 dol_delete_file($val['fullname'], 0, 0, 0, null, false, 0);
702 }
703 }
704 }
705
706 return ($errormsg ? -1 : 0);
707 }
708
709
710
724 public function executeCLI($command, $outputfile, $execmethod = 0, $redirectionfile = null, $noescapecommand = 0, $redirectionfileerr = null)
725 {
726 global $langs;
727
728 $result = 0;
729 $output = '';
730 $error = '';
731
732 if (empty($noescapecommand)) {
733 $command = escapeshellcmd($command);
734 }
735
736 if ($redirectionfile) {
737 $command .= " > ".dol_sanitizePathName($redirectionfile);
738 }
739
740 if ($redirectionfileerr && ($redirectionfileerr != $redirectionfile)) {
741 // If we ask a redirect of stderr on a given file not already used for stdout
742 $command .= " 2> ".dol_sanitizePathName($redirectionfileerr);
743 } else {
744 $command .= " 2>&1";
745 }
746
747 if (getDolGlobalString('MAIN_EXEC_USE_POPEN')) {
748 $execmethod = getDolGlobalString('MAIN_EXEC_USE_POPEN');
749 }
750 if (empty($execmethod)) {
751 $execmethod = 1;
752 }
753 //$execmethod=1;
754 dol_syslog("Utils::executeCLI execmethod=".$execmethod." command=".$command, LOG_DEBUG);
755 $output_arr = array();
756
757 if ($execmethod == 1) {
758 $retval = null;
759 exec($command, $output_arr, $retval); // @phan-suppress-current-line PhanPluginConstantVariableNull
760 $result = $retval;
761 if ($retval != 0) {
762 $langs->load("errors");
763 dol_syslog("Utils::executeCLI retval after exec=".$retval, LOG_ERR);
764 $error = 'Error '.$retval;
765 }
766 }
767 if ($execmethod == 2) { // With this method, there is no way to get the return code, only output
768 $handle = fopen($outputfile, 'w+b');
769 if ($handle) {
770 dol_syslog("Utils::executeCLI run command ".$command);
771 $handlein = popen($command, 'r');
772 while (!feof($handlein)) {
773 $read = fgets($handlein);
774 fwrite($handle, $read);
775 $output_arr[] = $read;
776 }
777 pclose($handlein);
778 fclose($handle);
779 }
780 dolChmod($outputfile);
781 }
782
783 // Update with result
784 if (is_array($output_arr) && count($output_arr) > 0) {
785 foreach ($output_arr as $val) {
786 $output .= $val.($execmethod == 2 ? '' : "\n");
787 }
788 }
789
790 dol_syslog("Utils::executeCLI result=".$result." output=".$output." error=".$error, LOG_DEBUG);
791
792 return array('result' => $result, 'output' => $output, 'error' => $error);
793 }
794
801 public function generateDoc($module)
802 {
803 global $conf, $langs, $user, $mysoc;
804 global $dirins;
805
806 $error = 0;
807
808 $modulelowercase = strtolower($module);
809 $now = dol_now();
810
811 // Dir for module
812 $dir = $dirins.'/'.$modulelowercase;
813 // Zip file to build
814 $FILENAMEDOC = '';
815
816 // Load module
817 dol_include_once($modulelowercase.'/core/modules/mod'.$module.'.class.php');
818 $class = 'mod'.$module;
819
820 $moduleobj = null;
821 if (class_exists($class)) {
822 try {
823 $moduleobj = new $class($this->db);
824 } catch (Exception $e) {
825 $error++;
826 dol_print_error(null, $e->getMessage());
827 }
828 } else {
829 $error++;
830 $langs->load("errors");
831 dol_print_error(null, $langs->trans("ErrorFailedToLoadModuleDescriptorForXXX", $module));
832 exit;
833 }
834
835 $arrayversion = $moduleobj === null ? array() : explode('.', $moduleobj->version, 3);
836 if (count($arrayversion)) {
837 $FILENAMEASCII = strtolower($module).'.asciidoc';
838 $FILENAMEDOC = strtolower($module).'.html';
839 $FILENAMEDOCPDF = strtolower($module).'.pdf';
840
841 $dirofmodule = dol_buildpath(strtolower($module), 0);
842 $dirofmoduledoc = dol_buildpath(strtolower($module), 0).'/doc';
843 $dirofmoduletmp = dol_buildpath(strtolower($module), 0).'/doc/temp';
844 $outputfiledoc = $dirofmoduledoc.'/'.$FILENAMEDOC;
845 if ($dirofmoduledoc) {
846 if (!dol_is_dir($dirofmoduledoc)) {
847 dol_mkdir($dirofmoduledoc);
848 }
849 if (!dol_is_dir($dirofmoduletmp)) {
850 dol_mkdir($dirofmoduletmp);
851 }
852 if (!is_writable($dirofmoduletmp)) {
853 $this->error = 'Dir '.$dirofmoduletmp.' does not exists or is not writable';
854 return -1;
855 }
856
857 if (!getDolGlobalString('MODULEBUILDER_ASCIIDOCTOR') && !getDolGlobalString('MODULEBUILDER_ASCIIDOCTORPDF')) {
858 $this->error = 'Setup of module ModuleBuilder not complete';
859 return -1;
860 }
861
862 // Copy some files into temp directory, so instruction include::ChangeLog.md[] will works inside the asciidoc file.
863 dol_copy($dirofmodule.'/README.md', $dirofmoduletmp.'/README.md', '0', 1);
864 dol_copy($dirofmodule.'/ChangeLog.md', $dirofmoduletmp.'/ChangeLog.md', '0', 1);
865
866 // Replace into README.md and ChangeLog.md (in case they are included into documentation with tag __README__ or __CHANGELOG__)
867 $arrayreplacement = array();
868 $arrayreplacement['/^#\s.*/m'] = ''; // Remove first level of title into .md files
869 $arrayreplacement['/^#/m'] = '##'; // Add on # to increase level
870
871 dolReplaceInFile($dirofmoduletmp.'/README.md', $arrayreplacement, '', '0', 0, 1);
872 dolReplaceInFile($dirofmoduletmp.'/ChangeLog.md', $arrayreplacement, '', '0', 0, 1);
873
874
875 $destfile = $dirofmoduletmp.'/'.$FILENAMEASCII;
876
877 $fhandle = fopen($destfile, 'w+');
878 if ($fhandle) {
879 $specs = dol_dir_list(dol_buildpath(strtolower($module).'/doc', 0), 'files', 1, '(\.md|\.asciidoc)$', array('\/temp\/'));
880
881 $i = 0;
882 foreach ($specs as $spec) {
883 if (preg_match('/notindoc/', $spec['relativename'])) {
884 continue; // Discard file
885 }
886 if (preg_match('/example/', $spec['relativename'])) {
887 continue; // Discard file
888 }
889 if (preg_match('/disabled/', $spec['relativename'])) {
890 continue; // Discard file
891 }
892
893 $pathtofile = strtolower($module).'/doc/'.$spec['relativename'];
894 $format = 'asciidoc';
895 if (preg_match('/\.md$/i', $spec['name'])) {
896 $format = 'markdown';
897 }
898
899 $filecursor = @file_get_contents($spec['fullname']);
900 if ($filecursor) {
901 fwrite($fhandle, ($i ? "\n<<<\n\n" : "").$filecursor."\n");
902 } else {
903 $this->error = 'Failed to concat content of file '.$spec['fullname'];
904 return -1;
905 }
906
907 $i++;
908 }
909
910 fclose($fhandle);
911
912 $contentreadme = file_get_contents($dirofmoduletmp.'/README.md');
913 $contentchangelog = file_get_contents($dirofmoduletmp.'/ChangeLog.md');
914
915 include DOL_DOCUMENT_ROOT.'/core/lib/parsemd.lib.php';
916
917 //var_dump($phpfileval['fullname']);
918 $arrayreplacement = array(
919 'mymodule' => strtolower($module),
920 'MyModule' => $module,
921 'MYMODULE' => strtoupper($module),
922 'My module' => $module,
923 'my module' => $module,
924 'Mon module' => $module,
925 'mon module' => $module,
926 'htdocs/modulebuilder/template' => strtolower($module),
927 '__MYCOMPANY_NAME__' => $mysoc->name,
928 '__KEYWORDS__' => $module,
929 '__USER_FULLNAME__' => $user->getFullName($langs),
930 '__USER_EMAIL__' => $user->email,
931 '__YYYY-MM-DD__' => dol_print_date($now, 'dayrfc'),
932 '---Put here your own copyright and developer email---' => dol_print_date($now, 'dayrfc').' '.$user->getFullName($langs).($user->email ? ' <'.$user->email.'>' : ''),
933 '__DATA_SPECIFICATION__' => 'Not yet available',
934 '__README__' => dolMd2Asciidoc($contentreadme),
935 '__CHANGELOG__' => dolMd2Asciidoc($contentchangelog),
936 );
937
938 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
939 dolReplaceInFile($destfile, $arrayreplacement);
940 }
941
942 // Launch doc generation
943 $currentdir = getcwd();
944 chdir($dirofmodule);
945
946 require_once DOL_DOCUMENT_ROOT.'/core/class/utils.class.php';
947 $utils = new Utils($this->db);
948
949 // Build HTML doc
950 $command = getDolGlobalString('MODULEBUILDER_ASCIIDOCTOR') . ' '.$destfile.' -n -o '.$dirofmoduledoc.'/'.$FILENAMEDOC;
951 $outfile = $dirofmoduletmp.'/out.tmp';
952
953 $resarray = $utils->executeCLI($command, $outfile);
954 if ($resarray['result'] != '0') {
955 $this->error = $resarray['error'].' '.$resarray['output'];
956 $this->errors[] = $this->error;
957 }
958 $result = ($resarray['result'] == 0) ? 1 : 0;
959 if ($result < 0 && empty($this->errors)) {
960 $this->error = $langs->trans("ErrorFailToGenerateFile", $FILENAMEDOC);
961 $this->errors[] = $this->error;
962 }
963
964 // Build PDF doc
965 $command = getDolGlobalString('MODULEBUILDER_ASCIIDOCTORPDF') . ' '.$destfile.' -n -o '.$dirofmoduledoc.'/'.$FILENAMEDOCPDF;
966 $outfile = $dirofmoduletmp.'/outpdf.tmp';
967 $resarray = $utils->executeCLI($command, $outfile);
968 if ($resarray['result'] != '0') {
969 $this->error = $resarray['error'].' '.$resarray['output'];
970 $this->errors[] = $this->error;
971 }
972 $result = ($resarray['result'] == 0) ? 1 : 0;
973 if ($result < 0 && empty($this->errors)) {
974 $this->error = $langs->trans("ErrorFailToGenerateFile", $FILENAMEDOCPDF);
975 $this->errors[] = $this->error;
976 }
977
978 chdir($currentdir);
979 } else {
980 $result = 0;
981 }
982
983 if ($result > 0) {
984 return 1;
985 } else {
986 $error++;
987 }
988 } else {
989 $error++;
990 $langs->load("errors");
991 $this->error = $langs->trans("ErrorCheckVersionIsDefined");
992 }
993
994 return -1;
995 }
996
1004 public function compressSyslogs()
1005 {
1006 global $conf;
1007
1008 if (empty($conf->loghandlers['mod_syslog_file'])) { // File Syslog disabled
1009 return 0;
1010 }
1011
1012 if (!function_exists('gzopen')) {
1013 $this->error = 'Support for gzopen not available in this PHP';
1014 return -1;
1015 }
1016
1017 require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
1018
1019 $nbSaves = intval(getDolGlobalString('SYSLOG_FILE_SAVES', 10));
1020
1021 if (!getDolGlobalString('SYSLOG_FILE')) {
1022 $mainlogdir = DOL_DATA_ROOT;
1023 $mainlog = 'dolibarr.log';
1024 } else {
1025 $mainlogfull = str_replace('DOL_DATA_ROOT', DOL_DATA_ROOT, $conf->global->SYSLOG_FILE);
1026 $mainlogdir = dirname($mainlogfull);
1027 $mainlog = basename($mainlogfull);
1028 }
1029
1030 $tabfiles = dol_dir_list(DOL_DATA_ROOT, 'files', 0, '^(dolibarr_.+|odt2pdf)\.log$'); // Also handle other log files like dolibarr_install.log
1031 $tabfiles[] = array('name' => $mainlog, 'path' => $mainlogdir);
1032
1033 foreach ($tabfiles as $file) {
1034 $logname = $file['name'];
1035 $logpath = $file['path'];
1036
1037 if (dol_is_file($logpath.'/'.$logname) && dol_filesize($logpath.'/'.$logname) > 0) { // If log file exists and is not empty
1038 // Handle already compressed files to rename them and add +1
1039
1040 $filter = '^'.preg_quote($logname, '/').'\.([0-9]+)\.gz$';
1041
1042 $gzfilestmp = dol_dir_list($logpath, 'files', 0, $filter);
1043 $gzfiles = array();
1044
1045 foreach ($gzfilestmp as $gzfile) {
1046 $tabmatches = array();
1047 preg_match('/'.$filter.'/i', $gzfile['name'], $tabmatches);
1048
1049 $numsave = intval($tabmatches[1]);
1050
1051 $gzfiles[$numsave] = $gzfile;
1052 }
1053
1054 krsort($gzfiles, SORT_NUMERIC);
1055
1056 foreach ($gzfiles as $numsave => $dummy) {
1057 if (dol_is_file($logpath.'/'.$logname.'.'.($numsave + 1).'.gz')) {
1058 return -2;
1059 }
1060
1061 if ($numsave >= $nbSaves) {
1062 dol_delete_file($logpath.'/'.$logname.'.'.$numsave.'.gz', 0, 0, 0, null, false, 0);
1063 } else {
1064 dol_move($logpath.'/'.$logname.'.'.$numsave.'.gz', $logpath.'/'.$logname.'.'.($numsave + 1).'.gz', '0', 1, 0, 0);
1065 }
1066 }
1067
1068 // Compress current file and recreate it
1069
1070 if ($nbSaves > 0) { // If $nbSaves is 1, we keep 1 archive .gz file, If 2, we keep 2 .gz files
1071 $gzfilehandle = gzopen($logpath.'/'.$logname.'.1.gz', 'wb9');
1072
1073 if (empty($gzfilehandle)) {
1074 $this->error = 'Failted to open file '.$logpath.'/'.$logname.'.1.gz';
1075 return -3;
1076 }
1077
1078 $sourcehandle = fopen($logpath.'/'.$logname, 'r');
1079
1080 if (empty($sourcehandle)) {
1081 $this->error = 'Failed to open file '.$logpath.'/'.$logname;
1082 return -4;
1083 }
1084
1085 while (!feof($sourcehandle)) {
1086 gzwrite($gzfilehandle, fread($sourcehandle, 512 * 1024)); // Read 512 kB at a time
1087 }
1088
1089 fclose($sourcehandle);
1090 gzclose($gzfilehandle);
1091
1092 dolChmod($logpath.'/'.$logname.'.1.gz');
1093 }
1094
1095 dol_delete_file($logpath.'/'.$logname, 0, 0, 0, null, false, 0);
1096
1097 // Create empty file
1098 $newlog = fopen($logpath.'/'.$logname, 'a+');
1099 fclose($newlog);
1100
1101 //var_dump($logpath.'/'.$logname." - ".octdec(empty($conf->global->MAIN_UMASK)?'0664':$conf->global->MAIN_UMASK));
1102 dolChmod($logpath.'/'.$logname);
1103 }
1104 }
1105
1106 $this->output = 'Archive log files (keeping last SYSLOG_FILE_SAVES='.$nbSaves.' files) done.';
1107 return 0;
1108 }
1109
1120 public function backupTables($outputfile, $tables = '*')
1121 {
1122 global $db, $langs;
1123 global $errormsg;
1124
1125 // Set to UTF-8
1126 if (is_a($db, 'DoliDBMysqli')) {
1128 $db->db->set_charset('utf8');
1129 } else {
1131 $db->query('SET NAMES utf8');
1132 $db->query('SET CHARACTER SET utf8');
1133 }
1134
1135 //get all of the tables
1136 if ($tables == '*') {
1137 $tables = array();
1138 $result = $db->query('SHOW FULL TABLES WHERE Table_type = \'BASE TABLE\'');
1139 while ($row = $db->fetch_row($result)) {
1140 $tables[] = $row[0];
1141 }
1142 } else {
1143 $tables = is_array($tables) ? $tables : explode(',', $tables);
1144 }
1145
1146 //cycle through
1147 $handle = fopen($outputfile, 'w+');
1148 if (fwrite($handle, '') === false) {
1149 $langs->load("errors");
1150 dol_syslog("Failed to open file ".$outputfile, LOG_ERR);
1151 $errormsg = $langs->trans("ErrorFailedToWriteInDir");
1152 return -1;
1153 }
1154
1155 // Print headers and global mysql config vars
1156 $sqlhead = '';
1157 $sqlhead .= "-- ".$db::LABEL." dump via php with Dolibarr ".DOL_VERSION."
1158--
1159-- Host: ".$db->db->host_info." Database: ".$db->database_name."
1160-- ------------------------------------------------------
1161-- Server version ".$db->db->server_info."
1162
1163;
1164;
1165;
1166;
1167;
1168;
1169;
1170;
1171;
1172;
1173
1174";
1175
1176 if (GETPOST("nobin_disable_fk")) {
1177 $sqlhead .= "SET FOREIGN_KEY_CHECKS=0;\n";
1178 }
1179 //$sqlhead .= "SET SQL_MODE=\"NO_AUTO_VALUE_ON_ZERO\";\n";
1180 if (GETPOST("nobin_use_transaction")) {
1181 $sqlhead .= "SET AUTOCOMMIT=0;\nSTART TRANSACTION;\n";
1182 }
1183
1184 fwrite($handle, $sqlhead);
1185
1186 $ignore = '';
1187 if (GETPOST("nobin_sql_ignore")) {
1188 $ignore = 'IGNORE ';
1189 }
1190 $delayed = '';
1191 if (GETPOST("nobin_delayed")) {
1192 $delayed = 'DELAYED ';
1193 }
1194
1195 // Process each table and print their definition + their datas
1196 foreach ($tables as $table) {
1197 // Saving the table structure
1198 fwrite($handle, "\n--\n-- Table structure for table `".$table."`\n--\n");
1199
1200 if (GETPOST("nobin_drop")) {
1201 fwrite($handle, "DROP TABLE IF EXISTS `".$table."`;\n"); // Dropping table if exists prior to re create it
1202 }
1203 fwrite($handle, "/*!40101 SET @saved_cs_client = @@character_set_client */;\n");
1204 fwrite($handle, "/*!40101 SET character_set_client = utf8 */;\n");
1205 $resqldrop = $db->query('SHOW CREATE TABLE '.$table);
1206 $row2 = $db->fetch_row($resqldrop);
1207 if (empty($row2[1])) {
1208 fwrite($handle, "\n-- WARNING: Show create table ".$table." return empty string when it should not.\n");
1209 } else {
1210 fwrite($handle, $row2[1].";\n");
1211 //fwrite($handle,"/*!40101 SET character_set_client = @saved_cs_client */;\n\n");
1212
1213 // Dumping the data (locking the table and disabling the keys check while doing the process)
1214 fwrite($handle, "\n--\n-- Dumping data for table `".$table."`\n--\n");
1215 if (!GETPOST("nobin_nolocks")) {
1216 fwrite($handle, "LOCK TABLES `".$table."` WRITE;\n"); // Lock the table before inserting data (when the data will be imported back)
1217 }
1218 if (GETPOST("nobin_disable_fk")) {
1219 fwrite($handle, "ALTER TABLE `".$table."` DISABLE KEYS;\n");
1220 } else {
1221 fwrite($handle, "/*!40000 ALTER TABLE `".$table."` DISABLE KEYS */;\n");
1222 }
1223
1224 $sql = "SELECT * FROM ".$table; // Here SELECT * is allowed because we don't have definition of columns to take
1225 $result = $db->query($sql);
1226 while ($row = $db->fetch_row($result)) {
1227 // For each row of data we print a line of INSERT
1228 fwrite($handle, "INSERT ".$delayed.$ignore."INTO ".$table." VALUES (");
1229 $columns = count($row);
1230 for ($j = 0; $j < $columns; $j++) {
1231 // 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)
1232 if ($row[$j] == null && !is_string($row[$j])) {
1233 // IMPORTANT: if the field is NULL we set it NULL
1234 $row[$j] = 'NULL';
1235 } elseif (is_string($row[$j]) && $row[$j] == '') {
1236 // if it's an empty string, we set it as an empty string
1237 $row[$j] = "''";
1238 } 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)
1239 // if it's a number, we return it as-is
1240 // $row[$j] = $row[$j];
1241 } else { // else for all other cases we escape the value and put quotes around
1242 $row[$j] = addslashes($row[$j]);
1243 $row[$j] = preg_replace("#\n#", "\\n", $row[$j]);
1244 $row[$j] = "'".$row[$j]."'";
1245 }
1246 }
1247 fwrite($handle, implode(',', $row).");\n");
1248 }
1249 if (GETPOST("nobin_disable_fk")) {
1250 fwrite($handle, "ALTER TABLE `".$table."` ENABLE KEYS;\n"); // Enabling back the keys/index checking
1251 }
1252 if (!GETPOST("nobin_nolocks")) {
1253 fwrite($handle, "UNLOCK TABLES;\n"); // Unlocking the table
1254 }
1255 fwrite($handle, "\n\n\n");
1256 }
1257 }
1258
1259 /* Backup Procedure structure*/
1260 /*
1261 $result = $db->query('SHOW PROCEDURE STATUS');
1262 if ($db->num_rows($result) > 0)
1263 {
1264 while ($row = $db->fetch_row($result)) { $procedures[] = $row[1]; }
1265 foreach($procedures as $proc)
1266 {
1267 fwrite($handle,"DELIMITER $$\n\n");
1268 fwrite($handle,"DROP PROCEDURE IF EXISTS '$name'.'$proc'$$\n");
1269 $resqlcreateproc=$db->query("SHOW CREATE PROCEDURE '$proc'");
1270 $row2 = $db->fetch_row($resqlcreateproc);
1271 fwrite($handle,"\n".$row2[2]."$$\n\n");
1272 fwrite($handle,"DELIMITER ;\n\n");
1273 }
1274 }
1275 */
1276 /* Backup Procedure structure*/
1277
1278 // Write the footer (restore the previous database settings)
1279 $sqlfooter = "\n\n";
1280 if (GETPOST("nobin_use_transaction")) {
1281 $sqlfooter .= "COMMIT;\n";
1282 }
1283 if (GETPOST("nobin_disable_fk")) {
1284 $sqlfooter .= "SET FOREIGN_KEY_CHECKS=1;\n";
1285 }
1286 $sqlfooter .= "\n\n-- Dump completed on ".date('Y-m-d G-i-s');
1287 fwrite($handle, $sqlfooter);
1288
1289 fclose($handle);
1290
1291 return 1;
1292 }
1293
1307 public function sendBackup($sendto = '', $from = '', $subject = '', $message = '', $filename = '', $filter = '', $sizelimit = 100000000)
1308 {
1309 global $conf, $langs;
1311
1312 $filepath = '';
1313 $filesize = -1;
1314 $output = '';
1315 $error = 0;
1316 $mimetype = '';
1317
1318 if (!empty($from)) {
1319 $from = dol_escape_htmltag($from);
1320 } elseif (getDolGlobalString('MAIN_MAIL_EMAIL_FROM')) {
1321 $from = dol_escape_htmltag(getDolGlobalString('MAIN_MAIL_EMAIL_FROM'));
1322 } else {
1323 $error++;
1324 }
1325
1326 if (!empty($sendto)) {
1327 $sendto = dol_escape_htmltag($sendto);
1328 } elseif (getDolGlobalString('MAIN_INFO_SOCIETE_MAIL')) {
1329 $sendto = dol_escape_htmltag(getDolGlobalString('MAIN_INFO_SOCIETE_MAIL'));
1330 } else {
1331 $error++;
1332 }
1333
1334 if (!empty($subject)) {
1335 $subject = dol_escape_htmltag($subject);
1336 } else {
1337 $subject = dol_escape_htmltag($langs->trans('MakeSendLocalDatabaseDumpShort'));
1338 }
1339
1340 if (empty($message)) {
1341 $message = dol_escape_htmltag($langs->trans('MakeSendLocalDatabaseDumpShort'));
1342 }
1343
1344 $tmpfiles = array();
1345 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1346 if ($filename) {
1347 if (dol_is_file($conf->admin->dir_output.'/backup/'.$filename)) {
1348 $tmpfiles = dol_most_recent_file($conf->admin->dir_output.'/backup', $filename);
1349 }
1350 } else {
1351 $tmpfiles = dol_most_recent_file($conf->admin->dir_output.'/backup', $filter);
1352 }
1353 if ($tmpfiles && is_array($tmpfiles)) {
1354 foreach ($tmpfiles as $key => $val) {
1355 if ($key == 'fullname') {
1356 $filepath = array($val);
1357 $filesize = dol_filesize($val);
1358 }
1359 if ($key == 'type') {
1360 $mimetype = array($val);
1361 }
1362 if ($key == 'relativename') {
1363 $filename = array($val);
1364 }
1365 }
1366 }
1367
1368 if ($filepath) {
1369 if ($filesize > $sizelimit) {
1370 $message .= '<br>'.$langs->trans("BackupIsTooLargeSend");
1371 $documenturl = $dolibarr_main_url_root.'/document.php?modulepart=systemtools&atachement=1&file=backup/'.urlencode($filename[0]);
1372 $message .= '<br><a href='.$documenturl.'>Download link</a>';
1373 $filepath = '';
1374 $mimetype = '';
1375 $filename = '';
1376 }
1377 } else {
1378 $output = 'No backup file found';
1379 $error++;
1380 }
1381
1382 $mailfile = null;
1383 if (!$error) {
1384 include_once DOL_DOCUMENT_ROOT . '/core/class/CMailFile.class.php';
1385 $mailfile = new CMailFile($subject, $sendto, $from, $message, $filepath, $mimetype, $filename, '', '', 0, 1);
1386 // $mailfile = new CMailFile($subject, $sendto, $from, $message, $filepath, $mimetype, $filename, '', '', 0, 1);
1387 if ($mailfile->error) {
1388 $error++;
1389 $output = $mailfile->error;
1390 }
1391 }
1392
1393 $result = false;
1394 $output = '';
1395 if (!$error && $mailfile !== null) {
1396 $result = $mailfile->sendfile();
1397 if (!$result) {
1398 $error++;
1399 $output = $mailfile->error;
1400 }
1401 }
1402
1403 dol_syslog(__METHOD__, LOG_DEBUG);
1404
1405 $this->error = "Error sending backup file ".((string) $error);
1406 $this->output = $output;
1407
1408 if ($result) {
1409 return 0;
1410 } else {
1411 return -1;
1412 }
1413 }
1414
1422 public function cleanUnfinishedCronjob()
1423 {
1424 global $db, $user;
1425 dol_syslog("Utils::cleanUnfinishedCronjob Starting cleaning");
1426
1427 // Import Cronjob class if not present
1428 require_once DOL_DOCUMENT_ROOT . '/cron/class/cronjob.class.php';
1429
1430 // Get this job object
1431 $this_job = new Cronjob($db);
1432 $this_job->fetch(-1, 'Utils', 'cleanUnfinishedCronjob');
1433 if (empty($this_job->id) || !empty($this_job->error)) {
1434 dol_syslog("Utils::cleanUnfinishedCronjob Unable to fetch himself: ".$this_job->error, LOG_ERR);
1435 return -1;
1436 }
1437
1438 // Set this job processing to 0 to avoid being locked by his processing state
1439 $this_job->processing = 0;
1440 if ($this_job->update($user) < 0) {
1441 dol_syslog("Utils::cleanUnfinishedCronjob Unable to update himself: ".implode(', ', $this_job->errors), LOG_ERR);
1442 return -1;
1443 }
1444
1445 $cron_job = new Cronjob($db);
1446 $cron_job->fetchAll('DESC', 't.rowid', 100, 0, 1, [], 1); // Fetch jobs that are currently running
1447
1448 // Iterate over all jobs in processing (this can't be this job since his state is set to 0 before)
1449 foreach ($cron_job->lines as $job_line) {
1450 // Avoid job with no PID
1451 if (empty($job_line->pid)) {
1452 dol_syslog("Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id." don't have a PID", LOG_DEBUG);
1453 continue;
1454 }
1455
1456 $job = new Cronjob($db);
1457 $job->fetch($job_line->id);
1458 if (empty($job->id) || !empty($job->error)) {
1459 dol_syslog("Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id." can't be fetch: ".$job->error, LOG_ERR);
1460 continue;
1461 }
1462
1463 // Calling posix_kill with the 0 kill signal will return true if the process is running, false otherwise.
1464 if (! posix_kill($job->pid, 0)) {
1465 // Clean processing and pid values
1466 $job->processing = 0;
1467 $job->pid = null;
1468
1469 // Set last result as an error and add the reason on the last output
1470 $job->lastresult = strval(-1);
1471 $job->lastoutput = 'Job killed by job cleanUnfinishedCronjob';
1472
1473 if ($job->update($user) < 0) {
1474 dol_syslog("Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id." can't be updated: ".implode(', ', $job->errors), LOG_ERR);
1475 continue;
1476 }
1477 dol_syslog("Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id." cleaned");
1478 }
1479 }
1480
1481 dol_syslog("Utils::cleanUnfinishedCronjob Cleaning completed");
1482 return 0;
1483 }
1484}
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_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)
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.