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);
151 if (isModEnabled(
'syslog')) {
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,
179 if (isModEnabled(
'api')) {
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') {
204 if (isModEnabled(
'ecm') && $choice ==
'allfiles') {
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)' :
'');
223 if (isModEnabled(
'api')) {
241 if (preg_match(
'/^win/i', PHP_OS)) {
243 return '-p"'.str_replace(array(
'"',
'`',
'$'), array(
'\\"',
'\\`',
'\\$'), $password).
'"';
247 return '-p'.escapeshellarg($password);
264 public function dumpDatabase($compression =
'none', $type =
'auto', $usedefault = 1, $file =
'auto', $keeplastnfiles = 0, $execmethod = 0, $lowmemorydump = 0)
266 global
$db,
$conf, $langs, $dolibarr_main_data_root;
267 global $dolibarr_main_db_name, $dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_port, $dolibarr_main_db_pass;
268 global $dolibarr_main_db_character_set;
270 $langs->load(
"admin");
272 dol_syslog(
"Utils::dumpDatabase type=".$type.
" compression=".$compression.
" file=".$file, LOG_DEBUG);
273 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
279 if (!in_array($compression, array(
'none',
'gz',
'bz',
'zip',
'zstd'))) {
280 $langs->load(
"errors");
281 $this->error = $langs->transnoentitiesnoconv(
"ErrorBadValueForParameter", $compression,
"Compression");
286 if ($type ==
'auto') {
287 $type = $this->db->type;
289 if (!in_array($type, array(
'postgresql',
'pgsql',
'mysql',
'mysqli',
'mysqlnobin'))) {
290 $langs->load(
"errors");
291 $this->error = $langs->transnoentitiesnoconv(
"ErrorBadValueForParameter", $type,
"Basetype");
296 if ($file ==
'auto') {
299 if (in_array($type, array(
'mysql',
'mysqli'))) {
300 $prefix =
'mysqldump';
303 if (in_array($type, array(
'pgsql'))) {
309 $outputdir =
$conf->admin->dir_output.
'/backup';
314 if ($type ==
'mysql' || $type ==
'mysqli') {
316 $cmddump =
$db->getPathOfDump();
320 if (empty($cmddump)) {
321 $this->error =
"Failed to detect command to use for mysqldump. Try a manual backup before to set path of command.";
325 $outputfile = $outputdir.
'/'.$file;
327 $compression = $compression ? $compression :
'none';
328 if ($compression ==
'gz') {
329 $outputfile .=
'.gz';
330 } elseif ($compression ==
'bz') {
331 $outputfile .=
'.bz2';
332 } elseif ($compression ==
'zstd') {
333 $outputfile .=
'.zst';
335 $outputerror = $outputfile.
'.err';
340 $command = preg_replace(
'/(\$|%)/',
'', $command);
341 if (preg_match(
"/\s/", $command)) {
342 $command = escapeshellarg($command);
346 $param = $dolibarr_main_db_name.
" -h ".$dolibarr_main_db_host;
347 $param .=
" -u ".$dolibarr_main_db_user;
348 if (!empty($dolibarr_main_db_port)) {
349 $param .=
" -P ".$dolibarr_main_db_port.
" --protocol=tcp";
351 if (
GETPOST(
"use_transaction",
"alpha")) {
352 $param .=
" --single-transaction";
354 if (
GETPOST(
"disable_fk",
"alpha") || $usedefault) {
357 if (
GETPOST(
"sql_compat",
"alpha") &&
GETPOST(
"sql_compat",
"alpha") !=
'NONE') {
358 $param .=
" --compatible=".escapeshellarg(
GETPOST(
"sql_compat",
"alpha"));
360 if (
GETPOST(
"drop_database",
"alpha")) {
361 $param .=
" --add-drop-database";
363 if (
GETPOST(
"use_mysql_quick_param",
"alpha")) {
364 $param .=
" --quick";
366 if (
GETPOST(
"use_force",
"alpha")) {
369 if (
GETPOST(
"sql_structure",
"alpha") || $usedefault) {
370 if (
GETPOST(
"drop",
"alpha") || $usedefault) {
371 $param .=
" --add-drop-table=TRUE";
373 $param .=
" --add-drop-table=FALSE";
378 if (
GETPOST(
"disable-add-locks",
"alpha")) {
379 $param .=
" --add-locks=FALSE";
381 if (
GETPOST(
"sql_data",
"alpha") || $usedefault) {
382 $param .=
" --tables";
383 if (
GETPOST(
"showcolumns",
"alpha") || $usedefault) {
386 if (
GETPOST(
"extended_ins",
"alpha") || $usedefault) {
389 $param .=
" --skip-extended-insert";
391 if (
GETPOST(
"delayed",
"alpha")) {
392 $param .=
" --delayed-insert";
394 if (
GETPOST(
"sql_ignore",
"alpha")) {
395 $param .=
" --insert-ignore";
397 if (
GETPOST(
"hexforbinary",
"alpha") || $usedefault) {
398 $param .=
" --hex-blob";
403 if ($dolibarr_main_db_character_set ==
'utf8mb4') {
405 $param .=
" --default-character-set=utf8mb4 --no-tablespaces";
407 $param .=
" --default-character-set=utf8 --no-tablespaces";
409 $paramcrypted = $param;
410 $paramclear = $param;
411 if (!empty($dolibarr_main_db_pass)) {
412 $paramcrypted .=
' -p"'.preg_replace(
'/./i',
'*', $dolibarr_main_db_pass).
'"';
413 $paramclear .=
' '.$this->getShellPasswordParam($dolibarr_main_db_pass);
419 $fullcommandcrypted = $command.
" ".$paramcrypted.
" 2>&1";
420 $fullcommandclear = $command.
" ".$paramclear.
" 2>&1";
421 if (!$lowmemorydump) {
422 if ($compression ==
'none') {
423 $handle = fopen($outputfile,
'w');
424 } elseif ($compression ==
'gz') {
425 $handle = gzopen($outputfile,
'w');
426 } elseif ($compression ==
'bz') {
427 $handle = bzopen($outputfile,
'w');
428 } elseif ($compression ==
'zstd') {
429 $handle = fopen($outputfile,
'w');
432 if ($compression ==
'none') {
433 $fullcommandclear .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." > "'.dol_sanitizePathName($outputfile).
'"';
434 $fullcommandcrypted .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." > "'.dol_sanitizePathName($outputfile).
'"';
436 } elseif ($compression ==
'gz') {
437 $fullcommandclear .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | gzip > "'.dol_sanitizePathName($outputfile).
'"';
438 $fullcommandcrypted .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | gzip > "'.dol_sanitizePathName($outputfile).
'"';
439 $paramcrypted .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | gzip';
441 } elseif ($compression ==
'bz') {
442 $fullcommandclear .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | bzip2 > "'.dol_sanitizePathName($outputfile).
'"';
443 $fullcommandcrypted .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | bzip2 > "'.dol_sanitizePathName($outputfile).
'"';
444 $paramcrypted .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | bzip2';
446 } elseif ($compression ==
'zstd') {
447 $fullcommandclear .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | zstd > "'.dol_sanitizePathName($outputfile).
'"';
448 $fullcommandcrypted .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | zstd > "'.dol_sanitizePathName($outputfile).
'"';
449 $paramcrypted .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | zstd';
459 if (empty($execmethod)) {
463 dol_syslog(
"Utils::dumpDatabase execmethod=".$execmethod.
", lowmemorydump=".$lowmemorydump.
", command=".$fullcommandcrypted, LOG_INFO);
468 if (!empty($MemoryLimit)) {
469 @ini_set(
'memory_limit', $MemoryLimit);
473 if ($execmethod == 1) {
474 $output_arr = array();
477 exec($fullcommandclear, $output_arr, $retval);
485 $langs->load(
"errors");
486 dol_syslog(
"Datadump retval after exec=".$retval, LOG_ERR);
487 $errormsg =
'Error '.$retval;
491 if (!empty($output_arr)) {
492 foreach ($output_arr as $key => $read) {
494 if ($i == 1 && preg_match(
'/Warning.*Using a password/i', $read)) {
499 if (!$lowmemorydump) {
500 fwrite($handle, $read.($execmethod == 2 ?
'' :
"\n"));
501 if (preg_match(
'/'.preg_quote(
'-- Dump completed',
'/').
'/i', $read)) {
503 } elseif (preg_match(
'/'.preg_quote(
'SET SQL_NOTES=@OLD_SQL_NOTES',
'/').
'/i', $read)) {
510 } elseif ($lowmemorydump) {
516 if ($execmethod == 2) {
517 $handlein = popen($fullcommandclear,
'r');
520 while (!feof($handlein)) {
522 $read = fgets($handlein);
524 if ($i == 1 && preg_match(
'/Warning.*Using a password/i', $read)) {
527 fwrite($handle, $read);
528 if (preg_match(
'/'.preg_quote(
'-- Dump completed').
'/i', $read)) {
530 } elseif (preg_match(
'/'.preg_quote(
'SET SQL_NOTES=@OLD_SQL_NOTES').
'/i', $read)) {
538 if (!$lowmemorydump) {
539 if ($compression ==
'none') {
541 } elseif ($compression ==
'gz') {
543 } elseif ($compression ==
'bz') {
545 } elseif ($compression ==
'zstd') {
552 $langs->load(
"errors");
553 dol_syslog(
"Failed to open file ".$outputfile, LOG_ERR);
554 $errormsg = $langs->trans(
"ErrorFailedToWriteInDir");
558 if ($compression ==
'none') {
559 $handle = fopen($outputfile,
'r');
560 } elseif ($compression ==
'gz') {
561 $handle = gzopen($outputfile,
'r');
562 } elseif ($compression ==
'bz') {
563 $handle = bzopen($outputfile,
'r');
564 } elseif ($compression ==
'zstd') {
565 $handle = fopen(
"compress.zstd://" . $outputfile,
"rb");
569 $errormsg = fgets($handle, 2048);
573 if ($compression ==
'none') {
575 } elseif ($compression ==
'gz') {
577 } elseif ($compression ==
'bz') {
579 } elseif ($compression ==
'zstd') {
582 if ($ok && preg_match(
'/^-- (MySql|MariaDB)/i', $errormsg) || preg_match(
'/^\/\*M?!999999/', $errormsg)) {
588 @
dol_move($outputfile, $outputerror,
'0', 1, 0, 0);
591 $langs->load(
"errors");
592 $errormsg = $langs->trans(
"ErrorFailedToRunExternalCommand");
598 $this->output = $errormsg;
599 $this->error = $errormsg;
600 $this->result = array(
"commandbackuplastdone" => $command.
" ".$paramcrypted,
"commandbackuptorun" =>
"");
605 if ($type ==
'mysqlnobin') {
606 $outputfile = $outputdir.
'/'.$file;
607 $outputfiletemp = $outputfile.
'-TMP.sql';
609 $compression = $compression ? $compression :
'none';
610 if ($compression ==
'gz') {
611 $outputfile .=
'.gz';
613 if ($compression ==
'bz') {
614 $outputfile .=
'.bz2';
616 $outputerror = $outputfile.
'.err';
619 if ($compression ==
'gz' or $compression ==
'bz') {
620 $this->backupTables($outputfiletemp);
621 dol_compress_file($outputfiletemp, $outputfile, $compression);
622 unlink($outputfiletemp);
624 $this->backupTables($outputfile);
628 $this->result = array(
"commandbackuplastdone" =>
"",
"commandbackuptorun" =>
"");
632 if ($type ==
'postgresql' || $type ==
'pgsql') {
635 $outputfile = $outputdir.
'/'.$file;
637 $compression = $compression ? $compression :
'none';
638 if ($compression ==
'gz') {
639 $outputfile .=
'.gz';
641 if ($compression ==
'bz') {
642 $outputfile .=
'.bz2';
644 $outputerror = $outputfile.
'.err';
649 $command = preg_replace(
'/(\$|%)/',
'', $command);
650 if (preg_match(
"/\s/", $command)) {
651 $command = escapeshellarg($command);
657 $param .=
" --no-tablespaces --inserts -h ".$dolibarr_main_db_host;
658 $param .=
" -U ".$dolibarr_main_db_user;
659 if (!empty($dolibarr_main_db_port)) {
660 $param .=
" -p ".$dolibarr_main_db_port;
663 $param .=
" --disable-dollar-quoting";
665 if (
GETPOST(
"drop_database")) {
668 if (
GETPOST(
"sql_structure")) {
670 $param .=
" --add-drop-table";
677 if (!
GETPOST(
"sql_structure")) {
684 $param .=
' -f "'.$outputfile.
'"';
686 if ($compression ==
'gz') {
690 $paramcrypted = $param;
691 $paramclear = $param;
697 $paramcrypted .=
" -w ".$dolibarr_main_db_name;
698 $paramclear .=
" -w ".$dolibarr_main_db_name;
701 $this->result = array(
"commandbackuplastdone" =>
"",
"commandbackuptorun" => $command.
" ".$paramcrypted);
705 if (!$errormsg && $keeplastnfiles > 0) {
706 $tmpfiles =
dol_dir_list(
$conf->admin->dir_output.
'/backup',
'files', 0,
'',
'(\.err|\.old|\.sav)$',
'date', SORT_DESC);
708 if (is_array($tmpfiles)) {
709 foreach ($tmpfiles as $key => $val) {
711 if ($i <= $keeplastnfiles) {
719 return ($errormsg ? -1 : 0);
737 public function executeCLI($command, $outputfile, $execmethod = 0, $redirectionfile =
null, $noescapecommand = 0, $redirectionfileerr =
null)
739 global
$conf, $langs;
745 if (empty($noescapecommand)) {
746 $command = escapeshellcmd($command);
749 if ($redirectionfile) {
750 $command .=
" > ".dol_sanitizePathName($redirectionfile);
753 if ($redirectionfileerr && ($redirectionfileerr != $redirectionfile)) {
755 $command .=
" 2> ".dol_sanitizePathName($redirectionfileerr);
763 if (empty($execmethod)) {
767 dol_syslog(
"Utils::executeCLI execmethod=".$execmethod.
" command=".$command, LOG_DEBUG);
768 $output_arr = array();
770 if ($execmethod == 1) {
772 exec($command, $output_arr, $retval);
775 $langs->load(
"errors");
776 dol_syslog(
"Utils::executeCLI retval after exec=".$retval, LOG_ERR);
777 $error =
'Error '.$retval;
780 if ($execmethod == 2) {
781 $handle = fopen($outputfile,
'w+b');
783 dol_syslog(
"Utils::executeCLI run command ".$command);
784 $handlein = popen($command,
'r');
785 while (!feof($handlein)) {
786 $read = fgets($handlein);
787 fwrite($handle, $read);
788 $output_arr[] = $read;
797 if (is_array($output_arr) && count($output_arr) > 0) {
798 foreach ($output_arr as $val) {
799 $output .= $val.($execmethod == 2 ?
'' :
"\n");
803 dol_syslog(
"Utils::executeCLI result=".$result.
" output=".$output.
" error=".$error, LOG_DEBUG);
805 return array(
'result' => $result,
'output' => $output,
'error' => $error);
816 global
$conf, $langs, $user, $mysoc;
821 $modulelowercase = strtolower($module);
825 $dir = $dirins.
'/'.$modulelowercase;
830 dol_include_once($modulelowercase.
'/core/modules/mod'.$module.
'.class.php');
831 $class =
'mod'.$module;
833 if (class_exists($class)) {
842 $langs->load(
"errors");
843 dol_print_error(
null, $langs->trans(
"ErrorFailedToLoadModuleDescriptorForXXX", $module));
847 $arrayversion = explode(
'.',
$moduleobj->version, 3);
848 if (count($arrayversion)) {
849 $FILENAMEASCII = strtolower($module).
'.asciidoc';
850 $FILENAMEDOC = strtolower($module).
'.html';
851 $FILENAMEDOCPDF = strtolower($module).
'.pdf';
854 $dirofmoduledoc =
dol_buildpath(strtolower($module), 0).
'/doc';
855 $dirofmoduletmp =
dol_buildpath(strtolower($module), 0).
'/doc/temp';
856 $outputfiledoc = $dirofmoduledoc.
'/'.$FILENAMEDOC;
857 if ($dirofmoduledoc) {
864 if (!is_writable($dirofmoduletmp)) {
865 $this->error =
'Dir '.$dirofmoduletmp.
' does not exists or is not writable';
870 $this->error =
'Setup of module ModuleBuilder not complete';
875 dol_copy($dirofmodule.
'/README.md', $dirofmoduletmp.
'/README.md',
'0', 1);
876 dol_copy($dirofmodule.
'/ChangeLog.md', $dirofmoduletmp.
'/ChangeLog.md',
'0', 1);
879 $arrayreplacement = array();
880 $arrayreplacement[
'/^#\s.*/m'] =
'';
881 $arrayreplacement[
'/^#/m'] =
'##';
883 dolReplaceInFile($dirofmoduletmp.
'/README.md', $arrayreplacement,
'',
'0', 0, 1);
884 dolReplaceInFile($dirofmoduletmp.
'/ChangeLog.md', $arrayreplacement,
'',
'0', 0, 1);
887 $destfile = $dirofmoduletmp.
'/'.$FILENAMEASCII;
889 $fhandle = fopen($destfile,
'w+');
891 $specs =
dol_dir_list(
dol_buildpath(strtolower($module).
'/doc', 0),
'files', 1,
'(\.md|\.asciidoc)$', array(
'\/temp\/'));
894 foreach ($specs as $spec) {
895 if (preg_match(
'/notindoc/', $spec[
'relativename'])) {
898 if (preg_match(
'/example/', $spec[
'relativename'])) {
901 if (preg_match(
'/disabled/', $spec[
'relativename'])) {
905 $pathtofile = strtolower($module).
'/doc/'.$spec[
'relativename'];
906 $format =
'asciidoc';
907 if (preg_match(
'/\.md$/i', $spec[
'name'])) {
908 $format =
'markdown';
911 $filecursor = @file_get_contents($spec[
'fullname']);
913 fwrite($fhandle, ($i ?
"\n<<<\n\n" :
"").$filecursor.
"\n");
915 $this->error =
'Failed to concat content of file '.$spec[
'fullname'];
924 $contentreadme = file_get_contents($dirofmoduletmp.
'/README.md');
925 $contentchangelog = file_get_contents($dirofmoduletmp.
'/ChangeLog.md');
927 include DOL_DOCUMENT_ROOT.
'/core/lib/parsemd.lib.php';
930 $arrayreplacement = array(
931 'mymodule' => strtolower($module),
932 'MyModule' => $module,
933 'MYMODULE' => strtoupper($module),
934 'My module' => $module,
935 'my module' => $module,
936 'Mon module' => $module,
937 'mon module' => $module,
938 'htdocs/modulebuilder/template' => strtolower($module),
939 '__MYCOMPANY_NAME__' => $mysoc->name,
940 '__KEYWORDS__' => $module,
941 '__USER_FULLNAME__' => $user->getFullName($langs),
942 '__USER_EMAIL__' => $user->email,
944 '---Put here your own copyright and developer email---' =>
dol_print_date($now,
'dayrfc').
' '.$user->getFullName($langs).($user->email ?
' <'.$user->email.
'>' :
''),
945 '__DATA_SPECIFICATION__' =>
'Not yet available',
955 $currentdir = getcwd();
958 require_once DOL_DOCUMENT_ROOT.
'/core/class/utils.class.php';
959 $utils =
new Utils($this->db);
962 $command =
getDolGlobalString(
'MODULEBUILDER_ASCIIDOCTOR') .
' '.$destfile.
' -n -o '.$dirofmoduledoc.
'/'.$FILENAMEDOC;
963 $outfile = $dirofmoduletmp.
'/out.tmp';
965 $resarray = $utils->executeCLI($command, $outfile);
966 if ($resarray[
'result'] !=
'0') {
967 $this->error = $resarray[
'error'].
' '.$resarray[
'output'];
968 $this->errors[] = $this->error;
970 $result = ($resarray[
'result'] == 0) ? 1 : 0;
971 if ($result < 0 && empty($this->errors)) {
972 $this->error = $langs->trans(
"ErrorFailToGenerateFile", $FILENAMEDOC);
973 $this->errors[] = $this->error;
977 $command =
getDolGlobalString(
'MODULEBUILDER_ASCIIDOCTORPDF') .
' '.$destfile.
' -n -o '.$dirofmoduledoc.
'/'.$FILENAMEDOCPDF;
978 $outfile = $dirofmoduletmp.
'/outpdf.tmp';
979 $resarray = $utils->executeCLI($command, $outfile);
980 if ($resarray[
'result'] !=
'0') {
981 $this->error = $resarray[
'error'].
' '.$resarray[
'output'];
982 $this->errors[] = $this->error;
984 $result = ($resarray[
'result'] == 0) ? 1 : 0;
985 if ($result < 0 && empty($this->errors)) {
986 $this->error = $langs->trans(
"ErrorFailToGenerateFile", $FILENAMEDOCPDF);
987 $this->errors[] = $this->error;
1002 $langs->load(
"errors");
1003 $this->error = $langs->trans(
"ErrorCheckVersionIsDefined");
1020 if (empty(
$conf->loghandlers[
'mod_syslog_file'])) {
1024 if (!function_exists(
'gzopen')) {
1025 $this->error =
'Support for gzopen not available in this PHP';
1029 require_once DOL_DOCUMENT_ROOT .
'/core/lib/files.lib.php';
1034 $mainlogdir = DOL_DATA_ROOT;
1035 $mainlog =
'dolibarr.log';
1037 $mainlogfull = str_replace(
'DOL_DATA_ROOT', DOL_DATA_ROOT,
$conf->global->SYSLOG_FILE);
1038 $mainlogdir = dirname($mainlogfull);
1039 $mainlog = basename($mainlogfull);
1042 $tabfiles =
dol_dir_list(DOL_DATA_ROOT,
'files', 0,
'^(dolibarr_.+|odt2pdf)\.log$');
1043 $tabfiles[] = array(
'name' => $mainlog,
'path' => $mainlogdir);
1045 foreach ($tabfiles as $file) {
1046 $logname = $file[
'name'];
1047 $logpath = $file[
'path'];
1052 $filter =
'^'.preg_quote($logname,
'/').
'\.([0-9]+)\.gz$';
1054 $gzfilestmp =
dol_dir_list($logpath,
'files', 0, $filter);
1057 foreach ($gzfilestmp as $gzfile) {
1058 $tabmatches = array();
1059 preg_match(
'/'.$filter.
'/i', $gzfile[
'name'], $tabmatches);
1061 $numsave = intval($tabmatches[1]);
1063 $gzfiles[$numsave] = $gzfile;
1066 krsort($gzfiles, SORT_NUMERIC);
1068 foreach ($gzfiles as $numsave => $dummy) {
1069 if (
dol_is_file($logpath.
'/'.$logname.
'.'.($numsave + 1).
'.gz')) {
1073 if ($numsave >= $nbSaves) {
1074 dol_delete_file($logpath.
'/'.$logname.
'.'.$numsave.
'.gz', 0, 0, 0,
null,
false, 0);
1076 dol_move($logpath.
'/'.$logname.
'.'.$numsave.
'.gz', $logpath.
'/'.$logname.
'.'.($numsave + 1).
'.gz',
'0', 1, 0, 0);
1083 $gzfilehandle = gzopen($logpath.
'/'.$logname.
'.1.gz',
'wb9');
1085 if (empty($gzfilehandle)) {
1086 $this->error =
'Failted to open file '.$logpath.
'/'.$logname.
'.1.gz';
1090 $sourcehandle = fopen($logpath.
'/'.$logname,
'r');
1092 if (empty($sourcehandle)) {
1093 $this->error =
'Failed to open file '.$logpath.
'/'.$logname;
1097 while (!feof($sourcehandle)) {
1098 gzwrite($gzfilehandle, fread($sourcehandle, 512 * 1024));
1101 fclose($sourcehandle);
1102 gzclose($gzfilehandle);
1104 dolChmod($logpath.
'/'.$logname.
'.1.gz');
1110 $newlog = fopen($logpath.
'/'.$logname,
'a+');
1118 $this->output =
'Archive log files (keeping last SYSLOG_FILE_SAVES='.$nbSaves.
' files) done.';
1132 public function backupTables($outputfile, $tables =
'*')
1136 global $dolibarr_main_db_character_set;
1140 $charset = ($dolibarr_main_db_character_set ==
'utf8mb4' ?
'utf8mb4' :
'utf8');
1141 $sanitizedcharset =
$db->sanitize($charset);
1142 if (is_a(
$db,
'DoliDBMysqli')) {
1144 $db->db->set_charset($charset);
1147 $db->query(
'SET NAMES '.
$db->sanitize($charset));
1148 $db->query(
'SET CHARACTER SET '.
$db->sanitize($charset));
1152 if ($tables ==
'*') {
1154 $result =
$db->query(
'SHOW FULL TABLES WHERE Table_type = \'BASE TABLE\'');
1155 while ($row =
$db->fetch_row($result)) {
1156 $tables[] = $row[0];
1159 $tables = is_array($tables) ? $tables : explode(
',', $tables);
1163 $handle = fopen($outputfile,
'w+');
1164 if (fwrite($handle,
'') ===
false) {
1165 $langs->load(
"errors");
1166 dol_syslog(
"Failed to open file ".$outputfile, LOG_ERR);
1167 $errormsg = $langs->trans(
"ErrorFailedToWriteInDir");
1173 $sqlhead .=
"-- ".$db::LABEL.
" dump via php with Dolibarr ".DOL_VERSION.
"
1175-- Host: ".
$db->db->host_info.
" Database: ".
$db->database_name.
"
1176-- ------------------------------------------------------
1177-- Server version ".
$db->db->server_info.
"
1192 if (
GETPOST(
"nobin_disable_fk")) {
1193 $sqlhead .=
"SET FOREIGN_KEY_CHECKS=0;\n";
1196 if (
GETPOST(
"nobin_use_transaction")) {
1197 $sqlhead .=
"SET AUTOCOMMIT=0;\nSTART TRANSACTION;\n";
1200 fwrite($handle, $sqlhead);
1203 if (
GETPOST(
"nobin_sql_ignore")) {
1204 $ignore =
'IGNORE ';
1207 if (
GETPOST(
"nobin_delayed")) {
1208 $delayed =
'DELAYED ';
1212 foreach ($tables as $table) {
1214 fwrite($handle,
"\n--\n-- Table structure for table `".$table.
"`\n--\n");
1217 fwrite($handle,
"DROP TABLE IF EXISTS `".$table.
"`;\n");
1219 fwrite($handle,
"/*!40101 SET @saved_cs_client = @@character_set_client */;\n");
1220 fwrite($handle,
"/*!40101 SET character_set_client = ".$sanitizedcharset.
" */;\n");
1221 $resqldrop =
$db->query(
'SHOW CREATE TABLE '.$table);
1222 $row2 =
$db->fetch_row($resqldrop);
1223 if (empty($row2[1])) {
1224 fwrite($handle,
"\n-- WARNING: Show create table ".$table.
" return empty string when it should not.\n");
1226 fwrite($handle, $row2[1].
";\n");
1230 fwrite($handle,
"\n--\n-- Dumping data for table `".$table.
"`\n--\n");
1231 if (!
GETPOST(
"nobin_nolocks")) {
1232 fwrite($handle,
"LOCK TABLES `".$table.
"` WRITE;\n");
1234 if (
GETPOST(
"nobin_disable_fk")) {
1235 fwrite($handle,
"ALTER TABLE `".$table.
"` DISABLE KEYS;\n");
1237 fwrite($handle,
"/*!40000 ALTER TABLE `".$table.
"` DISABLE KEYS */;\n");
1240 $sql =
"SELECT * FROM ".$table;
1241 $result =
$db->query($sql);
1242 while ($row =
$db->fetch_row($result)) {
1244 fwrite($handle,
"INSERT ".$delayed.$ignore.
"INTO ".$table.
" VALUES (");
1245 $columns = count($row);
1246 for ($j = 0; $j < $columns; $j++) {
1248 if ($row[$j] ==
null && !is_string($row[$j])) {
1251 } elseif (is_string($row[$j]) && $row[$j] ==
'') {
1254 } elseif (is_numeric($row[$j]) && !strcmp((
string) $row[$j], (
string) ((
float) $row[$j] + 0))) {
1258 $row[$j] = addslashes($row[$j]);
1259 $row[$j] = preg_replace(
"#\n#",
"\\n", $row[$j]);
1260 $row[$j] =
"'".$row[$j].
"'";
1263 fwrite($handle, implode(
',', $row).
");\n");
1265 if (
GETPOST(
"nobin_disable_fk")) {
1266 fwrite($handle,
"ALTER TABLE `".$table.
"` ENABLE KEYS;\n");
1268 if (!
GETPOST(
"nobin_nolocks")) {
1269 fwrite($handle,
"UNLOCK TABLES;\n");
1271 fwrite($handle,
"\n\n\n");
1295 $sqlfooter =
"\n\n";
1296 if (
GETPOST(
"nobin_use_transaction")) {
1297 $sqlfooter .=
"COMMIT;\n";
1299 if (
GETPOST(
"nobin_disable_fk")) {
1300 $sqlfooter .=
"SET FOREIGN_KEY_CHECKS=1;\n";
1302 $sqlfooter .=
"\n\n-- Dump completed on ".date(
'Y-m-d G-i-s');
1303 fwrite($handle, $sqlfooter);
1323 public function sendBackup($sendto =
'', $from =
'', $subject =
'', $message =
'', $filename =
'', $filter =
'', $sizelimit = 100000000)
1325 global
$conf, $langs;
1334 if (!empty($from)) {
1342 if (!empty($sendto)) {
1350 if (!empty($subject)) {
1356 if (empty($message)) {
1360 $tmpfiles = array();
1361 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
1369 if ($tmpfiles && is_array($tmpfiles)) {
1370 foreach ($tmpfiles as $key => $val) {
1371 if ($key ==
'fullname') {
1372 $filepath = array($val);
1375 if ($key ==
'type') {
1376 $mimetype = array($val);
1378 if ($key ==
'relativename') {
1379 $filename = array($val);
1385 if ($filesize > $sizelimit) {
1386 $message .=
'<br>'.$langs->trans(
"BackupIsTooLargeSend");
1387 $documenturl =
$dolibarr_main_url_root.
'/document.php?modulepart=systemtools&atachement=1&file=backup/'.urlencode($filename[0]);
1388 $message .=
'<br><a href='.$documenturl.
'>Download link</a>';
1394 $output =
'No backup file found';
1400 include_once DOL_DOCUMENT_ROOT .
'/core/class/CMailFile.class.php';
1401 $mailfile =
new CMailFile($subject, $sendto, $from, $message, $filepath, $mimetype, $filename,
'',
'', 0, 1);
1403 if ($mailfile->error) {
1405 $output = $mailfile->error;
1411 if (!$error && $mailfile !==
null) {
1412 $result = $mailfile->sendfile();
1415 $output = $mailfile->error;
1421 $this->error =
"Error sending backup file ".((string) $error);
1422 $this->output = $output;
1441 dol_syslog(
"Utils::cleanUnfinishedCronjob Starting cleaning");
1444 require_once DOL_DOCUMENT_ROOT .
'/cron/class/cronjob.class.php';
1448 $this_job->fetch(-1,
'Utils',
'cleanUnfinishedCronjob');
1449 if (empty($this_job->id) || !empty($this_job->error)) {
1450 dol_syslog(
"Utils::cleanUnfinishedCronjob Unable to fetch himself: ".$this_job->error, LOG_ERR);
1455 $this_job->processing = 0;
1456 if ($this_job->update($user) < 0) {
1457 dol_syslog(
"Utils::cleanUnfinishedCronjob Unable to update himself: ".implode(
', ', $this_job->errors), LOG_ERR);
1462 $cron_job->fetchAll(
'DESC',
't.rowid', 100, 0, 1, [], 1);
1465 foreach ($cron_job->lines as $job_line) {
1467 if (empty($job_line->pid)) {
1468 dol_syslog(
"Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id.
" don't have a PID", LOG_DEBUG);
1473 $job->fetch($job_line->id);
1474 if (empty($job->id) || !empty($job->error)) {
1475 dol_syslog(
"Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id.
" can't be fetch: ".$job->error, LOG_ERR);
1480 if (! posix_kill($job->pid, 0)) {
1482 $job->processing = 0;
1486 $job->lastresult = strval(-1);
1487 $job->lastoutput =
'Job killed by job cleanUnfinishedCronjob';
1489 if ($job->update($user) < 0) {
1490 dol_syslog(
"Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id.
" can't be updated: ".implode(
', ', $job->errors), LOG_ERR);
1493 dol_syslog(
"Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id.
" cleaned");
1497 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_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_move($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array(), $entity=0)
Move a file into another name.
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.
dolChmod($filepath, $newmask='')
Change mod of a file.
dol_now($mode='auto')
Return date for now.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0)
Clean a string to use it as a file name.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
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...
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
dolMd2Asciidoc($content, $parser='dolibarr', $replaceimagepath=null)
Function to parse MD content into ASCIIDOC.