Passed
Push — 3.0 ( 5e1ed3...5a5495 )
by Rubén
04:22
created

UpgradeConfigService   A

Complexity

Total Complexity 25

Size/Duplication

Total Lines 277
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 138
dl 0
loc 277
rs 10
c 0
b 0
f 0
wmc 25

8 Methods

Rating   Name   Duplication   Size   Complexity  
B upgradeOldConfigFile() 0 60 10
A applyUpgrade() 0 9 3
A getConfigParams() 0 55 1
A upgrade_200_17011202() 0 11 1
A upgrade_300_18111001() 0 41 5
A needsUpgrade() 0 3 1
A upgrade() 0 14 3
A initialize() 0 3 1
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\Services\Upgrade;
26
27
use SP\Config\ConfigData;
28
use SP\Core\Events\Event;
29
use SP\Core\Events\EventMessage;
30
use SP\Core\MimeTypes;
31
use SP\Providers\Log\FileLogHandler;
32
use SP\Services\Service;
33
use SP\Util\VersionUtil;
34
35
/**
36
 * Class UpgradeService
37
 *
38
 * @package SP\Services\Upgrade
39
 */
40
final class UpgradeConfigService extends Service implements UpgradeInterface
41
{
42
    /**
43
     * @var array Versiones actualizables
44
     */
45
    const UPGRADES = ['112.4', '130.16020501', '200.17011202', '300.18111001'];
46
    /**
47
     * @var ConfigData
48
     */
49
    protected $configData;
50
51
    /**
52
     * @param $version
53
     *
54
     * @return bool
55
     */
56
    public static function needsUpgrade($version)
57
    {
58
        return VersionUtil::checkVersion($version, self::UPGRADES);
59
    }
60
61
    /**
62
     * Actualizar el archivo de configuración a formato XML
63
     *
64
     * @param $version
65
     *
66
     * @throws UpgradeException
67
     */
68
    public function upgradeOldConfigFile($version)
69
    {
70
        $configData = $this->config->getConfigData();
71
72
        $message = EventMessage::factory()->addDescription(__u('Update Configuration'));
73
74
        $this->eventDispatcher->notifyEvent('upgrade.config.old.start', new Event($this, $message));
75
76
        // Include the file, save the data from $CONFIG
77
        include OLD_CONFIG_FILE;
78
79
        $message = EventMessage::factory();
80
81
        if (isset($CONFIG) && is_array($CONFIG)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $CONFIG seems to never exist and therefore isset should always be false.
Loading history...
82
            $paramMapper = function ($mapFrom, $mapTo) use ($CONFIG, $message, $configData) {
83
                if (isset($CONFIG[$mapFrom])) {
84
                    $message->addDetail(__u('Parameter'), $mapFrom);
85
                    $configData->{$mapTo}($CONFIG[$mapFrom]);
86
                }
87
            };
88
89
            foreach (self::getConfigParams() as $mapTo => $mapFrom) {
90
                if (method_exists($configData, $mapTo)) {
91
                    if (is_array($mapFrom)) {
92
                        /** @var array $mapFrom */
93
                        foreach ($mapFrom as $param) {
94
                            $paramMapper($mapFrom, $param);
95
                        }
96
                    } else {
97
                        if (isset($CONFIG[$mapFrom])) {
98
                            $paramMapper($mapFrom, $mapTo);
99
                        }
100
                    }
101
                }
102
            }
103
        }
104
105
        $oldFile = OLD_CONFIG_FILE . '.old.' . time();
106
107
        try {
108
            $configData->setSiteTheme('material-blue');
109
            $configData->setConfigVersion($version);
110
111
            $this->config->saveConfig($configData, false);
112
113
            rename(OLD_CONFIG_FILE, $oldFile);
114
115
            $message->addDetail(__u('Version'), $version);
116
117
            $this->eventDispatcher->notifyEvent('upgrade.config.old.end', new Event($this, $message));
118
        } catch (\Exception $e) {
119
            processException($e);
120
121
            $this->eventDispatcher->notifyEvent('exception',
122
                new Event($this, EventMessage::factory()
123
                    ->addDescription(__u('Error while updating the configuration'))
124
                    ->addDetail(__u('File'), $oldFile))
125
            );
126
127
            throw new UpgradeException(__u('Error while updating the configuration'));
128
        }
129
    }
130
131
    /**
132
     * Devuelve array de métodos y parámetros de configuración
133
     *
134
     * @return array
135
     */
136
    private static function getConfigParams()
137
    {
138
        return [
139
            'setAccountCount' => 'account_count',
140
            'setAccountLink' => 'account_link',
141
            'setCheckUpdates' => 'checkupdates',
142
            'setCheckNotices' => 'checknotices',
143
            'setDbHost' => 'dbhost',
144
            'setDbName' => 'dbname',
145
            'setDbPass' => 'dbpass',
146
            'setDbUser' => 'dbuser',
147
            'setDebug' => 'debug',
148
            'setDemoEnabled' => 'demo_enabled',
149
            'setGlobalSearch' => 'globalsearch',
150
            'setInstalled' => 'installed',
151
            'setMaintenance' => 'maintenance',
152
            'setPasswordSalt' => 'passwordsalt',
153
            'setSessionTimeout' => 'session_timeout',
154
            'setSiteLang' => 'sitelang',
155
            'setConfigVersion' => 'version',
156
            'setConfigHash' => 'config_hash',
157
            'setProxyEnabled' => 'proxy_enabled',
158
            'setProxyPass' => 'proxy_pass',
159
            'setProxyPort' => 'proxy_port',
160
            'setProxyServer' => 'proxy_server',
161
            'setProxyUser' => 'proxy_user',
162
            'setResultsAsCards' => 'resultsascards',
163
            'setSiteTheme' => 'sitetheme',
164
            'setAccountPassToImage' => 'account_passtoimage',
165
            'setFilesAllowedExts' => ['allowed_exts', 'files_allowed_exts'],
166
            'setFilesAllowedSize' => ['allowed_size', 'files_allowed_size'],
167
            'setFilesEnabled' => ['filesenabled', 'files_enabled'],
168
            'setLdapBase' => ['ldapbase', 'ldap_base'],
169
            'setLdapBindPass' => ['ldapbindpass', 'ldap_bindpass'],
170
            'setLdapBindUser' => ['ldapbinduser', 'ldap_binduser'],
171
            'setLdapEnabled' => ['ldapenabled', 'ldap_enabled'],
172
            'setLdapGroup' => ['ldapgroup', 'ldap_group'],
173
            'setLdapServer' => ['ldapserver', 'ldap_server'],
174
            'setLdapAds' => 'ldap_ads',
175
            'setLdapDefaultGroup' => 'ldap_defaultgroup',
176
            'setLdapDefaultProfile' => 'ldap_defaultprofile',
177
            'setLogEnabled' => ['logenabled', 'log_enabled'],
178
            'setMailEnabled' => ['mailenabled', 'mail_enabled'],
179
            'setMailFrom' => ['mailfrom', 'mail_from'],
180
            'setMailPass' => ['mailpass', 'mail_pass'],
181
            'setMailPort' => ['mailport', 'mail_port'],
182
            'setMailRequestsEnabled' => ['mailrequestsenabled', 'mail_requestsenabled'],
183
            'setMailAuthenabled' => 'mail_authenabled',
184
            'setMailSecurity' => ['mailsecurity', 'mail_security'],
185
            'setMailServer' => ['mailserver', 'mail_server'],
186
            'setMailUser' => ['mailuser', 'mail_user'],
187
            'setWikiEnabled' => ['wikienabled', 'wiki_enabled'],
188
            'setWikiFilter' => ['wikifilter', 'wiki_filter'],
189
            'setWikiPageUrl' => ['wikipageurl' . 'wiki_pageurl'],
190
            'setWikiSearchUrl' => ['wikisearchurl', 'wiki_searchurl']
191
        ];
192
    }
193
194
    /**
195
     * Migrar valores de configuración.
196
     *
197
     * @param            $version
198
     * @param ConfigData $configData
199
     *
200
     * @throws \DI\DependencyException
201
     * @throws \DI\NotFoundException
202
     * @throws \SP\Storage\File\FileException
203
     */
204
    public function upgrade($version, ConfigData $configData)
205
    {
206
        $this->configData = $configData;
207
208
        $message = EventMessage::factory()->addDescription(__u('Update Configuration'));
209
        $this->eventDispatcher->notifyEvent('upgrade.config.start', new Event($this, $message));
210
211
        foreach (self::UPGRADES as $upgradeVersion) {
212
            if (VersionUtil::checkVersion($version, $upgradeVersion)) {
213
                $this->applyUpgrade($upgradeVersion);
214
            }
215
        }
216
217
        $this->eventDispatcher->notifyEvent('upgrade.config.end', new Event($this, $message));
218
    }
219
220
    /**
221
     * @param $version
222
     *
223
     * @throws \DI\DependencyException
224
     * @throws \DI\NotFoundException
225
     * @throws \SP\Storage\File\FileException
226
     */
227
    private function applyUpgrade($version)
228
    {
229
        switch ($version) {
230
            case '200.17011202':
231
                $this->upgrade_200_17011202($version);
232
                break;
233
            case '300.18111001':
234
                $this->upgrade_300_18111001($version);
235
                break;
236
        }
237
    }
238
239
    /**
240
     * @param $version
241
     *
242
     * @throws \DI\DependencyException
243
     * @throws \DI\NotFoundException
244
     * @throws \SP\Storage\File\FileException
245
     */
246
    private function upgrade_200_17011202($version)
247
    {
248
        $this->configData->setSiteTheme('material-blue');
249
        $this->configData->setConfigVersion($version);
250
251
        $this->config->saveConfig($this->configData, false);
252
253
        $this->eventDispatcher->notifyEvent('upgrade.config.process',
254
            new Event($this, EventMessage::factory()
255
                ->addDescription(__u('Update Configuration'))
256
                ->addDetail(__u('Version'), $version))
257
        );
258
    }
259
260
    /**
261
     * @param $version
262
     *
263
     * @throws \DI\DependencyException
264
     * @throws \DI\NotFoundException
265
     * @throws \SP\Storage\File\FileException
266
     */
267
    private function upgrade_300_18111001($version)
268
    {
269
        $extensions = array_map('strtolower', $this->configData->getFilesAllowedExts());
270
        $mimeTypes = $this->dic->get(MimeTypes::class)->getMimeTypes();
271
        $configMimeTypes = [];
272
273
        foreach ($extensions as $extension) {
274
            $exists = false;
275
276
            foreach ($mimeTypes as $mimeType) {
277
                if (strtolower($mimeType['extension']) === $extension) {
278
                    $configMimeTypes[] = $mimeType['type'];
279
                    $exists = true;
280
281
                    $this->eventDispatcher->notifyEvent('upgrade.config.process',
282
                        new Event($this, EventMessage::factory()
283
                            ->addDescription(__u('MIME type set for this extension'))
284
                            ->addDetail(__u('MIME type'), $mimeType['type'])
285
                            ->addDetail(__u('Extension'), $extension))
286
                    );
287
                }
288
            }
289
290
            if (!$exists) {
291
                $this->eventDispatcher->notifyEvent('upgrade.config.process',
292
                    new Event($this, EventMessage::factory()
293
                        ->addDescription(__u('MIME type not found for this extension'))
294
                        ->addDetail(__u('Extension'), $extension))
295
                );
296
            }
297
        }
298
299
        $this->configData->setFilesAllowedMime($configMimeTypes);
300
        $this->configData->setConfigVersion($version);
301
302
        $this->config->saveConfig($this->configData, false);
303
304
        $this->eventDispatcher->notifyEvent('upgrade.config.process',
305
            new Event($this, EventMessage::factory()
306
                ->addDescription(__u('Update Configuration'))
307
                ->addDetail(__u('Version'), $version))
308
        );
309
    }
310
311
    /**
312
     * initialize
313
     */
314
    protected function initialize()
315
    {
316
        $this->eventDispatcher->attach($this->dic->get(FileLogHandler::class));
317
    }
318
}