-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebhooks_plugin.php
369 lines (333 loc) · 12.4 KB
/
webhooks_plugin.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
<?php
use Blesta\Core\Util\Events\Common\EventInterface;
/**
* Webhooks plugin handler
*
* @package blesta
* @subpackage blesta.plugins.webhooks
* @copyright Copyright (c) 2023, Phillips Data, Inc.
* @license http://www.blesta.com/license/ The Blesta License Agreement
* @link http://www.blesta.com/ Blesta
*/
class WebhooksPlugin extends Plugin
{
public function __construct()
{
// Load components required by this plugin
Loader::loadComponents($this, ['Input', 'Record']);
Language::loadLang('webhooks_plugin', null, dirname(__FILE__) . DS . 'language' . DS);
$this->loadConfig(dirname(__FILE__) . DS . 'config.json');
// Initialize a single instance of WebhookEvents
if (!isset($this->WebhooksEvents)) {
Loader::loadModels($this, ['Webhooks.WebhooksEvents']);
}
}
/**
* Performs any necessary bootstraping actions
*
* @param int $plugin_id The ID of the plugin being installed
*/
public function install($plugin_id)
{
if (!isset($this->Record)) {
Loader::loadComponents($this, ['Record']);
}
if (!isset($this->CronTasks)) {
Loader::loadModels($this, ['CronTasks']);
}
// Add all webhook tables, *IFF* not already added
try {
// webhooks
$this->Record->
setField('id', ['type' => 'int', 'size' => 10, 'unsigned' => true, 'auto_increment' => true])->
setField('company_id', ['type' => 'int', 'size' => 10, 'unsigned' => true])->
setField('callback', ['type' => 'varchar', 'size' => 255])->
setField('type', ['type' => 'enum', 'size' => "'incoming','outgoing'", 'default' => 'incoming'])->
setField('method', ['type' => 'enum', 'size' => "'get','post','put','put_json','post_json'", 'default' => 'post'])->
setKey(['id'], 'primary')->
create('webhooks', true);
// webhook_events
$this->Record->
setField('webhook_id', ['type' => 'int', 'size' => 10, 'unsigned' => true])->
setField('event', ['type' => 'varchar', 'size' => 255])->
setKey(['webhook_id', 'event'], 'primary')->
create('webhook_events', true);
// webhook_fields
$this->Record->
setField('webhook_id', ['type' => 'int', 'size' => 10, 'unsigned' => true])->
setField('field', ['type' => 'varchar', 'size' => 255])->
setField('parameter', ['type' => 'varchar', 'size' => 255])->
setKey(['webhook_id', 'field'], 'primary')->
create('webhook_fields', true);
} catch (Exception $e) {
// Error adding... no permission?
$this->Input->setErrors(['db'=> ['create'=>$e->getMessage()]]);
return;
}
// Add cron tasks
$this->addCronTasks($this->getCronTasks());
}
/**
* Performs any necessary cleanup actions
*
* @param int $plugin_id The ID of the plugin being uninstalled
* @param bool $last_instance True if $plugin_id is the last instance across
* all companies for this plugin, false otherwise
*/
public function uninstall($plugin_id, $last_instance)
{
if (!isset($this->CronTasks)) {
Loader::loadModels($this, ['CronTasks']);
}
$cron_tasks = $this->getCronTasks();
// Remove the tables created by this plugin
if ($last_instance) {
try {
$this->Record->drop('webhooks');
$this->Record->drop('webhook_fields');
} catch (Exception $e) {
// Error dropping... no permission?
$this->Input->setErrors(['db'=> ['create'=>$e->getMessage()]]);
return;
}
// Remove the cron tasks
foreach ($cron_tasks as $task) {
$cron_task = $this->CronTasks
->getByKey($task['key'], $task['dir'], $task['task_type']);
if ($cron_task) {
$this->CronTasks->deleteTask($cron_task->id, $task['task_type'], $task['dir']);
}
}
}
// Remove individual cron task runs
foreach ($cron_tasks as $task) {
$cron_task_run = $this->CronTasks
->getTaskRunByKey($task['key'], $task['dir'], false, $task['task_type']);
if ($cron_task_run) {
$this->CronTasks->deleteTaskRun($cron_task_run->task_run_id);
}
}
}
/**
* Performs migration of data from $current_version (the current installed version)
* to the given file set version
*
* @param string $current_version The current installed version of this plugin
* @param int $plugin_id The ID of the plugin being upgraded
*/
public function upgrade($current_version, $plugin_id)
{
// Upgrade if possible
if (version_compare($this->getVersion(), $current_version, '>')) {
// Handle the upgrade, set errors using $this->Input->setErrors() if any errors encountered
// Upgrade to 1.1.0
if (version_compare($current_version, '1.1.0', '<')) {
$this->upgrade1_1_0();
}
// Upgrade to 1.2.0
if (version_compare($current_version, '1.2.0', '<')) {
$this->upgrade1_2_0();
}
}
}
/**
* Update to v1.1.0
*/
private function upgrade1_1_0()
{
$this->Record->query(
"ALTER TABLE `webhooks` CHANGE `method` `method` ENUM('get','post','put','put_json','post_json','json') CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL;"
);
$vars = ['method' => 'post_json'];
$this->Record->where('method', '=', 'json')->
update('webhooks', $vars, array_keys($vars));
$this->Record->query(
"ALTER TABLE `webhooks` CHANGE `method` `method` ENUM('get','post','put','put_json','post_json') CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL;"
);
// Drop the index on 'company_id'
$this->Record->query('DROP INDEX `company_id` ON `webhooks`');
// Add cron tasks
$this->addCronTasks($this->getCronTasks());
}
/**
* Update to v1.2.0
*/
private function upgrade1_2_0()
{
// Add new webhook_events table
try {
$this->Record->
setField('webhook_id', ['type' => 'int', 'size' => 10, 'unsigned' => true])->
setField('event', ['type' => 'varchar', 'size' => 255])->
setKey(['webhook_id', 'event'], 'primary')->
create('webhook_events', true);
} catch (Exception $e) {
// Error adding... no permission?
$this->Input->setErrors(['db'=> ['create'=>$e->getMessage()]]);
}
// Move events to the new table
$webhooks = $this->Record->select()->from('webhooks')
->fetchAll();
foreach ($webhooks as $webhook) {
$this->Record->insert('webhook_events', ['webhook_id' => $webhook->id, 'event' => $webhook->event]);
}
// Remove webhooks.callback column
$this->Record->query('ALTER TABLE `webhooks` DROP COLUMN `event`;');
}
/**
* Returns all events to be registered for this plugin (invoked after install() or upgrade(),
* overwrites all existing events)
*
* @return array A numerically indexed array containing:
*
* - event The event to register for
* - callback A string or array representing a callback function or class/method. If a user (e.g.
* non-native PHP) function or class/method, the plugin must automatically define it when the plugin is loaded.
* To invoke an instance methods pass "this" instead of the class name as the 1st callback element.
*/
public function getEvents()
{
// Get all the available events on the system
$events = $this->WebhooksEvents->getAll();
// Build a list of events
$callbacks = [];
foreach ($events as $event) {
$callbacks[] = [
'event' => $event,
'callback' => ['this', 'listen']
];
}
return $callbacks;
}
/**
* Listens to all events and triggers outgoing webhooks
*
* @param EventInterface $event The event to process
*/
public function listen(EventInterface $event)
{
$this->WebhooksEvents->listen($event);
}
/**
* Returns all permissions to be configured for this plugin (invoked after install(), upgrade(),
* and uninstall(), overwrites all existing permissions)
*
* @return array A numerically indexed array containing:
*
* - group_alias The alias of the permission group this permission belongs to
* - name The name of this permission
* - alias The ACO alias for this permission (i.e. the Class name to apply to)
* - action The action this ACO may control (i.e. the Method name of the alias to control access for)
*/
public function getPermissions()
{
return [
[
'group_alias' => 'admin_tools',
'name' => Language::_('WebhooksPlugin.name', true),
'alias' => 'webhooks.admin_main',
'action' => '*'
]
];
}
/**
* Returns all actions to be configured for this widget
* (invoked after install() or upgrade(), overwrites all existing actions)
*
* @return array A numerically indexed array containing:
* - action The action to register for
* - uri The URI to be invoked for the given action
* - name The name to represent the action (can be language definition)
*/
public function getActions()
{
return [
[
'action' => 'nav_secondary_staff',
'uri' => 'plugin/webhooks/admin_main/',
'name' => 'WebhooksPlugin.name',
'options' => ['parent' => 'tools/']
]
];
}
/**
* {@inheritdoc}
*/
public function cron($key)
{
if ($key === 'clear_cache') {
$this->clearCache(Configure::get('Blesta.company_id'));
}
}
/**
* Clears the plugin cache
*
* @param int $company_id
*/
private function clearCache($company_id)
{
if (Configure::get('Caching.on') && is_writable(CACHEDIR)) {
Cache::clearCache(
'event_observers',
$company_id . DS . 'plugins' . DS . 'webhooks' . DS
);
}
}
/**
* Retrieves cron tasks available to this plugin along with their default values
*
* @return array A list of cron tasks
*/
private function getCronTasks()
{
return [
// Cron task to check for incoming email tickets
[
'key' => 'clear_cache',
'dir' => 'webhooks',
'task_type' => 'plugin',
'name' => Language::_(
'WebhooksPlugin.getCronTasks.clear_cache_name',
true
),
'description' => Language::_(
'WebhooksPlugin.getCronTasks.clear_cache_desc',
true
),
'type' => 'time',
'type_value' => '12:00:00',
'enabled' => 1
]
];
}
/**
* Attempts to add new cron tasks for this plugin
*
* @param array $tasks A list of cron tasks to add
*/
private function addCronTasks(array $tasks)
{
foreach ($tasks as $task) {
$task_id = $this->CronTasks->add($task);
if (!$task_id) {
$cron_task = $this->CronTasks->getByKey(
$task['key'],
$task['dir'],
$task['task_type']
);
if ($cron_task) {
$task_id = $cron_task->id;
}
}
if ($task_id) {
$task_vars = ['enabled' => $task['enabled']];
if ($task['type'] === 'interval') {
$task_vars['interval'] = $task['type_value'];
} else {
$task_vars['time'] = $task['type_value'];
}
$this->CronTasks->addTaskRun($task_id, $task_vars);
}
}
}
}