dolibarr  19.0.0-dev
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 (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  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 (isModEnabled('api')) {
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  dolChmod($outputfile);
498  } else {
499  $langs->load("errors");
500  dol_syslog("Failed to open file ".$outputfile, LOG_ERR);
501  $errormsg = $langs->trans("ErrorFailedToWriteInDir");
502  }
503 
504  // Get errorstring
505  if ($compression == 'none') {
506  $handle = fopen($outputfile, 'r');
507  } elseif ($compression == 'gz') {
508  $handle = gzopen($outputfile, 'r');
509  } elseif ($compression == 'bz') {
510  $handle = bzopen($outputfile, 'r');
511  } elseif ($compression == 'zstd') {
512  $handle = fopen($outputfile, 'r');
513  }
514  if ($handle) {
515  // Get 2048 first chars of error message.
516  $errormsg = fgets($handle, 2048);
517  //$ok=0;$errormsg=''; To force error
518 
519  // Close file
520  if ($compression == 'none') {
521  fclose($handle);
522  } elseif ($compression == 'gz') {
523  gzclose($handle);
524  } elseif ($compression == 'bz') {
525  bzclose($handle);
526  } elseif ($compression == 'zstd') {
527  fclose($handle);
528  }
529  if ($ok && preg_match('/^-- (MySql|MariaDB)/i', $errormsg)) { // No error
530  $errormsg = '';
531  } else {
532  // Renommer fichier sortie en fichier erreur
533  //print "$outputfile -> $outputerror";
534  @dol_delete_file($outputerror, 1, 0, 0, null, false, 0);
535  @rename($outputfile, $outputerror);
536  // Si safe_mode on et command hors du parametre exec, on a un fichier out vide donc errormsg vide
537  if (!$errormsg) {
538  $langs->load("errors");
539  $errormsg = $langs->trans("ErrorFailedToRunExternalCommand");
540  }
541  }
542  }
543  // Fin execution commande
544 
545  $this->output = $errormsg;
546  $this->error = $errormsg;
547  $this->result = array("commandbackuplastdone" => $command." ".$paramcrypted, "commandbackuptorun" => "");
548  //if (empty($this->output)) $this->output=$this->result['commandbackuplastdone'];
549  }
550 
551  // MYSQL NO BIN
552  if ($type == 'mysqlnobin') {
553  $outputfile = $outputdir.'/'.$file;
554  $outputfiletemp = $outputfile.'-TMP.sql';
555  // for compression format, we add extension
556  $compression = $compression ? $compression : 'none';
557  if ($compression == 'gz') {
558  $outputfile .= '.gz';
559  }
560  if ($compression == 'bz') {
561  $outputfile .= '.bz2';
562  }
563  $outputerror = $outputfile.'.err';
564  dol_mkdir($conf->admin->dir_output.'/backup');
565 
566  if ($compression == 'gz' or $compression == 'bz') {
567  $this->backupTables($outputfiletemp);
568  dol_compress_file($outputfiletemp, $outputfile, $compression);
569  unlink($outputfiletemp);
570  } else {
571  $this->backupTables($outputfile);
572  }
573 
574  $this->output = "";
575  $this->result = array("commandbackuplastdone" => "", "commandbackuptorun" => "");
576  }
577 
578  // POSTGRESQL
579  if ($type == 'postgresql' || $type == 'pgsql') {
580  $cmddump = $conf->global->SYSTEMTOOLS_POSTGRESQLDUMP;
581 
582  $outputfile = $outputdir.'/'.$file;
583  // for compression format, we add extension
584  $compression = $compression ? $compression : 'none';
585  if ($compression == 'gz') {
586  $outputfile .= '.gz';
587  }
588  if ($compression == 'bz') {
589  $outputfile .= '.bz2';
590  }
591  $outputerror = $outputfile.'.err';
592  dol_mkdir($conf->admin->dir_output.'/backup');
593 
594  // Parameteres execution
595  $command = $cmddump;
596  $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.
597  if (preg_match("/\s/", $command)) {
598  $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
599  }
600 
601  //$param=escapeshellarg($dolibarr_main_db_name)." -h ".escapeshellarg($dolibarr_main_db_host)." -u ".escapeshellarg($dolibarr_main_db_user)." -p".escapeshellarg($dolibarr_main_db_pass);
602  //$param="-F c";
603  $param = "-F p";
604  $param .= " --no-tablespaces --inserts -h ".$dolibarr_main_db_host;
605  $param .= " -U ".$dolibarr_main_db_user;
606  if (!empty($dolibarr_main_db_port)) {
607  $param .= " -p ".$dolibarr_main_db_port;
608  }
609  if (GETPOST("sql_compat") && GETPOST("sql_compat") == 'ANSI') {
610  $param .= " --disable-dollar-quoting";
611  }
612  if (GETPOST("drop_database")) {
613  $param .= " -c -C";
614  }
615  if (GETPOST("sql_structure")) {
616  if (GETPOST("drop")) {
617  $param .= " --add-drop-table";
618  }
619  if (!GETPOST("sql_data")) {
620  $param .= " -s";
621  }
622  }
623  if (GETPOST("sql_data")) {
624  if (!GETPOST("sql_structure")) {
625  $param .= " -a";
626  }
627  if (GETPOST("showcolumns")) {
628  $param .= " -c";
629  }
630  }
631  $param .= ' -f "'.$outputfile.'"';
632  //if ($compression == 'none')
633  if ($compression == 'gz') {
634  $param .= ' -Z 9';
635  }
636  //if ($compression == 'bz')
637  $paramcrypted = $param;
638  $paramclear = $param;
639  /*if (!empty($dolibarr_main_db_pass))
640  {
641  $paramcrypted.=" -W".preg_replace('/./i','*',$dolibarr_main_db_pass);
642  $paramclear.=" -W".$dolibarr_main_db_pass;
643  }*/
644  $paramcrypted .= " -w ".$dolibarr_main_db_name;
645  $paramclear .= " -w ".$dolibarr_main_db_name;
646 
647  $this->output = "";
648  $this->result = array("commandbackuplastdone" => "", "commandbackuptorun" => $command." ".$paramcrypted);
649  }
650 
651  // Clean old files
652  if (!$errormsg && $keeplastnfiles > 0) {
653  $tmpfiles = dol_dir_list($conf->admin->dir_output.'/backup', 'files', 0, '', '(\.err|\.old|\.sav)$', 'date', SORT_DESC);
654  $i = 0;
655  if (is_array($tmpfiles)) {
656  foreach ($tmpfiles as $key => $val) {
657  $i++;
658  if ($i <= $keeplastnfiles) {
659  continue;
660  }
661  dol_delete_file($val['fullname'], 0, 0, 0, null, false, 0);
662  }
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  dolChmod($outputfile);
741  }
742 
743  // Update with result
744  if (is_array($output_arr) && count($output_arr) > 0) {
745  foreach ($output_arr as $val) {
746  $output .= $val.($execmethod == 2 ? '' : "\n");
747  }
748  }
749 
750  dol_syslog("Utils::executeCLI result=".$result." output=".$output." error=".$error, LOG_DEBUG);
751 
752  return array('result'=>$result, 'output'=>$output, 'error'=>$error);
753  }
754 
761  public function generateDoc($module)
762  {
763  global $conf, $langs, $user, $mysoc;
764  global $dirins;
765 
766  $error = 0;
767 
768  $modulelowercase = strtolower($module);
769  $now = dol_now();
770 
771  // Dir for module
772  $dir = $dirins.'/'.$modulelowercase;
773  // Zip file to build
774  $FILENAMEDOC = '';
775 
776  // Load module
777  dol_include_once($modulelowercase.'/core/modules/mod'.$module.'.class.php');
778  $class = 'mod'.$module;
779 
780  if (class_exists($class)) {
781  try {
782  $moduleobj = new $class($this->db);
783  } catch (Exception $e) {
784  $error++;
785  dol_print_error($e->getMessage());
786  }
787  } else {
788  $error++;
789  $langs->load("errors");
790  dol_print_error($langs->trans("ErrorFailedToLoadModuleDescriptorForXXX", $module));
791  exit;
792  }
793 
794  $arrayversion = explode('.', $moduleobj->version, 3);
795  if (count($arrayversion)) {
796  $FILENAMEASCII = strtolower($module).'.asciidoc';
797  $FILENAMEDOC = strtolower($module).'.html';
798  $FILENAMEDOCPDF = strtolower($module).'.pdf';
799 
800  $dirofmodule = dol_buildpath(strtolower($module), 0);
801  $dirofmoduledoc = dol_buildpath(strtolower($module), 0).'/doc';
802  $dirofmoduletmp = dol_buildpath(strtolower($module), 0).'/doc/temp';
803  $outputfiledoc = $dirofmoduledoc.'/'.$FILENAMEDOC;
804  if ($dirofmoduledoc) {
805  if (!dol_is_dir($dirofmoduledoc)) {
806  dol_mkdir($dirofmoduledoc);
807  }
808  if (!dol_is_dir($dirofmoduletmp)) {
809  dol_mkdir($dirofmoduletmp);
810  }
811  if (!is_writable($dirofmoduletmp)) {
812  $this->error = 'Dir '.$dirofmoduletmp.' does not exists or is not writable';
813  return -1;
814  }
815 
816  if (empty($conf->global->MODULEBUILDER_ASCIIDOCTOR) && empty($conf->global->MODULEBUILDER_ASCIIDOCTORPDF)) {
817  $this->error = 'Setup of module ModuleBuilder not complete';
818  return -1;
819  }
820 
821  // Copy some files into temp directory, so instruction include::ChangeLog.md[] will works inside the asciidoc file.
822  dol_copy($dirofmodule.'/README.md', $dirofmoduletmp.'/README.md', 0, 1);
823  dol_copy($dirofmodule.'/ChangeLog.md', $dirofmoduletmp.'/ChangeLog.md', 0, 1);
824 
825  // Replace into README.md and ChangeLog.md (in case they are included into documentation with tag __README__ or __CHANGELOG__)
826  $arrayreplacement = array();
827  $arrayreplacement['/^#\s.*/m'] = ''; // Remove first level of title into .md files
828  $arrayreplacement['/^#/m'] = '##'; // Add on # to increase level
829 
830  dolReplaceInFile($dirofmoduletmp.'/README.md', $arrayreplacement, '', 0, 0, 1);
831  dolReplaceInFile($dirofmoduletmp.'/ChangeLog.md', $arrayreplacement, '', 0, 0, 1);
832 
833 
834  $destfile = $dirofmoduletmp.'/'.$FILENAMEASCII;
835 
836  $fhandle = fopen($destfile, 'w+');
837  if ($fhandle) {
838  $specs = dol_dir_list(dol_buildpath(strtolower($module).'/doc', 0), 'files', 1, '(\.md|\.asciidoc)$', array('\/temp\/'));
839 
840  $i = 0;
841  foreach ($specs as $spec) {
842  if (preg_match('/notindoc/', $spec['relativename'])) {
843  continue; // Discard file
844  }
845  if (preg_match('/example/', $spec['relativename'])) {
846  continue; // Discard file
847  }
848  if (preg_match('/disabled/', $spec['relativename'])) {
849  continue; // Discard file
850  }
851 
852  $pathtofile = strtolower($module).'/doc/'.$spec['relativename'];
853  $format = 'asciidoc';
854  if (preg_match('/\.md$/i', $spec['name'])) {
855  $format = 'markdown';
856  }
857 
858  $filecursor = @file_get_contents($spec['fullname']);
859  if ($filecursor) {
860  fwrite($fhandle, ($i ? "\n<<<\n\n" : "").$filecursor."\n");
861  } else {
862  $this->error = 'Failed to concat content of file '.$spec['fullname'];
863  return -1;
864  }
865 
866  $i++;
867  }
868 
869  fclose($fhandle);
870 
871  $contentreadme = file_get_contents($dirofmoduletmp.'/README.md');
872  $contentchangelog = file_get_contents($dirofmoduletmp.'/ChangeLog.md');
873 
874  include DOL_DOCUMENT_ROOT.'/core/lib/parsemd.lib.php';
875 
876  //var_dump($phpfileval['fullname']);
877  $arrayreplacement = array(
878  'mymodule'=>strtolower($module),
879  'MyModule'=>$module,
880  'MYMODULE'=>strtoupper($module),
881  'My module'=>$module,
882  'my module'=>$module,
883  'Mon module'=>$module,
884  'mon module'=>$module,
885  'htdocs/modulebuilder/template'=>strtolower($module),
886  '__MYCOMPANY_NAME__'=>$mysoc->name,
887  '__KEYWORDS__'=>$module,
888  '__USER_FULLNAME__'=>$user->getFullName($langs),
889  '__USER_EMAIL__'=>$user->email,
890  '__YYYY-MM-DD__'=>dol_print_date($now, 'dayrfc'),
891  '---Put here your own copyright and developer email---'=>dol_print_date($now, 'dayrfc').' '.$user->getFullName($langs).($user->email ? ' <'.$user->email.'>' : ''),
892  '__DATA_SPECIFICATION__'=>'Not yet available',
893  '__README__'=>dolMd2Asciidoc($contentreadme),
894  '__CHANGELOG__'=>dolMd2Asciidoc($contentchangelog),
895  );
896 
897  dolReplaceInFile($destfile, $arrayreplacement);
898  }
899 
900  // Launch doc generation
901  $currentdir = getcwd();
902  chdir($dirofmodule);
903 
904  require_once DOL_DOCUMENT_ROOT.'/core/class/utils.class.php';
905  $utils = new Utils($this->db);
906 
907  // Build HTML doc
908  $command = $conf->global->MODULEBUILDER_ASCIIDOCTOR.' '.$destfile.' -n -o '.$dirofmoduledoc.'/'.$FILENAMEDOC;
909  $outfile = $dirofmoduletmp.'/out.tmp';
910 
911  $resarray = $utils->executeCLI($command, $outfile);
912  if ($resarray['result'] != '0') {
913  $this->error = $resarray['error'].' '.$resarray['output'];
914  $this->errors[] = $this->error;
915  }
916  $result = ($resarray['result'] == 0) ? 1 : 0;
917  if ($result < 0 && empty($this->errors)) {
918  $this->error = $langs->trans("ErrorFailToGenerateFile", $FILENAMEDOC);
919  $this->errors[] = $this->error;
920  }
921 
922  // Build PDF doc
923  $command = $conf->global->MODULEBUILDER_ASCIIDOCTORPDF.' '.$destfile.' -n -o '.$dirofmoduledoc.'/'.$FILENAMEDOCPDF;
924  $outfile = $dirofmoduletmp.'/outpdf.tmp';
925  $resarray = $utils->executeCLI($command, $outfile);
926  if ($resarray['result'] != '0') {
927  $this->error = $resarray['error'].' '.$resarray['output'];
928  $this->errors[] = $this->error;
929  }
930  $result = ($resarray['result'] == 0) ? 1 : 0;
931  if ($result < 0 && empty($this->errors)) {
932  $this->error = $langs->trans("ErrorFailToGenerateFile", $FILENAMEDOCPDF);
933  $this->errors[] = $this->error;
934  }
935 
936  chdir($currentdir);
937  } else {
938  $result = 0;
939  }
940 
941  if ($result > 0) {
942  return 1;
943  } else {
944  $error++;
945  }
946  } else {
947  $error++;
948  $langs->load("errors");
949  $this->error = $langs->trans("ErrorCheckVersionIsDefined");
950  }
951 
952  return -1;
953  }
954 
962  public function compressSyslogs()
963  {
964  global $conf;
965 
966  if (empty($conf->loghandlers['mod_syslog_file'])) { // File Syslog disabled
967  return 0;
968  }
969 
970  if (!function_exists('gzopen')) {
971  $this->error = 'Support for gzopen not available in this PHP';
972  return -1;
973  }
974 
975  dol_include_once('/core/lib/files.lib.php');
976 
977  $nbSaves = intval(getDolGlobalString('SYSLOG_FILE_SAVES', 10));
978 
979  if (empty($conf->global->SYSLOG_FILE)) {
980  $mainlogdir = DOL_DATA_ROOT;
981  $mainlog = 'dolibarr.log';
982  } else {
983  $mainlogfull = str_replace('DOL_DATA_ROOT', DOL_DATA_ROOT, $conf->global->SYSLOG_FILE);
984  $mainlogdir = dirname($mainlogfull);
985  $mainlog = basename($mainlogfull);
986  }
987 
988  $tabfiles = dol_dir_list(DOL_DATA_ROOT, 'files', 0, '^(dolibarr_.+|odt2pdf)\.log$'); // Also handle other log files like dolibarr_install.log
989  $tabfiles[] = array('name' => $mainlog, 'path' => $mainlogdir);
990 
991  foreach ($tabfiles as $file) {
992  $logname = $file['name'];
993  $logpath = $file['path'];
994 
995  if (dol_is_file($logpath.'/'.$logname) && dol_filesize($logpath.'/'.$logname) > 0) { // If log file exists and is not empty
996  // Handle already compressed files to rename them and add +1
997 
998  $filter = '^'.preg_quote($logname, '/').'\.([0-9]+)\.gz$';
999 
1000  $gzfilestmp = dol_dir_list($logpath, 'files', 0, $filter);
1001  $gzfiles = array();
1002 
1003  foreach ($gzfilestmp as $gzfile) {
1004  $tabmatches = array();
1005  preg_match('/'.$filter.'/i', $gzfile['name'], $tabmatches);
1006 
1007  $numsave = intval($tabmatches[1]);
1008 
1009  $gzfiles[$numsave] = $gzfile;
1010  }
1011 
1012  krsort($gzfiles, SORT_NUMERIC);
1013 
1014  foreach ($gzfiles as $numsave => $dummy) {
1015  if (dol_is_file($logpath.'/'.$logname.'.'.($numsave + 1).'.gz')) {
1016  return -2;
1017  }
1018 
1019  if ($numsave >= $nbSaves) {
1020  dol_delete_file($logpath.'/'.$logname.'.'.$numsave.'.gz', 0, 0, 0, null, false, 0);
1021  } else {
1022  dol_move($logpath.'/'.$logname.'.'.$numsave.'.gz', $logpath.'/'.$logname.'.'.($numsave + 1).'.gz', 0, 1, 0, 0);
1023  }
1024  }
1025 
1026  // Compress current file and recreate it
1027 
1028  if ($nbSaves > 0) { // If $nbSaves is 1, we keep 1 archive .gz file, If 2, we keep 2 .gz files
1029  $gzfilehandle = gzopen($logpath.'/'.$logname.'.1.gz', 'wb9');
1030 
1031  if (empty($gzfilehandle)) {
1032  $this->error = 'Failted to open file '.$logpath.'/'.$logname.'.1.gz';
1033  return -3;
1034  }
1035 
1036  $sourcehandle = fopen($logpath.'/'.$logname, 'r');
1037 
1038  if (empty($sourcehandle)) {
1039  $this->error = 'Failed to open file '.$logpath.'/'.$logname;
1040  return -4;
1041  }
1042 
1043  while (!feof($sourcehandle)) {
1044  gzwrite($gzfilehandle, fread($sourcehandle, 512 * 1024)); // Read 512 kB at a time
1045  }
1046 
1047  fclose($sourcehandle);
1048  gzclose($gzfilehandle);
1049 
1050  dolChmod($logpath.'/'.$logname.'.1.gz');
1051  }
1052 
1053  dol_delete_file($logpath.'/'.$logname, 0, 0, 0, null, false, 0);
1054 
1055  // Create empty file
1056  $newlog = fopen($logpath.'/'.$logname, 'a+');
1057  fclose($newlog);
1058 
1059  //var_dump($logpath.'/'.$logname." - ".octdec(empty($conf->global->MAIN_UMASK)?'0664':$conf->global->MAIN_UMASK));
1060  dolChmod($logpath.'/'.$logname);
1061  }
1062  }
1063 
1064  $this->output = 'Archive log files (keeping last SYSLOG_FILE_SAVES='.$nbSaves.' files) done.';
1065  return 0;
1066  }
1067 
1078  public function backupTables($outputfile, $tables = '*')
1079  {
1080  global $db, $langs;
1081  global $errormsg;
1082 
1083  // Set to UTF-8
1084  if (is_a($db, 'DoliDBMysqli')) {
1086  $db->db->set_charset('utf8');
1087  } else {
1089  $db->query('SET NAMES utf8');
1090  $db->query('SET CHARACTER SET utf8');
1091  }
1092 
1093  //get all of the tables
1094  if ($tables == '*') {
1095  $tables = array();
1096  $result = $db->query('SHOW FULL TABLES WHERE Table_type = \'BASE TABLE\'');
1097  while ($row = $db->fetch_row($result)) {
1098  $tables[] = $row[0];
1099  }
1100  } else {
1101  $tables = is_array($tables) ? $tables : explode(',', $tables);
1102  }
1103 
1104  //cycle through
1105  $handle = fopen($outputfile, 'w+');
1106  if (fwrite($handle, '') === false) {
1107  $langs->load("errors");
1108  dol_syslog("Failed to open file ".$outputfile, LOG_ERR);
1109  $errormsg = $langs->trans("ErrorFailedToWriteInDir");
1110  return -1;
1111  }
1112 
1113  // Print headers and global mysql config vars
1114  $sqlhead = '';
1115  $sqlhead .= "-- ".$db::LABEL." dump via php with Dolibarr ".DOL_VERSION."
1116 --
1117 -- Host: ".$db->db->host_info." Database: ".$db->database_name."
1118 -- ------------------------------------------------------
1119 -- Server version ".$db->db->server_info."
1120 ;;;;;;;;;;
1131 
1132 ";
1133 
1134  if (GETPOST("nobin_disable_fk")) {
1135  $sqlhead .= "SET FOREIGN_KEY_CHECKS=0;\n";
1136  }
1137  //$sqlhead .= "SET SQL_MODE=\"NO_AUTO_VALUE_ON_ZERO\";\n";
1138  if (GETPOST("nobin_use_transaction")) {
1139  $sqlhead .= "SET AUTOCOMMIT=0;\nSTART TRANSACTION;\n";
1140  }
1141 
1142  fwrite($handle, $sqlhead);
1143 
1144  $ignore = '';
1145  if (GETPOST("nobin_sql_ignore")) {
1146  $ignore = 'IGNORE ';
1147  }
1148  $delayed = '';
1149  if (GETPOST("nobin_delayed")) {
1150  $delayed = 'DELAYED ';
1151  }
1152 
1153  // Process each table and print their definition + their datas
1154  foreach ($tables as $table) {
1155  // Saving the table structure
1156  fwrite($handle, "\n--\n-- Table structure for table `".$table."`\n--\n");
1157 
1158  if (GETPOST("nobin_drop")) {
1159  fwrite($handle, "DROP TABLE IF EXISTS `".$table."`;\n"); // Dropping table if exists prior to re create it
1160  }
1161  fwrite($handle, "/*!40101 SET @saved_cs_client = @@character_set_client */;\n");
1162  fwrite($handle, "/*!40101 SET character_set_client = utf8 */;\n");
1163  $resqldrop = $db->query('SHOW CREATE TABLE '.$table);
1164  $row2 = $db->fetch_row($resqldrop);
1165  if (empty($row2[1])) {
1166  fwrite($handle, "\n-- WARNING: Show create table ".$table." return empy string when it should not.\n");
1167  } else {
1168  fwrite($handle, $row2[1].";\n");
1169  //fwrite($handle,"/*!40101 SET character_set_client = @saved_cs_client */;\n\n");
1170 
1171  // Dumping the data (locking the table and disabling the keys check while doing the process)
1172  fwrite($handle, "\n--\n-- Dumping data for table `".$table."`\n--\n");
1173  if (!GETPOST("nobin_nolocks")) {
1174  fwrite($handle, "LOCK TABLES `".$table."` WRITE;\n"); // Lock the table before inserting data (when the data will be imported back)
1175  }
1176  if (GETPOST("nobin_disable_fk")) {
1177  fwrite($handle, "ALTER TABLE `".$table."` DISABLE KEYS;\n");
1178  } else {
1179  fwrite($handle, "/*!40000 ALTER TABLE `".$table."` DISABLE KEYS */;\n");
1180  }
1181 
1182  $sql = "SELECT * FROM ".$table; // Here SELECT * is allowed because we don't have definition of columns to take
1183  $result = $db->query($sql);
1184  while ($row = $db->fetch_row($result)) {
1185  // For each row of data we print a line of INSERT
1186  fwrite($handle, "INSERT ".$delayed.$ignore."INTO ".$table." VALUES (");
1187  $columns = count($row);
1188  for ($j = 0; $j < $columns; $j++) {
1189  // 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)
1190  if ($row[$j] == null && !is_string($row[$j])) {
1191  // IMPORTANT: if the field is NULL we set it NULL
1192  $row[$j] = 'NULL';
1193  } elseif (is_string($row[$j]) && $row[$j] == '') {
1194  // if it's an empty string, we set it as an empty string
1195  $row[$j] = "''";
1196  } 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)
1197  // if it's a number, we return it as-is
1198  // $row[$j] = $row[$j];
1199  } else { // else for all other cases we escape the value and put quotes around
1200  $row[$j] = addslashes($row[$j]);
1201  $row[$j] = preg_replace("#\n#", "\\n", $row[$j]);
1202  $row[$j] = "'".$row[$j]."'";
1203  }
1204  }
1205  fwrite($handle, implode(',', $row).");\n");
1206  }
1207  if (GETPOST("nobin_disable_fk")) {
1208  fwrite($handle, "ALTER TABLE `".$table."` ENABLE KEYS;\n"); // Enabling back the keys/index checking
1209  }
1210  if (!GETPOST("nobin_nolocks")) {
1211  fwrite($handle, "UNLOCK TABLES;\n"); // Unlocking the table
1212  }
1213  fwrite($handle, "\n\n\n");
1214  }
1215  }
1216 
1217  /* Backup Procedure structure*/
1218  /*
1219  $result = $db->query('SHOW PROCEDURE STATUS');
1220  if ($db->num_rows($result) > 0)
1221  {
1222  while ($row = $db->fetch_row($result)) { $procedures[] = $row[1]; }
1223  foreach($procedures as $proc)
1224  {
1225  fwrite($handle,"DELIMITER $$\n\n");
1226  fwrite($handle,"DROP PROCEDURE IF EXISTS '$name'.'$proc'$$\n");
1227  $resqlcreateproc=$db->query("SHOW CREATE PROCEDURE '$proc'");
1228  $row2 = $db->fetch_row($resqlcreateproc);
1229  fwrite($handle,"\n".$row2[2]."$$\n\n");
1230  fwrite($handle,"DELIMITER ;\n\n");
1231  }
1232  }
1233  */
1234  /* Backup Procedure structure*/
1235 
1236  // Write the footer (restore the previous database settings)
1237  $sqlfooter = "\n\n";
1238  if (GETPOST("nobin_use_transaction")) {
1239  $sqlfooter .= "COMMIT;\n";
1240  }
1241  if (GETPOST("nobin_disable_fk")) {
1242  $sqlfooter .= "SET FOREIGN_KEY_CHECKS=1;\n";
1243  }
1244  $sqlfooter .= "\n\n-- Dump completed on ".date('Y-m-d G-i-s');
1245  fwrite($handle, $sqlfooter);
1246 
1247  fclose($handle);
1248 
1249  return 1;
1250  }
1251 
1265  public function sendBackup($sendto = '', $from = '', $subject = '', $message = '', $filename = '', $filter = '', $sizelimit = 100000000)
1266  {
1267  global $conf, $langs;
1268 
1269  $filepath = '';
1270  $output = '';
1271  $error = 0;
1272 
1273  if (!empty($from)) {
1274  $from = dol_escape_htmltag($from);
1275  } elseif (!empty($conf->global->MAIN_INFO_SOCIETE_MAIL)) {
1276  $from = dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_MAIL);
1277  } else {
1278  $error++;
1279  }
1280 
1281  if (!empty($sendto)) {
1282  $sendto = dol_escape_htmltag($sendto);
1283  } elseif (!empty($conf->global->MAIN_INFO_SOCIETE_MAIL)) {
1284  $from = dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_MAIL);
1285  } else {
1286  $error++;
1287  }
1288 
1289  if (!empty($subject)) {
1290  $subject = dol_escape_htmltag($subject);
1291  } else {
1292  $subject = dol_escape_htmltag($langs->trans('MakeSendLocalDatabaseDumpShort'));
1293  }
1294 
1295  if (empty($message)) {
1296  $message = dol_escape_htmltag($langs->trans('MakeSendLocalDatabaseDumpShort'));
1297  }
1298 
1299  $tmpfiles = array();
1300  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1301  if ($filename) {
1302  if (dol_is_file($conf->admin->dir_output.'/backup/'.$filename)) {
1303  $tmpfiles = dol_most_recent_file($conf->admin->dir_output.'/backup', $filename);
1304  }
1305  } else {
1306  $tmpfiles = dol_most_recent_file($conf->admin->dir_output.'/backup', $filter);
1307  }
1308  if ($tmpfiles && is_array($tmpfiles)) {
1309  foreach ($tmpfiles as $key => $val) {
1310  if ($key == 'fullname') {
1311  $filepath = array($val);
1312  $filesize = dol_filesize($val);
1313  }
1314  if ($key == 'type') {
1315  $mimetype = array($val);
1316  }
1317  if ($key == 'relativename') {
1318  $filename = array($val);
1319  }
1320  }
1321  }
1322 
1323  if ($filepath) {
1324  if ($filesize > $sizelimit) {
1325  $message .= '<br>'.$langs->trans("BackupIsTooLargeSend");
1326  $documenturl = $dolibarr_main_url_root.'/document.php?modulepart=systemtools&atachement=1&file=backup/'.urlencode($filename[0]);
1327  $message .= '<br><a href='.$documenturl.'>Lien de tĂ©lĂ©chargement</a>';
1328  $filepath = '';
1329  $mimetype = '';
1330  $filename = '';
1331  }
1332  } else {
1333  $output = 'No backup file found';
1334  $error++;
1335  }
1336 
1337  if (!$error) {
1338  include_once DOL_DOCUMENT_ROOT . '/core/class/CMailFile.class.php';
1339  $mailfile = new CMailFile($subject, $sendto, $from, $message, $filepath, $mimetype, $filename, '', '', 0, -1);
1340  if ($mailfile->error) {
1341  $error++;
1342  $output = $mailfile->error;
1343  }
1344  }
1345 
1346  if (!$error) {
1347  $result = $mailfile->sendfile();
1348  if ($result <= 0) {
1349  $error++;
1350  $output = $mailfile->error;
1351  }
1352  }
1353 
1354  dol_syslog(__METHOD__, LOG_DEBUG);
1355 
1356  $this->error = $error;
1357  $this->output = $output;
1358 
1359  if ($result == true) {
1360  return 0;
1361  } else {
1362  return $result;
1363  }
1364  }
1365 
1373  public function cleanUnfinishedCronjob()
1374  {
1375  global $db, $user;
1376  dol_syslog("Utils::cleanUnfinishedCronjob Starting cleaning");
1377 
1378  // Import Cronjob class if not present
1379  dol_include_once('/cron/class/cronjob.class.php');
1380 
1381  // Get this job object
1382  $this_job = new Cronjob($db);
1383  $this_job->fetch(-1, 'Utils', 'cleanUnfinishedCronjob');
1384  if (empty($this_job->id) || !empty($this_job->error)) {
1385  dol_syslog("Utils::cleanUnfinishedCronjob Unable to fetch himself: ".$this_job->error, LOG_ERR);
1386  return -1;
1387  }
1388 
1389  // Set this job processing to 0 to avoid being locked by his processing state
1390  $this_job->processing = 0;
1391  if ($this_job->update($user) < 0) {
1392  dol_syslog("Utils::cleanUnfinishedCronjob Unable to update himself: ".implode(', ', $this_job->errors), LOG_ERR);
1393  return -1;
1394  }
1395 
1396  $cron_job = new Cronjob($db);
1397  $cron_job->fetchAll('DESC', 't.rowid', 100, 0, 1, '', 1); // Fetch jobs that are currently running
1398 
1399  // Iterate over all jobs in processing (this can't be this job since his state is set to 0 before)
1400  foreach ($cron_job->lines as $job_line) {
1401  // Avoid job with no PID
1402  if (empty($job_line->pid)) {
1403  dol_syslog("Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id." don't have a PID", LOG_DEBUG);
1404  continue;
1405  }
1406 
1407  $job = new Cronjob($db);
1408  $job->fetch($job_line->id);
1409  if (empty($job->id) || !empty($job->error)) {
1410  dol_syslog("Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id." can't be fetch: ".$job->error, LOG_ERR);
1411  continue;
1412  }
1413 
1414  // Calling posix_kill with the 0 kill signal will return true if the process is running, false otherwise.
1415  if (! posix_kill($job->pid, 0)) {
1416  // Clean processing and pid values
1417  $job->processing = 0;
1418  $job->pid = null;
1419 
1420  // Set last result as an error and add the reason on the last output
1421  $job->lastresult = -1;
1422  $job->lastoutput = 'Job killed by job cleanUnfinishedCronjob';
1423 
1424  if ($job->update($user) < 0) {
1425  dol_syslog("Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id." can't be updated: ".implode(', ', $job->errors), LOG_ERR);
1426  continue;
1427  }
1428  dol_syslog("Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id." cleaned");
1429  }
1430  }
1431 
1432  dol_syslog("Utils::cleanUnfinishedCronjob Cleaning completed");
1433  return 0;
1434  }
1435 }
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
if(isModEnabled('facture') && $user->hasRight('facture', 'lire')) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') && $user->hasRight('don', 'lire')) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $sql
Social contributions to pay.
Definition: index.php:746
dol_filesize($pathoffile)
Return size of a file.
Definition: files.lib.php:587
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:1485
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:1334
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:2524
dol_is_file($pathoffile)
Return if path is a file.
Definition: files.lib.php:483
dolReplaceInFile($srcfile, $arrayreplacement, $destfile='', $newmask=0, $indexdatabase=0, $arrayreplacementisregex=0)
Make replacement of strings into a file.
Definition: files.lib.php:629
dol_copy($srcfile, $destfile, $newmask=0, $overwriteifexists=1, $testvirus=0, $indexdatabase=0)
Copy a file to another file.
Definition: files.lib.php:717
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.
Definition: files.lib.php:453
dol_move($srcfile, $destfile, $newmask=0, $overwriteifexists=1, $testvirus=0, $indexdatabase=1)
Move a file into another name.
Definition: files.lib.php:947
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.
dolChmod($filepath, $newmask='')
Change mod of a file.
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.
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.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
dolMd2Asciidoc($content, $parser='dolibarr', $replaceimagepath=null)
Function to parse MD content into ASCIIDOC.
Definition: parsemd.lib.php:70