admin.php 35 KB

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