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