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