admin.php 29 KB

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