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