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