-
Notifications
You must be signed in to change notification settings - Fork 638
/
PackageManager.php
1186 lines (1085 loc) · 47 KB
/
PackageManager.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
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
672
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
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
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
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace TYPO3\CMS\Core\Package;
/*
* 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!
*/
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo;
use TYPO3\CMS\Core\Cache\Frontend\FrontendInterface;
use TYPO3\CMS\Core\Core\ClassLoadingInformation;
use TYPO3\CMS\Core\Core\Environment;
use TYPO3\CMS\Core\Information\Typo3Version;
use TYPO3\CMS\Core\Package\Event\BeforePackageActivationEvent;
use TYPO3\CMS\Core\Package\Event\PackagesMayHaveChangedEvent;
use TYPO3\CMS\Core\Service\DependencyOrderingService;
use TYPO3\CMS\Core\Service\OpcodeCacheService;
use TYPO3\CMS\Core\SingletonInterface;
use TYPO3\CMS\Core\Utility\ArrayUtility;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\PathUtility;
/**
* The default TYPO3 Package Manager
*/
class PackageManager implements SingletonInterface
{
/**
* @var DependencyOrderingService
*/
protected $dependencyOrderingService;
/**
* @var FrontendInterface
*/
protected $coreCache;
/**
* @var string
*/
protected $cacheIdentifier;
/**
* @var array
*/
protected $packagesBasePaths = [];
/**
* @var array
*/
protected $packageAliasMap = [];
/**
* @var array
*/
protected $runtimeActivatedPackages = [];
/**
* Absolute path leading to the various package directories
* @var string
*/
protected $packagesBasePath;
/**
* Array of available packages, indexed by package key
* @var PackageInterface[]
*/
protected $packages = [];
/**
* @var bool
*/
protected $availablePackagesScanned = false;
/**
* A map between ComposerName and PackageKey, only available when scanAvailablePackages is run
* @var array
*/
protected $composerNameToPackageKeyMap = [];
/**
* List of active packages as package key => package object
* @var array
*/
protected $activePackages = [];
/**
* @var string
*/
protected $packageStatesPathAndFilename;
/**
* Package states configuration as stored in the PackageStates.php file
* @var array
*/
protected $packageStatesConfiguration = [];
/**
* @param DependencyOrderingService $dependencyOrderingService
*/
public function __construct(DependencyOrderingService $dependencyOrderingService)
{
$this->packagesBasePath = Environment::getPublicPath() . '/';
$this->packageStatesPathAndFilename = Environment::getLegacyConfigPath() . '/PackageStates.php';
$this->dependencyOrderingService = $dependencyOrderingService;
}
/**
* @param FrontendInterface $coreCache
* @internal
*/
public function injectCoreCache(FrontendInterface $coreCache)
{
$this->coreCache = $coreCache;
}
/**
* Initializes the package manager
* @internal
*/
public function initialize()
{
try {
$this->loadPackageManagerStatesFromCache();
} catch (Exception\PackageManagerCacheUnavailableException $exception) {
$this->loadPackageStates();
$this->initializePackageObjects();
$this->saveToPackageCache();
}
}
/**
* @internal
* @return string | null
*/
public function getCacheIdentifier()
{
if ($this->cacheIdentifier === null) {
$mTime = @filemtime($this->packageStatesPathAndFilename);
if ($mTime !== false) {
$this->cacheIdentifier = md5((string)(new Typo3Version()) . $this->packageStatesPathAndFilename . $mTime);
} else {
$this->cacheIdentifier = null;
}
}
return $this->cacheIdentifier;
}
/**
* @return string
*/
protected function getCacheEntryIdentifier()
{
$cacheIdentifier = $this->getCacheIdentifier();
return $cacheIdentifier !== null ? 'PackageManager_' . $cacheIdentifier : null;
}
/**
* Saves the current state of all relevant information to the TYPO3 Core Cache
*/
protected function saveToPackageCache()
{
$cacheEntryIdentifier = $this->getCacheEntryIdentifier();
if ($cacheEntryIdentifier !== null) {
// Build cache file
$packageCache = [
'packageStatesConfiguration' => $this->packageStatesConfiguration,
'packageAliasMap' => $this->packageAliasMap,
'composerNameToPackageKeyMap' => $this->composerNameToPackageKeyMap,
'packageObjects' => serialize($this->packages),
];
$this->coreCache->set(
$cacheEntryIdentifier,
'return ' . PHP_EOL . var_export($packageCache, true) . ';'
);
}
}
/**
* Attempts to load the package manager states from cache
*
* @throws Exception\PackageManagerCacheUnavailableException
*/
protected function loadPackageManagerStatesFromCache()
{
$cacheEntryIdentifier = $this->getCacheEntryIdentifier();
if ($cacheEntryIdentifier === null || ($packageCache = $this->coreCache->require($cacheEntryIdentifier)) === false) {
throw new Exception\PackageManagerCacheUnavailableException('The package state cache could not be loaded.', 1393883342);
}
$this->packageStatesConfiguration = $packageCache['packageStatesConfiguration'];
if ($this->packageStatesConfiguration['version'] < 5) {
throw new Exception\PackageManagerCacheUnavailableException('The package state cache could not be loaded.', 1393883341);
}
$this->packageAliasMap = $packageCache['packageAliasMap'];
$this->composerNameToPackageKeyMap = $packageCache['composerNameToPackageKeyMap'];
$this->packages = unserialize($packageCache['packageObjects'], [
'allowed_classes' => [
Package::class,
MetaData::class,
MetaData\PackageConstraint::class,
\stdClass::class,
]
]);
}
/**
* Loads the states of available packages from the PackageStates.php file.
* The result is stored in $this->packageStatesConfiguration.
*
* @throws Exception\PackageStatesUnavailableException
*/
protected function loadPackageStates()
{
$this->packageStatesConfiguration = @include $this->packageStatesPathAndFilename ?: [];
if (!isset($this->packageStatesConfiguration['version']) || $this->packageStatesConfiguration['version'] < 5) {
throw new Exception\PackageStatesUnavailableException('The PackageStates.php file is either corrupt or unavailable.', 1381507733);
}
$this->registerPackagesFromConfiguration($this->packageStatesConfiguration['packages'], false);
}
/**
* Initializes activePackages property
*
* Saves PackageStates.php if list of required extensions has changed.
*/
protected function initializePackageObjects()
{
$requiredPackages = [];
$activePackages = [];
foreach ($this->packages as $packageKey => $package) {
if ($package->isProtected()) {
$requiredPackages[$packageKey] = $package;
}
if (isset($this->packageStatesConfiguration['packages'][$packageKey])) {
$activePackages[$packageKey] = $package;
}
}
$previousActivePackages = $activePackages;
$activePackages = array_merge($requiredPackages, $activePackages);
if ($activePackages != $previousActivePackages) {
foreach ($requiredPackages as $requiredPackageKey => $package) {
$this->registerActivePackage($package);
}
$this->sortAndSavePackageStates();
}
}
/**
* @param PackageInterface $package
*/
protected function registerActivePackage(PackageInterface $package)
{
// reset the active packages so they are rebuilt.
$this->activePackages = [];
$this->packageStatesConfiguration['packages'][$package->getPackageKey()] = ['packagePath' => str_replace($this->packagesBasePath, '', $package->getPackagePath())];
}
/**
* Scans all directories in the packages directories for available packages.
* For each package a Package object is created and stored in $this->packages.
* @internal
*/
public function scanAvailablePackages()
{
$packagePaths = $this->scanPackagePathsForExtensions();
$packages = [];
foreach ($packagePaths as $packageKey => $packagePath) {
try {
$composerManifest = $this->getComposerManifest($packagePath);
$packageKey = $this->getPackageKeyFromManifest($composerManifest, $packagePath);
$this->composerNameToPackageKeyMap[strtolower($composerManifest->name)] = $packageKey;
$packages[$packageKey] = ['packagePath' => str_replace($this->packagesBasePath, '', $packagePath)];
} catch (Exception\MissingPackageManifestException $exception) {
if (!$this->isPackageKeyValid($packageKey)) {
continue;
}
} catch (Exception\InvalidPackageKeyException $exception) {
continue;
}
}
$this->availablePackagesScanned = true;
$registerOnlyNewPackages = !empty($this->packages);
$this->registerPackagesFromConfiguration($packages, $registerOnlyNewPackages);
}
/**
* Event listener to retrigger scanning of available packages.
*
* @param PackagesMayHaveChangedEvent $event
*/
public function packagesMayHaveChanged(PackagesMayHaveChangedEvent $event): void
{
$this->scanAvailablePackages();
}
public function beforeInstallationEventListener(BeforePackageActivationEvent $event): void
{
if (TYPO3_REQUESTTYPE & TYPO3_REQUESTTYPE_BE) {
$this->scanAvailablePackages();
}
}
/**
* Scans all directories for a certain package.
*
* @param string $packageKey
* @return PackageInterface
*/
protected function registerPackageDuringRuntime($packageKey)
{
$packagePaths = $this->scanPackagePathsForExtensions();
$packagePath = $packagePaths[$packageKey];
$composerManifest = $this->getComposerManifest($packagePath);
$packageKey = $this->getPackageKeyFromManifest($composerManifest, $packagePath);
$this->composerNameToPackageKeyMap[strtolower($composerManifest->name)] = $packageKey;
$packagePath = PathUtility::sanitizeTrailingSeparator($packagePath);
$package = new Package($this, $packageKey, $packagePath);
$this->registerPackage($package);
return $package;
}
/**
* Fetches all directories from sysext/global/local locations and checks if the extension contains an ext_emconf.php
*
* @return array
*/
protected function scanPackagePathsForExtensions()
{
$collectedExtensionPaths = [];
foreach ($this->getPackageBasePaths() as $packageBasePath) {
// Only add the extension if we have an EMCONF and the extension is not yet registered.
// This is crucial in order to allow overriding of system extension by local extensions
// and strongly depends on the order of paths defined in $this->packagesBasePaths.
$finder = new Finder();
$finder
->name('ext_emconf.php')
->followLinks()
->depth(0)
->ignoreUnreadableDirs()
->in($packageBasePath);
/** @var SplFileInfo $fileInfo */
foreach ($finder as $fileInfo) {
$path = PathUtility::dirname($fileInfo->getPathname());
$extensionName = PathUtility::basename($path);
// Fix Windows backslashes
// we can't use GeneralUtility::fixWindowsFilePath as we have to keep double slashes for Unit Tests (vfs://)
$currentPath = str_replace('\\', '/', $path) . '/';
if (!isset($collectedExtensionPaths[$extensionName])) {
$collectedExtensionPaths[$extensionName] = $currentPath;
}
}
}
return $collectedExtensionPaths;
}
/**
* Requires and registers all packages which were defined in packageStatesConfiguration
*
* @param array $packages
* @param bool $registerOnlyNewPackages
* @throws Exception\InvalidPackageStateException
* @throws Exception\PackageStatesFileNotWritableException
*/
protected function registerPackagesFromConfiguration(array $packages, $registerOnlyNewPackages = false)
{
$packageStatesHasChanged = false;
foreach ($packages as $packageKey => $stateConfiguration) {
if ($registerOnlyNewPackages && $this->isPackageRegistered($packageKey)) {
continue;
}
if (!isset($stateConfiguration['packagePath'])) {
$this->unregisterPackageByPackageKey($packageKey);
$packageStatesHasChanged = true;
continue;
}
try {
$packagePath = PathUtility::sanitizeTrailingSeparator($this->packagesBasePath . $stateConfiguration['packagePath']);
$package = new Package($this, $packageKey, $packagePath);
} catch (Exception\InvalidPackagePathException|Exception\InvalidPackageKeyException|Exception\InvalidPackageManifestException $exception) {
$this->unregisterPackageByPackageKey($packageKey);
$packageStatesHasChanged = true;
continue;
}
$this->registerPackage($package);
}
if ($packageStatesHasChanged) {
$this->sortAndSavePackageStates();
}
}
/**
* Register a native TYPO3 package
*
* @param PackageInterface $package The Package to be registered
* @return PackageInterface
* @throws Exception\InvalidPackageStateException
* @internal
*/
public function registerPackage(PackageInterface $package)
{
$packageKey = $package->getPackageKey();
if ($this->isPackageRegistered($packageKey)) {
throw new Exception\InvalidPackageStateException('Package "' . $packageKey . '" is already registered.', 1338996122);
}
$this->packages[$packageKey] = $package;
if ($package instanceof PackageInterface) {
foreach ($package->getPackageReplacementKeys() as $packageToReplace => $versionConstraint) {
$this->packageAliasMap[strtolower($packageToReplace)] = $package->getPackageKey();
}
}
return $package;
}
/**
* Unregisters a package from the list of available packages
*
* @param string $packageKey Package Key of the package to be unregistered
*/
protected function unregisterPackageByPackageKey($packageKey)
{
try {
$package = $this->getPackage($packageKey);
if ($package instanceof PackageInterface) {
foreach ($package->getPackageReplacementKeys() as $packageToReplace => $versionConstraint) {
unset($this->packageAliasMap[strtolower($packageToReplace)]);
}
}
} catch (Exception\UnknownPackageException $e) {
}
unset($this->packages[$packageKey]);
unset($this->packageStatesConfiguration['packages'][$packageKey]);
}
/**
* Resolves a TYPO3 package key from a composer package name.
*
* @param string $composerName
* @return string
* @internal
*/
public function getPackageKeyFromComposerName($composerName)
{
$lowercasedComposerName = strtolower($composerName);
if (isset($this->packageAliasMap[$lowercasedComposerName])) {
return $this->packageAliasMap[$lowercasedComposerName];
}
if (isset($this->composerNameToPackageKeyMap[$lowercasedComposerName])) {
return $this->composerNameToPackageKeyMap[$lowercasedComposerName];
}
return $composerName;
}
/**
* Returns a PackageInterface object for the specified package.
* A package is available, if the package directory contains valid MetaData information.
*
* @param string $packageKey
* @return PackageInterface The requested package object
* @throws Exception\UnknownPackageException if the specified package is not known
*/
public function getPackage($packageKey)
{
if (!$this->isPackageRegistered($packageKey) && !$this->isPackageAvailable($packageKey)) {
throw new Exception\UnknownPackageException('Package "' . $packageKey . '" is not available. Please check if the package exists and that the package key is correct (package keys are case sensitive).', 1166546734);
}
return $this->packages[$packageKey];
}
/**
* Returns TRUE if a package is available (the package's files exist in the packages directory)
* or FALSE if it's not. If a package is available it doesn't mean necessarily that it's active!
*
* @param string $packageKey The key of the package to check
* @return bool TRUE if the package is available, otherwise FALSE
*/
public function isPackageAvailable($packageKey)
{
if ($this->isPackageRegistered($packageKey)) {
return true;
}
// If activePackages is empty, the PackageManager is currently initializing
// thus packages should not be scanned
if (!$this->availablePackagesScanned && !empty($this->activePackages)) {
$this->scanAvailablePackages();
}
return $this->isPackageRegistered($packageKey);
}
/**
* Returns TRUE if a package is activated or FALSE if it's not.
*
* @param string $packageKey The key of the package to check
* @return bool TRUE if package is active, otherwise FALSE
*/
public function isPackageActive($packageKey)
{
$packageKey = $this->getPackageKeyFromComposerName($packageKey);
return isset($this->runtimeActivatedPackages[$packageKey]) || isset($this->packageStatesConfiguration['packages'][$packageKey]);
}
/**
* Deactivates a package and updates the packagestates configuration
*
* @param string $packageKey
* @throws Exception\PackageStatesFileNotWritableException
* @throws Exception\ProtectedPackageKeyException
* @throws Exception\UnknownPackageException
* @internal
*/
public function deactivatePackage($packageKey)
{
$packagesWithDependencies = $this->sortActivePackagesByDependencies();
foreach ($packagesWithDependencies as $packageStateKey => $packageStateConfiguration) {
if ($packageKey === $packageStateKey || empty($packageStateConfiguration['dependencies'])) {
continue;
}
if (in_array($packageKey, $packageStateConfiguration['dependencies'], true)) {
$this->deactivatePackage($packageStateKey);
}
}
if (!$this->isPackageActive($packageKey)) {
return;
}
$package = $this->getPackage($packageKey);
if ($package->isProtected()) {
throw new Exception\ProtectedPackageKeyException('The package "' . $packageKey . '" is protected and cannot be deactivated.', 1308662891);
}
$this->activePackages = [];
unset($this->packageStatesConfiguration['packages'][$packageKey]);
$this->sortAndSavePackageStates();
}
/**
* @param string $packageKey
* @internal
*/
public function activatePackage($packageKey)
{
$package = $this->getPackage($packageKey);
$this->registerTransientClassLoadingInformationForPackage($package);
if ($this->isPackageActive($packageKey)) {
return;
}
$this->registerActivePackage($package);
$this->sortAndSavePackageStates();
}
/**
* Enables packages during runtime, but no class aliases will be available
*
* @param string $packageKey
*/
public function activatePackageDuringRuntime($packageKey)
{
$package = $this->registerPackageDuringRuntime($packageKey);
$this->runtimeActivatedPackages[$package->getPackageKey()] = $package;
$this->registerTransientClassLoadingInformationForPackage($package);
}
/**
* @param PackageInterface $package
* @throws \TYPO3\CMS\Core\Exception
*/
protected function registerTransientClassLoadingInformationForPackage(PackageInterface $package)
{
if (Environment::isComposerMode()) {
return;
}
ClassLoadingInformation::registerTransientClassLoadingInformationForPackage($package);
}
/**
* Removes a package from the file system.
*
* @param string $packageKey
* @throws Exception
* @throws Exception\ProtectedPackageKeyException
* @throws Exception\UnknownPackageException
* @internal
*/
public function deletePackage($packageKey)
{
if (!$this->isPackageAvailable($packageKey)) {
throw new Exception\UnknownPackageException('Package "' . $packageKey . '" is not available and cannot be removed.', 1166543253);
}
$package = $this->getPackage($packageKey);
if ($package->isProtected()) {
throw new Exception\ProtectedPackageKeyException('The package "' . $packageKey . '" is protected and cannot be removed.', 1220722120);
}
if ($this->isPackageActive($packageKey)) {
$this->deactivatePackage($packageKey);
}
$this->unregisterPackage($package);
$this->sortAndSavePackageStates();
$packagePath = $package->getPackagePath();
$deletion = GeneralUtility::rmdir($packagePath, true);
if ($deletion === false) {
throw new Exception('Please check file permissions. The directory "' . $packagePath . '" for package "' . $packageKey . '" could not be removed.', 1301491089);
}
}
/**
* Returns an array of \TYPO3\CMS\Core\Package objects of all active packages.
* A package is active, if it is available and has been activated in the package
* manager settings. This method returns runtime activated packages too
*
* @return PackageInterface[]
*/
public function getActivePackages()
{
if (empty($this->activePackages)) {
if (!empty($this->packageStatesConfiguration['packages'])) {
foreach ($this->packageStatesConfiguration['packages'] as $packageKey => $packageConfig) {
$this->activePackages[$packageKey] = $this->getPackage($packageKey);
}
}
}
return array_merge($this->activePackages, $this->runtimeActivatedPackages);
}
/**
* Returns TRUE if a package was already registered or FALSE if it's not.
*
* @param string $packageKey
* @return bool
*/
protected function isPackageRegistered($packageKey)
{
$packageKey = $this->getPackageKeyFromComposerName($packageKey);
return isset($this->packages[$packageKey]);
}
/**
* Orders all active packages by comparing their dependencies. By this, the packages
* and package configurations arrays holds all packages in the correct
* initialization order.
*
* @return array
*/
protected function sortActivePackagesByDependencies()
{
$packagesWithDependencies = $this->resolvePackageDependencies($this->packageStatesConfiguration['packages']);
// sort the packages by key at first, so we get a stable sorting of "equivalent" packages afterwards
ksort($packagesWithDependencies);
$sortedPackageKeys = $this->sortPackageStatesConfigurationByDependency($packagesWithDependencies);
// Reorder the packages according to the loading order
$this->packageStatesConfiguration['packages'] = [];
foreach ($sortedPackageKeys as $packageKey) {
$this->registerActivePackage($this->packages[$packageKey]);
}
return $packagesWithDependencies;
}
/**
* Resolves the dependent packages from the meta data of all packages recursively. The
* resolved direct or indirect dependencies of each package will put into the package
* states configuration array.
*
* @param $packageConfig
* @return array
*/
protected function resolvePackageDependencies($packageConfig)
{
$packagesWithDependencies = [];
foreach ($packageConfig as $packageKey => $_) {
$packagesWithDependencies[$packageKey]['dependencies'] = $this->getDependencyArrayForPackage($packageKey);
$packagesWithDependencies[$packageKey]['suggestions'] = $this->getSuggestionArrayForPackage($packageKey);
}
return $packagesWithDependencies;
}
/**
* Returns an array of suggested package keys for the given package.
*
* @param string $packageKey The package key to fetch the suggestions for
* @return array|null An array of directly suggested packages
*/
protected function getSuggestionArrayForPackage($packageKey)
{
if (!isset($this->packages[$packageKey])) {
return null;
}
$suggestedPackageKeys = [];
$suggestedPackageConstraints = $this->packages[$packageKey]->getPackageMetaData()->getConstraintsByType(MetaData::CONSTRAINT_TYPE_SUGGESTS);
foreach ($suggestedPackageConstraints as $constraint) {
if ($constraint instanceof MetaData\PackageConstraint) {
$suggestedPackageKey = $constraint->getValue();
if (isset($this->packages[$suggestedPackageKey])) {
$suggestedPackageKeys[] = $suggestedPackageKey;
}
}
}
return array_reverse($suggestedPackageKeys);
}
/**
* Saves the current content of $this->packageStatesConfiguration to the
* PackageStates.php file.
*
* @throws Exception\PackageStatesFileNotWritableException
*/
protected function savePackageStates()
{
$this->packageStatesConfiguration['version'] = 5;
$fileDescription = "# PackageStates.php\n\n";
$fileDescription .= "# This file is maintained by TYPO3's package management. Although you can edit it\n";
$fileDescription .= "# manually, you should rather use the extension manager for maintaining packages.\n";
$fileDescription .= "# This file will be regenerated automatically if it doesn't exist. Deleting this file\n";
$fileDescription .= "# should, however, never become necessary if you use the package commands.\n";
if (!@is_writable($this->packageStatesPathAndFilename)) {
// If file does not exist, try to create it
$fileHandle = @fopen($this->packageStatesPathAndFilename, 'x');
if (!$fileHandle) {
throw new Exception\PackageStatesFileNotWritableException(
sprintf('We could not update the list of installed packages because the file %s is not writable. Please, check the file system permissions for this file and make sure that the web server can update it.', $this->packageStatesPathAndFilename),
1382449759
);
}
fclose($fileHandle);
}
$packageStatesCode = "<?php\n$fileDescription\nreturn " . ArrayUtility::arrayExport($this->packageStatesConfiguration) . ";\n";
GeneralUtility::writeFile($this->packageStatesPathAndFilename, $packageStatesCode, true);
GeneralUtility::makeInstance(OpcodeCacheService::class)->clearAllActive($this->packageStatesPathAndFilename);
}
/**
* Saves the current content of $this->packageStatesConfiguration to the
* PackageStates.php file.
*
* @throws Exception\PackageStatesFileNotWritableException
*/
protected function sortAndSavePackageStates()
{
$this->sortActivePackagesByDependencies();
$this->savePackageStates();
}
/**
* Check the conformance of the given package key
*
* @param string $packageKey The package key to validate
* @return bool If the package key is valid, returns TRUE otherwise FALSE
*/
public function isPackageKeyValid($packageKey)
{
return preg_match(PackageInterface::PATTERN_MATCH_PACKAGEKEY, $packageKey) === 1 || preg_match(PackageInterface::PATTERN_MATCH_EXTENSIONKEY, $packageKey) === 1;
}
/**
* Returns an array of \TYPO3\CMS\Core\Package objects of all available packages.
* A package is available, if the package directory contains valid meta information.
*
* @return PackageInterface[] Array of PackageInterface
*/
public function getAvailablePackages()
{
if ($this->availablePackagesScanned === false) {
$this->scanAvailablePackages();
}
return $this->packages;
}
/**
* Unregisters a package from the list of available packages
*
* @param PackageInterface $package The package to be unregistered
* @throws Exception\InvalidPackageStateException
* @internal
*/
public function unregisterPackage(PackageInterface $package)
{
$packageKey = $package->getPackageKey();
if (!$this->isPackageRegistered($packageKey)) {
throw new Exception\InvalidPackageStateException('Package "' . $packageKey . '" is not registered.', 1338996142);
}
$this->unregisterPackageByPackageKey($packageKey);
}
/**
* Reloads a package and its information
*
* @param string $packageKey
* @throws Exception\InvalidPackageStateException if the package isn't available
* @internal
*/
public function reloadPackageInformation($packageKey)
{
if (!$this->isPackageRegistered($packageKey)) {
throw new Exception\InvalidPackageStateException('Package "' . $packageKey . '" is not registered.', 1436201329);
}
/** @var PackageInterface $package */
$package = $this->packages[$packageKey];
$packagePath = $package->getPackagePath();
$newPackage = new Package($this, $packageKey, $packagePath);
$this->packages[$packageKey] = $newPackage;
unset($package);
}
/**
* Returns contents of Composer manifest as a stdObject
*
* @param string $manifestPath
* @return \stdClass
* @throws Exception\InvalidPackageManifestException
* @internal
*/
public function getComposerManifest($manifestPath)
{
$composerManifest = null;
if (file_exists($manifestPath . 'composer.json')) {
$json = file_get_contents($manifestPath . 'composer.json');
$composerManifest = json_decode($json);
if (!$composerManifest instanceof \stdClass) {
throw new Exception\InvalidPackageManifestException('The composer.json found for extension "' . PathUtility::basename($manifestPath) . '" is invalid!', 1439555561);
}
}
$extensionManagerConfiguration = $this->getExtensionEmConf($manifestPath);
$composerManifest = $this->mapExtensionManagerConfigurationToComposerManifest(
PathUtility::basename($manifestPath),
$extensionManagerConfiguration,
$composerManifest ?: new \stdClass()
);
return $composerManifest;
}
/**
* Fetches MetaData information from ext_emconf.php, used for
* resolving dependencies as well.
*
* @param string $packagePath
* @return array
* @throws Exception\InvalidPackageManifestException
*/
protected function getExtensionEmConf($packagePath)
{
$packageKey = PathUtility::basename($packagePath);
$_EXTKEY = $packageKey;
$path = $packagePath . 'ext_emconf.php';
$EM_CONF = null;
if (@file_exists($path)) {
include $path;
if (is_array($EM_CONF[$_EXTKEY])) {
return $EM_CONF[$_EXTKEY];
}
}
throw new Exception\InvalidPackageManifestException('No valid ext_emconf.php file found for package "' . $packageKey . '".', 1360403545);
}
/**
* Fetches information from ext_emconf.php and maps it so it is treated as it would come from composer.json
*
* @param string $packageKey
* @param array $extensionManagerConfiguration
* @param \stdClass $composerManifest
* @return \stdClass
* @throws Exception\InvalidPackageManifestException
*/
protected function mapExtensionManagerConfigurationToComposerManifest($packageKey, array $extensionManagerConfiguration, \stdClass $composerManifest)
{
$this->setComposerManifestValueIfEmpty($composerManifest, 'name', $packageKey);
$this->setComposerManifestValueIfEmpty($composerManifest, 'type', 'typo3-cms-extension');
$this->setComposerManifestValueIfEmpty($composerManifest, 'description', $extensionManagerConfiguration['title'] ?? '');
$this->setComposerManifestValueIfEmpty($composerManifest, 'authors', [['name' => $extensionManagerConfiguration['author'] ?? '', 'email' => $extensionManagerConfiguration['author_email'] ?? '']]);
$composerManifest->version = $extensionManagerConfiguration['version'] ?? '';
if (isset($extensionManagerConfiguration['constraints']['depends']) && is_array($extensionManagerConfiguration['constraints']['depends'])) {
$composerManifest->require = new \stdClass();
foreach ($extensionManagerConfiguration['constraints']['depends'] as $requiredPackageKey => $requiredPackageVersion) {
if (!empty($requiredPackageKey)) {
if ($requiredPackageKey === 'typo3') {
// Add implicit dependency to 'core'
$composerManifest->require->core = $requiredPackageVersion;
} elseif ($requiredPackageKey !== 'php') {
// Skip php dependency
$composerManifest->require->{$requiredPackageKey} = $requiredPackageVersion;
}
} else {
throw new Exception\InvalidPackageManifestException(sprintf('The extension "%s" has invalid version constraints in depends section. Extension key is missing!', $packageKey), 1439552058);
}
}
}
if (isset($extensionManagerConfiguration['constraints']['conflicts']) && is_array($extensionManagerConfiguration['constraints']['conflicts'])) {
$composerManifest->conflict = new \stdClass();
foreach ($extensionManagerConfiguration['constraints']['conflicts'] as $conflictingPackageKey => $conflictingPackageVersion) {
if (!empty($conflictingPackageKey)) {
$composerManifest->conflict->$conflictingPackageKey = $conflictingPackageVersion;
} else {
throw new Exception\InvalidPackageManifestException(sprintf('The extension "%s" has invalid version constraints in conflicts section. Extension key is missing!', $packageKey), 1439552059);
}
}
}
if (isset($extensionManagerConfiguration['constraints']['suggests']) && is_array($extensionManagerConfiguration['constraints']['suggests'])) {
$composerManifest->suggest = new \stdClass();
foreach ($extensionManagerConfiguration['constraints']['suggests'] as $suggestedPackageKey => $suggestedPackageVersion) {
if (!empty($suggestedPackageKey)) {
$composerManifest->suggest->$suggestedPackageKey = $suggestedPackageVersion;
} else {
throw new Exception\InvalidPackageManifestException(sprintf('The extension "%s" has invalid version constraints in suggests section. Extension key is missing!', $packageKey), 1439552060);
}
}
}
if (isset($extensionManagerConfiguration['autoload'])) {
$composerManifest->autoload = json_decode(json_encode($extensionManagerConfiguration['autoload']));
}
// composer.json autoload-dev information must be discarded, as it may contain information only available after a composer install
unset($composerManifest->{'autoload-dev'});
if (isset($extensionManagerConfiguration['autoload-dev'])) {
$composerManifest->{'autoload-dev'} = json_decode(json_encode($extensionManagerConfiguration['autoload-dev']));
}
return $composerManifest;
}
/**
* @param \stdClass $manifest
* @param string $property
* @param mixed $value
* @return \stdClass
*/
protected function setComposerManifestValueIfEmpty(\stdClass $manifest, $property, $value)
{
if (empty($manifest->{$property})) {
$manifest->{$property} = $value;
}
return $manifest;
}
/**
* Returns an array of dependent package keys for the given package. It will
* do this recursively, so dependencies of dependent packages will also be
* in the result.
*
* @param string $packageKey The package key to fetch the dependencies for
* @param array $dependentPackageKeys
* @param array $trace An array of already visited package keys, to detect circular dependencies
* @return array|null An array of direct or indirect dependent packages
* @throws Exception\InvalidPackageKeyException
*/
protected function getDependencyArrayForPackage($packageKey, array &$dependentPackageKeys = [], array $trace = [])
{
if (!isset($this->packages[$packageKey])) {
return null;
}
if (in_array($packageKey, $trace, true) !== false) {
return $dependentPackageKeys;
}
$trace[] = $packageKey;
$dependentPackageConstraints = $this->packages[$packageKey]->getPackageMetaData()->getConstraintsByType(MetaData::CONSTRAINT_TYPE_DEPENDS);
foreach ($dependentPackageConstraints as $constraint) {
if ($constraint instanceof MetaData\PackageConstraint) {
$dependentPackageKey = $constraint->getValue();
if (in_array($dependentPackageKey, $dependentPackageKeys, true) === false && in_array($dependentPackageKey, $trace, true) === false) {
$dependentPackageKeys[] = $dependentPackageKey;
}
$this->getDependencyArrayForPackage($dependentPackageKey, $dependentPackageKeys, $trace);
}
}
return array_reverse($dependentPackageKeys);
}