admin.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. <?php
  2. namespace Grav\Plugin;
  3. use Grav\Common\GPM\GPM;
  4. use Grav\Common\Grav;
  5. use Grav\Common\Language\Language;
  6. use Grav\Common\Page\Page;
  7. use Grav\Common\Page\Pages;
  8. use Grav\Common\Plugin;
  9. use Grav\Common\Uri;
  10. use RocketTheme\Toolbox\File\File;
  11. use RocketTheme\Toolbox\Event\Event;
  12. use RocketTheme\Toolbox\Session\Session;
  13. class AdminPlugin extends Plugin
  14. {
  15. /**
  16. * @var bool
  17. */
  18. protected $active = false;
  19. /**
  20. * @var string
  21. */
  22. protected $template;
  23. /**
  24. * @var string
  25. */
  26. protected $theme;
  27. /**
  28. * @var string
  29. */
  30. protected $route;
  31. /**
  32. * @var Uri
  33. */
  34. protected $uri;
  35. /**
  36. * @var Admin
  37. */
  38. protected $admin;
  39. /**
  40. * @var Session
  41. */
  42. protected $session;
  43. /**
  44. * @var Popularity
  45. */
  46. protected $popularity;
  47. /**
  48. * @var string
  49. */
  50. protected $base;
  51. /**
  52. * @return array
  53. */
  54. public static function getSubscribedEvents()
  55. {
  56. return [
  57. 'onPluginsInitialized' => [['login', 100000], ['onPluginsInitialized', 1000]],
  58. 'onShutdown' => ['onShutdown', 1000]
  59. ];
  60. }
  61. /**
  62. * If the admin path matches, initialize the Login plugin configuration and set the admin
  63. * as active.
  64. */
  65. public function login()
  66. {
  67. // Check for Pro version is enabled
  68. if ($this->config->get('plugins.admin-pro.enabled')) {
  69. $this->active = false;
  70. return;
  71. }
  72. $route = $this->config->get('plugins.admin.route');
  73. if (!$route) {
  74. return;
  75. }
  76. $this->grav['debugger']->addMessage("Admin Basic");
  77. $this->base = '/' . trim($route, '/');
  78. $this->uri = $this->grav['uri'];
  79. // Only activate admin if we're inside the admin path.
  80. if ($this->uri->route() == $this->base ||
  81. substr($this->uri->route(), 0, strlen($this->base) + 1) == $this->base . '/') {
  82. $this->active = true;
  83. }
  84. }
  85. /**
  86. * If the admin plugin is set as active, initialize the admin
  87. */
  88. public function onPluginsInitialized()
  89. {
  90. // Only activate admin if we're inside the admin path.
  91. if ($this->active) {
  92. $this->initializeAdmin();
  93. // Disable Asset pipelining
  94. $this->config->set('system.assets.css_pipeline', false);
  95. $this->config->set('system.assets.js_pipeline', false);
  96. }
  97. // We need popularity no matter what
  98. require_once __DIR__ . '/classes/popularity.php';
  99. $this->popularity = new Popularity();
  100. }
  101. /**
  102. * Sets longer path to the home page allowing us to have list of pages when we enter to pages section.
  103. */
  104. public function onPagesInitialized()
  105. {
  106. $this->session = $this->grav['session'];
  107. // Set original route for the home page.
  108. $home = '/' . trim($this->config->get('system.home.alias'), '/');
  109. // set the default if not set before
  110. $this->session->expert = $this->session->expert ?: false;
  111. // set session variable if it's passed via the url
  112. if ($this->uri->param('mode') == 'expert') {
  113. $this->session->expert = true;
  114. } elseif ($this->uri->param('mode') == 'normal') {
  115. $this->session->expert = false;
  116. }
  117. // check for existence of a user account
  118. $account_dir = $file_path = $this->grav['locator']->findResource('account://');
  119. $user_check = (array) glob($account_dir . '/*.yaml');
  120. if (!count($user_check) > 0) {
  121. $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.NO_USER_ACCOUNTS'), 'info');
  122. }
  123. /** @var Pages $pages */
  124. $pages = $this->grav['pages'];
  125. $this->grav['admin']->routes = $pages->routes();
  126. // Remove default route from routes.
  127. if (isset($this->grav['admin']->routes['/'])) {
  128. unset($this->grav['admin']->routes['/']);
  129. }
  130. $page = $pages->dispatch('/', true);
  131. // If page is null, the default page does not exist, and we cannot route to it
  132. if ($page) {
  133. $page->route($home);
  134. }
  135. // Make local copy of POST.
  136. $post = !empty($_POST) ? $_POST : array();
  137. // Handle tasks.
  138. $this->admin->task = $task = !empty($post['task']) ? $post['task'] : $this->uri->param('task');
  139. if ($task) {
  140. require_once __DIR__ . '/classes/controller.php';
  141. $controller = new AdminController($this->grav, $this->template, $task, $this->route, $post);
  142. $controller->execute();
  143. $controller->redirect();
  144. } elseif ($this->template == 'logs' && $this->route) {
  145. // Display RAW error message.
  146. echo $this->admin->logEntry();
  147. exit();
  148. }
  149. $self = $this;
  150. // Replace page service with admin.
  151. $this->grav['page'] = function () use ($self) {
  152. $page = new Page;
  153. if (file_exists(__DIR__ . "/pages/admin/{$self->template}.md")) {
  154. $page->init(new \SplFileInfo(__DIR__ . "/pages/admin/{$self->template}.md"));
  155. $page->slug(basename($self->template));
  156. return $page;
  157. }
  158. // If the page cannot be found, try looking in plugins.
  159. // Allows pages added by plugins in admin
  160. $plugins = Grav::instance()['config']->get('plugins', []);
  161. foreach($plugins as $plugin => $data) {
  162. $path = $this->grav['locator']->findResource(
  163. "user://plugins/{$plugin}/admin/pages/{$self->template}.md");
  164. if (file_exists($path)) {
  165. $page->init(new \SplFileInfo($path));
  166. $page->slug(basename($self->template));
  167. return $page;
  168. }
  169. }
  170. };
  171. }
  172. /**
  173. * Add twig paths to plugin templates.
  174. */
  175. public function onTwigTemplatePaths()
  176. {
  177. $twig_paths = [];
  178. $this->grav->fireEvent('onAdminTwigTemplatePaths', new Event(['paths' => &$twig_paths]));
  179. $twig_paths[] = __DIR__ . '/themes/' . $this->theme . '/templates';
  180. $this->grav['twig']->twig_paths = $twig_paths;
  181. }
  182. /**
  183. * Set all twig variables for generating output.
  184. */
  185. public function onTwigSiteVariables()
  186. {
  187. $twig = $this->grav['twig'];
  188. // Dynamic type support
  189. $format = $this->uri->extension();
  190. $ext = '.' . ($format ? $format : 'html') . TWIG_EXT;
  191. $twig->twig_vars['location'] = $this->template;
  192. $twig->twig_vars['base_url_relative_frontend'] = $twig->twig_vars['base_url_relative'] ?: '/';
  193. $twig->twig_vars['admin_route'] = trim($this->config->get('plugins.admin.route'), '/');
  194. $twig->twig_vars['base_url_relative'] =
  195. $twig->twig_vars['base_url_simple'] . '/' . $twig->twig_vars['admin_route'];
  196. $twig->twig_vars['theme_url'] = '/user/plugins/admin/themes/' . $this->theme;
  197. $twig->twig_vars['base_url'] = $twig->twig_vars['base_url_relative'];
  198. $twig->twig_vars['base_path'] = GRAV_ROOT;
  199. $twig->twig_vars['admin'] = $this->admin;
  200. // Gather Plugin-hooked nav items
  201. $this->grav->fireEvent('onAdminMenu');
  202. // DEPRECATED
  203. $this->grav->fireEvent('onAdminTemplateNavPluginHook');
  204. switch ($this->template) {
  205. case 'dashboard':
  206. $twig->twig_vars['popularity'] = $this->popularity;
  207. break;
  208. case 'pages':
  209. $page = $this->admin->page(true);
  210. if ($page != null) {
  211. $twig->twig_vars['file'] = File::instance($page->filePath());
  212. $twig->twig_vars['media_types'] = str_replace('defaults,', '',
  213. implode(',.', array_keys($this->config->get('media'))));
  214. }
  215. break;
  216. }
  217. }
  218. public function onShutdown()
  219. {
  220. // Just so we know that we're in this debug mode
  221. if ($this->config->get('plugins.admin.popularity.enabled')) {
  222. // Only track non-admin
  223. if (!$this->active) {
  224. $this->popularity->trackHit();
  225. }
  226. }
  227. }
  228. /**
  229. * Handles getting GPM updates
  230. */
  231. public function onTaskGPM()
  232. {
  233. $action = $_POST['action']; // getUpdatable | getUpdatablePlugins | getUpdatableThemes | gravUpdates
  234. $flush = isset($_POST['flush']) && $_POST['flush'] == true ? true : false;
  235. if (isset($this->grav['session'])) {
  236. $this->grav['session']->close();
  237. }
  238. try {
  239. $gpm = new GPM($flush);
  240. switch ($action) {
  241. case 'getUpdates':
  242. $resources_updates = $gpm->getUpdatable();
  243. $grav_updates = [
  244. "isUpdatable" => $gpm->grav->isUpdatable(),
  245. "assets" => $gpm->grav->getAssets(),
  246. "version" => GRAV_VERSION,
  247. "available" => $gpm->grav->getVersion(),
  248. "date" => $gpm->grav->getDate(),
  249. "isSymlink" => $gpm->grav->isSymlink()
  250. ];
  251. echo json_encode([
  252. "status" => "success",
  253. "payload" => ["resources" => $resources_updates, "grav" => $grav_updates, "installed" => $gpm->countInstalled(), 'flushed' => $flush]
  254. ]);
  255. break;
  256. }
  257. } catch (\Exception $e) {
  258. echo json_encode(["status" => "error", "message" => $e->getMessage()]);
  259. }
  260. exit;
  261. }
  262. /**
  263. * Initialize the admin.
  264. *
  265. * @throws \RuntimeException
  266. */
  267. protected function initializeAdmin()
  268. {
  269. $this->enable([
  270. 'onTwigExtensions' => ['onTwigExtensions', 1000],
  271. 'onPagesInitialized' => ['onPagesInitialized', 1000],
  272. 'onTwigTemplatePaths' => ['onTwigTemplatePaths', 1000],
  273. 'onTwigSiteVariables' => ['onTwigSiteVariables', 1000],
  274. 'onTask.GPM' => ['onTaskGPM', 0]
  275. ]);
  276. // Check for required plugins
  277. if (!$this->grav['config']->get('plugins.login.enabled') ||
  278. !$this->grav['config']->get('plugins.form.enabled') ||
  279. !$this->grav['config']->get('plugins.email.enabled')) {
  280. throw new \RuntimeException('One of the required plugins is missing or not enabled');
  281. }
  282. // Double check we have system.yaml and site.yaml
  283. $config_files[] = $this->grav['locator']->findResource('user://config') . '/system.yaml';
  284. $config_files[] = $this->grav['locator']->findResource('user://config') . '/site.yaml';
  285. foreach ($config_files as $config_file) {
  286. if (!file_exists($config_file)) {
  287. touch($config_file);
  288. }
  289. }
  290. // Decide admin template and route.
  291. $path = trim(substr($this->uri->route(), strlen($this->base)), '/');
  292. $this->template = 'dashboard';
  293. if ($path) {
  294. $array = explode('/', $path, 2);
  295. $this->template = array_shift($array);
  296. $this->route = array_shift($array);
  297. }
  298. /** @var Language $language */
  299. // $require_language = ['pages', 'translations'];
  300. // $language = $this->grav['language'];
  301. // if ($language->isLanguageInUrl() && !in_array($this->template, $require_language)) {
  302. // $this->grav->redirect($this->uri->route());
  303. // }
  304. // Initialize admin class.
  305. require_once __DIR__ . '/classes/admin.php';
  306. $this->admin = new Admin($this->grav, $this->base, $this->template, $this->route);
  307. // And store the class into DI container.
  308. $this->grav['admin'] = $this->admin;
  309. // Get theme for admin
  310. $this->theme = $this->config->get('plugins.admin.theme', 'grav');
  311. $assets = $this->grav['assets'];
  312. $translations = 'if (!window.translations) window.translations = {}; ' . PHP_EOL . 'window.translations.PLUGIN_ADMIN = {};' . PHP_EOL;
  313. $strings = ['EVERYTHING_UP_TO_DATE',
  314. 'UPDATES_ARE_AVAILABLE',
  315. 'IS_AVAILABLE_FOR_UPDATE',
  316. 'AND',
  317. 'IS_NOW_AVAILABLE',
  318. 'CURRENT',
  319. 'UPDATE_GRAV_NOW',
  320. 'TASK_COMPLETED',
  321. 'UPDATE',
  322. 'UPDATING_PLEASE_WAIT',
  323. 'GRAV_SYMBOLICALLY_LINKED',
  324. 'OF_YOUR',
  325. 'OF_THIS',
  326. 'HAVE_AN_UPDATE_AVAILABLE',
  327. 'UPDATE_AVAILABLE',
  328. 'UPDATES_AVAILABLE',
  329. 'FULLY_UPDATED',
  330. 'DAYS'];
  331. foreach($strings as $string) {
  332. $translations .= 'translations.PLUGIN_ADMIN.' . $string .' = "' . $this->admin->translate('PLUGIN_ADMIN.' . $string) . '"; ' . PHP_EOL;;
  333. }
  334. $assets->addInlineJs($translations);
  335. }
  336. /**
  337. * Add Twig Extensions
  338. */
  339. public function onTwigExtensions()
  340. {
  341. require_once(__DIR__.'/twig/AdminTwigExtension.php');
  342. $this->grav['twig']->twig->addExtension(new AdminTwigExtension());
  343. }
  344. }