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';
319 dol_mkdir($conf->admin->dir_output.
'/backup');
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';
604 dol_mkdir($conf->admin->dir_output.
'/backup');
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';
632 dol_mkdir($conf->admin->dir_output.
'/backup');
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);
803 global $conf, $langs, $user,
$mysoc;
808 $modulelowercase = strtolower($module);
812 $dir = $dirins.
'/'.$modulelowercase;
817 dol_include_once($modulelowercase.
'/core/modules/mod'.$module.
'.class.php');
818 $class =
'mod'.$module;
820 if (class_exists($class)) {
829 $langs->load(
"errors");
830 dol_print_error(
null, $langs->trans(
"ErrorFailedToLoadModuleDescriptorForXXX", $module));
834 $arrayversion = explode(
'.',
$moduleobj->version, 3);
835 if (count($arrayversion)) {
836 $FILENAMEASCII = strtolower($module).
'.asciidoc';
837 $FILENAMEDOC = strtolower($module).
'.html';
838 $FILENAMEDOCPDF = strtolower($module).
'.pdf';
841 $dirofmoduledoc =
dol_buildpath(strtolower($module), 0).
'/doc';
842 $dirofmoduletmp =
dol_buildpath(strtolower($module), 0).
'/doc/temp';
843 $outputfiledoc = $dirofmoduledoc.
'/'.$FILENAMEDOC;
844 if ($dirofmoduledoc) {
851 if (!is_writable($dirofmoduletmp)) {
852 $this->error =
'Dir '.$dirofmoduletmp.
' does not exists or is not writable';
857 $this->error =
'Setup of module ModuleBuilder not complete';
862 dol_copy($dirofmodule.
'/README.md', $dirofmoduletmp.
'/README.md',
'0', 1);
863 dol_copy($dirofmodule.
'/ChangeLog.md', $dirofmoduletmp.
'/ChangeLog.md',
'0', 1);
866 $arrayreplacement = array();
867 $arrayreplacement[
'/^#\s.*/m'] =
'';
868 $arrayreplacement[
'/^#/m'] =
'##';
870 dolReplaceInFile($dirofmoduletmp.
'/README.md', $arrayreplacement,
'',
'0', 0, 1);
871 dolReplaceInFile($dirofmoduletmp.
'/ChangeLog.md', $arrayreplacement,
'',
'0', 0, 1);
874 $destfile = $dirofmoduletmp.
'/'.$FILENAMEASCII;
876 $fhandle = fopen($destfile,
'w+');
878 $specs =
dol_dir_list(
dol_buildpath(strtolower($module).
'/doc', 0),
'files', 1,
'(\.md|\.asciidoc)$', array(
'\/temp\/'));
881 foreach ($specs as $spec) {
882 if (preg_match(
'/notindoc/', $spec[
'relativename'])) {
885 if (preg_match(
'/example/', $spec[
'relativename'])) {
888 if (preg_match(
'/disabled/', $spec[
'relativename'])) {
892 $pathtofile = strtolower($module).
'/doc/'.$spec[
'relativename'];
893 $format =
'asciidoc';
894 if (preg_match(
'/\.md$/i', $spec[
'name'])) {
895 $format =
'markdown';
898 $filecursor = @file_get_contents($spec[
'fullname']);
900 fwrite($fhandle, ($i ?
"\n<<<\n\n" :
"").$filecursor.
"\n");
902 $this->error =
'Failed to concat content of file '.$spec[
'fullname'];
911 $contentreadme = file_get_contents($dirofmoduletmp.
'/README.md');
912 $contentchangelog = file_get_contents($dirofmoduletmp.
'/ChangeLog.md');
914 include DOL_DOCUMENT_ROOT.
'/core/lib/parsemd.lib.php';
917 $arrayreplacement = array(
918 'mymodule' => strtolower($module),
919 'MyModule' => $module,
920 'MYMODULE' => strtoupper($module),
921 'My module' => $module,
922 'my module' => $module,
923 'Mon module' => $module,
924 'mon module' => $module,
925 'htdocs/modulebuilder/template' => strtolower($module),
926 '__MYCOMPANY_NAME__' =>
$mysoc->name,
927 '__KEYWORDS__' => $module,
928 '__USER_FULLNAME__' => $user->getFullName($langs),
929 '__USER_EMAIL__' => $user->email,
931 '---Put here your own copyright and developer email---' =>
dol_print_date($now,
'dayrfc').
' '.$user->getFullName($langs).($user->email ?
' <'.$user->email.
'>' :
''),
932 '__DATA_SPECIFICATION__' =>
'Not yet available',
942 $currentdir = getcwd();
945 require_once DOL_DOCUMENT_ROOT.
'/core/class/utils.class.php';
946 $utils =
new Utils($this->db);
949 $command =
getDolGlobalString(
'MODULEBUILDER_ASCIIDOCTOR') .
' '.$destfile.
' -n -o '.$dirofmoduledoc.
'/'.$FILENAMEDOC;
950 $outfile = $dirofmoduletmp.
'/out.tmp';
952 $resarray = $utils->executeCLI($command, $outfile);
953 if ($resarray[
'result'] !=
'0') {
954 $this->error = $resarray[
'error'].
' '.$resarray[
'output'];
955 $this->errors[] = $this->error;
957 $result = ($resarray[
'result'] == 0) ? 1 : 0;
958 if ($result < 0 && empty($this->errors)) {
959 $this->error = $langs->trans(
"ErrorFailToGenerateFile", $FILENAMEDOC);
960 $this->errors[] = $this->error;
964 $command =
getDolGlobalString(
'MODULEBUILDER_ASCIIDOCTORPDF') .
' '.$destfile.
' -n -o '.$dirofmoduledoc.
'/'.$FILENAMEDOCPDF;
965 $outfile = $dirofmoduletmp.
'/outpdf.tmp';
966 $resarray = $utils->executeCLI($command, $outfile);
967 if ($resarray[
'result'] !=
'0') {
968 $this->error = $resarray[
'error'].
' '.$resarray[
'output'];
969 $this->errors[] = $this->error;
971 $result = ($resarray[
'result'] == 0) ? 1 : 0;
972 if ($result < 0 && empty($this->errors)) {
973 $this->error = $langs->trans(
"ErrorFailToGenerateFile", $FILENAMEDOCPDF);
974 $this->errors[] = $this->error;
989 $langs->load(
"errors");
990 $this->error = $langs->trans(
"ErrorCheckVersionIsDefined");
1007 if (empty($conf->loghandlers[
'mod_syslog_file'])) {
1011 if (!function_exists(
'gzopen')) {
1012 $this->error =
'Support for gzopen not available in this PHP';
1016 require_once DOL_DOCUMENT_ROOT .
'/core/lib/files.lib.php';
1021 $mainlogdir = DOL_DATA_ROOT;
1022 $mainlog =
'dolibarr.log';
1024 $mainlogfull = str_replace(
'DOL_DATA_ROOT', DOL_DATA_ROOT, $conf->global->SYSLOG_FILE);
1025 $mainlogdir = dirname($mainlogfull);
1026 $mainlog = basename($mainlogfull);
1029 $tabfiles =
dol_dir_list(DOL_DATA_ROOT,
'files', 0,
'^(dolibarr_.+|odt2pdf)\.log$');
1030 $tabfiles[] = array(
'name' => $mainlog,
'path' => $mainlogdir);
1032 foreach ($tabfiles as $file) {
1033 $logname = $file[
'name'];
1034 $logpath = $file[
'path'];
1039 $filter =
'^'.preg_quote($logname,
'/').
'\.([0-9]+)\.gz$';
1041 $gzfilestmp =
dol_dir_list($logpath,
'files', 0, $filter);
1044 foreach ($gzfilestmp as $gzfile) {
1045 $tabmatches = array();
1046 preg_match(
'/'.$filter.
'/i', $gzfile[
'name'], $tabmatches);
1048 $numsave = intval($tabmatches[1]);
1050 $gzfiles[$numsave] = $gzfile;
1053 krsort($gzfiles, SORT_NUMERIC);
1055 foreach ($gzfiles as $numsave => $dummy) {
1056 if (
dol_is_file($logpath.
'/'.$logname.
'.'.($numsave + 1).
'.gz')) {
1060 if ($numsave >= $nbSaves) {
1061 dol_delete_file($logpath.
'/'.$logname.
'.'.$numsave.
'.gz', 0, 0, 0,
null,
false, 0);
1063 dol_move($logpath.
'/'.$logname.
'.'.$numsave.
'.gz', $logpath.
'/'.$logname.
'.'.($numsave + 1).
'.gz',
'0', 1, 0, 0);
1070 $gzfilehandle = gzopen($logpath.
'/'.$logname.
'.1.gz',
'wb9');
1072 if (empty($gzfilehandle)) {
1073 $this->error =
'Failted to open file '.$logpath.
'/'.$logname.
'.1.gz';
1077 $sourcehandle = fopen($logpath.
'/'.$logname,
'r');
1079 if (empty($sourcehandle)) {
1080 $this->error =
'Failed to open file '.$logpath.
'/'.$logname;
1084 while (!feof($sourcehandle)) {
1085 gzwrite($gzfilehandle, fread($sourcehandle, 512 * 1024));
1088 fclose($sourcehandle);
1089 gzclose($gzfilehandle);
1091 dolChmod($logpath.
'/'.$logname.
'.1.gz');
1097 $newlog = fopen($logpath.
'/'.$logname,
'a+');
1105 $this->output =
'Archive log files (keeping last SYSLOG_FILE_SAVES='.$nbSaves.
' files) done.';
1119 public function backupTables($outputfile, $tables =
'*')
1125 if (is_a(
$db,
'DoliDBMysqli')) {
1127 $db->db->set_charset(
'utf8');
1130 $db->query(
'SET NAMES utf8');
1131 $db->query(
'SET CHARACTER SET utf8');
1135 if ($tables ==
'*') {
1137 $result =
$db->query(
'SHOW FULL TABLES WHERE Table_type = \'BASE TABLE\'');
1138 while ($row =
$db->fetch_row($result)) {
1139 $tables[] = $row[0];
1142 $tables = is_array($tables) ? $tables : explode(
',', $tables);
1146 $handle = fopen($outputfile,
'w+');
1147 if (fwrite($handle,
'') ===
false) {
1148 $langs->load(
"errors");
1149 dol_syslog(
"Failed to open file ".$outputfile, LOG_ERR);
1150 $errormsg = $langs->trans(
"ErrorFailedToWriteInDir");
1156 $sqlhead .=
"-- ".$db::LABEL.
" dump via php with Dolibarr ".DOL_VERSION.
"
1158-- Host: ".
$db->db->host_info.
" Database: ".
$db->database_name.
"
1159-- ------------------------------------------------------
1160-- Server version ".
$db->db->server_info.
"
1175 if (
GETPOST(
"nobin_disable_fk")) {
1176 $sqlhead .=
"SET FOREIGN_KEY_CHECKS=0;\n";
1179 if (
GETPOST(
"nobin_use_transaction")) {
1180 $sqlhead .=
"SET AUTOCOMMIT=0;\nSTART TRANSACTION;\n";
1183 fwrite($handle, $sqlhead);
1186 if (
GETPOST(
"nobin_sql_ignore")) {
1187 $ignore =
'IGNORE ';
1190 if (
GETPOST(
"nobin_delayed")) {
1191 $delayed =
'DELAYED ';
1195 foreach ($tables as $table) {
1197 fwrite($handle,
"\n--\n-- Table structure for table `".$table.
"`\n--\n");
1200 fwrite($handle,
"DROP TABLE IF EXISTS `".$table.
"`;\n");
1202 fwrite($handle,
"/*!40101 SET @saved_cs_client = @@character_set_client */;\n");
1203 fwrite($handle,
"/*!40101 SET character_set_client = utf8 */;\n");
1204 $resqldrop =
$db->query(
'SHOW CREATE TABLE '.$table);
1205 $row2 =
$db->fetch_row($resqldrop);
1206 if (empty($row2[1])) {
1207 fwrite($handle,
"\n-- WARNING: Show create table ".$table.
" return empty string when it should not.\n");
1209 fwrite($handle, $row2[1].
";\n");
1213 fwrite($handle,
"\n--\n-- Dumping data for table `".$table.
"`\n--\n");
1214 if (!
GETPOST(
"nobin_nolocks")) {
1215 fwrite($handle,
"LOCK TABLES `".$table.
"` WRITE;\n");
1217 if (
GETPOST(
"nobin_disable_fk")) {
1218 fwrite($handle,
"ALTER TABLE `".$table.
"` DISABLE KEYS;\n");
1220 fwrite($handle,
"/*!40000 ALTER TABLE `".$table.
"` DISABLE KEYS */;\n");
1223 $sql =
"SELECT * FROM ".$table;
1224 $result =
$db->query($sql);
1225 while ($row =
$db->fetch_row($result)) {
1227 fwrite($handle,
"INSERT ".$delayed.$ignore.
"INTO ".$table.
" VALUES (");
1228 $columns = count($row);
1229 for ($j = 0; $j < $columns; $j++) {
1231 if ($row[$j] ==
null && !is_string($row[$j])) {
1234 } elseif (is_string($row[$j]) && $row[$j] ==
'') {
1237 } elseif (is_numeric($row[$j]) && !strcmp((
string) $row[$j], (
string) ((
float) $row[$j] + 0))) {
1241 $row[$j] = addslashes($row[$j]);
1242 $row[$j] = preg_replace(
"#\n#",
"\\n", $row[$j]);
1243 $row[$j] =
"'".$row[$j].
"'";
1246 fwrite($handle, implode(
',', $row).
");\n");
1248 if (
GETPOST(
"nobin_disable_fk")) {
1249 fwrite($handle,
"ALTER TABLE `".$table.
"` ENABLE KEYS;\n");
1251 if (!
GETPOST(
"nobin_nolocks")) {
1252 fwrite($handle,
"UNLOCK TABLES;\n");
1254 fwrite($handle,
"\n\n\n");
1278 $sqlfooter =
"\n\n";
1279 if (
GETPOST(
"nobin_use_transaction")) {
1280 $sqlfooter .=
"COMMIT;\n";
1282 if (
GETPOST(
"nobin_disable_fk")) {
1283 $sqlfooter .=
"SET FOREIGN_KEY_CHECKS=1;\n";
1285 $sqlfooter .=
"\n\n-- Dump completed on ".date(
'Y-m-d G-i-s');
1286 fwrite($handle, $sqlfooter);
1306 public function sendBackup($sendto =
'', $from =
'', $subject =
'', $message =
'', $filename =
'', $filter =
'', $sizelimit = 100000000)
1308 global $conf, $langs;
1317 if (!empty($from)) {
1325 if (!empty($sendto)) {
1333 if (!empty($subject)) {
1339 if (empty($message)) {
1343 $tmpfiles = array();
1344 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
1346 if (
dol_is_file($conf->admin->dir_output.
'/backup/'.$filename)) {
1352 if ($tmpfiles && is_array($tmpfiles)) {
1353 foreach ($tmpfiles as $key => $val) {
1354 if ($key ==
'fullname') {
1355 $filepath = array($val);
1358 if ($key ==
'type') {
1359 $mimetype = array($val);
1361 if ($key ==
'relativename') {
1362 $filename = array($val);
1368 if ($filesize > $sizelimit) {
1369 $message .=
'<br>'.$langs->trans(
"BackupIsTooLargeSend");
1370 $documenturl =
$dolibarr_main_url_root.
'/document.php?modulepart=systemtools&atachement=1&file=backup/'.urlencode($filename[0]);
1371 $message .=
'<br><a href='.$documenturl.
'>Download link</a>';
1377 $output =
'No backup file found';
1383 include_once DOL_DOCUMENT_ROOT .
'/core/class/CMailFile.class.php';
1384 $mailfile =
new CMailFile($subject, $sendto, $from, $message, $filepath, $mimetype, $filename,
'',
'', 0, 1);
1386 if ($mailfile->error) {
1388 $output = $mailfile->error;
1394 if (!$error && $mailfile !==
null) {
1395 $result = $mailfile->sendfile();
1398 $output = $mailfile->error;
1404 $this->error =
"Error sending backup file ".((string) $error);
1405 $this->output = $output;
1424 dol_syslog(
"Utils::cleanUnfinishedCronjob Starting cleaning");
1427 require_once DOL_DOCUMENT_ROOT .
'/cron/class/cronjob.class.php';
1431 $this_job->fetch(-1,
'Utils',
'cleanUnfinishedCronjob');
1432 if (empty($this_job->id) || !empty($this_job->error)) {
1433 dol_syslog(
"Utils::cleanUnfinishedCronjob Unable to fetch himself: ".$this_job->error, LOG_ERR);
1438 $this_job->processing = 0;
1439 if ($this_job->update($user) < 0) {
1440 dol_syslog(
"Utils::cleanUnfinishedCronjob Unable to update himself: ".implode(
', ', $this_job->errors), LOG_ERR);
1445 $cron_job->fetchAll(
'DESC',
't.rowid', 100, 0, 1, [], 1);
1448 foreach ($cron_job->lines as $job_line) {
1450 if (empty($job_line->pid)) {
1451 dol_syslog(
"Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id.
" don't have a PID", LOG_DEBUG);
1456 $job->fetch($job_line->id);
1457 if (empty($job->id) || !empty($job->error)) {
1458 dol_syslog(
"Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id.
" can't be fetch: ".$job->error, LOG_ERR);
1463 if (! posix_kill($job->pid, 0)) {
1465 $job->processing = 0;
1469 $job->lastresult = strval(-1);
1470 $job->lastoutput =
'Job killed by job cleanUnfinishedCronjob';
1472 if ($job->update($user) < 0) {
1473 dol_syslog(
"Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id.
" can't be updated: ".implode(
', ', $job->errors), LOG_ERR);
1476 dol_syslog(
"Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id.
" cleaned");
1480 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.