admin.php 29 KB

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