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