-
Notifications
You must be signed in to change notification settings - Fork 58
/
git-sync.php
490 lines (420 loc) · 14.5 KB
/
git-sync.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
485
486
487
488
489
490
<?php
namespace Grav\Plugin;
use Composer\Autoload\ClassLoader;
use Grav\Common\Config\Config;
use Grav\Common\Data\Data;
use Grav\Common\Grav;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Common\Plugin;
use Grav\Common\Scheduler\Scheduler;
use Grav\Plugin\GitSync\AdminController;
use Grav\Plugin\GitSync\GitSync;
use Grav\Plugin\GitSync\Helper;
use RocketTheme\Toolbox\Event\Event;
/**
* Class GitSyncPlugin
*
* @package Grav\Plugin
*/
class GitSyncPlugin extends Plugin
{
/** @var AdminController|null */
protected $controller;
/** @var GitSync */
protected $git;
/**
* @return array
*/
public static function getSubscribedEvents()
{
return [
'onPluginsInitialized' => [
['autoload', 100000],
['onPluginsInitialized', 1000]
],
'onPageInitialized' => ['onPageInitialized', 0],
'onFormProcessed' => ['onFormProcessed', 0],
'onSchedulerInitialized' => ['onSchedulerInitialized', 0]
];
}
/**
* [onPluginsInitialized:100000] Composer autoload.
*
* @return ClassLoader
*/
public function autoload() : ClassLoader
{
return require __DIR__ . '/vendor/autoload.php';
}
/**
* @return string
*/
public static function generateWebhookSecret()
{
return static::generateHash(24);
}
/**
* @return string
*/
public static function generateRandomWebhook()
{
return '/_git-sync-' . static::generateHash(6);
}
/**
* Initialize the plugin
*/
public function onPluginsInitialized()
{
$this->enable(['gitsync' => ['synchronize', 0]]);
$this->init();
if ($this->isAdmin()) {
$this->enable([
'onTwigTemplatePaths' => ['onTwigTemplatePaths', 0],
'onTwigSiteVariables' => ['onTwigSiteVariables', 0],
'onAdminMenu' => ['onAdminMenu', 0],
'onAdminSave' => ['onAdminSave', 0],
'onAdminAfterSave' => ['onAdminAfterSave', 0],
'onAdminAfterSaveAs' => ['onAdminAfterSaveAs', 0],
'onAdminAfterDelete' => ['onAdminAfterDelete', 0],
'onAdminAfterAddMedia' => ['onAdminAfterMedia', 0],
'onAdminAfterDelMedia' => ['onAdminAfterMedia', 0],
]);
return;
}
$config = $this->config->get('plugins.' . $this->name);
$route = $this->grav['uri']->route();
$webhook = $config['webhook'] ?? false;
$secret = $config['webhook_secret'] ?? false;
$enabled = $config['webhook_enabled'] ?? false;
if ($enabled && $route === $webhook && $_SERVER['REQUEST_METHOD'] === 'POST') {
if ($secret) {
if (!$this->isRequestAuthorized($secret)) {
http_response_code(401);
header('Content-Type: application/json');
echo json_encode([
'status' => 'error',
'message' => 'Unauthorized request'
]);
exit;
}
}
try {
$this->synchronize();
header('Content-Type: application/json');
echo json_encode([
'status' => 'success',
'message' => 'GitSync completed the synchronization'
]);
} catch (\Exception $e) {
http_response_code(500);
header('Content-Type: application/json');
echo json_encode([
'status' => 'error',
'message' => 'GitSync failed to synchronize'
]);
}
exit;
}
}
/**
* 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
*/
public function isRequestAuthorized($secret)
{
if (isset($_SERVER['HTTP_X_HUB_SIGNATURE'])) {
$payload = file_get_contents('php://input') ?: '';
return $this->isGithubSignatureValid($secret, $_SERVER['HTTP_X_HUB_SIGNATURE'], $payload);
}
if (isset($_SERVER['HTTP_X_GITLAB_TOKEN'])) {
return $this->isGitlabTokenValid($secret, $_SERVER['HTTP_X_GITLAB_TOKEN']);
} else {
$payload = file_get_contents('php://input');
return $this->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
*/
public function isGithubSignatureValid($secret, $signatureHeader, $payload)
{
[$algorithm, $signature] = explode('=', $signatureHeader);
return $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
*/
public function isGitlabTokenValid($secret, $token)
{
return $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 boolean Whether the client secret matches the payload secret or
* not
*/
public function isGiteaSecretValid($secret, $payload)
{
$payload = json_decode($payload, true);
if (!empty($payload) && isset($payload['secret'])) {
return $secret === $payload['secret'];
}
return false;
}
public function onAdminMenu()
{
$base = rtrim($this->grav['base_url'], '/') . '/' . trim($this->grav['admin']->base, '/');
$options = [
'hint' => Helper::isGitInitialized() ? 'Synchronize GitSync' : 'Configure GitSync',
'class' => 'gitsync-sync',
'location' => 'pages',
'route' => Helper::isGitInitialized() ? 'admin' : 'admin/plugins/git-sync',
'icon' => 'fa-' . $this->grav['plugins']->get('git-sync')->blueprints()->get('icon')
];
if (Helper::isGitInstalled()) {
if (Helper::isGitInitialized()) {
$options['data'] = [
'gitsync-useraction' => 'sync',
'gitsync-uri' => $base . '/plugins/git-sync'
];
}
$this->grav['twig']->plugins_quick_tray['GitSync'] = $options;
}
}
public function init()
{
if ($this->isAdmin()) {
/** @var AdminController controller */
$this->controller = new AdminController($this);
$this->git = &$this->controller->git;
} else {
$this->git = new GitSync();
}
}
/**
* @return bool
*/
public function synchronize()
{
if (!Helper::isGitInstalled() || !Helper::isGitInitialized()) {
return true;
}
$this->grav->fireEvent('onGitSyncBeforeSynchronize');
if ($this->git->hasChangesToCommit()) {
$this->git->commit();
}
// synchronize with remote
$this->git->sync();
$this->grav->fireEvent('onGitSyncAfterSynchronize');
return true;
}
public function onSchedulerInitialized(Event $event)
{
/** @var Config $config */
$config = Grav::instance()['config'];
$run_at = $config->get('plugins.git-sync.sync.cron_at', '0 12,23 * * *');
if ($config->get('plugins.git-sync.sync.cron_enable', false)) {
/** @var Scheduler $scheduler */
$scheduler = $event['scheduler'];
$job = $scheduler->addFunction('Grav\Plugin\GitSync\Helper::synchronize', [], 'GitSync');
$job->at($run_at);
}
}
/**
* @return bool
*/
public function reset()
{
if (!Helper::isGitInstalled() || !Helper::isGitInitialized()) {
return true;
}
$this->grav->fireEvent('onGitSyncBeforeReset');
$this->git->reset();
$this->grav->fireEvent('onGitSyncAfterReset');
return true;
}
/**
* Add current directory to twig lookup paths.
*/
public function onTwigTemplatePaths()
{
$this->grav['twig']->twig_paths[] = __DIR__ . '/templates';
}
/**
* Set needed variables to display cart.
*
* @return bool
*/
public function onTwigSiteVariables()
{
// workaround for admin plugin issue that doesn't properly unsubscribe events upon plugin uninstall
if (!class_exists(Helper::class)) {
return false;
}
$user = $this->grav['user'];
if (!$user->authenticated) {
return false;
}
$settings = [
'first_time' => !Helper::isGitInitialized(),
'git_installed' => Helper::isGitInstalled()
];
$this->grav['twig']->twig_vars['git_sync'] = $settings;
$adminPath = trim($this->grav['admin']->base, '/');
if ($this->grav['uri']->path() === "/$adminPath/plugins/git-sync") {
$this->grav['assets']->addCss('plugin://git-sync/css-compiled/git-sync.css');
} else {
$this->grav['assets']->addInlineJs('var GitSync = ' . json_encode($settings) . ';');
}
$this->grav['assets']->addJs('plugin://git-sync/js/vendor.js', ['loading' => 'defer', 'priority' => 0]);
$this->grav['assets']->addJs('plugin://git-sync/js/app.js', ['loading' => 'defer', 'priority' => 0]);
$this->grav['assets']->addCss('plugin://git-sync/css-compiled/git-sync-icon.css');
return true;
}
public function onPageInitialized()
{
if ($this->controller && $this->controller->isActive()) {
$this->controller->execute();
$this->controller->redirect();
}
}
/**
* @param Event $event
* @return Data|true
*/
public function onAdminSave(Event $event)
{
$obj = $event['object'];
$adminPath = trim($this->grav['admin']->base, '/');
$isPluginRoute = $this->grav['uri']->path() === "/$adminPath/plugins/" . $this->name;
if ($obj instanceof Data) {
if (!$isPluginRoute || !Helper::isGitInstalled()) {
return true;
}
// empty password, keep current one or encrypt if haven't already
$password = $obj->get('password', false);
if (!$password) { // set to !()
$current_password = $this->git->getPassword();
// password exists but was never encrypted
if ($current_password && strpos($current_password, 'gitsync-') !== 0) {
$current_password = Helper::encrypt($current_password);
}
} else {
// password is getting changed
$current_password = Helper::encrypt($password);
}
$obj->set('password', $current_password);
}
return $obj;
}
/**
* @param Event $event
*/
public function onAdminAfterSave(Event $event)
{
$obj = $event['object'];
$adminPath = trim($this->grav['admin']->base, '/');
$uriPath = $this->grav['uri']->path();
$isPluginRoute = $uriPath === "/$adminPath/plugins/" . $this->name;
if ($obj instanceof PageInterface && !$this->grav['config']->get('plugins.git-sync.sync.on_save', true)) {
return;
}
if ($obj instanceof Data) {
$folders = $this->git->getConfig('folders', $event['object']->get('folders', []));
$data_type = preg_replace('#^/' . preg_quote($adminPath, '#') . '/#', '', $uriPath);
$data_type = explode('/', $data_type);
$data_type = array_shift($data_type);
if (null === $data_type || !Helper::isGitInstalled() || (!$isPluginRoute && !in_array($this->getFolderMapping($data_type), $folders, true))) {
return;
}
if ($isPluginRoute) {
$this->git->setConfig($obj->toArray());
// initialize git if not done yet
$this->git->initializeRepository();
// set committer and remote data
$this->git->setUser();
$this->git->addRemote();
}
}
$this->synchronize();
}
public function onAdminAfterSaveAs()
{
if ($this->grav['config']->get('plugins.git-sync.sync.on_save', true))
{
$this->synchronize();
}
}
public function onAdminAfterDelete()
{
if ($this->grav['config']->get('plugins.git-sync.sync.on_delete', true))
{
$this->synchronize();
}
}
public function onAdminAfterMedia()
{
if ($this->grav['config']->get('plugins.git-sync.sync.on_media', true))
{
$this->synchronize();
}
}
/**
* @param Event $event
*/
public function onFormProcessed(Event $event)
{
$action = $event['action'];
if ($action === 'gitsync') {
$this->synchronize();
}
}
/**
* @param string $data_type
* @return string|null
*/
public function getFolderMapping($data_type)
{
switch ($data_type) {
case 'user':
return 'accounts';
case 'themes':
return 'config';
case 'config':
case 'data':
case 'plugins':
case 'pages':
return $data_type;
}
return null;
}
/**
* @param int $len
* @return string
*/
protected static function generateHash(int $len): string
{
$bytes = openssl_random_pseudo_bytes($len, $isStrong);
if ($bytes === false) {
throw new \RuntimeException('Could not generate hash');
}
if ($isStrong === false) {
// It's ok not to be strong [EA].
$isStrong = true;
}
return bin2hex($bytes);
}
}