admin.php 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347
  1. <?php
  2. namespace Grav\Plugin;
  3. use Composer\Autoload\ClassLoader;
  4. use Grav\Common\Cache;
  5. use Grav\Common\Data\Data;
  6. use Grav\Common\Debugger;
  7. use Grav\Common\File\CompiledYamlFile;
  8. use Grav\Common\Grav;
  9. use Grav\Common\Helpers\LogViewer;
  10. use Grav\Common\Inflector;
  11. use Grav\Common\Language\Language;
  12. use Grav\Common\Page\Interfaces\PageInterface;
  13. use Grav\Common\Page\Page;
  14. use Grav\Common\Page\Pages;
  15. use Grav\Common\Plugin;
  16. use Grav\Common\Plugins;
  17. use Grav\Common\Processors\Events\RequestHandlerEvent;
  18. use Grav\Common\Session;
  19. use Grav\Common\Twig\Twig;
  20. use Grav\Common\Uri;
  21. use Grav\Common\User\Interfaces\UserInterface;
  22. use Grav\Common\Utils;
  23. use Grav\Common\Yaml;
  24. use Grav\Events\PermissionsRegisterEvent;
  25. use Grav\Framework\Acl\PermissionsReader;
  26. use Grav\Framework\Psr7\Response;
  27. use Grav\Framework\Session\Exceptions\SessionException;
  28. use Grav\Plugin\Admin\Admin;
  29. use Grav\Plugin\Admin\AdminFormFactory;
  30. use Grav\Plugin\Admin\Popularity;
  31. use Grav\Plugin\Admin\Router;
  32. use Grav\Plugin\Admin\Themes;
  33. use Grav\Plugin\Admin\AdminController;
  34. use Grav\Plugin\Admin\Twig\AdminTwigExtension;
  35. use Grav\Plugin\Admin\WhiteLabel;
  36. use Grav\Plugin\Form\Form;
  37. use Grav\Plugin\Form\Forms;
  38. use Grav\Plugin\Login\Login;
  39. use Pimple\Container;
  40. use Psr\Http\Message\ResponseInterface;
  41. use RocketTheme\Toolbox\Event\Event;
  42. use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
  43. /**
  44. * Class AdminPlugin
  45. * @package Grav\Plugin\Admin
  46. */
  47. class AdminPlugin extends Plugin
  48. {
  49. public $features = [
  50. 'blueprints' => 1000,
  51. ];
  52. /** @var bool */
  53. protected $active = false;
  54. /** @var string */
  55. protected $template;
  56. /** @var string */
  57. protected $theme;
  58. /** @var string */
  59. protected $route;
  60. /** @var string */
  61. protected $admin_route;
  62. /** @var Uri */
  63. protected $uri;
  64. /** @var Admin */
  65. protected $admin;
  66. /** @var Session */
  67. protected $session;
  68. /** @var Popularity */
  69. protected $popularity;
  70. /** @var string */
  71. protected $base;
  72. /** @var string */
  73. protected $version;
  74. /**
  75. * @return array
  76. */
  77. public static function getSubscribedEvents()
  78. {
  79. return [
  80. 'onPluginsInitialized' => [
  81. ['autoload', 100001],
  82. ['setup', 100000],
  83. ['onPluginsInitialized', 1001]
  84. ],
  85. 'onRequestHandlerInit' => [
  86. ['onRequestHandlerInit', 100000]
  87. ],
  88. 'onFormRegisterTypes' => ['onFormRegisterTypes', 0],
  89. 'onPageInitialized' => ['onPageInitialized', 0],
  90. 'onShutdown' => ['onShutdown', 1000],
  91. PermissionsRegisterEvent::class => ['onRegisterPermissions', 1000],
  92. ];
  93. }
  94. /**
  95. * Get list of form field types specified in this plugin. Only special types needs to be listed.
  96. *
  97. * @return array
  98. */
  99. public function getFormFieldTypes()
  100. {
  101. return [
  102. 'column' => [
  103. 'input@' => false
  104. ],
  105. 'columns' => [
  106. 'input@' => false
  107. ],
  108. 'fieldset' => [
  109. 'input@' => false
  110. ],
  111. 'section' => [
  112. 'input@' => false
  113. ],
  114. 'list' => [
  115. 'array' => true
  116. ],
  117. 'file' => [
  118. 'array' => true,
  119. 'media_field' => true,
  120. 'validate' => [
  121. 'type' => 'ignore'
  122. ]
  123. ],
  124. 'pagemedia' => [
  125. 'array' => true,
  126. 'media_field' => true,
  127. 'validate' => [
  128. 'type' => 'ignore'
  129. ]
  130. ],
  131. 'filepicker' => [
  132. 'media_picker_field' => true
  133. ],
  134. 'pagemediaselect' => [
  135. 'media_picker_field' => true
  136. ],
  137. 'permissions' => [
  138. 'ignore_empty' => true,
  139. 'validate' => [
  140. 'type' => 'array'
  141. ],
  142. 'filter' => [
  143. 'type' => 'flatten_array',
  144. 'value_type' => 'bool',
  145. ]
  146. ],
  147. 'acl_picker' => [
  148. 'ignore_empty' => true,
  149. 'validate' => [
  150. 'type' => 'array'
  151. ],
  152. 'filter' => [
  153. 'type' => 'array',
  154. 'key_type' => 'string',
  155. 'value_type' => 'bool',
  156. ]
  157. ],
  158. 'taxonomy' => [
  159. 'multiple' => true,
  160. 'validate' => [
  161. 'type' => 'array'
  162. ]
  163. ]
  164. ];
  165. }
  166. /**
  167. * [onPluginsInitialized:100000] Composer autoload.
  168. *
  169. * @return ClassLoader
  170. */
  171. public function autoload(): ClassLoader
  172. {
  173. return require __DIR__ . '/vendor/autoload.php';
  174. }
  175. /**
  176. * @param Event $event
  177. * @return void
  178. */
  179. public function onFormRegisterTypes(Event $event): void
  180. {
  181. /** @var Forms $forms */
  182. $forms = $event['forms'];
  183. $forms->registerType('admin', new AdminFormFactory());
  184. }
  185. /**
  186. * [onPluginsInitialized:100000]
  187. *
  188. * If the admin path matches, initialize the Login plugin configuration and set the admin
  189. * as active.
  190. *
  191. * @return void
  192. */
  193. public function setup()
  194. {
  195. // Only enable admin if it has a route.
  196. $route = $this->config->get('plugins.admin.route');
  197. if (!$route) {
  198. return;
  199. }
  200. /** @var Uri uri */
  201. $this->uri = $this->grav['uri'];
  202. $this->base = '/' . trim($route, '/');
  203. $this->admin_route = rtrim($this->grav['pages']->base(), '/') . $this->base;
  204. $inAdmin = $this->isAdminPath();
  205. // If no users found, go to register.
  206. if (!$inAdmin && !Admin::doAnyUsersExist()) {
  207. $this->grav->redirect($this->admin_route);
  208. }
  209. // Only setup admin if we're inside the admin path.
  210. if ($inAdmin) {
  211. $this->setupAdmin();
  212. }
  213. }
  214. /**
  215. * [onPluginsInitialized:1001]
  216. *
  217. * If the admin plugin is set as active, initialize the admin
  218. *
  219. * @return void
  220. */
  221. public function onPluginsInitialized()
  222. {
  223. // Only activate admin if we're inside the admin path.
  224. if ($this->active) {
  225. $this->initializeAdmin();
  226. }
  227. // Always initialize popularity.
  228. $this->popularity = new Popularity();
  229. }
  230. /**
  231. * [onRequestHandlerInit:100000]
  232. *
  233. * @param RequestHandlerEvent $event
  234. * @return void
  235. */
  236. public function onRequestHandlerInit(RequestHandlerEvent $event)
  237. {
  238. // Store this version.
  239. $this->version = $this->getBlueprint()->get('version');
  240. $route = $event->getRoute();
  241. $base = $route->getRoute(0, 1);
  242. if ($base === $this->base) {
  243. /** @var Debugger $debugger */
  244. $debugger = $this->grav['debugger'];
  245. $debugger->addMessage('Admin v' . $this->version);
  246. $event->addMiddleware('admin_router', new Router($this->grav, $this->admin));
  247. }
  248. }
  249. /**
  250. * @param Event $event
  251. * @return void
  252. */
  253. public function onAdminControllerInit(Event $event): void
  254. {
  255. $eventController = $event['controller'];
  256. // Blacklist login related views.
  257. $loginViews = ['login', 'forgot', 'register', 'reset'];
  258. $eventController->blacklist_views = array_merge($eventController->blacklist_views, $loginViews);
  259. }
  260. /**
  261. * Force compile during save if admin plugin save
  262. *
  263. * @param Event $event
  264. * @return void
  265. */
  266. public function onAdminSave(Event $event)
  267. {
  268. $obj = $event['object'];
  269. if ($obj instanceof Data
  270. && ($blueprint = $obj->blueprints()) && $blueprint && $blueprint->getFilename() === 'admin/blueprints') {
  271. [$status, $msg] = $this->grav['admin-whitelabel']->compilePresetScss($obj);
  272. if (!$status) {
  273. $this->grav['messages']->add($msg, 'error');
  274. }
  275. }
  276. }
  277. /**
  278. * [onPageInitialized:0]
  279. *
  280. * @return void
  281. */
  282. public function onPageInitialized()
  283. {
  284. $template = $this->uri->param('tmpl');
  285. if ($template) {
  286. /** @var PageInterface $page */
  287. $page = $this->grav['page'];
  288. $page->template($template);
  289. }
  290. }
  291. /**
  292. * [onShutdown:1000]
  293. *
  294. * Handles the shutdown
  295. *
  296. * @return void
  297. */
  298. public function onShutdown()
  299. {
  300. if ($this->active) {
  301. //only activate when Admin is active
  302. if ($this->admin->shouldLoadAdditionalFilesInBackground()) {
  303. $this->admin->loadAdditionalFilesInBackground();
  304. }
  305. } elseif ($this->popularity && $this->config->get('plugins.admin.popularity.enabled')) {
  306. //if popularity is enabled, track non-admin hits
  307. $this->popularity->trackHit();
  308. }
  309. }
  310. /**
  311. * [onAdminDashboard:0]
  312. *
  313. * @return void
  314. */
  315. public function onAdminDashboard()
  316. {
  317. $lang = $this->grav['language'];
  318. $this->grav['twig']->plugins_hooked_dashboard_widgets_top[] = [
  319. 'name' => $lang->translate('PLUGIN_ADMIN.MAINTENANCE'),
  320. 'template' => 'dashboard-maintenance',
  321. ];
  322. $this->grav['twig']->plugins_hooked_dashboard_widgets_top[] = [
  323. 'name' => $lang->translate('PLUGIN_ADMIN.VIEWS_STATISTICS'),
  324. 'template' => 'dashboard-statistics',
  325. ];
  326. $this->grav['twig']->plugins_hooked_dashboard_widgets_top[] = [
  327. 'name' => $lang->translate('PLUGIN_ADMIN.NOTIFICATIONS'),
  328. 'template' => 'dashboard-notifications',
  329. ];
  330. $this->grav['twig']->plugins_hooked_dashboard_widgets_top[] = [
  331. 'name' => $lang->translate('PLUGIN_ADMIN.NEWS_FEED'),
  332. 'template' => 'dashboard-feed',
  333. ];
  334. $this->grav['twig']->plugins_hooked_dashboard_widgets_main[] = [
  335. 'name' => $lang->translate('PLUGIN_ADMIN.LATEST_PAGE_UPDATES'),
  336. 'template' => 'dashboard-pages',
  337. ];
  338. }
  339. /**
  340. * [onAdminTools:0]
  341. *
  342. * Provide the tools for the Tools page, currently only direct install
  343. *
  344. * @return void
  345. */
  346. public function onAdminTools(Event $event)
  347. {
  348. $event['tools'] = array_merge($event['tools'], [
  349. 'backups' => [['admin.maintenance', 'admin.super'], 'PLUGIN_ADMIN.BACKUPS'],
  350. 'scheduler' => [['admin.super'], 'PLUGIN_ADMIN.SCHEDULER'],
  351. 'logs' => [['admin.super'], 'PLUGIN_ADMIN.LOGS'],
  352. 'reports' => [['admin.super'], 'PLUGIN_ADMIN.REPORTS'],
  353. 'direct-install' => [['admin.super'], 'PLUGIN_ADMIN.DIRECT_INSTALL'],
  354. ]);
  355. }
  356. /**
  357. * Sets longer path to the home page allowing us to have list of pages when we enter to pages section.
  358. *
  359. * @return void
  360. */
  361. public function onPagesInitialized()
  362. {
  363. $config = $this->config;
  364. // Force SSL with redirect if required
  365. if ($config->get('system.force_ssl')) {
  366. if (!isset($_SERVER['HTTPS']) || strtolower($_SERVER['HTTPS']) !== 'on') {
  367. Admin::DEBUG && Admin::addDebugMessage('Admin SSL forced on, redirect');
  368. $url = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  369. $this->grav->redirect($url);
  370. }
  371. }
  372. $this->session = $this->grav['session'];
  373. // set session variable if it's passed via the url
  374. if (!$this->session->user->authorize('admin.super') || $this->uri->param('mode') === 'normal') {
  375. $this->session->expert = false;
  376. } elseif ($this->uri->param('mode') === 'expert') {
  377. $this->session->expert = true;
  378. } else {
  379. // set the default if not set before
  380. $this->session->expert = $this->session->expert ?? false;
  381. }
  382. // make sure page is not frozen!
  383. unset($this->grav['page']);
  384. // Call the controller if it has been set.
  385. $adminParams = $this->admin->request->getAttribute('admin');
  386. $page = null;
  387. if (isset($adminParams['controller'])) {
  388. $controllerParams = $adminParams['controller'];
  389. $class = $controllerParams['class'];
  390. if (!class_exists($class)) {
  391. throw new \RuntimeException(sprintf('Admin controller %s does not exist', $class));
  392. }
  393. /** @var \Grav\Plugin\Admin\Controllers\AdminController $controller */
  394. $controller = new $class($this->grav);
  395. $method = $controllerParams['method'];
  396. $params = $controllerParams['params'] ?? [];
  397. if (!is_callable([$controller, $method])) {
  398. throw new \RuntimeException(sprintf('Admin controller method %s() does not exist', $method));
  399. }
  400. /** @var ResponseInterface $response */
  401. $response = $controller->{$method}(...$params);
  402. if ($response->getStatusCode() !== 418) {
  403. $this->grav->close($response);
  404. }
  405. $page = $controller->getPage();
  406. if (!$page) {
  407. throw new \RuntimeException('Not Found', 404);
  408. }
  409. $this->grav['page'] = $page;
  410. $this->admin->form = $controller->getActiveForm();
  411. $legacyController = false;
  412. } else {
  413. $legacyController = true;
  414. }
  415. // Replace page service with admin.
  416. if (empty($this->grav['page'])) {
  417. /** @var UserInterface $user */
  418. $user = $this->grav['user'];
  419. $this->grav['page'] = function () use ($user) {
  420. $page = new Page();
  421. // Plugins may not have the correct Cache-Control header set, force no-store for the proxies.
  422. $page->expires(0);
  423. if ($user->authorize('admin.login')) {
  424. $event = new Event(['page' => $page]);
  425. $event = $this->grav->fireEvent('onAdminPage', $event);
  426. /** @var PageInterface $page */
  427. $page = $event['page'];
  428. if ($page->slug()) {
  429. Admin::DEBUG && Admin::addDebugMessage('Admin page: from event');
  430. return $page;
  431. }
  432. }
  433. // Look in the pages provided by the Admin plugin itself
  434. if (file_exists(__DIR__ . "/pages/admin/{$this->template}.md")) {
  435. Admin::DEBUG && Admin::addDebugMessage("Admin page: {$this->template}");
  436. $page->init(new \SplFileInfo(__DIR__ . "/pages/admin/{$this->template}.md"));
  437. $page->slug(basename($this->template));
  438. return $page;
  439. }
  440. /** @var UniformResourceLocator $locator */
  441. $locator = $this->grav['locator'];
  442. // If not provided by Admin, lookup pages added by other plugins
  443. /** @var Plugins $plugins */
  444. $plugins = $this->grav['plugins'];
  445. foreach ($plugins as $plugin) {
  446. if ($this->config->get("plugins.{$plugin->name}.enabled") !== true) {
  447. continue;
  448. }
  449. $path = $locator->findResource("plugins://{$plugin->name}/admin/pages/{$this->template}.md");
  450. if ($path) {
  451. Admin::DEBUG && Admin::addDebugMessage("Admin page: plugin {$plugin->name}/{$this->template}");
  452. $page->init(new \SplFileInfo($path));
  453. $page->slug(basename($this->template));
  454. return $page;
  455. }
  456. }
  457. return null;
  458. };
  459. }
  460. if (empty($this->grav['page'])) {
  461. if ($user->authenticated) {
  462. Admin::DEBUG && Admin::addDebugMessage('Admin page: fire onPageNotFound event');
  463. $event = new Event(['page' => null]);
  464. $event->page = null;
  465. $event = $this->grav->fireEvent('onPageNotFound', $event);
  466. /** @var PageInterface $page */
  467. $page = $event->page;
  468. if (!$page || !$page->routable()) {
  469. Admin::DEBUG && Admin::addDebugMessage('Admin page: 404 Not Found');
  470. $error_file = $this->grav['locator']->findResource('plugins://admin/pages/admin/error.md');
  471. $page = new Page();
  472. $page->init(new \SplFileInfo($error_file));
  473. $page->slug(basename($this->route));
  474. $page->routable(true);
  475. }
  476. unset($this->grav['page']);
  477. $this->grav['page'] = $page;
  478. } else {
  479. Admin::DEBUG && Admin::addDebugMessage('Admin page: login');
  480. // Not Found and not logged in: Display login page.
  481. $login_file = $this->grav['locator']->findResource('plugins://admin/pages/admin/login.md');
  482. $page = new Page();
  483. $page->init(new \SplFileInfo($login_file));
  484. $page->slug(basename($this->route));
  485. unset($this->grav['page']);
  486. $this->grav['page'] = $page;
  487. }
  488. }
  489. if ($legacyController) {
  490. // Handle tasks.
  491. $this->admin->task = $task = $this->grav['task'] ?? $this->grav['action'];
  492. if ($task) {
  493. Admin::DEBUG && Admin::addDebugMessage("Admin task: {$task}");
  494. // Make local copy of POST.
  495. $post = $this->grav['uri']->post();
  496. $this->initializeController($task, $post);
  497. } elseif ($this->template === 'logs' && $this->route) {
  498. // Display RAW error message.
  499. $response = new Response(200, [], $this->admin->logEntry());
  500. $this->grav->close($response);
  501. }
  502. }
  503. // Explicitly set a timestamp on assets
  504. $this->grav['assets']->setTimestamp(substr(md5(GRAV_VERSION . $this->grav['config']->checksum()), 0, 10));
  505. }
  506. /**
  507. * Handles initializing the assets
  508. *
  509. * @return void
  510. */
  511. public function onAssetsInitialized()
  512. {
  513. // Disable Asset pipelining
  514. $assets = $this->grav['assets'];
  515. $assets->setJsPipeline(false);
  516. $assets->setCssPipeline(false);
  517. }
  518. /**
  519. * Add twig paths to plugin templates.
  520. *
  521. * @return void
  522. */
  523. public function onTwigTemplatePaths()
  524. {
  525. $twig_paths = [];
  526. $this->grav->fireEvent('onAdminTwigTemplatePaths', new Event(['paths' => &$twig_paths]));
  527. $twig_paths[] = __DIR__ . '/themes/' . $this->theme . '/templates';
  528. $this->grav['twig']->twig_paths = $twig_paths;
  529. }
  530. /**
  531. * Set all twig variables for generating output.
  532. *
  533. * @return void
  534. */
  535. public function onTwigSiteVariables()
  536. {
  537. /** @var Twig $twig */
  538. $twig = $this->grav['twig'];
  539. /** @var PageInterface $page */
  540. $page = $this->grav['page'];
  541. $twig->twig_vars['location'] = $this->template;
  542. $twig->twig_vars['nav_route'] = trim($this->template . '/' . $this->route, '/') . '/';
  543. $twig->twig_vars['base_url_relative_frontend'] = $twig->twig_vars['base_url_relative'] ?: '/';
  544. $twig->twig_vars['admin_route'] = trim($this->admin_route, '/');
  545. $twig->twig_vars['template_route'] = $this->template;
  546. $twig->twig_vars['current_route'] = '/' . $twig->twig_vars['admin_route'] . '/' . $this->template . '/' . $this->route;
  547. $twig->twig_vars['base_url_relative'] = $twig->twig_vars['base_url_simple'] . '/' . $twig->twig_vars['admin_route'];
  548. $twig->twig_vars['current_url'] = rtrim($twig->twig_vars['base_url_relative'] . '/' . $this->template . '/' . $this->route, '/');
  549. $theme_url = '/' . ltrim($this->grav['locator']->findResource('plugin://admin/themes/' . $this->theme,
  550. false), '/');
  551. $twig->twig_vars['theme_url'] = $theme_url;
  552. $twig->twig_vars['base_url'] = $twig->twig_vars['base_url_relative'];
  553. $twig->twig_vars['base_path'] = GRAV_ROOT;
  554. $twig->twig_vars['admin'] = $this->admin;
  555. $twig->twig_vars['user'] = $this->admin->user;
  556. $twig->twig_vars['admin_version'] = $this->version;
  557. $twig->twig_vars['logviewer'] = new LogViewer();
  558. $twig->twig_vars['form_max_filesize'] = Utils::getUploadLimit() / 1024 / 1024;
  559. // Start white label functionality
  560. $twig->twig_vars['whitelabel_presets'] = $this->getPresets();
  561. $custom_logo = $this->config->get('plugins.admin.whitelabel.logo_custom', false);
  562. $custom_login_logo = $this->config->get('plugins.admin.whitelabel.logo_login', false);
  563. $custom_footer = $this->config->get('plugins.admin.whitelabel.custom_footer', false);
  564. if ($custom_logo && is_array($custom_logo)) {
  565. $custom_logo = array_keys($custom_logo);
  566. $path = array_shift($custom_logo);
  567. $twig->twig_vars['custom_admin_logo'] = $path;
  568. }
  569. if ($custom_login_logo && is_array($custom_login_logo)) {
  570. $custom_login_logo = array_keys($custom_login_logo);
  571. $path = array_shift($custom_login_logo);
  572. $twig->twig_vars['custom_login_logo'] = $path;
  573. }
  574. if ($custom_footer) {
  575. $footer = Utils::processMarkdown($custom_footer);
  576. $twig->twig_vars['custom_admin_footer'] = $footer;
  577. }
  578. $custom_css = $this->config->get('plugins.admin.whitelabel.custom_css', false);
  579. if ($custom_css) {
  580. $this->grav['assets']->addInlineCss($custom_css);
  581. }
  582. // End white label functionality
  583. $fa_icons_file = CompiledYamlFile::instance($this->grav['locator']->findResource('plugin://admin/themes/grav/templates/forms/fields/iconpicker/icons' . YAML_EXT));
  584. $fa_icons = $fa_icons_file->content();
  585. $fa_icons = array_map(function ($icon) {
  586. //only pick used values
  587. return ['id' => $icon['id'], 'unicode' => $icon['unicode']];
  588. }, $fa_icons['icons']);
  589. $twig->twig_vars['fa_icons'] = $fa_icons;
  590. // add form if it exists in the page
  591. $header = $page->header();
  592. $forms = [];
  593. if (isset($header->forms)) foreach ($header->forms as $key => $form) {
  594. $forms[$key] = new Form($page, null, $form);
  595. }
  596. $twig->twig_vars['forms'] = $forms;
  597. // preserve form validation
  598. if ($this->admin->form) {
  599. $twig->twig_vars['form'] = $this->admin->form;
  600. } elseif (!isset($twig->twig_vars['form'])) {
  601. if (isset($header->form)) {
  602. $twig->twig_vars['form'] = new Form($page);
  603. } elseif (isset($header->forms)) {
  604. $twig->twig_vars['form'] = new Form($page, null, reset($header->forms));
  605. }
  606. }
  607. // Gather all nav items
  608. $this->grav['twig']->plugins_hooked_nav = [];
  609. $this->grav->fireEvent('onAdminMenu');
  610. uasort($this->grav['twig']->plugins_hooked_nav, function ($a, $b) {
  611. $ac = $a['priority'] ?? 0;
  612. $bc = $b['priority'] ?? 0;
  613. return $bc <=> $ac;
  614. });
  615. // Gather Plugin-hooked dashboard items
  616. $this->grav->fireEvent('onAdminDashboard');
  617. switch ($this->template) {
  618. case 'dashboard':
  619. $twig->twig_vars['popularity'] = $this->popularity;
  620. break;
  621. }
  622. $flashData = $this->grav['session']->getFlashCookieObject(Admin::TMP_COOKIE_NAME);
  623. if (isset($flashData->message)) {
  624. $this->grav['messages']->add($flashData->message, $flashData->status);
  625. }
  626. }
  627. /**
  628. * Add images to twig template paths to allow inclusion of SVG files
  629. *
  630. * @return void
  631. */
  632. public function onTwigLoader()
  633. {
  634. /** @var Twig $twig */
  635. $twig = $this->grav['twig'];
  636. /** @var UniformResourceLocator $locator */
  637. $locator = Grav::instance()['locator'];
  638. $theme_paths = $locator->findResources('plugins://admin/themes/' . $this->theme . '/images');
  639. foreach($theme_paths as $images_path) {
  640. $twig->addPath($images_path, 'admin-images');
  641. }
  642. }
  643. /**
  644. * Add the Admin Twig Extensions
  645. *
  646. * @return void
  647. */
  648. public function onTwigExtensions()
  649. {
  650. /** @var Twig $twig */
  651. $twig = $this->grav['twig'];
  652. $twig->twig->addExtension(new AdminTwigExtension);
  653. }
  654. /**
  655. * @param Event $event
  656. * @return void
  657. */
  658. public function onAdminAfterSave(Event $event)
  659. {
  660. // Special case to redirect after changing the admin route to avoid 'breaking'
  661. $obj = $event['object'];
  662. if (null !== $obj && method_exists($obj, 'blueprints')) {
  663. $blueprint = $obj->blueprints()->getFilename();
  664. if ($blueprint === 'admin/blueprints' && isset($obj->route) && $this->admin_route !== $obj->route) {
  665. $redirect = preg_replace('/^' . str_replace('/','\/',$this->admin_route) . '/',$obj->route,$this->uri->path());
  666. $this->grav->redirect($redirect);
  667. }
  668. }
  669. }
  670. /**
  671. * Convert some types where we want to process out of the standard config path
  672. *
  673. * @param Event $e
  674. * @return void
  675. */
  676. public function onAdminData(Event $e)
  677. {
  678. $type = $e['type'] ?? null;
  679. switch ($type) {
  680. case 'config':
  681. $e['type'] = $this->admin->authorize(['admin.configuration.system', 'admin.super']) ? 'config/system' : 'config/site';
  682. break;
  683. case 'tools/scheduler':
  684. $e['type'] = 'config/scheduler';
  685. break;
  686. case 'tools':
  687. case 'tools/backups':
  688. $e['type'] = 'config/backups';
  689. break;
  690. }
  691. }
  692. /**
  693. * @return void
  694. */
  695. public function onOutputGenerated()
  696. {
  697. // Clear flash objects for previously uploaded files whenever the user switches page or reloads
  698. // ignoring any JSON / extension call
  699. if ($this->admin->task !== 'save' && empty($this->uri->extension())) {
  700. // Discard any previously uploaded files session and remove all uploaded files.
  701. if ($flash = $this->session->getFlashObject('files-upload')) {
  702. $flash = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($flash));
  703. foreach ($flash as $key => $value) {
  704. if ($key !== 'tmp_name') {
  705. continue;
  706. }
  707. @unlink($value);
  708. }
  709. }
  710. }
  711. }
  712. /**
  713. * Initial stab at registering permissions (WIP)
  714. *
  715. * @param PermissionsRegisterEvent $event
  716. * @return void
  717. */
  718. public function onRegisterPermissions(PermissionsRegisterEvent $event): void
  719. {
  720. $actions = PermissionsReader::fromYaml("plugin://{$this->name}/permissions.yaml");
  721. $permissions = $event->permissions;
  722. $permissions->addActions($actions);
  723. }
  724. /**
  725. * @return void
  726. */
  727. public function onAdminMenu()
  728. {
  729. /** @var Twig $twig */
  730. $twig = $this->grav['twig'];
  731. // Dashboard
  732. $twig->plugins_hooked_nav['PLUGIN_ADMIN.DASHBOARD'] = [
  733. 'route' => 'dashboard',
  734. 'icon' => 'fa-th',
  735. 'authorize' => ['admin.login', 'admin.super'],
  736. 'priority' => 10
  737. ];
  738. // Configuration
  739. $twig->plugins_hooked_nav['PLUGIN_ADMIN.CONFIGURATION'] = [
  740. 'route' => 'config',
  741. 'icon' => 'fa-wrench',
  742. 'authorize' => [
  743. 'admin.configuration.system',
  744. 'admin.configuration.site',
  745. 'admin.configuration.media',
  746. 'admin.configuration.security',
  747. 'admin.configuration.info',
  748. 'admin.super'],
  749. 'priority' => 9
  750. ];
  751. // Pages
  752. $count = new Container(['count' => function () { return $this->admin->pagesCount(); }]);
  753. $twig->plugins_hooked_nav['PLUGIN_ADMIN.PAGES'] = [
  754. 'route' => 'pages',
  755. 'icon' => 'fa-file-text-o',
  756. 'authorize' => ['admin.pages', 'admin.super'],
  757. 'badge' => $count,
  758. 'priority' => 5
  759. ];
  760. // Plugins
  761. $count = new Container(['updates' => 0, 'count' => function () { return count($this->admin->plugins()); }]);
  762. $twig->plugins_hooked_nav['PLUGIN_ADMIN.PLUGINS'] = [
  763. 'route' => 'plugins',
  764. 'icon' => 'fa-plug',
  765. 'authorize' => ['admin.plugins', 'admin.super'],
  766. 'badge' => $count,
  767. 'priority' => -8
  768. ];
  769. // Themes
  770. $count = new Container(['updates' => 0, 'count' => function () { return count($this->admin->themes()); }]);
  771. $twig->plugins_hooked_nav['PLUGIN_ADMIN.THEMES'] = [
  772. 'route' => 'themes',
  773. 'icon' => 'fa-tint',
  774. 'authorize' => ['admin.themes', 'admin.super'],
  775. 'badge' => $count,
  776. 'priority' => -9
  777. ];
  778. // Tools
  779. $twig->plugins_hooked_nav['PLUGIN_ADMIN.TOOLS'] = [
  780. 'route' => 'tools',
  781. 'icon' => 'fa-briefcase',
  782. 'authorize' => $this->admin::toolsPermissions(),
  783. 'priority' => -10
  784. ];
  785. }
  786. /**
  787. * Check if the current route is under the admin path
  788. *
  789. * @return bool
  790. */
  791. public function isAdminPath()
  792. {
  793. $route = $this->uri->route();
  794. return $route === $this->base || 0 === strpos($route, $this->base . '/');
  795. }
  796. /**
  797. * Helper function to replace Pages::Types() and to provide an event to manipulate the data
  798. *
  799. * Dispatches 'onAdminPageTypes' event with 'types' data member which is a reference to the data
  800. *
  801. * @param bool $keysOnly
  802. * @return array
  803. */
  804. public static function pagesTypes(bool $keysOnly = false)
  805. {
  806. $types = Pages::types();
  807. // First filter by configuration
  808. $hideTypes = (array)Grav::instance()['config']->get('plugins.admin.hide_page_types');
  809. foreach ($hideTypes as $hide) {
  810. if (isset($types[$hide])) {
  811. unset($types[$hide]);
  812. } else {
  813. foreach ($types as $key => $type) {
  814. $match = preg_match('#' . $hide . '#i', $key);
  815. if ($match) {
  816. unset($types[$key]);
  817. }
  818. }
  819. }
  820. }
  821. // Allow manipulating of the data by event
  822. $e = new Event(['types' => &$types]);
  823. Grav::instance()->fireEvent('onAdminPageTypes', $e);
  824. return $keysOnly ? array_keys($types) : $types;
  825. }
  826. /**
  827. * Helper function to replace Pages::modularTypes() and to provide an event to manipulate the data
  828. *
  829. * Dispatches 'onAdminModularPageTypes' event with 'types' data member which is a reference to the data
  830. *
  831. * @param bool $keysOnly
  832. * @return array
  833. */
  834. public static function pagesModularTypes(bool $keysOnly = false)
  835. {
  836. $types = Pages::modularTypes();
  837. // First filter by configuration
  838. $hideTypes = (array)Grav::instance()['config']->get('plugins.admin.hide_modular_page_types');
  839. foreach ($hideTypes as $hide) {
  840. if (isset($types[$hide])) {
  841. unset($types[$hide]);
  842. } else {
  843. foreach ($types as $key => $type) {
  844. $match = preg_match('#' . $hide . '#i', $key);
  845. if ($match) {
  846. unset($types[$key]);
  847. }
  848. }
  849. }
  850. }
  851. // Allow manipulating of the data by event
  852. $e = new Event(['types' => &$types]);
  853. Grav::instance()->fireEvent('onAdminModularPageTypes', $e);
  854. return $keysOnly ? array_keys($types) : $types;
  855. }
  856. /**
  857. * Validate a value. Currently validates
  858. *
  859. * - 'user' for username format and username availability.
  860. * - 'password1' for password format
  861. * - 'password2' for equality to password1
  862. *
  863. * @param string $type The field type
  864. * @param string $value The field value
  865. * @param string $extra Any extra value required
  866. *
  867. * @return bool
  868. */
  869. protected function validate($type, $value, $extra = '')
  870. {
  871. /** @var Login $login */
  872. $login = $this->grav['login'];
  873. return $login->validateField($type, $value, $extra);
  874. }
  875. /**
  876. * @param string $task
  877. * @param array|null $post
  878. * @return void
  879. */
  880. protected function initializeController($task, $post = null): void
  881. {
  882. Admin::DEBUG && Admin::addDebugMessage('Admin controller: execute');
  883. $controller = new AdminController();
  884. $controller->initialize($this->grav, $this->template, $task, $this->route, $post);
  885. $controller->execute();
  886. $controller->redirect();
  887. }
  888. /**
  889. * @return void
  890. */
  891. protected function setupAdmin()
  892. {
  893. // Set cache based on admin_cache option.
  894. /** @var Cache $cache */
  895. $cache = $this->grav['cache'];
  896. $cache->setEnabled($this->config->get('plugins.admin.cache_enabled'));
  897. /** @var Pages $pages */
  898. $pages = $this->grav['pages'];
  899. // Disable frontend pages in admin.
  900. $pages->disablePages();
  901. // Force file hash checks to fix caching on moved and deleted pages.
  902. $pages->setCheckMethod('hash');
  903. /** @var Session $session */
  904. $session = $this->grav['session'];
  905. // Make sure that the session has been initialized.
  906. try {
  907. $session->init();
  908. } catch (SessionException $e) {
  909. $session->init();
  910. $message = 'Session corruption detected, restarting session...';
  911. /** @var Debugger $debugger */
  912. $debugger = $this->grav['debugger'];
  913. $debugger->addMessage($message);
  914. $this->grav['messages']->add($message, 'error');
  915. }
  916. $this->active = true;
  917. }
  918. /**
  919. * Initialize the admin.
  920. *
  921. * @return void
  922. * @throws \RuntimeException
  923. */
  924. protected function initializeAdmin()
  925. {
  926. // Check for required plugins
  927. if (!$this->grav['config']->get('plugins.login.enabled') || !$this->grav['config']->get('plugins.form.enabled') || !$this->grav['config']->get('plugins.email.enabled')) {
  928. throw new \RuntimeException('One of the required plugins is missing or not enabled');
  929. }
  930. /** @var Cache $cache */
  931. $cache = $this->grav['cache'];
  932. // Have a unique Admin-only Cache key
  933. $cache_key = $cache->getKey();
  934. $cache->setKey($cache_key . '$');
  935. /** @var Session $session */
  936. $session = $this->grav['session'];
  937. /** @var Language $language */
  938. $language = $this->grav['language'];
  939. /** @var UniformResourceLocator $locator */
  940. $locator = $this->grav['locator'];
  941. // Turn on Twig autoescaping
  942. if ($this->uri->param('task') !== 'processmarkdown') {
  943. $this->grav['twig']->setAutoescape(true);
  944. }
  945. // Initialize Admin Language if needed
  946. if ($language->enabled() && empty($session->admin_lang)) {
  947. $session->admin_lang = $language->getLanguage();
  948. }
  949. // Decide admin template and route.
  950. $path = trim(substr($this->uri->route(), strlen($this->base)), '/');
  951. if (empty($this->template)) {
  952. $this->template = 'dashboard';
  953. }
  954. // Can't access path directly...
  955. if ($path && $path !== 'register') {
  956. $array = explode('/', $path, 2);
  957. $this->template = array_shift($array);
  958. $this->route = array_shift($array);
  959. }
  960. // Initialize admin class (also registers it to Grav services).
  961. $this->admin = new Admin($this->grav, $this->admin_route, $this->template, $this->route);
  962. // Get theme for admin
  963. $this->theme = $this->config->get('plugins.admin.theme', 'grav');
  964. // Replace themes service with admin.
  965. $this->grav['themes'] = function () {
  966. return new Themes($this->grav);
  967. };
  968. // Initialize white label functionality
  969. $this->grav['admin-whitelabel'] = new WhiteLabel();
  970. // Compile a missing preset.css file
  971. $preset_css = 'asset://admin-preset.css';
  972. $preset_path = $this->grav['locator']->findResource($preset_css);
  973. if (!$preset_path) {
  974. $this->grav['admin-whitelabel']->compilePresetScss($this->config->get('plugins.admin.whitelabel'));
  975. }
  976. // These events are needed for login.
  977. $this->enable([
  978. 'onTwigExtensions' => ['onTwigExtensions', 1000],
  979. 'onPagesInitialized' => ['onPagesInitialized', 1000],
  980. 'onTwigLoader' => ['onTwigLoader', 1000],
  981. 'onTwigTemplatePaths' => ['onTwigTemplatePaths', 1000],
  982. 'onTwigSiteVariables' => ['onTwigSiteVariables', 1000],
  983. 'onAssetsInitialized' => ['onAssetsInitialized', 1000],
  984. ]);
  985. // Do not do more if user isn't logged in.
  986. if (!$this->admin->user->authorize('admin.login')) {
  987. return;
  988. }
  989. // These events are not needed during login.
  990. $this->enable([
  991. 'onAdminControllerInit' => ['onAdminControllerInit', 1001],
  992. 'onAdminDashboard' => ['onAdminDashboard', 0],
  993. 'onAdminMenu' => ['onAdminMenu', 1000],
  994. 'onAdminTools' => ['onAdminTools', 0],
  995. 'onAdminSave' => ['onAdminSave', 0],
  996. 'onAdminAfterSave' => ['onAdminAfterSave', 0],
  997. 'onAdminData' => ['onAdminData', 0],
  998. 'onOutputGenerated' => ['onOutputGenerated', 0],
  999. ]);
  1000. // Double check we have system.yaml, site.yaml etc
  1001. $config_path = $locator->findResource('user://config');
  1002. foreach ($this->admin::configurations() as $config_file) {
  1003. if ($config_file === 'info') {
  1004. continue;
  1005. }
  1006. $config_file = "{$config_path}/{$config_file}.yaml";
  1007. if (!file_exists($config_file)) {
  1008. touch($config_file);
  1009. }
  1010. }
  1011. $assets = $this->grav['assets'];
  1012. $translations = 'this.GravAdmin = this.GravAdmin || {}; if (!this.GravAdmin.translations) this.GravAdmin.translations = {}; ' . PHP_EOL . 'this.GravAdmin.translations.PLUGIN_ADMIN = {';
  1013. // Enable language translations
  1014. $translations_actual_state = $this->config->get('system.languages.translations');
  1015. $this->config->set('system.languages.translations', true);
  1016. $strings = [
  1017. 'EVERYTHING_UP_TO_DATE',
  1018. 'UPDATES_ARE_AVAILABLE',
  1019. 'IS_AVAILABLE_FOR_UPDATE',
  1020. 'AND',
  1021. 'IS_NOW_AVAILABLE',
  1022. 'CURRENT',
  1023. 'UPDATE_GRAV_NOW',
  1024. 'TASK_COMPLETED',
  1025. 'UPDATE',
  1026. 'UPDATING_PLEASE_WAIT',
  1027. 'GRAV_SYMBOLICALLY_LINKED',
  1028. 'OF_YOUR',
  1029. 'OF_THIS',
  1030. 'HAVE_AN_UPDATE_AVAILABLE',
  1031. 'UPDATE_AVAILABLE',
  1032. 'UPDATES_AVAILABLE',
  1033. 'FULLY_UPDATED',
  1034. 'DAYS',
  1035. 'PAGE_MODES',
  1036. 'PAGE_TYPES',
  1037. 'ACCESS_LEVELS',
  1038. 'NOTHING_TO_SAVE',
  1039. 'FILE_UNSUPPORTED',
  1040. 'FILE_ERROR_ADD',
  1041. 'FILE_ERROR_UPLOAD',
  1042. 'DROP_FILES_HERE_TO_UPLOAD',
  1043. 'DELETE',
  1044. 'UNSET',
  1045. 'INSERT',
  1046. 'METADATA',
  1047. 'VIEW',
  1048. 'UNDO',
  1049. 'REDO',
  1050. 'HEADERS',
  1051. 'BOLD',
  1052. 'ITALIC',
  1053. 'STRIKETHROUGH',
  1054. 'SUMMARY_DELIMITER',
  1055. 'LINK',
  1056. 'IMAGE',
  1057. 'BLOCKQUOTE',
  1058. 'UNORDERED_LIST',
  1059. 'ORDERED_LIST',
  1060. 'EDITOR',
  1061. 'PREVIEW',
  1062. 'FULLSCREEN',
  1063. 'MODULE',
  1064. 'NON_MODULE',
  1065. 'VISIBLE',
  1066. 'NON_VISIBLE',
  1067. 'ROUTABLE',
  1068. 'NON_ROUTABLE',
  1069. 'PUBLISHED',
  1070. 'NON_PUBLISHED',
  1071. 'PLUGINS',
  1072. 'THEMES',
  1073. 'ALL',
  1074. 'FROM',
  1075. 'TO',
  1076. 'DROPZONE_CANCEL_UPLOAD',
  1077. 'DROPZONE_CANCEL_UPLOAD_CONFIRMATION',
  1078. 'DROPZONE_DEFAULT_MESSAGE',
  1079. 'DROPZONE_FALLBACK_MESSAGE',
  1080. 'DROPZONE_FALLBACK_TEXT',
  1081. 'DROPZONE_FILE_TOO_BIG',
  1082. 'DROPZONE_INVALID_FILE_TYPE',
  1083. 'DROPZONE_MAX_FILES_EXCEEDED',
  1084. 'DROPZONE_REMOVE_FILE',
  1085. 'DROPZONE_RESPONSE_ERROR'
  1086. ];
  1087. foreach ($strings as $string) {
  1088. $separator = (end($strings) === $string) ? '' : ',';
  1089. $translations .= '"' . $string . '": "' . htmlspecialchars($this->admin::translate('PLUGIN_ADMIN.' . $string)) . '"' . $separator;
  1090. }
  1091. $translations .= '};';
  1092. $translations .= 'this.GravAdmin.translations.PLUGIN_FORM = {';
  1093. $strings = ['RESOLUTION_MIN', 'RESOLUTION_MAX'];
  1094. foreach ($strings as $string) {
  1095. $separator = (end($strings) === $string) ? '' : ',';
  1096. $translations .= '"' . $string . '": "' . $this->admin::translate('PLUGIN_FORM.' . $string) . '"' . $separator;
  1097. }
  1098. $translations .= '};';
  1099. $translations .= 'this.GravAdmin.translations.GRAV_CORE = {';
  1100. $strings = [
  1101. 'NICETIME.SECOND',
  1102. 'NICETIME.MINUTE',
  1103. 'NICETIME.HOUR',
  1104. 'NICETIME.DAY',
  1105. 'NICETIME.WEEK',
  1106. 'NICETIME.MONTH',
  1107. 'NICETIME.YEAR',
  1108. 'CRON.EVERY',
  1109. 'CRON.EVERY_HOUR',
  1110. 'CRON.EVERY_MINUTE',
  1111. 'CRON.EVERY_DAY_OF_WEEK',
  1112. 'CRON.EVERY_DAY_OF_MONTH',
  1113. 'CRON.EVERY_MONTH',
  1114. 'CRON.TEXT_PERIOD',
  1115. 'CRON.TEXT_MINS',
  1116. 'CRON.TEXT_TIME',
  1117. 'CRON.TEXT_DOW',
  1118. 'CRON.TEXT_MONTH',
  1119. 'CRON.TEXT_DOM',
  1120. 'CRON.ERROR1',
  1121. 'CRON.ERROR2',
  1122. 'CRON.ERROR3',
  1123. 'CRON.ERROR4',
  1124. 'MONTHS_OF_THE_YEAR',
  1125. 'DAYS_OF_THE_WEEK'
  1126. ];
  1127. foreach ($strings as $string) {
  1128. $separator = (end($strings) === $string) ? '' : ',';
  1129. $translations .= '"' . $string . '": ' . json_encode($this->admin::translate('GRAV.'.$string)) . $separator;
  1130. }
  1131. $translations .= '};';
  1132. // set the actual translations state back
  1133. $this->config->set('system.languages.translations', $translations_actual_state);
  1134. $assets->addInlineJs($translations);
  1135. // Fire even to register permissions from other plugins
  1136. $this->grav->fireEvent('onAdminRegisterPermissions', new Event(['admin' => $this->admin]));
  1137. }
  1138. /**
  1139. * @return array
  1140. */
  1141. public static function themeOptions()
  1142. {
  1143. static $options;
  1144. if (null === $options) {
  1145. $options = [];
  1146. $theme_files = glob(__dir__ . '/themes/grav/css/codemirror/themes/*.css');
  1147. foreach ($theme_files as $theme_file) {
  1148. $theme = basename(basename($theme_file, '.css'));
  1149. $options[$theme] = Inflector::titleize($theme);
  1150. }
  1151. }
  1152. return $options;
  1153. }
  1154. /**
  1155. * @return array
  1156. */
  1157. public function getPresets()
  1158. {
  1159. $filename = $this->grav['locator']->findResource('plugin://admin/presets.yaml', false);
  1160. $file = CompiledYamlFile::instance($filename);
  1161. $presets = (array)$file->content();
  1162. $custom_presets = $this->config->get('plugins.admin.whitelabel.custom_presets');
  1163. if (isset($custom_presets)) {
  1164. $custom_presets = Yaml::parse($custom_presets);
  1165. if (is_array($custom_presets)) {
  1166. if (isset($custom_presets['name'], $custom_presets['colors'], $custom_presets['accents'])) {
  1167. $preset = [Inflector::hyphenize($custom_presets['name']) => $custom_presets];
  1168. $presets = $preset + $presets;
  1169. } else {
  1170. foreach ($custom_presets as $value) {
  1171. if (isset($value['name'], $value['colors'], $value['accents'])) {
  1172. $preset = [Inflector::hyphenize($value['name']) => $value];
  1173. $presets = $preset + $presets;
  1174. }
  1175. }
  1176. }
  1177. }
  1178. }
  1179. return $presets;
  1180. }
  1181. }