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