admin.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  1. <?php
  2. namespace Grav\Plugin;
  3. use Composer\Autoload\ClassLoader;
  4. use Grav\Common\Cache;
  5. use Grav\Common\Debugger;
  6. use Grav\Common\File\CompiledYamlFile;
  7. use Grav\Common\Grav;
  8. use Grav\Common\Helpers\LogViewer;
  9. use Grav\Common\Inflector;
  10. use Grav\Common\Language\Language;
  11. use Grav\Common\Page\Interfaces\PageInterface;
  12. use Grav\Common\Page\Page;
  13. use Grav\Common\Page\Pages;
  14. use Grav\Common\Plugin;
  15. use Grav\Common\Session;
  16. use Grav\Common\Uri;
  17. use Grav\Common\User\Interfaces\UserCollectionInterface;
  18. use Grav\Common\Utils;
  19. use Grav\Framework\Session\Exceptions\SessionException;
  20. use Grav\Plugin\Admin\Admin;
  21. use Grav\Plugin\Admin\Popularity;
  22. use Grav\Plugin\Admin\Themes;
  23. use Grav\Plugin\Admin\AdminController;
  24. use Grav\Plugin\Admin\Twig\AdminTwigExtension;
  25. use Grav\Plugin\Form\Form;
  26. use Grav\Plugin\Login\Login;
  27. use RocketTheme\Toolbox\Event\Event;
  28. class AdminPlugin extends Plugin
  29. {
  30. public $features = [
  31. 'blueprints' => 1000,
  32. ];
  33. /** @var bool */
  34. protected $active = false;
  35. /** @var string */
  36. protected $template;
  37. /** @var string */
  38. protected $theme;
  39. /** @var string */
  40. protected $route;
  41. /** @var string */
  42. protected $admin_route;
  43. /** @var Uri */
  44. protected $uri;
  45. /** @var Admin */
  46. protected $admin;
  47. /** @var Session */
  48. protected $session;
  49. /** @var Popularity */
  50. protected $popularity;
  51. /** @var string */
  52. protected $base;
  53. /** @var string */
  54. protected $version;
  55. /**
  56. * @return array
  57. */
  58. public static function getSubscribedEvents()
  59. {
  60. return [
  61. 'onPluginsInitialized' => [
  62. ['autoload', 100001],
  63. ['setup', 100000],
  64. ['onPluginsInitialized', 1001]
  65. ],
  66. 'onPageInitialized' => ['onPageInitialized', 0],
  67. 'onFormProcessed' => ['onFormProcessed', 0],
  68. 'onShutdown' => ['onShutdown', 1000],
  69. 'onAdminDashboard' => ['onAdminDashboard', 0],
  70. 'onAdminTools' => ['onAdminTools', 0],
  71. ];
  72. }
  73. /**
  74. * Get list of form field types specified in this plugin. Only special types needs to be listed.
  75. *
  76. * @return array
  77. */
  78. public function getFormFieldTypes()
  79. {
  80. return [
  81. 'column' => [
  82. 'input@' => false
  83. ],
  84. 'columns' => [
  85. 'input@' => false
  86. ],
  87. 'fieldset' => [
  88. 'input@' => false
  89. ],
  90. 'section' => [
  91. 'input@' => false
  92. ],
  93. 'list' => [
  94. 'array' => true
  95. ],
  96. 'file' => [
  97. 'array' => true
  98. ]
  99. ];
  100. }
  101. /**
  102. * [onPluginsInitialized:100000] Composer autoload.
  103. *
  104. * @return ClassLoader
  105. */
  106. public function autoload()
  107. {
  108. return require __DIR__ . '/vendor/autoload.php';
  109. }
  110. /**
  111. * [onPluginsInitialized:100000]
  112. *
  113. * If the admin path matches, initialize the Login plugin configuration and set the admin
  114. * as active.
  115. */
  116. public function setup()
  117. {
  118. $route = $this->config->get('plugins.admin.route');
  119. if (!$route) {
  120. return;
  121. }
  122. $this->base = '/' . trim($route, '/');
  123. $this->admin_route = rtrim($this->grav['pages']->base(), '/') . $this->base;
  124. $this->uri = $this->grav['uri'];
  125. $users_exist = Admin::doAnyUsersExist();
  126. // If no users found, go to register
  127. if (!$users_exist) {
  128. if (!$this->isAdminPath()) {
  129. $this->grav->redirect($this->admin_route);
  130. }
  131. $this->template = 'register';
  132. }
  133. // Only activate admin if we're inside the admin path.
  134. if ($this->isAdminPath()) {
  135. try {
  136. $this->grav['session']->init();
  137. } catch (SessionException $e) {
  138. $this->grav['session']->init();
  139. $message = 'Session corruption detected, restarting session...';
  140. /** @var Debugger $debugger */
  141. $debugger = $this->grav['debugger'];
  142. $debugger->addMessage($message);
  143. $this->grav['messages']->add($message, 'error');
  144. }
  145. $this->active = true;
  146. // Set cache based on admin_cache option
  147. $this->grav['cache']->setEnabled($this->config->get('plugins.admin.cache_enabled'));
  148. $pages = $this->grav['pages'];
  149. if (method_exists($pages, 'setCheckMethod')) {
  150. // Force file hash checks to fix caching on moved and deleted pages.
  151. $pages->setCheckMethod('hash');
  152. }
  153. }
  154. }
  155. /**
  156. * [onPluginsInitialized:1001]
  157. *
  158. * If the admin plugin is set as active, initialize the admin
  159. */
  160. public function onPluginsInitialized()
  161. {
  162. // Only activate admin if we're inside the admin path.
  163. if ($this->active) {
  164. // Store this version.
  165. $this->version = $this->getBlueprint()->get('version');
  166. // Have a unique Admin-only Cache key
  167. if (method_exists($this->grav['cache'], 'setKey')) {
  168. /** @var Cache $cache */
  169. $cache = $this->grav['cache'];
  170. $cache_key = $cache->getKey();
  171. $cache->setKey($cache_key . '$');
  172. }
  173. // Turn on Twig autoescaping
  174. if (method_exists($this->grav['twig'], 'setAutoescape') && $this->grav['uri']->param('task') !== 'processmarkdown') {
  175. $this->grav['twig']->setAutoescape(true);
  176. }
  177. $this->grav['debugger']->addMessage('Admin v' . $this->version);
  178. $this->initializeAdmin();
  179. // Disable Asset pipelining (old method - remove this after Grav is updated)
  180. if (!method_exists($this->grav['assets'], 'setJsPipeline')) {
  181. $this->config->set('system.assets.css_pipeline', false);
  182. $this->config->set('system.assets.js_pipeline', false);
  183. }
  184. // Replace themes service with admin.
  185. $this->grav['themes'] = function () {
  186. return new Themes($this->grav);
  187. };
  188. }
  189. // We need popularity no matter what
  190. $this->popularity = new Popularity();
  191. // Fire even to register permissions from other plugins
  192. $this->grav->fireEvent('onAdminRegisterPermissions', new Event(['admin' => $this->admin]));
  193. }
  194. /**
  195. * [onPageInitialized:0]
  196. */
  197. public function onPageInitialized()
  198. {
  199. $page = $this->grav['page'];
  200. $template = $this->grav['uri']->param('tmpl');
  201. if ($template) {
  202. $page->template($template);
  203. }
  204. }
  205. /**
  206. * [onFormProcessed:0]
  207. *
  208. * Process the admin registration form.
  209. *
  210. * @param Event $event
  211. */
  212. public function onFormProcessed(Event $event)
  213. {
  214. $form = $event['form'];
  215. $action = $event['action'];
  216. switch ($action) {
  217. case 'register_admin_user':
  218. if (Admin::doAnyUsersExist()) {
  219. throw new \RuntimeException('A user account already exists, please create an admin account manually.');
  220. }
  221. if (!$this->config->get('plugins.login.enabled')) {
  222. throw new \RuntimeException($this->grav['language']->translate('PLUGIN_LOGIN.PLUGIN_LOGIN_DISABLED'));
  223. }
  224. $data = [];
  225. $username = $form->value('username');
  226. if ($form->value('password1') !== $form->value('password2')) {
  227. $this->grav->fireEvent('onFormValidationError', new Event([
  228. 'form' => $form,
  229. 'message' => $this->grav['language']->translate('PLUGIN_LOGIN.PASSWORDS_DO_NOT_MATCH')
  230. ]));
  231. $event->stopPropagation();
  232. return;
  233. }
  234. $data['password'] = $form->value('password1');
  235. $fields = [
  236. 'email',
  237. 'fullname',
  238. 'title'
  239. ];
  240. foreach ($fields as $field) {
  241. // Process value of field if set in the page process.register_user
  242. if (!isset($data[$field]) && $form->value($field)) {
  243. $data[$field] = $form->value($field);
  244. }
  245. }
  246. // Don't store plain text password or username (part of the filename).
  247. unset($data['password1'], $data['password2'], $data['username']);
  248. // Extra lowercase to ensure file is saved lowercase
  249. $username = strtolower($username);
  250. $inflector = new Inflector();
  251. $data['fullname'] = $data['fullname'] ?? $inflector->titleize($username);
  252. $data['title'] = $data['title'] ?? 'Administrator';
  253. $data['state'] = 'enabled';
  254. $data['access'] = ['admin' => ['login' => true, 'super' => true], 'site' => ['login' => true]];
  255. /** @var UserCollectionInterface $users */
  256. $users = $this->grav['accounts'];
  257. // Create user object and save it
  258. $user = $users->load($username);
  259. $user->update($data);
  260. $user->save();
  261. //Login user
  262. $this->grav['session']->user = $user;
  263. unset($this->grav['user']);
  264. $this->grav['user'] = $user;
  265. $user->authenticated = true;
  266. $user->authorized = $user->authorize('admin.login');
  267. $messages = $this->grav['messages'];
  268. $messages->add($this->grav['language']->translate('PLUGIN_ADMIN.LOGIN_LOGGED_IN'), 'info');
  269. $this->grav->redirect($this->admin_route);
  270. break;
  271. }
  272. }
  273. /**
  274. * [onShutdown:1000]
  275. *
  276. * Handles the shutdown
  277. */
  278. public function onShutdown()
  279. {
  280. if ($this->active) {
  281. //only activate when Admin is active
  282. if ($this->admin->shouldLoadAdditionalFilesInBackground()) {
  283. $this->admin->loadAdditionalFilesInBackground();
  284. }
  285. } else {
  286. //if popularity is enabled, track non-admin hits
  287. if ($this->config->get('plugins.admin.popularity.enabled')) {
  288. $this->popularity->trackHit();
  289. }
  290. }
  291. }
  292. /**
  293. * [onAdminDashboard:0]
  294. */
  295. public function onAdminDashboard()
  296. {
  297. $this->grav['twig']->plugins_hooked_dashboard_widgets_top[] = ['template' => 'dashboard-maintenance'];
  298. $this->grav['twig']->plugins_hooked_dashboard_widgets_top[] = ['template' => 'dashboard-statistics'];
  299. $this->grav['twig']->plugins_hooked_dashboard_widgets_top[] = ['template' => 'dashboard-notifications'];
  300. $this->grav['twig']->plugins_hooked_dashboard_widgets_top[] = ['template' => 'dashboard-feed'];
  301. $this->grav['twig']->plugins_hooked_dashboard_widgets_main[] = ['template' => 'dashboard-pages'];
  302. }
  303. /**
  304. * [onAdminTools:0]
  305. *
  306. * Provide the tools for the Tools page, currently only direct install
  307. *
  308. * @return Event
  309. */
  310. public function onAdminTools(Event $event)
  311. {
  312. $event['tools'] = array_merge($event['tools'], [
  313. 'backups' => [['admin.maintenance', 'admin.super'], $this->grav['language']->translate('PLUGIN_ADMIN.BACKUPS')],
  314. 'scheduler' => [['admin.super'], $this->grav['language']->translate('PLUGIN_ADMIN.SCHEDULER')],
  315. 'logs' => [['admin.super'], $this->grav['language']->translate('PLUGIN_ADMIN.LOGS')],
  316. 'reports' => [['admin.super'], $this->grav['language']->translate('PLUGIN_ADMIN.REPORTS')],
  317. 'direct-install' => [['admin.super'], $this->grav['language']->translate('PLUGIN_ADMIN.DIRECT_INSTALL')],
  318. ]);
  319. return $event;
  320. }
  321. /**
  322. * Sets longer path to the home page allowing us to have list of pages when we enter to pages section.
  323. */
  324. public function onPagesInitialized()
  325. {
  326. $config = $this->config;
  327. // Force SSL with redirect if required
  328. if ($config->get('system.force_ssl')) {
  329. if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] !== 'on') {
  330. $url = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  331. $this->grav->redirect($url);
  332. }
  333. }
  334. $this->session = $this->grav['session'];
  335. // Set original route for the home page.
  336. $home = '/' . trim($this->config->get('system.home.alias'), '/');
  337. // set session variable if it's passed via the url
  338. if ($this->uri->param('mode') === 'expert') {
  339. $this->session->expert = true;
  340. } elseif ($this->uri->param('mode') === 'normal') {
  341. $this->session->expert = false;
  342. } else {
  343. // set the default if not set before
  344. $this->session->expert = $this->session->expert ?? false;
  345. }
  346. /** @var Pages $pages */
  347. $pages = $this->grav['pages'];
  348. $this->grav['admin']->routes = $pages->routes();
  349. // Remove default route from routes.
  350. if (isset($this->grav['admin']->routes['/'])) {
  351. unset($this->grav['admin']->routes['/']);
  352. }
  353. $page = $pages->dispatch('/', true);
  354. // If page is null, the default page does not exist, and we cannot route to it
  355. if ($page) {
  356. $page->route($home);
  357. }
  358. // Make local copy of POST.
  359. $post = $this->grav['uri']->post();
  360. // Initialize Page Types
  361. Pages::types();
  362. // Handle tasks.
  363. $this->admin->task = $task = $this->grav['task'] ?? $this->grav['action'];
  364. if ($task) {
  365. $this->initializeController($task, $post);
  366. } elseif ($this->template === 'logs' && $this->route) {
  367. // Display RAW error message.
  368. echo $this->admin->logEntry();
  369. exit();
  370. }
  371. $self = $this;
  372. // make sure page is not frozen!
  373. unset($this->grav['page']);
  374. $this->admin->pagesCount();
  375. // Replace page service with admin.
  376. $this->grav['page'] = function () use ($self) {
  377. $page = new Page();
  378. // Plugins may not have the correct Cache-Control header set, force no-store for the proxies.
  379. $page->expires(0);
  380. if ($this->grav['user']->authorize('admin.login')) {
  381. $event = new Event(['page' => $page]);
  382. $event = $this->grav->fireEvent('onAdminPage', $event);
  383. $page = $event['page'];
  384. if ($page->slug()) {
  385. return $page;
  386. }
  387. }
  388. // Look in the pages provided by the Admin plugin itself
  389. if (file_exists(__DIR__ . "/pages/admin/{$self->template}.md")) {
  390. $page->init(new \SplFileInfo(__DIR__ . "/pages/admin/{$self->template}.md"));
  391. $page->slug(basename($self->template));
  392. return $page;
  393. }
  394. // If not provided by Admin, lookup pages added by other plugins
  395. $plugins = $this->grav['plugins'];
  396. $locator = $this->grav['locator'];
  397. foreach ($plugins as $plugin) {
  398. if ($this->config->get("plugins.{$plugin->name}.enabled") !== true) {
  399. continue;
  400. }
  401. $path = $locator->findResource("plugins://{$plugin->name}/admin/pages/{$self->template}.md");
  402. if ($path) {
  403. $page->init(new \SplFileInfo($path));
  404. $page->slug(basename($self->template));
  405. return $page;
  406. }
  407. }
  408. return null;
  409. };
  410. if (empty($this->grav['page'])) {
  411. if ($this->grav['user']->authenticated) {
  412. $event = new Event(['page' => null]);
  413. $event->page = null;
  414. $event = $this->grav->fireEvent('onPageNotFound', $event);
  415. /** @var PageInterface $page */
  416. $page = $event->page;
  417. if (!$page || !$page->routable()) {
  418. $error_file = $this->grav['locator']->findResource('plugins://admin/pages/admin/error.md');
  419. $page = new Page();
  420. $page->init(new \SplFileInfo($error_file));
  421. $page->slug(basename($this->route));
  422. $page->routable(true);
  423. }
  424. unset($this->grav['page']);
  425. $this->grav['page'] = $page;
  426. } else {
  427. // Not Found and not logged in: Display login page.
  428. $login_file = $this->grav['locator']->findResource('plugins://admin/pages/admin/login.md');
  429. $page = new Page();
  430. $page->init(new \SplFileInfo($login_file));
  431. $page->slug(basename($this->route));
  432. unset($this->grav['page']);
  433. $this->grav['page'] = $page;
  434. }
  435. }
  436. // Explicitly set a timestamp on assets
  437. $this->grav['assets']->setTimestamp(substr(md5(GRAV_VERSION . $this->grav['config']->checksum()), 0, 10));
  438. }
  439. /**
  440. * Handles initializing the assets
  441. */
  442. public function onAssetsInitialized()
  443. {
  444. // Disable Asset pipelining
  445. $assets = $this->grav['assets'];
  446. $assets->setJsPipeline(false);
  447. $assets->setCssPipeline(false);
  448. }
  449. /**
  450. * Add twig paths to plugin templates.
  451. */
  452. public function onTwigTemplatePaths()
  453. {
  454. $twig_paths = [];
  455. $this->grav->fireEvent('onAdminTwigTemplatePaths', new Event(['paths' => &$twig_paths]));
  456. $twig_paths[] = __DIR__ . '/themes/' . $this->theme . '/templates';
  457. $this->grav['twig']->twig_paths = $twig_paths;
  458. }
  459. /**
  460. * Set all twig variables for generating output.
  461. */
  462. public function onTwigSiteVariables()
  463. {
  464. $twig = $this->grav['twig'];
  465. $page = $this->grav['page'];
  466. $twig->twig_vars['location'] = $this->template;
  467. $twig->twig_vars['base_url_relative_frontend'] = $twig->twig_vars['base_url_relative'] ?: '/';
  468. $twig->twig_vars['admin_route'] = trim($this->admin_route, '/');
  469. $twig->twig_vars['template_route'] = $this->template;
  470. $twig->twig_vars['current_route'] = '/' . $twig->twig_vars['admin_route'] . '/' . $this->template . '/' . $this->route;
  471. $twig->twig_vars['base_url_relative'] = $twig->twig_vars['base_url_simple'] . '/' . $twig->twig_vars['admin_route'];
  472. $twig->twig_vars['current_url'] = rtrim($twig->twig_vars['base_url_relative'] . '/' . $this->template . '/' . $this->route, '/');
  473. $theme_url = '/' . ltrim($this->grav['locator']->findResource('plugin://admin/themes/' . $this->theme,
  474. false), '/');
  475. $twig->twig_vars['theme_url'] = $theme_url;
  476. $twig->twig_vars['preset_url'] = $twig->twig_vars['preset_url'] ?? $theme_url;
  477. $twig->twig_vars['base_url'] = $twig->twig_vars['base_url_relative'];
  478. $twig->twig_vars['base_path'] = GRAV_ROOT;
  479. $twig->twig_vars['admin'] = $this->admin;
  480. $twig->twig_vars['admin_version'] = $this->version;
  481. $twig->twig_vars['logviewer'] = new LogViewer();
  482. $twig->twig_vars['form_max_filesize'] = Utils::getUploadLimit() / 1024 / 1024;
  483. $fa_icons_file = CompiledYamlFile::instance($this->grav['locator']->findResource('plugin://admin/themes/grav/templates/forms/fields/iconpicker/icons' . YAML_EXT));
  484. $fa_icons = $fa_icons_file->content();
  485. $fa_icons = array_map(function ($icon) {
  486. //only pick used values
  487. return ['id' => $icon['id'], 'unicode' => $icon['unicode']];
  488. }, $fa_icons['icons']);
  489. $twig->twig_vars['fa_icons'] = $fa_icons;
  490. // add form if it exists in the page
  491. $header = $page->header();
  492. $forms = [];
  493. if (isset($header->forms)) foreach ($header->forms as $key => $form) {
  494. $forms[$key] = new Form($page, null, $form);
  495. }
  496. $twig->twig_vars['forms'] = $forms;
  497. // preserve form validation
  498. if (!isset($twig->twig_vars['form'])) {
  499. if (isset($header->form)) {
  500. $twig->twig_vars['form'] = new Form($page);
  501. } elseif (isset($header->forms)) {
  502. $twig->twig_vars['form'] = new Form($page, null, reset($header->forms));
  503. }
  504. }
  505. // Gather Plugin-hooked nav items
  506. $this->grav->fireEvent('onAdminMenu');
  507. switch ($this->template) {
  508. case 'dashboard':
  509. $twig->twig_vars['popularity'] = $this->popularity;
  510. // Gather Plugin-hooked dashboard items
  511. $this->grav->fireEvent('onAdminDashboard');
  512. break;
  513. }
  514. $flashData = $this->grav['session']->getFlashCookieObject(Admin::TMP_COOKIE_NAME);
  515. if (isset($flashData->message)) {
  516. $this->grav['messages']->add($flashData->message, $flashData->status);
  517. }
  518. }
  519. // Add images to twig template paths to allow inclusion of SVG files
  520. public function onTwigLoader()
  521. {
  522. $theme_paths = Grav::instance()['locator']->findResources('plugins://admin/themes/' . $this->theme . '/images');
  523. foreach($theme_paths as $images_path) {
  524. $this->grav['twig']->addPath($images_path, 'admin-images');
  525. }
  526. }
  527. /**
  528. * Add the Admin Twig Extensions
  529. */
  530. public function onTwigExtensions()
  531. {
  532. require_once __DIR__ . '/classes/Twig/AdminTwigExtension.php';
  533. $this->grav['twig']->twig->addExtension(new AdminTwigExtension);
  534. }
  535. public function onAdminAfterSave(Event $event)
  536. {
  537. // Special case to redirect after changing the admin route to avoid 'breaking'
  538. $obj = $event['object'];
  539. if (null !== $obj && method_exists($obj, 'blueprints')) {
  540. $blueprint = $obj->blueprints()->getFilename();
  541. if ($blueprint === 'admin/blueprints' && isset($obj->route) && $this->admin_route !== $obj->route) {
  542. $redirect = preg_replace('/^' . str_replace('/','\/',$this->admin_route) . '/',$obj->route,$this->uri->path());
  543. $this->grav->redirect($redirect);
  544. }
  545. }
  546. }
  547. /**
  548. * Convert some types where we want to process out of the standard config path
  549. *
  550. * @param Event $e
  551. */
  552. public function onAdminData(Event $e)
  553. {
  554. $type = $e['type'] ?? null;
  555. switch ($type) {
  556. case 'tools/scheduler':
  557. $e['type'] = 'config/scheduler';
  558. break;
  559. case 'tools':
  560. case 'tools/backups':
  561. $e['type'] = 'config/backups';
  562. break;
  563. }
  564. }
  565. public function onOutputGenerated()
  566. {
  567. // Clear flash objects for previously uploaded files whenever the user switches page or reloads
  568. // ignoring any JSON / extension call
  569. if ($this->admin->task !== 'save' && empty($this->uri->extension())) {
  570. // Discard any previously uploaded files session and remove all uploaded files.
  571. if ($flash = $this->session->getFlashObject('files-upload')) {
  572. $flash = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($flash));
  573. foreach ($flash as $key => $value) {
  574. if ($key !== 'tmp_name') {
  575. continue;
  576. }
  577. @unlink($value);
  578. }
  579. }
  580. }
  581. }
  582. /**
  583. * Initial stab at registering permissions (WIP)
  584. *
  585. * @param Event $e
  586. */
  587. public function onAdminRegisterPermissions(Event $e)
  588. {
  589. $admin = $e['admin'];
  590. $permissions = [
  591. 'admin.super' => 'boolean',
  592. 'admin.login' => 'boolean',
  593. 'admin.cache' => 'boolean',
  594. 'admin.configuration' => 'boolean',
  595. 'admin.configuration_system' => 'boolean',
  596. 'admin.configuration_site' => 'boolean',
  597. 'admin.configuration_media' => 'boolean',
  598. 'admin.configuration_info' => 'boolean',
  599. 'admin.settings' => 'boolean',
  600. 'admin.pages' => 'boolean',
  601. 'admin.maintenance' => 'boolean',
  602. 'admin.statistics' => 'boolean',
  603. 'admin.plugins' => 'boolean',
  604. 'admin.themes' => 'boolean',
  605. 'admin.tools' => 'boolean',
  606. 'admin.users' => 'boolean',
  607. ];
  608. $admin->addPermissions($permissions);
  609. }
  610. /**
  611. * Check if the current route is under the admin path
  612. *
  613. * @return bool
  614. */
  615. public function isAdminPath()
  616. {
  617. $route = $this->uri->route();
  618. return $route === $this->base || 0 === strpos($route, $this->base . '/');
  619. }
  620. /**
  621. * Helper function to replace Pages::Types()
  622. * and to provide an event to manipulate the data
  623. *
  624. * Dispatches 'onAdminPageTypes' event
  625. * with 'types' data member which is a
  626. * reference to the data
  627. */
  628. public static function pagesTypes()
  629. {
  630. $types = Pages::types();
  631. // First filter by configuration
  632. $hideTypes = Grav::instance()['config']->get('plugins.admin.hide_page_types', []);
  633. foreach ((array) $hideTypes as $type) {
  634. unset($types[$type]);
  635. }
  636. // Allow manipulating of the data by event
  637. $e = new Event(['types' => &$types]);
  638. Grav::instance()->fireEvent('onAdminPageTypes', $e);
  639. return $types;
  640. }
  641. /**
  642. * Helper function to replace Pages::modularTypes()
  643. * and to provide an event to manipulate the data
  644. *
  645. * Dispatches 'onAdminModularPageTypes' event
  646. * with 'types' data member which is a
  647. * reference to the data
  648. */
  649. public static function pagesModularTypes()
  650. {
  651. $types = Pages::modularTypes();
  652. // First filter by configuration
  653. $hideTypes = (array) Grav::instance()['config']->get('plugins.admin.hide_modular_page_types', []);
  654. foreach ($hideTypes as $type) {
  655. unset($types[$type]);
  656. }
  657. // Allow manipulating of the data by event
  658. $e = new Event(['types' => &$types]);
  659. Grav::instance()->fireEvent('onAdminModularPageTypes', $e);
  660. return $types;
  661. }
  662. /**
  663. * Validate a value. Currently validates
  664. *
  665. * - 'user' for username format and username availability.
  666. * - 'password1' for password format
  667. * - 'password2' for equality to password1
  668. *
  669. * @param string $type The field type
  670. * @param string $value The field value
  671. * @param string $extra Any extra value required
  672. *
  673. * @return bool
  674. */
  675. protected function validate($type, $value, $extra = '')
  676. {
  677. /** @var Login $login */
  678. $login = $this->grav['login'];
  679. return $login->validateField($type, $value, $extra);
  680. }
  681. protected function initializeController($task, $post)
  682. {
  683. $controller = new AdminController();
  684. $controller->initialize($this->grav, $this->template, $task, $this->route, $post);
  685. $controller->execute();
  686. $controller->redirect();
  687. }
  688. /**
  689. * Initialize the admin.
  690. *
  691. * @throws \RuntimeException
  692. */
  693. protected function initializeAdmin()
  694. {
  695. $this->enable([
  696. 'onTwigExtensions' => ['onTwigExtensions', 1000],
  697. 'onPagesInitialized' => ['onPagesInitialized', 1000],
  698. 'onTwigLoader' => ['onTwigLoader', 1000],
  699. 'onTwigTemplatePaths' => ['onTwigTemplatePaths', 1000],
  700. 'onTwigSiteVariables' => ['onTwigSiteVariables', 1000],
  701. 'onAssetsInitialized' => ['onAssetsInitialized', 1000],
  702. 'onAdminRegisterPermissions' => ['onAdminRegisterPermissions', 0],
  703. 'onOutputGenerated' => ['onOutputGenerated', 0],
  704. 'onAdminAfterSave' => ['onAdminAfterSave', 0],
  705. 'onAdminData' => ['onAdminData', 0],
  706. ]);
  707. // Autoload classes
  708. require_once __DIR__ . '/vendor/autoload.php';
  709. // Check for required plugins
  710. if (!$this->grav['config']->get('plugins.login.enabled') || !$this->grav['config']->get('plugins.form.enabled') || !$this->grav['config']->get('plugins.email.enabled')) {
  711. throw new \RuntimeException('One of the required plugins is missing or not enabled');
  712. }
  713. // Initialize Admin Language if needed
  714. /** @var Language $language */
  715. $language = $this->grav['language'];
  716. if ($language->enabled() && empty($this->grav['session']->admin_lang)) {
  717. $this->grav['session']->admin_lang = $language->getLanguage();
  718. }
  719. // Decide admin template and route.
  720. $path = trim(substr($this->uri->route(), strlen($this->base)), '/');
  721. if (empty($this->template)) {
  722. $this->template = 'dashboard';
  723. }
  724. // Can't access path directly...
  725. if ($path && $path !== 'register') {
  726. $array = explode('/', $path, 2);
  727. $this->template = array_shift($array);
  728. $this->route = array_shift($array);
  729. }
  730. // Initialize admin class (also registers it to Grav services).
  731. $this->admin = new Admin($this->grav, $this->admin_route, $this->template, $this->route);
  732. // Double check we have system.yaml, site.yaml etc
  733. $config_path = $this->grav['locator']->findResource('user://config');
  734. foreach ($this->admin::configurations() as $config_file) {
  735. $config_file = "{$config_path}/{$config_file}.yaml";
  736. if (!file_exists($config_file)) {
  737. touch($config_file);
  738. }
  739. }
  740. // Get theme for admin
  741. $this->theme = $this->config->get('plugins.admin.theme', 'grav');
  742. $assets = $this->grav['assets'];
  743. $translations = 'this.GravAdmin = this.GravAdmin || {}; if (!this.GravAdmin.translations) this.GravAdmin.translations = {}; ' . PHP_EOL . 'this.GravAdmin.translations.PLUGIN_ADMIN = {';
  744. // Enable language translations
  745. $translations_actual_state = $this->config->get('system.languages.translations');
  746. $this->config->set('system.languages.translations', true);
  747. $strings = [
  748. 'EVERYTHING_UP_TO_DATE',
  749. 'UPDATES_ARE_AVAILABLE',
  750. 'IS_AVAILABLE_FOR_UPDATE',
  751. 'AND',
  752. 'IS_NOW_AVAILABLE',
  753. 'CURRENT',
  754. 'UPDATE_GRAV_NOW',
  755. 'TASK_COMPLETED',
  756. 'UPDATE',
  757. 'UPDATING_PLEASE_WAIT',
  758. 'GRAV_SYMBOLICALLY_LINKED',
  759. 'OF_YOUR',
  760. 'OF_THIS',
  761. 'HAVE_AN_UPDATE_AVAILABLE',
  762. 'UPDATE_AVAILABLE',
  763. 'UPDATES_AVAILABLE',
  764. 'FULLY_UPDATED',
  765. 'DAYS',
  766. 'PAGE_MODES',
  767. 'PAGE_TYPES',
  768. 'ACCESS_LEVELS',
  769. 'NOTHING_TO_SAVE',
  770. 'FILE_UNSUPPORTED',
  771. 'FILE_ERROR_ADD',
  772. 'FILE_ERROR_UPLOAD',
  773. 'DROP_FILES_HERE_TO_UPLOAD',
  774. 'DELETE',
  775. 'UNSET',
  776. 'INSERT',
  777. 'METADATA',
  778. 'VIEW',
  779. 'UNDO',
  780. 'REDO',
  781. 'HEADERS',
  782. 'BOLD',
  783. 'ITALIC',
  784. 'STRIKETHROUGH',
  785. 'SUMMARY_DELIMITER',
  786. 'LINK',
  787. 'IMAGE',
  788. 'BLOCKQUOTE',
  789. 'UNORDERED_LIST',
  790. 'ORDERED_LIST',
  791. 'EDITOR',
  792. 'PREVIEW',
  793. 'FULLSCREEN',
  794. 'MODULAR',
  795. 'NON_MODULAR',
  796. 'VISIBLE',
  797. 'NON_VISIBLE',
  798. 'ROUTABLE',
  799. 'NON_ROUTABLE',
  800. 'PUBLISHED',
  801. 'NON_PUBLISHED',
  802. 'PLUGINS',
  803. 'THEMES',
  804. 'ALL',
  805. 'FROM',
  806. 'TO',
  807. 'DROPZONE_CANCEL_UPLOAD',
  808. 'DROPZONE_CANCEL_UPLOAD_CONFIRMATION',
  809. 'DROPZONE_DEFAULT_MESSAGE',
  810. 'DROPZONE_FALLBACK_MESSAGE',
  811. 'DROPZONE_FALLBACK_TEXT',
  812. 'DROPZONE_FILE_TOO_BIG',
  813. 'DROPZONE_INVALID_FILE_TYPE',
  814. 'DROPZONE_MAX_FILES_EXCEEDED',
  815. 'DROPZONE_REMOVE_FILE',
  816. 'DROPZONE_RESPONSE_ERROR'
  817. ];
  818. foreach ($strings as $string) {
  819. $separator = (end($strings) === $string) ? '' : ',';
  820. $translations .= '"' . $string . '": "' . htmlspecialchars($this->admin::translate('PLUGIN_ADMIN.' . $string)) . '"' . $separator;
  821. }
  822. $translations .= '};';
  823. $translations .= 'this.GravAdmin.translations.PLUGIN_FORM = {';
  824. $strings = ['RESOLUTION_MIN', 'RESOLUTION_MAX'];
  825. foreach ($strings as $string) {
  826. $separator = (end($strings) === $string) ? '' : ',';
  827. $translations .= '"' . $string . '": "' . $this->admin::translate('PLUGIN_FORM.' . $string) . '"' . $separator;
  828. }
  829. $translations .= '};';
  830. $translations .= 'this.GravAdmin.translations.GRAV_CORE = {';
  831. $strings = [
  832. 'NICETIME.SECOND',
  833. 'NICETIME.MINUTE',
  834. 'NICETIME.HOUR',
  835. 'NICETIME.DAY',
  836. 'NICETIME.WEEK',
  837. 'NICETIME.MONTH',
  838. 'NICETIME.YEAR',
  839. 'CRON.EVERY',
  840. 'CRON.EVERY_HOUR',
  841. 'CRON.EVERY_MINUTE',
  842. 'CRON.EVERY_DAY_OF_WEEK',
  843. 'CRON.EVERY_DAY_OF_MONTH',
  844. 'CRON.EVERY_MONTH',
  845. 'CRON.TEXT_PERIOD',
  846. 'CRON.TEXT_MINS',
  847. 'CRON.TEXT_TIME',
  848. 'CRON.TEXT_DOW',
  849. 'CRON.TEXT_MONTH',
  850. 'CRON.TEXT_DOM',
  851. 'CRON.ERROR1',
  852. 'CRON.ERROR2',
  853. 'CRON.ERROR3',
  854. 'CRON.ERROR4',
  855. 'MONTHS_OF_THE_YEAR',
  856. 'DAYS_OF_THE_WEEK'
  857. ];
  858. foreach ($strings as $string) {
  859. $separator = (end($strings) === $string) ? '' : ',';
  860. $translations .= '"' . $string . '": ' . json_encode($this->admin::translate('GRAV.'.$string)) . $separator;
  861. }
  862. $translations .= '};';
  863. // set the actual translations state back
  864. $this->config->set('system.languages.translations', $translations_actual_state);
  865. $assets->addInlineJs($translations);
  866. }
  867. }