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-2025 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';
40require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
41require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
42require_once DOL_DOCUMENT_ROOT.'/core/class/utils.class.php';
43require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
44
45$langs->load("admin");
46
47$action = GETPOST('action', 'aZ09');
48$what = GETPOST('what', 'alpha');
49$export_type = GETPOST('export_type', 'alpha');
50$file = trim(GETPOST('zipfilename_template', 'alpha'));
51$compression = GETPOST('compression', 'aZ09');
52
53$file = dol_sanitizeFileName($file, '_', 1, 1);
54$file = preg_replace('/(\.zip|\.tar|\.tgz|\.gz|\.tar\.gz|\.bz2|\.zst)$/i', '', $file);
55
56$sortfield = GETPOST('sortfield', 'aZ09comma');
57$sortorder = GETPOST('sortorder', 'aZ09comma');
58$page = GETPOSTISSET('pageplusone') ? (GETPOSTINT('pageplusone') - 1) : GETPOSTINT("page");
59if (!$sortorder) {
60 $sortorder = "DESC";
61}
62if (!$sortfield) {
63 $sortfield = "date";
64}
65if ($page < 0) {
66 $page = 0;
67} elseif (empty($page)) {
68 $page = 0;
69}
70$limit = GETPOSTINT('limit') ? GETPOSTINT('limit') : $conf->liste_limit;
71$offset = $limit * $page;
72
73if (!$user->admin) {
75}
76
77$errormsg = '';
78
79
80/*
81 * Actions
82 */
83
84if ($action == 'delete') {
85 $filerelative = dol_sanitizeFileName(GETPOST('urlfile', 'alpha'));
86 $filepath = $conf->admin->dir_output.'/'.$filerelative;
87 $ret = dol_delete_file($filepath, 1);
88 if ($ret) {
89 setEventMessages($langs->trans("FileWasRemoved", $filerelative), null, 'mesgs');
90 } else {
91 setEventMessages($langs->trans("ErrorFailToDeleteFile", $filerelative), null, 'errors');
92 }
93 $action = '';
94}
95
96
97/*
98 * View
99 */
100
101// Increase limit of time. Works only if we are not in safe mode
102$ExecTimeLimit = getDolGlobalInt('MAIN_ADMIN_TOOLS_EXPORT_FILES_EXEC_TIME_LIMIT', 1800);; // 30mn
103if (!empty($ExecTimeLimit)) {
104 $err = error_reporting();
105 error_reporting(0); // Disable all errors
106 //error_reporting(E_ALL);
107 @set_time_limit($ExecTimeLimit); // Need more than 240 on Windows 7/64
108 error_reporting($err);
109}
110
111/* If value has been forced with a php_admin_value, this has no effect. Example of value: '512M' */
112$MemoryLimit = getDolGlobalString('MAIN_MEMORY_LIMIT_ARCHIVE_DATAROOT');
113if (!empty($MemoryLimit)) {
114 @ini_set('memory_limit', $MemoryLimit);
115}
116
117$form = new Form($db);
118$formfile = new FormFile($db);
119
120//$help_url='EN:Backups|FR:Sauvegardes|ES:Copias_de_seguridad';
121//llxHeader('','',$help_url);
122
123//print load_fiche_titre($langs->trans("Backup"),'','title_setup');
124
125
126// Start with empty buffer
127$dump_buffer = '';
128$dump_buffer_len = 0;
129
130// We will send fake headers to avoid browser timeout when buffering
131$time_start = time();
132
133
134$outputdir = $conf->admin->dir_output.'/documents';
135$result = dol_mkdir($outputdir);
136
137$utils = new Utils($db);
138
139if ($export_type == 'externalmodule' && !empty($what)) {
140 $fulldirtocompress = DOL_DOCUMENT_ROOT.'/custom/'.dol_sanitizeFileName($what);
141} else {
142 $fulldirtocompress = DOL_DATA_ROOT;
143}
144$dirtoswitch = dirname($fulldirtocompress);
145$dirtocompress = basename($fulldirtocompress);
146
147if ($compression == 'zip') {
148 $file .= '.zip';
149
150 $excludefiles = '/(\.back|\.old|\.log|\.pdf_preview-.*\.png|[\/\\\]temp[\/\\\]|[\/\\\]admin[\/\\\]documents[\/\\\])/i';
151
152 //var_dump($fulldirtocompress);
153 //var_dump($outputdir."/".$file);exit;
154
155 $rootdirinzip = '';
156 if ($export_type == 'externalmodule' && !empty($what)) {
157 $rootdirinzip = $what;
158
159 global $dolibarr_allow_download_external_modules;
160 if (empty($dolibarr_allow_download_external_modules)) {
161 print 'Download of external modules is not allowed by $dolibarr_allow_download_external_modules in conf.php file';
162 $db->close();
163 exit();
164 }
165 }
166
167 global $errormsg;
168 $ret = dol_compress_dir($fulldirtocompress, $outputdir."/".$file, $compression, $excludefiles, $rootdirinzip); // Can modify $errormsg
169 if ($ret < 0) {
170 if ($ret == -2) {
171 $langs->load("errors");
172 $errormsg = $langs->trans("ErrNoZipEngine");
173 } else {
174 $langs->load("errors");
175 // @phpstan-ignore-next-line The $errormsg can have been modified by the dol_compress_dir function.
176 $errormsg = $langs->trans("ErrorFailedToWriteInDir", $outputdir).($errormsg ? "\n" . $errormsg : "");
177 }
178 }
179} elseif (in_array($compression, array('gz', 'bz', 'zstd'))) {
180 $userlogin = ($user->login ? $user->login : 'unknown');
181
182 $outputfile = $conf->admin->dir_temp.'/'.dol_sanitizeFileName('export_files.'.$userlogin.'.out'); // File used with popen method
183
184 $file .= '.tar';
185
186 // Write the tar into a temp directory outside the documents tree.
187 // If we wrote it directly under $outputdir (= DOL_DATA_ROOT/admin/documents),
188 // tar would notice its own output directory growing as it reads the source
189 // and exit with code 1 / 'file changed as we read it', even though the archive
190 // is complete. The error short-circuited compression at line 194 and left
191 // users with an uncompressed .tar plus a misleading error (#37266).
192 $tmpfile = $conf->admin->dir_temp.'/'.dol_sanitizeFileName($file);
193
194 // We also exclude '/temp/' dir and 'documents/admin/documents'
195 // We make escapement here and call executeCLI without escapement because we don't want to have the '*.log' escaped.
196 $cmd = "tar -cf '".escapeshellcmd($tmpfile)."' --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))."'";
197
198 $result = $utils->executeCLI($cmd, $outputfile, 0, null, 1);
199
200 $retval = $result['error'];
201 if ($result['result'] || !empty($retval)) {
202 $langs->load("errors");
203 dol_syslog("Documents tar retval after exec=".$retval, LOG_ERR);
204 $errormsg = 'Error tar generation return '.$retval;
205 if (file_exists($tmpfile)) {
206 unlink($tmpfile);
207 }
208 } else {
209 $compressedtmpfile = $tmpfile;
210 if ($compression == 'gz') {
211 $cmd = "gzip -f ".$tmpfile;
212 $compressedtmpfile = $tmpfile.'.gz';
213 } elseif ($compression == 'bz') {
214 $cmd = "bzip2 -f ".$tmpfile;
215 $compressedtmpfile = $tmpfile.'.bz2';
216 } elseif ($compression == 'zstd') {
217 $cmd = "zstd -z -9 -q --rm ".$tmpfile;
218 $compressedtmpfile = $tmpfile.'.zst';
219 }
220
221 $result = $utils->executeCLI($cmd, $outputfile);
222
223 $retval = $result['error'];
224 if ($result['result'] || !empty($retval)) {
225 $errormsg = 'Error '.$compression.' generation return '.$retval;
226 if (file_exists($tmpfile)) {
227 unlink($tmpfile);
228 }
229 if (file_exists($compressedtmpfile)) {
230 unlink($compressedtmpfile);
231 }
232 } else {
233 // Move the compressed archive from temp to the final outputdir.
234 $finalfile = $outputdir.'/'.basename($compressedtmpfile);
235 if (!@rename($compressedtmpfile, $finalfile)) {
236 $errormsg = 'Error moving generated archive to '.$outputdir;
237 if (file_exists($compressedtmpfile)) {
238 unlink($compressedtmpfile);
239 }
240 } else {
241 $file = basename($compressedtmpfile);
242 }
243 }
244 }
245} else {
246 $errormsg = 'Bad value for compression method';
247 print $errormsg;
248}
249
250
251// Output export
252
253if ($export_type != 'externalmodule' || empty($what)) {
254 top_httphead();
255
256 if ($errormsg) {
257 setEventMessages($langs->trans("Error")." : ".$errormsg, null, 'errors');
258 } else {
259 setEventMessages($langs->trans("BackupFileSuccessfullyCreated").'.<br>'.$langs->trans("YouCanDownloadBackupFile"), null, 'mesgs');
260 }
261
262 $db->close();
263
264 // Redirect to calling page
265 $returnto = 'dolibarr_export.php';
266
267 header("Location: ".$returnto);
268
269 exit();
270} else {
271 top_httphead('application/zip');
272
273 $zipname = $outputdir."/".$file;
274
275 // Then download the zipped file.
276
277 header('Content-disposition: attachment; filename='.basename($zipname));
278 header('Content-Length: '.filesize($zipname));
279 readfile($zipname);
280
281 dol_delete_file($zipname);
282
283 $db->close();
284
285 exit();
286}
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:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
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.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
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.