UpgradeController.php 51.7 KB
Newer Older
1
<?php
2

3
declare(strict_types=1);
4
5
6
7
8
9
10
11
12
13
14
15
16
17

/*
 * This file is part of the TYPO3 CMS project.
 *
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * The TYPO3 project - inspiring people to share!
 */

18
19
namespace TYPO3\CMS\Install\Controller;

20
21
22
23
24
25
26
use PhpParser\NodeTraverser;
use PhpParser\NodeVisitor\NameResolver;
use PhpParser\ParserFactory;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo;
27
use TYPO3\CMS\Core\Core\Environment;
28
use TYPO3\CMS\Core\Database\ConnectionPool;
29
use TYPO3\CMS\Core\Database\Schema\Exception\StatementException;
30
31
32
33
34
35
use TYPO3\CMS\Core\FormProtection\FormProtectionFactory;
use TYPO3\CMS\Core\FormProtection\InstallToolFormProtection;
use TYPO3\CMS\Core\Http\JsonResponse;
use TYPO3\CMS\Core\Messaging\FlashMessage;
use TYPO3\CMS\Core\Messaging\FlashMessageQueue;
use TYPO3\CMS\Core\Migrations\TcaMigration;
36
use TYPO3\CMS\Core\Package\PackageInterface;
37
use TYPO3\CMS\Core\Package\PackageManager;
38
use TYPO3\CMS\Core\Registry;
39
use TYPO3\CMS\Core\Service\OpcodeCacheService;
40
41
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
use TYPO3\CMS\Core\Utility\GeneralUtility;
42
use TYPO3\CMS\Core\Utility\StringUtility;
43
44
45
46
47
48
49
use TYPO3\CMS\Install\ExtensionScanner\Php\CodeStatistics;
use TYPO3\CMS\Install\ExtensionScanner\Php\GeneratorClassesResolver;
use TYPO3\CMS\Install\ExtensionScanner\Php\Matcher\ArrayDimensionMatcher;
use TYPO3\CMS\Install\ExtensionScanner\Php\Matcher\ArrayGlobalMatcher;
use TYPO3\CMS\Install\ExtensionScanner\Php\Matcher\ClassConstantMatcher;
use TYPO3\CMS\Install\ExtensionScanner\Php\Matcher\ClassNameMatcher;
use TYPO3\CMS\Install\ExtensionScanner\Php\Matcher\ConstantMatcher;
50
use TYPO3\CMS\Install\ExtensionScanner\Php\Matcher\ConstructorArgumentMatcher;
51
52
use TYPO3\CMS\Install\ExtensionScanner\Php\Matcher\FunctionCallMatcher;
use TYPO3\CMS\Install\ExtensionScanner\Php\Matcher\InterfaceMethodChangedMatcher;
53
use TYPO3\CMS\Install\ExtensionScanner\Php\Matcher\MethodAnnotationMatcher;
54
55
56
use TYPO3\CMS\Install\ExtensionScanner\Php\Matcher\MethodArgumentDroppedMatcher;
use TYPO3\CMS\Install\ExtensionScanner\Php\Matcher\MethodArgumentDroppedStaticMatcher;
use TYPO3\CMS\Install\ExtensionScanner\Php\Matcher\MethodArgumentRequiredMatcher;
57
use TYPO3\CMS\Install\ExtensionScanner\Php\Matcher\MethodArgumentRequiredStaticMatcher;
58
59
60
use TYPO3\CMS\Install\ExtensionScanner\Php\Matcher\MethodArgumentUnusedMatcher;
use TYPO3\CMS\Install\ExtensionScanner\Php\Matcher\MethodCallMatcher;
use TYPO3\CMS\Install\ExtensionScanner\Php\Matcher\MethodCallStaticMatcher;
61
use TYPO3\CMS\Install\ExtensionScanner\Php\Matcher\PropertyAnnotationMatcher;
62
use TYPO3\CMS\Install\ExtensionScanner\Php\Matcher\PropertyExistsStaticMatcher;
63
64
65
use TYPO3\CMS\Install\ExtensionScanner\Php\Matcher\PropertyProtectedMatcher;
use TYPO3\CMS\Install\ExtensionScanner\Php\Matcher\PropertyPublicMatcher;
use TYPO3\CMS\Install\ExtensionScanner\Php\MatcherFactory;
66
use TYPO3\CMS\Install\Service\ClearCacheService;
67
68
use TYPO3\CMS\Install\Service\CoreUpdateService;
use TYPO3\CMS\Install\Service\CoreVersionService;
69
use TYPO3\CMS\Install\Service\LateBootService;
70
71
72
73
74
75
use TYPO3\CMS\Install\Service\LoadTcaService;
use TYPO3\CMS\Install\Service\UpgradeWizardsService;
use TYPO3\CMS\Install\UpgradeAnalysis\DocumentationFile;

/**
 * Upgrade controller
76
 * @internal This class is a specific controller implementation and is not considered part of the Public TYPO3 API.
77
78
79
80
81
82
83
84
85
86
87
88
89
 */
class UpgradeController extends AbstractController
{
    /**
     * @var CoreUpdateService
     */
    protected $coreUpdateService;

    /**
     * @var CoreVersionService
     */
    protected $coreVersionService;

90
91
92
93
94
    /**
     * @var UpgradeWizardsService
     */
    private $upgradeWizardsService;

95
96
97
98
99
100
    /**
     * @var PackageManager
     */
    protected $packageManager;

    /**
101
     * @var LateBootService
102
     */
103
104
    private $lateBootService;

105
106
107
108
109
    public function __construct(
        PackageManager $packageManager,
        LateBootService $lateBootService,
        UpgradeWizardsService $upgradeWizardsService
    ) {
110
111
        $this->packageManager = $packageManager;
        $this->lateBootService = $lateBootService;
112
        $this->upgradeWizardsService = $upgradeWizardsService;
113
114
    }

115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
    /**
     * Matcher registry of extension scanner.
     * Node visitors that implement CodeScannerInterface
     *
     * @var array
     */
    protected $matchers = [
        [
            'class' => ArrayDimensionMatcher::class,
            'configurationFile' => 'EXT:install/Configuration/ExtensionScanner/Php/ArrayDimensionMatcher.php',
        ],
        [
            'class' => ArrayGlobalMatcher::class,
            'configurationFile' => 'EXT:install/Configuration/ExtensionScanner/Php/ArrayGlobalMatcher.php',
        ],
        [
            'class' => ClassConstantMatcher::class,
            'configurationFile' => 'EXT:install/Configuration/ExtensionScanner/Php/ClassConstantMatcher.php',
        ],
        [
            'class' => ClassNameMatcher::class,
            'configurationFile' => 'EXT:install/Configuration/ExtensionScanner/Php/ClassNameMatcher.php',
        ],
        [
            'class' => ConstantMatcher::class,
            'configurationFile' => 'EXT:install/Configuration/ExtensionScanner/Php/ConstantMatcher.php',
        ],
142
143
144
145
        [
            'class' => ConstructorArgumentMatcher::class,
            'configurationFile' => 'EXT:install/Configuration/ExtensionScanner/Php/ConstructorArgumentMatcher.php',
        ],
146
147
148
149
        [
            'class' => PropertyAnnotationMatcher::class,
            'configurationFile' => 'EXT:install/Configuration/ExtensionScanner/Php/PropertyAnnotationMatcher.php',
        ],
150
151
152
153
        [
            'class' => MethodAnnotationMatcher::class,
            'configurationFile' => 'EXT:install/Configuration/ExtensionScanner/Php/MethodAnnotationMatcher.php',
        ],
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
        [
            'class' => FunctionCallMatcher::class,
            'configurationFile' => 'EXT:install/Configuration/ExtensionScanner/Php/FunctionCallMatcher.php',
        ],
        [
            'class' => InterfaceMethodChangedMatcher::class,
            'configurationFile' => 'EXT:install/Configuration/ExtensionScanner/Php/InterfaceMethodChangedMatcher.php',
        ],
        [
            'class' => MethodArgumentDroppedMatcher::class,
            'configurationFile' => 'EXT:install/Configuration/ExtensionScanner/Php/MethodArgumentDroppedMatcher.php',
        ],
        [
            'class' => MethodArgumentDroppedStaticMatcher::class,
            'configurationFile' => 'EXT:install/Configuration/ExtensionScanner/Php/MethodArgumentDroppedStaticMatcher.php',
        ],
        [
            'class' => MethodArgumentRequiredMatcher::class,
            'configurationFile' => 'EXT:install/Configuration/ExtensionScanner/Php/MethodArgumentRequiredMatcher.php',
173
174
175
176
        ],
        [
            'class' => MethodArgumentRequiredStaticMatcher::class,
            'configurationFile' => 'EXT:install/Configuration/ExtensionScanner/Php/MethodArgumentRequiredStaticMatcher.php',
177
178
179
180
181
182
183
184
185
186
187
188
189
        ],
        [
            'class' => MethodArgumentUnusedMatcher::class,
            'configurationFile' => 'EXT:install/Configuration/ExtensionScanner/Php/MethodArgumentUnusedMatcher.php',
        ],
        [
            'class' => MethodCallMatcher::class,
            'configurationFile' => 'EXT:install/Configuration/ExtensionScanner/Php/MethodCallMatcher.php',
        ],
        [
            'class' => MethodCallStaticMatcher::class,
            'configurationFile' => 'EXT:install/Configuration/ExtensionScanner/Php/MethodCallStaticMatcher.php',
        ],
190
191
192
193
        [
            'class' => PropertyExistsStaticMatcher::class,
            'configurationFile' => 'EXT:install/Configuration/ExtensionScanner/Php/PropertyExistsStaticMatcher.php'
        ],
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
        [
            'class' => PropertyProtectedMatcher::class,
            'configurationFile' => 'EXT:install/Configuration/ExtensionScanner/Php/PropertyProtectedMatcher.php',
        ],
        [
            'class' => PropertyPublicMatcher::class,
            'configurationFile' => 'EXT:install/Configuration/ExtensionScanner/Php/PropertyPublicMatcher.php',
        ],
    ];

    /**
     * Main "show the cards" view
     *
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     */
    public function cardsAction(ServerRequestInterface $request): ResponseInterface
    {
        $view = $this->initializeStandaloneView($request, 'Upgrade/Cards.html');
213
        $view->assign('extensionFoldersInTypo3conf', (new Finder())->directories()->in(Environment::getExtensionsPath())->depth(0)->count());
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
        return new JsonResponse([
            'success' => true,
            'html' => $view->render(),
        ]);
    }

    /**
     * Activate a new core
     *
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     */
    public function coreUpdateActivateAction(ServerRequestInterface $request): ResponseInterface
    {
        $this->coreUpdateInitialize();
        return new JsonResponse([
            'success' => $this->coreUpdateService->activateVersion($this->coreUpdateGetVersionToHandle($request)),
            'status' => $this->coreUpdateService->getMessages(),
        ]);
    }

    /**
     * Check if core update is possible
     *
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     */
    public function coreUpdateCheckPreConditionsAction(ServerRequestInterface $request): ResponseInterface
    {
        $this->coreUpdateInitialize();
        return new JsonResponse([
            'success' => $this->coreUpdateService->checkPreConditions($this->coreUpdateGetVersionToHandle($request)),
            'status' => $this->coreUpdateService->getMessages(),
        ]);
    }

    /**
     * Download new core
     *
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     */
    public function coreUpdateDownloadAction(ServerRequestInterface $request): ResponseInterface
    {
        $this->coreUpdateInitialize();
        return new JsonResponse([
            'success' => $this->coreUpdateService->downloadVersion($this->coreUpdateGetVersionToHandle($request)),
            'status' => $this->coreUpdateService->getMessages(),
        ]);
    }

Philipp Hamid's avatar
Philipp Hamid committed
265
266
267
    /**
     * Core Update Get Data Action
     *
268
     * @param ServerRequestInterface $request
Philipp Hamid's avatar
Philipp Hamid committed
269
270
271
272
273
     * @return ResponseInterface
     */
    public function coreUpdateGetDataAction(ServerRequestInterface $request): ResponseInterface
    {
        $view = $this->initializeStandaloneView($request, 'Upgrade/CoreUpdate.html');
274
275
        $coreUpdateService = GeneralUtility::makeInstance(CoreUpdateService::class);
        $coreVersionService = GeneralUtility::makeInstance(CoreVersionService::class);
276
277
278
279
280
281
282

        $coreUpdateEnabled = $coreUpdateService->isCoreUpdateEnabled();
        $coreUpdateComposerMode = Environment::isComposerMode();
        $coreUpdateIsReleasedVersion = $coreVersionService->isInstalledVersionAReleasedVersion();
        $coreUpdateIsSymLinkedCore = is_link(Environment::getPublicPath() . '/typo3_src');
        $isUpdatable = !$coreUpdateComposerMode && $coreUpdateEnabled && $coreUpdateIsReleasedVersion && $coreUpdateIsSymLinkedCore;

283
        $view->assignMultiple([
284
285
286
287
288
            'coreIsUpdatable' => $isUpdatable,
            'coreUpdateEnabled' => $coreUpdateEnabled,
            'coreUpdateComposerMode' => $coreUpdateComposerMode,
            'coreUpdateIsReleasedVersion' => $coreUpdateIsReleasedVersion,
            'coreUpdateIsSymLinkedCore' => $coreUpdateIsSymLinkedCore,
289
        ]);
290
291
292
293
294
295
296
297
298
299
300
301
302

        $buttons = [];
        if ($isUpdatable) {
            $buttons[] = [
                'btnClass' => 'btn-warning t3js-coreUpdate-button t3js-coreUpdate-init',
                'name' => 'coreUpdateCheckForUpdate',
                'text' => 'Check for core updates',
                'dataAttributes' => [
                    'action' => 'checkForUpdate',
                ],
            ];
        }

Philipp Hamid's avatar
Philipp Hamid committed
303
304
305
        return new JsonResponse([
            'success' => true,
            'html' => $view->render(),
306
            'buttons' => $buttons,
Philipp Hamid's avatar
Philipp Hamid committed
307
308
309
        ]);
    }

310
311
312
313
314
315
316
    /**
     * Check for new core
     *
     * @return ResponseInterface
     */
    public function coreUpdateIsUpdateAvailableAction(): ResponseInterface
    {
317
        $action = null;
318
319
320
321
322
        $this->coreUpdateInitialize();
        $messageQueue = new FlashMessageQueue('install');
        if ($this->coreVersionService->isInstalledVersionAReleasedVersion()) {
            $isUpdateAvailable = $this->coreVersionService->isYoungerPatchReleaseAvailable();
            $isUpdateSecurityRelevant = $this->coreVersionService->isUpdateSecurityRelevant();
323
            if (!$isUpdateAvailable) {
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
                $messageQueue->enqueue(new FlashMessage(
                    '',
                    'No regular update available',
                    FlashMessage::NOTICE
                ));
            } elseif ($isUpdateAvailable) {
                $newVersion = $this->coreVersionService->getYoungestPatchRelease();
                if ($isUpdateSecurityRelevant) {
                    $messageQueue->enqueue(new FlashMessage(
                        '',
                        'Update to security relevant released version ' . $newVersion . ' is available!',
                        FlashMessage::WARNING
                    ));
                    $action = ['title' => 'Update now', 'action' => 'updateRegular'];
                } else {
                    $messageQueue->enqueue(new FlashMessage(
                        '',
                        'Update to regular released version ' . $newVersion . ' is available!',
                        FlashMessage::INFO
                    ));
                    $action = ['title' => 'Update now', 'action' => 'updateRegular'];
                }
            }
        } else {
            $messageQueue->enqueue(new FlashMessage(
                '',
                'Current version is a development version and can not be updated',
                FlashMessage::WARNING
            ));
        }
        $responseData = [
            'success' => true,
            'status' => $messageQueue,
        ];
        if (isset($action)) {
            $responseData['action'] = $action;
        }
        return new JsonResponse($responseData);
    }

    /**
     * Move core to new location
     *
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     */
    public function coreUpdateMoveAction(ServerRequestInterface $request): ResponseInterface
    {
        $this->coreUpdateInitialize();
        return new JsonResponse([
            'success' => $this->coreUpdateService->moveVersion($this->coreUpdateGetVersionToHandle($request)),
            'status' => $this->coreUpdateService->getMessages(),
        ]);
    }

    /**
     * Unpack a downloaded core
     *
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     */
    public function coreUpdateUnpackAction(ServerRequestInterface $request): ResponseInterface
    {
        $this->coreUpdateInitialize();
        return new JsonResponse([
            'success' => $this->coreUpdateService->unpackVersion($this->coreUpdateGetVersionToHandle($request)),
            'status' => $this->coreUpdateService->getMessages(),
        ]);
    }

    /**
     * Verify downloaded core checksum
     *
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     */
    public function coreUpdateVerifyChecksumAction(ServerRequestInterface $request): ResponseInterface
    {
        $this->coreUpdateInitialize();
        return new JsonResponse([
            'success' => $this->coreUpdateService->verifyFileChecksum($this->coreUpdateGetVersionToHandle($request)),
            'status' => $this->coreUpdateService->getMessages(),
        ]);
    }

    /**
     * Get list of loaded extensions
     *
Philipp Hamid's avatar
Philipp Hamid committed
412
     * @param ServerRequestInterface $request
413
414
     * @return ResponseInterface
     */
Philipp Hamid's avatar
Philipp Hamid committed
415
    public function extensionCompatTesterLoadedExtensionListAction(ServerRequestInterface $request): ResponseInterface
416
    {
Philipp Hamid's avatar
Philipp Hamid committed
417
418
419
420
421
422
423
424
        $formProtection = FormProtectionFactory::get(InstallToolFormProtection::class);
        $view = $this->initializeStandaloneView($request, 'Upgrade/ExtensionCompatTester.html');
        $view->assignMultiple([
            'extensionCompatTesterLoadExtLocalconfToken' => $formProtection->generateToken('installTool', 'extensionCompatTesterLoadExtLocalconf'),
            'extensionCompatTesterLoadExtTablesToken' => $formProtection->generateToken('installTool', 'extensionCompatTesterLoadExtTables'),
            'extensionCompatTesterUninstallToken' => $formProtection->generateToken('installTool', 'extensionCompatTesterUninstallExtension'),
        ]);

425
426
        return new JsonResponse([
            'success' => true,
Philipp Hamid's avatar
Philipp Hamid committed
427
            'html' => $view->render(),
428
429
430
431
432
433
            'buttons' => [
                [
                    'btnClass' => 'btn-default disabled t3js-extensionCompatTester-check',
                    'text' => 'Check extensions',
                ],
            ],
434
435
436
437
438
439
440
441
442
443
444
        ]);
    }

    /**
     * Load all ext_localconf files in order until given extension name
     *
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     */
    public function extensionCompatTesterLoadExtLocalconfAction(ServerRequestInterface $request): ResponseInterface
    {
445
        $brokenExtensions = [];
446
447
448
        $container = $this->lateBootService->getContainer();
        $backup = $this->lateBootService->makeCurrent($container);

449
        foreach ($this->packageManager->getActivePackages() as $package) {
450
451
452
453
454
455
456
            try {
                $this->extensionCompatTesterLoadExtLocalconfForExtension($package);
            } catch (\Throwable $e) {
                $brokenExtensions[] = [
                    'name' => $package->getPackageKey(),
                    'isProtected' => $package->isProtected()
                ];
457
458
            }
        }
459
460
461

        $this->lateBootService->makeCurrent(null, $backup);

462
        return new JsonResponse([
463
464
            'brokenExtensions' => $brokenExtensions,
        ], empty($brokenExtensions) ? 200 : 500);
465
466
467
468
469
470
471
472
473
474
    }

    /**
     * Load all ext_localconf files in order until given extension name
     *
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     */
    public function extensionCompatTesterLoadExtTablesAction(ServerRequestInterface $request): ResponseInterface
    {
475
        $brokenExtensions = [];
476
477
478
        $container = $this->lateBootService->getContainer();
        $backup = $this->lateBootService->makeCurrent($container);

479
480
        $activePackages = $this->packageManager->getActivePackages();
        foreach ($activePackages as $package) {
481
            // Load all ext_localconf files first
482
            $this->extensionCompatTesterLoadExtLocalconfForExtension($package);
483
        }
484
        foreach ($activePackages as $package) {
485
486
487
488
489
490
491
            try {
                $this->extensionCompatTesterLoadExtTablesForExtension($package);
            } catch (\Throwable $e) {
                $brokenExtensions[] = [
                    'name' => $package->getPackageKey(),
                    'isProtected' => $package->isProtected()
                ];
492
493
            }
        }
494
495
496

        $this->lateBootService->makeCurrent(null, $backup);

497
        return new JsonResponse([
498
499
            'brokenExtensions' => $brokenExtensions,
        ], empty($brokenExtensions) ? 200 : 500);
500
501
502
503
504
505
506
    }

    /**
     * Unload one extension
     *
     * @param ServerRequestInterface $request
     * @return ResponseInterface
Philipp Hamid's avatar
Philipp Hamid committed
507
     * @throws \RuntimeException
508
509
510
511
512
513
514
515
516
517
518
519
520
521
     */
    public function extensionCompatTesterUninstallExtensionAction(ServerRequestInterface $request): ResponseInterface
    {
        $extension = $request->getParsedBody()['install']['extension'];
        if (empty($extension)) {
            throw new \RuntimeException(
                'No extension given',
                1505407269
            );
        }
        $messageQueue = new FlashMessageQueue('install');
        if (ExtensionManagementUtility::isLoaded($extension)) {
            try {
                ExtensionManagementUtility::unloadExtension($extension);
522
523
524
                GeneralUtility::makeInstance(ClearCacheService::class)->clearAll();
                GeneralUtility::makeInstance(OpcodeCacheService::class)->clearAllActive();

525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
                $messageQueue->enqueue(new FlashMessage(
                    'Extension "' . $extension . '" unloaded.',
                    '',
                    FlashMessage::ERROR
                ));
            } catch (\Exception $e) {
                $messageQueue->enqueue(new FlashMessage(
                    $e->getMessage(),
                    '',
                    FlashMessage::ERROR
                ));
            }
        }
        return new JsonResponse([
            'success' => true,
            'status' => $messageQueue,
        ]);
    }

Philipp Hamid's avatar
Philipp Hamid committed
544
545
546
    /**
     * Create Extension Scanner Data action
     *
547
     * @param ServerRequestInterface $request
Philipp Hamid's avatar
Philipp Hamid committed
548
549
550
551
     * @return ResponseInterface
     */
    public function extensionScannerGetDataAction(ServerRequestInterface $request): ResponseInterface
    {
552
        $extensionsInTypo3conf = (new Finder())->directories()->in(Environment::getExtensionsPath())->depth(0)->sortByName();
Philipp Hamid's avatar
Philipp Hamid committed
553
554
555
556
557
558
559
560
561
562
563
        $view = $this->initializeStandaloneView($request, 'Upgrade/ExtensionScanner.html');
        $formProtection = FormProtectionFactory::get(InstallToolFormProtection::class);
        $view->assignMultiple([
            'extensionScannerExtensionList' => $extensionsInTypo3conf,
            'extensionScannerFilesToken' => $formProtection->generateToken('installTool', 'extensionScannerFiles'),
            'extensionScannerScanFileToken' => $formProtection->generateToken('installTool', 'extensionScannerScanFile'),
            'extensionScannerMarkFullyScannedRestFilesToken' => $formProtection->generateToken('installTool', 'extensionScannerMarkFullyScannedRestFiles'),
        ]);
        return new JsonResponse([
            'success' => true,
            'html' => $view->render(),
564
565
566
567
568
569
            'buttons' => [
                [
                    'btnClass' => 'btn-default t3js-extensionScanner-scan-all',
                    'text' => 'Scan all',
                ],
            ],
Philipp Hamid's avatar
Philipp Hamid committed
570
571
572
        ]);
    }

573
574
575
576
577
578
579
580
581
582
    /**
     * Return a list of files of an extension
     *
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     */
    public function extensionScannerFilesAction(ServerRequestInterface $request): ResponseInterface
    {
        // Get and validate path
        $extension = $request->getParsedBody()['install']['extension'];
583
        $extensionBasePath = Environment::getExtensionsPath() . '/' . $extension;
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
        if (empty($extension) || !GeneralUtility::isAllowedAbsPath($extensionBasePath)) {
            throw new \RuntimeException(
                'Path to extension ' . $extension . ' not allowed.',
                1499777261
            );
        }
        if (!is_dir($extensionBasePath)) {
            throw new \RuntimeException(
                'Extension path ' . $extensionBasePath . ' does not exist or is no directory.',
                1499777330
            );
        }

        $finder = new Finder();
        $files = $finder->files()->in($extensionBasePath)->name('*.php')->sortByName();
        // A list of file names relative to extension directory
        $relativeFileNames = [];
        foreach ($files as $file) {
602
            /** @var SplFileInfo $file */
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
            $relativeFileNames[] = GeneralUtility::fixWindowsFilePath($file->getRelativePathname());
        }
        return new JsonResponse([
            'success' => true,
            'files' => $relativeFileNames,
        ]);
    }

    /**
     * Ajax controller, part of "extension scanner". Called at the end of "scan all"
     * as last action. Gets a list of RST file hashes that matched, goes through all
     * existing RST files, finds those marked as "FullyScanned" and marks those that
     * did not had any matches as "you are not affected".
     *
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     */
    public function extensionScannerMarkFullyScannedRestFilesAction(ServerRequestInterface $request): ResponseInterface
    {
622
        $foundRestFileHashes = (array)($request->getParsedBody()['install']['hashes'] ?? []);
623
624
625
626
627
628
629
        // First un-mark files marked as scanned-ok
        $registry = new Registry();
        $registry->removeAllByNamespace('extensionScannerNotAffected');
        // Find all .rst files (except those from v8), see if they are tagged with "FullyScanned"
        // and if their content is not in incoming "hashes" array, mark as "not affected"
        $documentationFile = new DocumentationFile();
        $finder = new Finder();
630
        $restFilesBasePath = ExtensionManagementUtility::extPath('core') . 'Documentation/Changelog';
631
632
633
634
        $restFiles = $finder->files()->in($restFilesBasePath);
        $fullyScannedRestFilesNotAffected = [];
        foreach ($restFiles as $restFile) {
            // Skip files in "8.x" directory
635
            /** @var SplFileInfo $restFile */
636
            if (strpos($restFile->getRelativePath(), '8') === 0) {
637
638
639
640
                continue;
            }

            // Build array of file (hashes) not affected by current scan, if they are tagged as "FullyScanned"
641
            $listEntries = $documentationFile->getListEntry(str_replace(
642
643
                '\\',
                '/',
644
645
646
                (string)realpath($restFile->getPathname())
            ));
            $parsedRestFile = array_pop($listEntries);
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
            if (!in_array($parsedRestFile['file_hash'], $foundRestFileHashes, true)
                && in_array('FullyScanned', $parsedRestFile['tags'], true)
            ) {
                $fullyScannedRestFilesNotAffected[] = $parsedRestFile['file_hash'];
            }
        }
        foreach ($fullyScannedRestFilesNotAffected as $fileHash) {
            $registry->set('extensionScannerNotAffected', $fileHash, $fileHash);
        }
        return new JsonResponse([
            'success' => true,
            'markedAsNotAffected' => count($fullyScannedRestFilesNotAffected),
        ]);
    }

    /**
     * Scan a single extension file for breaking / deprecated core code usages
     *
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     */
    public function extensionScannerScanFileAction(ServerRequestInterface $request): ResponseInterface
    {
        // Get and validate path and file
        $extension = $request->getParsedBody()['install']['extension'];
672
        $extensionBasePath = Environment::getExtensionsPath() . '/' . $extension;
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
        if (empty($extension) || !GeneralUtility::isAllowedAbsPath($extensionBasePath)) {
            throw new \RuntimeException(
                'Path to extension ' . $extension . ' not allowed.',
                1499789246
            );
        }
        if (!is_dir($extensionBasePath)) {
            throw new \RuntimeException(
                'Extension path ' . $extensionBasePath . ' does not exist or is no directory.',
                1499789259
            );
        }
        $file = $request->getParsedBody()['install']['file'];
        $absoluteFilePath = $extensionBasePath . '/' . $file;
        if (empty($file) || !GeneralUtility::isAllowedAbsPath($absoluteFilePath)) {
            throw new \RuntimeException(
                'Path to file ' . $file . ' of extension ' . $extension . ' not allowed.',
                1499789384
            );
        }
        if (!is_file($absoluteFilePath)) {
            throw new \RuntimeException(
                'File ' . $file . ' not found or is not a file.',
                1499789433
            );
        }

        $parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7);
        // Parse PHP file to AST and traverse tree calling visitors
        $statements = $parser->parse(file_get_contents($absoluteFilePath));

        // The built in NameResolver translates class names shortened with 'use' to fully qualified
        // class names at all places. Incredibly useful for us and added as first visitor.
706
707
708
        // IMPORTANT: first process completely to resolve fully qualified names of arguments
        // (otherwise GeneratorClassesResolver will NOT get reliable results)
        $traverser = new NodeTraverser();
709
        $traverser->addVisitor(new NameResolver());
710
711
712
713
714
        $statements = $traverser->traverse($statements);

        // IMPORTANT: second process to actually work on the pre-resolved statements
        $traverser = new NodeTraverser();
        // Understand GeneralUtility::makeInstance('My\\Package\\Foo\\Bar') as fqdn class name in first argument
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
        $traverser->addVisitor(new GeneratorClassesResolver());
        // Count ignored lines, effective code lines, ...
        $statistics = new CodeStatistics();
        $traverser->addVisitor($statistics);

        // Add all configured matcher classes
        $matcherFactory = new MatcherFactory();
        $matchers = $matcherFactory->createAll($this->matchers);
        foreach ($matchers as $matcher) {
            $traverser->addVisitor($matcher);
        }

        $traverser->traverse($statements);

        // Gather code matches
730
        $matches = [[]];
731
732
        foreach ($matchers as $matcher) {
            /** @var \TYPO3\CMS\Install\ExtensionScanner\CodeScannerInterface $matcher */
733
            $matches[] = $matcher->getMatches();
734
        }
735
        $matches = array_merge(...$matches);
736
737

        // Prepare match output
738
        $restFilesBasePath = ExtensionManagementUtility::extPath('core') . 'Documentation/Changelog';
739
740
741
742
        $documentationFile = new DocumentationFile();
        $preparedMatches = [];
        foreach ($matches as $match) {
            $preparedHit = [];
743
            $preparedHit['uniqueId'] = StringUtility::getUniqueId();
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
            $preparedHit['message'] = $match['message'];
            $preparedHit['line'] = $match['line'];
            $preparedHit['indicator'] = $match['indicator'];
            $preparedHit['lineContent'] = $this->extensionScannerGetLineFromFile($absoluteFilePath, $match['line']);
            $preparedHit['restFiles'] = [];
            foreach ($match['restFiles'] as $fileName) {
                $finder = new Finder();
                $restFileLocation = $finder->files()->in($restFilesBasePath)->name($fileName);
                if ($restFileLocation->count() !== 1) {
                    throw new \RuntimeException(
                        'ResT file ' . $fileName . ' not found or multiple files found.',
                        1499803909
                    );
                }
                foreach ($restFileLocation as $restFile) {
                    /** @var SplFileInfo $restFile */
                    $restFileLocation = $restFile->getPathname();
                    break;
                }
763
                $listEntries = $documentationFile->getListEntry(str_replace(
764
765
                    '\\',
                    '/',
766
767
768
                    (string)realpath($restFileLocation)
                ));
                $parsedRestFile = array_pop($listEntries);
769
                $version = GeneralUtility::trimExplode(DIRECTORY_SEPARATOR, $restFileLocation);
770
771
772
                array_pop($version);
                // something like "8.2" .. "8.7" .. "master"
                $parsedRestFile['version'] = array_pop($version);
773
                $parsedRestFile['uniqueId'] = StringUtility::getUniqueId();
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
                $preparedHit['restFiles'][] = $parsedRestFile;
            }
            $preparedMatches[] = $preparedHit;
        }
        return new JsonResponse([
            'success' => true,
            'matches' => $preparedMatches,
            'isFileIgnored' => $statistics->isFileIgnored(),
            'effectiveCodeLines' => $statistics->getNumberOfEffectiveCodeLines(),
            'ignoredLines' => $statistics->getNumberOfIgnoredLines(),
        ]);
    }

    /**
     * Check if loading ext_tables.php files still changes TCA
     *
790
     * @param ServerRequestInterface $request
791
792
     * @return ResponseInterface
     */
Philipp Hamid's avatar
Philipp Hamid committed
793
    public function tcaExtTablesCheckAction(ServerRequestInterface $request): ResponseInterface
794
    {
Philipp Hamid's avatar
Philipp Hamid committed
795
        $view = $this->initializeStandaloneView($request, 'Upgrade/TcaExtTablesCheck.html');
796
797
798
799
        $messageQueue = new FlashMessageQueue('install');
        $loadTcaService = GeneralUtility::makeInstance(LoadTcaService::class);
        $loadTcaService->loadExtensionTablesWithoutMigration();
        $baseTca = $GLOBALS['TCA'];
800
801
        $container = $this->lateBootService->getContainer();
        $backup = $this->lateBootService->makeCurrent($container);
802
        foreach ($this->packageManager->getActivePackages() as $package) {
803
804
            $this->extensionCompatTesterLoadExtLocalconfForExtension($package);

805
806
807
            $extensionKey = $package->getPackageKey();
            $extTablesPath = $package->getPackagePath() . 'ext_tables.php';
            if (@file_exists($extTablesPath)) {
808
809
810
811
812
813
814
815
816
817
818
819
                $loadTcaService->loadSingleExtTablesFile($extensionKey);
                $newTca = $GLOBALS['TCA'];
                if ($newTca !== $baseTca) {
                    $messageQueue->enqueue(new FlashMessage(
                        '',
                        $extensionKey,
                        FlashMessage::NOTICE
                    ));
                }
                $baseTca = $newTca;
            }
        }
820
        $this->lateBootService->makeCurrent(null, $backup);
821
822
823
        return new JsonResponse([
            'success' => true,
            'status' => $messageQueue,
Philipp Hamid's avatar
Philipp Hamid committed
824
            'html' => $view->render(),
825
826
827
828
829
830
            'buttons' => [
                [
                    'btnClass' => 'btn-default t3js-tcaExtTablesCheck-check',
                    'text' => 'Check loaded extensions',
                ],
            ],
831
832
833
834
835
836
        ]);
    }

    /**
     * Check TCA for needed migrations
     *
Philipp Hamid's avatar
Philipp Hamid committed
837
     * @param ServerRequestInterface $request
838
839
     * @return ResponseInterface
     */
Philipp Hamid's avatar
Philipp Hamid committed
840
    public function tcaMigrationsCheckAction(ServerRequestInterface $request): ResponseInterface
841
    {
Philipp Hamid's avatar
Philipp Hamid committed
842
        $view = $this->initializeStandaloneView($request, 'Upgrade/TcaMigrationsCheck.html');
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
        $messageQueue = new FlashMessageQueue('install');
        GeneralUtility::makeInstance(LoadTcaService::class)->loadExtensionTablesWithoutMigration();
        $tcaMigration = GeneralUtility::makeInstance(TcaMigration::class);
        $GLOBALS['TCA'] = $tcaMigration->migrate($GLOBALS['TCA']);
        $tcaMessages = $tcaMigration->getMessages();
        foreach ($tcaMessages as $tcaMessage) {
            $messageQueue->enqueue(new FlashMessage(
                '',
                $tcaMessage,
                FlashMessage::NOTICE
            ));
        }
        return new JsonResponse([
            'success' => true,
            'status' => $messageQueue,
Philipp Hamid's avatar
Philipp Hamid committed
858
            'html' => $view->render(),
859
860
861
862
863
864
            'buttons' => [
                [
                    'btnClass' => 'btn-default t3js-tcaMigrationsCheck-check',
                    'text' => 'Check TCA Migrations',
                ],
            ],
865
866
867
868
        ]);
    }

    /**
869
     * Render list of versions
870
871
872
873
874
875
876
     *
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     */
    public function upgradeDocsGetContentAction(ServerRequestInterface $request): ResponseInterface
    {
        $formProtection = FormProtectionFactory::get(InstallToolFormProtection::class);
877
        $documentationDirectories = $this->getDocumentationDirectories();
878
879
880
881
        $view = $this->initializeStandaloneView($request, 'Upgrade/UpgradeDocsGetContent.html');
        $view->assignMultiple([
            'upgradeDocsMarkReadToken' => $formProtection->generateToken('installTool', 'upgradeDocsMarkRead'),
            'upgradeDocsUnmarkReadToken' => $formProtection->generateToken('installTool', 'upgradeDocsUnmarkRead'),
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
            'upgradeDocsVersions' => $documentationDirectories,
        ]);
        return new JsonResponse([
            'success' => true,
            'html' => $view->render(),
        ]);
    }

    /**
     * Render list of .rst files
     *
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     */
    public function upgradeDocsGetChangelogForVersionAction(ServerRequestInterface $request): ResponseInterface
    {
        $version = $request->getQueryParams()['install']['version'] ?? '';
        $this->assertValidVersion($version);

        $documentationFiles = $this->getDocumentationFiles($version);
        $view = $this->initializeStandaloneView($request, 'Upgrade/UpgradeDocsGetChangelogForVersion.html');
        $view->assignMultiple([
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
            'upgradeDocsFiles' => $documentationFiles['normalFiles'],
            'upgradeDocsReadFiles' => $documentationFiles['readFiles'],
            'upgradeDocsNotAffectedFiles' => $documentationFiles['notAffectedFiles'],
        ]);
        return new JsonResponse([
            'success' => true,
            'html' => $view->render(),
        ]);
    }

    /**
     * Mark a .rst file as read
     *
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     */
    public function upgradeDocsMarkReadAction(ServerRequestInterface $request): ResponseInterface
    {
        $registry = new Registry();
        $filePath = $request->getParsedBody()['install']['ignoreFile'];
        $fileHash = md5_file($filePath);
        $registry->set('upgradeAnalysisIgnoredFiles', $fileHash, $filePath);
        return new JsonResponse([
            'success' => true,
        ]);
    }

    /**
     * Mark a .rst file as not read
     *
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     */
    public function upgradeDocsUnmarkReadAction(ServerRequestInterface $request): ResponseInterface
    {
        $registry = new Registry();
        $filePath = $request->getParsedBody()['install']['ignoreFile'];
        $fileHash = md5_file($filePath);
        $registry->remove('upgradeAnalysisIgnoredFiles', $fileHash);
        return new JsonResponse([
            'success' => true,
        ]);
    }

    /**
     * Check if new tables and fields should be added before executing wizards
     *
     * @return ResponseInterface
     */
    public function upgradeWizardsBlockingDatabaseAddsAction(): ResponseInterface
    {
        // ext_localconf, db and ext_tables must be loaded for the updates :(
956
        $this->lateBootService->loadExtLocalconfDatabaseAndExtTables(false);
957
        $adds = [];
958
        $needsUpdate = false;
959
        try {
960
961
            $adds = $this->upgradeWizardsService->getBlockingDatabaseAdds();
            $this->lateBootService->resetGlobalContainer();
962
963
964
965
            if (!empty($adds)) {
                $needsUpdate = true;
            }
        } catch (StatementException $exception) {
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
            $needsUpdate = true;
        }
        return new JsonResponse([
            'success' => true,
            'needsUpdate' => $needsUpdate,
            'adds' => $adds,
        ]);
    }

    /**
     * Add new tables and fields
     *
     * @return ResponseInterface
     */
    public function upgradeWizardsBlockingDatabaseExecuteAction(): ResponseInterface
    {
        // ext_localconf, db and ext_tables must be loaded for the updates :(
983
984
985
        $this->lateBootService->loadExtLocalconfDatabaseAndExtTables(false);
        $this->upgradeWizardsService->addMissingTablesAndFields();
        $this->lateBootService->resetGlobalContainer();
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
        $messages = new FlashMessageQueue('install');
        $messages->enqueue(new FlashMessage(
            '',
            'Added missing database fields and tables'
        ));
        return new JsonResponse([
            'success' => true,
            'status' => $messages,
        ]);
    }

    /**
     * Fix a broken DB charset setting
     *
     * @return ResponseInterface
     */
    public function upgradeWizardsBlockingDatabaseCharsetFixAction(): ResponseInterface
    {
1004
        $this->upgradeWizardsService->setDatabaseCharsetUtf8();
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
        $messages = new FlashMessageQueue('install');
        $messages->enqueue(new FlashMessage(
            '',
            'Default connection database has been set to utf8'
        ));
        return new JsonResponse([
            'success' => true,
            'status' => $messages,
        ]);
    }

    /**
     * Test if database charset is ok
     *
     * @return ResponseInterface
     */
    public function upgradeWizardsBlockingDatabaseCharsetTestAction(): ResponseInterface
    {
1023
        $result = !$this->upgradeWizardsService->isDatabaseCharsetUtf8();
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
        return new JsonResponse([
            'success' => true,
            'needsUpdate' => $result,
        ]);
    }

    /**
     * Get list of upgrade wizards marked as done
     *
     * @return ResponseInterface
     */
    public function upgradeWizardsDoneUpgradesAction(): ResponseInterface
    {
1037
1038
1039
1040
        $this->lateBootService->loadExtLocalconfDatabaseAndExtTables(false);
        $wizardsDone = $this->upgradeWizardsService->listOfWizardsDone();
        $rowUpdatersDone = $this->upgradeWizardsService->listOfRowUpdatersDone();
        $this->lateBootService->resetGlobalContainer();
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
        $messages = new FlashMessageQueue('install');
        if (empty($wizardsDone) && empty($rowUpdatersDone)) {
            $messages->enqueue(new FlashMessage(
                '',
                'No wizards are marked as done'
            ));
        }
        return new JsonResponse([
            'success' => true,
            'status' => $messages,
            'wizardsDone' => $wizardsDone,
            'rowUpdatersDone' => $rowUpdatersDone,
        ]);
    }

    /**
     * Execute one upgrade wizard
     *
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     */
    public function upgradeWizardsExecuteAction(ServerRequestInterface $request): ResponseInterface
    {
        // ext_localconf, db and ext_tables must be loaded for the updates :(
1065
        $this->lateBootService->loadExtLocalconfDatabaseAndExtTables(false);
1066
        $identifier = $request->getParsedBody()['install']['identifier'];
1067
1068
        $messages = $this->upgradeWizardsService->executeWizard($identifier);
        $this->lateBootService->resetGlobalContainer();
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
        return new JsonResponse([
            'success' => true,
            'status' => $messages,
        ]);
    }

    /**
     * Input stage of a specific upgrade wizard
     *
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     */
    public function upgradeWizardsInputAction(ServerRequestInterface $request): ResponseInterface
    {
        // ext_localconf, db and ext_tables must be loaded for the updates :(
1084
        $this->lateBootService->loadExtLocalconfDatabaseAndExtTables(false);
1085
        $identifier = $request->getParsedBody()['install']['identifier'];
1086
1087
        $result = $this->upgradeWizardsService->getWizardUserInput($identifier);
        $this->lateBootService->resetGlobalContainer();
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
        return new JsonResponse([
            'success' => true,
            'status' => [],
            'userInput' => $result,
        ]);
    }

    /**
     * List available upgrade wizards
     *
     * @return ResponseInterface
     */
    public function upgradeWizardsListAction(): ResponseInterface
    {
        // ext_localconf, db and ext_tables must be loaded for the updates :(
1103
1104
1105
        $this->lateBootService->loadExtLocalconfDatabaseAndExtTables(false);
        $wizards = $this->upgradeWizardsService->getUpgradeWizardsList();
        $this->lateBootService->resetGlobalContainer();
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
        return new JsonResponse([
            'success' => true,
            'status' => [],
            'wizards' => $wizards,
        ]);
    }

    /**
     * Mark a wizard as "not done"
     *
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     */
    public function upgradeWizardsMarkUndoneAction(ServerRequestInterface $request): ResponseInterface
    {
1121
        $this->lateBootService->loadExtLocalconfDatabaseAndExtTables(false);
1122
        $wizardToBeMarkedAsUndoneIdentifier = $request->getParsedBody()['install']['identifier'];
1123
        $wizardToBeMarkedAsUndone = $this->upgradeWizardsService->getWizardInformationByIdentifier($wizardToBeMarkedAsUndoneIdentifier);
1124
1125
        $result = $this->upgradeWizardsService->markWizardUndone($wizardToBeMarkedAsUndoneIdentifier);
        $this->lateBootService->resetGlobalContainer();
1126
1127
1128
        $messages = new FlashMessageQueue('install');
        if ($result) {
            $messages->enqueue(new FlashMessage(
1129
1130
                'The wizard "' . $wizardToBeMarkedAsUndone['title'] . '" has been marked as undone.',
                'Wizard marked as undone'
1131
1132
1133
            ));
        } else {
            $messages->enqueue(new FlashMessage(
1134
                'The wizard "' . $wizardToBeMarkedAsUndone['title'] . '" has not been marked as undone.',
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
                'Wizard has not been marked undone',
                FlashMessage::ERROR
            ));
        }
        return new JsonResponse([
            'success' => true,
            'status' => $messages,
        ]);
    }

Philipp Hamid's avatar
Philipp Hamid committed
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
    /**
     * Change install tool password
     *
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     */
    public function upgradeWizardsGetDataAction(ServerRequestInterface $request): ResponseInterface
    {
        $view = $this->initializeStandaloneView($request, 'Upgrade/UpgradeWizards.html');
        $formProtection = FormProtectionFactory::get(InstallToolFormProtection::class);
        $view->assignMultiple([
            'upgradeWizardsMarkUndoneToken' => $formProtection->generateToken('installTool', 'upgradeWizardsMarkUndone'),
            'upgradeWizardsInputToken' => $formProtection->generateToken('installTool', 'upgradeWizardsInput'),
            'upgradeWizardsExecuteToken' => $formProtection->generateToken('installTool', 'upgradeWizardsExecute'),
        ]);
        return new JsonResponse([
            'success' => true,
            'html' => $view->render(),
        ]);
    }

1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
    /**
     * Initialize the core upgrade actions
     *
     * @throws \RuntimeException
     */
    protected function coreUpdateInitialize()
    {
        $this->coreUpdateService = GeneralUtility::makeInstance(CoreUpdateService::class);
        $this->coreVersionService = GeneralUtility::makeInstance(CoreVersionService::class);
        if (!$this->coreUpdateService->isCoreUpdateEnabled()) {
            throw new \RuntimeException(
                'Core Update disabled in this environment',
                1381609294
            );
        }
        // @todo: Does the core updater really depend on loaded ext_* files?
1182
        $this->lateBootService->loadExtLocalconfDatabaseAndExtTables();
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
    }

    /**
     * Find out which version upgrade should be handled. This may
     * be different depending on whether development or regular release.
     *
     * @param ServerRequestInterface $request
     * @throws \RuntimeException
     * @return string Version to handle, eg. 6.2.2
     */
    protected function coreUpdateGetVersionToHandle(ServerRequestInterface $request): string
    {
        $type = $request->getQueryParams()['install']['type'];
        if (!isset($type) || empty($type)) {
            throw new \RuntimeException(
                'Type must be set to either "regular" or "development"',
                1380975303
            );
        }
1202
        return $this->coreVersionService->getYoungestPatchRelease();
1203
1204
1205
1206
1207
1208
    }

    /**
     * Loads ext_localconf.php for a single extension. Method is a modified copy of
     * the original bootstrap method.
     *
1209
     * @param PackageInterface $package
1210
     */
1211
    protected function extensionCompatTesterLoadExtLocalconfForExtension(PackageInterface $package)
1212
    {
1213
1214
1215
        $extLocalconfPath = $package->getPackagePath() . 'ext_localconf.php';
        if (@file_exists($extLocalconfPath)) {
            require $extLocalconfPath;
1216
1217
1218
1219
1220
1221
1222
        }
    }

    /**
     * Loads ext_tables.php for a single extension. Method is a modified copy of
     * the original bootstrap method.
     *
1223
     * @param PackageInterface $package
1224
     */
1225
    protected function extensionCompatTesterLoadExtTablesForExtension(PackageInterface $package)
1226
    {
1227
1228
1229
        $extTablesPath = $package->getPackagePath() . 'ext_tables.php';
        if (@file_exists($extTablesPath)) {
            require $extTablesPath;
1230
1231
1232
        }
    }

1233
1234
1235
1236
1237
1238
1239
    /**
     * @return string[]
     */
    protected function getDocumentationDirectories(): array
    {
        $documentationFileService = new DocumentationFile();
        $documentationDirectories = $documentationFileService->findDocumentationDirectories(
1240
            str_replace('\\', '/', (string)realpath(ExtensionManagementUtility::extPath('core') . 'Documentation/Changelog'))
1241
1242
1243
1244
        );
        return array_reverse($documentationDirectories);
    }

1245
1246
1247
    /**
     * Get a list of '.rst' files and their details for "Upgrade documentation" view.
     *
1248
     * @param string $version
1249
1250
     * @return array
     */
1251
    protected function getDocumentationFiles(string $version): array
1252
1253
1254
    {
        $documentationFileService = new DocumentationFile();
        $documentationFiles = $documentationFileService->findDocumentationFiles(
1255
            str_replace('\\', '/', (string)realpath(ExtensionManagementUtility::extPath('core') . 'Documentation/Changelog/' . $version))
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
        );

        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_registry');
        $filesMarkedAsRead = $queryBuilder
            ->select('*')
            ->from('sys_registry')
            ->where(
                $queryBuilder->expr()->eq(
                    'entry_namespace',
                    $queryBuilder->createNamedParameter('upgradeAnalysisIgnoredFiles', \PDO::PARAM_STR)
                )
            )
            ->execute()
            ->fetchAll();
        $hashesMarkedAsRead = [];
        foreach ($filesMarkedAsRead as $file) {
            $hashesMarkedAsRead[] = $file['entry_key'];
        }

        $fileMarkedAsNotAffected = $queryBuilder
            ->select('*')
            ->from('sys_registry')
            ->where(
                $queryBuilder->expr()->eq(
                    'entry_namespace',
                    $queryBuilder->createNamedParameter('extensionScannerNotAffected', \PDO::PARAM_STR)
                )
            )
            ->execute()
            ->fetchAll();
        $hashesMarkedAsNotAffected = [];
        foreach ($fileMarkedAsNotAffected as $file) {
            $hashesMarkedAsNotAffected[] = $file['entry_key'];
        }

        $readFiles = [];
        $notAffectedFiles = [];
1293
1294
1295
1296
1297
1298
1299
        foreach ($documentationFiles as $fileId => $fileData) {
            if (in_array($fileData['file_hash'], $hashesMarkedAsRead, true)) {
                $readFiles[$fileId] = $fileData;
                unset($documentationFiles[$fileId]);
            } elseif (in_array($fileData['file_hash'], $hashesMarkedAsNotAffected, true)) {
                $notAffectedFiles[$fileId] = $fileData;
                unset($documentationFiles[$fileId]);
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
            }
        }

        return [
            'normalFiles' => $documentationFiles,
            'readFiles' => $readFiles,
            'notAffectedFiles' => $notAffectedFiles,
        ];
    }

    /**
     * Find a code line in a file
     *
     * @param string $file Absolute path to file
     * @param int $lineNumber Find this line in file
     * @return string Code line
     */
    protected function extensionScannerGetLineFromFile(string $file, int $lineNumber): string
    {
        $fileContent = file($file, FILE_IGNORE_NEW_LINES);
        $line = '';
        if (isset($fileContent[$lineNumber - 1])) {
            $line = trim($fileContent[$lineNumber - 1]);
        }
        return $line;
    }
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338

    /**
     * Asserts that the given version is valid
     *
     * @param string $version
     * @throws \InvalidArgumentException
     */
    protected function assertValidVersion(string $version): void
    {
        if ($version !== 'master' && !preg_match('/^\d+.\d+(?:.(?:\d+|x))?$/', $version)) {
            throw new \InvalidArgumentException('Given version "' . $version . '" is invalid', 1537209128);
        }
    }
1339
}