Completed
Push — master ( c0ebdc...d32ac4 )
by Craig
07:05
created

AjaxUpgradeController::from140to141()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 22
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 0
dl 0
loc 22
rs 9.2
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the Zikula package.
5
 *
6
 * Copyright Zikula Foundation - http://zikula.org/
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Zikula\Bundle\CoreInstallerBundle\Controller;
13
14
use RandomLib\Factory;
15
use Symfony\Component\DependencyInjection\ContainerInterface;
16
use Symfony\Component\HttpFoundation\JsonResponse;
17
use Symfony\Component\HttpFoundation\Request;
18
use Symfony\Component\Yaml\Yaml;
19
use Zikula\Bundle\CoreBundle\YamlDumper;
20
use Zikula\ExtensionsModule\Api\VariableApi;
21
use Zikula\ThemeModule\Entity\Repository\ThemeEntityRepository;
22
23
/**
24
 * Class AjaxUpgradeController
25
 */
26
class AjaxUpgradeController extends AbstractController
27
{
28
    /**
29
     * @var YamlDumper
30
     */
31
    private $yamlManager;
32
33
    /**
34
     * @var string the currently installed core version
35
     */
36
    private $currentVersion;
37
38
    /**
39
     * AjaxUpgradeController constructor.
40
     * @param ContainerInterface $container
41
     */
42
    public function __construct(ContainerInterface $container)
43
    {
44
        parent::__construct($container);
45
        $originalParameters = Yaml::parse(file_get_contents($this->container->get('kernel')->getRootDir() .'/config/parameters.yml'));
46
        $this->yamlManager = new YamlDumper($this->container->get('kernel')->getRootDir() .'/config', 'custom_parameters.yml');
47
        // load and set new default values from the original parameters.yml file into the custom_parameters.yml file.
48
        $this->yamlManager->setParameters(array_merge($originalParameters['parameters'], $this->yamlManager->getParameters()));
49
        $this->currentVersion = $this->container->getParameter(\ZikulaKernel::CORE_INSTALLED_VERSION_PARAM);
50
    }
51
52
    public function ajaxAction(Request $request)
53
    {
54
        $stage = $request->request->get('stage');
55
        $this->container->setParameter('upgrading', true);
56
        $status = $this->executeStage($stage);
57
        $response = ['status' => (bool) $status];
58
        if (is_array($status)) {
59
            $response['results'] = $status;
60
        }
61
62
        return new JsonResponse($response);
63
    }
64
65
    public function commandLineAction($stage)
66
    {
67
        $this->container->setParameter('upgrading', true);
68
69
        return $this->executeStage($stage);
70
    }
71
72
    private function executeStage($stageName)
73
    {
74
        switch ($stageName) {
75
            case "loginadmin":
76
                $params = $this->decodeParameters($this->yamlManager->getParameters());
77
78
                return $this->loginAdmin($params);
79
            case "upgrademodules":
80
                $result = $this->upgradeModules();
81
                if (count($result) === 0) {
82
                    return true;
83
                }
84
85
                return $result;
86
            case "installroutes":
87
                if (version_compare(\ZikulaKernel::VERSION, '1.4.0', '>') && version_compare($this->currentVersion, '1.4.0', '>=')) {
88
                    // this stage is not necessary to upgrade from 1.4.0 -> 1.4.x
89
                    return true;
90
                }
91
                $this->installModule('ZikulaRoutesModule');
92
                $this->reSyncAndActivateModules();
93
                $this->setModuleCategory('ZikulaRoutesModule', $this->translator->__('System'));
94
95
                return true;
96
            case "regenthemes":
97
                return $this->regenerateThemes();
98
            case "from140to141":
99
                return $this->from140to141();
100
            case "from141to142":
101
                return $this->from141to142();
102
            case "from142to143":
103
                return $this->from142to143();
104
            case "from143to144":
105
                return $this->from143to144();
106
            case "from144to145":
107
                return $this->from144to145();
108
            case "from145to146":
109
                return $this->from145to146();
110
            case "finalizeparameters":
111
                return $this->finalizeParameters();
112
            case "clearcaches":
113
                return $this->clearCaches();
114
        }
115
116
        return true;
117
    }
118
119
    /**
120
     * Attempt to upgrade ALL the core modules. Some will need it, some will not.
121
     * Modules that do not need upgrading return TRUE as a result of the upgrade anyway.
122
     * @return array
123
     */
124
    private function upgradeModules()
125
    {
126
        $coreModulesInPriorityUpgradeOrder = [
127
            'ZikulaExtensionsModule',
128
            'ZikulaUsersModule',
129
            'ZikulaZAuthModule',
130
            'ZikulaGroupsModule',
131
            'ZikulaPermissionsModule',
132
            'ZikulaAdminModule',
133
            'ZikulaBlocksModule',
134
            'ZikulaThemeModule',
135
            'ZikulaSettingsModule',
136
            'ZikulaCategoriesModule',
137
            'ZikulaSecurityCenterModule',
138
            'ZikulaRoutesModule',
139
            'ZikulaMailerModule',
140
            'ZikulaSearchModule',
141
            'ZikulaMenuModule',
142
        ];
143
        $result = [];
144
        foreach ($coreModulesInPriorityUpgradeOrder as $moduleName) {
145
            $extensionEntity = $this->container->get('zikula_extensions_module.extension_repository')->get($moduleName);
146
            if (isset($extensionEntity)) {
147
                $result[$moduleName] = $this->container->get('zikula_extensions_module.extension_helper')->upgrade($extensionEntity);
148
            }
149
        }
150
151
        return $result;
152
    }
153
154
    private function regenerateThemes()
155
    {
156
        // regenerate the themes list
157
        $this->container->get('zikula_theme_module.helper.bundle_sync_helper')->regenerate();
158
        // set all themes as active @todo this is probably overkill
159
        $themes = $this->container->get('zikula_theme_module.theme_entity.repository')->findAll();
160
        /** @var \Zikula\ThemeModule\Entity\ThemeEntity $theme */
161
        foreach ($themes as $theme) {
162
            $theme->setState(ThemeEntityRepository::STATE_ACTIVE);
163
        }
164
        $this->container->get('doctrine')->getManager()->flush();
165
166
        return true;
167
    }
168
169
    private function from140to141()
170
    {
171
        if (version_compare($this->currentVersion, '1.4.1', '>=')) {
0 ignored issues
show
Unused Code introduced by
This if statement and the following return statement are superfluous as you return always true.
Loading history...
172
            return true;
173
        }
174
        // perform the following SQL
175
//ALTER TABLE categories_category ADD CONSTRAINT FK_D0B2B0F88304AF18 FOREIGN KEY (cr_uid) REFERENCES users (uid);
176
//ALTER TABLE categories_category ADD CONSTRAINT FK_D0B2B0F8C072C1DD FOREIGN KEY (lu_uid) REFERENCES users (uid);
177
//ALTER TABLE categories_registry ADD CONSTRAINT FK_1B56B4338304AF18 FOREIGN KEY (cr_uid) REFERENCES users (uid);
178
//ALTER TABLE categories_registry ADD CONSTRAINT FK_1B56B433C072C1DD FOREIGN KEY (lu_uid) REFERENCES users (uid);
179
//ALTER TABLE sc_intrusion ADD CONSTRAINT FK_8595CE46539B0606 FOREIGN KEY (uid) REFERENCES users (uid);
180
//DROP INDEX gid_uid ON group_membership;
181
//ALTER TABLE group_membership DROP PRIMARY KEY;
182
//ALTER TABLE group_membership ADD CONSTRAINT FK_5132B337539B0606 FOREIGN KEY (uid) REFERENCES users (uid);
183
//ALTER TABLE group_membership ADD CONSTRAINT FK_5132B3374C397118 FOREIGN KEY (gid) REFERENCES groups (gid);
184
//CREATE INDEX IDX_5132B337539B0606 ON group_membership (uid);
185
//CREATE INDEX IDX_5132B3374C397118 ON group_membership (gid);
186
//ALTER TABLE group_membership ADD PRIMARY KEY (uid, gid);
187
188
        // take whatever additional actions necessary to upgrade from 140 to 141
189
        return true;
190
    }
191
192
    private function from141to142()
193
    {
194
        if (version_compare($this->currentVersion, '1.4.2', '>=')) {
195
            return true;
196
        }
197
        // do some clean up
198
        $request = $this->container->get('request_stack')->getCurrentRequest();
199
        if (isset($request) && $request->hasSession()) {
200
            $request->getSession()->remove('interactive_init');
201
            $request->getSession()->remove('interactive_remove');
202
            $request->getSession()->remove('interactive_upgrade');
203
        }
204
205
        return true;
206
    }
207
208 View Code Duplication
    private function from142to143()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
209
    {
210
        if (version_compare($this->currentVersion, '1.4.3', '>=')) {
211
            return true;
212
        }
213
        $this->installModule('ZikulaZAuthModule');
214
        $this->reSyncAndActivateModules();
215
        $this->setModuleCategory('ZikulaZAuthModule', $this->translator->__('Users'));
216
217
        return true;
218
    }
219
220 View Code Duplication
    private function from143to144()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
221
    {
222
        if (version_compare($this->currentVersion, '1.4.4', '>=')) {
223
            return true;
224
        }
225
        $this->installModule('ZikulaMenuModule');
226
        $this->reSyncAndActivateModules();
227
        $this->setModuleCategory('ZikulaMenuModule', $this->translator->__('Content'));
228
229
        return true;
230
    }
231
232
    private function from144to145()
233
    {
234
        if (version_compare($this->currentVersion, '1.4.5', '>=')) {
0 ignored issues
show
Unused Code introduced by
This if statement and the following return statement are superfluous as you return always true.
Loading history...
235
            return true;
236
        }
237
238
        return true;
239
    }
240
241
    private function from145to146()
242
    {
243
        if (version_compare($this->currentVersion, '1.4.6', '>=')) {
0 ignored issues
show
Unused Code introduced by
This if statement and the following return statement are superfluous as you return always true.
Loading history...
244
            return true;
245
        }
246
247
        return true;
248
    }
249
250
    private function finalizeParameters()
251
    {
252
        $variableApi = $this->container->get('zikula_extensions_module.api.variable');
253
        // Set the System Identifier as a unique string.
254
        if (!$variableApi->get(VariableApi::CONFIG, 'system_identifier')) {
255
            $variableApi->set(VariableApi::CONFIG, 'system_identifier', str_replace('.', '', uniqid(rand(1000000000, 9999999999), true)));
256
        }
257
258
        // add new configuration parameters
259
        $params = $this->yamlManager->getParameters();
260
        unset($params['username'], $params['password']);
261
        $RandomLibFactory = new Factory();
262
        $generator = $RandomLibFactory->getMediumStrengthGenerator();
263
264
        if (!isset($params['secret']) || ($params['secret'] == 'ThisTokenIsNotSoSecretChangeIt')) {
265
            $params['secret'] = $generator->generateString(50);
266
        }
267
        if (!isset($params['url_secret'])) {
268
            $params['url_secret'] = $generator->generateString(10);
269
        }
270
        // Configure the Request Context
271
        // see http://symfony.com/doc/current/cookbook/console/sending_emails.html#configuring-the-request-context-globally
272
        $params['router.request_context.host'] = isset($params['router.request_context.host']) ? $params['router.request_context.host'] : $this->container->get('request')->getHost();
273
        $params['router.request_context.scheme'] = isset($params['router.request_context.scheme']) ? $params['router.request_context.scheme'] : 'http';
274
        $params['router.request_context.base_url'] = isset($params['router.request_context.base_url']) ? $params['router.request_context.base_url'] : $this->container->get('request')->getBasePath();
275
276
        // set currently installed version into parameters
277
        $params[\ZikulaKernel::CORE_INSTALLED_VERSION_PARAM] = \ZikulaKernel::VERSION;
278
279
        // disable asset combination on upgrades
280
        $params['zikula_asset_manager.combine'] = false;
281
282
        $this->yamlManager->setParameters($params);
283
284
        // store the recent version in a config var for later usage. This enables us to determine the version we are upgrading from
285
        $variableApi->set(VariableApi::CONFIG, 'Version_Num', \ZikulaKernel::VERSION);
286
        $variableApi->set(VariableApi::CONFIG, 'Version_Sub', \ZikulaKernel::VERSION_SUB);
287
288
        // set the 'start' page information to empty to avoid missing module errors.
289
        $variableApi->set(VariableApi::CONFIG, 'startpage', '');
290
        $variableApi->set(VariableApi::CONFIG, 'starttype', '');
291
        $variableApi->set(VariableApi::CONFIG, 'startfunc', '');
292
        $variableApi->set(VariableApi::CONFIG, 'startargs', '');
293
294
        return true;
295
    }
296
297
    private function clearCaches()
298
    {
299
        // clear cache with zikula's method
300
        $cacheClearer = $this->container->get('zikula.cache_clearer');
301
        $cacheClearer->clear('symfony');
302
        // use full symfony cache_clearer not zikula's to clear entire cache and set for warmup
303
        // console commands always run in `dev` mode but site should be `prod` mode. clear both for good measure.
304
        $this->container->get('cache_clearer')->clear('dev');
305
        $this->container->get('cache_clearer')->clear('prod');
306
        if (in_array($this->container->getParameter('env'), ['dev', 'prod'])) {
307
            // this is just in case anyone ever creates a mode that isn't dev|prod
308
            $this->container->get('cache_clearer')->clear($this->container->getParameter('env'));
309
        }
310
311
        // finally remove upgrading flag in parameters
312
        $this->yamlManager->delParameter('upgrading');
313
314
        return true;
315
    }
316
}
317