/
PluginManager.php
367 lines (328 loc) · 12.7 KB
/
PluginManager.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
<?php
namespace ls\pluginmanager;
use \Yii;
use Plugin;
/**
* Factory for limesurvey plugin objects.
*/
class PluginManager extends \CApplicationComponent{
/**
* Object containing any API that the plugins can use.
* @var mixed $api The class name of the API class to load, or
*/
public $api;
/**
* Array mapping guids to question object class names.
* @var type
*/
protected $guidToQuestion = array();
protected $plugins = array();
protected $pluginDirs = [
'webroot.plugins', // User plugins
'application.core.plugins' // Core plugins
];
protected $stores = array();
protected $subscriptions = array();
/**
* Creates the plugin manager.
*
*
* a reference to an already constructed reference.
*/
public function init() {
parent::init();
if (!is_object($this->api)) {
$class = $this->api;
$this->api = new $class;
}
$this->loadPlugins();
}
/**
* Return a list of installed plugins, but only if the files are still there
*
* This prevents errors when a plugin was installed but the files were removed
* from the server.
*
* @return array
*/
public function getInstalledPlugins()
{
$pluginModel = Plugin::model();
$records = $pluginModel->findAll();
$plugins = array();
foreach ($records as $record) {
// Only add plugins we can find
if ($this->loadPlugin($record->name) !== false) {
$plugins[$record->id] = $record;
}
}
return $plugins;
}
/**
* Returns the storage instance of type $storageClass.
* If needed initializes the storage object.
* @param string $storageClass
*/
public function getStore($storageClass)
{
if (!isset($this->stores[$storageClass]))
{
$this->stores[$storageClass] = new $storageClass();
}
return $this->stores[$storageClass];
}
/**
* This function returns an API object, exposing an API to each plugin.
* In the current case this is the LimeSurvey API.
* @return LimesurveyApi
*/
public function getAPI()
{
return $this->api;
}
/**
* Registers a plugin to be notified on some event.
* @param iPlugin $plugin Reference to the plugin.
* @param string $event Name of the event.
* @param string $function Optional function of the plugin to be called.
*/
public function subscribe(iPlugin $plugin, $event, $function = null)
{
if (!isset($this->subscriptions[$event]))
{
$this->subscriptions[$event] = array();
}
if (!$function)
{
$function = $event;
}
$subscription = array($plugin, $function);
// Subscribe only if not yet subscribed.
if (!in_array($subscription, $this->subscriptions[$event]))
{
$this->subscriptions[$event][] = $subscription;
}
}
/**
* Unsubscribes a plugin from an event.
* @param iPlugin $plugin Reference to the plugin being unsubscribed.
* @param string $event Name of the event. Use '*', to unsubscribe all events for the plugin.
* @param string $function Optional function of the plugin that was registered.
*/
public function unsubscribe(iPlugin $plugin, $event)
{
// Unsubscribe recursively.
if ($event == '*')
{
foreach ($this->subscriptions as $event)
{
$this->unsubscribe($plugin, $event);
}
}
elseif (isset($this->subscriptions[$event]))
{
foreach ($this->subscriptions[$event] as $index => $subscription)
{
if ($subscription[0] == $plugin)
{
unset($this->subscriptions[$event][$index]);
}
}
}
}
/**
* This function dispatches an event to all registered plugins.
* @param PluginEvent $event Object holding all event properties
* @param string|array $target Optional name of plugin to fire the event on
*
* @return PluginEvent
*/
public function dispatchEvent(PluginEvent $event, $target = array())
{
$eventName = $event->getEventName();
if (is_string($target)) {
$target = array($target);
}
if (isset($this->subscriptions[$eventName]))
{
foreach($this->subscriptions[$eventName] as $subscription)
{
if (!$event->isStopped()
&& (empty($target) || in_array(get_class($subscription[0]), $target)))
{
$subscription[0]->setEvent($event);
call_user_func($subscription);
}
}
}
return $event;
}
/**
* Scans the plugin directory for plugins.
* This function is not efficient so should only be used in the admin interface
* that specifically deals with enabling / disabling plugins.
*/
public function scanPlugins($forceReload = false)
{
$result = array();
foreach ($this->pluginDirs as $pluginDir) {
$currentDir = Yii::getPathOfAlias($pluginDir);
if (is_dir($currentDir)) {
foreach (new \DirectoryIterator($currentDir) as $fileInfo)
{
if (!$fileInfo->isDot() && $fileInfo->isDir())
{
// Check if the base plugin file exists.
// Directory name Example most contain file ExamplePlugin.php.
$pluginName = $fileInfo->getFilename();
$file = Yii::getPathOfAlias($pluginDir . ".$pluginName.{$pluginName}") . ".php";
if (file_exists($file))
{
$result[$pluginName] = $this->getPluginInfo($pluginName, $pluginDir);
}
}
}
}
\Yii::app()->cache->set($cacheKey, $plugins, 3600);
}
return $result;
}
/**
* Gets the description of a plugin. The description is accessed via a
* static function inside the plugin file.
*
* @param string $pluginClass The classname of the plugin
*/
public function getPluginInfo($pluginClass, $pluginDir = null)
{
$result = array();
$class = "{$pluginClass}";
if (!class_exists($class, false)) {
$found = false;
if (!is_null($pluginDir)) {
$dirs = array($pluginDir);
} else {
$dirs = $this->pluginDirs;
}
foreach ($this->pluginDirs as $pluginDir) {
$file = Yii::getPathOfAlias($pluginDir . ".$pluginClass.{$pluginClass}") . ".php";
if (file_exists($file)) {
Yii::import($pluginDir . ".$pluginClass.*");
$found = true;
break;
}
}
if (!$found) {
return false;
}
}
$result['description'] = call_user_func(array($class, 'getDescription'));
$result['pluginName'] = call_user_func(array($class, 'getName'));
$result['pluginClass'] = $class;
return $result;
}
/**
* Returns the instantiated plugin
*
* @param string $pluginName
* @param int $id Identifier used for identifying a specific plugin instance.
* If ommitted will return the first instantiated plugin with the given name.
* @return iPlugin|null The plugin or null when missing
*/
public function loadPlugin($pluginName, $id = null)
{
// If the id is not set we search for the plugin.
if (!isset($id))
{
foreach ($this->plugins as $plugin)
{
if (get_class($plugin) == $pluginName)
{
return $plugin;
}
}
}
else
{
if ((!isset($this->plugins[$id]) || get_class($this->plugins[$id]) !== $pluginName))
{
if ($this->getPluginInfo($pluginName) !== false) {
$this->plugins[$id] = new $pluginName($this, $id);
} else {
$this->plugins[$id] = null;
}
}
return $this->plugins[$id];
}
}
/**
* Handles loading all active plugins
*
* Possible improvement would be to load them for a specific context.
* For instance 'survey' for runtime or 'admin' for backend. This needs
* some thinking before implementing.
*/
public function loadPlugins()
{
try {
$pluginModel = Plugin::model();
$records = $pluginModel->findAllByAttributes(array('active'=>1));
foreach ($records as $record) {
$this->loadPlugin($record->name, $record->id);
}
} catch (Exception $exc) {
// Something went wrong, maybe no database was present so we load no plugins
}
$this->dispatchEvent(new PluginEvent('afterPluginLoad', $this)); // Alow plugins to do stuff after all plugins are loaded
}
/**
* Get a list of question objects and load some information about them.
* This registers the question object classes with Yii.
*/
public function loadQuestionObjects($forceReload = false)
{
if (empty($this->guidToQuestion) || $forceReload)
{
$event = new PluginEvent('listQuestionPlugins');
$this->dispatchEvent($event);
foreach ($event->get('questionplugins', array()) as $pluginClass => $paths)
{
foreach ($paths as $path)
{
Yii::import("webroot.plugins.$pluginClass.$path");
$parts = explode('.', $path);
// Get the class name.
$className = array_pop($parts);
// Get the GUID for the question object.
$guid = forward_static_call(array($className, 'getGUID'));
// Save the GUID-class mapping.
$this->guidToQuestion[$guid] = array(
'class' => $className,
'guid' => $guid,
'plugin' => $pluginClass,
'name' => $className::$info['name']
);
}
}
}
return $this->guidToQuestion;
}
/**
* Construct a question object from a GUID.
* @param string $guid
* @param int $questionId,
* @param int $responseId
* @return iQuestion
*/
public function constructQuestionFromGUID($guid, $questionId = null, $responseId = null)
{
$this->loadQuestionObjects();
if (isset($this->guidToQuestion[$guid]))
{
$questionClass = $this->guidToQuestion[$guid]['class'];
$questionObject = new $questionClass($this->loadPlugin($this->guidToQuestion[$guid]['plugin']), $this->api, $questionId, $responseId);
return $questionObject;
}
}
}
?>