forked from hughbris/grav-plugin-pushy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pushy.php
484 lines (415 loc) · 14.3 KB
/
pushy.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
<?php
namespace Grav\Plugin;
use Composer\Autoload\ClassLoader;
use Exception;
use Grav\Common\Assets;
use Grav\Common\Plugin;
use Grav\Common\Page\Page;
use Grav\Common\Uri;
use Grav\Events\PermissionsRegisterEvent;
use Grav\Framework\Acl\PermissionsReader;
use Grav\Framework\DI\Container;
use Grav\Plugin\Pushy\RequestHandler;
use RocketTheme\Toolbox\Event\Event;
use Grav\Plugin\Pushy\PushyRepo;
use Grav\Plugin\Pushy\GitUtils;
/**
* Class PushyPlugin
* @package Grav\Plugin
*/
class PushyPlugin extends Plugin
{
/** @var PushyRepo */
protected $repo;
/** @var string */
protected $admin_route = 'publish';
/**
* @return array
*/
public static function getSubscribedEvents(): array
{
return [
'onPluginsInitialized' => [
['onPluginsInitialized', 0],
],
];
}
/**
* Composer autoload
*
* @return ClassLoader
*/
public function autoload(): ClassLoader
{
return require __DIR__ . '/vendor/autoload.php';
}
/**
* Initialize the class instance
*/
public function init(): void
{
$this->repo = new PushyRepo();
}
/**
* Initialize the plugin
*/
public function onPluginsInitialized(): void
{
if ($this->isAdmin()) {
$this->init();
if ($this->isOnRoute()) {
/** @var RequestHandler */
$requestHandler = new RequestHandler();
$response = $requestHandler->handleRequest();
if ($response !== null) {
echo json_encode($response);
die();
}
}
$this->enable([
'onAdminTwigTemplatePaths' => ['setAdminTwigTemplatePaths', 0],
'onAdminMenu' => ['showPublishingMenu', 0],
'onTwigSiteVariables' => ['setTwigSiteVariables', 0],
'onAssetsInitialized' => ['onAssetsInitialized', 0],
PermissionsRegisterEvent::class => ['onRegisterPermissions', 0],
]);
} else {
$this->enable([
'onPageInitialized' => ['serveHooks', 0],
]);
}
}
/**
* Get admin page template
*/
public function setAdminTwigTemplatePaths(Event $event): void
{
$paths = $event['paths'];
$paths[] = __DIR__ . DS . 'admin/templates';
$event['paths'] = $paths;
}
/**
* Register new permission to list of permissions for Account and Group
*/
public function onRegisterPermissions(PermissionsRegisterEvent $event): void
{
$actions = PermissionsReader::fromYaml("plugin://{$this->name}/permissions.yaml");
$permissions = $event->permissions;
$permissions->addActions($actions);
}
/**
* Show the publishing menu item(s) in Admin
*/
public function showPublishingMenu(): void
{
$isInitialized = GitUtils::isGitInitialized();
// TODO: test for GitUtils::isGitInstalled()
$menuLabel = $isInitialized ? $this->translate('MENU_LABEL_PUBLISH') : $this->translate('MENU_LABEL_CONFIG');
$count = new Container(['count' => function () {
$itemCount = count($this->repo->getChangedItems() ?? []);
return $itemCount === 0 ? '' : $itemCount;
}]);
$options = [
'hint' => $isInitialized ? $this->translate('MENU_HINT_PUBLISH') : $this->translate('MENU_HINT_CONFIG'),
'route' => $isInitialized ? $this->admin_route : "plugins/{$this->name}",
'icon' => 'fa-' . ($isInitialized ? $this->grav['plugins']->get($this->name)->blueprints()->get('icon') : 'cog'),
'badge' => $count,
'authorize' => ['admin.publisher'],
// 'class' => '',
// 'data' => [],
];
$this->grav['twig']->plugins_hooked_nav[$menuLabel] = $options; // TODO: make this configurable in YAML/blueprint
}
/**
* Set any special variables for Twig templates
*/
public function setTwigSiteVariables(): void
{
$publish_path = $this->config->get('plugins.admin.route') . DS . $this->admin_route;
$route = $this->grav['uri']->path();
$isInitialized = GitUtils::isGitInitialized();
// TODO: test for GitUtils::isGitInstalled() - make a wrapper for these two funcs since we're checking them twice now
$twig = $this->grav['twig'];
if ($isInitialized && $route == $publish_path) {
$twig->twig_vars['git_index'] = $this->repo->statusSelect(); # TRUE, $env='index', $select='MTDRCA');
}
$twig->twig_vars['isAuthorised'] = $this->grav['user']->authorize('admin.publisher');
}
public function serveHooks(): void {
$webhooks = $this->config->get("plugins.{$this->name}.webhooks");
if (!($webhooks['enabled'] ?? FALSE)) {
return;
}
$page = $this->grav['page'] ?? NULL;
if (strpos($this->grav['uri']->uri(), $webhooks['path']) === 0) {
if ($webhooks['secret'] ?? FALSE) {
if (!self::isWebhookAuthenticated($webhooks['secret'])) { // authentication fails
self::jsonRespond(401, [
'status' => 'error',
'message' => 'Unauthorized request',
]);
}
}
if (strtoupper($_SERVER['REQUEST_METHOD']) != 'POST') {
self::jsonRespond(405, [
'status' => 'error',
'message' => 'Only POST operations supported',
]);
}
$endpoints = $webhooks['endpoints'] ?? [];
// check if the request path is an exact match with the webhook root path
if($this->grav['uri']->uri() == $webhooks['path']) {
self::jsonRespond(300, [
'status' => 'info',
'message' => ('Available endpoints are: ' . implode(', ', array_keys($endpoints))),
]);
}
foreach ($endpoints as $hook => $hook_properties) {
// match on the endpoint
$endpoint = strtolower(implode('/', [$webhooks['path'], $hook]));
if (strtolower($this->grav['uri']->uri()) == $endpoint) {
// check for declared hook response action
if (!$hook_properties || !array_key_exists('run', $hook_properties)) {
self::jsonRespond(418, [
'status' => 'undefined',
'message' => 'Am teapot, no operation specified or performed',
// 'debug' => $hook_properties,
]);
}
// let's grab that payload
$payload = file_get_contents('php://input');
$payload = !empty($payload) ? json_decode($payload) : FALSE;
if(!$payload) {
self::jsonRespond(400, [
'status' => 'undefined',
'message' => 'No payload or invalid payload',
// 'debug' => $hook_properties,
]);
}
// check declared conditions
if (array_key_exists('conditions', $hook_properties)) {
$conditions = $hook_properties['conditions'];
if(array_key_exists('branch', $conditions) && ($this->parsePayload($payload, 'branch') !== $conditions['branch'])) {
self::jsonRespond(422, [ // FIXME: 422 not sure
'status' => 'undefined',
'message' => 'Branch constraint not met',
// 'debug' => $hook_properties,
]);
}
if(array_key_exists('committer', $conditions) && ($this->parsePayload($payload, 'committer') !== $conditions['committer'])) {
self::jsonRespond(422, [ // FIXME: 422 not sure
'status' => 'undefined',
'message' => 'Committer constraint not met',
// 'debug' => $this->parsePayload($payload, 'committer'),
]);
}
}
try {
// perform the named scheduled task
$action = $hook_properties['run'];
$result = self::triggerSchedulerJob($action);
if($result) {
self::jsonRespond(200, [
'status' => 'success',
'message' => "Operation succeeded: '$action'",
// 'debug' => $hook_properties,
]);
}
}
catch (\Exception $e) {
self::jsonRespond(500, [
'status' => 'error',
'message' => "Operation failed: '$action' with \"{$e->getMessage()}\"",
// 'debug' => $hook_properties,
]);
}
}
}
// 404 fallback for endpoints under webhooks path, happens anyway I think but this sets useful JSON body
self::jsonRespond(404, [
'status' => 'error',
'message' => 'Endpoint not found',
// 'debug' => $webhooks,
]);
}
}
/**
* Perform a Grav Scheduler task, specified by name
* @param string $job_name The name (ID) of the task to run
* @return bool true if the job was found and ran successfully, otherwise throws \Exception
*/
private static function triggerSchedulerJob($job_name): bool
{
$scheduler = new \Grav\Common\Scheduler\Scheduler();
$job = $scheduler->getJob($job_name);
if ($job) {
$job->inForeground()->run();
if (!$job->isSuccessful()) { // was unsuccessful
throw new \Exception($job->getOutput());
}
} else {
throw new \Exception('job not defined');
}
return TRUE; // FIXME: return the job instead, since we can then access its properties and methods from the caller
}
// TODO: move these into GitUtils I think ..
/**
* Returns true if the request contains a valid signature or token
* @param string $secret local secret
* @return bool whether or not the request is authorized
*/
// copied from GitSync base class method isRequestAuthorized()
private static function isWebhookAuthenticated($secret): bool
{
if (isset($_SERVER['HTTP_X_HUB_SIGNATURE'])) {
$payload = file_get_contents('php://input') ?: '';
return self::isGithubSignatureValid($secret, $_SERVER['HTTP_X_HUB_SIGNATURE'], $payload);
}
if (isset($_SERVER['HTTP_X_GITLAB_TOKEN'])) {
return self::isGitlabTokenValid($secret, $_SERVER['HTTP_X_GITLAB_TOKEN']);
} else {
$payload = file_get_contents('php://input');
return self::isGiteaSecretValid($secret, $payload);
}
return FALSE;
}
/**
* Hashes the webhook request body with the client secret and checks if it matches the webhook signature header
* @param string $secret The webhook secret
* @param string $signatureHeader The signature of the webhook request
* @param string $payload The webhook request body
* @return bool whether the signature is valid or not
*/
// copied from GitSync base class method but uses more secure hash_equals()
private static function isGithubSignatureValid($secret, $signatureHeader, $payload): bool
{
[$algorithm, $signature] = explode('=', $signatureHeader);
return hash_equals($signature, hash_hmac($algorithm, $payload, $secret));
}
/**
* Returns true if given Gitlab token matches secret
* @param string $secret local secret
* @param string $token token received from Gitlab webhook request
* @return bool whether or not secret and token match
*/
// copied from GitSync base class method but uses more secure hash_equals()
// TODO: untested
private static function isGitlabTokenValid($secret, $token): bool
{
return hash_equals($secret, $token);
}
/**
* Returns true if secret contained in the payload matches the client secret
* @param string $secret The webhook secret
* @param string $payload The webhook request body
* @return bool whether the client secret matches the payload secret or not
*/
// copied from GitSync base class method but uses more secure hash_equals()
// TODO: untested
private static function isGiteaSecretValid($secret, $payload): bool
{
$payload = json_decode($payload, TRUE);
if (!empty($payload) && isset($payload['secret'])) {
return hash_equals($secret, $payload['secret']);
}
return FALSE;
}
// TODO: this can be static
/**
* Provide a HTTP status and JSON response and exit
* @param int $http_status HTTP status number to return
* @param array $proto_payload Payload as array to be served as JSON
* @return void
*/
private static function jsonRespond(int $http_status, array $proto_payload): void {
header('Content-Type: application/json');
http_response_code($http_status);
echo json_encode($proto_payload);
exit;
}
// TODO: this can be static
/**
* Parse JSON payloads and extract key properties
* @param object $payload JSON-decoded payload string
* @param string $component Enumerated standard element name to be extracted
* @return mixed
*/
private function parsePayload($payload, $component)
{
switch ($component) {
case 'branch':
if (property_exists($payload, 'ref')) {
return substr($payload->ref, strlen('refs/heads/'));
}
case 'committer':
if (property_exists($payload, 'pusher') && property_exists($payload->pusher, 'email')) {
return $payload->pusher->email;
}
}
// fallback
return NULL;
}
/**
* Add requied JavaScript and CSS to page
*/
public function onAssetsInitialized(): void
{
if (!$this->isOnRoute() || !$this->grav['user']->authorize('admin.publisher')) {
return;
}
/** @var Assets */
$assets = $this->grav['assets'];
$assets->addJs("plugin://pushy/js/pushy-admin.js", ['type' => 'module']);
$assets->addInlineJs($this->getTranslations());
$assets->addCss("plugin://pushy/css/pushy-admin.css");
}
/**
* Check if the request is made by the Pushy plugin.
*
* @return bool
*/
protected function isOnRoute(): bool
{
Assert($this->config !== null, 'Config has not been initialized');
$currentPath = $this->grav['uri']->path();
$publishPath = $this->config->get('plugins.admin.route') . "/$this->admin_route";
return $currentPath === $publishPath;
}
/**
* Get translations for front-end
*/
protected function getTranslations(): string{
$isInitialized = GitUtils::isGitInitialized();
// TODO: test for GitUtils::isGitInstalled()
$menuLabel = $isInitialized ? $this->translate('MENU_LABEL_PUBLISH') : $this->translate('MENU_LABEL_CONFIG');
$translations = "const pushy = {
translations: {
menuLabel: '$menuLabel',
listHeaderStatus: '{$this->translate("LIST_HEADER_STATUS")}',
listHeaderPath: '{$this->translate("LIST_HEADER_PATH")}',
listHeaderEdit: '{$this->translate("LIST_HEADER_EDIT")}',
fetchInvalidResponse: '{$this->translate("FETCH_INVALID_RESPONSE")}',
fetchException: '{$this->translate("FETCH_EXCEPTION")}',
fetchItemsFound: '{$this->translate("FETCH_ITEMS_FOUND")}',
fetchNoItemsFound: '{$this->translate("FETCH_NO_ITEMS_FOUND")}',
publishIinvalidResponse: '{$this->translate("PUBLISH_INVALID_RESPONSE")}',
publishException: '{$this->translate("PUBLISH_EXCEPTION")}',
statusNew: '{$this->translate("STATUS_NEW")}',
statusModified: '{$this->translate("STATUS_MODIFIED")}',
statusDeleted: '{$this->translate("STATUS_DELETED")}',
statusRenamed: '{$this->translate("STATUS_RENAMED")}',
}
};";
return $translations;
}
private function translate(string $key, ?string $arg = null) : string {
$prefix = 'PLUGIN_PUSHY';
$user = $this->grav['user'];
$language = $user['language'];
$translation = $this->grav['language']->translate(["$prefix.$key", $arg], [$language]);
if ($translation == "$prefix.$key") {
$translation = $this->grav['language']->translate(["$prefix.$key", $arg], ['en']);
}
return $translation;
}
}