dolibarr  16.0.5
export_files.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2006-2014 Laurent Destailleur <eldy@users.sourceforge.net>
3  * Copyright (C) 2011 Juanjo Menent <jmenent@2byte.es>
4  * Copyright (C) 2015 RaphaĆ«l Doursenaud <rdoursenaud@gpcsolutions.fr>
5  * Copyright (C) 2021 Regis Houssin <regis.houssin@inodbox.com>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program. If not, see <https://www.gnu.org/licenses/>.
19  */
20 
26 if (! defined('CSRFCHECK_WITH_TOKEN')) {
27  define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET
28 }
29 
30 require '../../main.inc.php';
31 require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
32 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
33 require_once DOL_DOCUMENT_ROOT.'/core/class/utils.class.php';
34 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
35 
36 $langs->load("admin");
37 
38 $action = GETPOST('action', 'aZ09');
39 $what = GETPOST('what', 'alpha');
40 $export_type = GETPOST('export_type', 'alpha');
41 $file = trim(GETPOST('zipfilename_template', 'alpha'));
42 $compression = GETPOST('compression', 'aZ09');
43 
44 $file = dol_sanitizeFileName($file);
45 $file = preg_replace('/(\.zip|\.tar|\.tgz|\.gz|\.tar\.gz|\.bz2|\.zst)$/i', '', $file);
46 
47 $sortfield = GETPOST('sortfield', 'aZ09comma');
48 $sortorder = GETPOST('sortorder', 'aZ09comma');
49 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
50 if (!$sortorder) {
51  $sortorder = "DESC";
52 }
53 if (!$sortfield) {
54  $sortfield = "date";
55 }
56 if ($page < 0) {
57  $page = 0;
58 } elseif (empty($page)) {
59  $page = 0;
60 }
61 $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
62 $offset = $limit * $page;
63 
64 if (!$user->admin) {
66 }
67 
68 $errormsg = '';
69 
70 
71 /*
72  * Actions
73  */
74 
75 if ($action == 'delete') {
76  $filerelative = dol_sanitizeFileName(GETPOST('urlfile', 'alpha'));
77  $filepath = $conf->admin->dir_output.'/'.$filerelative;
78  $ret = dol_delete_file($filepath, 1);
79  if ($ret) {
80  setEventMessages($langs->trans("FileWasRemoved", $filerelative), null, 'mesgs');
81  } else {
82  setEventMessages($langs->trans("ErrorFailToDeleteFile", $filerelative), null, 'errors');
83  }
84  $action = '';
85 }
86 
87 
88 /*
89  * View
90  */
91 
92 // Increase limit of time. Works only if we are not in safe mode
93 $ExecTimeLimit = 1800; // 30mn
94 if (!empty($ExecTimeLimit)) {
95  $err = error_reporting();
96  error_reporting(0); // Disable all errors
97  //error_reporting(E_ALL);
98  @set_time_limit($ExecTimeLimit); // Need more than 240 on Windows 7/64
99  error_reporting($err);
100 }
101 
102 /* If value has been forced with a php_admin_value, this has no effect. Example of value: '512M' */
103 $MemoryLimit = getDolGlobalString('MAIN_MEMORY_LIMIT_ARCHIVE_DATAROOT');
104 if (!empty($MemoryLimit)) {
105  @ini_set('memory_limit', $MemoryLimit);
106 }
107 
108 $form = new Form($db);
109 $formfile = new FormFile($db);
110 
111 //$help_url='EN:Backups|FR:Sauvegardes|ES:Copias_de_seguridad';
112 //llxHeader('','',$help_url);
113 
114 //print load_fiche_titre($langs->trans("Backup"),'','title_setup');
115 
116 
117 // Start with empty buffer
118 $dump_buffer = '';
119 $dump_buffer_len = 0;
120 
121 // We will send fake headers to avoid browser timeout when buffering
122 $time_start = time();
123 
124 
125 $outputdir = $conf->admin->dir_output.'/documents';
126 $result = dol_mkdir($outputdir);
127 
128 $utils = new Utils($db);
129 
130 if ($export_type == 'externalmodule' && ! empty($what)) {
131  $fulldirtocompress = DOL_DOCUMENT_ROOT.'/custom/'.dol_sanitizeFileName($what);
132 } else {
133  $fulldirtocompress = DOL_DATA_ROOT;
134 }
135 $dirtoswitch = dirname($fulldirtocompress);
136 $dirtocompress = basename($fulldirtocompress);
137 
138 if ($compression == 'zip') {
139  $file .= '.zip';
140 
141  $excludefiles = '/(\.back|\.old|\.log|\.pdf_preview-.*\.png|[\/\\\]temp[\/\\\]|[\/\\\]admin[\/\\\]documents[\/\\\])/i';
142 
143  //var_dump($fulldirtocompress);
144  //var_dump($outputdir."/".$file);exit;
145 
146  $rootdirinzip = '';
147  if ($export_type == 'externalmodule' && !empty($what)) {
148  $rootdirinzip = $what;
149 
150  global $dolibarr_allow_download_external_modules;
151  if (empty($dolibarr_allow_download_external_modules)) {
152  print 'Download of external modules is not allowed by $dolibarr_allow_download_external_modules in conf.php file';
153  $db->close();
154  exit();
155  }
156  }
157 
158  $ret = dol_compress_dir($fulldirtocompress, $outputdir."/".$file, $compression, $excludefiles, $rootdirinzip);
159  if ($ret < 0) {
160  if ($ret == -2) {
161  $langs->load("errors");
162  $errormsg = $langs->trans("ErrNoZipEngine");
163  } else {
164  $langs->load("errors");
165  $errormsg = $langs->trans("ErrorFailedToWriteInDir", $outputdir);
166  }
167  }
168 } elseif (in_array($compression, array('gz', 'bz', 'zstd'))) {
169  $userlogin = ($user->login ? $user->login : 'unknown');
170 
171  $outputfile = $conf->admin->dir_temp.'/export_files.'.$userlogin.'.out'; // File used with popen method
172 
173  $file .= '.tar';
174 
175  // We also exclude '/temp/' dir and 'documents/admin/documents'
176  // We make escapement here and call executeCLI without escapement because we don't want to have the '*.log' escaped.
177  $cmd = "tar -cf '".escapeshellcmd($outputdir."/".$file)."' --exclude-vcs --exclude-caches-all --exclude='temp' --exclude='*.log' --exclude='*.pdf_preview-*.png' --exclude='documents/admin/documents' -C '".escapeshellcmd(dol_sanitizePathName($dirtoswitch))."' '".escapeshellcmd(dol_sanitizeFileName($dirtocompress))."'";
178 
179  $result = $utils->executeCLI($cmd, $outputfile, 0, null, 1);
180 
181  $retval = $result['error'];
182  if ($result['result'] || !empty($retval)) {
183  $langs->load("errors");
184  dol_syslog("Documents tar retval after exec=".$retval, LOG_ERR);
185  $errormsg = 'Error tar generation return '.$retval;
186  } else {
187  if ($compression == 'gz') {
188  $cmd = "gzip -f ".$outputdir."/".$file;
189  } elseif ($compression == 'bz') {
190  $cmd = "bzip2 -f ".$outputdir."/".$file;
191  } elseif ($compression == 'zstd') {
192  $cmd = "zstd -z -9 -q --rm ".$outputdir."/".$file;
193  }
194 
195  $result = $utils->executeCLI($cmd, $outputfile);
196 
197  $retval = $result['error'];
198  if ($result['result'] || !empty($retval)) {
199  $errormsg = 'Error '.$compression.' generation return '.$retval;
200  unlink($outputdir."/".$file);
201  }
202  }
203 } else {
204  $errormsg = 'Bad value for compression method';
205  print $errormsg;
206 }
207 
208 if ($export_type != 'externalmodule' || empty($what)) {
209  if ($errormsg) {
210  setEventMessages($langs->trans("Error")." : ".$errormsg, null, 'errors');
211  } else {
212  setEventMessages($langs->trans("BackupFileSuccessfullyCreated").'.<br>'.$langs->trans("YouCanDownloadBackupFile"), null, 'mesgs');
213  }
214 
215  $db->close();
216 
217  // Redirect to calling page
218  $returnto = 'dolibarr_export.php';
219 
220  header("Location: ".$returnto);
221  exit();
222 } else {
223  $zipname = $outputdir."/".$file;
224 
225  // Then download the zipped file.
226  header('Content-Type: application/zip');
227  header('Content-disposition: attachment; filename='.basename($zipname));
228  header('Content-Length: '.filesize($zipname));
229  readfile($zipname);
230 
231  dol_delete_file($zipname);
232 
233  $db->close();
234 
235  exit();
236 }
dol_sanitizePathName
dol_sanitizePathName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a path name.
Definition: functions.lib.php:1251
dol_sanitizeFileName
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
Definition: functions.lib.php:1226
GETPOST
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
Definition: functions.lib.php:484
Utils
Class to manage utility methods.
Definition: utils.class.php:30
$form
if($cancel &&! $id) if($action=='add' &&! $cancel) if($action=='delete') if($id) $form
Actions.
Definition: card.php:142
dol_delete_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.
Definition: files.lib.php:1231
FormFile
Class to offer components to list and upload files.
Definition: html.formfile.class.php:36
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1603
getDolGlobalString
if(!function_exists('utf8_encode')) if(!function_exists('utf8_decode')) getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
Definition: functions.lib.php:80
GETPOSTISSET
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
Definition: functions.lib.php:386
Form
Class to manage generation of HTML components Only common components must be here.
Definition: html.form.class.php:52
setEventMessages
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='')
Set event messages in dol_events session object.
Definition: functions.lib.php:8137
accessforbidden
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program Calling this function terminate execution ...
Definition: security.lib.php:933
dol_mkdir
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
Definition: functions.lib.php:6603