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)' :
'');
247 public function dumpDatabase($compression =
'none', $type =
'auto', $usedefault = 1, $file =
'auto', $keeplastnfiles = 0, $execmethod = 0, $lowmemorydump = 0)
249 global
$db,
$conf, $langs, $dolibarr_main_data_root;
250 global $dolibarr_main_db_name, $dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_port, $dolibarr_main_db_pass;
251 global $dolibarr_main_db_character_set;
253 $langs->load(
"admin");
255 dol_syslog(
"Utils::dumpDatabase type=".$type.
" compression=".$compression.
" file=".$file, LOG_DEBUG);
256 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
262 if (!in_array($compression, array(
'none',
'gz',
'bz',
'zip',
'zstd'))) {
263 $langs->load(
"errors");
264 $this->error = $langs->transnoentitiesnoconv(
"ErrorBadValueForParameter", $compression,
"Compression");
269 if ($type ==
'auto') {
270 $type = $this->db->type;
272 if (!in_array($type, array(
'postgresql',
'pgsql',
'mysql',
'mysqli',
'mysqlnobin'))) {
273 $langs->load(
"errors");
274 $this->error = $langs->transnoentitiesnoconv(
"ErrorBadValueForParameter", $type,
"Basetype");
279 if ($file ==
'auto') {
282 if (in_array($type, array(
'mysql',
'mysqli'))) {
283 $prefix =
'mysqldump';
286 if (in_array($type, array(
'pgsql'))) {
292 $outputdir =
$conf->admin->dir_output.
'/backup';
297 if ($type ==
'mysql' || $type ==
'mysqli') {
299 $cmddump =
$db->getPathOfDump();
303 if (empty($cmddump)) {
304 $this->error =
"Failed to detect command to use for mysqldump. Try a manual backup before to set path of command.";
308 $outputfile = $outputdir.
'/'.$file;
310 $compression = $compression ? $compression :
'none';
311 if ($compression ==
'gz') {
312 $outputfile .=
'.gz';
313 } elseif ($compression ==
'bz') {
314 $outputfile .=
'.bz2';
315 } elseif ($compression ==
'zstd') {
316 $outputfile .=
'.zst';
318 $outputerror = $outputfile.
'.err';
323 $command = preg_replace(
'/(\$|%)/',
'', $command);
324 if (preg_match(
"/\s/", $command)) {
325 $command = escapeshellarg($command);
329 $param = $dolibarr_main_db_name.
" -h ".$dolibarr_main_db_host;
330 $param .=
" -u ".$dolibarr_main_db_user;
331 if (!empty($dolibarr_main_db_port)) {
332 $param .=
" -P ".$dolibarr_main_db_port.
" --protocol=tcp";
334 if (
GETPOST(
"use_transaction",
"alpha")) {
335 $param .=
" --single-transaction";
337 if (
GETPOST(
"disable_fk",
"alpha") || $usedefault) {
340 if (
GETPOST(
"sql_compat",
"alpha") &&
GETPOST(
"sql_compat",
"alpha") !=
'NONE') {
341 $param .=
" --compatible=".escapeshellarg(
GETPOST(
"sql_compat",
"alpha"));
343 if (
GETPOST(
"drop_database",
"alpha")) {
344 $param .=
" --add-drop-database";
346 if (
GETPOST(
"use_mysql_quick_param",
"alpha")) {
347 $param .=
" --quick";
349 if (
GETPOST(
"use_force",
"alpha")) {
352 if (
GETPOST(
"sql_structure",
"alpha") || $usedefault) {
353 if (
GETPOST(
"drop",
"alpha") || $usedefault) {
354 $param .=
" --add-drop-table=TRUE";
356 $param .=
" --add-drop-table=FALSE";
361 if (
GETPOST(
"disable-add-locks",
"alpha")) {
362 $param .=
" --add-locks=FALSE";
364 if (
GETPOST(
"sql_data",
"alpha") || $usedefault) {
365 $param .=
" --tables";
366 if (
GETPOST(
"showcolumns",
"alpha") || $usedefault) {
369 if (
GETPOST(
"extended_ins",
"alpha") || $usedefault) {
372 $param .=
" --skip-extended-insert";
374 if (
GETPOST(
"delayed",
"alpha")) {
375 $param .=
" --delayed-insert";
377 if (
GETPOST(
"sql_ignore",
"alpha")) {
378 $param .=
" --insert-ignore";
380 if (
GETPOST(
"hexforbinary",
"alpha") || $usedefault) {
381 $param .=
" --hex-blob";
386 if ($dolibarr_main_db_character_set ==
'utf8mb4') {
388 $param .=
" --default-character-set=utf8mb4 --no-tablespaces";
390 $param .=
" --default-character-set=utf8 --no-tablespaces";
392 $paramcrypted = $param;
393 $paramclear = $param;
394 if (!empty($dolibarr_main_db_pass)) {
395 $paramcrypted .=
' -p"'.preg_replace(
'/./i',
'*', $dolibarr_main_db_pass).
'"';
396 $paramclear .=
' -p"'.str_replace(array(
'"',
'`',
'$'), array(
'\"',
'\`',
'\$'), $dolibarr_main_db_pass).
'"';
402 $fullcommandcrypted = $command.
" ".$paramcrypted.
" 2>&1";
403 $fullcommandclear = $command.
" ".$paramclear.
" 2>&1";
404 if (!$lowmemorydump) {
405 if ($compression ==
'none') {
406 $handle = fopen($outputfile,
'w');
407 } elseif ($compression ==
'gz') {
408 $handle = gzopen($outputfile,
'w');
409 } elseif ($compression ==
'bz') {
410 $handle = bzopen($outputfile,
'w');
411 } elseif ($compression ==
'zstd') {
412 $handle = fopen($outputfile,
'w');
417 if ($compression ==
'none') {
418 $fullcommandclear .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." > "'.dol_sanitizePathName($outputfile).
'"';
419 $fullcommandcrypted .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." > "'.dol_sanitizePathName($outputfile).
'"';
421 } elseif ($compression ==
'gz') {
422 $fullcommandclear .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | gzip > "'.dol_sanitizePathName($outputfile).
'"';
423 $fullcommandcrypted .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | gzip > "'.dol_sanitizePathName($outputfile).
'"';
424 $paramcrypted .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | gzip';
426 } elseif ($compression ==
'bz') {
427 $fullcommandclear .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | bzip2 > "'.dol_sanitizePathName($outputfile).
'"';
428 $fullcommandcrypted .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | bzip2 > "'.dol_sanitizePathName($outputfile).
'"';
429 $paramcrypted .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | bzip2';
431 } elseif ($compression ==
'zstd') {
432 $fullcommandclear .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | zstd > "'.dol_sanitizePathName($outputfile).
'"';
433 $fullcommandcrypted .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | zstd > "'.dol_sanitizePathName($outputfile).
'"';
434 $paramcrypted .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | zstd';
444 if (empty($execmethod)) {
448 dol_syslog(
"Utils::dumpDatabase execmethod=".$execmethod.
", lowmemorydump=".$lowmemorydump.
", command=".$fullcommandcrypted, LOG_INFO);
453 if (!empty($MemoryLimit)) {
454 @ini_set(
'memory_limit', $MemoryLimit);
458 if ($execmethod == 1) {
459 $output_arr = array();
462 exec($fullcommandclear, $output_arr, $retval);
470 $langs->load(
"errors");
471 dol_syslog(
"Datadump retval after exec=".$retval, LOG_ERR);
472 $errormsg =
'Error '.$retval;
476 if (!empty($output_arr)) {
477 foreach ($output_arr as $key => $read) {
479 if ($i == 1 && preg_match(
'/Warning.*Using a password/i', $read)) {
484 if (!$lowmemorydump) {
487 fwrite($handle, $read.($execmethod == 2 ?
'' :
"\n"));
488 if (preg_match(
'/'.preg_quote(
'-- Dump completed',
'/').
'/i', $read)) {
490 } elseif (preg_match(
'/'.preg_quote(
'SET SQL_NOTES=@OLD_SQL_NOTES',
'/').
'/i', $read)) {
497 } elseif ($lowmemorydump) {
503 if ($execmethod == 2) {
504 $handlein = popen($fullcommandclear,
'r');
507 while (!feof($handlein)) {
509 $read = fgets($handlein);
511 if ($i == 1 && preg_match(
'/Warning.*Using a password/i', $read)) {
514 fwrite($handle, $read);
515 if (preg_match(
'/'.preg_quote(
'-- Dump completed',
'/').
'/i', $read)) {
517 } elseif (preg_match(
'/'.preg_quote(
'SET SQL_NOTES=@OLD_SQL_NOTES',
'/').
'/i', $read)) {
525 if (!$lowmemorydump) {
526 if ($compression ==
'none') {
528 } elseif ($compression ==
'gz') {
530 } elseif ($compression ==
'bz') {
532 } elseif ($compression ==
'zstd') {
539 $langs->load(
"errors");
540 dol_syslog(
"Failed to open file ".$outputfile, LOG_ERR);
541 $errormsg = $langs->trans(
"ErrorFailedToWriteInDir");
545 if ($compression ==
'none') {
546 $handle = fopen($outputfile,
'r');
547 } elseif ($compression ==
'gz') {
548 $handle = gzopen($outputfile,
'r');
549 } elseif ($compression ==
'bz') {
550 $handle = bzopen($outputfile,
'r');
551 } elseif ($compression ==
'zstd') {
552 $handle = fopen($outputfile,
'r');
556 $errormsg = fgets($handle, 2048);
560 if ($compression ==
'none') {
562 } elseif ($compression ==
'gz') {
564 } elseif ($compression ==
'bz') {
566 } elseif ($compression ==
'zstd') {
569 if ($ok && preg_match(
'/^-- (MySql|MariaDB)/i', $errormsg) || preg_match(
'/^\/\*M?!999999/', $errormsg)) {
575 @
dol_move($outputfile, $outputerror,
'0', 1, 0, 0);
578 $langs->load(
"errors");
579 $errormsg = $langs->trans(
"ErrorFailedToRunExternalCommand");
585 $this->output = $errormsg;
586 $this->error = $errormsg;
587 $this->result = array(
"commandbackuplastdone" => $command.
" ".$paramcrypted,
"commandbackuptorun" =>
"");
592 if ($type ==
'mysqlnobin') {
593 $outputfile = $outputdir.
'/'.$file;
594 $outputfiletemp = $outputfile.
'-TMP.sql';
596 $compression = $compression ? $compression :
'none';
597 if ($compression ==
'gz') {
598 $outputfile .=
'.gz';
600 if ($compression ==
'bz') {
601 $outputfile .=
'.bz2';
603 $outputerror = $outputfile.
'.err';
606 if ($compression ==
'gz' or $compression ==
'bz') {
607 $this->backupTables($outputfiletemp);
608 dol_compress_file($outputfiletemp, $outputfile, $compression);
609 unlink($outputfiletemp);
611 $this->backupTables($outputfile);
615 $this->result = array(
"commandbackuplastdone" =>
"",
"commandbackuptorun" =>
"");
619 if ($type ==
'postgresql' || $type ==
'pgsql') {
622 $outputfile = $outputdir.
'/'.$file;
624 $compression = $compression ? $compression :
'none';
625 if ($compression ==
'gz') {
626 $outputfile .=
'.gz';
628 if ($compression ==
'bz') {
629 $outputfile .=
'.bz2';
631 $outputerror = $outputfile.
'.err';
636 $command = preg_replace(
'/(\$|%)/',
'', $command);
637 if (preg_match(
"/\s/", $command)) {
638 $command = escapeshellarg($command);
644 $param .=
" --no-tablespaces --inserts -h ".$dolibarr_main_db_host;
645 $param .=
" -U ".$dolibarr_main_db_user;
646 if (!empty($dolibarr_main_db_port)) {
647 $param .=
" -p ".$dolibarr_main_db_port;
650 $param .=
" --disable-dollar-quoting";
652 if (
GETPOST(
"drop_database")) {
655 if (
GETPOST(
"sql_structure")) {
657 $param .=
" --add-drop-table";
664 if (!
GETPOST(
"sql_structure")) {
671 $param .=
' -f "'.$outputfile.
'"';
673 if ($compression ==
'gz') {
677 $paramcrypted = $param;
678 $paramclear = $param;
684 $paramcrypted .=
" -w ".$dolibarr_main_db_name;
685 $paramclear .=
" -w ".$dolibarr_main_db_name;
688 $this->result = array(
"commandbackuplastdone" =>
"",
"commandbackuptorun" => $command.
" ".$paramcrypted);
692 if (!$errormsg && $keeplastnfiles > 0) {
693 $tmpfiles =
dol_dir_list(
$conf->admin->dir_output.
'/backup',
'files', 0,
'',
'(\.err|\.old|\.sav)$',
'date', SORT_DESC);
695 if (is_array($tmpfiles)) {
696 foreach ($tmpfiles as $key => $val) {
698 if ($i <= $keeplastnfiles) {
706 return ($errormsg ? -1 : 0);
724 public function executeCLI($command, $outputfile, $execmethod = 0, $redirectionfile =
null, $noescapecommand = 0, $redirectionfileerr =
null)
732 if (empty($noescapecommand)) {
733 $command = escapeshellcmd($command);
736 if ($redirectionfile) {
737 $command .=
" > ".dol_sanitizePathName($redirectionfile);
740 if ($redirectionfileerr && ($redirectionfileerr != $redirectionfile)) {
742 $command .=
" 2> ".dol_sanitizePathName($redirectionfileerr);
750 if (empty($execmethod)) {
754 dol_syslog(
"Utils::executeCLI execmethod=".$execmethod.
" command=".$command, LOG_DEBUG);
755 $output_arr = array();
757 if ($execmethod == 1) {
759 exec($command, $output_arr, $retval);
762 $langs->load(
"errors");
763 dol_syslog(
"Utils::executeCLI retval after exec=".$retval, LOG_ERR);
764 $error =
'Error '.$retval;
767 if ($execmethod == 2) {
768 $handle = fopen($outputfile,
'w+b');
770 dol_syslog(
"Utils::executeCLI run command ".$command);
771 $handlein = popen($command,
'r');
772 while (!feof($handlein)) {
773 $read = fgets($handlein);
774 fwrite($handle, $read);
775 $output_arr[] = $read;
784 if (is_array($output_arr) && count($output_arr) > 0) {
785 foreach ($output_arr as $val) {
786 $output .= $val.($execmethod == 2 ?
'' :
"\n");
790 dol_syslog(
"Utils::executeCLI result=".$result.
" output=".$output.
" error=".$error, LOG_DEBUG);
792 return array(
'result' => $result,
'output' => $output,
'error' => $error);
808 $modulelowercase = strtolower($module);
812 $dir = $dirins.
'/'.$modulelowercase;
817 dol_include_once($modulelowercase.
'/core/modules/mod'.$module.
'.class.php');
818 $class =
'mod'.$module;
821 if (class_exists($class)) {
830 $langs->load(
"errors");
831 dol_print_error(
null, $langs->trans(
"ErrorFailedToLoadModuleDescriptorForXXX", $module));
836 if (count($arrayversion)) {
837 $FILENAMEASCII = strtolower($module).
'.asciidoc';
838 $FILENAMEDOC = strtolower($module).
'.html';
839 $FILENAMEDOCPDF = strtolower($module).
'.pdf';
842 $dirofmoduledoc =
dol_buildpath(strtolower($module), 0).
'/doc';
843 $dirofmoduletmp =
dol_buildpath(strtolower($module), 0).
'/doc/temp';
844 $outputfiledoc = $dirofmoduledoc.
'/'.$FILENAMEDOC;
845 if ($dirofmoduledoc) {
852 if (!is_writable($dirofmoduletmp)) {
853 $this->error =
'Dir '.$dirofmoduletmp.
' does not exists or is not writable';
858 $this->error =
'Setup of module ModuleBuilder not complete';
863 dol_copy($dirofmodule.
'/README.md', $dirofmoduletmp.
'/README.md',
'0', 1);
864 dol_copy($dirofmodule.
'/ChangeLog.md', $dirofmoduletmp.
'/ChangeLog.md',
'0', 1);
867 $arrayreplacement = array();
868 $arrayreplacement[
'/^#\s.*/m'] =
'';
869 $arrayreplacement[
'/^#/m'] =
'##';
871 dolReplaceInFile($dirofmoduletmp.
'/README.md', $arrayreplacement,
'',
'0', 0, 1);
872 dolReplaceInFile($dirofmoduletmp.
'/ChangeLog.md', $arrayreplacement,
'',
'0', 0, 1);
875 $destfile = $dirofmoduletmp.
'/'.$FILENAMEASCII;
877 $fhandle = fopen($destfile,
'w+');
879 $specs =
dol_dir_list(
dol_buildpath(strtolower($module).
'/doc', 0),
'files', 1,
'(\.md|\.asciidoc)$', array(
'\/temp\/'));
882 foreach ($specs as $spec) {
883 if (preg_match(
'/notindoc/', $spec[
'relativename'])) {
886 if (preg_match(
'/example/', $spec[
'relativename'])) {
889 if (preg_match(
'/disabled/', $spec[
'relativename'])) {
893 $pathtofile = strtolower($module).
'/doc/'.$spec[
'relativename'];
894 $format =
'asciidoc';
895 if (preg_match(
'/\.md$/i', $spec[
'name'])) {
896 $format =
'markdown';
899 $filecursor = @file_get_contents($spec[
'fullname']);
901 fwrite($fhandle, ($i ?
"\n<<<\n\n" :
"").$filecursor.
"\n");
903 $this->error =
'Failed to concat content of file '.$spec[
'fullname'];
912 $contentreadme = file_get_contents($dirofmoduletmp.
'/README.md');
913 $contentchangelog = file_get_contents($dirofmoduletmp.
'/ChangeLog.md');
915 include DOL_DOCUMENT_ROOT.
'/core/lib/parsemd.lib.php';
918 $arrayreplacement = array(
919 'mymodule' => strtolower($module),
920 'MyModule' => $module,
921 'MYMODULE' => strtoupper($module),
922 'My module' => $module,
923 'my module' => $module,
924 'Mon module' => $module,
925 'mon module' => $module,
926 'htdocs/modulebuilder/template' => strtolower($module),
927 '__MYCOMPANY_NAME__' =>
$mysoc->name,
928 '__KEYWORDS__' => $module,
929 '__USER_FULLNAME__' => $user->getFullName($langs),
930 '__USER_EMAIL__' => $user->email,
932 '---Put here your own copyright and developer email---' =>
dol_print_date($now,
'dayrfc').
' '.$user->getFullName($langs).($user->email ?
' <'.$user->email.
'>' :
''),
933 '__DATA_SPECIFICATION__' =>
'Not yet available',
943 $currentdir = getcwd();
946 require_once DOL_DOCUMENT_ROOT.
'/core/class/utils.class.php';
947 $utils =
new Utils($this->db);
950 $command =
getDolGlobalString(
'MODULEBUILDER_ASCIIDOCTOR') .
' '.$destfile.
' -n -o '.$dirofmoduledoc.
'/'.$FILENAMEDOC;
951 $outfile = $dirofmoduletmp.
'/out.tmp';
953 $resarray = $utils->executeCLI($command, $outfile);
954 if ($resarray[
'result'] !=
'0') {
955 $this->error = $resarray[
'error'].
' '.$resarray[
'output'];
956 $this->errors[] = $this->error;
958 $result = ($resarray[
'result'] == 0) ? 1 : 0;
959 if ($result < 0 && empty($this->errors)) {
960 $this->error = $langs->trans(
"ErrorFailToGenerateFile", $FILENAMEDOC);
961 $this->errors[] = $this->error;
965 $command =
getDolGlobalString(
'MODULEBUILDER_ASCIIDOCTORPDF') .
' '.$destfile.
' -n -o '.$dirofmoduledoc.
'/'.$FILENAMEDOCPDF;
966 $outfile = $dirofmoduletmp.
'/outpdf.tmp';
967 $resarray = $utils->executeCLI($command, $outfile);
968 if ($resarray[
'result'] !=
'0') {
969 $this->error = $resarray[
'error'].
' '.$resarray[
'output'];
970 $this->errors[] = $this->error;
972 $result = ($resarray[
'result'] == 0) ? 1 : 0;
973 if ($result < 0 && empty($this->errors)) {
974 $this->error = $langs->trans(
"ErrorFailToGenerateFile", $FILENAMEDOCPDF);
975 $this->errors[] = $this->error;
990 $langs->load(
"errors");
991 $this->error = $langs->trans(
"ErrorCheckVersionIsDefined");
1008 if (empty(
$conf->loghandlers[
'mod_syslog_file'])) {
1012 if (!function_exists(
'gzopen')) {
1013 $this->error =
'Support for gzopen not available in this PHP';
1017 require_once DOL_DOCUMENT_ROOT .
'/core/lib/files.lib.php';
1022 $mainlogdir = DOL_DATA_ROOT;
1023 $mainlog =
'dolibarr.log';
1025 $mainlogfull = str_replace(
'DOL_DATA_ROOT', DOL_DATA_ROOT,
$conf->global->SYSLOG_FILE);
1026 $mainlogdir = dirname($mainlogfull);
1027 $mainlog = basename($mainlogfull);
1030 $tabfiles =
dol_dir_list(DOL_DATA_ROOT,
'files', 0,
'^(dolibarr_.+|odt2pdf)\.log$');
1031 $tabfiles[] = array(
'name' => $mainlog,
'path' => $mainlogdir);
1033 foreach ($tabfiles as $file) {
1034 $logname = $file[
'name'];
1035 $logpath = $file[
'path'];
1040 $filter =
'^'.preg_quote($logname,
'/').
'\.([0-9]+)\.gz$';
1042 $gzfilestmp =
dol_dir_list($logpath,
'files', 0, $filter);
1045 foreach ($gzfilestmp as $gzfile) {
1046 $tabmatches = array();
1047 preg_match(
'/'.$filter.
'/i', $gzfile[
'name'], $tabmatches);
1049 $numsave = intval($tabmatches[1]);
1051 $gzfiles[$numsave] = $gzfile;
1054 krsort($gzfiles, SORT_NUMERIC);
1056 foreach ($gzfiles as $numsave => $dummy) {
1057 if (
dol_is_file($logpath.
'/'.$logname.
'.'.($numsave + 1).
'.gz')) {
1061 if ($numsave >= $nbSaves) {
1062 dol_delete_file($logpath.
'/'.$logname.
'.'.$numsave.
'.gz', 0, 0, 0,
null,
false, 0);
1064 dol_move($logpath.
'/'.$logname.
'.'.$numsave.
'.gz', $logpath.
'/'.$logname.
'.'.($numsave + 1).
'.gz',
'0', 1, 0, 0);
1071 $gzfilehandle = gzopen($logpath.
'/'.$logname.
'.1.gz',
'wb9');
1073 if (empty($gzfilehandle)) {
1074 $this->error =
'Failted to open file '.$logpath.
'/'.$logname.
'.1.gz';
1078 $sourcehandle = fopen($logpath.
'/'.$logname,
'r');
1080 if (empty($sourcehandle)) {
1081 $this->error =
'Failed to open file '.$logpath.
'/'.$logname;
1085 while (!feof($sourcehandle)) {
1086 gzwrite($gzfilehandle, fread($sourcehandle, 512 * 1024));
1089 fclose($sourcehandle);
1090 gzclose($gzfilehandle);
1092 dolChmod($logpath.
'/'.$logname.
'.1.gz');
1098 $newlog = fopen($logpath.
'/'.$logname,
'a+');
1106 $this->output =
'Archive log files (keeping last SYSLOG_FILE_SAVES='.$nbSaves.
' files) done.';
1120 public function backupTables($outputfile, $tables =
'*')
1126 if (is_a(
$db,
'DoliDBMysqli')) {
1128 $db->db->set_charset(
'utf8');
1131 $db->query(
'SET NAMES utf8');
1132 $db->query(
'SET CHARACTER SET utf8');
1136 if ($tables ==
'*') {
1138 $result =
$db->query(
'SHOW FULL TABLES WHERE Table_type = \'BASE TABLE\'');
1139 while ($row =
$db->fetch_row($result)) {
1140 $tables[] = $row[0];
1143 $tables = is_array($tables) ? $tables : explode(
',', $tables);
1147 $handle = fopen($outputfile,
'w+');
1148 if (fwrite($handle,
'') ===
false) {
1149 $langs->load(
"errors");
1150 dol_syslog(
"Failed to open file ".$outputfile, LOG_ERR);
1151 $errormsg = $langs->trans(
"ErrorFailedToWriteInDir");
1157 $sqlhead .=
"-- ".$db::LABEL.
" dump via php with Dolibarr ".DOL_VERSION.
"
1159-- Host: ".
$db->db->host_info.
" Database: ".
$db->database_name.
"
1160-- ------------------------------------------------------
1161-- Server version ".
$db->db->server_info.
"
1176 if (
GETPOST(
"nobin_disable_fk")) {
1177 $sqlhead .=
"SET FOREIGN_KEY_CHECKS=0;\n";
1180 if (
GETPOST(
"nobin_use_transaction")) {
1181 $sqlhead .=
"SET AUTOCOMMIT=0;\nSTART TRANSACTION;\n";
1184 fwrite($handle, $sqlhead);
1187 if (
GETPOST(
"nobin_sql_ignore")) {
1188 $ignore =
'IGNORE ';
1191 if (
GETPOST(
"nobin_delayed")) {
1192 $delayed =
'DELAYED ';
1196 foreach ($tables as $table) {
1198 fwrite($handle,
"\n--\n-- Table structure for table `".$table.
"`\n--\n");
1201 fwrite($handle,
"DROP TABLE IF EXISTS `".$table.
"`;\n");
1203 fwrite($handle,
"/*!40101 SET @saved_cs_client = @@character_set_client */;\n");
1204 fwrite($handle,
"/*!40101 SET character_set_client = utf8 */;\n");
1205 $resqldrop =
$db->query(
'SHOW CREATE TABLE '.$table);
1206 $row2 =
$db->fetch_row($resqldrop);
1207 if (empty($row2[1])) {
1208 fwrite($handle,
"\n-- WARNING: Show create table ".$table.
" return empty string when it should not.\n");
1210 fwrite($handle, $row2[1].
";\n");
1214 fwrite($handle,
"\n--\n-- Dumping data for table `".$table.
"`\n--\n");
1215 if (!
GETPOST(
"nobin_nolocks")) {
1216 fwrite($handle,
"LOCK TABLES `".$table.
"` WRITE;\n");
1218 if (
GETPOST(
"nobin_disable_fk")) {
1219 fwrite($handle,
"ALTER TABLE `".$table.
"` DISABLE KEYS;\n");
1221 fwrite($handle,
"/*!40000 ALTER TABLE `".$table.
"` DISABLE KEYS */;\n");
1224 $sql =
"SELECT * FROM ".$table;
1225 $result =
$db->query($sql);
1226 while ($row =
$db->fetch_row($result)) {
1228 fwrite($handle,
"INSERT ".$delayed.$ignore.
"INTO ".$table.
" VALUES (");
1229 $columns = count($row);
1230 for ($j = 0; $j < $columns; $j++) {
1232 if ($row[$j] ==
null && !is_string($row[$j])) {
1235 } elseif (is_string($row[$j]) && $row[$j] ==
'') {
1238 } elseif (is_numeric($row[$j]) && !strcmp((
string) $row[$j], (
string) ((
float) $row[$j] + 0))) {
1242 $row[$j] = addslashes($row[$j]);
1243 $row[$j] = preg_replace(
"#\n#",
"\\n", $row[$j]);
1244 $row[$j] =
"'".$row[$j].
"'";
1247 fwrite($handle, implode(
',', $row).
");\n");
1249 if (
GETPOST(
"nobin_disable_fk")) {
1250 fwrite($handle,
"ALTER TABLE `".$table.
"` ENABLE KEYS;\n");
1252 if (!
GETPOST(
"nobin_nolocks")) {
1253 fwrite($handle,
"UNLOCK TABLES;\n");
1255 fwrite($handle,
"\n\n\n");
1279 $sqlfooter =
"\n\n";
1280 if (
GETPOST(
"nobin_use_transaction")) {
1281 $sqlfooter .=
"COMMIT;\n";
1283 if (
GETPOST(
"nobin_disable_fk")) {
1284 $sqlfooter .=
"SET FOREIGN_KEY_CHECKS=1;\n";
1286 $sqlfooter .=
"\n\n-- Dump completed on ".date(
'Y-m-d G-i-s');
1287 fwrite($handle, $sqlfooter);
1307 public function sendBackup($sendto =
'', $from =
'', $subject =
'', $message =
'', $filename =
'', $filter =
'', $sizelimit = 100000000)
1309 global
$conf, $langs;
1318 if (!empty($from)) {
1326 if (!empty($sendto)) {
1334 if (!empty($subject)) {
1340 if (empty($message)) {
1344 $tmpfiles = array();
1345 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
1353 if ($tmpfiles && is_array($tmpfiles)) {
1354 foreach ($tmpfiles as $key => $val) {
1355 if ($key ==
'fullname') {
1356 $filepath = array($val);
1359 if ($key ==
'type') {
1360 $mimetype = array($val);
1362 if ($key ==
'relativename') {
1363 $filename = array($val);
1369 if ($filesize > $sizelimit) {
1370 $message .=
'<br>'.$langs->trans(
"BackupIsTooLargeSend");
1371 $documenturl =
$dolibarr_main_url_root.
'/document.php?modulepart=systemtools&atachement=1&file=backup/'.urlencode($filename[0]);
1372 $message .=
'<br><a href='.$documenturl.
'>Download link</a>';
1378 $output =
'No backup file found';
1384 include_once DOL_DOCUMENT_ROOT .
'/core/class/CMailFile.class.php';
1385 $mailfile =
new CMailFile($subject, $sendto, $from, $message, $filepath, $mimetype, $filename,
'',
'', 0, 1);
1387 if ($mailfile->error) {
1389 $output = $mailfile->error;
1395 if (!$error && $mailfile !==
null) {
1396 $result = $mailfile->sendfile();
1399 $output = $mailfile->error;
1405 $this->error =
"Error sending backup file ".((string) $error);
1406 $this->output = $output;
1425 dol_syslog(
"Utils::cleanUnfinishedCronjob Starting cleaning");
1428 require_once DOL_DOCUMENT_ROOT .
'/cron/class/cronjob.class.php';
1432 $this_job->fetch(-1,
'Utils',
'cleanUnfinishedCronjob');
1433 if (empty($this_job->id) || !empty($this_job->error)) {
1434 dol_syslog(
"Utils::cleanUnfinishedCronjob Unable to fetch himself: ".$this_job->error, LOG_ERR);
1439 $this_job->processing = 0;
1440 if ($this_job->update($user) < 0) {
1441 dol_syslog(
"Utils::cleanUnfinishedCronjob Unable to update himself: ".implode(
', ', $this_job->errors), LOG_ERR);
1446 $cron_job->fetchAll(
'DESC',
't.rowid', 100, 0, 1, [], 1);
1449 foreach ($cron_job->lines as $job_line) {
1451 if (empty($job_line->pid)) {
1452 dol_syslog(
"Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id.
" don't have a PID", LOG_DEBUG);
1457 $job->fetch($job_line->id);
1458 if (empty($job->id) || !empty($job->error)) {
1459 dol_syslog(
"Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id.
" can't be fetch: ".$job->error, LOG_ERR);
1464 if (! posix_kill($job->pid, 0)) {
1466 $job->processing = 0;
1470 $job->lastresult = strval(-1);
1471 $job->lastoutput =
'Job killed by job cleanUnfinishedCronjob';
1473 if ($job->update($user) < 0) {
1474 dol_syslog(
"Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id.
" can't be updated: ".implode(
', ', $job->errors), LOG_ERR);
1477 dol_syslog(
"Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id.
" cleaned");
1481 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.
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_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)
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.