80 public function purgeFiles($choices =
'tempfilesold+logfiles', $nbsecondsold = 86400)
82 global $conf, $langs, $user;
83 global $dolibarr_main_data_root;
85 $langs->load(
"admin");
87 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
89 if (empty($choices)) {
90 $choices =
'tempfilesold+logfiles';
92 if ($choices ==
'allfiles' && $nbsecondsold > 0) {
93 $choices =
'allfilesold';
96 dol_syslog(
"Utils::purgeFiles choice=".$choices, LOG_DEBUG);
99 if (in_array($choices, array(
'allfiles',
'allfilesold'))) {
100 if (empty($user->admin)) {
101 $this->output =
'Error: to erase data files, user running the batch (currently '.$user->login.
') must be an admin user';
111 $choicesarray = preg_split(
'/[\+,]/', $choices);
112 foreach ($choicesarray as $choice) {
114 $filesarray = array();
116 if ($choice ==
'tempfiles' || $choice ==
'tempfilesold') {
118 if ($dolibarr_main_data_root) {
119 $filesarray =
dol_dir_list($dolibarr_main_data_root,
"directories", 1,
'^temp$',
'',
'name', SORT_ASC, 2, 0,
'', 1);
121 if ($choice ==
'tempfilesold') {
122 foreach ($filesarray as $key => $val) {
123 if ($val[
'date'] > ($now - ($nbsecondsold))) {
124 unset($filesarray[$key]);
131 if ($choice ==
'allfiles') {
133 if ($dolibarr_main_data_root) {
134 $filesarray =
dol_dir_list($dolibarr_main_data_root,
"all", 0,
'',
'(\.lock|\.unlock)$',
'name', SORT_ASC, 0, 0,
'', 1);
138 if ($choice ==
'allfilesold') {
140 if ($dolibarr_main_data_root) {
141 $filesarray =
dol_dir_list($dolibarr_main_data_root,
"files", 1,
'',
'(\.lock|\.unlock)$',
'name', SORT_ASC, 0, 0,
'', 1, $nbsecondsold);
145 if ($choice ==
'logfile' || $choice ==
'logfiles') {
147 if ($dolibarr_main_data_root) {
148 $filesarray =
dol_dir_list($dolibarr_main_data_root,
"files", 0,
'.*\.log[\.0-9]*(\.gz)?$',
'(\.lock|\.unlock)$',
'name', SORT_ASC, 0, 0,
'', 1);
153 $filelog = preg_replace(
'/DOL_DATA_ROOT/i', DOL_DATA_ROOT, $filelog);
155 $alreadyincluded =
false;
156 foreach ($filesarray as $tmpcursor) {
157 if ($tmpcursor[
'fullname'] == $filelog) {
158 $alreadyincluded =
true;
161 if (!$alreadyincluded) {
162 $filesarray[] = array(
'fullname' => $filelog,
'type' =>
'file');
167 if (is_array($filesarray) && count($filesarray)) {
168 foreach ($filesarray as $key => $value) {
170 if ($filesarray[$key][
'type'] ==
'dir') {
172 $tmpcountdeleted = 0;
177 $conf->user->dir_temp,
180 $excluded[] = $conf->api->dir_temp;
183 if (!in_array($filesarray[$key][
'fullname'], $excluded)) {
185 $countdeleted += $tmpcountdeleted;
187 } elseif ($filesarray[$key][
'type'] ==
'file') {
188 if ($choice !=
'allfilesold' || $filesarray[$key][
'date'] < ($now - $nbsecondsold)) {
190 if ($filesarray[$key][
'fullname'] != $filelog || $choice ==
'logfile' || $choice ==
'logfiles') {
205 require_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmdirectory.class.php';
207 $result = $ecmdirstatic->refreshcachenboffile(1);
213 $langs->load(
"admin");
214 $this->output = $langs->trans(
"PurgeNDirectoriesDeleted", $countdeleted);
215 if ($count > $countdeleted) {
216 $this->output .=
'<br>'.$langs->trans(
"PurgeNDirectoriesFailed", ($count - $countdeleted));
219 $this->output = $langs->trans(
"PurgeNothingToDelete").(in_array(
'tempfilesold', $choicesarray) ?
' (older than 24h for temp files)' :
'');
242 if (preg_match(
'/^win/i', PHP_OS)) {
244 return '-p"'.str_replace(array(
'"',
'`',
'$'), array(
'\\"',
'\\`',
'\\$'), $password).
'"';
248 return '-p'.escapeshellarg($password);
265 public function dumpDatabase($compression =
'none', $type =
'auto', $usedefault = 1, $file =
'auto', $keeplastnfiles = 0, $execmethod = 0, $lowmemorydump = 0)
267 global
$db, $conf, $langs, $dolibarr_main_data_root;
268 global $dolibarr_main_db_name, $dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_port, $dolibarr_main_db_pass;
269 global $dolibarr_main_db_character_set;
271 $langs->load(
"admin");
273 dol_syslog(
"Utils::dumpDatabase type=".$type.
" compression=".$compression.
" file=".$file, LOG_DEBUG);
274 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
280 if (!in_array($compression, array(
'none',
'gz',
'bz',
'zip',
'zstd'))) {
281 $langs->load(
"errors");
282 $this->error = $langs->transnoentitiesnoconv(
"ErrorBadValueForParameter", $compression,
"Compression");
287 if ($type ==
'auto') {
288 $type = $this->db->type;
290 if (!in_array($type, array(
'postgresql',
'pgsql',
'mysql',
'mysqli',
'mysqlnobin'))) {
291 $langs->load(
"errors");
292 $this->error = $langs->transnoentitiesnoconv(
"ErrorBadValueForParameter", $type,
"Basetype");
297 if ($file ==
'auto') {
300 if (in_array($type, array(
'mysql',
'mysqli'))) {
301 $prefix =
'mysqldump';
304 if (in_array($type, array(
'pgsql'))) {
310 $outputdir = $conf->admin->dir_output.
'/backup';
315 if ($type ==
'mysql' || $type ==
'mysqli') {
317 $cmddump =
$db->getPathOfDump();
321 if (empty($cmddump)) {
322 $this->error =
"Failed to detect command to use for mysqldump. Try a manual backup before to set path of command.";
326 $outputfile = $outputdir.
'/'.$file;
328 $compression = $compression ? $compression :
'none';
329 if ($compression ==
'gz') {
330 $outputfile .=
'.gz';
331 } elseif ($compression ==
'bz') {
332 $outputfile .=
'.bz2';
333 } elseif ($compression ==
'zstd') {
334 $outputfile .=
'.zst';
336 $outputerror = $outputfile.
'.err';
337 dol_mkdir($conf->admin->dir_output.
'/backup');
341 $command = preg_replace(
'/(\$|%)/',
'', $command);
342 if (preg_match(
"/\s/", $command)) {
343 $command = escapeshellarg($command);
347 $param = $dolibarr_main_db_name.
" -h ".$dolibarr_main_db_host;
348 $param .=
" -u ".$dolibarr_main_db_user;
349 if (!empty($dolibarr_main_db_port)) {
350 $param .=
" -P ".$dolibarr_main_db_port.
" --protocol=tcp";
352 if (
GETPOST(
"use_transaction",
"alpha")) {
353 $param .=
" --single-transaction";
355 if (
GETPOST(
"disable_fk",
"alpha") || $usedefault) {
358 if (
GETPOST(
"sql_compat",
"alpha") &&
GETPOST(
"sql_compat",
"alpha") !=
'NONE') {
359 $param .=
" --compatible=".escapeshellarg(
GETPOST(
"sql_compat",
"alpha"));
361 if (
GETPOST(
"drop_database",
"alpha")) {
362 $param .=
" --add-drop-database";
364 if (
GETPOST(
"use_mysql_quick_param",
"alpha")) {
365 $param .=
" --quick";
367 if (
GETPOST(
"use_force",
"alpha")) {
370 if (
GETPOST(
"sql_structure",
"alpha") || $usedefault) {
371 if (
GETPOST(
"drop",
"alpha") || $usedefault) {
372 $param .=
" --add-drop-table=TRUE";
374 $param .=
" --add-drop-table=FALSE";
379 if (
GETPOST(
"disable-add-locks",
"alpha")) {
380 $param .=
" --add-locks=FALSE";
382 if (
GETPOST(
"sql_data",
"alpha") || $usedefault) {
383 $param .=
" --tables";
384 if (
GETPOST(
"showcolumns",
"alpha") || $usedefault) {
387 if (
GETPOST(
"extended_ins",
"alpha") || $usedefault) {
390 $param .=
" --skip-extended-insert";
392 if (
GETPOST(
"delayed",
"alpha")) {
393 $param .=
" --delayed-insert";
395 if (
GETPOST(
"sql_ignore",
"alpha")) {
396 $param .=
" --insert-ignore";
398 if (
GETPOST(
"hexforbinary",
"alpha") || $usedefault) {
399 $param .=
" --hex-blob";
404 if ($dolibarr_main_db_character_set ==
'utf8mb4') {
406 $param .=
" --default-character-set=utf8mb4 --no-tablespaces";
408 $param .=
" --default-character-set=utf8 --no-tablespaces";
410 $paramcrypted = $param;
411 $paramclear = $param;
412 if (!empty($dolibarr_main_db_pass)) {
413 $paramcrypted .=
' -p"'.preg_replace(
'/./i',
'*', $dolibarr_main_db_pass).
'"';
414 $paramclear .=
' '.$this->getShellPasswordParam($dolibarr_main_db_pass);
420 $fullcommandcrypted = $command.
" ".$paramcrypted.
" 2>&1";
421 $fullcommandclear = $command.
" ".$paramclear.
" 2>&1";
422 if (!$lowmemorydump) {
423 if ($compression ==
'none') {
424 $handle = fopen($outputfile,
'w');
425 } elseif ($compression ==
'gz') {
426 $handle = gzopen($outputfile,
'w');
427 } elseif ($compression ==
'bz') {
428 $handle = bzopen($outputfile,
'w');
429 } elseif ($compression ==
'zstd') {
430 $handle = fopen(
"compress.zstd://" . $outputfile,
"wb");
435 if ($compression ==
'none') {
436 $fullcommandclear .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." > "'.dol_sanitizePathName($outputfile).
'"';
437 $fullcommandcrypted .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." > "'.dol_sanitizePathName($outputfile).
'"';
439 } elseif ($compression ==
'gz') {
440 $fullcommandclear .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | gzip > "'.dol_sanitizePathName($outputfile).
'"';
441 $fullcommandcrypted .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | gzip > "'.dol_sanitizePathName($outputfile).
'"';
442 $paramcrypted .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | gzip';
444 } elseif ($compression ==
'bz') {
445 $fullcommandclear .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | bzip2 > "'.dol_sanitizePathName($outputfile).
'"';
446 $fullcommandcrypted .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | bzip2 > "'.dol_sanitizePathName($outputfile).
'"';
447 $paramcrypted .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | bzip2';
449 } elseif ($compression ==
'zstd') {
450 $fullcommandclear .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | zstd > "'.dol_sanitizePathName($outputfile).
'"';
451 $fullcommandcrypted .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | zstd > "'.dol_sanitizePathName($outputfile).
'"';
452 $paramcrypted .=
' | grep -v "Warning: Using a password on the command line interface can be insecure." | zstd';
462 if (empty($execmethod)) {
466 dol_syslog(
"Utils::dumpDatabase execmethod=".$execmethod.
", lowmemorydump=".$lowmemorydump.
", command=".$fullcommandcrypted, LOG_INFO);
471 if (!empty($MemoryLimit)) {
472 @ini_set(
'memory_limit', $MemoryLimit);
476 if ($execmethod == 1) {
477 $output_arr = array();
480 exec($fullcommandclear, $output_arr, $retval);
488 $langs->load(
"errors");
489 dol_syslog(
"Datadump retval after exec=".$retval, LOG_ERR);
490 $errormsg =
'Error '.$retval;
494 if (!empty($output_arr)) {
495 foreach ($output_arr as $key => $read) {
497 if ($i == 1 && preg_match(
'/Warning.*Using a password/i', $read)) {
502 if (!$lowmemorydump) {
505 fwrite($handle, $read.($execmethod == 2 ?
'' :
"\n"));
506 if (preg_match(
'/'.preg_quote(
'-- Dump completed',
'/').
'/i', $read)) {
508 } elseif (preg_match(
'/'.preg_quote(
'SET SQL_NOTES=@OLD_SQL_NOTES',
'/').
'/i', $read)) {
515 } elseif ($lowmemorydump) {
521 if ($execmethod == 2) {
522 $handlein = popen($fullcommandclear,
'r');
525 while (!feof($handlein)) {
527 $read = fgets($handlein);
529 if ($i == 1 && preg_match(
'/Warning.*Using a password/i', $read)) {
532 fwrite($handle, $read);
533 if (preg_match(
'/'.preg_quote(
'-- Dump completed',
'/').
'/i', $read)) {
535 } elseif (preg_match(
'/'.preg_quote(
'SET SQL_NOTES=@OLD_SQL_NOTES',
'/').
'/i', $read)) {
543 if (!$lowmemorydump) {
544 if ($compression ==
'none') {
546 } elseif ($compression ==
'gz') {
548 } elseif ($compression ==
'bz') {
550 } elseif ($compression ==
'zstd') {
557 $langs->load(
"errors");
558 dol_syslog(
"Failed to open file ".$outputfile, LOG_ERR);
559 $errormsg = $langs->trans(
"ErrorFailedToWriteInDir");
563 if ($compression ==
'none') {
564 $handle = fopen($outputfile,
'r');
565 } elseif ($compression ==
'gz') {
566 $handle = gzopen($outputfile,
'r');
567 } elseif ($compression ==
'bz') {
568 $handle = bzopen($outputfile,
'r');
569 } elseif ($compression ==
'zstd') {
570 $handle = fopen(
"compress.zstd://" . $outputfile,
"rb");
574 $errormsg = fgets($handle, 2048);
578 if ($compression ==
'none') {
580 } elseif ($compression ==
'gz') {
582 } elseif ($compression ==
'bz') {
584 } elseif ($compression ==
'zstd') {
587 if ($ok && preg_match(
'/^-- (MySql|MariaDB)/i', $errormsg) || preg_match(
'/^\/\*M?!999999/', $errormsg)) {
593 @
dol_move($outputfile, $outputerror,
'0', 1, 0, 0);
596 $langs->load(
"errors");
597 $errormsg = $langs->trans(
"ErrorFailedToRunExternalCommand");
603 $this->output = $errormsg;
604 $this->error = $errormsg;
605 $this->result = array(
"commandbackuplastdone" => $command.
" ".$paramcrypted,
"commandbackuptorun" =>
"");
610 if ($type ==
'mysqlnobin') {
611 $outputfile = $outputdir.
'/'.$file;
612 $outputfiletemp = $outputfile.
'-TMP.sql';
614 $compression = $compression ? $compression :
'none';
615 if ($compression ==
'gz') {
616 $outputfile .=
'.gz';
618 if ($compression ==
'bz') {
619 $outputfile .=
'.bz2';
621 $outputerror = $outputfile.
'.err';
622 dol_mkdir($conf->admin->dir_output.
'/backup');
624 if ($compression ==
'gz' or $compression ==
'bz') {
625 $this->backupTables($outputfiletemp);
626 dol_compress_file($outputfiletemp, $outputfile, $compression);
627 unlink($outputfiletemp);
629 $this->backupTables($outputfile);
633 $this->result = array(
"commandbackuplastdone" =>
"",
"commandbackuptorun" =>
"");
637 if ($type ==
'postgresql' || $type ==
'pgsql') {
640 $outputfile = $outputdir.
'/'.$file;
642 $compression = $compression ? $compression :
'none';
643 if ($compression ==
'gz') {
644 $outputfile .=
'.gz';
646 if ($compression ==
'bz') {
647 $outputfile .=
'.bz2';
649 $outputerror = $outputfile.
'.err';
650 dol_mkdir($conf->admin->dir_output.
'/backup');
654 $command = preg_replace(
'/(\$|%)/',
'', $command);
655 if (preg_match(
"/\s/", $command)) {
656 $command = escapeshellarg($command);
662 $param .=
" --no-tablespaces --inserts -h ".$dolibarr_main_db_host;
663 $param .=
" -U ".$dolibarr_main_db_user;
664 if (!empty($dolibarr_main_db_port)) {
665 $param .=
" -p ".$dolibarr_main_db_port;
668 $param .=
" --disable-dollar-quoting";
670 if (
GETPOST(
"drop_database")) {
673 if (
GETPOST(
"sql_structure")) {
675 $param .=
" --add-drop-table";
682 if (!
GETPOST(
"sql_structure")) {
689 $param .=
' -f "'.$outputfile.
'"';
691 if ($compression ==
'gz') {
695 $paramcrypted = $param;
696 $paramclear = $param;
702 $paramcrypted .=
" -w ".$dolibarr_main_db_name;
703 $paramclear .=
" -w ".$dolibarr_main_db_name;
706 $this->result = array(
"commandbackuplastdone" =>
"",
"commandbackuptorun" => $command.
" ".$paramcrypted);
710 if (!$errormsg && $keeplastnfiles > 0) {
711 $tmpfiles =
dol_dir_list($conf->admin->dir_output.
'/backup',
'files', 0,
'',
'(\.err|\.old|\.sav)$',
'date', SORT_DESC);
713 if (is_array($tmpfiles)) {
714 foreach ($tmpfiles as $key => $val) {
716 if ($i <= $keeplastnfiles) {
724 return ($errormsg ? -1 : 0);
742 public function executeCLI($command, $outputfile, $execmethod = 0, $redirectionfile =
null, $noescapecommand = 0, $redirectionfileerr =
null)
750 if (empty($noescapecommand)) {
751 $command = escapeshellcmd($command);
754 if ($redirectionfile) {
755 $command .=
" > ".dol_sanitizePathName($redirectionfile);
758 if ($redirectionfileerr && ($redirectionfileerr != $redirectionfile)) {
760 $command .=
" 2> ".dol_sanitizePathName($redirectionfileerr);
768 if (empty($execmethod)) {
772 dol_syslog(
"Utils::executeCLI execmethod=".$execmethod.
" command=".$command, LOG_DEBUG);
773 $output_arr = array();
775 if ($execmethod == 1) {
777 exec($command, $output_arr, $retval);
780 $langs->load(
"errors");
781 dol_syslog(
"Utils::executeCLI retval after exec=".$retval, LOG_ERR);
782 $error =
'Error '.$retval;
785 if ($execmethod == 2) {
786 $handle = fopen($outputfile,
'w+b');
788 dol_syslog(
"Utils::executeCLI run command ".$command);
789 $handlein = popen($command,
'r');
790 while (!feof($handlein)) {
791 $read = fgets($handlein);
792 fwrite($handle, $read);
793 $output_arr[] = $read;
802 if (is_array($output_arr) && count($output_arr) > 0) {
803 foreach ($output_arr as $val) {
804 $output .= $val.($execmethod == 2 ?
'' :
"\n");
808 dol_syslog(
"Utils::executeCLI result=".$result.
" output=".$output.
" error=".$error, LOG_DEBUG);
810 return array(
'result' => $result,
'output' => $output,
'error' => $error);
821 global $conf, $langs, $user,
$mysoc;
826 $modulelowercase = strtolower($module);
830 $dir = $dirins.
'/'.$modulelowercase;
835 dol_include_once($modulelowercase.
'/core/modules/mod'.$module.
'.class.php');
836 $class =
'mod'.$module;
838 if (class_exists($class)) {
847 $langs->load(
"errors");
848 dol_print_error(
null, $langs->trans(
"ErrorFailedToLoadModuleDescriptorForXXX", $module));
852 $arrayversion = explode(
'.',
$moduleobj->version, 3);
853 if (count($arrayversion)) {
854 $FILENAMEASCII = strtolower($module).
'.asciidoc';
855 $FILENAMEDOC = strtolower($module).
'.html';
856 $FILENAMEDOCPDF = strtolower($module).
'.pdf';
859 $dirofmoduledoc =
dol_buildpath(strtolower($module), 0).
'/doc';
860 $dirofmoduletmp =
dol_buildpath(strtolower($module), 0).
'/doc/temp';
861 $outputfiledoc = $dirofmoduledoc.
'/'.$FILENAMEDOC;
862 if ($dirofmoduledoc) {
869 if (!is_writable($dirofmoduletmp)) {
870 $this->error =
'Dir '.$dirofmoduletmp.
' does not exists or is not writable';
875 $this->error =
'Setup of module ModuleBuilder not complete';
880 dol_copy($dirofmodule.
'/README.md', $dirofmoduletmp.
'/README.md',
'0', 1);
881 dol_copy($dirofmodule.
'/ChangeLog.md', $dirofmoduletmp.
'/ChangeLog.md',
'0', 1);
884 $arrayreplacement = array();
885 $arrayreplacement[
'/^#\s.*/m'] =
'';
886 $arrayreplacement[
'/^#/m'] =
'##';
888 dolReplaceInFile($dirofmoduletmp.
'/README.md', $arrayreplacement,
'',
'0', 0, 1);
889 dolReplaceInFile($dirofmoduletmp.
'/ChangeLog.md', $arrayreplacement,
'',
'0', 0, 1);
892 $destfile = $dirofmoduletmp.
'/'.$FILENAMEASCII;
894 $fhandle = fopen($destfile,
'w+');
896 $specs =
dol_dir_list(
dol_buildpath(strtolower($module).
'/doc', 0),
'files', 1,
'(\.md|\.asciidoc)$', array(
'\/temp\/'));
899 foreach ($specs as $spec) {
900 if (preg_match(
'/notindoc/', $spec[
'relativename'])) {
903 if (preg_match(
'/example/', $spec[
'relativename'])) {
906 if (preg_match(
'/disabled/', $spec[
'relativename'])) {
910 $pathtofile = strtolower($module).
'/doc/'.$spec[
'relativename'];
911 $format =
'asciidoc';
912 if (preg_match(
'/\.md$/i', $spec[
'name'])) {
913 $format =
'markdown';
916 $filecursor = @file_get_contents($spec[
'fullname']);
918 fwrite($fhandle, ($i ?
"\n<<<\n\n" :
"").$filecursor.
"\n");
920 $this->error =
'Failed to concat content of file '.$spec[
'fullname'];
929 $contentreadme = file_get_contents($dirofmoduletmp.
'/README.md');
930 $contentchangelog = file_get_contents($dirofmoduletmp.
'/ChangeLog.md');
932 include DOL_DOCUMENT_ROOT.
'/core/lib/parsemd.lib.php';
935 $arrayreplacement = array(
936 'mymodule' => strtolower($module),
937 'MyModule' => $module,
938 'MYMODULE' => strtoupper($module),
939 'My module' => $module,
940 'my module' => $module,
941 'Mon module' => $module,
942 'mon module' => $module,
943 'htdocs/modulebuilder/template' => strtolower($module),
944 '__MYCOMPANY_NAME__' =>
$mysoc->name,
945 '__KEYWORDS__' => $module,
946 '__USER_FULLNAME__' => $user->getFullName($langs),
947 '__USER_EMAIL__' => $user->email,
949 '---Put here your own copyright and developer email---' =>
dol_print_date($now,
'dayrfc').
' '.$user->getFullName($langs).($user->email ?
' <'.$user->email.
'>' :
''),
950 '__DATA_SPECIFICATION__' =>
'Not yet available',
960 $currentdir = getcwd();
963 require_once DOL_DOCUMENT_ROOT.
'/core/class/utils.class.php';
964 $utils =
new Utils($this->db);
967 $command =
getDolGlobalString(
'MODULEBUILDER_ASCIIDOCTOR') .
' '.$destfile.
' -n -o '.$dirofmoduledoc.
'/'.$FILENAMEDOC;
968 $outfile = $dirofmoduletmp.
'/out.tmp';
970 $resarray = $utils->executeCLI($command, $outfile);
971 if ($resarray[
'result'] !=
'0') {
972 $this->error = $resarray[
'error'].
' '.$resarray[
'output'];
973 $this->errors[] = $this->error;
975 $result = ($resarray[
'result'] == 0) ? 1 : 0;
976 if ($result < 0 && empty($this->errors)) {
977 $this->error = $langs->trans(
"ErrorFailToGenerateFile", $FILENAMEDOC);
978 $this->errors[] = $this->error;
982 $command =
getDolGlobalString(
'MODULEBUILDER_ASCIIDOCTORPDF') .
' '.$destfile.
' -n -o '.$dirofmoduledoc.
'/'.$FILENAMEDOCPDF;
983 $outfile = $dirofmoduletmp.
'/outpdf.tmp';
984 $resarray = $utils->executeCLI($command, $outfile);
985 if ($resarray[
'result'] !=
'0') {
986 $this->error = $resarray[
'error'].
' '.$resarray[
'output'];
987 $this->errors[] = $this->error;
989 $result = ($resarray[
'result'] == 0) ? 1 : 0;
990 if ($result < 0 && empty($this->errors)) {
991 $this->error = $langs->trans(
"ErrorFailToGenerateFile", $FILENAMEDOCPDF);
992 $this->errors[] = $this->error;
1007 $langs->load(
"errors");
1008 $this->error = $langs->trans(
"ErrorCheckVersionIsDefined");
1025 if (empty($conf->loghandlers[
'mod_syslog_file'])) {
1029 if (!function_exists(
'gzopen')) {
1030 $this->error =
'Support for gzopen not available in this PHP';
1034 require_once DOL_DOCUMENT_ROOT .
'/core/lib/files.lib.php';
1039 $mainlogdir = DOL_DATA_ROOT;
1040 $mainlog =
'dolibarr.log';
1042 $mainlogfull = str_replace(
'DOL_DATA_ROOT', DOL_DATA_ROOT, $conf->global->SYSLOG_FILE);
1043 $mainlogdir = dirname($mainlogfull);
1044 $mainlog = basename($mainlogfull);
1047 $tabfiles =
dol_dir_list(DOL_DATA_ROOT,
'files', 0,
'^(dolibarr_.+|odt2pdf)\.log$');
1048 $tabfiles[] = array(
'name' => $mainlog,
'path' => $mainlogdir);
1050 foreach ($tabfiles as $file) {
1051 $logname = $file[
'name'];
1052 $logpath = $file[
'path'];
1057 $filter =
'^'.preg_quote($logname,
'/').
'\.([0-9]+)\.gz$';
1059 $gzfilestmp =
dol_dir_list($logpath,
'files', 0, $filter);
1062 foreach ($gzfilestmp as $gzfile) {
1063 $tabmatches = array();
1064 preg_match(
'/'.$filter.
'/i', $gzfile[
'name'], $tabmatches);
1066 $numsave = intval($tabmatches[1]);
1068 $gzfiles[$numsave] = $gzfile;
1071 krsort($gzfiles, SORT_NUMERIC);
1073 foreach ($gzfiles as $numsave => $dummy) {
1074 if (
dol_is_file($logpath.
'/'.$logname.
'.'.($numsave + 1).
'.gz')) {
1078 if ($numsave >= $nbSaves) {
1079 dol_delete_file($logpath.
'/'.$logname.
'.'.$numsave.
'.gz', 0, 0, 0,
null,
false, 0);
1081 dol_move($logpath.
'/'.$logname.
'.'.$numsave.
'.gz', $logpath.
'/'.$logname.
'.'.($numsave + 1).
'.gz',
'0', 1, 0, 0);
1088 $gzfilehandle = gzopen($logpath.
'/'.$logname.
'.1.gz',
'wb9');
1090 if (empty($gzfilehandle)) {
1091 $this->error =
'Failted to open file '.$logpath.
'/'.$logname.
'.1.gz';
1095 $sourcehandle = fopen($logpath.
'/'.$logname,
'r');
1097 if (empty($sourcehandle)) {
1098 $this->error =
'Failed to open file '.$logpath.
'/'.$logname;
1102 while (!feof($sourcehandle)) {
1103 gzwrite($gzfilehandle, fread($sourcehandle, 512 * 1024));
1106 fclose($sourcehandle);
1107 gzclose($gzfilehandle);
1109 dolChmod($logpath.
'/'.$logname.
'.1.gz');
1115 $newlog = fopen($logpath.
'/'.$logname,
'a+');
1123 $this->output =
'Archive log files (keeping last SYSLOG_FILE_SAVES='.$nbSaves.
' files) done.';
1137 public function backupTables($outputfile, $tables =
'*')
1141 global $dolibarr_main_db_character_set;
1145 $charset = ($dolibarr_main_db_character_set ==
'utf8mb4' ?
'utf8mb4' :
'utf8');
1146 $sanitizedcharset =
$db->sanitize($charset);
1147 if (is_a(
$db,
'DoliDBMysqli')) {
1149 $db->db->set_charset($charset);
1152 $db->query(
'SET NAMES '.
$db->sanitize($charset));
1153 $db->query(
'SET CHARACTER SET '.
$db->sanitize($charset));
1157 if ($tables ==
'*') {
1159 $result =
$db->query(
'SHOW FULL TABLES WHERE Table_type = \'BASE TABLE\'');
1160 while ($row =
$db->fetch_row($result)) {
1161 $tables[] = $row[0];
1164 $tables = is_array($tables) ? $tables : explode(
',', $tables);
1168 $handle = fopen($outputfile,
'w+');
1169 if (fwrite($handle,
'') ===
false) {
1170 $langs->load(
"errors");
1171 dol_syslog(
"Failed to open file ".$outputfile, LOG_ERR);
1172 $errormsg = $langs->trans(
"ErrorFailedToWriteInDir");
1178 $sqlhead .=
"-- ".$db::LABEL.
" dump via php with Dolibarr ".DOL_VERSION.
"
1180-- Host: ".
$db->db->host_info.
" Database: ".
$db->database_name.
"
1181-- ------------------------------------------------------
1182-- Server version ".
$db->db->server_info.
"
1197 if (
GETPOST(
"nobin_disable_fk")) {
1198 $sqlhead .=
"SET FOREIGN_KEY_CHECKS=0;\n";
1201 if (
GETPOST(
"nobin_use_transaction")) {
1202 $sqlhead .=
"SET AUTOCOMMIT=0;\nSTART TRANSACTION;\n";
1205 fwrite($handle, $sqlhead);
1208 if (
GETPOST(
"nobin_sql_ignore")) {
1209 $ignore =
'IGNORE ';
1212 if (
GETPOST(
"nobin_delayed")) {
1213 $delayed =
'DELAYED ';
1217 foreach ($tables as $table) {
1219 fwrite($handle,
"\n--\n-- Table structure for table `".$table.
"`\n--\n");
1222 fwrite($handle,
"DROP TABLE IF EXISTS `".$table.
"`;\n");
1224 fwrite($handle,
"/*!40101 SET @saved_cs_client = @@character_set_client */;\n");
1225 fwrite($handle,
"/*!40101 SET character_set_client = ".$sanitizedcharset.
" */;\n");
1226 $resqldrop =
$db->query(
'SHOW CREATE TABLE '.$table);
1227 $row2 =
$db->fetch_row($resqldrop);
1228 if (empty($row2[1])) {
1229 fwrite($handle,
"\n-- WARNING: Show create table ".$table.
" return empty string when it should not.\n");
1231 fwrite($handle, $row2[1].
";\n");
1235 fwrite($handle,
"\n--\n-- Dumping data for table `".$table.
"`\n--\n");
1236 if (!
GETPOST(
"nobin_nolocks")) {
1237 fwrite($handle,
"LOCK TABLES `".$table.
"` WRITE;\n");
1239 if (
GETPOST(
"nobin_disable_fk")) {
1240 fwrite($handle,
"ALTER TABLE `".$table.
"` DISABLE KEYS;\n");
1242 fwrite($handle,
"/*!40000 ALTER TABLE `".$table.
"` DISABLE KEYS */;\n");
1245 $sql =
"SELECT * FROM ".$table;
1246 $result =
$db->query($sql);
1247 while ($row =
$db->fetch_row($result)) {
1249 fwrite($handle,
"INSERT ".$delayed.$ignore.
"INTO ".$table.
" VALUES (");
1250 $columns = count($row);
1251 for ($j = 0; $j < $columns; $j++) {
1253 if ($row[$j] ==
null && !is_string($row[$j])) {
1256 } elseif (is_string($row[$j]) && $row[$j] ==
'') {
1259 } elseif (is_numeric($row[$j]) && !strcmp((
string) $row[$j], (
string) ((
float) $row[$j] + 0))) {
1263 $row[$j] = addslashes($row[$j]);
1264 $row[$j] = preg_replace(
"#\n#",
"\\n", $row[$j]);
1265 $row[$j] =
"'".$row[$j].
"'";
1268 fwrite($handle, implode(
',', $row).
");\n");
1270 if (
GETPOST(
"nobin_disable_fk")) {
1271 fwrite($handle,
"ALTER TABLE `".$table.
"` ENABLE KEYS;\n");
1273 if (!
GETPOST(
"nobin_nolocks")) {
1274 fwrite($handle,
"UNLOCK TABLES;\n");
1276 fwrite($handle,
"\n\n\n");
1300 $sqlfooter =
"\n\n";
1301 if (
GETPOST(
"nobin_use_transaction")) {
1302 $sqlfooter .=
"COMMIT;\n";
1304 if (
GETPOST(
"nobin_disable_fk")) {
1305 $sqlfooter .=
"SET FOREIGN_KEY_CHECKS=1;\n";
1307 $sqlfooter .=
"\n\n-- Dump completed on ".date(
'Y-m-d G-i-s');
1308 fwrite($handle, $sqlfooter);
1328 public function sendBackup($sendto =
'', $from =
'', $subject =
'', $message =
'', $filename =
'', $filter =
'', $sizelimit = 100000000)
1330 global $conf, $langs;
1339 if (!empty($from)) {
1347 if (!empty($sendto)) {
1355 if (!empty($subject)) {
1361 if (empty($message)) {
1365 $tmpfiles = array();
1366 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
1368 if (
dol_is_file($conf->admin->dir_output.
'/backup/'.$filename)) {
1374 if ($tmpfiles && is_array($tmpfiles)) {
1375 foreach ($tmpfiles as $key => $val) {
1376 if ($key ==
'fullname') {
1377 $filepath = array($val);
1380 if ($key ==
'type') {
1381 $mimetype = array($val);
1383 if ($key ==
'relativename') {
1384 $filename = array($val);
1390 if ($filesize > $sizelimit) {
1391 $message .=
'<br>'.$langs->trans(
"BackupIsTooLargeSend");
1392 $documenturl =
$dolibarr_main_url_root.
'/document.php?modulepart=systemtools&atachement=1&file=backup/'.urlencode($filename[0]);
1393 $message .=
'<br><a href='.$documenturl.
'>Download link</a>';
1399 $output =
'No backup file found';
1405 include_once DOL_DOCUMENT_ROOT .
'/core/class/CMailFile.class.php';
1406 $mailfile =
new CMailFile($subject, $sendto, $from, $message, $filepath, $mimetype, $filename,
'',
'', 0, 1);
1408 if ($mailfile->error) {
1410 $output = $mailfile->error;
1416 if (!$error && $mailfile !==
null) {
1417 $result = $mailfile->sendfile();
1420 $output = $mailfile->error;
1426 $this->error =
"Error sending backup file ".((string) $error);
1427 $this->output = $output;
1446 dol_syslog(
"Utils::cleanUnfinishedCronjob Starting cleaning");
1449 require_once DOL_DOCUMENT_ROOT .
'/cron/class/cronjob.class.php';
1453 $this_job->fetch(-1,
'Utils',
'cleanUnfinishedCronjob');
1454 if (empty($this_job->id) || !empty($this_job->error)) {
1455 dol_syslog(
"Utils::cleanUnfinishedCronjob Unable to fetch himself: ".$this_job->error, LOG_ERR);
1460 $this_job->processing = 0;
1461 if ($this_job->update($user) < 0) {
1462 dol_syslog(
"Utils::cleanUnfinishedCronjob Unable to update himself: ".implode(
', ', $this_job->errors), LOG_ERR);
1467 $cron_job->fetchAll(
'DESC',
't.rowid', 100, 0, 1, [], 1);
1470 foreach ($cron_job->lines as $job_line) {
1472 if (empty($job_line->pid)) {
1473 dol_syslog(
"Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id.
" don't have a PID", LOG_DEBUG);
1478 $job->fetch($job_line->id);
1479 if (empty($job->id) || !empty($job->error)) {
1480 dol_syslog(
"Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id.
" can't be fetch: ".$job->error, LOG_ERR);
1485 if (! posix_kill($job->pid, 0)) {
1487 $job->processing = 0;
1491 $job->lastresult = strval(-1);
1492 $job->lastoutput =
'Job killed by job cleanUnfinishedCronjob';
1494 if ($job->update($user) < 0) {
1495 dol_syslog(
"Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id.
" can't be updated: ".implode(
', ', $job->errors), LOG_ERR);
1498 dol_syslog(
"Utils::cleanUnfinishedCronjob Cronjob ".$job_line->id.
" cleaned");
1502 dol_syslog(
"Utils::cleanUnfinishedCronjob Cleaning completed");
global $dolibarr_main_url_root
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Class to manage ECM directories.
Class to manage utility methods.
executeCLI($command, $outputfile, $execmethod=0, $redirectionfile=null, $noescapecommand=0, $redirectionfileerr=null)
Execute a CLI command.
__construct($db)
Constructor.
generateDoc($module)
Generate documentation of a Module.
getShellPasswordParam($password)
Return the -p parameter of mysqldump with the password, escaped to be used in a shell command line.
compressSyslogs()
This saves syslog files and compresses older ones.
sendBackup($sendto='', $from='', $subject='', $message='', $filename='', $filter='', $sizelimit=100000000)
Make a send last backup of database or fil in param CAN BE A CRON TASK.
dumpDatabase($compression='none', $type='auto', $usedefault=1, $file='auto', $keeplastnfiles=0, $execmethod=0, $lowmemorydump=0)
Make a backup of database CAN BE A CRON TASK.
cleanUnfinishedCronjob()
Clean unfinished cronjob in processing when pid is no longer present in the system CAN BE A CRON TASK...
purgeFiles($choices='tempfilesold+logfiles', $nbsecondsold=86400)
Purge files into directory of data files.
dol_move($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array(), $entity=null)
Move a file into another name.
dol_filesize($pathoffile)
Return size of a file.
dol_copy($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=0)
Copy a file to another file.
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_is_file($pathoffile)
Return if path is a file.
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
dol_most_recent_file($dir, $regexfilter='', $excludefilter=array('(\.meta|_preview.*\.png) $', '^\.'), $nohook=0, $mode=0)
Return file(s) into a directory (by default most recent)
dol_is_dir($folder)
Test if filename is a directory.
dolReplaceInFile($srcfile, $arrayreplacement, $destfile='', $newmask='0', $indexdatabase=0, $arrayreplacementisregex=0)
Make replacement of strings into a file.
dol_now($mode='gmt')
Return date for now.
dol_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.