-
Notifications
You must be signed in to change notification settings - Fork 638
/
Copy pathPlugins.php
1355 lines (1153 loc) · 45.4 KB
/
Plugins.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
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\services;
use Craft;
use craft\base\Plugin;
use craft\base\PluginInterface;
use craft\db\MigrationManager;
use craft\db\Query;
use craft\db\Table;
use craft\enums\LicenseKeyStatus;
use craft\errors\InvalidLicenseKeyException;
use craft\errors\InvalidPluginException;
use craft\events\PluginEvent;
use craft\helpers\App;
use craft\helpers\ArrayHelper;
use craft\helpers\DateTimeHelper;
use craft\helpers\Db;
use craft\helpers\FileHelper;
use craft\helpers\ProjectConfig as ProjectConfigHelper;
use craft\helpers\StringHelper;
use DateTime;
use ReflectionClass;
use ReflectionException;
use Throwable;
use yii\base\Component;
use yii\base\InvalidArgumentException;
use yii\helpers\Inflector;
use yii\web\HttpException;
/**
* The Plugins service provides APIs for managing plugins.
*
* An instance of the service is available via [[\craft\base\ApplicationTrait::getPlugins()|`Craft::$app->plugins`]].
*
* @author Pixel & Tonic, Inc. <[email protected]>
* @since 3.0.0
*/
class Plugins extends Component
{
/**
* @event \yii\base\Event The event that is triggered before any plugins have been loaded
*/
public const EVENT_BEFORE_LOAD_PLUGINS = 'beforeLoadPlugins';
/**
* @event \yii\base\Event The event that is triggered after all plugins have been loaded
*/
public const EVENT_AFTER_LOAD_PLUGINS = 'afterLoadPlugins';
/**
* @event PluginEvent The event that is triggered before a plugin is enabled
*/
public const EVENT_BEFORE_ENABLE_PLUGIN = 'beforeEnablePlugin';
/**
* @event PluginEvent The event that is triggered after a plugin is enabled
*/
public const EVENT_AFTER_ENABLE_PLUGIN = 'afterEnablePlugin';
/**
* @event PluginEvent The event that is triggered before a plugin is disabled
*/
public const EVENT_BEFORE_DISABLE_PLUGIN = 'beforeDisablePlugin';
/**
* @event PluginEvent The event that is triggered after a plugin is disabled
*/
public const EVENT_AFTER_DISABLE_PLUGIN = 'afterDisablePlugin';
/**
* @event PluginEvent The event that is triggered before a plugin is installed
*/
public const EVENT_BEFORE_INSTALL_PLUGIN = 'beforeInstallPlugin';
/**
* @event PluginEvent The event that is triggered after a plugin is installed
*/
public const EVENT_AFTER_INSTALL_PLUGIN = 'afterInstallPlugin';
/**
* @event PluginEvent The event that is triggered before a plugin is uninstalled
*/
public const EVENT_BEFORE_UNINSTALL_PLUGIN = 'beforeUninstallPlugin';
/**
* @event PluginEvent The event that is triggered after a plugin is uninstalled
*/
public const EVENT_AFTER_UNINSTALL_PLUGIN = 'afterUninstallPlugin';
/**
* @event PluginEvent The event that is triggered before a plugin’s settings are saved
*/
public const EVENT_BEFORE_SAVE_PLUGIN_SETTINGS = 'beforeSavePluginSettings';
/**
* @event PluginEvent The event that is triggered after a plugin’s settings are saved
*/
public const EVENT_AFTER_SAVE_PLUGIN_SETTINGS = 'afterSavePluginSettings';
/**
* @var array[] Custom plugin configurations.
* @since 3.4.0
*/
public array $pluginConfigs;
/**
* @var bool Whether plugins have been loaded yet for this request
*/
private bool $_pluginsLoaded = false;
/**
* @var bool Whether plugins are in the middle of being loaded
*/
private bool $_loadingPlugins = false;
/**
* @var PluginInterface[] All the enabled plugins, indexed by handles
*/
private array $_plugins = [];
/**
* @var array|null Plugin info provided by Composer, indexed by handles
*/
private ?array $_composerPluginInfo = null;
/**
* @var array All of the stored info for plugins (enabled or disabled), indexed by handles
* @see getStoredPluginInfo()
*/
private array $_storedPluginInfo;
/**
* @var string[]|string|null Any plugin handles that must be disabled per the `disablePlugins` config setting
*/
private string|array|null $_forceDisabledPlugins = null;
/**
* @var string[] Cache for [[getPluginHandleByClass()]]
*/
private array $_classPluginHandles = [];
/**
* @inheritdoc
*/
public function init(): void
{
$generalConfig = Craft::$app->getConfig()->getGeneral();
if ($generalConfig->safeMode) {
$this->_forceDisabledPlugins = '*';
} else {
$this->_forceDisabledPlugins = is_array($generalConfig->disabledPlugins) ? array_flip($generalConfig->disabledPlugins) : $generalConfig->disabledPlugins;
}
$this->_composerPluginInfo = [];
$path = Craft::$app->getVendorPath() . DIRECTORY_SEPARATOR . 'craftcms' . DIRECTORY_SEPARATOR . 'plugins.php';
if (file_exists($path)) {
/** @var array $plugins */
$plugins = require $path;
foreach ($plugins as $packageName => $plugin) {
$plugin['packageName'] = $packageName;
// Normalize the base path (and find the actual path, not a possibly-symlinked path)
if (isset($plugin['basePath'])) {
if (($basePath = realpath($plugin['basePath'])) !== false) {
$plugin['basePath'] = FileHelper::normalizePath($basePath);
} else {
Craft::warning("Invalid plugin base path: {$plugin['basePath']}", __METHOD__);
unset($plugin['basePath']);
}
}
$handle = $this->_normalizeHandle(ArrayHelper::remove($plugin, 'handle'));
$this->_composerPluginInfo[$handle] = $plugin;
}
}
}
/**
* Loads the enabled plugins.
*/
public function loadPlugins(): void
{
if ($this->_pluginsLoaded === true || $this->_loadingPlugins === true || Craft::$app->getIsInstalled() === false) {
return;
}
// Prevent this function from getting called twice.
$this->_loadingPlugins = true;
// Fire a 'beforeLoadPlugins' event
if ($this->hasEventHandlers(self::EVENT_BEFORE_LOAD_PLUGINS)) {
$this->trigger(self::EVENT_BEFORE_LOAD_PLUGINS);
}
// Find all of the installed plugins
$pluginInfo = $this->_createPluginQuery()
->orderBy(['handle' => SORT_ASC])
->indexBy('handle')
->all();
$this->_storedPluginInfo = [];
foreach ($pluginInfo as $handle => $row) {
try {
$configData = $this->_getPluginConfigData($handle);
} catch (InvalidPluginException) {
continue;
}
// Clean up the row data
$row['edition'] = $configData['edition'] ?? null;
$row['settings'] = $configData['settings'] ?? [];
$row['licenseKey'] = $configData['licenseKey'] ?? null;
$row['enabled'] = !empty($configData['enabled']);
$row['installDate'] = DateTimeHelper::toDateTime($row['installDate']);
$this->_storedPluginInfo[$handle] = $row;
}
foreach ($this->_storedPluginInfo as $handle => $row) {
// Skip disabled plugins
if (!$row['enabled']) {
continue;
}
try {
$plugin = $this->createPlugin($handle, $row);
} catch (InvalidPluginException) {
$plugin = null;
}
if ($plugin !== null) {
$hasVersionChanged = $this->hasPluginVersionNumberChanged($plugin);
// If the plugin’s version just changed, make sure the old version is >= the min allowed version
if (
$hasVersionChanged &&
isset($plugin->minVersionRequired) &&
$plugin->minVersionRequired &&
!str_starts_with($row['version'], 'dev-') &&
!str_ends_with($row['version'], '-dev') &&
version_compare($row['version'], $plugin->minVersionRequired, '<')
) {
throw new HttpException(200, Craft::t('app', 'You need to be on at least {plugin} {version} before you can update to {plugin} {targetVersion}.', [
'version' => $plugin->minVersionRequired,
'targetVersion' => $plugin->version,
'plugin' => $plugin->name,
]));
}
// If we're not updating, check if the plugin’s version number changed, but not its schema version.
if (!Craft::$app->getIsInMaintenanceMode() && $hasVersionChanged && !$this->isPluginUpdatePending($plugin)) {
// Update our record of the plugin’s version number
Db::update(Table::PLUGINS, [
'version' => $plugin->getVersion(),
], [
'id' => $row['id'],
]);
}
$this->_registerPlugin($plugin);
}
}
unset($row);
// Sort enabled plugins by their names
ArrayHelper::multisort($this->_plugins, 'name', SORT_ASC, SORT_NATURAL | SORT_FLAG_CASE);
$this->_loadingPlugins = false;
$this->_pluginsLoaded = true;
// Fire an 'afterLoadPlugins' event
if ($this->hasEventHandlers(self::EVENT_AFTER_LOAD_PLUGINS)) {
$this->trigger(self::EVENT_AFTER_LOAD_PLUGINS);
}
}
/**
* Returns whether plugins have been loaded yet for this request.
*
* @return bool
*/
public function arePluginsLoaded(): bool
{
return $this->_pluginsLoaded;
}
/**
* Returns an enabled plugin by its handle.
*
* @param string $handle The plugin’s handle
* @return PluginInterface|null The plugin, or null if it doesn’t exist
*/
public function getPlugin(string $handle): ?PluginInterface
{
$this->loadPlugins();
if (isset($this->_plugins[$handle])) {
return $this->_plugins[$handle];
}
return null;
}
/**
* Returns an enabled plugin by its package name.
*
* @param string $packageName The plugin’s package name
* @return PluginInterface|null The plugin, or null if it doesn’t exist
*/
public function getPluginByPackageName(string $packageName): ?PluginInterface
{
$this->loadPlugins();
foreach ($this->_plugins as $plugin) {
if ($plugin->packageName === $packageName) {
return $plugin;
}
}
return null;
}
/**
* Returns the plugin handle that contains the given class, if any.
*
* The plugin may not actually be installed.
*
* @param class-string $class
* @return string|null The plugin handle, or null if it can’t be determined
*/
public function getPluginHandleByClass(string $class): ?string
{
if (array_key_exists($class, $this->_classPluginHandles)) {
return $this->_classPluginHandles[$class];
}
// Figure out the path to the folder that contains this class
try {
// Add a trailing slash so we don't get false positives
$classPath = FileHelper::normalizePath(dirname((new ReflectionClass($class))->getFileName())) . DIRECTORY_SEPARATOR;
} catch (ReflectionException) {
return $this->_classPluginHandles[$class] = null;
}
// Find the plugin that contains this path (if any)
foreach ($this->_composerPluginInfo as $handle => $info) {
if (isset($info['basePath']) && str_starts_with($classPath, $info['basePath'] . DIRECTORY_SEPARATOR)) {
return $this->_classPluginHandles[$class] = $handle;
}
}
return $this->_classPluginHandles[$class] = null;
}
/**
* Returns all the enabled plugins.
*
* @return PluginInterface[]
*/
public function getAllPlugins(): array
{
$this->loadPlugins();
return $this->_plugins;
}
/**
* Enables a plugin by its handle.
*
* @param string $handle The plugin’s handle
* @return bool Whether the plugin was enabled successfully
* @throws InvalidPluginException if the plugin isn't installed
*/
public function enablePlugin(string $handle): bool
{
if ($this->isPluginEnabled($handle)) {
// It's already enabled
return true;
}
if (($info = $this->getStoredPluginInfo($handle)) === null) {
throw new InvalidPluginException($handle);
}
if (($plugin = $this->createPlugin($handle, $info)) === null) {
throw new InvalidPluginException($handle);
}
// Fire a 'beforeEnablePlugin' event
if ($this->hasEventHandlers(self::EVENT_BEFORE_ENABLE_PLUGIN)) {
$this->trigger(self::EVENT_BEFORE_ENABLE_PLUGIN, new PluginEvent([
'plugin' => $plugin,
]));
}
// Enable the plugin in the project config
Craft::$app->getProjectConfig()->set(ProjectConfig::PATH_PLUGINS . '.' . $handle . '.enabled', true, "Enable plugin “{$handle}”");
$this->_storedPluginInfo[$handle]['enabled'] = true;
$this->_registerPlugin($plugin);
// Fire an 'afterEnablePlugin' event
if ($this->hasEventHandlers(self::EVENT_AFTER_ENABLE_PLUGIN)) {
$this->trigger(self::EVENT_AFTER_ENABLE_PLUGIN, new PluginEvent([
'plugin' => $plugin,
]));
}
return true;
}
/**
* Disables a plugin by its handle.
*
* @param string $handle The plugin’s handle
* @return bool Whether the plugin was disabled successfully
* @throws InvalidPluginException if the plugin isn’t installed
*/
public function disablePlugin(string $handle): bool
{
if (!$this->isPluginInstalled($handle)) {
throw new InvalidPluginException($handle);
}
if (!$this->isPluginEnabled($handle)) {
// It's already disabled
return true;
}
if (($plugin = $this->getPlugin($handle)) === null) {
throw new InvalidPluginException($handle);
}
// Fire a 'beforeDisablePlugin' event
if ($this->hasEventHandlers(self::EVENT_BEFORE_DISABLE_PLUGIN)) {
$this->trigger(self::EVENT_BEFORE_DISABLE_PLUGIN, new PluginEvent([
'plugin' => $plugin,
]));
}
// Disable the plugin in the project config
Craft::$app->getProjectConfig()->set(ProjectConfig::PATH_PLUGINS . '.' . $handle . '.enabled', false, "Disable plugin “{$handle}”");
$this->_storedPluginInfo[$handle]['enabled'] = false;
$this->_unregisterPlugin($plugin);
// Fire an 'afterDisablePlugin' event
if ($this->hasEventHandlers(self::EVENT_AFTER_DISABLE_PLUGIN)) {
$this->trigger(self::EVENT_AFTER_DISABLE_PLUGIN, new PluginEvent([
'plugin' => $plugin,
]));
}
return true;
}
/**
* Installs a plugin by its handle.
*
* @param string $handle The plugin’s handle
* @param string|null $edition The plugin’s edition
* @return bool Whether the plugin was installed successfully.
* @throws InvalidPluginException if the plugin doesn’t exist
* @throws Throwable if reasons
*/
public function installPlugin(string $handle, ?string $edition = null): bool
{
$this->loadPlugins();
if ($this->getStoredPluginInfo($handle) !== null) {
// It's already installed
return true;
}
// Temporarily allow changes to the project config even if it's supposed to be read only
$projectConfig = Craft::$app->getProjectConfig();
$readOnly = $projectConfig->readOnly;
$projectConfig->readOnly = false;
$configKey = ProjectConfig::PATH_PLUGINS . '.' . $handle;
$plugin = $this->createPlugin($handle);
if ($plugin === null) {
throw new InvalidPluginException($handle);
}
// Set the edition
if ($edition === null) {
// See if one is already set in the project config
$edition = $projectConfig->get($configKey . '.edition');
}
$editions = $plugin::editions();
if ($edition === null || !in_array($edition, $editions, true)) {
$edition = reset($editions);
}
$plugin->edition = $edition;
// Fire a 'beforeInstallPlugin' event
if ($this->hasEventHandlers(self::EVENT_BEFORE_INSTALL_PLUGIN)) {
$this->trigger(self::EVENT_BEFORE_INSTALL_PLUGIN, new PluginEvent([
'plugin' => $plugin,
]));
}
$db = Craft::$app->getDb();
$transaction = $db->beginTransaction();
try {
$info = [
'handle' => $handle,
'version' => $plugin->getVersion(),
'schemaVersion' => $plugin->schemaVersion,
'installDate' => Db::prepareDateForDb(new DateTime()),
];
// Make sure the plugin doesn't have a row in the `plugins` or `migrations` tables first, just in case
Db::delete(Table::PLUGINS, [
'handle' => $handle,
]);
Db::delete(Table::MIGRATIONS, [
'track' => "plugin:$handle",
]);
Db::insert(Table::PLUGINS, $info);
$info['enabled'] = $projectConfig->get($configKey . '.enabled') ?? true;
$info['installDate'] = DateTimeHelper::toDateTime($info['installDate']);
$info['id'] = $db->getLastInsertID(Table::PLUGINS);
$this->_setPluginMigrator($plugin);
$plugin->install();
$transaction->commit();
} catch (Throwable $e) {
$transaction->rollBack();
if ($db->getIsMysql()) {
// Explicitly remove the plugins row just in case the transaction was implicitly committed
Db::delete(Table::PLUGINS, [
'handle' => $handle,
]);
}
throw $e;
}
// Add the plugin to the project config
$pluginData = [
'edition' => $edition,
'enabled' => true,
'schemaVersion' => $plugin->schemaVersion,
];
$projectConfig->set($configKey, $pluginData, "Install plugin “{$handle}”");
$this->_storedPluginInfo[$handle] = $info;
$this->_registerPlugin($plugin);
// Fire an 'afterInstallPlugin' event
if ($this->hasEventHandlers(self::EVENT_AFTER_INSTALL_PLUGIN)) {
$this->trigger(self::EVENT_AFTER_INSTALL_PLUGIN, new PluginEvent([
'plugin' => $plugin,
]));
}
$projectConfig->readOnly = $readOnly;
return true;
}
/**
* Uninstalls a plugin by its handle.
*
* @param string $handle The plugin’s handle
* @param bool $force Whether to force the plugin uninstallation, even if it is disabled, its
* `uninstall()` method returns `false`, or its files aren’t present
* @return bool Whether the plugin was uninstalled successfully
* @throws InvalidPluginException if the plugin doesn’t exist
* @throws Throwable if reasons
*/
public function uninstallPlugin(string $handle, bool $force = false): bool
{
$this->loadPlugins();
if (!$this->isPluginInstalled($handle)) {
// It's already uninstalled
return true;
}
$enabled = $this->isPluginEnabled($handle);
if (!$enabled && !$force) {
// Don't allow uninstalling disabled plugins, because that could be buggy
// if the plugin was composer-updated while disabled, and its uninstall()
// function is out of sync with what's actually in the database
throw new InvalidPluginException($handle, 'Uninstalling disabled plugins is not allowed.');
}
// Temporarily allow changes to the project config even if it's supposed to be read only
$projectConfig = Craft::$app->getProjectConfig();
$readOnly = $projectConfig->readOnly;
$projectConfig->readOnly = false;
if (($plugin = $this->getPlugin($handle)) === null && !$force) {
throw new InvalidPluginException($handle);
}
// Fire a 'beforeUninstallPlugin' event
if ($plugin && $this->hasEventHandlers(self::EVENT_BEFORE_UNINSTALL_PLUGIN)) {
$this->trigger(self::EVENT_BEFORE_UNINSTALL_PLUGIN, new PluginEvent([
'plugin' => $plugin,
]));
}
$transaction = Craft::$app->getDb()->beginTransaction();
try {
// Let the plugin uninstall itself first
if ($plugin && $enabled) {
try {
$plugin->uninstall();
} catch (Throwable $e) {
if (!$force) {
throw $e;
}
}
}
// Clean up the plugins and migrations tables
$info = $this->getStoredPluginInfo($handle);
if ($info !== null) {
Db::delete(Table::PLUGINS, [
'id' => $info['id'],
]);
}
Db::delete(Table::MIGRATIONS, [
'track' => "plugin:$handle",
]);
$transaction->commit();
} catch (Throwable $e) {
$transaction->rollBack();
throw $e;
}
// Remove the plugin from the project config
if ($projectConfig->get(ProjectConfig::PATH_PLUGINS . '.' . $handle, true)) {
$projectConfig->remove(ProjectConfig::PATH_PLUGINS . '.' . $handle, "Uninstall the “{$handle}” plugin");
}
if ($plugin) {
$this->_unregisterPlugin($plugin);
}
unset($this->_storedPluginInfo[$handle]);
// Fire an 'afterUninstallPlugin' event
if ($plugin && $this->hasEventHandlers(self::EVENT_AFTER_UNINSTALL_PLUGIN)) {
$this->trigger(self::EVENT_AFTER_UNINSTALL_PLUGIN, new PluginEvent([
'plugin' => $plugin,
]));
}
$projectConfig->readOnly = $readOnly;
return true;
}
/**
* Switches a plugin’s edition.
*
* @param string $handle The plugin’s handle
* @param string $edition The plugin’s edition
* @throws InvalidPluginException if the plugin doesn’t exist
* @throws InvalidArgumentException if $edition is invalid
* @throws Throwable if reasons
*/
public function switchEdition(string $handle, string $edition): void
{
$info = $this->getPluginInfo($handle);
/** @var class-string<PluginInterface> $class */
$class = $info['class'];
if (!in_array($edition, $class::editions(), true)) {
throw new InvalidArgumentException('Invalid plugin edition: ' . $edition);
}
// Update the project config
Craft::$app->getProjectConfig()->set(ProjectConfig::PATH_PLUGINS . '.' . $handle . '.edition', $edition, "Switch edition for plugin “{$handle}”");
if (isset($this->_storedPluginInfo[$handle])) {
$this->_storedPluginInfo[$handle]['edition'] = $edition;
}
// If it's installed, update the instance and our locally stored info
$plugin = $this->getPlugin($handle);
if ($plugin !== null) {
$plugin->edition = $edition;
}
}
/**
* Saves a plugin’s settings.
*
* @param PluginInterface $plugin The plugin
* @param array $settings The plugin’s new settings
* @return bool Whether the plugin’s settings were saved successfully
*/
public function savePluginSettings(PluginInterface $plugin, array $settings): bool
{
// Save the settings on the plugin
$plugin->getSettings()->setAttributes($settings, false);
// Validate them, now that it's a model
if ($plugin->getSettings()->validate() === false) {
return false;
}
// Fire a 'beforeSavePluginSettings' event
if ($this->hasEventHandlers(self::EVENT_BEFORE_SAVE_PLUGIN_SETTINGS)) {
$this->trigger(self::EVENT_BEFORE_SAVE_PLUGIN_SETTINGS, new PluginEvent([
'plugin' => $plugin,
]));
}
if (!$plugin->beforeSaveSettings()) {
return false;
}
// Update the plugin’s settings in the project config
$pluginSettings = $plugin->getSettings();
$pluginSettings = $pluginSettings ? ProjectConfigHelper::packAssociativeArrays($pluginSettings->toArray()) : [];
Craft::$app->getProjectConfig()->set(ProjectConfig::PATH_PLUGINS . '.' . $plugin->handle . '.settings', $pluginSettings, "Change settings for plugin “{$plugin->handle}”");
$plugin->afterSaveSettings();
// Fire an 'afterSavePluginSettings' event
if ($this->hasEventHandlers(self::EVENT_AFTER_SAVE_PLUGIN_SETTINGS)) {
$this->trigger(self::EVENT_AFTER_SAVE_PLUGIN_SETTINGS, new PluginEvent([
'plugin' => $plugin,
]));
}
return true;
}
/**
* Returns whether the given plugin’s version number has changed from what we have recorded in the database.
*
* @param PluginInterface $plugin The plugin
* @return bool Whether the plugin’s version number has changed from what we have recorded in the database
*/
public function hasPluginVersionNumberChanged(PluginInterface $plugin): bool
{
$this->loadPlugins();
if (($info = $this->getStoredPluginInfo($plugin->id)) === null) {
return false;
}
return $plugin->getVersion() !== $info['version'];
}
/**
* Returns whether the given plugin’s local schema version is greater than the record we have in the database.
*
* @param PluginInterface $plugin The plugin
* @return bool Whether the plugin’s local schema version is greater than the record we have in the database
* @since 4.0.0
*/
public function isPluginUpdatePending(PluginInterface $plugin): bool
{
$this->loadPlugins();
if (($info = $this->getStoredPluginInfo($plugin->id)) === null) {
return false;
}
return version_compare($plugin->schemaVersion, $info['schemaVersion'], '>');
}
/**
* Returns whether a given plugin is installed (even if it's disabled).
*
* @param string $handle The plugin handle
* @return bool
*/
public function isPluginInstalled(string $handle): bool
{
$this->loadPlugins();
return isset($this->_storedPluginInfo[$handle]);
}
/**
* Returns whether a given plugin is installed and enabled.
*
* @param string $handle The plugin handle
* @return bool
*/
public function isPluginEnabled(string $handle): bool
{
$this->loadPlugins();
return $this->_storedPluginInfo[$handle]['enabled'] ?? false;
}
/**
* Returns whether a given plugin is installed but disabled.
*
* @param string $handle The plugin handle
* @return bool
*/
public function isPluginDisabled(string $handle): bool
{
return !$this->isPluginEnabled($handle) && $this->isPluginInstalled($handle);
}
/**
* Returns the stored info for a given plugin.
*
* @param string $handle The plugin handle
* @return array|null The stored info, if there is any
*/
public function getStoredPluginInfo(string $handle): ?array
{
$this->loadPlugins();
return $this->_storedPluginInfo[$handle] ?? null;
}
/**
* Updates a plugin’s stored version & schema version to match what’s Composer-installed.
*
* @param PluginInterface $plugin
* @since 3.7.13
*/
public function updatePluginVersionInfo(PluginInterface $plugin): void
{
Db::update(Table::PLUGINS, [
'version' => $plugin->getVersion(),
'schemaVersion' => $plugin->schemaVersion,
], [
'handle' => $plugin->id,
]);
// Update our cache of the versions
$this->loadPlugins();
if (isset($this->_storedPluginInfo[$plugin->id])) {
$this->_storedPluginInfo[$plugin->id]['version'] = $plugin->getVersion();
$this->_storedPluginInfo[$plugin->id]['schemaVersion'] = $plugin->schemaVersion;
}
// Only update the schema version if it's changed from what's in the file,
// so we don't accidentally overwrite other pending changes
$projectConfig = Craft::$app->getProjectConfig();
$key = ProjectConfig::PATH_PLUGINS . ".$plugin->id.schemaVersion";
if ($projectConfig->get($key, true) !== $plugin->schemaVersion) {
Craft::$app->getProjectConfig()->set($key, $plugin->schemaVersion, "Update plugin schema version for “{$plugin->handle}”");
}
}
/**
* Returns the Composer-supplied info
*
* @param string|null $handle The plugin handle. If null is passed, info for all Composer-installed plugins will be returned.
* @return array|null The plugin info, or null if an unknown handle was passed.
*/
public function getComposerPluginInfo(?string $handle = null): ?array
{
if ($handle === null) {
return $this->_composerPluginInfo;
}
return $this->_composerPluginInfo[$handle] ?? null;
}
/**
* Creates and returns a new plugin instance based on its handle.
*
* @param string $handle The plugin’s handle
* @param array|null $info The plugin’s stored info, if any
* @return PluginInterface|null
* @throws InvalidPluginException if $handle is invalid
*/
public function createPlugin(string $handle, ?array $info = null): ?PluginInterface
{
if (!isset($this->_composerPluginInfo[$handle])) {
throw new InvalidPluginException($handle);
}
$config = $this->_composerPluginInfo[$handle];
if (isset($config['aliases'])) {
foreach ($config['aliases'] as $alias => $path) {
Craft::setAlias($alias, $path);
}
// Unset them so we don't end up calling Module::setAliases()
unset($config['aliases']);
}
/** @var class-string<PluginInterface> $class */
$class = $config['class'];
// Make sure the class exists and it implements PluginInterface
if (!is_subclass_of($class, PluginInterface::class)) {
return null;
}
// Merge in the plugin’s dynamic config
$config = ArrayHelper::merge($config, $class::config());
// Is it installed?
if ($info !== null) {
$config['isInstalled'] = true;
// Set the edition
$config['edition'] = $info['edition'] ?? 'standard';
$editions = $class::editions();
if (!in_array($config['edition'], $editions, true)) {
$config['edition'] = reset($editions);
}
$settings = array_merge(
$info['settings'] ?? [],
Craft::$app->getConfig()->getConfigFromFile($handle)
);
if ($settings !== []) {
$config['settings'] = $settings;
}
// Merge in the custom config, if there is one
if (isset($this->pluginConfigs[$handle])) {
$config = ArrayHelper::merge($config, $this->pluginConfigs[$handle]);
}
}
// Create the plugin
/** @var Plugin $plugin */
$plugin = Craft::createObject($config, [$handle, Craft::$app]);
$this->_setPluginMigrator($plugin);
return $plugin;
}
/**
* Returns info about all of the plugins we can find, whether they’re installed or not.
*
* @return array
*/
public function getAllPluginInfo(): array
{
$this->loadPlugins();
// Get the info arrays
$info = [];
foreach (array_keys($this->_composerPluginInfo) as $handle) {
$info[$handle] = $this->getPluginInfo($handle);
}
// Sort plugins by their names
ArrayHelper::multisort($info, 'name', SORT_ASC, SORT_NATURAL | SORT_FLAG_CASE);
return $info;
}
/**
* Returns info about a plugin, whether it's installed or not.
*
* @param string $handle The plugin’s handle
* @return array
* @throws InvalidPluginException if the plugin isn't Composer-installed
*/
public function getPluginInfo(string $handle): array
{
if (!isset($this->_composerPluginInfo[$handle])) {
throw new InvalidPluginException($handle);
}
$pluginInfo = $this->getStoredPluginInfo($handle);
// Get the plugin if it's enabled
$plugin = $this->getPlugin($handle);
$info = array_merge([
'developer' => null,
'developerUrl' => null,
'description' => null,
'documentationUrl' => null,
], $this->_composerPluginInfo[$handle]);
$edition = $pluginInfo['edition'] ?? 'standard';
if ($plugin) {
$editions = $plugin::editions();
if (!in_array($edition, $editions, true)) {