Passed
Push — devel-3.0 ( 40e719...463a23 )
by Rubén
03:27
created

ConfigBackupController::downloadBackupAppAction()   A

Complexity

Conditions 2
Paths 16

Size

Total Lines 36
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 24
nc 16
nop 0
dl 0
loc 36
rs 9.536
c 0
b 0
f 0
1
<?php
2
/**
3
 * sysPass
4
 *
5
 * @author    nuxsmin
6
 * @link      https://syspass.org
7
 * @copyright 2012-2018, Rubén Domínguez nuxsmin@$syspass.org
8
 *
9
 * This file is part of sysPass.
10
 *
11
 * sysPass is free software: you can redistribute it and/or modify
12
 * it under the terms of the GNU General Public License as published by
13
 * the Free Software Foundation, either version 3 of the License, or
14
 * (at your option) any later version.
15
 *
16
 * sysPass is distributed in the hope that it will be useful,
17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19
 * GNU General Public License for more details.
20
 *
21
 * You should have received a copy of the GNU General Public License
22
 *  along with sysPass.  If not, see <http://www.gnu.org/licenses/>.
23
 */
24
25
namespace SP\Modules\Web\Controllers;
26
27
use SP\Core\Acl\Acl;
28
use SP\Core\Acl\UnauthorizedPageException;
29
use SP\Core\Context\SessionContext;
30
use SP\Core\Events\Event;
31
use SP\Core\Events\EventMessage;
32
use SP\Http\JsonResponse;
33
use SP\Modules\Web\Controllers\Traits\ConfigTrait;
34
use SP\Services\Backup\FileBackupService;
35
use SP\Services\Export\XmlExportService;
36
use SP\Services\Export\XmlVerifyService;
37
use SP\Storage\File\FileHandler;
38
39
/**
40
 * Class ConfigBackupController
41
 *
42
 * @package SP\Modules\Web\Controllers
43
 */
44
final class ConfigBackupController extends SimpleControllerBase
45
{
46
    use ConfigTrait;
47
48
    /**
49
     * @return bool
50
     * @throws \SP\Core\Exceptions\SPException
51
     */
52
    public function fileBackupAction()
53
    {
54
        $this->checkSecurityToken($this->previousSk, $this->request);
55
56
        if ($this->config->getConfigData()->isDemoEnabled()) {
57
            return $this->returnJsonResponse(JsonResponse::JSON_WARNING, __u('Ey, esto es una DEMO!!'));
58
        }
59
60
        try {
61
            SessionContext::close();
62
63
            $this->dic->get(FileBackupService::class)
64
                ->doBackup(BACKUP_PATH);
65
66
            $this->eventDispatcher->notifyEvent('run.backup.end',
67
                new Event($this, EventMessage::factory()
68
                    ->addDescription(__u('Copia de la aplicación y base de datos realizada correctamente')))
69
            );
70
71
            return $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Proceso de backup finalizado'));
72
        } catch (\Exception $e) {
73
            processException($e);
74
75
            $this->eventDispatcher->notifyEvent('exception', new Event($e));
76
77
            return $this->returnJsonResponseException($e);
78
        }
79
    }
80
81
    /**
82
     * @return bool
83
     */
84
    public function xmlExportAction()
85
    {
86
        $exportPassword = $this->request->analyzeEncrypted('exportPwd');
87
        $exportPasswordR = $this->request->analyzeEncrypted('exportPwdR');
88
89
        if (!empty($exportPassword) && $exportPassword !== $exportPasswordR) {
90
            return $this->returnJsonResponse(JsonResponse::JSON_ERROR, __u('Las claves no coinciden'));
91
        }
92
93
        try {
94
            $this->eventDispatcher->notifyEvent('run.export.start',
95
                new Event($this, EventMessage::factory()
96
                    ->addDescription(__u('Exportación de sysPass en XML')))
97
            );
98
99
            SessionContext::close();
100
101
            $export = $this->dic->get(XmlExportService::class);
102
            $export->doExport(BACKUP_PATH, $exportPassword);
103
104
            $this->eventDispatcher->notifyEvent('run.export.end',
105
                new Event($this, EventMessage::factory()
106
                    ->addDescription(__u('Proceso de exportación finalizado')))
107
            );
108
109
            $verify = $this->dic->get(XmlVerifyService::class);
110
111
            if ($export->isEncrypted()) {
112
                $verifyResult = $verify->verifyEncrypted($export->getExportFile(), $exportPassword);
113
            } else {
114
                $verifyResult = $verify->verify($export->getExportFile());
115
            }
116
117
            $nodes = $verifyResult->getNodes();
118
119
            $this->eventDispatcher->notifyEvent('run.export.verify',
120
                new Event($this, EventMessage::factory()
121
                    ->addDescription(__u('Verificación de datos exportados finalizada'))
122
                    ->addDetail(__u('Versión'), $verifyResult->getVersion())
123
                    ->addDetail(__u('Encriptado'), $verifyResult->isEncrypted() ? __u('Sí') : __u('No'))
124
                    ->addDetail(__u('Cuentas'), $nodes['Account'])
125
                    ->addDetail(__u('Clientes'), $nodes['Client'])
126
                    ->addDetail(__u('Categorías'), $nodes['Category'])
127
                    ->addDetail(__u('Etiquetas'), $nodes['Tag'])
128
                )
129
            );
130
131
            // Create the XML archive after verifying the export integrity
132
            $export->createArchive();
133
134
            return $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Proceso de exportación finalizado'));
135
        } catch (\Exception $e) {
136
            processException($e);
137
138
            $this->eventDispatcher->notifyEvent('exception', new Event($e));
139
140
            return $this->returnJsonResponseException($e);
141
        }
142
    }
143
144
    /**
145
     * @return bool
146
     * @throws \SP\Core\Exceptions\SPException
147
     */
148
    public function downloadExportAction()
149
    {
150
        $this->checkSecurityToken($this->previousSk, $this->request);
151
152
        try {
153
            SessionContext::close();
154
155
            $filePath = XmlExportService::getExportFilename(BACKUP_PATH, $this->configData->getExportHash(), true);
156
157
            $file = new FileHandler($filePath);
158
            $file->checkFileExists();
159
160
            $this->eventDispatcher->notifyEvent('download.exportFile',
161
                new Event($this, EventMessage::factory()
162
                    ->addDescription(__u('Archivo descargado'))
163
                    ->addDetail(__u('Archivo'), $file->getFile()))
164
            );
165
166
            $response = $this->router->response();
167
            $response->header('Cache-Control', 'max-age=60, must-revalidate');
168
            $response->header('Content-length', $file->getFileSize());
169
            $response->header('Content-type', $file->getFileType());
170
            $response->header('Content-Description', ' sysPass file');
171
            $response->header('Content-transfer-encoding', 'chunked');
172
            $response->header('Content-Disposition', 'attachment; filename="' . basename($file->getFile()) . '"');
173
            $response->header('Set-Cookie', 'fileDownload=true; path=/');
174
            $response->send();
175
176
            $file->readChunked();
177
        } catch (\Exception $e) {
178
            processException($e);
179
180
            $this->eventDispatcher->notifyEvent('exception', new Event($e));
181
        }
182
183
        return '';
0 ignored issues
show
Bug Best Practice introduced by
The expression return '' returns the type string which is incompatible with the documented return type boolean.
Loading history...
184
    }
185
186
    /**
187
     * @return bool
188
     * @throws \SP\Core\Exceptions\SPException
189
     */
190
    public function downloadBackupAppAction()
191
    {
192
        $this->checkSecurityToken($this->previousSk, $this->request);
193
194
        try {
195
            SessionContext::close();
196
197
            $filePath = FileBackupService::getAppBackupFilename(BACKUP_PATH, $this->configData->getBackupHash(), true);
198
199
            $file = new FileHandler($filePath);
200
            $file->checkFileExists();
201
202
            $this->eventDispatcher->notifyEvent('download.backupAppFile',
203
                new Event($this, EventMessage::factory()
204
                    ->addDescription(__u('Archivo descargado'))
205
                    ->addDetail(__u('Archivo'), $file->getFile()))
206
            );
207
208
            $response = $this->router->response();
209
            $response->header('Cache-Control', 'max-age=60, must-revalidate');
210
            $response->header('Content-length', $file->getFileSize());
211
            $response->header('Content-type', $file->getFileType());
212
            $response->header('Content-Description', ' sysPass file');
213
            $response->header('Content-transfer-encoding', 'chunked');
214
            $response->header('Content-Disposition', 'attachment; filename="' . basename($file->getFile()) . '"');
215
            $response->header('Set-Cookie', 'fileDownload=true; path=/');
216
            $response->send();
217
218
            $file->readChunked();
219
        } catch (\Exception $e) {
220
            processException($e);
221
222
            $this->eventDispatcher->notifyEvent('exception', new Event($e));
223
        }
224
225
        return '';
0 ignored issues
show
Bug Best Practice introduced by
The expression return '' returns the type string which is incompatible with the documented return type boolean.
Loading history...
226
    }
227
228
    /**
229
     * @return bool
230
     * @throws \SP\Core\Exceptions\SPException
231
     */
232
    public function downloadBackupDbAction()
233
    {
234
        $this->checkSecurityToken($this->previousSk, $this->request);
235
236
        try {
237
            SessionContext::close();
238
239
            $filePath = FileBackupService::getDbBackupFilename(BACKUP_PATH, $this->configData->getBackupHash(), true);
240
241
            $file = new FileHandler($filePath);
242
            $file->checkFileExists();
243
244
            $this->eventDispatcher->notifyEvent('download.backupDbFile',
245
                new Event($this, EventMessage::factory()
246
                    ->addDescription(__u('Archivo descargado'))
247
                    ->addDetail(__u('Archivo'), $file->getFile()))
248
            );
249
250
            $response = $this->router->response();
251
            $response->header('Cache-Control', 'max-age=60, must-revalidate');
252
            $response->header('Content-length', $file->getFileSize());
253
            $response->header('Content-type', $file->getFileType());
254
            $response->header('Content-Description', ' sysPass file');
255
            $response->header('Content-transfer-encoding', 'chunked');
256
            $response->header('Content-Disposition', 'attachment; filename="' . basename($file->getFile()) . '"');
257
            $response->header('Set-Cookie', 'fileDownload=true; path=/');
258
            $response->send();
259
260
            $file->readChunked();
261
        } catch (\Exception $e) {
262
            processException($e);
263
264
            $this->eventDispatcher->notifyEvent('exception', new Event($e));
265
        }
266
267
        return '';
0 ignored issues
show
Bug Best Practice introduced by
The expression return '' returns the type string which is incompatible with the documented return type boolean.
Loading history...
268
    }
269
270
    /**
271
     * initialize
272
     */
273
    protected function initialize()
274
    {
275
        try {
276
            $this->checks();
277
            $this->checkAccess(Acl::CONFIG_BACKUP);
278
        } catch (UnauthorizedPageException $e) {
279
            $this->eventDispatcher->notifyEvent('exception', new Event($e));
280
281
            $this->returnJsonResponseException($e);
282
        }
283
    }
284
}