dolibarr 25.0.0-alpha
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 * Copyright (C) 2024-2026 Frédéric France <frederic.france@free.fr>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
27if (! defined('CSRFCHECK_WITH_TOKEN')) {
28 define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET
29}
30
31// Load Dolibarr environment
32require '../../main.inc.php';
42require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
43require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
44require_once DOL_DOCUMENT_ROOT.'/core/class/utils.class.php';
45require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
46
47$langs->load("admin");
48
49$action = GETPOST('action', 'aZ09');
50$what = GETPOST('what', 'alpha');
51$export_type = GETPOST('export_type', 'alpha');
52$file = trim(GETPOST('zipfilename_template', 'alpha'));
53$compression = GETPOST('compression', 'aZ09');
54
55$file = dol_sanitizeFileName($file, '_', 1, 1);
56$file = preg_replace('/(\.zip|\.tar|\.tgz|\.gz|\.tar\.gz|\.bz2|\.zst)$/i', '', $file);
57
58$sortfield = GETPOST('sortfield', 'aZ09comma');
59$sortorder = GETPOST('sortorder', 'aZ09comma');
60$page = GETPOSTISSET('pageplusone') ? (GETPOSTINT('pageplusone') - 1) : GETPOSTINT("page");
61if (!$sortorder) {
62 $sortorder = "DESC";
63}
64if (!$sortfield) {
65 $sortfield = "date";
66}
67if ($page < 0) {
68 $page = 0;
69} elseif (empty($page)) {
70 $page = 0;
71}
72$limit = GETPOSTINT('limit') ? GETPOSTINT('limit') : $conf->liste_limit;
73$offset = $limit * $page;
74
75if (!$user->admin) {
77}
78
79$errormsg = '';
80
81
82/*
83 * Actions
84 */
85
86if ($action == 'delete') {
87 $filerelative = dol_sanitizeFileName(GETPOST('urlfile', 'alpha'));
88 $filepath = $conf->admin->dir_output.'/'.$filerelative;
89 $ret = dol_delete_file($filepath, 1);
90 if ($ret) {
91 setEventMessages($langs->trans("FileWasRemoved", $filerelative), null, 'mesgs');
92 } else {
93 setEventMessages($langs->trans("ErrorFailToDeleteFile", $filerelative), null, 'errors');
94 }
95 $action = '';
96}
97
98
99/*
100 * View
101 */
102
103// Increase limit of time. Works only if we are not in safe mode
104$ExecTimeLimit = getDolGlobalInt('MAIN_ADMIN_TOOLS_EXPORT_FILES_EXEC_TIME_LIMIT', 1800);; // 30mn
105if (!empty($ExecTimeLimit)) {
106 $err = error_reporting();
107 error_reporting(0); // Disable all errors
108 //error_reporting(E_ALL);
109 @set_time_limit($ExecTimeLimit); // Need more than 240 on Windows 7/64
110 error_reporting($err);
111}
112
113/* If value has been forced with a php_admin_value, this has no effect. Example of value: '512M' */
114$MemoryLimit = getDolGlobalString('MAIN_MEMORY_LIMIT_ARCHIVE_DATAROOT');
115if (!empty($MemoryLimit)) {
116 @ini_set('memory_limit', $MemoryLimit);
117}
118
119$form = new Form($db);
120$formfile = new FormFile($db);
121
122//$help_url='EN:Backups|FR:Sauvegardes|ES:Copias_de_seguridad';
123//llxHeader('','',$help_url);
124
125//print load_fiche_titre($langs->trans("Backup"),'','title_setup');
126
127
128// Start with empty buffer
129$dump_buffer = '';
130$dump_buffer_len = 0;
131
132// We will send fake headers to avoid browser timeout when buffering
133$time_start = time();
134
135
136// The exports of the application files are stored into the backupapp directory
137// to keep them separated from the exports of the documents directory.
138if ($export_type == 'app') {
139 $outputdir = $conf->admin->dir_output.'/backupapp';
140} else {
141 $outputdir = $conf->admin->dir_output.'/documents';
142}
143$result = dol_mkdir($outputdir);
144
145$utils = new Utils($db);
146
147// Export of application files is allowed only if the option $dolibarr_allow_download_app is set
148// into the conf/conf.php file, because the application directory contains the external modules
149// installed into the 'custom' directory.
150if ($export_type == 'app' && empty($dolibarr_allow_download_app)) {
151 setEventMessages($langs->trans("DownloadOfAppFileDisallowed"), null, 'errors');
152 $db->close();
153 header("Location: dolibarr_export.php");
154 exit();
155}
156
157if ($export_type == 'externalmodule' && !empty($what)) {
158 // Check is done here, before any compression method, so it can't be bypassed with compression=gz, bz or zstd
159 global $dolibarr_allow_download_app;
160 if (empty($dolibarr_allow_download_app)) {
161 print 'Download of external modules is not allowed by $dolibarr_allow_download_app in conf.php file';
162 $db->close();
163 exit();
164 }
165 // Only a module directory name is allowed (not '.' that would archive the whole custom directory)
166 if (!preg_match('/^[a-z0-9_\-]+$/i', $what) || !is_dir(DOL_DOCUMENT_ROOT.'/custom/'.dol_sanitizeFileName($what))) {
167 print 'Bad value for parameter what';
168 $db->close();
169 exit();
170 }
171 $fulldirtocompress = DOL_DOCUMENT_ROOT.'/custom/'.dol_sanitizeFileName($what);
172} elseif ($export_type == 'app') {
173 $fulldirtocompress = DOL_DOCUMENT_ROOT;
174} else {
175 $fulldirtocompress = DOL_DATA_ROOT;
176}
177$dirtoswitch = dirname($fulldirtocompress);
178$dirtocompress = basename($fulldirtocompress);
179
180if ($compression == 'zip') {
181 $file .= '.zip';
182
183 $excludefiles = '/(\.back|\.old|\.log|\.pdf_preview-.*\.png|[\/\\\]temp[\/\\\]|[\/\\\]admin[\/\\\]documents[\/\\\]|[\/\\\]admin[\/\\\]backup[\/\\\]|[\/\\\]admin[\/\\\]backupapp[\/\\\])/i';
184
185 //var_dump($fulldirtocompress);
186 //var_dump($outputdir."/".$file);exit;
187
188 $rootdirinzip = '';
189 if ($export_type == 'externalmodule' && !empty($what)) {
190 $rootdirinzip = $what;
191 }
192 if ($export_type == 'app') {
193 $rootdirinzip = basename(DOL_DOCUMENT_ROOT);
194 }
195
196 global $errormsg;
197 $ret = dol_compress_dir($fulldirtocompress, $outputdir."/".$file, $compression, $excludefiles, $rootdirinzip); // Can modify $errormsg
198 if ($ret < 0) {
199 if ($ret == -2) {
200 $langs->load("errors");
201 $errormsg = $langs->trans("ErrNoZipEngine");
202 } else {
203 $langs->load("errors");
204 // @phpstan-ignore-next-line The $errormsg can have been modified by the dol_compress_dir function.
205 $errormsg = $langs->trans("ErrorFailedToWriteInDir", $outputdir).($errormsg ? "\n" . $errormsg : "");
206 }
207 }
208} elseif (in_array($compression, array('gz', 'bz', 'zstd'))) {
209 $userlogin = ($user->login ? $user->login : 'unknown');
210
211 dol_mkdir($conf->admin->dir_temp); // May have been removed by a "Clean temporary files" purge
212
213 $outputfile = $conf->admin->dir_temp.'/'.dol_sanitizeFileName('export_files.'.$userlogin.'.out'); // File used with popen method
214
215 $file .= '.tar';
216
217 // Write the tar into a temp directory outside the documents tree.
218 // If we wrote it directly under $outputdir (= DOL_DATA_ROOT/admin/documents),
219 // tar would notice its own output directory growing as it reads the source
220 // and exit with code 1 / 'file changed as we read it', even though the archive
221 // is complete. The error short-circuited compression at line 194 and left
222 // users with an uncompressed .tar plus a misleading error (#37266).
223 $tmpfile = $conf->admin->dir_temp.'/'.dol_sanitizeFileName($file);
224
225 // We also exclude '/temp/' dir, 'documents/admin/documents' (previous documents backups), 'documents/admin/backup' (database dumps)
226 // and 'documents/admin/backupapp' (application archives backups)
227 // We make escapement here and call executeCLI without escapement because we don't want to have the '*.log' escaped.
228 $cmd = "tar -cf '".escapeshellcmd($tmpfile)."' --exclude-vcs --exclude-caches-all --exclude='temp' --exclude='*.log' --exclude='*.pdf_preview-*.png' --exclude='admin/documents' --exclude='admin/backup' --exclude='admin/backupapp' -C '".escapeshellcmd(dol_sanitizePathName($dirtoswitch))."' '".escapeshellcmd(dol_sanitizeFileName($dirtocompress))."'";
229
230 $result = $utils->executeCLI($cmd, $outputfile, 0, null, 1);
231
232 $retval = $result['error'];
233 if ($result['result'] || !empty($retval)) {
234 $langs->load("errors");
235 dol_syslog("Documents tar retval after exec=".$retval, LOG_ERR);
236 $errormsg = 'Error tar generation return '.$retval;
237 if (file_exists($tmpfile)) {
238 unlink($tmpfile);
239 }
240 } else {
241 $compressedtmpfile = $tmpfile;
242 if ($compression == 'gz') {
243 $cmd = "gzip -f ".$tmpfile;
244 $compressedtmpfile = $tmpfile.'.gz';
245 } elseif ($compression == 'bz') {
246 $cmd = "bzip2 -f ".$tmpfile;
247 $compressedtmpfile = $tmpfile.'.bz2';
248 } elseif ($compression == 'zstd') {
249 $cmd = "zstd -z -9 -q --rm ".$tmpfile;
250 $compressedtmpfile = $tmpfile.'.zst';
251 }
252
253 $result = $utils->executeCLI($cmd, $outputfile);
254
255 $retval = $result['error'];
256 if ($result['result'] || !empty($retval)) {
257 $errormsg = 'Error '.$compression.' generation return '.$retval;
258 if (file_exists($tmpfile)) {
259 unlink($tmpfile);
260 }
261 if (file_exists($compressedtmpfile)) {
262 unlink($compressedtmpfile);
263 }
264 } else {
265 // Move the compressed archive from temp to the final outputdir.
266 $finalfile = $outputdir.'/'.basename($compressedtmpfile);
267 if (!@rename($compressedtmpfile, $finalfile)) {
268 $errormsg = 'Error moving generated archive to '.$outputdir;
269 if (file_exists($compressedtmpfile)) {
270 unlink($compressedtmpfile);
271 }
272 } else {
273 $file = basename($compressedtmpfile);
274 }
275 }
276 }
277} else {
278 $errormsg = 'Bad value for compression method';
279 print $errormsg;
280}
281
282
283// Output export
284
285if ($export_type != 'externalmodule' || empty($what)) {
286 top_httphead();
287
288 if ($errormsg) {
289 setEventMessages($langs->trans("Error")." : ".$errormsg, null, 'errors');
290 } else {
291 setEventMessages($langs->trans("BackupFileSuccessfullyCreated").'.<br>'.$langs->trans("YouCanDownloadBackupFile"), null, 'mesgs');
292 }
293
294 $db->close();
295
296 // Redirect to calling page
297 $returnto = 'dolibarr_export.php';
298 if ($export_type == 'app' || GETPOSTINT('allow_download_app')) {
299 // Keep the parameter to keep the step to export the application files visible
300 $returnto .= '?allow_download_app=1';
301 }
302
303 header("Location: ".$returnto);
304
305 exit();
306} else {
307 top_httphead('application/zip');
308
309 $zipname = $outputdir."/".$file;
310
311 // Then download the zipped file.
312
313 header('Content-disposition: attachment; filename='.basename($zipname));
314 header('Content-Length: '.filesize($zipname));
315 readfile($zipname);
316
317 dol_delete_file($zipname);
318
319 $db->close();
320
321 exit();
322}
Class to offer components to list and upload files.
Class to manage generation of HTML components Only common components must be here.
Class to manage utility methods.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
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_sanitizePathName($str, $newstr='_', $unaccent=0, $allowdash=0)
Clean a string to use it as a path name.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
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)
if(!defined( 'NOREQUIREMENU')) if(!empty(GETPOST('seteventmessages', 'alpha'))) if(!function_exists("llxHeader")) top_httphead($contenttype='text/html', $forcenocache=0)
Show HTTP header.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.