forked from getgrav/grav-plugin-admin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
admin.php
413 lines (344 loc) · 13 KB
/
admin.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
<?php
namespace Grav\Plugin;
use Grav\Common\GPM\GPM;
use Grav\Common\Grav;
use Grav\Common\Language\Language;
use Grav\Common\Page\Page;
use Grav\Common\Page\Pages;
use Grav\Common\Plugin;
use Grav\Common\Uri;
use RocketTheme\Toolbox\File\File;
use RocketTheme\Toolbox\Event\Event;
use RocketTheme\Toolbox\Session\Session;
class AdminPlugin extends Plugin
{
/**
* @var bool
*/
protected $active = false;
/**
* @var string
*/
protected $template;
/**
* @var string
*/
protected $theme;
/**
* @var string
*/
protected $route;
/**
* @var Uri
*/
protected $uri;
/**
* @var Admin
*/
protected $admin;
/**
* @var Session
*/
protected $session;
/**
* @var Popularity
*/
protected $popularity;
/**
* @var string
*/
protected $base;
/**
* @return array
*/
public static function getSubscribedEvents()
{
return [
'onPluginsInitialized' => [['login', 100000], ['onPluginsInitialized', 1000]],
'onShutdown' => ['onShutdown', 1000]
];
}
/**
* If the admin path matches, initialize the Login plugin configuration and set the admin
* as active.
*/
public function login()
{
// Check for Pro version is enabled
if ($this->config->get('plugins.admin-pro.enabled')) {
$this->active = false;
return;
}
$route = $this->config->get('plugins.admin.route');
if (!$route) {
return;
}
$this->grav['debugger']->addMessage("Admin Basic");
$this->base = '/' . trim($route, '/');
$this->uri = $this->grav['uri'];
// Only activate admin if we're inside the admin path.
if ($this->uri->route() == $this->base ||
substr($this->uri->route(), 0, strlen($this->base) + 1) == $this->base . '/') {
$this->active = true;
}
}
/**
* If the admin plugin is set as active, initialize the admin
*/
public function onPluginsInitialized()
{
// Only activate admin if we're inside the admin path.
if ($this->active) {
$this->initializeAdmin();
}
// Disable Asset pipelining
$this->config->set('system.assets.css_pipeline', false);
$this->config->set('system.assets.js_pipeline', false);
// We need popularity no matter what
require_once __DIR__ . '/classes/popularity.php';
$this->popularity = new Popularity();
}
/**
* Sets longer path to the home page allowing us to have list of pages when we enter to pages section.
*/
public function onPagesInitialized()
{
$this->session = $this->grav['session'];
// Set original route for the home page.
$home = '/' . trim($this->config->get('system.home.alias'), '/');
// set the default if not set before
$this->session->expert = $this->session->expert ?: false;
// set session variable if it's passed via the url
if ($this->uri->param('mode') == 'expert') {
$this->session->expert = true;
} elseif ($this->uri->param('mode') == 'normal') {
$this->session->expert = false;
}
// check for existence of a user account
$account_dir = $file_path = $this->grav['locator']->findResource('account://');
$user_check = (array) glob($account_dir . '/*.yaml');
if (!count($user_check) > 0) {
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.NO_USER_ACCOUNTS'), 'info');
}
/** @var Pages $pages */
$pages = $this->grav['pages'];
$this->grav['admin']->routes = $pages->routes();
// Remove default route from routes.
if (isset($this->grav['admin']->routes['/'])) {
unset($this->grav['admin']->routes['/']);
}
$page = $pages->dispatch('/', true);
// If page is null, the default page does not exist, and we cannot route to it
if ($page) {
$page->route($home);
}
// Make local copy of POST.
$post = !empty($_POST) ? $_POST : array();
// Handle tasks.
$this->admin->task = $task = !empty($post['task']) ? $post['task'] : $this->uri->param('task');
if ($task) {
require_once __DIR__ . '/classes/controller.php';
$controller = new AdminController($this->grav, $this->template, $task, $this->route, $post);
$controller->execute();
$controller->redirect();
} elseif ($this->template == 'logs' && $this->route) {
// Display RAW error message.
echo $this->admin->logEntry();
exit();
}
$self = $this;
// Replace page service with admin.
$this->grav['page'] = function () use ($self) {
$page = new Page;
if (file_exists(__DIR__ . "/pages/admin/{$self->template}.md")) {
$page->init(new \SplFileInfo(__DIR__ . "/pages/admin/{$self->template}.md"));
$page->slug(basename($self->template));
return $page;
}
// If the page cannot be found, try looking in plugins.
// Allows pages added by plugins in admin
$plugins = Grav::instance()['config']->get('plugins', []);
foreach($plugins as $plugin => $data) {
$folder = GRAV_ROOT . "/user/plugins/" . $plugin . "/admin";
if (file_exists($folder)) {
$file = $folder . "/pages/{$self->template}.md";
if (file_exists($file)) {
$page->init(new \SplFileInfo($file));
$page->slug(basename($self->template));
return $page;
}
}
}
};
}
/**
* Add twig paths to plugin templates.
*/
public function onTwigTemplatePaths()
{
$twig_paths = [];
$this->grav->fireEvent('onAdminTwigTemplatePaths', new Event(['paths' => &$twig_paths]));
$twig_paths[] = __DIR__ . '/themes/' . $this->theme . '/templates';
$this->grav['twig']->twig_paths = $twig_paths;
}
/**
* Set all twig variables for generating output.
*/
public function onTwigSiteVariables()
{
$twig = $this->grav['twig'];
// Dynamic type support
$format = $this->uri->extension();
$ext = '.' . ($format ? $format : 'html') . TWIG_EXT;
$twig->twig_vars['location'] = $this->template;
$twig->twig_vars['base_url_relative_frontend'] = $twig->twig_vars['base_url_relative'] ?: '/';
$twig->twig_vars['admin_route'] = trim($this->config->get('plugins.admin.route'), '/');
$twig->twig_vars['base_url_relative'] .=
($twig->twig_vars['base_url_relative'] != '/' ? '/' : '') . $twig->twig_vars['admin_route'];
$twig->twig_vars['theme_url'] = '/user/plugins/admin/themes/' . $this->theme;
$twig->twig_vars['base_url'] = $twig->twig_vars['base_url_relative'];
$twig->twig_vars['base_path'] = GRAV_ROOT;
$twig->twig_vars['admin'] = $this->admin;
// Gather Plugin-hooked nav items
$this->grav->fireEvent('onAdminTemplateNavPluginHook');
switch ($this->template) {
case 'dashboard':
$twig->twig_vars['popularity'] = $this->popularity;
break;
case 'pages':
$page = $this->admin->page(true);
if ($page != null) {
$twig->twig_vars['file'] = File::instance($page->filePath());
$twig->twig_vars['media_types'] = str_replace('defaults,', '',
implode(',.', array_keys($this->config->get('media'))));
}
break;
}
}
public function onShutdown()
{
// Just so we know that we're in this debug mode
if ($this->config->get('plugins.admin.popularity.enabled')) {
// Only track non-admin
if (!$this->active) {
$this->popularity->trackHit();
}
}
}
/**
* Handles getting GPM updates
*/
public function onTaskGPM()
{
$action = $_POST['action']; // getUpdatable | getUpdatablePlugins | getUpdatableThemes | gravUpdates
$flush = isset($_POST['flush']) && $_POST['flush'] == true ? true : false;
if (isset($this->grav['session'])) {
$this->grav['session']->close();
}
try {
$gpm = new GPM($flush);
switch ($action) {
case 'getUpdates':
$resources_updates = $gpm->getUpdatable();
$grav_updates = [
"isUpdatable" => $gpm->grav->isUpdatable(),
"assets" => $gpm->grav->getAssets(),
"version" => GRAV_VERSION,
"available" => $gpm->grav->getVersion(),
"date" => $gpm->grav->getDate(),
"isSymlink" => $gpm->grav->isSymlink()
];
echo json_encode([
"status" => "success",
"payload" => ["resources" => $resources_updates, "grav" => $grav_updates, "installed" => $gpm->countInstalled(), 'flushed' => $flush]
]);
break;
}
} catch (\Exception $e) {
echo json_encode(["status" => "error", "message" => $e->getMessage()]);
}
exit;
}
/**
* Initialize the admin.
*
* @throws \RuntimeException
*/
protected function initializeAdmin()
{
$this->enable([
'onTwigExtensions' => ['onTwigExtensions', 1000],
'onPagesInitialized' => ['onPagesInitialized', 1000],
'onTwigTemplatePaths' => ['onTwigTemplatePaths', 1000],
'onTwigSiteVariables' => ['onTwigSiteVariables', 1000],
'onTask.GPM' => ['onTaskGPM', 0]
]);
// Check for required plugins
if (!$this->grav['config']->get('plugins.login.enabled') ||
!$this->grav['config']->get('plugins.form.enabled') ||
!$this->grav['config']->get('plugins.email.enabled')) {
throw new \RuntimeException('One of the required plugins is missing or not enabled');
}
// Double check we have system.yaml and site.yaml
$config_files[] = $this->grav['locator']->findResource('user://config') . '/system.yaml';
$config_files[] = $this->grav['locator']->findResource('user://config') . '/site.yaml';
foreach ($config_files as $config_file) {
if (!file_exists($config_file)) {
touch($config_file);
}
}
// Decide admin template and route.
$path = trim(substr($this->uri->route(), strlen($this->base)), '/');
$this->template = 'dashboard';
if ($path) {
$array = explode('/', $path, 2);
$this->template = array_shift($array);
$this->route = array_shift($array);
}
/** @var Language $language */
// $require_language = ['pages', 'translations'];
// $language = $this->grav['language'];
// if ($language->isLanguageInUrl() && !in_array($this->template, $require_language)) {
// $this->grav->redirect($this->uri->route());
// }
// Initialize admin class.
require_once __DIR__ . '/classes/admin.php';
$this->admin = new Admin($this->grav, $this->base, $this->template, $this->route);
// And store the class into DI container.
$this->grav['admin'] = $this->admin;
// Get theme for admin
$this->theme = $this->config->get('plugins.admin.theme', 'grav');
$assets = $this->grav['assets'];
$translations = 'if (!window.translations) window.translations = {}; ' . PHP_EOL . 'window.translations.PLUGIN_ADMIN = {};' . PHP_EOL;
$strings = ['EVERYTHING_UP_TO_DATE',
'UPDATES_ARE_AVAILABLE',
'IS_AVAILABLE_FOR_UPDATE',
'AND',
'IS_NOW_AVAILABLE',
'CURRENT',
'UPDATE_GRAV_NOW',
'TASK_COMPLETED',
'UPDATE',
'UPDATING_PLEASE_WAIT',
'GRAV_SYMBOLICALLY_LINKED',
'OF_YOUR',
'OF_THIS',
'HAVE_AN_UPDATE_AVAILABLE',
'UPDATE_AVAILABLE',
'UPDATES_AVAILABLE',
'FULLY_UPDATED',
'DAYS'];
foreach($strings as $string) {
$translations .= 'translations.PLUGIN_ADMIN.' . $string .' = "' . $this->admin->translate('PLUGIN_ADMIN.' . $string) . '"; ' . PHP_EOL;;
}
$assets->addInlineJs($translations);
}
/**
* Add Twig Extensions
*/
public function onTwigExtensions()
{
require_once(__DIR__.'/twig/AdminTwigExtension.php');
$this->grav['twig']->twig->addExtension(new AdminTwigExtension());
}
}