dolibarr 23.0.3
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 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 if (class_exists($class)) {
821 try {
822 $moduleobj = new $class($this->db);
823 } catch (Exception $e) {
824 $error++;
825 dol_print_error(null, $e->getMessage());
826 }
827 } else {
828 $error++;
829 $langs->load("errors");
830 dol_print_error(null, $langs->trans("ErrorFailedToLoadModuleDescriptorForXXX", $module));
831 exit;
832 }
833
834 $arrayversion = explode('.', $moduleobj->version, 3);
835 if (count($arrayversion)) {
836 $FILENAMEASCII = strtolower($module).'.asciidoc';
837 $FILENAMEDOC = strtolower($module).'.html';
838 $FILENAMEDOCPDF = strtolower($module).'.pdf';
839
840 $dirofmodule = dol_buildpath(strtolower($module), 0);
841 $dirofmoduledoc = dol_buildpath(strtolower($module), 0).'/doc';
842 $dirofmoduletmp = dol_buildpath(strtolower($module), 0).'/doc/temp';
843 $outputfiledoc = $dirofmoduledoc.'/'.$FILENAMEDOC;
844 if ($dirofmoduledoc) {
845 if (!dol_is_dir($dirofmoduledoc)) {
846 dol_mkdir($dirofmoduledoc);
847 }
848 if (!dol_is_dir($dirofmoduletmp)) {
849 dol_mkdir($dirofmoduletmp);
850 }
851 if (!is_writable($dirofmoduletmp)) {
852 $this->error = 'Dir '.$dirofmoduletmp.' does not exists or is not writable';
853 return -1;
854 }
855
856 if (!getDolGlobalString('MODULEBUILDER_ASCIIDOCTOR') && !getDolGlobalString('MODULEBUILDER_ASCIIDOCTORPDF')) {
857 $this->error = 'Setup of module ModuleBuilder not complete';
858 return -1;
859 }
860
861 // Copy some files into temp directory, so instruction include::ChangeLog.md[] will works inside the asciidoc file.
862 dol_copy($dirofmodule.'/README.md', $dirofmoduletmp.'/README.md', '0', 1);
863 dol_copy($dirofmodule.'/ChangeLog.md', $dirofmoduletmp.'/ChangeLog.md', '0', 1);
864
865 // Replace into README.md and ChangeLog.md (in case they are included into documentation with tag __README__ or __CHANGELOG__)
866 $arrayreplacement = array();
867 $arrayreplacement['/^#\s.*/m'] = ''; // Remove first level of title into .md files
868 $arrayreplacement['/^#/m'] = '##'; // Add on # to increase level
869
870 dolReplaceInFile($dirofmoduletmp.'/README.md', $arrayreplacement, '', '0', 0, 1);
871 dolReplaceInFile($dirofmoduletmp.'/ChangeLog.md', $arrayreplacement, '', '0', 0, 1);
872
873
874 $destfile = $dirofmoduletmp.'/'.$FILENAMEASCII;
875
876 $fhandle = fopen($destfile, 'w+');
877 if ($fhandle) {
878 $specs = dol_dir_list(dol_buildpath(strtolower($module).'/doc', 0), 'files', 1, '(\.md|\.asciidoc)$', array('\/temp\/'));
879
880 $i = 0;
881 foreach ($specs as $spec) {
882 if (preg_match('/notindoc/', $spec['relativename'])) {
883 continue; // Discard file
884 }
885 if (preg_match('/example/', $spec['relativename'])) {
886 continue; // Discard file
887 }
888 if (preg_match('/disabled/', $spec['relativename'])) {
889 continue; // Discard file
890 }
891
892 $pathtofile = strtolower($module).'/doc/'.$spec['relativename'];
893 $format = 'asciidoc';
894 if (preg_match('/\.md$/i', $spec['name'])) {
895 $format = 'markdown';
896 }
897
898 $filecursor = @file_get_contents($spec['fullname']);
899 if ($filecursor) {
900 fwrite($fhandle, ($i ? "\n<<<\n\n" : "").$filecursor."\n");
901 } else {
902 $this->error = 'Failed to concat content of file '.$spec['fullname'];
903 return -1;
904 }
905
906 $i++;
907 }
908
909 fclose($fhandle);
910
911 $contentreadme = file_get_contents($dirofmoduletmp.'/README.md');
912 $contentchangelog = file_get_contents($dirofmoduletmp.'/ChangeLog.md');
913
914 include DOL_DOCUMENT_ROOT.'/core/lib/parsemd.lib.php';
915
916 //var_dump($phpfileval['fullname']);
917 $arrayreplacement = array(
918 'mymodule' => strtolower($module),
919 'MyModule' => $module,
920 'MYMODULE' => strtoupper($module),
921 'My module' => $module,
922 'my module' => $module,
923 'Mon module' => $module,
924 'mon module' => $module,
925 'htdocs/modulebuilder/template' => strtolower($module),
926 '__MYCOMPANY_NAME__' => $mysoc->name,
927 '__KEYWORDS__' => $module,
928 '__USER_FULLNAME__' => $user->getFullName($langs),
929 '__USER_EMAIL__' => $user->email,
930 '__YYYY-MM-DD__' => dol_print_date($now, 'dayrfc'),
931 '---Put here your own copyright and developer email---' => dol_print_date($now, 'dayrfc').' '.$user->getFullName($langs).($user->email ? ' <'.$user->email.'>' : ''),
932 '__DATA_SPECIFICATION__' => 'Not yet available',
933 '__README__' => dolMd2Asciidoc($contentreadme),
934 '__CHANGELOG__' => dolMd2Asciidoc($contentchangelog),
935 );
936
937 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
938 dolReplaceInFile($destfile, $arrayreplacement);
939 }
940
941 // Launch doc generation
942 $currentdir = getcwd();
943 chdir($dirofmodule);
944
945 require_once DOL_DOCUMENT_ROOT.'/core/class/utils.class.php';
946 $utils = new Utils($this->db);
947
948 // Build HTML doc
949 $command = getDolGlobalString('MODULEBUILDER_ASCIIDOCTOR') . ' '.$destfile.' -n -o '.$dirofmoduledoc.'/'.$FILENAMEDOC;
950 $outfile = $dirofmoduletmp.'/out.tmp';
951
952 $resarray = $utils->executeCLI($command, $outfile);
953 if ($resarray['result'] != '0') {
954 $this->error = $resarray['error'].' '.$resarray['output'];
955 $this->errors[] = $this->error;
956 }
957 $result = ($resarray['result'] == 0) ? 1 : 0;
958 if ($result < 0 && empty($this->errors)) {
959 $this->error = $langs->trans("ErrorFailToGenerateFile", $FILENAMEDOC);
960 $this->errors[] = $this->error;
961 }
962
963 // Build PDF doc
964 $command = getDolGlobalString('MODULEBUILDER_ASCIIDOCTORPDF') . ' '.$destfile.' -n -o '.$dirofmoduledoc.'/'.$FILENAMEDOCPDF;
965 $outfile = $dirofmoduletmp.'/outpdf.tmp';
966 $resarray = $utils->executeCLI($command, $outfile);
967 if ($resarray['result'] != '0') {
968 $this->error = $resarray['error'].' '.$resarray['output'];
969 $this->errors[] = $this->error;
970 }
971 $result = ($resarray['result'] == 0) ? 1 : 0;
972 if ($result < 0 && empty($this->errors)) {
973 $this->error = $langs->trans("ErrorFailToGenerateFile", $FILENAMEDOCPDF);
974 $this->errors[] = $this->error;
975 }
976
977 chdir($currentdir);
978 } else {
979 $result = 0;
980 }
981
982 if ($result > 0) {
983 return 1;
984 } else {
985 $error++;
986 }
987 } else {
988 $error++;
989 $langs->load("errors");
990 $this->error = $langs->trans("ErrorCheckVersionIsDefined");
991 }
992
993 return -1;
994 }
995
1003 public function compressSyslogs()
1004 {
1005 global $conf;
1006
1007 if (empty($conf->loghandlers['mod_syslog_file'])) { // File Syslog disabled
1008 return 0;
1009 }
1010
1011 if (!function_exists('gzopen')) {
1012 $this->error = 'Support for gzopen not available in this PHP';
1013 return -1;
1014 }
1015
1016 require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
1017
1018 $nbSaves = intval(getDolGlobalString('SYSLOG_FILE_SAVES', 10));
1019
1020 if (!getDolGlobalString('SYSLOG_FILE')) {
1021 $mainlogdir = DOL_DATA_ROOT;
1022 $mainlog = 'dolibarr.log';
1023 } else {
1024 $mainlogfull = str_replace('DOL_DATA_ROOT', DOL_DATA_ROOT, $conf->global->SYSLOG_FILE);
1025 $mainlogdir = dirname($mainlogfull);
1026 $mainlog = basename($mainlogfull);
1027 }
1028
1029 $tabfiles = dol_dir_list(DOL_DATA_ROOT, 'files', 0, '^(dolibarr_.+|odt2pdf)\.log$'); // Also handle other log files like dolibarr_install.log
1030 $tabfiles[] = array('name' => $mainlog, 'path' => $mainlogdir);
1031
1032 foreach ($tabfiles as $file) {
1033 $logname = $file['name'];
1034 $logpath = $file['path'];
1035
1036 if (dol_is_file($logpath.'/'.$logname) && dol_filesize($logpath.'/'.$logname) > 0) { // If log file exists and is not empty
1037 // Handle already compressed files to rename them and add +1
1038
1039 $filter = '^'.preg_quote($logname, '/').'\.([0-9]+)\.gz$';
1040
1041 $gzfilestmp = dol_dir_list($logpath, 'files', 0, $filter);
1042 $gzfiles = array();
1043
1044 foreach ($gzfilestmp as $gzfile) {
1045 $tabmatches = array();
1046 preg_match('/'.$filter.'/i', $gzfile['name'], $tabmatches);
1047
1048 $numsave = intval($tabmatches[1]);
1049
1050 $gzfiles[$numsave] = $gzfile;
1051 }
1052
1053 krsort($gzfiles, SORT_NUMERIC);
1054
1055 foreach ($gzfiles as $numsave => $dummy) {
1056 if (dol_is_file($logpath.'/'.$logname.'.'.($numsave + 1).'.gz')) {
1057 return -2;
1058 }
1059
1060 if ($numsave >= $nbSaves) {
1061 dol_delete_file($logpath.'/'.$logname.'.'.$numsave.'.gz', 0, 0, 0, null, false, 0);
1062 } else {
1063 dol_move($logpath.'/'.$logname.'.'.$numsave.'.gz', $logpath.'/'.$logname.'.'.($numsave + 1).'.gz', '0', 1, 0, 0);
1064 }
1065 }
1066
1067 // Compress current file and recreate it
1068
1069 if ($nbSaves > 0) { // If $nbSaves is 1, we keep 1 archive .gz file, If 2, we keep 2 .gz files
1070 $gzfilehandle = gzopen($logpath.'/'.$logname.'.1.gz', 'wb9');
1071
1072 if (empty($gzfilehandle)) {
1073 $this->error = 'Failted to open file '.$logpath.'/'.$logname.'.1.gz';
1074 return -3;
1075 }
1076
1077 $sourcehandle = fopen($logpath.'/'.$logname, 'r');
1078
1079 if (empty($sourcehandle)) {
1080 $this->error = 'Failed to open file '.$logpath.'/'.$logname;
1081 return -4;
1082 }
1083
1084 while (!feof($sourcehandle)) {
1085 gzwrite($gzfilehandle, fread($sourcehandle, 512 * 1024)); // Read 512 kB at a time
1086 }
1087
1088 fclose($sourcehandle);
1089 gzclose($gzfilehandle);
1090
1091 dolChmod($logpath.'/'.$logname.'.1.gz');
1092 }
1093
1094 dol_delete_file($logpath.'/'.$logname, 0, 0, 0, null, false, 0);
1095
1096 // Create empty file
1097 $newlog = fopen($logpath.'/'.$logname, 'a+');
1098 fclose($newlog);
1099
1100 //var_dump($logpath.'/'.$logname." - ".octdec(empty($conf->global->MAIN_UMASK)?'0664':$conf->global->MAIN_UMASK));
1101 dolChmod($logpath.'/'.$logname);
1102 }
1103 }
1104
1105 $this->output = 'Archive log files (keeping last SYSLOG_FILE_SAVES='.$nbSaves.' files) done.';
1106 return 0;
1107 }
1108
1119 public function backupTables($outputfile, $tables = '*')
1120 {
1121 global $db, $langs;
1122 global $errormsg;
1123
1124 // Set to UTF-8
1125 if (is_a($db, 'DoliDBMysqli')) {
1127 $db->db->set_charset('utf8');
1128 } else {
1130 $db->query('SET NAMES utf8');
1131 $db->query('SET CHARACTER SET utf8');
1132 }
1133
1134 //get all of the tables
1135 if ($tables == '*') {
1136 $tables = array();
1137 $result = $db->query('SHOW FULL TABLES WHERE Table_type = \'BASE TABLE\'');
1138 while ($row = $db->fetch_row($result)) {
1139 $tables[] = $row[0];
1140 }
1141 } else {
1142 $tables = is_array($tables) ? $tables : explode(',', $tables);
1143 }
1144
1145 //cycle through
1146 $handle = fopen($outputfile, 'w+');
1147 if (fwrite($handle, '') === false) {
1148 $langs->load("errors");
1149 dol_syslog("Failed to open file ".$outputfile, LOG_ERR);
1150 $errormsg = $langs->trans("ErrorFailedToWriteInDir");
1151 return -1;
1152 }
1153
1154 // Print headers and global mysql config vars
1155 $sqlhead = '';
1156 $sqlhead .= "-- ".$db::LABEL." dump via php with Dolibarr ".DOL_VERSION."
1157--
1158-- Host: ".$db->db->host_info." Database: ".$db->database_name."
1159-- ------------------------------------------------------
1160-- Server version ".$db->db->server_info."
1161
1162;
1163;
1164;
1165;
1166;
1167;
1168;
1169;
1170;
1171;
1172
1173";
1174
1175 if (GETPOST("nobin_disable_fk")) {
1176 $sqlhead .= "SET FOREIGN_KEY_CHECKS=0;\n";
1177 }
1178 //$sqlhead .= "SET SQL_MODE=\"NO_AUTO_VALUE_ON_ZERO\";\n";
1179 if (GETPOST("nobin_use_transaction")) {
1180 $sqlhead .= "SET AUTOCOMMIT=0;\nSTART TRANSACTION;\n";
1181 }
1182
1183 fwrite($handle, $sqlhead);
1184
1185 $ignore = '';
1186 if (GETPOST("nobin_sql_ignore")) {
1187 $ignore = 'IGNORE ';
1188 }
1189 $delayed = '';
1190 if (GETPOST("nobin_delayed")) {
1191 $delayed = 'DELAYED ';
1192 }
1193
1194 // Process each table and print their definition + their datas
1195 foreach ($tables as $table) {
1196 // Saving the table structure
1197 fwrite($handle, "\n--\n-- Table structure for table `".$table."`\n--\n");
1198
1199 if (GETPOST("nobin_drop")) {
1200 fwrite($handle, "DROP TABLE IF EXISTS `".$table."`;\n"); // Dropping table if exists prior to re create it
1201 }
1202 fwrite($handle, "/*!40101 SET @saved_cs_client = @@character_set_client */;\n");
1203 fwrite($handle, "/*!40101 SET character_set_client = utf8 */;\n");
1204 $resqldrop = $db->query('SHOW CREATE TABLE '.$table);
1205 $row2 = $db->fetch_row($resqldrop);
1206 if (empty($row2[1])) {
1207 fwrite($handle, "\n-- WARNING: Show create table ".$table." return empty string when it should not.\n");
1208 } else {
1209 fwrite($handle, $row2[1].";\n");
1210 //fwrite($handle,"/*!40101 SET character_set_client = @saved_cs_client */;\n\n");
1211
1212 // Dumping the data (locking the table and disabling the keys check while doing the process)
1213 fwrite($handle, "\n--\n-- Dumping data for table `".$table."`\n--\n");
1214 if (!GETPOST("nobin_nolocks")) {
1215 fwrite($handle, "LOCK TABLES `".$table."` WRITE;\n"); // Lock the table before inserting data (when the data will be imported back)
1216 }
1217 if (GETPOST("nobin_disable_fk")) {
1218 fwrite($handle, "ALTER TABLE `".$table."` DISABLE KEYS;\n");
1219 } else {
1220 fwrite($handle, "/*!40000 ALTER TABLE `".$table."` DISABLE KEYS */;\n");
1221 }
1222
1223 $sql = "SELECT * FROM ".$table; // Here SELECT * is allowed because we don't have definition of columns to take
1224 $result = $db->query($sql);
1225 while ($row = $db->fetch_row($result)) {
1226 // For each row of data we print a line of INSERT
1227 fwrite($handle, "INSERT ".$delayed.$ignore."INTO ".$table." VALUES (");
1228 $columns = count($row);
1229 for ($j = 0; $j < $columns; $j++) {
1230 // 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)
1231 if ($row[$j] == null && !is_string($row[$j])) {
1232 // IMPORTANT: if the field is NULL we set it NULL
1233 $row[$j] = 'NULL';
1234 } elseif (is_string($row[$j]) && $row[$j] == '') {
1235 // if it's an empty string, we set it as an empty string
1236 $row[$j] = "''";
1237 } 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)
1238 // if it's a number, we return it as-is
1239 // $row[$j] = $row[$j];
1240 } else { // else for all other cases we escape the value and put quotes around
1241 $row[$j] = addslashes($row[$j]);
1242 $row[$j] = preg_replace("#\n#", "\\n", $row[$j]);
1243 $row[$j] = "'".$row[$j]."'";
1244 }
1245 }
1246 fwrite($handle, implode(',', $row).");\n");
1247 }
1248 if (GETPOST("nobin_disable_fk")) {
1249 fwrite($handle, "ALTER TABLE `".$table."` ENABLE KEYS;\n"); // Enabling back the keys/index checking
1250 }
1251 if (!GETPOST("nobin_nolocks")) {
1252 fwrite($handle, "UNLOCK TABLES;\n"); // Unlocking the table
1253 }
1254 fwrite($handle, "\n\n\n");
1255 }
1256 }
1257
1258 /* Backup Procedure structure*/
1259 /*
1260 $result = $db->query('SHOW PROCEDURE STATUS');
1261 if ($db->num_rows($result) > 0)
1262 {
1263 while ($row = $db->fetch_row($result)) { $procedures[] = $row[1]; }
1264 foreach($procedures as $proc)
1265 {
1266 fwrite($handle,"DELIMITER $$\n\n");
1267 fwrite($handle,"DROP PROCEDURE IF EXISTS '$name'.'$proc'$$\n");
1268 $resqlcreateproc=$db->query("SHOW CREATE PROCEDURE '$proc'");
1269 $row2 = $db->fetch_row($resqlcreateproc);
1270 fwrite($handle,"\n".$row2[2]."$$\n\n");
1271 fwrite($handle,"DELIMITER ;\n\n");
1272 }
1273 }
1274 */
1275 /* Backup Procedure structure*/
1276
1277 // Write the footer (restore the previous database settings)
1278 $sqlfooter = "\n\n";
1279 if (GETPOST("nobin_use_transaction")) {
1280 $sqlfooter .= "COMMIT;\n";
1281 }
1282 if (GETPOST("nobin_disable_fk")) {
1283 $sqlfooter .= "SET FOREIGN_KEY_CHECKS=1;\n";
1284 }
1285 $sqlfooter .= "\n\n-- Dump completed on ".date('Y-m-d G-i-s');
1286 fwrite($handle, $sqlfooter);
1287
1288 fclose($handle);
1289
1290 return 1;
1291 }
1292
1306 public function sendBackup($sendto = '', $from = '', $subject = '', $message = '', $filename = '', $filter = '', $sizelimit = 100000000)
1307 {
1308 global $conf, $langs;
1310
1311 $filepath = '';
1312 $filesize = -1;
1313 $output = '';
1314 $error = 0;
1315 $mimetype = '';
1316
1317 if (!empty($from)) {
1318 $from = dol_escape_htmltag($from);
1319 } elseif (getDolGlobalString('MAIN_MAIL_EMAIL_FROM')) {
1320 $from = dol_escape_htmltag(getDolGlobalString('MAIN_MAIL_EMAIL_FROM'));
1321 } else {
1322 $error++;
1323 }
1324
1325 if (!empty($sendto)) {
1326 $sendto = dol_escape_htmltag($sendto);
1327 } elseif (getDolGlobalString('MAIN_INFO_SOCIETE_MAIL')) {
1328 $sendto = dol_escape_htmltag(getDolGlobalString('MAIN_INFO_SOCIETE_MAIL'));
1329 } else {
1330 $error++;
1331 }
1332
1333 if (!empty($subject)) {
1334 $subject = dol_escape_htmltag($subject);
1335 } else {
1336 $subject = dol_escape_htmltag($langs->trans('MakeSendLocalDatabaseDumpShort'));
1337 }
1338
1339 if (empty($message)) {
1340 $message = dol_escape_htmltag($langs->trans('MakeSendLocalDatabaseDumpShort'));
1341 }
1342
1343 $tmpfiles = array();
1344 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1345 if ($filename) {
1346 if (dol_is_file($conf->admin->dir_output.'/backup/'.$filename)) {
1347 $tmpfiles = dol_most_recent_file($conf->admin->dir_output.'/backup', $filename);
1348 }
1349 } else {
1350 $tmpfiles = dol_most_recent_file($conf->admin->dir_output.'/backup', $filter);
1351 }
1352 if ($tmpfiles && is_array($tmpfiles)) {
1353 foreach ($tmpfiles as $key => $val) {
1354 if ($key == 'fullname') {
1355 $filepath = array($val);
1356 $filesize = dol_filesize($val);
1357 }
1358 if ($key == 'type') {
1359 $mimetype = array($val);
1360 }
1361 if ($key == 'relativename') {
1362 $filename = array($val);
1363 }
1364 }
1365 }
1366
1367 if ($filepath) {
1368 if ($filesize > $sizelimit) {
1369 $message .= '<br>'.$langs->trans("BackupIsTooLargeSend");
1370 $documenturl = $dolibarr_main_url_root.'/document.php?modulepart=systemtools&atachement=1&file=backup/'.urlencode($filename[0]);
1371 $message .= '<br><a href='.$documenturl.'>Download link</a>';
1372 $filepath = '';
1373 $mimetype = '';
1374 $filename = '';
1375 }
1376 } else {
1377 $output = 'No backup file found';
1378 $error++;
1379 }
1380
1381 $mailfile = null;
1382 if (!$error) {
1383 include_once DOL_DOCUMENT_ROOT . '/core/class/CMailFile.class.php';
1384 $mailfile = new CMailFile($subject, $sendto, $from, $message, $filepath, $mimetype, $filename, '', '', 0, 1);
1385 // $mailfile = new CMailFile($subject, $sendto, $from, $message, $filepath, $mimetype, $filename, '', '', 0, 1);
1386 if ($mailfile->error) {
1387 $error++;
1388 $output = $mailfile->error;
1389 }
1390 }
1391
1392 $result = false;
1393 $output = '';
1394 if (!$error && $mailfile !== null) {
1395 $result = $mailfile->sendfile();
1396 if (!$result) {
1397 $error++;
1398 $output = $mailfile->error;
1399 }
1400 }
1401
1402 dol_syslog(__METHOD__, LOG_DEBUG);
1403
1404 $this->error = "Error sending backup file ".((string) $error);
1405 $this->output = $output;
1406
1407 if ($result) {
1408 return 0;
1409 } else {
1410 return -1;
1411 }
1412 }
1413
1421 public function cleanUnfinishedCronjob()
1422 {
1423 global $db, $user;
1424 dol_syslog("Utils::cleanUnfinishedCronjob Starting cleaning");
1425
1426 // Import Cronjob class if not present
1427 require_once DOL_DOCUMENT_ROOT . '/cron/class/cronjob.class.php';
1428
1429 // Get this job object
1430 $this_job = new Cronjob($db);
1431 $this_job->fetch(-1, 'Utils', 'cleanUnfinishedCronjob');
1432 if (empty($this_job->id) || !empty($this_job->error)) {
1433 dol_syslog("Utils::cleanUnfinishedCronjob Unable to fetch himself: ".$this_job->error, LOG_ERR);
1434 return -1;
1435 }
1436
1437 // Set this job processing to 0 to avoid being locked by his processing state
1438 $this_job->processing = 0;
1439 if ($this_job->update($user) < 0) {
1440 dol_syslog("Utils::cleanUnfinishedCronjob Unable to update himself: ".implode(', ', $this_job->errors), LOG_ERR);
1441 return -1;
1442 }
1443
1444 $cron_job = new Cronjob($db);
1445 $cron_job->fetchAll('DESC', 't.rowid', 100, 0, 1, [], 1); // Fetch jobs that are currently running
1446
1447 // Iterate over all jobs in processing (this can't be this job since his state is set to 0 before)
1448 foreach ($cron_job->lines as $job_line) {
1449 // Avoid job with no PID
1450 if (empty($job_line->pid)) {
1451 dol_syslog("Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id." don't have a PID", LOG_DEBUG);
1452 continue;
1453 }
1454
1455 $job = new Cronjob($db);
1456 $job->fetch($job_line->id);
1457 if (empty($job->id) || !empty($job->error)) {
1458 dol_syslog("Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id." can't be fetch: ".$job->error, LOG_ERR);
1459 continue;
1460 }
1461
1462 // Calling posix_kill with the 0 kill signal will return true if the process is running, false otherwise.
1463 if (! posix_kill($job->pid, 0)) {
1464 // Clean processing and pid values
1465 $job->processing = 0;
1466 $job->pid = null;
1467
1468 // Set last result as an error and add the reason on the last output
1469 $job->lastresult = strval(-1);
1470 $job->lastoutput = 'Job killed by job cleanUnfinishedCronjob';
1471
1472 if ($job->update($user) < 0) {
1473 dol_syslog("Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id." can't be updated: ".implode(', ', $job->errors), LOG_ERR);
1474 continue;
1475 }
1476 dol_syslog("Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id." cleaned");
1477 }
1478 }
1479
1480 dol_syslog("Utils::cleanUnfinishedCronjob Cleaning completed");
1481 return 0;
1482 }
1483}
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
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:3284
dolMd2Asciidoc($content, $parser='dolibarr', $replaceimagepath=null)
Function to parse MD content into ASCIIDOC.