80 public function purgeFiles($choices =
'tempfilesold+logfiles', $nbsecondsold = 86400)
82 global
$conf, $langs, $user;
83 global $dolibarr_main_data_root;
85 $langs->load(
"admin");
87 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
89 if (empty($choices)) {
90 $choices =
'tempfilesold+logfiles';
92 if ($choices ==
'allfiles' && $nbsecondsold > 0) {
93 $choices =
'allfilesold';
96 dol_syslog(
"Utils::purgeFiles choice=".$choices, LOG_DEBUG);
99 if (in_array($choices, array(
'allfiles',
'allfilesold'))) {
100 if (empty($user->admin)) {
101 $this->output =
'Error: to erase data files, user running the batch (currently '.$user->login.
') must be an admin user';
111 $choicesarray = preg_split(
'/[\+,]/', $choices);
112 foreach ($choicesarray as $choice) {
114 $filesarray = array();
116 if ($choice ==
'tempfiles' || $choice ==
'tempfilesold') {
118 if ($dolibarr_main_data_root) {
119 $filesarray =
dol_dir_list($dolibarr_main_data_root,
"directories", 1,
'^temp$',
'',
'name', SORT_ASC, 2, 0,
'', 1);
121 if ($choice ==
'tempfilesold') {
122 foreach ($filesarray as $key => $val) {
123 if ($val[
'date'] > ($now - ($nbsecondsold))) {
124 unset($filesarray[$key]);
131 if ($choice ==
'allfiles') {
133 if ($dolibarr_main_data_root) {
134 $filesarray =
dol_dir_list($dolibarr_main_data_root,
"all", 0,
'',
'(\.lock|\.unlock)$',
'name', SORT_ASC, 0, 0,
'', 1);
138 if ($choice ==
'allfilesold') {
140 if ($dolibarr_main_data_root) {
141 $filesarray =
dol_dir_list($dolibarr_main_data_root,
"files", 1,
'',
'(\.lock|\.unlock)$',
'name', SORT_ASC, 0, 0,
'', 1, $nbsecondsold);
145 if ($choice ==
'logfile' || $choice ==
'logfiles') {
147 if ($dolibarr_main_data_root) {
148 $filesarray =
dol_dir_list($dolibarr_main_data_root,
"files", 0,
'.*\.log[\.0-9]*(\.gz)?$',
'(\.lock|\.unlock)$',
'name', SORT_ASC, 0, 0,
'', 1);
153 $filelog = preg_replace(
'/DOL_DATA_ROOT/i', DOL_DATA_ROOT, $filelog);
155 $alreadyincluded =
false;
156 foreach ($filesarray as $tmpcursor) {
157 if ($tmpcursor[
'fullname'] == $filelog) {
158 $alreadyincluded =
true;
161 if (!$alreadyincluded) {
162 $filesarray[] = array(
'fullname' => $filelog,
'type' =>
'file');
167 if (is_array($filesarray) && count($filesarray)) {
168 foreach ($filesarray as $key => $value) {
170 if ($filesarray[$key][
'type'] ==
'dir') {
172 $tmpcountdeleted = 0;
177 $conf->user->dir_temp,
180 $excluded[] =
$conf->api->dir_temp;
183 if (!in_array($filesarray[$key][
'fullname'], $excluded)) {
185 $countdeleted += $tmpcountdeleted;
187 } elseif ($filesarray[$key][
'type'] ==
'file') {
188 if ($choice !=
'allfilesold' || $filesarray[$key][
'date'] < ($now - $nbsecondsold)) {
190 if ($filesarray[$key][
'fullname'] != $filelog || $choice ==
'logfile' || $choice ==
'logfiles') {
205 require_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmdirectory.class.php';
207 $result = $ecmdirstatic->refreshcachenboffile(1);
213 $langs->load(
"admin");
214 $this->output = $langs->trans(
"PurgeNDirectoriesDeleted", $countdeleted);
215 if ($count > $countdeleted) {
216 $this->output .=
'<br>'.$langs->trans(
"PurgeNDirectoriesFailed", ($count - $countdeleted));
219 $this->output = $langs->trans(
"PurgeNothingToDelete").(in_array(
'tempfilesold', $choicesarray) ?
' (older than 24h for temp files)' :
'');
242 if (preg_match(
'/^win/i', PHP_OS)) {
244 return '-p"'.str_replace(array(
'"',
'`',
'$'), array(
'\\"',
'\\`',
'\\$'), $password).
'"';
248 return '-p'.escapeshellarg($password);
265 public function dumpDatabase($compression =
'none', $type =
'auto', $usedefault = 1, $file =
'auto', $keeplastnfiles = 0, $execmethod = 0, $lowmemorydump = 0)
268 global $dolibarr_main_db_name, $dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_port, $dolibarr_main_db_pass;
269 global $dolibarr_main_db_character_set;
270 global $dolibarr_main_restrict_os_commands;
272 $langs->load(
"admin");
274 dol_syslog(
"Utils::dumpDatabase type=".$type.
" compression=".$compression.
" file=".$file, LOG_DEBUG);
275 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
281 if (!in_array($compression, array(
'none',
'gz',
'bz',
'zip',
'zstd'))) {
282 $langs->load(
"errors");
283 $this->error = $langs->transnoentitiesnoconv(
"ErrorBadValueForParameter", $compression,
"Compression");
288 if ($type ==
'auto') {
289 $type = $this->db->type;
291 if (!in_array($type, array(
'postgresql',
'pgsql',
'mysql',
'mysqli',
'mysqlnobin'))) {
292 $langs->load(
"errors");
293 $this->error = $langs->transnoentitiesnoconv(
"ErrorBadValueForParameter", $type,
"Basetype");
298 if ($file ==
'auto') {
301 if (in_array($type, array(
'mysql',
'mysqli'))) {
302 $prefix =
'mysqldump';
305 if (in_array($type, array(
'pgsql'))) {
311 $outputdir =
$conf->admin->dir_output.
'/backup';
316 if ($type ==
'mysql' || $type ==
'mysqli') {
318 $cmddump =
$db->getPathOfDump();
322 if (empty($cmddump)) {
323 $this->error =
"Failed to detect command to use for mysqldump. Try a manual backup before to set path of command.";
327 $outputfile = $outputdir.
'/'.$file;
329 $compression = $compression ? $compression :
'none';
330 if ($compression ==
'gz') {
331 $outputfile .=
'.gz';
332 } elseif ($compression ==
'bz') {
333 $outputfile .=
'.bz2';
334 } elseif ($compression ==
'zstd') {
335 $outputfile .=
'.zst';
337 $outputerror = $outputfile.
'.err';
342 $basenamecmddump = basename(str_replace(
'\\',
'/', $cmddump));
345 if (!empty($dolibarr_main_restrict_os_commands)) {
346 $arrayofallowedcommand = explode(
',', $dolibarr_main_restrict_os_commands);
347 $arrayofallowedcommand = array_map(
'trim', $arrayofallowedcommand);
348 dol_syslog(
"Command are restricted to ".$dolibarr_main_restrict_os_commands.
". We check that one of this command is inside ".$cmddump);
349 if (!in_array($basenamecmddump, $arrayofallowedcommand)) {
350 $langs->load(
"errors");
351 $this->error = $langs->trans(
'CommandIsNotInsideAllowedCommands');
352 $this->error .=
'<br>'.$langs->trans(
'ErrorCheckTheCommandInsideTheAdvancedOptions');
359 $command = preg_replace(
'/(\$|%)/',
'', $command);
360 if (preg_match(
"/\s/", $command)) {
361 $command = escapeshellarg($command);
365 $param = $dolibarr_main_db_name.
" -h ".$dolibarr_main_db_host;
366 $param .=
" -u ".$dolibarr_main_db_user;
367 if (!empty($dolibarr_main_db_port)) {
368 $param .=
" -P ".$dolibarr_main_db_port.
" --protocol=tcp";
370 if (
GETPOST(
"use_transaction",
"alpha")) {
371 $param .=
" --single-transaction";
373 if (
GETPOST(
"disable_fk",
"alpha") || $usedefault) {
376 if (
GETPOST(
"sql_compat",
"alpha") &&
GETPOST(
"sql_compat",
"alpha") !=
'NONE') {
377 $param .=
" --compatible=".escapeshellarg(
GETPOST(
"sql_compat",
"alpha"));
379 if (
GETPOST(
"drop_database",
"alpha")) {
380 $param .=
" --add-drop-database";
382 if (
GETPOST(
"use_mysql_quick_param",
"alpha")) {
383 $param .=
" --quick";
385 if (
GETPOST(
"use_force",
"alpha")) {
388 if (
GETPOST(
"sql_structure",
"alpha") || $usedefault) {
389 if (
GETPOST(
"drop",
"alpha") || $usedefault) {
390 $param .=
" --add-drop-table=TRUE";
392 $param .=
" --add-drop-table=FALSE";
397 if (
GETPOST(
"disable-add-locks",
"alpha")) {
398 $param .=
" --add-locks=FALSE";
400 if (
GETPOST(
"sql_data",
"alpha") || $usedefault) {
401 $param .=
" --tables";
402 if (
GETPOST(
"showcolumns",
"alpha") || $usedefault) {
405 if (
GETPOST(
"extended_ins",
"alpha") || $usedefault) {
408 $param .=
" --skip-extended-insert";
410 if (
GETPOST(
"delayed",
"alpha")) {
411 $param .=
" --delayed-insert";
413 if (
GETPOST(
"sql_ignore",
"alpha")) {
414 $param .=
" --insert-ignore";
416 if (
GETPOST(
"hexforbinary",
"alpha") || $usedefault) {
417 $param .=
" --hex-blob";
422 if ($dolibarr_main_db_character_set ==
'utf8mb4') {
424 $param .=
" --default-character-set=utf8mb4 --no-tablespaces";
426 $param .=
" --default-character-set=utf8 --no-tablespaces";
428 $paramcrypted = $param;
429 $paramclear = $param;
430 if (!empty($dolibarr_main_db_pass)) {
431 $paramcrypted .=
' -p"'.preg_replace(
'/./i',
'*', $dolibarr_main_db_pass).
'"';
432 $paramclear .=
' '.$this->getShellPasswordParam($dolibarr_main_db_pass);
438 $fullcommandcrypted = $command.
" ".$paramcrypted.
" 2>&1";
439 $fullcommandclear = $command.
" ".$paramclear.
" 2>&1";
440 if (!$lowmemorydump) {
441 if ($compression ==
'none') {
442 $handle = fopen($outputfile,
'w');
443 } elseif ($compression ==
'gz') {
444 $handle = gzopen($outputfile,
'w');
445 } elseif ($compression ==
'bz') {
446 $handle = bzopen($outputfile,
'w');
447 } elseif ($compression ==
'zstd') {
448 $handle = fopen(
"compress.zstd://" . $outputfile,
"wb");
453 if ($compression ==
'none') {
454 $fullcommandclear .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." > "'.dol_sanitizePathName($outputfile).
'"';
455 $fullcommandcrypted .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." > "'.dol_sanitizePathName($outputfile).
'"';
457 } elseif ($compression ==
'gz') {
458 $fullcommandclear .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | gzip > "'.dol_sanitizePathName($outputfile).
'"';
459 $fullcommandcrypted .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | gzip > "'.dol_sanitizePathName($outputfile).
'"';
460 $paramcrypted .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | gzip';
462 } elseif ($compression ==
'bz') {
463 $fullcommandclear .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | bzip2 > "'.dol_sanitizePathName($outputfile).
'"';
464 $fullcommandcrypted .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | bzip2 > "'.dol_sanitizePathName($outputfile).
'"';
465 $paramcrypted .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | bzip2';
467 } elseif ($compression ==
'zstd') {
468 $fullcommandclear .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | zstd > "'.dol_sanitizePathName($outputfile).
'"';
469 $fullcommandcrypted .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | zstd > "'.dol_sanitizePathName($outputfile).
'"';
470 $paramcrypted .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | zstd';
480 if (empty($execmethod)) {
484 dol_syslog(
"Utils::dumpDatabase execmethod=".$execmethod.
", lowmemorydump=".$lowmemorydump.
", command=".$fullcommandcrypted, LOG_INFO);
489 if (!empty($MemoryLimit)) {
490 @ini_set(
'memory_limit', $MemoryLimit);
494 if ($execmethod == 1) {
495 $output_arr = array();
498 exec($fullcommandclear, $output_arr, $retval);
506 $langs->load(
"errors");
507 dol_syslog(
"Datadump retval after exec=".$retval, LOG_ERR);
508 $errormsg =
'Error '.$retval;
512 if (!empty($output_arr)) {
513 foreach ($output_arr as $key => $read) {
515 if ($i == 1 && preg_match(
'/Warning.*Using a password/i', $read)) {
520 if (!$lowmemorydump) {
523 fwrite($handle, $read.($execmethod == 2 ?
'' :
"\n"));
524 if (preg_match(
'/'.preg_quote(
'-- Dump completed',
'/').
'/i', $read)) {
526 } elseif (preg_match(
'/'.preg_quote(
'SET SQL_NOTES=@OLD_SQL_NOTES',
'/').
'/i', $read)) {
533 } elseif ($lowmemorydump) {
539 if ($execmethod == 2) {
540 $handlein = popen($fullcommandclear,
'r');
543 while (!feof($handlein)) {
545 $read = fgets($handlein);
547 if ($i == 1 && preg_match(
'/Warning.*Using a password/i', $read)) {
550 fwrite($handle, $read);
551 if (preg_match(
'/'.preg_quote(
'-- Dump completed',
'/').
'/i', $read)) {
553 } elseif (preg_match(
'/'.preg_quote(
'SET SQL_NOTES=@OLD_SQL_NOTES',
'/').
'/i', $read)) {
561 if (!$lowmemorydump) {
562 if ($compression ==
'none') {
564 } elseif ($compression ==
'gz') {
566 } elseif ($compression ==
'bz') {
568 } elseif ($compression ==
'zstd') {
575 $langs->load(
"errors");
576 dol_syslog(
"Failed to open file ".$outputfile, LOG_ERR);
577 $errormsg = $langs->trans(
"ErrorFailedToWriteInDir");
581 if ($compression ==
'none') {
582 $handle = fopen($outputfile,
'r');
583 } elseif ($compression ==
'gz') {
584 $handle = gzopen($outputfile,
'r');
585 } elseif ($compression ==
'bz') {
586 $handle = bzopen($outputfile,
'r');
587 } elseif ($compression ==
'zstd') {
588 $handle = fopen(
"compress.zstd://" . $outputfile,
"rb");
592 $errormsg = fgets($handle, 2048);
596 if ($compression ==
'none') {
598 } elseif ($compression ==
'gz') {
600 } elseif ($compression ==
'bz') {
602 } elseif ($compression ==
'zstd') {
605 if ($ok && preg_match(
'/^-- (MySql|MariaDB)/i', $errormsg) || preg_match(
'/^\/\*M?!999999/', $errormsg)) {
611 @
dol_move($outputfile, $outputerror,
'0', 1, 0, 0);
614 $langs->load(
"errors");
615 $errormsg = $langs->trans(
"ErrorFailedToRunExternalCommand");
621 $this->output = $errormsg;
622 $this->error = $errormsg;
623 $this->result = array(
"commandbackuplastdone" => $command.
" ".$paramcrypted,
"commandbackuptorun" =>
"");
628 if ($type ==
'mysqlnobin') {
629 $outputfile = $outputdir.
'/'.$file;
630 $outputfiletemp = $outputfile.
'-TMP.sql';
632 $compression = $compression ? $compression :
'none';
633 if ($compression ==
'gz') {
634 $outputfile .=
'.gz';
636 if ($compression ==
'bz') {
637 $outputfile .=
'.bz2';
639 $outputerror = $outputfile.
'.err';
642 if ($compression ==
'gz' or $compression ==
'bz') {
643 $this->backupTables($outputfiletemp);
644 dol_compress_file($outputfiletemp, $outputfile, $compression);
645 unlink($outputfiletemp);
647 $this->backupTables($outputfile);
651 $this->result = array(
"commandbackuplastdone" =>
"",
"commandbackuptorun" =>
"");
655 if ($type ==
'postgresql' || $type ==
'pgsql') {
658 $outputfile = $outputdir.
'/'.$file;
660 $compression = $compression ? $compression :
'none';
661 if ($compression ==
'gz') {
662 $outputfile .=
'.gz';
664 if ($compression ==
'bz') {
665 $outputfile .=
'.bz2';
667 $outputerror = $outputfile.
'.err';
673 $basenamecmddump = basename(str_replace(
'\\',
'/', $cmddump));
675 if (!empty($dolibarr_main_restrict_os_commands)) {
676 $arrayofallowedcommand = explode(
',', $dolibarr_main_restrict_os_commands);
677 $arrayofallowedcommand = array_map(
'trim', $arrayofallowedcommand);
678 dol_syslog(
"Command are restricted to ".$dolibarr_main_restrict_os_commands.
". We check that one of this command is inside ".$cmddump);
679 if (!in_array($basenamecmddump, $arrayofallowedcommand)) {
680 $langs->load(
"errors");
681 $this->error = $langs->trans(
'CommandIsNotInsideAllowedCommands');
682 $this->error .=
'<br>'.$langs->trans(
'ErrorCheckTheCommandInsideTheAdvancedOptions');
689 $command = preg_replace(
'/(\$|%)/',
'', $command);
690 if (preg_match(
"/\s/", $command)) {
691 $command = escapeshellarg($command);
697 $param .=
" --no-tablespaces --inserts -h ".$dolibarr_main_db_host;
698 $param .=
" -U ".$dolibarr_main_db_user;
699 if (!empty($dolibarr_main_db_port)) {
700 $param .=
" -p ".$dolibarr_main_db_port;
703 $param .=
" --disable-dollar-quoting";
705 if (
GETPOST(
"drop_database")) {
708 if (
GETPOST(
"sql_structure")) {
710 $param .=
" --add-drop-table";
717 if (!
GETPOST(
"sql_structure")) {
724 $param .=
' -f "'.$outputfile.
'"';
726 if ($compression ==
'gz') {
730 $paramcrypted = $param;
731 $paramclear = $param;
737 $paramcrypted .=
" -w ".$dolibarr_main_db_name;
738 $paramclear .=
" -w ".$dolibarr_main_db_name;
741 $this->result = array(
"commandbackuplastdone" =>
"",
"commandbackuptorun" => $command.
" ".$paramcrypted);
745 if (!$errormsg && $keeplastnfiles > 0) {
746 $tmpfiles =
dol_dir_list(
$conf->admin->dir_output.
'/backup',
'files', 0,
'',
'(\.err|\.old|\.sav)$',
'date', SORT_DESC);
748 if (is_array($tmpfiles)) {
749 foreach ($tmpfiles as $key => $val) {
751 if ($i <= $keeplastnfiles) {
759 return ($errormsg ? -1 : 0);
777 public function executeCLI($command, $outputfile, $execmethod = 0, $redirectionfile =
null, $noescapecommand = 0, $redirectionfileerr =
null)
785 global $dolibarr_main_restrict_os_commands;
786 if (!empty($dolibarr_main_restrict_os_commands)) {
787 $arrayofallowedcommand = explode(
',', $dolibarr_main_restrict_os_commands);
788 $arrayofallowedcommand = array_map(
'trim', $arrayofallowedcommand);
790 $commands = preg_split(
'/\|\||&&|\||&/', $command);
791 foreach ($commands as $newcommand) {
792 $newcommand = trim($newcommand);
795 if (preg_match(
'/^(?:\'([^\']*)\'|"([^"]*)"|(\S+))/', $newcommand, $matches)) {
796 $newcommand = $matches[1] ?: ($matches[2] ?: $matches[3]);
798 if (!in_array(basename($newcommand), $arrayofallowedcommand)) {
799 dol_syslog(
"files.lib.php::executeCLI canceled because target filename ".basename($newcommand).
" is not in the whitelist of allowed commands.", LOG_WARNING);
800 return array(
'result' => -1,
'output' =>
'',
'error' =>
'Command '.basename($newcommand).
' is not in the whitelist of allowed commands');
805 if (empty($noescapecommand)) {
806 $command = escapeshellcmd($command);
809 if ($redirectionfile) {
810 $command .=
" > ".dol_sanitizePathName($redirectionfile);
813 if ($redirectionfileerr && ($redirectionfileerr != $redirectionfile)) {
815 $command .=
" 2> ".dol_sanitizePathName($redirectionfileerr);
823 if (empty($execmethod)) {
827 dol_syslog(
"Utils::executeCLI execmethod=".$execmethod.
" command=".$command, LOG_DEBUG);
828 $output_arr = array();
830 if ($execmethod == 1) {
832 exec($command, $output_arr, $retval);
835 $langs->load(
"errors");
836 dol_syslog(
"Utils::executeCLI retval after exec=".$retval, LOG_ERR);
837 $error =
'Error '.$retval;
840 if ($execmethod == 2) {
841 $handle = fopen($outputfile,
'w+b');
843 dol_syslog(
"Utils::executeCLI run command ".$command);
844 $handlein = popen($command,
'r');
845 while (!feof($handlein)) {
846 $read = fgets($handlein);
847 fwrite($handle, $read);
848 $output_arr[] = $read;
857 if (is_array($output_arr) && count($output_arr) > 0) {
858 foreach ($output_arr as $val) {
859 $output .= $val.($execmethod == 2 ?
'' :
"\n");
863 dol_syslog(
"Utils::executeCLI result=".$result.
" output=".$output.
" error=".$error, LOG_DEBUG);
865 return array(
'result' => $result,
'output' => $output,
'error' => $error);
876 global $langs, $user,
$mysoc;
881 $modulelowercase = strtolower($module);
885 $dir = $dirins.
'/'.$modulelowercase;
890 dol_include_once($modulelowercase.
'/core/modules/mod'.$module.
'.class.php');
891 $class =
'mod'.$module;
894 if (class_exists($class)) {
903 $langs->load(
"errors");
904 dol_print_error(
null, $langs->trans(
"ErrorFailedToLoadModuleDescriptorForXXX", $module));
909 if (count($arrayversion)) {
910 $FILENAMEASCII = strtolower($module).
'.asciidoc';
911 $FILENAMEDOC = strtolower($module).
'.html';
912 $FILENAMEDOCPDF = strtolower($module).
'.pdf';
915 $dirofmoduledoc =
dol_buildpath(strtolower($module), 0).
'/doc';
916 $dirofmoduletmp =
dol_buildpath(strtolower($module), 0).
'/doc/temp';
917 $outputfiledoc = $dirofmoduledoc.
'/'.$FILENAMEDOC;
918 if ($dirofmoduledoc) {
925 if (!is_writable($dirofmoduletmp)) {
926 $this->error =
'Dir '.$dirofmoduletmp.
' does not exists or is not writable';
931 $this->error =
'Setup of module ModuleBuilder not complete';
936 dol_copy($dirofmodule.
'/README.md', $dirofmoduletmp.
'/README.md',
'0', 1);
937 dol_copy($dirofmodule.
'/ChangeLog.md', $dirofmoduletmp.
'/ChangeLog.md',
'0', 1);
940 $arrayreplacement = array();
941 $arrayreplacement[
'/^#\s.*/m'] =
'';
942 $arrayreplacement[
'/^#/m'] =
'##';
944 dolReplaceInFile($dirofmoduletmp.
'/README.md', $arrayreplacement,
'',
'0', 0, 1);
945 dolReplaceInFile($dirofmoduletmp.
'/ChangeLog.md', $arrayreplacement,
'',
'0', 0, 1);
948 $destfile = $dirofmoduletmp.
'/'.$FILENAMEASCII;
950 $fhandle = fopen($destfile,
'w+');
952 $specs =
dol_dir_list(
dol_buildpath(strtolower($module).
'/doc', 0),
'files', 1,
'(\.md|\.asciidoc)$', array(
'\/temp\/'));
955 foreach ($specs as $spec) {
956 if (preg_match(
'/notindoc/', $spec[
'relativename'])) {
959 if (preg_match(
'/example/', $spec[
'relativename'])) {
962 if (preg_match(
'/disabled/', $spec[
'relativename'])) {
966 $pathtofile = strtolower($module).
'/doc/'.$spec[
'relativename'];
967 $format =
'asciidoc';
968 if (preg_match(
'/\.md$/i', $spec[
'name'])) {
969 $format =
'markdown';
972 $filecursor = @file_get_contents($spec[
'fullname']);
974 fwrite($fhandle, ($i ?
"\n<<<\n\n" :
"").$filecursor.
"\n");
976 $this->error =
'Failed to concat content of file '.$spec[
'fullname'];
985 $contentreadme = file_get_contents($dirofmoduletmp.
'/README.md');
986 $contentchangelog = file_get_contents($dirofmoduletmp.
'/ChangeLog.md');
988 include DOL_DOCUMENT_ROOT.
'/core/lib/parsemd.lib.php';
991 $arrayreplacement = array(
992 'mymodule' => strtolower($module),
993 'MyModule' => $module,
994 'MYMODULE' => strtoupper($module),
995 'My module' => $module,
996 'my module' => $module,
997 'Mon module' => $module,
998 'mon module' => $module,
999 'htdocs/modulebuilder/template' => strtolower($module),
1000 '__MYCOMPANY_NAME__' =>
$mysoc->name,
1001 '__KEYWORDS__' => $module,
1002 '__USER_FULLNAME__' => $user->getFullName($langs),
1003 '__USER_EMAIL__' => $user->email,
1005 '---Put here your own copyright and developer email---' =>
dol_print_date($now,
'dayrfc').
' '.$user->getFullName($langs).($user->email ?
' <'.$user->email.
'>' :
''),
1006 '__DATA_SPECIFICATION__' =>
'Not yet available',
1016 $currentdir = getcwd();
1017 chdir($dirofmodule);
1019 require_once DOL_DOCUMENT_ROOT.
'/core/class/utils.class.php';
1020 $utils =
new Utils($this->db);
1023 $command =
getDolGlobalString(
'MODULEBUILDER_ASCIIDOCTOR') .
' '.$destfile.
' -n -o '.$dirofmoduledoc.
'/'.$FILENAMEDOC;
1024 $outfile = $dirofmoduletmp.
'/out.tmp';
1026 $resarray = $utils->executeCLI($command, $outfile);
1027 if ($resarray[
'result'] !=
'0') {
1028 $this->error = $resarray[
'error'].
' '.$resarray[
'output'];
1029 $this->errors[] = $this->error;
1031 $result = ($resarray[
'result'] == 0) ? 1 : 0;
1032 if ($result < 0 && empty($this->errors)) {
1033 $this->error = $langs->trans(
"ErrorFailToGenerateFile", $FILENAMEDOC);
1034 $this->errors[] = $this->error;
1038 $command =
getDolGlobalString(
'MODULEBUILDER_ASCIIDOCTORPDF') .
' '.$destfile.
' -n -o '.$dirofmoduledoc.
'/'.$FILENAMEDOCPDF;
1039 $outfile = $dirofmoduletmp.
'/outpdf.tmp';
1040 $resarray = $utils->executeCLI($command, $outfile);
1041 if ($resarray[
'result'] !=
'0') {
1042 $this->error = $resarray[
'error'].
' '.$resarray[
'output'];
1043 $this->errors[] = $this->error;
1045 $result = ($resarray[
'result'] == 0) ? 1 : 0;
1046 if ($result < 0 && empty($this->errors)) {
1047 $this->error = $langs->trans(
"ErrorFailToGenerateFile", $FILENAMEDOCPDF);
1048 $this->errors[] = $this->error;
1063 $langs->load(
"errors");
1064 $this->error = $langs->trans(
"ErrorCheckVersionIsDefined");
1081 if (empty(
$conf->loghandlers[
'mod_syslog_file'])) {
1085 if (!function_exists(
'gzopen')) {
1086 $this->error =
'Support for gzopen not available in this PHP';
1090 require_once DOL_DOCUMENT_ROOT .
'/core/lib/files.lib.php';
1095 $mainlogdir = DOL_DATA_ROOT;
1096 $mainlog =
'dolibarr.log';
1098 $mainlogfull = str_replace(
'DOL_DATA_ROOT', DOL_DATA_ROOT,
$conf->global->SYSLOG_FILE);
1099 $mainlogdir = dirname($mainlogfull);
1100 $mainlog = basename($mainlogfull);
1103 $tabfiles =
dol_dir_list(DOL_DATA_ROOT,
'files', 0,
'^(dolibarr_.+|odt2pdf)\.log$');
1104 $tabfiles[] = array(
'name' => $mainlog,
'path' => $mainlogdir);
1106 foreach ($tabfiles as $file) {
1107 $logname = $file[
'name'];
1108 $logpath = $file[
'path'];
1113 $filter =
'^'.preg_quote($logname,
'/').
'\.([0-9]+)\.gz$';
1115 $gzfilestmp =
dol_dir_list($logpath,
'files', 0, $filter);
1118 foreach ($gzfilestmp as $gzfile) {
1119 $tabmatches = array();
1120 preg_match(
'/'.$filter.
'/i', $gzfile[
'name'], $tabmatches);
1122 $numsave = intval($tabmatches[1]);
1124 $gzfiles[$numsave] = $gzfile;
1127 krsort($gzfiles, SORT_NUMERIC);
1129 foreach ($gzfiles as $numsave => $dummy) {
1130 if (
dol_is_file($logpath.
'/'.$logname.
'.'.($numsave + 1).
'.gz')) {
1134 if ($numsave >= $nbSaves) {
1135 dol_delete_file($logpath.
'/'.$logname.
'.'.$numsave.
'.gz', 0, 0, 0,
null,
false, 0);
1137 dol_move($logpath.
'/'.$logname.
'.'.$numsave.
'.gz', $logpath.
'/'.$logname.
'.'.($numsave + 1).
'.gz',
'0', 1, 0, 0);
1144 $gzfilehandle = gzopen($logpath.
'/'.$logname.
'.1.gz',
'wb9');
1146 if (empty($gzfilehandle)) {
1147 $this->error =
'Failted to open file '.$logpath.
'/'.$logname.
'.1.gz';
1151 $sourcehandle = fopen($logpath.
'/'.$logname,
'r');
1153 if (empty($sourcehandle)) {
1154 $this->error =
'Failed to open file '.$logpath.
'/'.$logname;
1158 while (!feof($sourcehandle)) {
1159 gzwrite($gzfilehandle, fread($sourcehandle, 512 * 1024));
1162 fclose($sourcehandle);
1163 gzclose($gzfilehandle);
1165 dolChmod($logpath.
'/'.$logname.
'.1.gz');
1171 $newlog = fopen($logpath.
'/'.$logname,
'a+');
1179 $this->output =
'Archive log files (keeping last SYSLOG_FILE_SAVES='.$nbSaves.
' files) done.';
1193 public function backupTables($outputfile, $tables =
'*')
1197 global $dolibarr_main_db_character_set;
1201 $charset = ($dolibarr_main_db_character_set ==
'utf8mb4' ?
'utf8mb4' :
'utf8');
1202 $sanitizedcharset =
$db->sanitize($charset);
1203 if (is_a(
$db,
'DoliDBMysqli')) {
1205 $db->db->set_charset($charset);
1208 $db->query(
'SET NAMES '.
$db->sanitize($charset));
1209 $db->query(
'SET CHARACTER SET '.
$db->sanitize($charset));
1213 if ($tables ==
'*') {
1215 $result =
$db->query(
'SHOW FULL TABLES WHERE Table_type = \'BASE TABLE\'');
1216 while ($row =
$db->fetch_row($result)) {
1217 $tables[] = $row[0];
1220 $tables = is_array($tables) ? $tables : explode(
',', $tables);
1224 $handle = fopen($outputfile,
'w+');
1225 if (fwrite($handle,
'') ===
false) {
1226 $langs->load(
"errors");
1227 dol_syslog(
"Failed to open file ".$outputfile, LOG_ERR);
1228 $errormsg = $langs->trans(
"ErrorFailedToWriteInDir");
1234 $sqlhead .=
"-- ".$db::LABEL.
" dump via php with Dolibarr ".DOL_VERSION.
"
1236-- Host: ".
$db->db->host_info.
" Database: ".
$db->database_name.
"
1237-- ------------------------------------------------------
1238-- Server version ".
$db->db->server_info.
"
1253 if (
GETPOST(
"nobin_disable_fk")) {
1254 $sqlhead .=
"SET FOREIGN_KEY_CHECKS=0;\n";
1257 if (
GETPOST(
"nobin_use_transaction")) {
1258 $sqlhead .=
"SET AUTOCOMMIT=0;\nSTART TRANSACTION;\n";
1261 fwrite($handle, $sqlhead);
1264 if (
GETPOST(
"nobin_sql_ignore")) {
1265 $ignore =
'IGNORE ';
1268 if (
GETPOST(
"nobin_delayed")) {
1269 $delayed =
'DELAYED ';
1273 foreach ($tables as $table) {
1275 fwrite($handle,
"\n--\n-- Table structure for table `".$table.
"`\n--\n");
1278 fwrite($handle,
"DROP TABLE IF EXISTS `".$table.
"`;\n");
1280 fwrite($handle,
"/*!40101 SET @saved_cs_client = @@character_set_client */;\n");
1281 fwrite($handle,
"/*!40101 SET character_set_client = ".$sanitizedcharset.
" */;\n");
1282 $resqldrop =
$db->query(
'SHOW CREATE TABLE '.$table);
1283 $row2 =
$db->fetch_row($resqldrop);
1284 if (empty($row2[1])) {
1285 fwrite($handle,
"\n-- WARNING: Show create table ".$table.
" return empty string when it should not.\n");
1287 fwrite($handle, $row2[1].
";\n");
1291 fwrite($handle,
"\n--\n-- Dumping data for table `".$table.
"`\n--\n");
1292 if (!
GETPOST(
"nobin_nolocks")) {
1293 fwrite($handle,
"LOCK TABLES `".$table.
"` WRITE;\n");
1295 if (
GETPOST(
"nobin_disable_fk")) {
1296 fwrite($handle,
"ALTER TABLE `".$table.
"` DISABLE KEYS;\n");
1298 fwrite($handle,
"/*!40000 ALTER TABLE `".$table.
"` DISABLE KEYS */;\n");
1301 $sql =
"SELECT * FROM ".$table;
1302 $result =
$db->query($sql);
1303 while ($row =
$db->fetch_row($result)) {
1305 fwrite($handle,
"INSERT ".$delayed.$ignore.
"INTO ".$table.
" VALUES (");
1306 $columns = count($row);
1307 for ($j = 0; $j < $columns; $j++) {
1309 if ($row[$j] ==
null && !is_string($row[$j])) {
1312 } elseif (is_string($row[$j]) && $row[$j] ==
'') {
1315 } elseif (is_numeric($row[$j]) && !strcmp((
string) $row[$j], (
string) ((
float) $row[$j] + 0))) {
1319 $row[$j] = addslashes($row[$j]);
1320 $row[$j] = preg_replace(
"#\n#",
"\\n", $row[$j]);
1321 $row[$j] =
"'".$row[$j].
"'";
1324 fwrite($handle, implode(
',', $row).
");\n");
1326 if (
GETPOST(
"nobin_disable_fk")) {
1327 fwrite($handle,
"ALTER TABLE `".$table.
"` ENABLE KEYS;\n");
1329 fwrite($handle,
"/*!40000 ALTER TABLE `".$table.
"` ENABLE KEYS */;\n");
1331 if (!
GETPOST(
"nobin_nolocks")) {
1332 fwrite($handle,
"UNLOCK TABLES;\n");
1334 fwrite($handle,
"\n\n\n");
1358 $sqlfooter =
"\n\n";
1359 if (
GETPOST(
"nobin_use_transaction")) {
1360 $sqlfooter .=
"COMMIT;\n";
1362 if (
GETPOST(
"nobin_disable_fk")) {
1363 $sqlfooter .=
"SET FOREIGN_KEY_CHECKS=1;\n";
1365 $sqlfooter .=
"\n\n-- Dump completed on ".date(
'Y-m-d G-i-s');
1366 fwrite($handle, $sqlfooter);
1386 public function sendBackup($sendto =
'', $from =
'', $subject =
'', $message =
'', $filename =
'', $filter =
'', $sizelimit = 100000000)
1388 global
$conf, $langs;
1397 if (!empty($from)) {
1405 if (!empty($sendto)) {
1413 if (!empty($subject)) {
1419 if (empty($message)) {
1423 $tmpfiles = array();
1424 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
1432 if ($tmpfiles && is_array($tmpfiles)) {
1433 foreach ($tmpfiles as $key => $val) {
1434 if ($key ==
'fullname') {
1435 $filepath = array($val);
1438 if ($key ==
'type') {
1439 $mimetype = array($val);
1441 if ($key ==
'relativename') {
1442 $filename = array($val);
1448 if ($filesize > $sizelimit) {
1449 $message .=
'<br>'.$langs->trans(
"BackupIsTooLargeSend");
1450 $documenturl =
$dolibarr_main_url_root.
'/document.php?modulepart=systemtools&atachement=1&file=backup/'.urlencode($filename[0]);
1451 $message .=
'<br><a href='.$documenturl.
'>Download link</a>';
1457 $output =
'No backup file found';
1463 include_once DOL_DOCUMENT_ROOT .
'/core/class/CMailFile.class.php';
1464 $mailfile =
new CMailFile($subject, $sendto, $from, $message, $filepath, $mimetype, $filename,
'',
'', 0, 1);
1466 if ($mailfile->error) {
1468 $output = $mailfile->error;
1474 if (!$error && $mailfile !==
null) {
1475 $result = $mailfile->sendfile();
1478 $output = $mailfile->error;
1484 $this->error =
"Error sending backup file ".((string) $error);
1485 $this->output = $output;
1504 dol_syslog(
"Utils::cleanUnfinishedCronjob Starting cleaning");
1507 require_once DOL_DOCUMENT_ROOT .
'/cron/class/cronjob.class.php';
1511 $this_job->fetch(-1,
'Utils',
'cleanUnfinishedCronjob');
1512 if (empty($this_job->id) || !empty($this_job->error)) {
1513 dol_syslog(
"Utils::cleanUnfinishedCronjob Unable to fetch himself: ".$this_job->error, LOG_ERR);
1518 $this_job->processing = 0;
1519 if ($this_job->update($user) < 0) {
1520 dol_syslog(
"Utils::cleanUnfinishedCronjob Unable to update himself: ".implode(
', ', $this_job->errors), LOG_ERR);
1525 $cron_job->fetchAll(
'DESC',
't.rowid', 100, 0, 1, [], 1);
1528 foreach ($cron_job->lines as $job_line) {
1530 if (empty($job_line->pid)) {
1531 dol_syslog(
"Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id.
" don't have a PID", LOG_DEBUG);
1536 $job->fetch($job_line->id);
1537 if (empty($job->id) || !empty($job->error)) {
1538 dol_syslog(
"Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id.
" can't be fetch: ".$job->error, LOG_ERR);
1543 if (! posix_kill($job->pid, 0)) {
1545 $job->processing = 0;
1549 $job->lastresult = strval(-1);
1550 $job->lastoutput =
'Job killed by job cleanUnfinishedCronjob';
1552 if ($job->update($user) < 0) {
1553 dol_syslog(
"Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id.
" can't be updated: ".implode(
', ', $job->errors), LOG_ERR);
1556 dol_syslog(
"Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id.
" cleaned");
1560 dol_syslog(
"Utils::cleanUnfinishedCronjob Cleaning completed");
global $dolibarr_main_url_root
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Class to manage ECM directories.
Class to manage utility methods.
executeCLI($command, $outputfile, $execmethod=0, $redirectionfile=null, $noescapecommand=0, $redirectionfileerr=null)
Execute a CLI command.
__construct($db)
Constructor.
generateDoc($module)
Generate documentation of a Module.
getShellPasswordParam($password)
Return the -p parameter of mysqldump with the password, escaped to be used in a shell command line.
compressSyslogs()
This saves syslog files and compresses older ones.
sendBackup($sendto='', $from='', $subject='', $message='', $filename='', $filter='', $sizelimit=100000000)
Make a send last backup of database or fil in param CAN BE A CRON TASK.
dumpDatabase($compression='none', $type='auto', $usedefault=1, $file='auto', $keeplastnfiles=0, $execmethod=0, $lowmemorydump=0)
Make a backup of database CAN BE A CRON TASK.
cleanUnfinishedCronjob()
Clean unfinished cronjob in processing when pid is no longer present in the system CAN BE A CRON TASK...
purgeFiles($choices='tempfilesold+logfiles', $nbsecondsold=86400)
Purge files into directory of data files.
dol_move($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array(), $entity=null)
Move a file into another name.
dol_filesize($pathoffile)
Return size of a file.
dol_copy($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=0)
Copy a file to another 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.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_is_file($pathoffile)
Return if path is a file.
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
dol_most_recent_file($dir, $regexfilter='', $excludefilter=array('(\.meta|_preview.*\.png) $', '^\.'), $nohook=0, $mode=0)
Return file(s) into a directory (by default most recent)
dol_is_dir($folder)
Test if filename is a directory.
dolReplaceInFile($srcfile, $arrayreplacement, $destfile='', $newmask='0', $indexdatabase=0, $arrayreplacementisregex=0)
Make replacement of strings into a file.
dol_now($mode='gmt')
Return date for now.
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='', $keepspaces=0)
Clean a string from all punctuation characters to use it as a ref or login.
dol_sanitizePathName($str, $newstr='_', $unaccent=0, $allowdash=0)
Clean a string to use it as a path name.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
dolChmod($filepath, $newmask='')
Change mod of a file.
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, $nodefault=0)
Return value of a param into GET or POST supervariable.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
dolMd2Asciidoc($content, $parser='dolibarr', $replaceimagepath=null)
Function to parse MD content into ASCIIDOC.