admin.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919
  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 = $this->grav['uri']->post();
  297. // Initialize Page Types
  298. Pages::types();
  299. // Handle tasks.
  300. $this->admin->task = $task = !empty($post['task']) ? $post['task'] : $this->uri->param('task');
  301. if ($task) {
  302. $this->initializeController($task, $post);
  303. } elseif ($this->template === 'logs' && $this->route) {
  304. // Display RAW error message.
  305. echo $this->admin->logEntry();
  306. exit();
  307. }
  308. $self = $this;
  309. // make sure page is not frozen!
  310. unset($this->grav['page']);
  311. $this->admin->pagesCount();
  312. // Replace page service with admin.
  313. $this->grav['page'] = function () use ($self) {
  314. $page = new Page;
  315. $page->expires(0);
  316. if ($this->grav['user']->authorize('admin.login')) {
  317. $event = new Event(['page' => $page]);
  318. $event = $this->grav->fireEvent('onAdminPage', $event);
  319. $page = $event['page'];
  320. if ($page->slug()) {
  321. return $page;
  322. }
  323. }
  324. // Look in the pages provided by the Admin plugin itself
  325. if (file_exists(__DIR__ . "/pages/admin/{$self->template}.md")) {
  326. $page->init(new \SplFileInfo(__DIR__ . "/pages/admin/{$self->template}.md"));
  327. $page->slug(basename($self->template));
  328. return $page;
  329. }
  330. // If not provided by Admin, lookup pages added by other plugins
  331. $plugins = $this->grav['plugins'];
  332. $locator = $this->grav['locator'];
  333. foreach ($plugins as $plugin) {
  334. if ($this->config->get("plugins.{$plugin->name}.enabled") !== true) {
  335. continue;
  336. }
  337. $path = $locator->findResource("user://plugins/{$plugin->name}/admin/pages/{$self->template}.md");
  338. if ($path) {
  339. $page->init(new \SplFileInfo($path));
  340. $page->slug(basename($self->template));
  341. return $page;
  342. }
  343. }
  344. return null;
  345. };
  346. if (empty($this->grav['page'])) {
  347. if ($this->grav['user']->authenticated) {
  348. $event = $this->grav->fireEvent('onPageNotFound');
  349. if (isset($event->page)) {
  350. unset($this->grav['page']);
  351. $this->grav['page'] = $event->page;
  352. } else {
  353. throw new \RuntimeException('Page Not Found', 404);
  354. }
  355. } else {
  356. $this->grav->redirect($this->admin_route);
  357. }
  358. }
  359. // Explicitly set a timestamp on assets
  360. $this->grav['assets']->setTimestamp(substr(md5(GRAV_VERSION . $this->grav['config']->checksum()), 0, 10));
  361. }
  362. /**
  363. * Handles initializing the assets
  364. */
  365. public function onAssetsInitialized()
  366. {
  367. // Disable Asset pipelining
  368. $assets = $this->grav['assets'];
  369. $assets->setJsPipeline(false);
  370. $assets->setCssPipeline(false);
  371. }
  372. /**
  373. * Add twig paths to plugin templates.
  374. */
  375. public function onTwigTemplatePaths()
  376. {
  377. $twig_paths = [];
  378. $this->grav->fireEvent('onAdminTwigTemplatePaths', new Event(['paths' => &$twig_paths]));
  379. $twig_paths[] = __DIR__ . '/themes/' . $this->theme . '/templates';
  380. $this->grav['twig']->twig_paths = $twig_paths;
  381. }
  382. /**
  383. * Set all twig variables for generating output.
  384. */
  385. public function onTwigSiteVariables()
  386. {
  387. $twig = $this->grav['twig'];
  388. $page = $this->grav['page'];
  389. $twig->twig_vars['location'] = $this->template;
  390. $twig->twig_vars['base_url_relative_frontend'] = $twig->twig_vars['base_url_relative'] ?: '/';
  391. $twig->twig_vars['admin_route'] = trim($this->admin_route, '/');
  392. $twig->twig_vars['current_route'] = '/' . $twig->twig_vars['admin_route'] . '/' . $this->template . '/' . $this->route;
  393. $twig->twig_vars['base_url_relative'] = $twig->twig_vars['base_url_simple'] . '/' . $twig->twig_vars['admin_route'];
  394. $twig->twig_vars['current_url'] = rtrim($twig->twig_vars['base_url_relative'] . '/' . $this->template . '/' . $this->route, '/');
  395. $theme_url = '/' . ltrim($this->grav['locator']->findResource('plugin://admin/themes/' . $this->theme,
  396. false), '/');
  397. $twig->twig_vars['theme_url'] = $theme_url;
  398. $twig->twig_vars['base_url'] = $twig->twig_vars['base_url_relative'];
  399. $twig->twig_vars['base_path'] = GRAV_ROOT;
  400. $twig->twig_vars['admin'] = $this->admin;
  401. $twig->twig_vars['admin_version'] = $this->version;
  402. $fa_icons_file = CompiledYamlFile::instance($this->grav['locator']->findResource('plugin://admin/themes/grav/templates/forms/fields/iconpicker/icons' . YAML_EXT));
  403. $fa_icons = $fa_icons_file->content();
  404. $fa_icons = array_map(function ($icon) {
  405. //only pick used values
  406. return ['id' => $icon['id'], 'unicode' => $icon['unicode']];
  407. }, $fa_icons['icons']);
  408. $twig->twig_vars['fa_icons'] = $fa_icons;
  409. // add form if it exists in the page
  410. $header = $page->header();
  411. $forms = [];
  412. if (isset($header->forms)) foreach ($header->forms as $key => $form) {
  413. $forms[$key] = new Form($page, null, $form);
  414. }
  415. $twig->twig_vars['forms'] = $forms;
  416. // preserve form validation
  417. if (!isset($twig->twig_vars['form'])) {
  418. if (isset($header->form)) {
  419. $twig->twig_vars['form'] = new Form($page);
  420. } elseif (isset($header->forms)) {
  421. $twig->twig_vars['form'] = new Form($page, null, reset($header->forms));
  422. }
  423. }
  424. // Gather Plugin-hooked nav items
  425. $this->grav->fireEvent('onAdminMenu');
  426. switch ($this->template) {
  427. case 'dashboard':
  428. $twig->twig_vars['popularity'] = $this->popularity;
  429. // Gather Plugin-hooked dashboard items
  430. $this->grav->fireEvent('onAdminDashboard');
  431. break;
  432. }
  433. $flashData = $this->grav['session']->getFlashCookieObject(Admin::TMP_COOKIE_NAME);
  434. if (isset($flashData->message)) {
  435. $this->grav['messages']->add($flashData->message, $flashData->status);
  436. }
  437. }
  438. /**
  439. * Handles the shutdown
  440. */
  441. public function onShutdown()
  442. {
  443. if ($this->active) {
  444. //only activate when Admin is active
  445. if ($this->admin->shouldLoadAdditionalFilesInBackground()) {
  446. $this->admin->loadAdditionalFilesInBackground();
  447. }
  448. } else {
  449. //if popularity is enabled, track non-admin hits
  450. if ($this->config->get('plugins.admin.popularity.enabled')) {
  451. $this->popularity->trackHit();
  452. }
  453. }
  454. }
  455. /**
  456. * Get list of form field types specified in this plugin. Only special types needs to be listed.
  457. *
  458. * @return array
  459. */
  460. public function getFormFieldTypes()
  461. {
  462. return [
  463. 'column' => [
  464. 'input@' => false
  465. ],
  466. 'columns' => [
  467. 'input@' => false
  468. ],
  469. 'fieldset' => [
  470. 'input@' => false
  471. ],
  472. 'section' => [
  473. 'input@' => false
  474. ],
  475. 'tab' => [
  476. 'input@' => false
  477. ],
  478. 'tabs' => [
  479. 'input@' => false
  480. ],
  481. 'key' => [
  482. 'input@' => false
  483. ],
  484. 'list' => [
  485. 'array' => true
  486. ],
  487. 'file' => [
  488. 'array' => true
  489. ]
  490. ];
  491. }
  492. /**
  493. * Initialize the admin.
  494. *
  495. * @throws \RuntimeException
  496. */
  497. protected function initializeAdmin()
  498. {
  499. $this->enable([
  500. 'onTwigExtensions' => ['onTwigExtensions', 1000],
  501. 'onPagesInitialized' => ['onPagesInitialized', 1000],
  502. 'onTwigTemplatePaths' => ['onTwigTemplatePaths', 1000],
  503. 'onTwigSiteVariables' => ['onTwigSiteVariables', 1000],
  504. 'onAssetsInitialized' => ['onAssetsInitialized', 1000],
  505. 'onAdminRegisterPermissions' => ['onAdminRegisterPermissions', 0],
  506. 'onOutputGenerated' => ['onOutputGenerated', 0],
  507. 'onAdminAfterSave' => ['onAdminAfterSave', 0],
  508. ]);
  509. // Autoload classes
  510. require_once __DIR__ . '/vendor/autoload.php';
  511. // Check for required plugins
  512. if (!$this->grav['config']->get('plugins.login.enabled') || !$this->grav['config']->get('plugins.form.enabled') || !$this->grav['config']->get('plugins.email.enabled')) {
  513. throw new \RuntimeException('One of the required plugins is missing or not enabled');
  514. }
  515. // Initialize Admin Language if needed
  516. /** @var Language $language */
  517. $language = $this->grav['language'];
  518. if ($language->enabled() && empty($this->grav['session']->admin_lang)) {
  519. $this->grav['session']->admin_lang = $language->getLanguage();
  520. }
  521. // Decide admin template and route.
  522. $path = trim(substr($this->uri->route(), strlen($this->base)), '/');
  523. if (empty($this->template)) {
  524. $this->template = 'dashboard';
  525. }
  526. // Can't access path directly...
  527. if ($path && $path !== 'register') {
  528. $array = explode('/', $path, 2);
  529. $this->template = array_shift($array);
  530. $this->route = array_shift($array);
  531. }
  532. // Initialize admin class.
  533. $this->admin = new Admin($this->grav, $this->admin_route, $this->template, $this->route);
  534. // And store the class into DI container.
  535. $this->grav['admin'] = $this->admin;
  536. // Double check we have system.yaml, site.yaml etc
  537. $config_path = $this->grav['locator']->findResource('user://config');
  538. foreach ($this->admin->configurations() as $config_file) {
  539. $config_file = "{$config_path}/{$config_file}.yaml";
  540. if (!file_exists($config_file)) {
  541. touch($config_file);
  542. }
  543. }
  544. // Get theme for admin
  545. $this->theme = $this->config->get('plugins.admin.theme', 'grav');
  546. $assets = $this->grav['assets'];
  547. $translations = 'this.GravAdmin = this.GravAdmin || {}; if (!this.GravAdmin.translations) this.GravAdmin.translations = {}; ' . PHP_EOL . 'this.GravAdmin.translations.PLUGIN_ADMIN = {';
  548. // Enable language translations
  549. $translations_actual_state = $this->config->get('system.languages.translations');
  550. $this->config->set('system.languages.translations', true);
  551. $strings = [
  552. 'EVERYTHING_UP_TO_DATE',
  553. 'UPDATES_ARE_AVAILABLE',
  554. 'IS_AVAILABLE_FOR_UPDATE',
  555. 'AND',
  556. 'IS_NOW_AVAILABLE',
  557. 'CURRENT',
  558. 'UPDATE_GRAV_NOW',
  559. 'TASK_COMPLETED',
  560. 'UPDATE',
  561. 'UPDATING_PLEASE_WAIT',
  562. 'GRAV_SYMBOLICALLY_LINKED',
  563. 'OF_YOUR',
  564. 'OF_THIS',
  565. 'HAVE_AN_UPDATE_AVAILABLE',
  566. 'UPDATE_AVAILABLE',
  567. 'UPDATES_AVAILABLE',
  568. 'FULLY_UPDATED',
  569. 'DAYS',
  570. 'PAGE_MODES',
  571. 'PAGE_TYPES',
  572. 'ACCESS_LEVELS',
  573. 'NOTHING_TO_SAVE',
  574. 'FILE_UNSUPPORTED',
  575. 'FILE_ERROR_ADD',
  576. 'FILE_ERROR_UPLOAD',
  577. 'DROP_FILES_HERE_TO_UPLOAD',
  578. 'DELETE',
  579. 'UNSET',
  580. 'INSERT',
  581. 'METADATA',
  582. 'VIEW',
  583. 'UNDO',
  584. 'REDO',
  585. 'HEADERS',
  586. 'BOLD',
  587. 'ITALIC',
  588. 'STRIKETHROUGH',
  589. 'SUMMARY_DELIMITER',
  590. 'LINK',
  591. 'IMAGE',
  592. 'BLOCKQUOTE',
  593. 'UNORDERED_LIST',
  594. 'ORDERED_LIST',
  595. 'EDITOR',
  596. 'PREVIEW',
  597. 'FULLSCREEN',
  598. 'MODULAR',
  599. 'NON_MODULAR',
  600. 'VISIBLE',
  601. 'NON_VISIBLE',
  602. 'ROUTABLE',
  603. 'NON_ROUTABLE',
  604. 'PUBLISHED',
  605. 'NON_PUBLISHED',
  606. 'PLUGINS',
  607. 'THEMES',
  608. 'ALL',
  609. 'FROM',
  610. 'TO',
  611. 'DROPZONE_CANCEL_UPLOAD',
  612. 'DROPZONE_CANCEL_UPLOAD_CONFIRMATION',
  613. 'DROPZONE_DEFAULT_MESSAGE',
  614. 'DROPZONE_FALLBACK_MESSAGE',
  615. 'DROPZONE_FALLBACK_TEXT',
  616. 'DROPZONE_FILE_TOO_BIG',
  617. 'DROPZONE_INVALID_FILE_TYPE',
  618. 'DROPZONE_MAX_FILES_EXCEEDED',
  619. 'DROPZONE_REMOVE_FILE',
  620. 'DROPZONE_RESPONSE_ERROR'
  621. ];
  622. foreach ($strings as $string) {
  623. $separator = (end($strings) === $string) ? '' : ',';
  624. $translations .= '"' . $string . '": "' . htmlspecialchars($this->admin->translate('PLUGIN_ADMIN.' . $string)) . '"' . $separator;
  625. }
  626. $translations .= '};';
  627. $translations .= 'this.GravAdmin.translations.PLUGIN_FORM = {';
  628. $strings = ['RESOLUTION_MIN', 'RESOLUTION_MAX'];
  629. foreach ($strings as $string) {
  630. $separator = (end($strings) === $string) ? '' : ',';
  631. $translations .= '"' . $string . '": "' . $this->admin->translate('PLUGIN_FORM.' . $string) . '"' . $separator;
  632. }
  633. $translations .= '};';
  634. // set the actual translations state back
  635. $this->config->set('system.languages.translations', $translations_actual_state);
  636. $assets->addInlineJs($translations);
  637. }
  638. /**
  639. * Add the Admin Twig Extensions
  640. */
  641. public function onTwigExtensions()
  642. {
  643. require_once __DIR__ . '/classes/Twig/AdminTwigExtension.php';
  644. $this->grav['twig']->twig->addExtension(new AdminTwigExtension);
  645. }
  646. /**
  647. * Check if the current route is under the admin path
  648. *
  649. * @return bool
  650. */
  651. public function isAdminPath()
  652. {
  653. $route = $this->uri->route();
  654. return $route === $this->base || 0 === strpos($route, $this->base . '/');
  655. }
  656. public function onAdminAfterSave(Event $event)
  657. {
  658. // Special case to redirect after changing the admin route to avoid 'breaking'
  659. $obj = $event['object'];
  660. if (null !== $obj && method_exists($obj, 'blueprints')) {
  661. $blueprint = $obj->blueprints()->getFilename();
  662. if ($blueprint === 'admin/blueprints' && isset($obj->route) && $this->admin_route !== $obj->route) {
  663. $redirect = preg_replace('/^' . str_replace('/','\/',$this->admin_route) . '/',$obj->route,$this->uri->path());
  664. $this->grav->redirect($redirect);
  665. }
  666. }
  667. }
  668. /**
  669. * Provide the tools for the Tools page, currently only direct install
  670. *
  671. * @return Event
  672. */
  673. public function onAdminTools(Event $event)
  674. {
  675. $event['tools'] = array_merge($event['tools'], [$this->grav['language']->translate('PLUGIN_ADMIN.DIRECT_INSTALL')]);
  676. return $event;
  677. }
  678. public function onAdminDashboard()
  679. {
  680. $this->grav['twig']->plugins_hooked_dashboard_widgets_top[] = ['template' => 'dashboard-maintenance'];
  681. $this->grav['twig']->plugins_hooked_dashboard_widgets_top[] = ['template' => 'dashboard-statistics'];
  682. $this->grav['twig']->plugins_hooked_dashboard_widgets_top[] = ['template' => 'dashboard-notifications'];
  683. $this->grav['twig']->plugins_hooked_dashboard_widgets_top[] = ['template' => 'dashboard-feed'];
  684. $this->grav['twig']->plugins_hooked_dashboard_widgets_main[] = ['template' => 'dashboard-pages'];
  685. }
  686. public function onOutputGenerated()
  687. {
  688. // Clear flash objects for previously uploaded files
  689. // whenever the user switches page / reloads
  690. // ignoring any JSON / extension call
  691. if ($this->admin->task !== 'save' && empty($this->uri->extension())) {
  692. // Discard any previously uploaded files session.
  693. // and if there were any uploaded file, remove them from the filesystem
  694. if ($flash = $this->session->getFlashObject('files-upload')) {
  695. $flash = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($flash));
  696. foreach ($flash as $key => $value) {
  697. if ($key !== 'tmp_name') {
  698. continue;
  699. }
  700. @unlink($value);
  701. }
  702. }
  703. }
  704. }
  705. /**
  706. * Initial stab at registering permissions (WIP)
  707. *
  708. * @param Event $e
  709. */
  710. public function onAdminRegisterPermissions(Event $e)
  711. {
  712. $admin = $e['admin'];
  713. $permissions = [
  714. 'admin.super' => 'boolean',
  715. 'admin.login' => 'boolean',
  716. 'admin.cache' => 'boolean',
  717. 'admin.configuration' => 'boolean',
  718. 'admin.configuration_system' => 'boolean',
  719. 'admin.configuration_site' => 'boolean',
  720. 'admin.configuration_media' => 'boolean',
  721. 'admin.configuration_info' => 'boolean',
  722. 'admin.settings' => 'boolean',
  723. 'admin.pages' => 'boolean',
  724. 'admin.maintenance' => 'boolean',
  725. 'admin.statistics' => 'boolean',
  726. 'admin.plugins' => 'boolean',
  727. 'admin.themes' => 'boolean',
  728. 'admin.users' => 'boolean',
  729. ];
  730. $admin->addPermissions($permissions);
  731. }
  732. /**
  733. * Helper function to replace Pages::Types()
  734. * and to provide an event to manipulate the data
  735. *
  736. * Dispatches 'onAdminPageTypes' event
  737. * with 'types' data member which is a
  738. * reference to the data
  739. */
  740. public static function pagesTypes()
  741. {
  742. $types = Pages::types();
  743. // First filter by configuration
  744. $hideTypes = Grav::instance()['config']->get('plugins.admin.hide_page_types', []);
  745. foreach ((array) $hideTypes as $type) {
  746. unset($types[$type]);
  747. }
  748. // Allow manipulating of the data by event
  749. $e = new Event(['types' => &$types]);
  750. Grav::instance()->fireEvent('onAdminPageTypes', $e);
  751. return $types;
  752. }
  753. /**
  754. * Helper function to replace Pages::modularTypes()
  755. * and to provide an event to manipulate the data
  756. *
  757. * Dispatches 'onAdminModularPageTypes' event
  758. * with 'types' data member which is a
  759. * reference to the data
  760. */
  761. public static function pagesModularTypes()
  762. {
  763. $types = Pages::modularTypes();
  764. // First filter by configuration
  765. $hideTypes = (array) Grav::instance()['config']->get('plugins.admin.hide_modular_page_types', []);
  766. foreach ($hideTypes as $type) {
  767. unset($types[$type]);
  768. }
  769. // Allow manipulating of the data by event
  770. $e = new Event(['types' => &$types]);
  771. Grav::instance()->fireEvent('onAdminModularPageTypes', $e);
  772. return $types;
  773. }
  774. }