admin.php 29 KB

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