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')) {
246 public function dumpDatabase($compression =
'none', $type =
'auto', $usedefault = 1, $file =
'auto', $keeplastnfiles = 0, $execmethod = 0, $lowmemorydump = 0)
248 global
$db,
$conf, $langs, $dolibarr_main_data_root;
249 global $dolibarr_main_db_name, $dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_port, $dolibarr_main_db_pass;
250 global $dolibarr_main_db_character_set;
252 $langs->load(
"admin");
254 dol_syslog(
"Utils::dumpDatabase type=".$type.
" compression=".$compression.
" file=".$file, LOG_DEBUG);
255 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
261 if (!in_array($compression, array(
'none',
'gz',
'bz',
'zip',
'zstd'))) {
262 $langs->load(
"errors");
263 $this->error = $langs->transnoentitiesnoconv(
"ErrorBadValueForParameter", $compression,
"Compression");
268 if ($type ==
'auto') {
269 $type = $this->db->type;
271 if (!in_array($type, array(
'postgresql',
'pgsql',
'mysql',
'mysqli',
'mysqlnobin'))) {
272 $langs->load(
"errors");
273 $this->error = $langs->transnoentitiesnoconv(
"ErrorBadValueForParameter", $type,
"Basetype");
278 if ($file ==
'auto') {
281 if (in_array($type, array(
'mysql',
'mysqli'))) {
282 $prefix =
'mysqldump';
285 if (in_array($type, array(
'pgsql'))) {
291 $outputdir =
$conf->admin->dir_output.
'/backup';
296 if ($type ==
'mysql' || $type ==
'mysqli') {
298 $cmddump =
$db->getPathOfDump();
302 if (empty($cmddump)) {
303 $this->error =
"Failed to detect command to use for mysqldump. Try a manual backup before to set path of command.";
307 $outputfile = $outputdir.
'/'.$file;
309 $compression = $compression ? $compression :
'none';
310 if ($compression ==
'gz') {
311 $outputfile .=
'.gz';
312 } elseif ($compression ==
'bz') {
313 $outputfile .=
'.bz2';
314 } elseif ($compression ==
'zstd') {
315 $outputfile .=
'.zst';
317 $outputerror = $outputfile.
'.err';
322 $command = preg_replace(
'/(\$|%)/',
'', $command);
323 if (preg_match(
"/\s/", $command)) {
324 $command = escapeshellarg($command);
328 $param = $dolibarr_main_db_name.
" -h ".$dolibarr_main_db_host;
329 $param .=
" -u ".$dolibarr_main_db_user;
330 if (!empty($dolibarr_main_db_port)) {
331 $param .=
" -P ".$dolibarr_main_db_port.
" --protocol=tcp";
333 if (
GETPOST(
"use_transaction",
"alpha")) {
334 $param .=
" --single-transaction";
336 if (
GETPOST(
"disable_fk",
"alpha") || $usedefault) {
339 if (
GETPOST(
"sql_compat",
"alpha") &&
GETPOST(
"sql_compat",
"alpha") !=
'NONE') {
340 $param .=
" --compatible=".escapeshellarg(
GETPOST(
"sql_compat",
"alpha"));
342 if (
GETPOST(
"drop_database",
"alpha")) {
343 $param .=
" --add-drop-database";
345 if (
GETPOST(
"use_mysql_quick_param",
"alpha")) {
346 $param .=
" --quick";
348 if (
GETPOST(
"use_force",
"alpha")) {
351 if (
GETPOST(
"sql_structure",
"alpha") || $usedefault) {
352 if (
GETPOST(
"drop",
"alpha") || $usedefault) {
353 $param .=
" --add-drop-table=TRUE";
355 $param .=
" --add-drop-table=FALSE";
360 if (
GETPOST(
"disable-add-locks",
"alpha")) {
361 $param .=
" --add-locks=FALSE";
363 if (
GETPOST(
"sql_data",
"alpha") || $usedefault) {
364 $param .=
" --tables";
365 if (
GETPOST(
"showcolumns",
"alpha") || $usedefault) {
368 if (
GETPOST(
"extended_ins",
"alpha") || $usedefault) {
371 $param .=
" --skip-extended-insert";
373 if (
GETPOST(
"delayed",
"alpha")) {
374 $param .=
" --delayed-insert";
376 if (
GETPOST(
"sql_ignore",
"alpha")) {
377 $param .=
" --insert-ignore";
379 if (
GETPOST(
"hexforbinary",
"alpha") || $usedefault) {
380 $param .=
" --hex-blob";
385 if ($dolibarr_main_db_character_set ==
'utf8mb4') {
387 $param .=
" --default-character-set=utf8mb4 --no-tablespaces";
389 $param .=
" --default-character-set=utf8 --no-tablespaces";
391 $paramcrypted = $param;
392 $paramclear = $param;
393 if (!empty($dolibarr_main_db_pass)) {
394 $paramcrypted .=
' -p"'.preg_replace(
'/./i',
'*', $dolibarr_main_db_pass).
'"';
395 $paramclear .=
' -p"'.str_replace(array(
'"',
'`',
'$'), array(
'\"',
'\`',
'\$'), $dolibarr_main_db_pass).
'"';
401 $fullcommandcrypted = $command.
" ".$paramcrypted.
" 2>&1";
402 $fullcommandclear = $command.
" ".$paramclear.
" 2>&1";
403 if (!$lowmemorydump) {
404 if ($compression ==
'none') {
405 $handle = fopen($outputfile,
'w');
406 } elseif ($compression ==
'gz') {
407 $handle = gzopen($outputfile,
'w');
408 } elseif ($compression ==
'bz') {
409 $handle = bzopen($outputfile,
'w');
410 } elseif ($compression ==
'zstd') {
411 $handle = fopen($outputfile,
'w');
414 if ($compression ==
'none') {
415 $fullcommandclear .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." > "'.dol_sanitizePathName($outputfile).
'"';
416 $fullcommandcrypted .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." > "'.dol_sanitizePathName($outputfile).
'"';
418 } elseif ($compression ==
'gz') {
419 $fullcommandclear .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | gzip > "'.dol_sanitizePathName($outputfile).
'"';
420 $fullcommandcrypted .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | gzip > "'.dol_sanitizePathName($outputfile).
'"';
421 $paramcrypted .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | gzip';
423 } elseif ($compression ==
'bz') {
424 $fullcommandclear .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | bzip2 > "'.dol_sanitizePathName($outputfile).
'"';
425 $fullcommandcrypted .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | bzip2 > "'.dol_sanitizePathName($outputfile).
'"';
426 $paramcrypted .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | bzip2';
428 } elseif ($compression ==
'zstd') {
429 $fullcommandclear .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | zstd > "'.dol_sanitizePathName($outputfile).
'"';
430 $fullcommandcrypted .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | zstd > "'.dol_sanitizePathName($outputfile).
'"';
431 $paramcrypted .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | zstd';
441 if (empty($execmethod)) {
445 dol_syslog(
"Utils::dumpDatabase execmethod=".$execmethod.
" command:".$fullcommandcrypted, LOG_INFO);
450 if (!empty($MemoryLimit)) {
451 @ini_set(
'memory_limit', $MemoryLimit);
455 if ($execmethod == 1) {
456 $output_arr = array();
459 exec($fullcommandclear, $output_arr, $retval);
467 $langs->load(
"errors");
468 dol_syslog(
"Datadump retval after exec=".$retval, LOG_ERR);
469 $errormsg =
'Error '.$retval;
473 if (!empty($output_arr)) {
474 foreach ($output_arr as $key => $read) {
476 if ($i == 1 && preg_match(
'/Warning.*Using a password/i', $read)) {
481 if (!$lowmemorydump) {
482 fwrite($handle, $read.($execmethod == 2 ?
'' :
"\n"));
483 if (preg_match(
'/'.preg_quote(
'-- Dump completed',
'/').
'/i', $read)) {
485 } elseif (preg_match(
'/'.preg_quote(
'SET SQL_NOTES=@OLD_SQL_NOTES',
'/').
'/i', $read)) {
492 } elseif ($lowmemorydump) {
498 if ($execmethod == 2) {
499 $handlein = popen($fullcommandclear,
'r');
502 while (!feof($handlein)) {
504 $read = fgets($handlein);
506 if ($i == 1 && preg_match(
'/Warning.*Using a password/i', $read)) {
509 fwrite($handle, $read);
510 if (preg_match(
'/'.preg_quote(
'-- Dump completed').
'/i', $read)) {
512 } elseif (preg_match(
'/'.preg_quote(
'SET SQL_NOTES=@OLD_SQL_NOTES').
'/i', $read)) {
520 if (!$lowmemorydump) {
521 if ($compression ==
'none') {
523 } elseif ($compression ==
'gz') {
525 } elseif ($compression ==
'bz') {
527 } elseif ($compression ==
'zstd') {
534 $langs->load(
"errors");
535 dol_syslog(
"Failed to open file ".$outputfile, LOG_ERR);
536 $errormsg = $langs->trans(
"ErrorFailedToWriteInDir");
540 if ($compression ==
'none') {
541 $handle = fopen($outputfile,
'r');
542 } elseif ($compression ==
'gz') {
543 $handle = gzopen($outputfile,
'r');
544 } elseif ($compression ==
'bz') {
545 $handle = bzopen($outputfile,
'r');
546 } elseif ($compression ==
'zstd') {
547 $handle = fopen($outputfile,
'r');
551 $errormsg = fgets($handle, 2048);
555 if ($compression ==
'none') {
557 } elseif ($compression ==
'gz') {
559 } elseif ($compression ==
'bz') {
561 } elseif ($compression ==
'zstd') {
564 if ($ok && preg_match(
'/^-- (MySql|MariaDB)/i', $errormsg) || preg_match(
'/^\/\*M?!999999/', $errormsg)) {
570 @
dol_move($outputfile, $outputerror,
'0', 1, 0, 0);
573 $langs->load(
"errors");
574 $errormsg = $langs->trans(
"ErrorFailedToRunExternalCommand");
580 $this->output = $errormsg;
581 $this->error = $errormsg;
582 $this->result = array(
"commandbackuplastdone" => $command.
" ".$paramcrypted,
"commandbackuptorun" =>
"");
587 if ($type ==
'mysqlnobin') {
588 $outputfile = $outputdir.
'/'.$file;
589 $outputfiletemp = $outputfile.
'-TMP.sql';
591 $compression = $compression ? $compression :
'none';
592 if ($compression ==
'gz') {
593 $outputfile .=
'.gz';
595 if ($compression ==
'bz') {
596 $outputfile .=
'.bz2';
598 $outputerror = $outputfile.
'.err';
601 if ($compression ==
'gz' or $compression ==
'bz') {
602 $this->backupTables($outputfiletemp);
603 dol_compress_file($outputfiletemp, $outputfile, $compression);
604 unlink($outputfiletemp);
606 $this->backupTables($outputfile);
610 $this->result = array(
"commandbackuplastdone" =>
"",
"commandbackuptorun" =>
"");
614 if ($type ==
'postgresql' || $type ==
'pgsql') {
617 $outputfile = $outputdir.
'/'.$file;
619 $compression = $compression ? $compression :
'none';
620 if ($compression ==
'gz') {
621 $outputfile .=
'.gz';
623 if ($compression ==
'bz') {
624 $outputfile .=
'.bz2';
626 $outputerror = $outputfile.
'.err';
631 $command = preg_replace(
'/(\$|%)/',
'', $command);
632 if (preg_match(
"/\s/", $command)) {
633 $command = escapeshellarg($command);
639 $param .=
" --no-tablespaces --inserts -h ".$dolibarr_main_db_host;
640 $param .=
" -U ".$dolibarr_main_db_user;
641 if (!empty($dolibarr_main_db_port)) {
642 $param .=
" -p ".$dolibarr_main_db_port;
645 $param .=
" --disable-dollar-quoting";
647 if (
GETPOST(
"drop_database")) {
650 if (
GETPOST(
"sql_structure")) {
652 $param .=
" --add-drop-table";
659 if (!
GETPOST(
"sql_structure")) {
666 $param .=
' -f "'.$outputfile.
'"';
668 if ($compression ==
'gz') {
672 $paramcrypted = $param;
673 $paramclear = $param;
679 $paramcrypted .=
" -w ".$dolibarr_main_db_name;
680 $paramclear .=
" -w ".$dolibarr_main_db_name;
683 $this->result = array(
"commandbackuplastdone" =>
"",
"commandbackuptorun" => $command.
" ".$paramcrypted);
687 if (!$errormsg && $keeplastnfiles > 0) {
688 $tmpfiles =
dol_dir_list(
$conf->admin->dir_output.
'/backup',
'files', 0,
'',
'(\.err|\.old|\.sav)$',
'date', SORT_DESC);
690 if (is_array($tmpfiles)) {
691 foreach ($tmpfiles as $key => $val) {
693 if ($i <= $keeplastnfiles) {
701 return ($errormsg ? -1 : 0);
719 public function executeCLI($command, $outputfile, $execmethod = 0, $redirectionfile =
null, $noescapecommand = 0, $redirectionfileerr =
null)
721 global
$conf, $langs;
727 if (empty($noescapecommand)) {
728 $command = escapeshellcmd($command);
731 if ($redirectionfile) {
732 $command .=
" > ".dol_sanitizePathName($redirectionfile);
735 if ($redirectionfileerr && ($redirectionfileerr != $redirectionfile)) {
737 $command .=
" 2> ".dol_sanitizePathName($redirectionfileerr);
745 if (empty($execmethod)) {
749 dol_syslog(
"Utils::executeCLI execmethod=".$execmethod.
" command=".$command, LOG_DEBUG);
750 $output_arr = array();
752 if ($execmethod == 1) {
754 exec($command, $output_arr, $retval);
757 $langs->load(
"errors");
758 dol_syslog(
"Utils::executeCLI retval after exec=".$retval, LOG_ERR);
759 $error =
'Error '.$retval;
762 if ($execmethod == 2) {
763 $handle = fopen($outputfile,
'w+b');
765 dol_syslog(
"Utils::executeCLI run command ".$command);
766 $handlein = popen($command,
'r');
767 while (!feof($handlein)) {
768 $read = fgets($handlein);
769 fwrite($handle, $read);
770 $output_arr[] = $read;
779 if (is_array($output_arr) && count($output_arr) > 0) {
780 foreach ($output_arr as $val) {
781 $output .= $val.($execmethod == 2 ?
'' :
"\n");
785 dol_syslog(
"Utils::executeCLI result=".$result.
" output=".$output.
" error=".$error, LOG_DEBUG);
787 return array(
'result' => $result,
'output' => $output,
'error' => $error);
798 global
$conf, $langs, $user, $mysoc;
803 $modulelowercase = strtolower($module);
807 $dir = $dirins.
'/'.$modulelowercase;
812 dol_include_once($modulelowercase.
'/core/modules/mod'.$module.
'.class.php');
813 $class =
'mod'.$module;
815 if (class_exists($class)) {
824 $langs->load(
"errors");
825 dol_print_error(
null, $langs->trans(
"ErrorFailedToLoadModuleDescriptorForXXX", $module));
829 $arrayversion = explode(
'.',
$moduleobj->version, 3);
830 if (count($arrayversion)) {
831 $FILENAMEASCII = strtolower($module).
'.asciidoc';
832 $FILENAMEDOC = strtolower($module).
'.html';
833 $FILENAMEDOCPDF = strtolower($module).
'.pdf';
836 $dirofmoduledoc =
dol_buildpath(strtolower($module), 0).
'/doc';
837 $dirofmoduletmp =
dol_buildpath(strtolower($module), 0).
'/doc/temp';
838 $outputfiledoc = $dirofmoduledoc.
'/'.$FILENAMEDOC;
839 if ($dirofmoduledoc) {
846 if (!is_writable($dirofmoduletmp)) {
847 $this->error =
'Dir '.$dirofmoduletmp.
' does not exists or is not writable';
852 $this->error =
'Setup of module ModuleBuilder not complete';
857 dol_copy($dirofmodule.
'/README.md', $dirofmoduletmp.
'/README.md',
'0', 1);
858 dol_copy($dirofmodule.
'/ChangeLog.md', $dirofmoduletmp.
'/ChangeLog.md',
'0', 1);
861 $arrayreplacement = array();
862 $arrayreplacement[
'/^#\s.*/m'] =
'';
863 $arrayreplacement[
'/^#/m'] =
'##';
865 dolReplaceInFile($dirofmoduletmp.
'/README.md', $arrayreplacement,
'',
'0', 0, 1);
866 dolReplaceInFile($dirofmoduletmp.
'/ChangeLog.md', $arrayreplacement,
'',
'0', 0, 1);
869 $destfile = $dirofmoduletmp.
'/'.$FILENAMEASCII;
871 $fhandle = fopen($destfile,
'w+');
873 $specs =
dol_dir_list(
dol_buildpath(strtolower($module).
'/doc', 0),
'files', 1,
'(\.md|\.asciidoc)$', array(
'\/temp\/'));
876 foreach ($specs as $spec) {
877 if (preg_match(
'/notindoc/', $spec[
'relativename'])) {
880 if (preg_match(
'/example/', $spec[
'relativename'])) {
883 if (preg_match(
'/disabled/', $spec[
'relativename'])) {
887 $pathtofile = strtolower($module).
'/doc/'.$spec[
'relativename'];
888 $format =
'asciidoc';
889 if (preg_match(
'/\.md$/i', $spec[
'name'])) {
890 $format =
'markdown';
893 $filecursor = @file_get_contents($spec[
'fullname']);
895 fwrite($fhandle, ($i ?
"\n<<<\n\n" :
"").$filecursor.
"\n");
897 $this->error =
'Failed to concat content of file '.$spec[
'fullname'];
906 $contentreadme = file_get_contents($dirofmoduletmp.
'/README.md');
907 $contentchangelog = file_get_contents($dirofmoduletmp.
'/ChangeLog.md');
909 include DOL_DOCUMENT_ROOT.
'/core/lib/parsemd.lib.php';
912 $arrayreplacement = array(
913 'mymodule' => strtolower($module),
914 'MyModule' => $module,
915 'MYMODULE' => strtoupper($module),
916 'My module' => $module,
917 'my module' => $module,
918 'Mon module' => $module,
919 'mon module' => $module,
920 'htdocs/modulebuilder/template' => strtolower($module),
921 '__MYCOMPANY_NAME__' => $mysoc->name,
922 '__KEYWORDS__' => $module,
923 '__USER_FULLNAME__' => $user->getFullName($langs),
924 '__USER_EMAIL__' => $user->email,
926 '---Put here your own copyright and developer email---' =>
dol_print_date($now,
'dayrfc').
' '.$user->getFullName($langs).($user->email ?
' <'.$user->email.
'>' :
''),
927 '__DATA_SPECIFICATION__' =>
'Not yet available',
937 $currentdir = getcwd();
940 require_once DOL_DOCUMENT_ROOT.
'/core/class/utils.class.php';
941 $utils =
new Utils($this->db);
944 $command =
getDolGlobalString(
'MODULEBUILDER_ASCIIDOCTOR') .
' '.$destfile.
' -n -o '.$dirofmoduledoc.
'/'.$FILENAMEDOC;
945 $outfile = $dirofmoduletmp.
'/out.tmp';
947 $resarray = $utils->executeCLI($command, $outfile);
948 if ($resarray[
'result'] !=
'0') {
949 $this->error = $resarray[
'error'].
' '.$resarray[
'output'];
950 $this->errors[] = $this->error;
952 $result = ($resarray[
'result'] == 0) ? 1 : 0;
953 if ($result < 0 && empty($this->errors)) {
954 $this->error = $langs->trans(
"ErrorFailToGenerateFile", $FILENAMEDOC);
955 $this->errors[] = $this->error;
959 $command =
getDolGlobalString(
'MODULEBUILDER_ASCIIDOCTORPDF') .
' '.$destfile.
' -n -o '.$dirofmoduledoc.
'/'.$FILENAMEDOCPDF;
960 $outfile = $dirofmoduletmp.
'/outpdf.tmp';
961 $resarray = $utils->executeCLI($command, $outfile);
962 if ($resarray[
'result'] !=
'0') {
963 $this->error = $resarray[
'error'].
' '.$resarray[
'output'];
964 $this->errors[] = $this->error;
966 $result = ($resarray[
'result'] == 0) ? 1 : 0;
967 if ($result < 0 && empty($this->errors)) {
968 $this->error = $langs->trans(
"ErrorFailToGenerateFile", $FILENAMEDOCPDF);
969 $this->errors[] = $this->error;
984 $langs->load(
"errors");
985 $this->error = $langs->trans(
"ErrorCheckVersionIsDefined");
1002 if (empty(
$conf->loghandlers[
'mod_syslog_file'])) {
1006 if (!function_exists(
'gzopen')) {
1007 $this->error =
'Support for gzopen not available in this PHP';
1011 require_once DOL_DOCUMENT_ROOT .
'/core/lib/files.lib.php';
1016 $mainlogdir = DOL_DATA_ROOT;
1017 $mainlog =
'dolibarr.log';
1019 $mainlogfull = str_replace(
'DOL_DATA_ROOT', DOL_DATA_ROOT,
$conf->global->SYSLOG_FILE);
1020 $mainlogdir = dirname($mainlogfull);
1021 $mainlog = basename($mainlogfull);
1024 $tabfiles =
dol_dir_list(DOL_DATA_ROOT,
'files', 0,
'^(dolibarr_.+|odt2pdf)\.log$');
1025 $tabfiles[] = array(
'name' => $mainlog,
'path' => $mainlogdir);
1027 foreach ($tabfiles as $file) {
1028 $logname = $file[
'name'];
1029 $logpath = $file[
'path'];
1034 $filter =
'^'.preg_quote($logname,
'/').
'\.([0-9]+)\.gz$';
1036 $gzfilestmp =
dol_dir_list($logpath,
'files', 0, $filter);
1039 foreach ($gzfilestmp as $gzfile) {
1040 $tabmatches = array();
1041 preg_match(
'/'.$filter.
'/i', $gzfile[
'name'], $tabmatches);
1043 $numsave = intval($tabmatches[1]);
1045 $gzfiles[$numsave] = $gzfile;
1048 krsort($gzfiles, SORT_NUMERIC);
1050 foreach ($gzfiles as $numsave => $dummy) {
1051 if (
dol_is_file($logpath.
'/'.$logname.
'.'.($numsave + 1).
'.gz')) {
1055 if ($numsave >= $nbSaves) {
1056 dol_delete_file($logpath.
'/'.$logname.
'.'.$numsave.
'.gz', 0, 0, 0,
null,
false, 0);
1058 dol_move($logpath.
'/'.$logname.
'.'.$numsave.
'.gz', $logpath.
'/'.$logname.
'.'.($numsave + 1).
'.gz',
'0', 1, 0, 0);
1065 $gzfilehandle = gzopen($logpath.
'/'.$logname.
'.1.gz',
'wb9');
1067 if (empty($gzfilehandle)) {
1068 $this->error =
'Failted to open file '.$logpath.
'/'.$logname.
'.1.gz';
1072 $sourcehandle = fopen($logpath.
'/'.$logname,
'r');
1074 if (empty($sourcehandle)) {
1075 $this->error =
'Failed to open file '.$logpath.
'/'.$logname;
1079 while (!feof($sourcehandle)) {
1080 gzwrite($gzfilehandle, fread($sourcehandle, 512 * 1024));
1083 fclose($sourcehandle);
1084 gzclose($gzfilehandle);
1086 dolChmod($logpath.
'/'.$logname.
'.1.gz');
1092 $newlog = fopen($logpath.
'/'.$logname,
'a+');
1100 $this->output =
'Archive log files (keeping last SYSLOG_FILE_SAVES='.$nbSaves.
' files) done.';
1114 public function backupTables($outputfile, $tables =
'*')
1120 if (is_a(
$db,
'DoliDBMysqli')) {
1122 $db->db->set_charset(
'utf8');
1125 $db->query(
'SET NAMES utf8');
1126 $db->query(
'SET CHARACTER SET utf8');
1130 if ($tables ==
'*') {
1132 $result =
$db->query(
'SHOW FULL TABLES WHERE Table_type = \'BASE TABLE\'');
1133 while ($row =
$db->fetch_row($result)) {
1134 $tables[] = $row[0];
1137 $tables = is_array($tables) ? $tables : explode(
',', $tables);
1141 $handle = fopen($outputfile,
'w+');
1142 if (fwrite($handle,
'') ===
false) {
1143 $langs->load(
"errors");
1144 dol_syslog(
"Failed to open file ".$outputfile, LOG_ERR);
1145 $errormsg = $langs->trans(
"ErrorFailedToWriteInDir");
1151 $sqlhead .=
"-- ".$db::LABEL.
" dump via php with Dolibarr ".DOL_VERSION.
"
1153-- Host: ".
$db->db->host_info.
" Database: ".
$db->database_name.
"
1154-- ------------------------------------------------------
1155-- Server version ".
$db->db->server_info.
"
1170 if (
GETPOST(
"nobin_disable_fk")) {
1171 $sqlhead .=
"SET FOREIGN_KEY_CHECKS=0;\n";
1174 if (
GETPOST(
"nobin_use_transaction")) {
1175 $sqlhead .=
"SET AUTOCOMMIT=0;\nSTART TRANSACTION;\n";
1178 fwrite($handle, $sqlhead);
1181 if (
GETPOST(
"nobin_sql_ignore")) {
1182 $ignore =
'IGNORE ';
1185 if (
GETPOST(
"nobin_delayed")) {
1186 $delayed =
'DELAYED ';
1190 foreach ($tables as $table) {
1192 fwrite($handle,
"\n--\n-- Table structure for table `".$table.
"`\n--\n");
1195 fwrite($handle,
"DROP TABLE IF EXISTS `".$table.
"`;\n");
1197 fwrite($handle,
"/*!40101 SET @saved_cs_client = @@character_set_client */;\n");
1198 fwrite($handle,
"/*!40101 SET character_set_client = utf8 */;\n");
1199 $resqldrop =
$db->query(
'SHOW CREATE TABLE '.$table);
1200 $row2 =
$db->fetch_row($resqldrop);
1201 if (empty($row2[1])) {
1202 fwrite($handle,
"\n-- WARNING: Show create table ".$table.
" return empty string when it should not.\n");
1204 fwrite($handle, $row2[1].
";\n");
1208 fwrite($handle,
"\n--\n-- Dumping data for table `".$table.
"`\n--\n");
1209 if (!
GETPOST(
"nobin_nolocks")) {
1210 fwrite($handle,
"LOCK TABLES `".$table.
"` WRITE;\n");
1212 if (
GETPOST(
"nobin_disable_fk")) {
1213 fwrite($handle,
"ALTER TABLE `".$table.
"` DISABLE KEYS;\n");
1215 fwrite($handle,
"/*!40000 ALTER TABLE `".$table.
"` DISABLE KEYS */;\n");
1218 $sql =
"SELECT * FROM ".$table;
1219 $result =
$db->query($sql);
1220 while ($row =
$db->fetch_row($result)) {
1222 fwrite($handle,
"INSERT ".$delayed.$ignore.
"INTO ".$table.
" VALUES (");
1223 $columns = count($row);
1224 for ($j = 0; $j < $columns; $j++) {
1226 if ($row[$j] ==
null && !is_string($row[$j])) {
1229 } elseif (is_string($row[$j]) && $row[$j] ==
'') {
1232 } elseif (is_numeric($row[$j]) && !strcmp((
string) $row[$j], (
string) ((
float) $row[$j] + 0))) {
1236 $row[$j] = addslashes($row[$j]);
1237 $row[$j] = preg_replace(
"#\n#",
"\\n", $row[$j]);
1238 $row[$j] =
"'".$row[$j].
"'";
1241 fwrite($handle, implode(
',', $row).
");\n");
1243 if (
GETPOST(
"nobin_disable_fk")) {
1244 fwrite($handle,
"ALTER TABLE `".$table.
"` ENABLE KEYS;\n");
1246 if (!
GETPOST(
"nobin_nolocks")) {
1247 fwrite($handle,
"UNLOCK TABLES;\n");
1249 fwrite($handle,
"\n\n\n");
1273 $sqlfooter =
"\n\n";
1274 if (
GETPOST(
"nobin_use_transaction")) {
1275 $sqlfooter .=
"COMMIT;\n";
1277 if (
GETPOST(
"nobin_disable_fk")) {
1278 $sqlfooter .=
"SET FOREIGN_KEY_CHECKS=1;\n";
1280 $sqlfooter .=
"\n\n-- Dump completed on ".date(
'Y-m-d G-i-s');
1281 fwrite($handle, $sqlfooter);
1301 public function sendBackup($sendto =
'', $from =
'', $subject =
'', $message =
'', $filename =
'', $filter =
'', $sizelimit = 100000000)
1303 global
$conf, $langs;
1304 global $dolibarr_main_url_root;
1312 if (!empty($from)) {
1320 if (!empty($sendto)) {
1328 if (!empty($subject)) {
1334 if (empty($message)) {
1338 $tmpfiles = array();
1339 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
1347 if ($tmpfiles && is_array($tmpfiles)) {
1348 foreach ($tmpfiles as $key => $val) {
1349 if ($key ==
'fullname') {
1350 $filepath = array($val);
1353 if ($key ==
'type') {
1354 $mimetype = array($val);
1356 if ($key ==
'relativename') {
1357 $filename = array($val);
1363 if ($filesize > $sizelimit) {
1364 $message .=
'<br>'.$langs->trans(
"BackupIsTooLargeSend");
1365 $documenturl = $dolibarr_main_url_root.
'/document.php?modulepart=systemtools&atachement=1&file=backup/'.urlencode($filename[0]);
1366 $message .=
'<br><a href='.$documenturl.
'>Download link</a>';
1372 $output =
'No backup file found';
1378 include_once DOL_DOCUMENT_ROOT .
'/core/class/CMailFile.class.php';
1379 $mailfile =
new CMailFile($subject, $sendto, $from, $message, $filepath, $mimetype, $filename,
'',
'', 0, -1);
1380 if ($mailfile->error) {
1382 $output = $mailfile->error;
1388 if (!$error && $mailfile !==
null) {
1389 $result = $mailfile->sendfile();
1392 $output = $mailfile->error;
1398 $this->error =
"Error sending backup file ".((string) $error);
1399 $this->output = $output;
1418 dol_syslog(
"Utils::cleanUnfinishedCronjob Starting cleaning");
1421 require_once DOL_DOCUMENT_ROOT .
'/cron/class/cronjob.class.php';
1425 $this_job->fetch(-1,
'Utils',
'cleanUnfinishedCronjob');
1426 if (empty($this_job->id) || !empty($this_job->error)) {
1427 dol_syslog(
"Utils::cleanUnfinishedCronjob Unable to fetch himself: ".$this_job->error, LOG_ERR);
1432 $this_job->processing = 0;
1433 if ($this_job->update($user) < 0) {
1434 dol_syslog(
"Utils::cleanUnfinishedCronjob Unable to update himself: ".implode(
', ', $this_job->errors), LOG_ERR);
1439 $cron_job->fetchAll(
'DESC',
't.rowid', 100, 0, 1, [], 1);
1442 foreach ($cron_job->lines as $job_line) {
1444 if (empty($job_line->pid)) {
1445 dol_syslog(
"Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id.
" don't have a PID", LOG_DEBUG);
1450 $job->fetch($job_line->id);
1451 if (empty($job->id) || !empty($job->error)) {
1452 dol_syslog(
"Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id.
" can't be fetch: ".$job->error, LOG_ERR);
1457 if (! posix_kill($job->pid, 0)) {
1459 $job->processing = 0;
1463 $job->lastresult = strval(-1);
1464 $job->lastoutput =
'Job killed by job cleanUnfinishedCronjob';
1466 if ($job->update($user) < 0) {
1467 dol_syslog(
"Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id.
" can't be updated: ".implode(
', ', $job->errors), LOG_ERR);
1470 dol_syslog(
"Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id.
" cleaned");
1474 dol_syslog(
"Utils::cleanUnfinishedCronjob Cleaning completed");
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_filesize($pathoffile)
Return size of a file.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
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_move($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array())
Move a file into another name.
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_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
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.
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.