/
plugin_service.js
executable file
·2291 lines (2028 loc) · 87.5 KB
/
plugin_service.js
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
/*
Copyright (C) 2015 PencilBlue, LLC
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//dependencies
var fs = require('fs');
var npm = require('npm');
var path = require('path');
var process = require('process');
var async = require('async');
var domain = require('domain');
var semver = require('semver');
var util = require('../../util.js');
module.exports = function PluginServiceModule(pb) {
/**
* PluginService - Provides functions for interacting with plugins.
* Install/uninstall, setting retrieval, plugin retrieval, etc.
*
* @class PluginService
* @constructor
* @module Services
* @submodule Entities
*/
function PluginService(){
//construct settings services
var caching = pb.config.plugins.caching;
/**
* A setting service that sets and retrieves the settings for plugins
* @property pluginSettingsService
* @type {SimpleLayeredService}
*/
this.pluginSettingsService = PluginService.genSettingsService('plugin_settings', caching.use_memory, caching.use_cache, 'PluginSettingService');
/**
* A setting service that sets and retrieves the settings for plugins
* @property pluginSettingsService
* @type {SimpleLayeredService}
*/
this.themeSettingsService = PluginService.genSettingsService('theme_settings', caching.use_memory, caching.use_cache, 'ThemeSettingService');
}
//constants
/**
* The absolute path to the plugins directory for this PecilBlue installation
* @property PLUGINS_DIR
* @type {String}
*/
var PLUGINS_DIR = path.join(pb.config.docRoot, 'plugins');
/**
* The name of the file that defines the plugin's properties
* @property DETAILS_FILE_NAME
* @type {String}
*/
var DETAILS_FILE_NAME = 'details.json';
/**
* The name of the directory for each plugin that contains the public resources
* @property PUBLIC_DIR_NAME
* @type {String}
*/
var PUBLIC_DIR_NAME = 'public';
//statics
/**
* A hash of the plugins that are installed and active in this instance of PB.
* @property ACTIVE_PLUGINS
* @type {Object}
*/
var ACTIVE_PLUGINS = {};
/**
* The name of the collection where plugin descriptors are stored
* @private
* @static
* @readonly
* @property PLUGIN_COLL
* @type {String}
*/
var PLUGIN_COLL = 'plugin';
/**
* The maximum number of retries to acquire
* @private
* @static
* @readonly
* @property MAX_DEPENDENCY_LOCK_RETRY_CNT
* @type {Integer}
*/
var MAX_DEPENDENCY_LOCK_RETRY_CNT = 45;
/**
* Retrieves the path to the active fav icon.
* @method getActiveIcon
* @param {Function} cb A callback that provides two parameters: cb(Error, URL_PATH_TO_ICON)
*/
PluginService.prototype.getActiveIcon = function(cb) {
pb.settings.get('active_theme', function(err, theme) {
if (ACTIVE_PLUGINS[theme] && ACTIVE_PLUGINS[theme].icon) {
cb(err, ACTIVE_PLUGINS[theme].icon);
}
else {
cb(err, '/favicon.ico');
}
});
};
/**
* Remove the active plugin entry from the current PB process.
* NOTE: it is not recommended to call this directly.
* @static
* @method deactivatePlugin
* @param {String} pluginUid
* @return {Boolean}
*/
PluginService.deactivatePlugin = function(pluginUid) {
if (!pb.validation.validateNonEmptyStr(pluginUid)) {
throw new Error('A non-existent or empty plugin UID was passed');
}
if (ACTIVE_PLUGINS[pluginUid]) {
delete ACTIVE_PLUGINS[pluginUid];
return true;
}
return false;
};
/**
* Retrieves the main module prototype for the specified active plugin
* @static
* @method getActiveMainModule
* @param {String} pluginUid
* @return {Function} The prototype that is the plugin's main module.
*/
PluginService.getActiveMainModule = function(pluginUid) {
return ACTIVE_PLUGINS[pluginUid] ? ACTIVE_PLUGINS[pluginUid].main_module : null;
};
/**
* Retrieves the names of the active plugins for this instance
* @method getActivePluginNames
* @return {array} An array that contain the names of the plugins that
* initialized successfully within this instance.
*/
PluginService.prototype.getActivePluginNames = function() {
return Object.keys(ACTIVE_PLUGINS);
};
/**
* Retrieves a single setting for the specified plugin.
*
* @method getSetting
* @param {string} settingName The name of the setting to retrieve
* @param {string} pluginName The name of the plugin who owns the setting
* @param {function} cb A callback that provides two parameters: cb(error, settingValue).
* Null is returned if the setting does not exist or the specified plugin is not
* installed.
*/
PluginService.prototype.getSetting = function(settingName, pluginName, cb) {
this.getSettings(pluginName, function(err, settings) {
if (util.isError(err)) {
cb(err, null);
return;
}
var val = null;
if (util.isArray(settings)) {
for (var i = 0; i < settings.length; i++) {
if (settingName === settings[i].name) {
val = settings[i].value;
break;
}
}
}
cb(err, val);
});
};
/**
* Retrieves all of the settings for the specfied plugin.
*
* @method getSettings
* @param pluginName The name of the plugin who's settings are being requested
* @param cb A callback that provides two parameters: cb(error, settings).
* Null is provided in the event that the plugin is not installed.
*/
PluginService.prototype.getSettings = function(pluginName, cb) {
this.pluginSettingsService.get(pluginName, cb);
};
/**
* Retrieves the settings for a plugin as hash of key/value pairs. This
* differs from the getSettings function because the getSettings function
* provides the settings in their raw form as an array of objects containing
* multiple properties. In most circumstances just the k/v pair is needed and
* not any additional information about the property. The function takes the
* raw settings array and transforms it into an object where the setting name
* is the property and the setting value is the value.
* @method getSettingsKV
* @param {String} pluginName The unique ID of the plugin who settings are to be retrieved
* @param {Function} cb A callback that takes two parameters. A error, if
* exists, and a hash of of the plugin's settings' names/values.
*/
PluginService.prototype.getSettingsKV = function(pluginName, cb) {
this.pluginSettingsService.get(pluginName, function(err, settings) {
if (util.isError(err)) {
return cb(err);
}
else if (!util.isArray(settings)) {
return cb(null, null);
}
cb(null, util.arrayToObj(settings, 'name', 'value'));
});
};
/**
* Replaces a single setting for the specified plugin
*
* @method setSetting
* @param name The name of the setting to change
* @param value The new value for the setting
* @param pluginName The plugin who's setting is being changed.
* @param cb A callback that provides two parameters: cb(error, TRUE/FALSE).
* TRUE if the setting was persisted successfully, FALSE if not.
*/
PluginService.prototype.setSetting = function(name, value, pluginName, cb) {
var self = this;
//error checking
if (!PluginService.validateSettingValue(value)) {
cb(new Error("PluginService: The setting value is required when modifing a theme setting"), false);
}
if (!pb.validation.validateNonEmptyStr(name, true)) {
cb(new Error("PluginService: The setting name is required when modifing a theme setting"), false);
}
//retrieve the settings to modify
this.getSettings(pluginName, function(err, settings) {
if (util.isError(err) || !settings) {
cb(err, false);
return;
}
var wasFound = false;
for (var i = 0; i < settings.length; i++) {
if (name === settings[i].name) {
settings[i].value = value;
wasFound = true;
break;
}
}
if (!wasFound) {
settings.push({
name: name,
value: value
});
}
self.setSettings(settings, pluginName, cb);
});
};
/**
* Replaces the settings for the specified plugin.
*
* @method setSettings
* @param settings The settings object to be validated and persisted
* @param pluginName The name of the plugin who's settings are being represented
* @param cb A callback that provides two parameters: cb(error, TRUE/FALSE).
* TRUE if the settings were persisted successfully, FALSE if not.
*/
PluginService.prototype.setSettings = function(settings, pluginName, cb) {
var self = this;
//error checking
if (!settings) {
cb(new Error("PluginService: The settings object is required when making changes to plugin settings"), false);
return;
}
if (!pluginName) {
cb(new Error("PluginService: The plugin name is required when making changes to plugin settings"), false);
return;
}
this.isInstalled(pluginName, function(err, isInstalled) {
if (util.isError(err) || !isInstalled) {
cb(err, false);
return;
}
self.pluginSettingsService.set(pluginName, settings, function(err, result) {
cb(err, !util.isError(err) && result);
});
});
};
/**
* Replaces a single theme setting for the specified plugin
*
* @method setThemeSetting
* @param name The name of the setting to change
* @param value The new value for the setting
* @param pluginName The plugin who's setting is being changed.
* @param cb A callback that provides two parameters: cb(error, TRUE/FALSE).
* TRUE if the setting was persisted successfully, FALSE if not.
*/
PluginService.prototype.setThemeSetting = function(name, value, pluginName, cb) {
var self = this;
//error checking
if (!PluginService.validateSettingValue(value)) {
cb(new Error("PluginService: The setting value is required when modifing a theme setting"), false);
}
if (!pb.validation.validateNonEmptyStr(name, true)) {
cb(new Error("PluginService: The setting name is required when modifing a theme setting"), false);
}
//retrieve the settings to modify
this.getThemeSettings(pluginName, function(err, settings) {
if (util.isError(err) || !settings) {
cb(err, false);
return;
}
var wasFound = false;
for (var i = 0; i < settings.length; i++) {
if (name === settings[i].name) {
settings[i].value = value;
wasFound = true;
break;
}
}
if (!wasFound) {
settings.push({
name: name,
value: value
});
}
self.setThemeSettings(settings, pluginName, cb);
});
};
/**
* Replaces the theme settings for the specified plugin.
*
* @method setThemeSettings
* @param settings The settings object to be validated and persisted
* @param pluginName The uid of the plugin who's settings are being represented
* @param cb A callback that provides two parameters: cb(error, TRUE/FALSE).
* TRUE if the settings were persisted successfully, FALSE if not.
*/
PluginService.prototype.setThemeSettings = function(settings, pluginName, cb) {
var self = this;
//error checking
if (!settings) {
cb(new Error("PluginService: The settings object is required when making changes to theme settings"), false);
return;
}
if (!pluginName) {
cb(new Error("PluginService: The plugin name is required when making changes to theme settings"), false);
return;
}
this.isInstalled(pluginName, function(err, isInstalled) {
if (util.isError(err) || !isInstalled) {
cb(err, false);
return;
}
self.themeSettingsService.set(pluginName, settings, function(err, result) {
cb(err, !util.isError(err) && result);
});
});
};
/**
* Retrieves a single theme setting value.
*
* @method getThemeSetting
* @param settingName The uid of the setting
* @param pluginName The plugin to retrieve the setting from
* @param cb A callback that provides two parameters: cb(error, settingValue)
*/
PluginService.prototype.getThemeSetting = function(settingName, pluginName, cb) {
this.getThemeSettings(pluginName, function(err, settings) {
if (util.isError(err)) {
cb(err, null);
return;
}
var val = null;
if (util.isArray(settings)) {
for (var i = 0; i < settings.length; i++) {
if (settingName === settings[i].name) {
val = settings[i].value;
break;
}
}
}
cb(err, val);
});
};
/**
* Retrieves the theme settings for the specified plugin
*
* @method getThemeSettings
* @param pluginName The uid of the plugin
* @param cb A callback that provides two parameters: cb(err, settingsObject)
*/
PluginService.prototype.getThemeSettings = function(pluginName, cb) {
this.themeSettingsService.get(pluginName, cb);
};
/**
* Retrieves the theme settings for a plugin as hash of key/value pairs. This
* differs from the getThemeSettings function because the getThemeSettings function
* provides the settings in their raw form as an array of objects containing
* multiple properties. In most circumstances just the k/v pair is needed and
* not any additional information about the property. The function takes the
* raw settings array and transforms it into an object where the setting name
* is the property and the setting value is the value.
* @method getThemeSettingsKV
* @param {String} pluginName The unique ID of the plugin who settings are to be retrieved
* @param {Function} cb A callback that takes two parameters. A error, if
* exists, and a hash of of the plugin's settings' names/values.
*/
PluginService.prototype.getThemeSettingsKV = function(pluginName, cb) {
this.themeSettingsService.get(pluginName, function(err, settings) {
if (util.isError(err)) {
return cb(err);
}
else if (!util.isArray(settings)) {
return cb(null, null);
}
cb(null, util.arrayToObj(settings, 'name', 'value'));
});
};
/**
* Indicates if a plugin by the specified identifier is installed.
*
* @method isInstalled
* @param pluginIdentifer The identifier can either be an ObjectID or the
* plugin name
* @param cb A callback that provides two parameters: cb(error, TRUE/FALSE).
* TRUE if the plugin is installed, FALSE if not.
*/
PluginService.prototype.isInstalled = function(pluginIdentifier, cb) {
this.getPlugin(pluginIdentifier, function(err, plugin) {
cb(err, plugin ? true : false);
});
};
/**
* Retrieves a plugin descriptor (plugin document)
*
* @method getPlugin
* @param pluginIdentifier The identifier can either be an ObjectID or the
* plugin name
* @param cb A callback that provides two parameters: cb(error, plugin). If the
* plugin does exist null is provided.
*/
PluginService.prototype.getPlugin = function(pluginIdentifier, cb) {
var where = {
$or: [
{},
{
uid: pluginIdentifier
}
]
};
where['$or'][0][pb.DAO.getIdField()] = pluginIdentifier;
var dao = new pb.DAO();
dao.loadByValues(where, PLUGIN_COLL, cb);
};
/**
* Retrieves the plugins that have themes associated with them
* @method getPluginsWithThemes
* @param {Function} cb Provides two parameters: Error, Array
*/
PluginService.prototype.getPluginsWithThemes = function(cb) {
var dao = new pb.DAO();
dao.q(PLUGIN_COLL, {where: {theme: {$exists: true}}}, cb);
};
/**
* Convenience function to generate a service to handle settings for a plugin.
*
* @static
* @method genSettingsService
* @param objType The type of object that will be dealt with. (plugin_settings,
* theme_settings)
* @param useMemory {Boolean} Indicates if the generated layered service should
* use an in memory service.
* @param useCache {Boolean} Indicates if the generated layered service should
* use a cache service.
* @param serviceName The name of the service
* @return {SimpleLayeredService}
*/
PluginService.genSettingsService = function(objType, useMemory, useCache, serviceName) {
//add in-memory service
var services = [];
if (useMemory){
var options = {
objType: objType,
timeout: pb.config.plugins.caching.memory_timeout
};
services.push(new pb.MemoryEntityService(options));
}
//add cache service
if (useCache) {
services.push(new pb.CacheEntityService(objType, undefined, undefined, 3600));
}
//always add DB
services.push(new pb.DBEntityService(objType, 'settings', 'plugin_uid'));
return new pb.SimpleLayeredService(services, serviceName);
};
/**
* Loads the settings from a details object and persists them in the DB. Any
* existing settings for the plugin are deleted before the new settings are
* persisted.
*
* @method resetSettings
* @param details The details object to extract the settings from
* @param cb A callback that provides two parameters: cb(error, TRUE/FALSE).
* TRUE if the settings were successfully cleared and reloaded. FALSE if not.
*/
PluginService.prototype.resetSettings = function(details, cb) {
var self = this;
//retrieve plugin to prove it exists (plus we need the id)
var pluginName = details.uid;
this.getPlugin(pluginName, function(err, plugin) {
if (util.isError(err) || !plugin) {
return cb(err ? err : new Error("The plugin "+pluginName+" is not installed"), false);
}
//remove any existing settings
self.pluginSettingsService.purge(pluginName, function (err, result) {
if (util.isError(err) || !result) {
return cb(err, false);
}
//build the object to persist
var baseDoc = {
plugin_name: plugin.name,
plugin_uid: plugin.uid,
plugin_id: plugin[pb.DAO.getIdField()].toString(),
settings: details.settings
};
var settings = pb.DocumentCreator.create('plugin_settings', baseDoc);
//save it
var dao = new pb.DAO();
dao.save(settings, function(err, result) {
cb(err, !util.isError(err));
});
});
});
};
/**
* Loads the Theme settings from a details object and persists them in the DB. Any
* existing theme settings for the plugin are deleted before the new settings
* are persisted. If the plugin does not have a theme then false is provided in
* the callback.
*
* @method resetThemeSettings
* @param details The details object to extract the settings from
* @param cb A callback that provides two parameters: cb(error, TRUE/FALSE).
* TRUE if the settings were successfully cleared and reloaded. FALSE if not.
*/
PluginService.prototype.resetThemeSettings = function(details, cb) {
var self = this;
//error checking
var pluginName = details.uid;
if (!details.theme || !details.theme.settings) {
cb(new Error("PluginService: Settings are required when attempting to reset a plugin's theme settings"), false);
return;
}
//retrieve plugin to prove it exists (plus we need the id)
this.getPlugin(pluginName, function(err, plugin) {
if (util.isError(err) || !plugin) {
cb(err, false);
return;
}
//remove any existing settings
self.themeSettingsService.purge(pluginName, function (err, result) {
if (util.isError(err) || !result) {
cb(err, false);
return;
}
//build the object to persist
var baseDoc = {
plugin_name: plugin.name,
plugin_uid: plugin.uid,
plugin_id: plugin[pb.DAO.getIdField()].toString(),
settings: details.theme.settings
};
var settings = pb.DocumentCreator.create('theme_settings', baseDoc);
//save it
var dao = new pb.DAO();
dao.save(settings, function(err, result) {
cb(err, !util.isError(err));
});
});
});
};
/**
* Retrieves the permission set for a given role. All active plugins are
* inspected.
* @static
* @method getPermissionsForRole
* @param {Integer|String} role The role to get permissions for
* @return {Object} A hash of the permissions
*/
PluginService.getPermissionsForRole = function(role) {
if (!isNaN(role)) {
role = pb.security.getRoleName(role);
}
var perms = {};
for(var pluginUid in ACTIVE_PLUGINS) {
var permissions = ACTIVE_PLUGINS[pluginUid].permissions;
if (permissions) {
var permsAtLevel = permissions[role];
if (permsAtLevel) {
util.merge(permsAtLevel, perms);
}
}
}
return perms;
};
/**
* Retrieves the file path to the public directory for the specified plugin.
* @static
* @method getActivePluginDir
* @param {String} pluginUid A plugin's UID value
* @return {String} File path to the plugin's public directory
*/
PluginService.getActivePluginPublicDir = function(pluginUid) {
var publicPath = null;
if (ACTIVE_PLUGINS[pluginUid]) {
publicPath = ACTIVE_PLUGINS[pluginUid].public_dir;
}
return publicPath;
};
/**
* Inidicates if the specified plugin is active in this instance of PB.
* @static
* @method isActivePlugin
* @param {String} uid The unique identifier for a plugin
* @return {Boolean} TRUE if the plugin is active, FALSE if not
*/
PluginService.isActivePlugin = function(uid) {
return ACTIVE_PLUGINS[uid] !== undefined;
};
/**
* Generates a URL path to a public resource for a plugin.
* @static
* @method genPublicPath
* @param {String} plugin The UID of the plugin
* @param {String} relativePathToMedia The relative path to the resource from
* the plugin's public directory.
* @return {String} URL path to the resource
*/
PluginService.genPublicPath = function(plugin, relativePathToMedia) {
if (!util.isString(plugin) || !util.isString(relativePathToMedia)) {
return '';
}
return pb.UrlService.urlJoin('/public', plugin, relativePathToMedia);
};
/**
* Retrieves the details for the active plugins.
* @method getActivePlugins
* @param {Function} cb A callback that provides two parameters: cb(Error, Array)
*/
PluginService.prototype.getActivePlugins = function(cb) {
var opts = {
select: pb.DAO.SELECT_ALL,
where: {uid: {'$in': this.getActivePluginNames()}},
order: {created: pb.DAO.ASC}
};
var dao = new pb.DAO();
dao.q(PLUGIN_COLL, opts, cb);
};
/**
* Retrieves the content templates for all of the active plugins
* @static
* @method getActiveContentTemplates
* @return {Array} An array of objects
*/
PluginService.getActiveContentTemplates = function() {
var templates = [];
for (var uid in ACTIVE_PLUGINS) {
var plugin = ACTIVE_PLUGINS[uid];
if (plugin.templates) {
var clone = util.clone(plugin.templates);
for(var i = 0; i < clone.length; i++) {
clone[i].theme_uid = uid;
templates.push(clone[i]);
}
}
}
return templates;
};
/**
* Retrieves the inactive plugins for this instance of PencilBlue. An inactive
* plugin is considered one who failed to install or one that failed to start
* properly.
* @method getInactivePlugins
* @param {Function} cb A callback that provides two parameters: cb(Error, Array)
*/
PluginService.prototype.getInactivePlugins = function(cb) {
var opts = {
select: pb.DAO.SELECT_ALL,
where: {uid: {'$nin': this.getActivePluginNames()}},
order: {created: pb.DAO.ASC}
};
var dao = new pb.DAO();
dao.q(PLUGIN_COLL, opts, cb);
};
/**
* Retrieves the available plugins. An available plugin is one who is
* uninstalled but available to be installed.
* @method getAvailablePlugins
* @param {Array} active An array of plugin detail objects. Each object is
* required to have a uid property that is a string.
* @param {Array} inactive An array of plugin details objects. Each object is
* required to have a uid property that is a string.
* @param {Function} cb A callback that provides two parameters: cb(Error, Array)
*/
PluginService.prototype.getAvailablePlugins = function(active, inactive, cb) {
if (util.isArray(active)) {
active = util.arrayToHash(active, function(active, i) {
return active[i] ? active[i].uid : '';
});
}
if (util.isArray(inactive)) {
inactive = util.arrayToHash(inactive, function(inactive, i) {
return inactive[i] ? inactive[i].uid : '';
});
}
util.getDirectories(PluginService.getPluginsDir(), function(err, directories) {
if (util.isError(err)) {
cb(err, null);
return;
}
var plugins = [];
var tasks = util.getTasks(directories, function(directories, i) {
return function(callback) {
//skip pencilblue
var parts = directories[i].split(path.sep);
var dirName = parts[parts.length - 1];
if (dirName === 'pencilblue') {
callback(null, true);
return;
}
var detailsFilePath = path.join(directories[i], DETAILS_FILE_NAME);
PluginService.loadDetailsFile(detailsFilePath, function(err, details) {
if (util.isError(err)) {
plugins.push({
uid: dirName,
dirName: dirName,
description: "Failed to load & parse the details.json file.",
validationErrors: ['An invalid details file was provided for plugin. '+err.stack]
});
callback(null, false);
return;
}
PluginService.validateDetails(details, dirName, function(err, result) {
if (util.isError(err)) {
plugins.push({
uid: dirName,
dirName: dirName,
description: "The plugin details file failed validation ",
validationErrors: err.validationErrors
});
callback(null, false);
return;
}
else if ( (active && active[details.uid]) || (inactive && inactive[details.uid])) {
callback(null, true);
return;
}
details.dirName = dirName;
plugins.push(details);
callback(null, true);
});
});
};
});
async.series(tasks, function(err, results) {
cb(err, plugins);
});
});
};
/**
* Retrieves a map of the system's plugin. The map provides three properties:
* active, inactive, available.
* @method getPluginMap
* @param {Function} cb A callback that provides two parameters: cb(Error, Object)
*/
PluginService.prototype.getPluginMap = function(cb) {
var self = this;
var tasks = {
active: function(callback) {
self.getActivePlugins(callback);
},
inactive: function(callback) {
self.getInactivePlugins(callback);
}
};
async.series(tasks, function(err, results) {
if (util.isError(err)) {
cb(err, results);
return;
}
self.getAvailablePlugins(results.active, results.inactive, function(err, available) {
results.available = available;
cb(err, results);
});
});
};
/**
* Uninstalls the plugin with the specified UID.
* @method uninstallPlugin
* @param {String} pluginUid The unique plugin identifier
* @param {Object} options
* @param {String} [options.jobId] Required when unintalling from the executing
* process instead of calling upon the cluster.
* @param {Boolean} [options.forCluster=true] When true or not provided the function
* instructs the cluster to uninstall the plugin. When explicitly FALSE the
* function installs the plugin from the executing process.
* @param {Function} [cb] A callback that provides two parameters: cb(Error, Boolean)
*/
PluginService.prototype.uninstallPlugin = function(pluginUid, options, cb) {
var self = this;
if (util.isFunction(options)) {
cb = options;
options = {};
}
if (!util.isObject(options)) {
options = {};
}
if (!util.isFunction(cb)) {
cb = util.cb;
}
//log start of operation
if (pb.log.isDebug()) {
pb.log.debug("PluginService:[%s] Attempting uninstall with options: %s", pluginUid, util.inspect(options));
}
var name = util.format('UNINSTALL_PLUGIN_%s', pluginUid);
var jobId = options.jobId;
var job = new pb.PluginUninstallJob();
job.init(name, jobId);
job.setPluginUid(pluginUid);
job.setRunAsInitiator(options.forCluster === false ? false : true);
job.run(cb);
return job.getId();
};
/**
* Installs a plugin by stepping through a series of steps that must be
* completed in order. There is currently no fallback plan for a failed install.
* In order for a plugin to be fully installed it must perform the following
* actions without error:
* <ol>
* <li>Load and parse the plugin's details.json file</li>
* <li>Pass validation</li>
* <li>Must not already be installed</li>
* <li>Successfully register itself with the system</li>
* <li>Successfully load any plugin settings</li>
* <li>Successfully load any theme settings</li>
* <li>Successfully execute the plugin's onInstall function</li>
* <li>Successfully initialize the plugin for runtime</li>
* </ol>
* @method installPlugin
* @param {string} pluginDirName The name of the directory that contains the
* plugin and its details.json file.
* @param {function} cb A callback that provides two parameters: cb(err, TRUE/FALSE)
*/
PluginService.prototype.installPlugin = function(pluginDirName, cb) {
cb = cb || util.cb;
var name = util.format('INSTALL_PLUGIN_%s', pluginDirName);
var job = new pb.PluginInstallJob();
job.init(name);
job.setRunAsInitiator(true);
job.setPluginUid(pluginDirName);
job.run(cb);
return job.getId();
};
/**
* Attempts to initialize all installed plugins.
* @method initPlugins
* @param {Function} A callback that provides two parameters: cb(Error, Boolean)
*/
PluginService.prototype.initPlugins = function(cb) {
pb.log.debug('PluginService: Beginning plugin initilization...');
var self = this;
var dao = new pb.DAO();
dao.q(PLUGIN_COLL, function(err, plugins) {
if (util.isError(err)) {
return cb(err);
}
else if (!util.isArray(plugins)) {
var err = new Error('An array of plugins was expected but found ['+(typeof plugins)+']['+util.inspect(plugins)+'] instead.');
pb.log.error('PluginService %s', err.stack);
return cb(err, plugins);
}
//make sure there are plugins to initialize
if (plugins.length === 0) {
pb.log.debug('PluginService: No plugins are installed');
return cb(null, true);
}
var tasks = util.getTasks(plugins, function(plugins, i) {
return function(callback) {
try {
self.initPlugin(plugins[i], function(err, didInitialize) {
process.nextTick(function() {
callback(null, {plugin: plugins[i], error: err, initialized: didInitialize});
});
});
}
catch(err) {
callback(null, {plugin: plugins[i], error: err, initialized: false});
}
};
});
async.series(tasks, function(err, results) {
for (var i = 0; i < results.length; i++) {
var result = results[i];
if (result.initialized === true) {
pb.log.debug('PluginService: Plugin [%s] was successfully initialized', result.plugin.name);
}
else {
pb.log.warn('PluginService: Plugin [%s] failed to initialize. INITIALIZED=%s', result.plugin.name, result.initialized);