admin.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  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'];
  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. $page->expires(0);
  379. if ($this->grav['user']->authorize('admin.login')) {
  380. $event = new Event(['page' => $page]);
  381. $event = $this->grav->fireEvent('onAdminPage', $event);
  382. $page = $event['page'];
  383. if ($page->slug()) {
  384. return $page;
  385. }
  386. }
  387. // Look in the pages provided by the Admin plugin itself
  388. if (file_exists(__DIR__ . "/pages/admin/{$self->template}.md")) {
  389. $page->init(new \SplFileInfo(__DIR__ . "/pages/admin/{$self->template}.md"));
  390. $page->slug(basename($self->template));
  391. return $page;
  392. }
  393. // If not provided by Admin, lookup pages added by other plugins
  394. $plugins = $this->grav['plugins'];
  395. $locator = $this->grav['locator'];
  396. foreach ($plugins as $plugin) {
  397. if ($this->config->get("plugins.{$plugin->name}.enabled") !== true) {
  398. continue;
  399. }
  400. $path = $locator->findResource("plugins://{$plugin->name}/admin/pages/{$self->template}.md");
  401. if ($path) {
  402. $page->init(new \SplFileInfo($path));
  403. $page->slug(basename($self->template));
  404. return $page;
  405. }
  406. }
  407. return null;
  408. };
  409. if (empty($this->grav['page'])) {
  410. if ($this->grav['user']->authenticated) {
  411. $event = new Event(['page' => null]);
  412. $event->page = null;
  413. $event = $this->grav->fireEvent('onPageNotFound', $event);
  414. /** @var PageInterface $page */
  415. $page = $event->page;
  416. if (!$page || !$page->routable()) {
  417. $error_file = $this->grav['locator']->findResource('plugins://admin/pages/admin/error.md');
  418. $page = new Page();
  419. $page->init(new \SplFileInfo($error_file));
  420. $page->slug(basename($this->route));
  421. $page->routable(true);
  422. }
  423. unset($this->grav['page']);
  424. $this->grav['page'] = $page;
  425. } else {
  426. // Not Found and not logged in: Display login page.
  427. $login_file = $this->grav['locator']->findResource('plugins://admin/pages/admin/login.md');
  428. $page = new Page();
  429. $page->init(new \SplFileInfo($login_file));
  430. $page->slug(basename($this->route));
  431. unset($this->grav['page']);
  432. $this->grav['page'] = $page;
  433. }
  434. }
  435. // Explicitly set a timestamp on assets
  436. $this->grav['assets']->setTimestamp(substr(md5(GRAV_VERSION . $this->grav['config']->checksum()), 0, 10));
  437. }
  438. /**
  439. * Handles initializing the assets
  440. */
  441. public function onAssetsInitialized()
  442. {
  443. // Disable Asset pipelining
  444. $assets = $this->grav['assets'];
  445. $assets->setJsPipeline(false);
  446. $assets->setCssPipeline(false);
  447. }
  448. /**
  449. * Add twig paths to plugin templates.
  450. */
  451. public function onTwigTemplatePaths()
  452. {
  453. $twig_paths = [];
  454. $this->grav->fireEvent('onAdminTwigTemplatePaths', new Event(['paths' => &$twig_paths]));
  455. $twig_paths[] = __DIR__ . '/themes/' . $this->theme . '/templates';
  456. $this->grav['twig']->twig_paths = $twig_paths;
  457. }
  458. /**
  459. * Set all twig variables for generating output.
  460. */
  461. public function onTwigSiteVariables()
  462. {
  463. $twig = $this->grav['twig'];
  464. $page = $this->grav['page'];
  465. $twig->twig_vars['location'] = $this->template;
  466. $twig->twig_vars['base_url_relative_frontend'] = $twig->twig_vars['base_url_relative'] ?: '/';
  467. $twig->twig_vars['admin_route'] = trim($this->admin_route, '/');
  468. $twig->twig_vars['template_route'] = $this->template;
  469. $twig->twig_vars['current_route'] = '/' . $twig->twig_vars['admin_route'] . '/' . $this->template . '/' . $this->route;
  470. $twig->twig_vars['base_url_relative'] = $twig->twig_vars['base_url_simple'] . '/' . $twig->twig_vars['admin_route'];
  471. $twig->twig_vars['current_url'] = rtrim($twig->twig_vars['base_url_relative'] . '/' . $this->template . '/' . $this->route, '/');
  472. $theme_url = '/' . ltrim($this->grav['locator']->findResource('plugin://admin/themes/' . $this->theme,
  473. false), '/');
  474. $twig->twig_vars['theme_url'] = $theme_url;
  475. $twig->twig_vars['preset_url'] = $twig->twig_vars['preset_url'] ?? $theme_url;
  476. $twig->twig_vars['base_url'] = $twig->twig_vars['base_url_relative'];
  477. $twig->twig_vars['base_path'] = GRAV_ROOT;
  478. $twig->twig_vars['admin'] = $this->admin;
  479. $twig->twig_vars['admin_version'] = $this->version;
  480. $twig->twig_vars['logviewer'] = new LogViewer();
  481. $twig->twig_vars['form_max_filesize'] = Utils::getUploadLimit() / 1024 / 1024;
  482. $fa_icons_file = CompiledYamlFile::instance($this->grav['locator']->findResource('plugin://admin/themes/grav/templates/forms/fields/iconpicker/icons' . YAML_EXT));
  483. $fa_icons = $fa_icons_file->content();
  484. $fa_icons = array_map(function ($icon) {
  485. //only pick used values
  486. return ['id' => $icon['id'], 'unicode' => $icon['unicode']];
  487. }, $fa_icons['icons']);
  488. $twig->twig_vars['fa_icons'] = $fa_icons;
  489. // add form if it exists in the page
  490. $header = $page->header();
  491. $forms = [];
  492. if (isset($header->forms)) foreach ($header->forms as $key => $form) {
  493. $forms[$key] = new Form($page, null, $form);
  494. }
  495. $twig->twig_vars['forms'] = $forms;
  496. // preserve form validation
  497. if (!isset($twig->twig_vars['form'])) {
  498. if (isset($header->form)) {
  499. $twig->twig_vars['form'] = new Form($page);
  500. } elseif (isset($header->forms)) {
  501. $twig->twig_vars['form'] = new Form($page, null, reset($header->forms));
  502. }
  503. }
  504. // Gather Plugin-hooked nav items
  505. $this->grav->fireEvent('onAdminMenu');
  506. switch ($this->template) {
  507. case 'dashboard':
  508. $twig->twig_vars['popularity'] = $this->popularity;
  509. // Gather Plugin-hooked dashboard items
  510. $this->grav->fireEvent('onAdminDashboard');
  511. break;
  512. }
  513. $flashData = $this->grav['session']->getFlashCookieObject(Admin::TMP_COOKIE_NAME);
  514. if (isset($flashData->message)) {
  515. $this->grav['messages']->add($flashData->message, $flashData->status);
  516. }
  517. }
  518. // Add images to twig template paths to allow inclusion of SVG files
  519. public function onTwigLoader()
  520. {
  521. $theme_paths = Grav::instance()['locator']->findResources('plugins://admin/themes/' . $this->theme . '/images');
  522. foreach($theme_paths as $images_path) {
  523. $this->grav['twig']->addPath($images_path, 'admin-images');
  524. }
  525. }
  526. /**
  527. * Add the Admin Twig Extensions
  528. */
  529. public function onTwigExtensions()
  530. {
  531. require_once __DIR__ . '/classes/Twig/AdminTwigExtension.php';
  532. $this->grav['twig']->twig->addExtension(new AdminTwigExtension);
  533. }
  534. public function onAdminAfterSave(Event $event)
  535. {
  536. // Special case to redirect after changing the admin route to avoid 'breaking'
  537. $obj = $event['object'];
  538. if (null !== $obj && method_exists($obj, 'blueprints')) {
  539. $blueprint = $obj->blueprints()->getFilename();
  540. if ($blueprint === 'admin/blueprints' && isset($obj->route) && $this->admin_route !== $obj->route) {
  541. $redirect = preg_replace('/^' . str_replace('/','\/',$this->admin_route) . '/',$obj->route,$this->uri->path());
  542. $this->grav->redirect($redirect);
  543. }
  544. }
  545. }
  546. /**
  547. * Convert some types where we want to process out of the standard config path
  548. *
  549. * @param Event $e
  550. */
  551. public function onAdminData(Event $e)
  552. {
  553. $type = $e['type'] ?? null;
  554. switch ($type) {
  555. case 'tools/scheduler':
  556. $e['type'] = 'config/scheduler';
  557. break;
  558. case 'tools':
  559. case 'tools/backups':
  560. $e['type'] = 'config/backups';
  561. break;
  562. }
  563. }
  564. public function onOutputGenerated()
  565. {
  566. // Clear flash objects for previously uploaded files whenever the user switches page or reloads
  567. // ignoring any JSON / extension call
  568. if ($this->admin->task !== 'save' && empty($this->uri->extension())) {
  569. // Discard any previously uploaded files session and remove all uploaded files.
  570. if ($flash = $this->session->getFlashObject('files-upload')) {
  571. $flash = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($flash));
  572. foreach ($flash as $key => $value) {
  573. if ($key !== 'tmp_name') {
  574. continue;
  575. }
  576. @unlink($value);
  577. }
  578. }
  579. }
  580. }
  581. /**
  582. * Initial stab at registering permissions (WIP)
  583. *
  584. * @param Event $e
  585. */
  586. public function onAdminRegisterPermissions(Event $e)
  587. {
  588. $admin = $e['admin'];
  589. $permissions = [
  590. 'admin.super' => 'boolean',
  591. 'admin.login' => 'boolean',
  592. 'admin.cache' => 'boolean',
  593. 'admin.configuration' => 'boolean',
  594. 'admin.configuration_system' => 'boolean',
  595. 'admin.configuration_site' => 'boolean',
  596. 'admin.configuration_media' => 'boolean',
  597. 'admin.configuration_info' => 'boolean',
  598. 'admin.settings' => 'boolean',
  599. 'admin.pages' => 'boolean',
  600. 'admin.maintenance' => 'boolean',
  601. 'admin.statistics' => 'boolean',
  602. 'admin.plugins' => 'boolean',
  603. 'admin.themes' => 'boolean',
  604. 'admin.tools' => 'boolean',
  605. 'admin.users' => 'boolean',
  606. ];
  607. $admin->addPermissions($permissions);
  608. }
  609. /**
  610. * Check if the current route is under the admin path
  611. *
  612. * @return bool
  613. */
  614. public function isAdminPath()
  615. {
  616. $route = $this->uri->route();
  617. return $route === $this->base || 0 === strpos($route, $this->base . '/');
  618. }
  619. /**
  620. * Helper function to replace Pages::Types()
  621. * and to provide an event to manipulate the data
  622. *
  623. * Dispatches 'onAdminPageTypes' event
  624. * with 'types' data member which is a
  625. * reference to the data
  626. */
  627. public static function pagesTypes()
  628. {
  629. $types = Pages::types();
  630. // First filter by configuration
  631. $hideTypes = Grav::instance()['config']->get('plugins.admin.hide_page_types', []);
  632. foreach ((array) $hideTypes as $type) {
  633. unset($types[$type]);
  634. }
  635. // Allow manipulating of the data by event
  636. $e = new Event(['types' => &$types]);
  637. Grav::instance()->fireEvent('onAdminPageTypes', $e);
  638. return $types;
  639. }
  640. /**
  641. * Helper function to replace Pages::modularTypes()
  642. * and to provide an event to manipulate the data
  643. *
  644. * Dispatches 'onAdminModularPageTypes' event
  645. * with 'types' data member which is a
  646. * reference to the data
  647. */
  648. public static function pagesModularTypes()
  649. {
  650. $types = Pages::modularTypes();
  651. // First filter by configuration
  652. $hideTypes = (array) Grav::instance()['config']->get('plugins.admin.hide_modular_page_types', []);
  653. foreach ($hideTypes as $type) {
  654. unset($types[$type]);
  655. }
  656. // Allow manipulating of the data by event
  657. $e = new Event(['types' => &$types]);
  658. Grav::instance()->fireEvent('onAdminModularPageTypes', $e);
  659. return $types;
  660. }
  661. /**
  662. * Validate a value. Currently validates
  663. *
  664. * - 'user' for username format and username availability.
  665. * - 'password1' for password format
  666. * - 'password2' for equality to password1
  667. *
  668. * @param string $type The field type
  669. * @param string $value The field value
  670. * @param string $extra Any extra value required
  671. *
  672. * @return bool
  673. */
  674. protected function validate($type, $value, $extra = '')
  675. {
  676. /** @var Login $login */
  677. $login = $this->grav['login'];
  678. return $login->validateField($type, $value, $extra);
  679. }
  680. protected function initializeController($task, $post)
  681. {
  682. $controller = new AdminController();
  683. $controller->initialize($this->grav, $this->template, $task, $this->route, $post);
  684. $controller->execute();
  685. $controller->redirect();
  686. }
  687. /**
  688. * Initialize the admin.
  689. *
  690. * @throws \RuntimeException
  691. */
  692. protected function initializeAdmin()
  693. {
  694. $this->enable([
  695. 'onTwigExtensions' => ['onTwigExtensions', 1000],
  696. 'onPagesInitialized' => ['onPagesInitialized', 1000],
  697. 'onTwigLoader' => ['onTwigLoader', 1000],
  698. 'onTwigTemplatePaths' => ['onTwigTemplatePaths', 1000],
  699. 'onTwigSiteVariables' => ['onTwigSiteVariables', 1000],
  700. 'onAssetsInitialized' => ['onAssetsInitialized', 1000],
  701. 'onAdminRegisterPermissions' => ['onAdminRegisterPermissions', 0],
  702. 'onOutputGenerated' => ['onOutputGenerated', 0],
  703. 'onAdminAfterSave' => ['onAdminAfterSave', 0],
  704. 'onAdminData' => ['onAdminData', 0],
  705. ]);
  706. // Autoload classes
  707. require_once __DIR__ . '/vendor/autoload.php';
  708. // Check for required plugins
  709. if (!$this->grav['config']->get('plugins.login.enabled') || !$this->grav['config']->get('plugins.form.enabled') || !$this->grav['config']->get('plugins.email.enabled')) {
  710. throw new \RuntimeException('One of the required plugins is missing or not enabled');
  711. }
  712. // Initialize Admin Language if needed
  713. /** @var Language $language */
  714. $language = $this->grav['language'];
  715. if ($language->enabled() && empty($this->grav['session']->admin_lang)) {
  716. $this->grav['session']->admin_lang = $language->getLanguage();
  717. }
  718. // Decide admin template and route.
  719. $path = trim(substr($this->uri->route(), strlen($this->base)), '/');
  720. if (empty($this->template)) {
  721. $this->template = 'dashboard';
  722. }
  723. // Can't access path directly...
  724. if ($path && $path !== 'register') {
  725. $array = explode('/', $path, 2);
  726. $this->template = array_shift($array);
  727. $this->route = array_shift($array);
  728. }
  729. // Initialize admin class (also registers it to Grav services).
  730. $this->admin = new Admin($this->grav, $this->admin_route, $this->template, $this->route);
  731. // Double check we have system.yaml, site.yaml etc
  732. $config_path = $this->grav['locator']->findResource('user://config');
  733. foreach ($this->admin::configurations() as $config_file) {
  734. $config_file = "{$config_path}/{$config_file}.yaml";
  735. if (!file_exists($config_file)) {
  736. touch($config_file);
  737. }
  738. }
  739. // Get theme for admin
  740. $this->theme = $this->config->get('plugins.admin.theme', 'grav');
  741. $assets = $this->grav['assets'];
  742. $translations = 'this.GravAdmin = this.GravAdmin || {}; if (!this.GravAdmin.translations) this.GravAdmin.translations = {}; ' . PHP_EOL . 'this.GravAdmin.translations.PLUGIN_ADMIN = {';
  743. // Enable language translations
  744. $translations_actual_state = $this->config->get('system.languages.translations');
  745. $this->config->set('system.languages.translations', true);
  746. $strings = [
  747. 'EVERYTHING_UP_TO_DATE',
  748. 'UPDATES_ARE_AVAILABLE',
  749. 'IS_AVAILABLE_FOR_UPDATE',
  750. 'AND',
  751. 'IS_NOW_AVAILABLE',
  752. 'CURRENT',
  753. 'UPDATE_GRAV_NOW',
  754. 'TASK_COMPLETED',
  755. 'UPDATE',
  756. 'UPDATING_PLEASE_WAIT',
  757. 'GRAV_SYMBOLICALLY_LINKED',
  758. 'OF_YOUR',
  759. 'OF_THIS',
  760. 'HAVE_AN_UPDATE_AVAILABLE',
  761. 'UPDATE_AVAILABLE',
  762. 'UPDATES_AVAILABLE',
  763. 'FULLY_UPDATED',
  764. 'DAYS',
  765. 'PAGE_MODES',
  766. 'PAGE_TYPES',
  767. 'ACCESS_LEVELS',
  768. 'NOTHING_TO_SAVE',
  769. 'FILE_UNSUPPORTED',
  770. 'FILE_ERROR_ADD',
  771. 'FILE_ERROR_UPLOAD',
  772. 'DROP_FILES_HERE_TO_UPLOAD',
  773. 'DELETE',
  774. 'UNSET',
  775. 'INSERT',
  776. 'METADATA',
  777. 'VIEW',
  778. 'UNDO',
  779. 'REDO',
  780. 'HEADERS',
  781. 'BOLD',
  782. 'ITALIC',
  783. 'STRIKETHROUGH',
  784. 'SUMMARY_DELIMITER',
  785. 'LINK',
  786. 'IMAGE',
  787. 'BLOCKQUOTE',
  788. 'UNORDERED_LIST',
  789. 'ORDERED_LIST',
  790. 'EDITOR',
  791. 'PREVIEW',
  792. 'FULLSCREEN',
  793. 'MODULAR',
  794. 'NON_MODULAR',
  795. 'VISIBLE',
  796. 'NON_VISIBLE',
  797. 'ROUTABLE',
  798. 'NON_ROUTABLE',
  799. 'PUBLISHED',
  800. 'NON_PUBLISHED',
  801. 'PLUGINS',
  802. 'THEMES',
  803. 'ALL',
  804. 'FROM',
  805. 'TO',
  806. 'DROPZONE_CANCEL_UPLOAD',
  807. 'DROPZONE_CANCEL_UPLOAD_CONFIRMATION',
  808. 'DROPZONE_DEFAULT_MESSAGE',
  809. 'DROPZONE_FALLBACK_MESSAGE',
  810. 'DROPZONE_FALLBACK_TEXT',
  811. 'DROPZONE_FILE_TOO_BIG',
  812. 'DROPZONE_INVALID_FILE_TYPE',
  813. 'DROPZONE_MAX_FILES_EXCEEDED',
  814. 'DROPZONE_REMOVE_FILE',
  815. 'DROPZONE_RESPONSE_ERROR'
  816. ];
  817. foreach ($strings as $string) {
  818. $separator = (end($strings) === $string) ? '' : ',';
  819. $translations .= '"' . $string . '": "' . htmlspecialchars($this->admin::translate('PLUGIN_ADMIN.' . $string)) . '"' . $separator;
  820. }
  821. $translations .= '};';
  822. $translations .= 'this.GravAdmin.translations.PLUGIN_FORM = {';
  823. $strings = ['RESOLUTION_MIN', 'RESOLUTION_MAX'];
  824. foreach ($strings as $string) {
  825. $separator = (end($strings) === $string) ? '' : ',';
  826. $translations .= '"' . $string . '": "' . $this->admin::translate('PLUGIN_FORM.' . $string) . '"' . $separator;
  827. }
  828. $translations .= '};';
  829. $translations .= 'this.GravAdmin.translations.GRAV_CORE = {';
  830. $strings = [
  831. 'NICETIME.SECOND',
  832. 'NICETIME.MINUTE',
  833. 'NICETIME.HOUR',
  834. 'NICETIME.DAY',
  835. 'NICETIME.WEEK',
  836. 'NICETIME.MONTH',
  837. 'NICETIME.YEAR',
  838. 'CRON.EVERY',
  839. 'CRON.EVERY_HOUR',
  840. 'CRON.EVERY_MINUTE',
  841. 'CRON.EVERY_DAY_OF_WEEK',
  842. 'CRON.EVERY_DAY_OF_MONTH',
  843. 'CRON.EVERY_MONTH',
  844. 'CRON.TEXT_PERIOD',
  845. 'CRON.TEXT_MINS',
  846. 'CRON.TEXT_TIME',
  847. 'CRON.TEXT_DOW',
  848. 'CRON.TEXT_MONTH',
  849. 'CRON.TEXT_DOM',
  850. 'CRON.ERROR1',
  851. 'CRON.ERROR2',
  852. 'CRON.ERROR3',
  853. 'CRON.ERROR4',
  854. 'MONTHS_OF_THE_YEAR',
  855. 'DAYS_OF_THE_WEEK'
  856. ];
  857. foreach ($strings as $string) {
  858. $separator = (end($strings) === $string) ? '' : ',';
  859. $translations .= '"' . $string . '": ' . json_encode($this->admin::translate('GRAV.'.$string)) . $separator;
  860. }
  861. $translations .= '};';
  862. // set the actual translations state back
  863. $this->config->set('system.languages.translations', $translations_actual_state);
  864. $assets->addInlineJs($translations);
  865. }
  866. }