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