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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
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
1293
|
<?php
/**
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*
*/
namespace Piwik\Plugin;
use Piwik\Common;
use Piwik\Config as PiwikConfig;
use Piwik\Config;
use Piwik\Db;
use Piwik\EventDispatcher;
use Piwik\Filesystem;
use Piwik\Option;
use Piwik\Plugin;
use Piwik\Singleton;
use Piwik\Theme;
use Piwik\Tracker;
use Piwik\Translate;
use Piwik\Updater;
use Piwik\Plugin\Dimension\ActionDimension;
use Piwik\Plugin\Dimension\ConversionDimension;
use Piwik\Plugin\Dimension\VisitDimension;
require_once PIWIK_INCLUDE_PATH . '/core/EventDispatcher.php';
/**
* The singleton that manages plugin loading/unloading and installation/uninstallation.
*
* @method static \Piwik\Plugin\Manager getInstance()
*/
class Manager extends Singleton
{
protected $pluginsToLoad = array();
protected $doLoadPlugins = true;
/**
* @var Plugin[]
*/
protected $loadedPlugins = array();
/**
* Default theme used in Piwik.
*/
const DEFAULT_THEME = "Morpheus";
protected $doLoadAlwaysActivatedPlugins = true;
// These are always activated and cannot be deactivated
protected $pluginToAlwaysActivate = array(
'CoreHome',
'CoreUpdater',
'CoreAdminHome',
'CoreConsole',
'CorePluginsAdmin',
'CoreVisualizations',
'Installation',
'SitesManager',
'UsersManager',
'API',
'Proxy',
'LanguagesManager',
// default Piwik theme, always enabled
self::DEFAULT_THEME,
);
// Plugins bundled with core package, disabled by default
protected $corePluginsDisabledByDefault = array(
'DBStats',
'ExampleCommand',
'ExampleSettingsPlugin',
'ExampleUI',
'ExampleVisualization',
'ExamplePluginTemplate',
);
// Themes bundled with core package, disabled by default
protected $coreThemesDisabledByDefault = array(
'ExampleTheme'
);
/**
* Loads plugin that are enabled
*/
public function loadActivatedPlugins()
{
$pluginsToLoad = Config::getInstance()->Plugins['Plugins'];
$this->loadPlugins($pluginsToLoad);
}
/**
* Called during Tracker
*/
public function loadCorePluginsDuringTracker()
{
$pluginsToLoad = Config::getInstance()->Plugins['Plugins'];
$pluginsToLoad = array_diff($pluginsToLoad, Tracker::getPluginsNotToLoad());
$this->loadPlugins($pluginsToLoad);
}
/**
* @return array names of plugins that have been loaded
*/
public function loadTrackerPlugins()
{
$this->unloadPlugins();
$pluginsTracker = PiwikConfig::getInstance()->Plugins_Tracker['Plugins_Tracker'];
if (empty($pluginsTracker)) {
return array();
}
$pluginsTracker = array_diff($pluginsTracker, Tracker::getPluginsNotToLoad());
$this->doNotLoadAlwaysActivatedPlugins();
$this->loadPlugins($pluginsTracker);
return $pluginsTracker;
}
public function getCorePluginsDisabledByDefault()
{
return array_merge( $this->corePluginsDisabledByDefault, $this->coreThemesDisabledByDefault);
}
// If a plugin hooks onto at least an event starting with "Tracker.", we load the plugin during tracker
const TRACKER_EVENT_PREFIX = 'Tracker.';
/**
* @param $pluginName
* @return bool
*/
public function isPluginOfficialAndNotBundledWithCore($pluginName)
{
static $gitModules;
if(empty($gitModules)) {
$gitModules = file_get_contents(PIWIK_INCLUDE_PATH . '/.gitmodules');
}
// All submodules are officially maintained plugins
$isSubmodule = false !== strpos($gitModules, "plugins/" . $pluginName . "\n");
return $isSubmodule;
}
/**
* Update Plugins config
*
* @param array $plugins Plugins
*/
private function updatePluginsConfig($pluginsToLoad)
{
$section = PiwikConfig::getInstance()->Plugins;
$section['Plugins'] = $pluginsToLoad;
PiwikConfig::getInstance()->Plugins = $section;
}
/**
* Update Plugins_Tracker config
*
* @param array $plugins Plugins
*/
private function updatePluginsTrackerConfig($plugins)
{
$section = PiwikConfig::getInstance()->Plugins_Tracker;
$section['Plugins_Tracker'] = $plugins;
PiwikConfig::getInstance()->Plugins_Tracker = $section;
}
/**
* Update PluginsInstalled config
*
* @param array $plugins Plugins
*/
private function updatePluginsInstalledConfig($plugins)
{
$section = PiwikConfig::getInstance()->PluginsInstalled;
$section['PluginsInstalled'] = $plugins;
PiwikConfig::getInstance()->PluginsInstalled = $section;
}
public function clearPluginsInstalledConfig()
{
$this->updatePluginsInstalledConfig( array() );
PiwikConfig::getInstance()->forceSave();
PiwikConfig::getInstance()->init();
}
/**
* Returns true if plugin is always activated
*
* @param string $name Name of plugin
* @return bool
*/
private function isPluginAlwaysActivated($name)
{
return in_array($name, $this->pluginToAlwaysActivate);
}
/**
* Returns true if the plugin can be uninstalled. Any non-core plugin can be uninstalled.
*
* @param $name
* @return bool
*/
private function isPluginUninstallable($name)
{
return !$this->isPluginBundledWithCore($name);
}
/**
* Returns `true` if a plugin has been activated.
*
* @param string $name Name of plugin, eg, `'Actions'`.
* @return bool
* @api
*/
public function isPluginActivated($name)
{
return in_array($name, $this->pluginsToLoad)
|| $this->isPluginAlwaysActivated($name);
}
/**
* Returns `true` if plugin is loaded (in memory).
*
* @param string $name Name of plugin, eg, `'Acions'`.
* @return bool
* @api
*/
public function isPluginLoaded($name)
{
return isset($this->loadedPlugins[$name]);
}
/**
* Reads the directories inside the plugins/ directory and returns their names in an array
*
* @return array
*/
public function readPluginsDirectory()
{
$pluginsName = _glob(self::getPluginsDirectory() . '*', GLOB_ONLYDIR);
$result = array();
if ($pluginsName != false) {
foreach ($pluginsName as $path) {
if (self::pluginStructureLooksValid($path)) {
$result[] = basename($path);
}
}
}
return $result;
}
public static function getPluginsDirectory()
{
return PIWIK_INCLUDE_PATH . '/plugins/';
}
/**
* Deactivate plugin
*
* @param string $pluginName Name of plugin
*/
public function deactivatePlugin($pluginName)
{
// execute deactivate() to let the plugin do cleanups
$this->executePluginDeactivate($pluginName);
$this->unloadPluginFromMemory($pluginName);
$this->removePluginFromConfig($pluginName);
$this->clearCache($pluginName);
}
/**
* Tries to find the given components such as a Menu or Tasks implemented by plugins.
* This method won't cache the found components. If you need to find the same component multiple times you might
* want to cache the result to save a tiny bit of time.
*
* @param string $componentName The name of the component you want to look for. In case you request a
* component named 'Menu' it'll look for a file named 'Menu.php' within the
* root of all plugin folders that implement a class named
* Piwik\Plugin\$PluginName\Menu.
* @param string $expectedSubclass If not empty, a check will be performed whether a found file extends the
* given subclass. If the requested file exists but does not extend this class
* a warning will be shown to advice a developer to extend this certain class.
*
* @return \stdClass[]
*/
public function findComponents($componentName, $expectedSubclass)
{
$plugins = $this->getLoadedPlugins();
$components = array();
foreach ($plugins as $plugin) {
$component = $plugin->findComponent($componentName, $expectedSubclass);
if (!empty($component)) {
$components[] = $component;
}
}
return $components;
}
public function findMultipleComponents($directoryWithinPlugin, $expectedSubclass)
{
$plugins = $this->getLoadedPlugins();
$found = array();
foreach ($plugins as $plugin) {
$components = $plugin->findMultipleComponents($directoryWithinPlugin, $expectedSubclass);
if (!empty($components)) {
$found = array_merge($found, $components);
}
}
return $found;
}
/**
* Uninstalls a Plugin (deletes plugin files from the disk)
* Only deactivated plugins can be uninstalled
*
* @param $pluginName
* @throws \Exception
* @return bool
*/
public function uninstallPlugin($pluginName)
{
if ($this->isPluginLoaded($pluginName)) {
throw new \Exception("To uninstall the plugin $pluginName, first disable it in Piwik > Settings > Plugins");
}
$this->returnLoadedPluginsInfo();
$this->executePluginDeactivate($pluginName);
$this->executePluginUninstall($pluginName);
$this->removePluginFromPluginsInstalledConfig($pluginName);
$this->unloadPluginFromMemory($pluginName);
$this->removePluginFromConfig($pluginName);
Option::delete('version_' . $pluginName);
\Piwik\Settings\Manager::cleanupPluginSettings($pluginName);
$this->clearCache($pluginName);
self::deletePluginFromFilesystem($pluginName);
if ($this->isPluginInFilesystem($pluginName)) {
return false;
}
return true;
}
/**
* @param string $pluginName
*/
private function clearCache($pluginName)
{
Filesystem::deleteAllCacheOnUpdate($pluginName);
}
public static function deletePluginFromFilesystem($plugin)
{
Filesystem::unlinkRecursive(PIWIK_INCLUDE_PATH . '/plugins/' . $plugin, $deleteRootToo = true);
}
/**
* Install loaded plugins
*
* @throws
* @return array Error messages of plugin install fails
*/
public function installLoadedPlugins()
{
$messages = array();
foreach ($this->getLoadedPlugins() as $plugin) {
try {
$this->installPluginIfNecessary($plugin);
} catch (\Exception $e) {
$messages[] = $e->getMessage();
}
}
return $messages;
}
/**
* Activate the specified plugin and install (if needed)
*
* @param string $pluginName Name of plugin
* @throws \Exception
*/
public function activatePlugin($pluginName)
{
$plugins = PiwikConfig::getInstance()->Plugins['Plugins'];
if (in_array($pluginName, $plugins)) {
throw new \Exception("Plugin '$pluginName' already activated.");
}
if (!$this->isPluginInFilesystem($pluginName)) {
throw new \Exception("Plugin '$pluginName' cannot be found in the filesystem in plugins/ directory.");
}
$this->deactivateThemeIfTheme($pluginName);
// Load plugin
$plugin = $this->loadPlugin($pluginName);
if ($plugin === null) {
throw new \Exception("The plugin '$pluginName' was found in the filesystem, but could not be loaded.'");
}
$this->installPluginIfNecessary($plugin);
$plugin->activate();
EventDispatcher::getInstance()->postPendingEventsTo($plugin);
$this->pluginsToLoad[] = $pluginName;
$this->updatePluginsConfig($this->pluginsToLoad);
PiwikConfig::getInstance()->forceSave();
$this->clearCache($pluginName);
}
protected function isPluginInFilesystem($pluginName)
{
$existingPlugins = $this->readPluginsDirectory();
$isPluginInFilesystem = array_search($pluginName, $existingPlugins) !== false;
return Filesystem::isValidFilename($pluginName)
&& $isPluginInFilesystem;
}
/**
* Returns the currently enabled theme.
*
* If no theme is enabled, the **Morpheus** plugin is returned (this is the base and default theme).
*
* @return Plugin
* @api
*/
public function getThemeEnabled()
{
$plugins = $this->getLoadedPlugins();
$theme = false;
foreach ($plugins as $plugin) {
/* @var $plugin Plugin */
if ($plugin->isTheme()
&& $this->isPluginActivated($plugin->getPluginName())
) {
if ($plugin->getPluginName() != self::DEFAULT_THEME) {
return $plugin; // enabled theme (not default)
}
$theme = $plugin; // default theme
}
}
return $theme;
}
/**
* @param string $themeName
* @throws \Exception
* @return Theme
*/
public function getTheme($themeName)
{
$plugins = $this->getLoadedPlugins();
foreach ($plugins as $plugin) {
if ($plugin->isTheme() && $plugin->getPluginName() == $themeName) {
return new Theme($plugin);
}
}
throw new \Exception('Theme not found : ' . $themeName);
}
public function getNumberOfActivatedPlugins()
{
$counter = 0;
$pluginNames = $this->getLoadedPluginsName();
foreach ($pluginNames as $pluginName) {
if ($this->isPluginActivated($pluginName)) {
$counter++;
}
}
return $counter;
}
/**
* Returns info regarding all plugins. Loads plugins that can be loaded.
*
* @return array An array that maps plugin names with arrays of plugin information. Plugin
* information consists of the following entries:
*
* - **activated**: Whether the plugin is activated.
* - **alwaysActivated**: Whether the plugin should always be activated,
* or not.
* - **uninstallable**: Whether the plugin is uninstallable or not.
* - **invalid**: If the plugin is invalid, this property will be set to true.
* If the plugin is not invalid, this property will not exist.
* - **info**: If the plugin was loaded, will hold the plugin information.
* See {@link Piwik\Plugin::getInformation()}.
* @api
*/
public function returnLoadedPluginsInfo()
{
$language = Translate::getLanguageToLoad();
$plugins = array();
$listPlugins = array_merge(
$this->readPluginsDirectory(),
PiwikConfig::getInstance()->Plugins['Plugins']
);
$listPlugins = array_unique($listPlugins);
foreach ($listPlugins as $pluginName) {
// Hide plugins that are never going to be used
if($this->isPluginBogus($pluginName)) {
continue;
}
// If the plugin is not core and looks bogus, do not load
if ($this->isPluginThirdPartyAndBogus($pluginName)) {
$info = array(
'invalid' => true,
'activated' => false,
'alwaysActivated' => false,
'uninstallable' => true,
);
} else {
$this->loadTranslation($pluginName, $language);
$this->loadPlugin($pluginName);
$info = array(
'activated' => $this->isPluginActivated($pluginName),
'alwaysActivated' => $this->isPluginAlwaysActivated($pluginName),
'uninstallable' => $this->isPluginUninstallable($pluginName),
);
}
$plugins[$pluginName] = $info;
}
$this->loadPluginTranslations();
$loadedPlugins = $this->getLoadedPlugins();
foreach ($loadedPlugins as $oPlugin) {
$pluginName = $oPlugin->getPluginName();
$info = array(
'info' => $oPlugin->getInformation(),
'activated' => $this->isPluginActivated($pluginName),
'alwaysActivated' => $this->isPluginAlwaysActivated($pluginName),
'missingRequirements' => $oPlugin->getMissingDependencies(),
'uninstallable' => $this->isPluginUninstallable($pluginName),
);
$plugins[$pluginName] = $info;
}
return $plugins;
}
protected static function isManifestFileFound($path)
{
return file_exists($path . "/" . MetadataLoader::PLUGIN_JSON_FILENAME);
}
/**
* Returns `true` if the plugin is bundled with core or `false` if it is third party.
*
* @param string $name The name of the plugin, eg, `'Actions'`.
* @return bool
*/
public function isPluginBundledWithCore($name)
{
// Reading the plugins from the global.ini.php config file
$pluginsBundledWithPiwik = PiwikConfig::getInstance()->getFromGlobalConfig('Plugins');
$pluginsBundledWithPiwik = $pluginsBundledWithPiwik['Plugins'];
return (!empty($pluginsBundledWithPiwik)
&& in_array($name, $pluginsBundledWithPiwik))
|| in_array($name, $this->getCorePluginsDisabledByDefault())
|| $name == self::DEFAULT_THEME;
}
protected function isPluginThirdPartyAndBogus($pluginName)
{
if($this->isPluginBundledWithCore($pluginName)) {
return false;
}
if($this->isPluginBogus($pluginName)) {
return true;
}
$path = $this->getPluginsDirectory() . $pluginName;
if(!$this->isManifestFileFound($path)) {
return true;
}
return false;
}
/**
* Load the specified plugins.
*
* @param array $pluginsToLoad Array of plugins to load.
*/
public function loadPlugins(array $pluginsToLoad)
{
$pluginsToLoad = array_unique($pluginsToLoad);
$this->pluginsToLoad = $pluginsToLoad;
$this->reloadPlugins();
}
/**
* Disable plugin loading.
*/
public function doNotLoadPlugins()
{
$this->doLoadPlugins = false;
}
/**
* Disable loading of "always activated" plugins.
*/
public function doNotLoadAlwaysActivatedPlugins()
{
$this->doLoadAlwaysActivatedPlugins = false;
}
/**
* Load translations for loaded plugins
*
* @param bool|string $language Optional language code
*/
public function loadPluginTranslations($language = false)
{
if (empty($language)) {
$language = Translate::getLanguageToLoad();
}
$plugins = $this->getLoadedPlugins();
foreach ($plugins as $plugin) {
$this->loadTranslation($plugin, $language);
}
}
/**
* Execute postLoad() hook for loaded plugins
*/
public function postLoadPlugins()
{
$plugins = $this->getLoadedPlugins();
foreach ($plugins as $plugin) {
$plugin->postLoad();
}
}
/**
* Returns an array containing the plugins class names (eg. 'UserCountry' and NOT 'UserCountry')
*
* @return array
*/
public function getLoadedPluginsName()
{
return array_keys($this->getLoadedPlugins());
}
/**
* Returns an array mapping loaded plugin names with their plugin objects, eg,
*
* array(
* 'UserCountry' => Plugin $pluginObject,
* 'UserSettings' => Plugin $pluginObject,
* );
*
* @return Plugin[]
*/
public function getLoadedPlugins()
{
return $this->loadedPlugins;
}
/**
* @param string $piwikVersion
* @return Plugin[]
*/
public function getIncompatiblePlugins($piwikVersion)
{
$plugins = $this->getLoadedPlugins();
$incompatible = array();
foreach ($plugins as $plugin) {
if ($plugin->hasMissingDependencies($piwikVersion)) {
$incompatible[] = $plugin;
}
}
return $incompatible;
}
/**
* Returns an array of plugins that are currently loaded and activated,
* mapping loaded plugin names with their plugin objects, eg,
*
* array(
* 'UserCountry' => Plugin $pluginObject,
* 'UserSettings' => Plugin $pluginObject,
* );
*
* @return Plugin[]
*/
public function getPluginsLoadedAndActivated()
{
$plugins = $this->getLoadedPlugins();
$enabled = $this->getActivatedPlugins();
if(empty($enabled)) {
return array();
}
$enabled = array_combine($enabled, $enabled);
$plugins = array_intersect_key($plugins, $enabled);
return $plugins;
}
/**
* Returns a list of all names of currently activated plugin eg,
*
* array(
* 'UserCountry'
* 'UserSettings'
* );
*
* @return string[]
*/
public function getActivatedPlugins()
{
return $this->pluginsToLoad;
}
/**
* Returns a Plugin object by name.
*
* @param string $name The name of the plugin, eg, `'Actions'`.
* @throws \Exception If the plugin has not been loaded.
* @return Plugin
*/
public function getLoadedPlugin($name)
{
if (!isset($this->loadedPlugins[$name])) {
throw new \Exception("The plugin '$name' has not been loaded.");
}
return $this->loadedPlugins[$name];
}
/**
* Load the plugins classes installed.
* Register the observers for every plugin.
*/
private function reloadPlugins()
{
if ($this->doLoadAlwaysActivatedPlugins) {
$this->pluginsToLoad = array_merge($this->pluginsToLoad, $this->pluginToAlwaysActivate);
}
$this->pluginsToLoad = array_unique($this->pluginsToLoad);
$pluginsToPostPendingEventsTo = array();
foreach ($this->pluginsToLoad as $pluginName) {
if (!$this->isPluginLoaded($pluginName)
&& !$this->isPluginThirdPartyAndBogus($pluginName)
) {
$newPlugin = $this->loadPlugin($pluginName);
if ($newPlugin === null) {
continue;
}
if ($newPlugin->hasMissingDependencies()) {
$this->deactivatePlugin($pluginName);
continue;
}
$pluginsToPostPendingEventsTo[] = $newPlugin;
}
}
// post pending events after all plugins are successfully loaded
foreach ($pluginsToPostPendingEventsTo as $plugin) {
EventDispatcher::getInstance()->postPendingEventsTo($plugin);
}
}
public function getIgnoredBogusPlugins()
{
$ignored = array();
foreach ($this->pluginsToLoad as $pluginName) {
if ($this->isPluginThirdPartyAndBogus($pluginName)) {
$ignored[] = $pluginName;
}
}
return $ignored;
}
/**
* Returns the name of all plugins found in this Piwik instance
* (including those not enabled and themes)
*
* @return array
*/
public static function getAllPluginsNames()
{
$pluginsToLoad = array_merge(
PiwikConfig::getInstance()->Plugins['Plugins'],
self::getInstance()->readPluginsDirectory(),
self::getInstance()->getCorePluginsDisabledByDefault()
);
$pluginsToLoad = array_values(array_unique($pluginsToLoad));
return $pluginsToLoad;
}
/**
* Loads the plugin filename and instantiates the plugin with the given name, eg. UserCountry
*
* @param string $pluginName
* @throws \Exception
* @return Plugin|null
*/
public function loadPlugin($pluginName)
{
if (isset($this->loadedPlugins[$pluginName])) {
return $this->loadedPlugins[$pluginName];
}
$newPlugin = $this->makePluginClass($pluginName);
$this->addLoadedPlugin($pluginName, $newPlugin);
return $newPlugin;
}
/**
* @param $pluginName
* @return Plugin
* @throws \Exception
*/
protected function makePluginClass($pluginName)
{
$pluginFileName = sprintf("%s/%s.php", $pluginName, $pluginName);
$pluginClassName = $pluginName;
if (!Filesystem::isValidFilename($pluginName)) {
throw new \Exception(sprintf("The plugin filename '%s' is not a valid filename", $pluginFileName));
}
$path = self::getPluginsDirectory() . $pluginFileName;
if (!file_exists($path)) {
// Create the smallest minimal Piwik Plugin
// Eg. Used for Morpheus default theme which does not have a Morpheus.php file
return new Plugin($pluginName);
}
require_once $path;
$namespacedClass = $this->getClassNamePlugin($pluginName);
if (!class_exists($namespacedClass, false)) {
throw new \Exception("The class $pluginClassName couldn't be found in the file '$path'");
}
$newPlugin = new $namespacedClass;
if (!($newPlugin instanceof Plugin)) {
throw new \Exception("The plugin $pluginClassName in the file $path must inherit from Plugin.");
}
return $newPlugin;
}
protected function getClassNamePlugin($pluginName)
{
$className = $pluginName;
if ($pluginName == 'API') {
$className = 'Plugin';
}
return "\\Piwik\\Plugins\\$pluginName\\$className";
}
/**
* Unload plugin
*
* @param Plugin|string $plugin
* @throws \Exception
*/
public function unloadPlugin($plugin)
{
if (!($plugin instanceof Plugin)) {
$oPlugin = $this->loadPlugin($plugin);
if ($oPlugin === null) {
unset($this->loadedPlugins[$plugin]);
return;
}
$plugin = $oPlugin;
}
unset($this->loadedPlugins[$plugin->getPluginName()]);
}
/**
* Unload all loaded plugins
*/
public function unloadPlugins()
{
$pluginsLoaded = $this->getLoadedPlugins();
foreach ($pluginsLoaded as $plugin) {
$this->unloadPlugin($plugin);
}
}
/**
* Install a specific plugin
*
* @param Plugin $plugin
* @throws \Piwik\Plugin\PluginException if installation fails
*/
private function executePluginInstall(Plugin $plugin)
{
try {
$plugin->install();
} catch (\Exception $e) {
throw new \Piwik\Plugin\PluginException($plugin->getPluginName(), $e->getMessage());
}
}
/**
* Add a plugin in the loaded plugins array
*
* @param string $pluginName plugin name without prefix (eg. 'UserCountry')
* @param Plugin $newPlugin
*/
private function addLoadedPlugin($pluginName, Plugin $newPlugin)
{
$this->loadedPlugins[$pluginName] = $newPlugin;
}
/**
* Load translation
*
* @param Plugin $plugin
* @param string $langCode
* @throws \Exception
* @return bool whether the translation was found and loaded
*/
private function loadTranslation($plugin, $langCode)
{
// we are in Tracker mode if Loader is not (yet) loaded
if (!class_exists('Piwik\\Loader', false)) {
return false;
}
if (is_string($plugin)) {
$pluginName = $plugin;
} else {
$pluginName = $plugin->getPluginName();
}
$path = self::getPluginsDirectory() . $pluginName . '/lang/%s.json';
$defaultLangPath = sprintf($path, $langCode);
$defaultEnglishLangPath = sprintf($path, 'en');
$translationsLoaded = false;
// merge in english translations as default first
if (file_exists($defaultEnglishLangPath)) {
$translations = $this->getTranslationsFromFile($defaultEnglishLangPath);
$translationsLoaded = true;
if (isset($translations[$pluginName])) {
// only merge translations of plugin - prevents overwritten strings
Translate::mergeTranslationArray(array($pluginName => $translations[$pluginName]));
}
}
// merge in specific language translations (to overwrite english defaults)
if (file_exists($defaultLangPath)) {
$translations = $this->getTranslationsFromFile($defaultLangPath);
$translationsLoaded = true;
if (isset($translations[$pluginName])) {
// only merge translations of plugin - prevents overwritten strings
Translate::mergeTranslationArray(array($pluginName => $translations[$pluginName]));
}
}
return $translationsLoaded;
}
/**
* Return names of all installed plugins.
*
* @return array
* @api
*/
public function getInstalledPluginsName()
{
$pluginNames = PiwikConfig::getInstance()->PluginsInstalled['PluginsInstalled'];
return $pluginNames;
}
/**
* Returns names of plugins that should be loaded, but cannot be since their
* files cannot be found.
*
* @return array
* @api
*/
public function getMissingPlugins()
{
$missingPlugins = array();
if (isset(PiwikConfig::getInstance()->Plugins['Plugins'])) {
$plugins = PiwikConfig::getInstance()->Plugins['Plugins'];
foreach ($plugins as $pluginName) {
// if a plugin is listed in the config, but is not loaded, it does not exist in the folder
if (!self::getInstance()->isPluginLoaded($pluginName)
&& !$this->isPluginBogus($pluginName)
) {
$missingPlugins[] = $pluginName;
}
}
}
return $missingPlugins;
}
/**
* Install a plugin, if necessary
*
* @param Plugin $plugin
*/
private function installPluginIfNecessary(Plugin $plugin)
{
$pluginName = $plugin->getPluginName();
$saveConfig = false;
// is the plugin already installed or is it the first time we activate it?
$pluginsInstalled = $this->getInstalledPluginsName();
if (!$this->isPluginInstalled($pluginName)) {
$this->executePluginInstall($plugin);
$pluginsInstalled[] = $pluginName;
$this->updatePluginsInstalledConfig($pluginsInstalled);
Updater::recordComponentSuccessfullyUpdated($plugin->getPluginName(), $plugin->getVersion());
$saveConfig = true;
}
if ($this->isTrackerPlugin($plugin)) {
$pluginsTracker = PiwikConfig::getInstance()->Plugins_Tracker['Plugins_Tracker'];
if (is_null($pluginsTracker)) {
$pluginsTracker = array();
}
if (!in_array($pluginName, $pluginsTracker)) {
$pluginsTracker[] = $pluginName;
$this->updatePluginsTrackerConfig($pluginsTracker);
$saveConfig = true;
}
}
if ($saveConfig) {
PiwikConfig::getInstance()->forceSave();
}
}
public function isTrackerPlugin(Plugin $plugin)
{
$dimensions = VisitDimension::getDimensions($plugin);
if (!empty($dimensions)) {
return true;
}
$dimensions = ActionDimension::getDimensions($plugin);
if (!empty($dimensions)) {
return true;
}
$hooks = $plugin->getListHooksRegistered();
$hookNames = array_keys($hooks);
foreach ($hookNames as $name) {
if (strpos($name, self::TRACKER_EVENT_PREFIX) === 0) {
return true;
}
if ($name === 'Request.initAuthenticationObject') {
return true;
}
}
$dimensions = ConversionDimension::getDimensions($plugin);
if (!empty($dimensions)) {
return true;
}
return false;
}
private static function pluginStructureLooksValid($path)
{
$name = basename($path);
return file_exists($path . "/" . $name . ".php")
|| self::isManifestFileFound($path);
}
/**
* @param $pluginName
*/
private function removePluginFromPluginsInstalledConfig($pluginName)
{
$pluginsInstalled = PiwikConfig::getInstance()->PluginsInstalled['PluginsInstalled'];
$key = array_search($pluginName, $pluginsInstalled);
if ($key !== false) {
unset($pluginsInstalled[$key]);
}
$this->updatePluginsInstalledConfig($pluginsInstalled);
}
/**
* @param $pluginName
*/
private function removePluginFromPluginsConfig($pluginName)
{
$pluginsEnabled = PiwikConfig::getInstance()->Plugins['Plugins'];
$key = array_search($pluginName, $pluginsEnabled);
if ($key !== false) {
unset($pluginsEnabled[$key]);
}
$this->updatePluginsConfig($pluginsEnabled);
}
private function removePluginFromTrackerConfig($pluginName)
{
$pluginsTracker = PiwikConfig::getInstance()->Plugins_Tracker['Plugins_Tracker'];
if (!is_null($pluginsTracker)) {
$key = array_search($pluginName, $pluginsTracker);
if ($key !== false) {
unset($pluginsTracker[$key]);
$this->updatePluginsTrackerConfig($pluginsTracker);
}
}
}
/**
* @param string $pathToTranslationFile
* @throws \Exception
* @return mixed
*/
private function getTranslationsFromFile($pathToTranslationFile)
{
$data = file_get_contents($pathToTranslationFile);
$translations = json_decode($data, true);
if (is_null($translations) && Common::hasJsonErrorOccurred()) {
$jsonError = Common::getLastJsonError();
$message = sprintf('Not able to load translation file %s: %s', $pathToTranslationFile, $jsonError);
throw new \Exception($message);
}
return $translations;
}
/**
* @param $pluginName
* @return bool
*/
private function isPluginBogus($pluginName)
{
$bogusPlugins = array(
'PluginMarketplace', //defines a plugin.json but 1.x Piwik plugin
'DoNotTrack', // Removed in 2.0.3
'AnonymizeIP', // Removed in 2.0.3
);
return in_array($pluginName, $bogusPlugins);
}
private function deactivateThemeIfTheme($pluginName)
{
// Only one theme enabled at a time
$themeEnabled = $this->getThemeEnabled();
if ($themeEnabled
&& $themeEnabled->getPluginName() != self::DEFAULT_THEME) {
$themeAlreadyEnabled = $themeEnabled->getPluginName();
$plugin = $this->loadPlugin($pluginName);
if ($plugin->isTheme()) {
$this->deactivatePlugin($themeAlreadyEnabled);
}
}
}
/**
* @param $pluginName
*/
private function executePluginDeactivate($pluginName)
{
if (!$this->isPluginBogus($pluginName)) {
$plugin = $this->loadPlugin($pluginName);
if ($plugin !== null) {
$plugin->deactivate();
}
}
}
/**
* @param $pluginName
*/
private function unloadPluginFromMemory($pluginName)
{
$key = array_search($pluginName, $this->pluginsToLoad);
if ($key !== false) {
unset($this->pluginsToLoad[$key]);
}
}
/**
* @param $pluginName
*/
private function removePluginFromConfig($pluginName)
{
$this->removePluginFromPluginsConfig($pluginName);
$this->removePluginFromTrackerConfig($pluginName);
PiwikConfig::getInstance()->forceSave();
}
/**
* @param $pluginName
*/
private function executePluginUninstall($pluginName)
{
try {
$plugin = $this->getLoadedPlugin($pluginName);
$plugin->uninstall();
} catch (\Exception $e) {
}
if (empty($plugin)) {
return;
}
try {
foreach (VisitDimension::getDimensions($plugin) as $dimension) {
$dimension->uninstall();
}
} catch (\Exception $e) {
}
try {
foreach (ActionDimension::getDimensions($plugin) as $dimension) {
$dimension->uninstall();
}
} catch (\Exception $e) {
}
try {
foreach (ConversionDimension::getDimensions($plugin) as $dimension) {
$dimension->uninstall();
}
} catch (\Exception $e) {
}
}
/**
* @param $pluginName
* @return bool
*/
public function isPluginInstalled($pluginName)
{
$pluginsInstalled = $this->getInstalledPluginsName();
return in_array($pluginName, $pluginsInstalled);
}
}
/**
*/
class PluginException extends \Exception
{
function __construct($pluginName, $message)
{
parent::__construct("There was a problem installing the plugin " . $pluginName . ": " . $message . "
If this plugin has already been installed, and if you want to hide this message</b>, you must add the following line under the
[PluginsInstalled]
entry in your config/config.ini.php file:
PluginsInstalled[] = $pluginName");
}
}
|