Passed
Push — 3.0 ( d2a6b7...b247bd )
by Rubén
04:14
created

UpgradeConfigService::initialize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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