Passed
Push — devel-3.0 ( 67d9a6...e0263f )
by Rubén
04:37
created

ConfigGeneralController::downloadLogAction()   A

Complexity

Conditions 3
Paths 16

Size

Total Lines 38
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 25
nc 16
nop 0
dl 0
loc 38
rs 9.52
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\Config\ConfigUtil;
28
use SP\Core\Acl\Acl;
29
use SP\Core\Acl\UnauthorizedPageException;
30
use SP\Core\Context\SessionContext;
31
use SP\Core\Events\Event;
32
use SP\Core\Events\EventMessage;
33
use SP\Http\JsonResponse;
34
use SP\Modules\Web\Controllers\Traits\ConfigTrait;
35
use SP\Services\Config\ConfigBackupService;
36
use SP\Storage\File\FileHandler;
37
38
/**
39
 * Class ConfigGeneral
40
 *
41
 * @package SP\Modules\Web\Controllers
42
 */
43
final class ConfigGeneralController extends SimpleControllerBase
44
{
45
    use ConfigTrait;
46
47
    /**
48
     * saveAction
49
     *
50
     * @throws \SP\Core\Exceptions\SPException
51
     */
52
    public function saveAction()
53
    {
54
        $this->checkSecurityToken($this->previousSk, $this->request);
55
56
        $configData = $this->config->getConfigData();
57
        $eventMessage = EventMessage::factory();
58
59
        // General
60
        $siteLang = $this->request->analyzeString('sitelang');
61
        $siteTheme = $this->request->analyzeString('sitetheme', 'material-blue');
62
        $sessionTimeout = $this->request->analyzeInt('session_timeout', 300);
63
        $httpsEnabled = $this->request->analyzeBool('https_enabled', false);
64
        $debugEnabled = $this->request->analyzeBool('debug_enabled', false);
65
        $maintenanceEnabled = $this->request->analyzeBool('maintenance_enabled', false);
66
        $checkUpdatesEnabled = $this->request->analyzeBool('check_updates_enabled', false);
67
        $checkNoticesEnabled = $this->request->analyzeBool('check_notices_enabled', false);
68
        $encryptSessionEnabled = $this->request->analyzeBool('encrypt_session_enabled', false);
69
70
        $configData->setSiteLang($siteLang);
71
        $configData->setSiteTheme($siteTheme);
72
        $configData->setSessionTimeout($sessionTimeout);
73
        $configData->setHttpsEnabled($httpsEnabled);
74
        $configData->setDebug($debugEnabled);
75
        $configData->setMaintenance($maintenanceEnabled);
76
        $configData->setCheckUpdates($checkUpdatesEnabled);
77
        $configData->setChecknotices($checkNoticesEnabled);
78
        $configData->setEncryptSession($encryptSessionEnabled);
79
80
        // Events
81
        $logEnabled = $this->request->analyzeBool('log_enabled', false);
82
        $syslogEnabled = $this->request->analyzeBool('syslog_enabled', false);
83
        $remoteSyslogEnabled = $this->request->analyzeBool('remotesyslog_enabled', false);
84
        $syslogServer = $this->request->analyzeString('remotesyslog_server');
85
        $syslogPort = $this->request->analyzeInt('remotesyslog_port', 0);
86
87
        $configData->setLogEnabled($logEnabled);
88
        $configData->setLogEvents($this->request->analyzeArray('log_events', function ($items) {
0 ignored issues
show
Bug introduced by
It seems like $this->request->analyzeA...{ /* ... */ }, array()) can also be of type null; however, parameter $logEvents of SP\Config\ConfigData::setLogEvents() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

88
        $configData->setLogEvents(/** @scrutinizer ignore-type */ $this->request->analyzeArray('log_events', function ($items) {
Loading history...
89
            return ConfigUtil::eventsAdapter($items);
90
        }, []));
91
92
        $configData->setSyslogEnabled($syslogEnabled);
93
94
        if ($remoteSyslogEnabled) {
95
            if (!$syslogServer || !$syslogPort) {
96
                return $this->returnJsonResponse(JsonResponse::JSON_ERROR, __u('Faltan parámetros de syslog remoto'));
97
            }
98
99
            $configData->setSyslogRemoteEnabled(true);
100
            $configData->setSyslogServer($syslogServer);
101
            $configData->setSyslogPort($syslogPort);
102
103
            if ($configData->isSyslogRemoteEnabled() === false) {
104
                $eventMessage->addDescription(__u('Syslog remoto habilitado'));
105
            }
106
        } elseif ($remoteSyslogEnabled === false && $configData->isSyslogEnabled()) {
107
            $configData->setSyslogRemoteEnabled(false);
108
109
            $eventMessage->addDescription(__u('Syslog remoto deshabilitado'));
110
        }
111
112
        // Proxy
113
        $proxyEnabled = $this->request->analyzeBool('proxy_enabled', false);
114
        $proxyServer = $this->request->analyzeString('proxy_server');
115
        $proxyPort = $this->request->analyzeInt('proxy_port', 8080);
116
        $proxyUser = $this->request->analyzeString('proxy_user');
117
        $proxyPass = $this->request->analyzeEncrypted('proxy_pass');
118
119
120
        // Valores para Proxy
121
        if ($proxyEnabled && (!$proxyServer || !$proxyPort)) {
122
            return $this->returnJsonResponse(JsonResponse::JSON_ERROR, __u('Faltan parámetros de Proxy'));
123
        }
124
125
        if ($proxyEnabled) {
126
            $configData->setProxyEnabled(true);
127
            $configData->setProxyServer($proxyServer);
128
            $configData->setProxyPort($proxyPort);
129
            $configData->setProxyUser($proxyUser);
130
131
            if ($proxyPass !== '***') {
132
                $configData->setProxyPass($proxyPass);
133
            }
134
135
            if ($configData->isProxyEnabled() === false) {
136
                $eventMessage->addDescription(__u('Proxy habiltado'));
137
            }
138
        } elseif ($proxyEnabled === false && $configData->isProxyEnabled()) {
139
            $configData->setProxyEnabled(false);
140
141
            $eventMessage->addDescription(__u('Proxy deshabilitado'));
142
        }
143
144
        // Autentificación
145
        $authBasicEnabled = $this->request->analyzeBool('authbasic_enabled', false);
146
        $authBasicAutologinEnabled = $this->request->analyzeBool('authbasicautologin_enabled', false);
147
        $authBasicDomain = $this->request->analyzeString('authbasic_domain');
148
        $authSsoDefaultGroup = $this->request->analyzeInt('sso_defaultgroup');
149
        $authSsoDefaultProfile = $this->request->analyzeInt('sso_defaultprofile');
150
151
        // Valores para Autentificación
152
        if ($authBasicEnabled) {
153
            $configData->setAuthBasicEnabled(true);
154
            $configData->setAuthBasicAutoLoginEnabled($authBasicAutologinEnabled);
155
            $configData->setAuthBasicDomain($authBasicDomain);
156
            $configData->setSsoDefaultGroup($authSsoDefaultGroup);
157
            $configData->setSsoDefaultProfile($authSsoDefaultProfile);
158
159
            if ($configData->isAuthBasicEnabled() === false) {
160
                $eventMessage->addDescription(__u('Auth Basic habilitada'));
161
            }
162
        } elseif ($authBasicEnabled === false && $configData->isAuthBasicEnabled()) {
163
            $configData->setAuthBasicEnabled(false);
164
            $configData->setAuthBasicAutoLoginEnabled(false);
165
166
            $eventMessage->addDescription(__u('Auth Basic deshabiltada'));
167
        }
168
169
        return $this->saveConfig($configData, $this->config, function () use ($eventMessage) {
170
            $this->eventDispatcher->notifyEvent('save.config.general', new Event($this, $eventMessage));
171
        });
172
    }
173
174
    /**
175
     * @return bool
176
     * @throws \SP\Core\Exceptions\SPException
177
     */
178
    public function downloadLogAction()
179
    {
180
        $this->checkSecurityToken($this->previousSk, $this->request);
181
182
        if ($this->configData->isDemoEnabled()) {
183
            return __('Ey, esto es una DEMO!!');
0 ignored issues
show
Bug Best Practice introduced by
The expression return __('Ey, esto es una DEMO!!') returns the type string which is incompatible with the documented return type boolean.
Loading history...
184
        }
185
186
        try {
187
            SessionContext::close();
188
189
            $file = new FileHandler(LOG_FILE);
190
            $file->checkFileExists();
191
192
            $this->eventDispatcher->notifyEvent('download.logFile',
193
                new Event($this, EventMessage::factory()
194
                    ->addDescription(__u('Archivo descargado'))
195
                    ->addDetail(__u('Archivo'), str_replace(APP_ROOT, '', $file->getFile())))
196
            );
197
198
            $response = $this->router->response();
199
            $response->header('Cache-Control', 'max-age=60, must-revalidate');
200
            $response->header('Content-length', $file->getFileSize());
201
            $response->header('Content-type', $file->getFileType());
202
            $response->header('Content-Description', ' sysPass file');
203
            $response->header('Content-transfer-encoding', 'chunked');
204
            $response->header('Content-Disposition', 'attachment; filename="' . basename($file->getFile()) . '"');
205
            $response->header('Set-Cookie', 'fileDownload=true; path=/');
206
            $response->send();
207
208
            $file->readChunked();
209
        } catch (\Exception $e) {
210
            processException($e);
211
212
            $this->eventDispatcher->notifyEvent('exception', new Event($e));
213
        }
214
215
        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...
216
    }
217
218
    /**
219
     * @param string $type
220
     *
221
     * @return bool
222
     * @throws \SP\Core\Exceptions\SPException
223
     */
224
    public function downloadConfigBackupAction($type)
225
    {
226
        $this->checkSecurityToken($this->previousSk, $this->request);
227
228
        if ($this->configData->isDemoEnabled()) {
229
            return __('Ey, esto es una DEMO!!');
0 ignored issues
show
Bug Best Practice introduced by
The expression return __('Ey, esto es una DEMO!!') returns the type string which is incompatible with the documented return type boolean.
Loading history...
230
        }
231
232
        try {
233
            $this->eventDispatcher->notifyEvent('download.configBackupFile',
234
                new Event($this, EventMessage::factory()
235
                    ->addDescription(__u('Archivo descargado'))
236
                    ->addDetail(__u('Archivo'), 'config.json'))
237
            );
238
239
            $configBackupService = $this->dic->get(ConfigBackupService::class);
240
241
            switch ($type) {
242
                case 'json':
243
                    $data = ConfigBackupService::configToJson($configBackupService->getBackup());
244
                    break;
245
                default:
246
                    throw new \RuntimeException('Not implemented');
247
            }
248
249
            $response = $this->router->response();
250
            $response->header('Cache-Control', 'max-age=60, must-revalidate');
251
            $response->header('Content-length', strlen($data));
252
            $response->header('Content-type', 'application/json');
253
            $response->header('Content-Description', ' sysPass file');
254
            $response->header('Content-transfer-encoding', 'chunked');
255
            $response->header('Content-Disposition', 'attachment; filename="config.json"');
256
            $response->header('Set-Cookie', 'fileDownload=true; path=/');
257
            $response->header('Content-transfer-encoding', 'binary');
258
            $response->header('Set-Cookie', 'fileDownload=true; path=/');
259
260
            $response->body($data);
261
            $response->send(true);
262
        } catch (\Exception $e) {
263
            processException($e);
264
265
            $this->eventDispatcher->notifyEvent('exception', new Event($e));
266
        }
267
268
        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...
269
    }
270
271
    /**
272
     * @return bool
273
     */
274
    protected function initialize()
275
    {
276
        try {
277
            $this->checks();
278
            $this->checkAccess(Acl::CONFIG_GENERAL);
279
        } catch (UnauthorizedPageException $e) {
280
            $this->eventDispatcher->notifyEvent('exception', new Event($e));
281
282
            return $this->returnJsonResponseException($e);
283
        }
284
    }
285
}