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