/**
  * Initialize a maintenance page
  */
 public function onPageInitialized()
 {
     $user = $this->grav['user'];
     $user->authorise($this->maintenance['login_access']);
     if ($this->maintenance['active']) {
         if (!$user->authenticated) {
             /** @var $page */
             $page = null;
             /** @var Pages $pages */
             $pages = $this->grav['pages'];
             // Get the custom page route if specified
             $custom_page_route = $this->config->get('plugins.maintenance.maintenance_page_route');
             if ($custom_page_route) {
                 // Try to load user error page.
                 $page = $pages->dispatch($custom_page_route, true);
             }
             // If no page found yet, use the built-in one...
             if (!$page) {
                 $page = new Page();
                 $page->init(new \SplFileInfo(__DIR__ . "/pages/maintenance.md"));
             }
             // unset the old page, and use the new one
             unset($this->grav['page']);
             $this->grav['page'] = $page;
         }
     }
 }
Пример #2
0
 /**
  * Replaces page object with admin one.
  */
 public function onPagesInitialized()
 {
     // Create admin page.
     $page = new Page();
     $page->init(new \SplFileInfo(__DIR__ . "/pages/gantry5.md"));
     $page->slug($this->template);
     $this->grav['page'] = $page;
 }
Пример #3
0
 /**
  * Create search result page.
  */
 public function onPageInitialized()
 {
     $page = new Page();
     $page->init(new \SplFileInfo(__DIR__ . '/pages/simplesearch.md'));
     // override the template is set in the config
     $template_override = $this->config->get('plugins.simplesearch.template');
     if ($template_override) {
         $page->template($template_override);
     }
     $this->grav['page'] = $page;
 }
Пример #4
0
 public function testAddPage()
 {
     /** @var UniformResourceLocator $locator */
     $locator = $this->grav['locator'];
     $path = $locator->findResource('tests://') . '/fake/single-pages/01.simple-page/default.md';
     $aPage = new Page();
     $aPage->init(new \SplFileInfo($path));
     $this->pages->addPage($aPage, '/new-page');
     $this->assertTrue(in_array('/new-page', array_keys($this->pages->routes())));
     $this->assertSame($locator->findResource('tests://') . '/fake/single-pages/01.simple-page', $this->pages->routes()['/new-page']);
 }
Пример #5
0
 /**
  * Display error page if no page was found for the current route.
  *
  * @param Event $event
  */
 public function onPageNotFound(Event $event)
 {
     /** @var Pages $pages */
     $pages = $this->grav['pages'];
     // Try to load user error page.
     $page = $pages->dispatch($this->config->get('plugins.error.routes.404', '/error'), true);
     if (!$page) {
         // If none provided use built in error page.
         $page = new Page();
         $page->init(new \SplFileInfo(__DIR__ . '/pages/error.md'));
     }
     $event->page = $page;
     $event->stopPropagation();
 }
Пример #6
0
 /**
  * Save the current page in a different language. Automatically switches to that language.
  *
  * @return bool True if the action was performed.
  */
 protected function taskSaveas()
 {
     if (!$this->authorizeTask('save', $this->dataPermissions())) {
         return false;
     }
     $data = (array) $this->data;
     $language = $data['lang'];
     if ($language) {
         $this->grav['session']->admin_lang = $language ?: 'en';
     }
     $uri = $this->grav['uri'];
     $obj = $this->admin->page($uri->route());
     $this->preparePage($obj, false, $language);
     $file = $obj->file();
     if ($file) {
         $filename = $this->determineFilenameIncludingLanguage($obj->name(), $language);
         $path = $obj->path() . DS . $filename;
         $aFile = File::instance($path);
         $aFile->save();
         $aPage = new Page();
         $aPage->init(new \SplFileInfo($path), $language . '.md');
         $aPage->header($obj->header());
         $aPage->rawMarkdown($obj->rawMarkdown());
         $aPage->validate();
         $aPage->filter();
         $aPage->save();
         $this->grav->fireEvent('onAdminAfterSave', new Event(['page' => $obj]));
     }
     $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_SWITCHED_LANGUAGE'), 'info');
     $this->setRedirect('/' . $language . $uri->route());
     return true;
 }
Пример #7
0
 /**
  * Sets longer path to the home page allowing us to have list of pages when we enter to pages section.
  */
 public function onPagesInitialized()
 {
     $this->session = $this->grav['session'];
     // Set original route for the home page.
     $home = '/' . trim($this->config->get('system.home.alias'), '/');
     // Disable Asset pipelining
     $this->config->set('system.assets.css_pipeline', false);
     $this->config->set('system.assets.js_pipeline', false);
     // set the default if not set before
     $this->session->expert = $this->session->expert ?: false;
     // set session variable if it's passed via the url
     if ($this->uri->param('mode') == 'expert') {
         $this->session->expert = true;
     } elseif ($this->uri->param('mode') == 'normal') {
         $this->session->expert = false;
     }
     /** @var Pages $pages */
     $pages = $this->grav['pages'];
     $this->grav['admin']->routes = $pages->routes();
     // Remove default route from routes.
     if (isset($this->grav['admin']->routes['/'])) {
         unset($this->grav['admin']->routes['/']);
     }
     $page = $pages->dispatch('/', true);
     // If page is null, the default page does not exist, and we cannot route to it
     if ($page) {
         $page->route($home);
     }
     // Make local copy of POST.
     $post = !empty($_POST) ? $_POST : array();
     // Handle tasks.
     $this->admin->task = $task = !empty($post['task']) ? $post['task'] : $this->uri->param('task');
     if ($task) {
         require_once __DIR__ . '/classes/controller.php';
         $controller = new AdminController($this->grav, $this->template, $task, $this->route, $post);
         $controller->execute();
         $controller->redirect();
     } elseif ($this->template == 'logs' && $this->route) {
         // Display RAW error message.
         echo $this->admin->logEntry();
         exit;
     }
     $self = $this;
     // Replace page service with admin.
     $this->grav['page'] = function () use($self) {
         $page = new Page();
         $page->init(new \SplFileInfo(__DIR__ . "/pages/admin/{$self->template}.md"));
         $page->slug(basename($self->template));
         return $page;
     };
 }
Пример #8
0
 /**
  * Replaces page object with admin one.
  */
 public function onAdminPagesInitialized()
 {
     // Create admin page.
     $page = new Page();
     $page->init(new \SplFileInfo(__DIR__ . "/pages/gantry.md"));
     $page->slug('gantry');
     // Dispatch Gantry in output buffer.
     ob_start();
     $gantry = Gantry::instance();
     $gantry['router']->dispatch();
     $content = ob_get_clean();
     // Store response into the page.
     $page->content($content);
     // Hook page into Grav as current page.
     unset($this->grav['page']);
     $this->grav['page'] = function () use($page) {
         return $page;
     };
 }
Пример #9
0
 /**
  * Return an array with the routes of other translated languages
  * @return array the page translated languages
  */
 public function translatedLanguages()
 {
     $filename = substr($this->name, 0, -strlen($this->extension()));
     $config = self::getGrav()['config'];
     $languages = $config->get('system.languages.supported', []);
     $translatedLanguages = [];
     foreach ($languages as $language) {
         $path = $this->path . DS . $this->folder . DS . $filename . '.' . $language . '.md';
         if (file_exists($path)) {
             $aPage = new Page();
             $aPage->init(new \SplFileInfo($path), $language . '.md');
             $route = isset($aPage->header()->routes['default']) ? $aPage->header()->routes['default'] : $aPage->rawRoute();
             if (!$route) {
                 $route = $aPage->slug();
             }
             $translatedLanguages[$language] = $route;
         }
     }
     return $translatedLanguages;
 }
Пример #10
0
 /**
  * Recursive function to load & build page relationships.
  *
  * @param string $directory
  * @param Page|null $parent
  * @return Page
  * @throws \RuntimeException
  * @internal
  */
 protected function recurse($directory, Page &$parent = null)
 {
     $directory = rtrim($directory, DS);
     $page = new Page();
     /** @var Config $config */
     $config = $this->grav['config'];
     /** @var Language $language */
     $language = $this->grav['language'];
     // stuff to do at root page
     if ($parent === null) {
         // Fire event for memory and time consuming plugins...
         if ($config->get('system.pages.events.page')) {
             $this->grav->fireEvent('onBuildPagesInitialized');
         }
     }
     $page->path($directory);
     if ($parent) {
         $page->parent($parent);
     }
     $page->orderDir($config->get('system.pages.order.dir'));
     $page->orderBy($config->get('system.pages.order.by'));
     // Add into instances
     if (!isset($this->instances[$page->path()])) {
         $this->instances[$page->path()] = $page;
         if ($parent && $page->path()) {
             $this->children[$parent->path()][$page->path()] = array('slug' => $page->slug());
         }
     } else {
         throw new \RuntimeException('Fatal error when creating page instances.');
     }
     $content_exists = false;
     $pages_found = glob($directory . '/*' . CONTENT_EXT);
     $page_extensions = $language->getFallbackPageExtensions();
     if ($pages_found) {
         foreach ($page_extensions as $extension) {
             foreach ($pages_found as $found) {
                 if (preg_match('/^.*\\/[0-9A-Za-z\\-\\_]+(' . $extension . ')$/', $found)) {
                     $page_found = $found;
                     $page_extension = $extension;
                     break 2;
                 }
             }
         }
     }
     if ($parent && !empty($page_found)) {
         $file = new \SplFileInfo($page_found);
         $page->init($file, $page_extension);
         $content_exists = true;
         if ($config->get('system.pages.events.page')) {
             $this->grav->fireEvent('onPageProcessed', new Event(['page' => $page]));
         }
     }
     // set current modified of page
     $last_modified = $page->modified();
     /** @var \DirectoryIterator $file */
     foreach (new \FilesystemIterator($directory) as $file) {
         $name = $file->getFilename();
         // Ignore all hidden files if set.
         if ($this->ignore_hidden) {
             if ($name && $name[0] == '.') {
                 continue;
             }
         }
         if ($file->isFile()) {
             // Update the last modified if it's newer than already found
             if (!in_array($file->getBasename(), $this->ignore_files) && ($modified = $file->getMTime()) > $last_modified) {
                 $last_modified = $modified;
             }
         } elseif ($file->isDir() && !in_array($file->getFilename(), $this->ignore_folders)) {
             if (!$page->path()) {
                 $page->path($file->getPath());
             }
             $path = $directory . DS . $name;
             $child = $this->recurse($path, $page);
             if (Utils::startsWith($name, '_')) {
                 $child->routable(false);
             }
             $this->children[$page->path()][$child->path()] = array('slug' => $child->slug());
             if ($config->get('system.pages.events.page')) {
                 $this->grav->fireEvent('onFolderProcessed', new Event(['page' => $page]));
             }
         }
     }
     // Set routability to false if no page found
     if (!$content_exists) {
         $page->routable(false);
     }
     // Override the modified and ID so that it takes the latest change into account
     $page->modified($last_modified);
     $page->id($last_modified . md5($page->filePath()));
     // Sort based on Defaults or Page Overridden sort order
     $this->children[$page->path()] = $this->sort($page);
     return $page;
 }
Пример #11
0
 /**
  * Authorize Page
  */
 public function authorizePage()
 {
     /** @var User $user */
     $user = $this->grav['user'];
     /** @var Page $page */
     $page = $this->grav['page'];
     if (!$page) {
         return;
     }
     $header = $page->header();
     $rules = isset($header->access) ? (array) $header->access : [];
     $config = $this->mergeConfig($page);
     if ($config->get('parent_acl')) {
         // If page has no ACL rules, use its parent's rules
         if (!$rules) {
             $parent = $page->parent();
             while (!$rules and $parent) {
                 $header = $parent->header();
                 $rules = isset($header->access) ? (array) $header->access : [];
                 $parent = $parent->parent();
             }
         }
     }
     // Continue to the page if it has no ACL rules.
     if (!$rules) {
         return;
     }
     // Continue to the page if user is authorized to access the page.
     foreach ($rules as $rule => $value) {
         if ($user->authorize($rule) == $value) {
             return;
         }
     }
     // User is not logged in; redirect to login page.
     if ($this->route && !$user->authenticated) {
         $this->grav->redirect($this->route, 302);
     }
     /** @var Language $l */
     $l = $this->grav['language'];
     // Reset page with login page.
     if (!$user->authenticated) {
         $page = new Page();
         // Get the admin Login page is needed, else teh default
         if ($this->isAdmin()) {
             $login_file = $this->grav['locator']->findResource("plugins://admin/pages/admin/login.md");
             $page->init(new \SplFileInfo($login_file));
         } else {
             $page->init(new \SplFileInfo(__DIR__ . "/pages/login.md"));
         }
         $page->slug(basename($this->route));
         $this->authenticated = false;
         unset($this->grav['page']);
         $this->grav['page'] = $page;
     } else {
         $this->grav['messages']->add($l->translate('PLUGIN_LOGIN.ACCESS_DENIED'), 'info');
         $this->authenticated = false;
         $twig = $this->grav['twig'];
         $twig->twig_vars['notAuthorized'] = true;
     }
 }
Пример #12
0
 /**
  * Recursive function to load & build page relationships.
  *
  * @param string $directory
  * @param null $parent
  * @return Page
  * @throws \RuntimeException
  * @internal
  */
 protected function recurse($directory = PAGES_DIR, Page &$parent = null)
 {
     $directory = rtrim($directory, DS);
     $iterator = new \DirectoryIterator($directory);
     $page = new Page();
     $config = $this->grav['config'];
     $page->path($directory);
     if ($parent) {
         $page->parent($parent);
     }
     $page->orderDir($config->get('system.pages.order.dir'));
     $page->orderBy($config->get('system.pages.order.by'));
     // Add into instances
     if (!isset($this->instances[$page->path()])) {
         $this->instances[$page->path()] = $page;
         if ($parent && $page->path()) {
             $this->children[$parent->path()][$page->path()] = array('slug' => $page->slug());
         }
     } else {
         throw new \RuntimeException('Fatal error when creating page instances.');
     }
     $last_modified = 0;
     /** @var \DirectoryIterator $file */
     foreach ($iterator as $file) {
         $name = $file->getFilename();
         $date = $file->getMTime();
         if ($date > $last_modified) {
             $last_modified = $date;
         }
         if ($file->isFile() && Utils::endsWith($name, CONTENT_EXT)) {
             $page->init($file);
             if ($config->get('system.pages.events.page')) {
                 $this->grav->fireEvent('onPageProcessed', new Event(['page' => $page]));
             }
         } elseif ($file->isDir() && !$file->isDot()) {
             if (!$page->path()) {
                 $page->path($file->getPath());
             }
             $path = $directory . DS . $name;
             $child = $this->recurse($path, $page);
             if (Utils::startsWith($name, '_')) {
                 $child->routable(false);
             }
             $this->children[$page->path()][$child->path()] = array('slug' => $child->slug());
             // set the modified time if not already set
             if (!$page->date()) {
                 $page->date($file->getMTime());
             }
             // set the last modified time on pages
             $this->lastModified($file->getMTime());
             if ($config->get('system.pages.events.page')) {
                 $this->grav->fireEvent('onFolderProcessed', new Event(['page' => $page]));
             }
         }
     }
     // Override the modified and ID so that it takes the latest change
     // into account
     $page->modified($last_modified);
     $page->id($last_modified . md5($page->filePath()));
     // Sort based on Defaults or Page Overridden sort order
     $this->children[$page->path()] = $this->sort($page);
     return $page;
 }
 /**
  * Create search result page.
  */
 public function onPageInitialized()
 {
     $page = new Page();
     $page->init(new \SplFileInfo(__DIR__ . '/pages/simplesearch.md'));
     // override the template is set in the config
     $template_override = $this->config->get('plugins.simplesearch.template');
     if ($template_override) {
         $page->template($template_override);
     }
     // allows us to redefine the page service without triggering RuntimeException: Cannot override frozen service
     // "page" issue
     unset($this->grav['page']);
     $this->grav['page'] = $page;
 }
Пример #14
0
 /**
  * Build search results.
  */
 public function onPagesInitialized()
 {
     /** @var Taxonomy $taxonomy_map */
     $taxonomy_map = $this->grav['taxonomy'];
     $filters = (array) $this->config->get('plugins.simplesearch.filters');
     $operator = $this->config->get('plugins.simplesearch.filter_combinator', 'and');
     $this->collection = new Collection();
     $this->collection->append($taxonomy_map->findTaxonomy($filters, $operator)->toArray());
     $extras = [];
     /** @var Page $page */
     foreach ($this->collection as $page) {
         foreach ($this->query as $query) {
             $query = trim($query);
             if (stripos($page->content(), $query) === false && stripos($page->title(), $query) === false) {
                 $this->collection->remove($page);
                 continue;
             }
             if ($page->modular()) {
                 $this->collection->remove($page);
                 $parent = $page->parent();
                 $extras[$parent->path()] = ['slug' => $parent->slug()];
             }
         }
     }
     if (!empty($extras)) {
         $this->collection->append($extras);
     }
     // create the search page
     $page = new Page();
     $page->init(new \SplFileInfo(__DIR__ . '/pages/simplesearch.md'));
     // override the template is set in the config
     $template_override = $this->config->get('plugins.simplesearch.template');
     if ($template_override) {
         $page->template($template_override);
     }
     // allows us to redefine the page service without triggering RuntimeException: Cannot override frozen service
     // "page" issue
     unset($this->grav['page']);
     $this->grav['page'] = $page;
 }
 public function register(Container $container)
 {
     $container['page'] = function ($c) {
         /** @var Grav $c */
         /** @var Pages $pages */
         $pages = $c['pages'];
         /** @var Language $language */
         $language = $c['language'];
         /** @var Uri $uri */
         $uri = $c['uri'];
         $path = $uri->path();
         // Don't trim to support trailing slash default routes
         $path = $path ?: '/';
         $page = $pages->dispatch($path);
         // Redirection tests
         if ($page) {
             if ($c['config']->get('system.force_ssl')) {
                 if (!isset($_SERVER['HTTPS']) || $_SERVER["HTTPS"] != "on") {
                     $url = "https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
                     $c->redirect($url);
                 }
             }
             $url = $page->route();
             if ($uri->params()) {
                 if ($url == '/') {
                     //Avoid double slash
                     $url = $uri->params();
                 } else {
                     $url .= $uri->params();
                 }
             }
             if ($uri->query()) {
                 $url .= '?' . $uri->query();
             }
             if ($uri->fragment()) {
                 $url .= '#' . $uri->fragment();
             }
             // Language-specific redirection scenarios
             if ($language->enabled()) {
                 if ($language->isLanguageInUrl() && !$language->isIncludeDefaultLanguage()) {
                     $c->redirect($url);
                 }
                 if (!$language->isLanguageInUrl() && $language->isIncludeDefaultLanguage()) {
                     $c->redirectLangSafe($url);
                 }
             }
             // Default route test and redirect
             if ($c['config']->get('system.pages.redirect_default_route') && $page->route() != $path) {
                 $c->redirectLangSafe($url);
             }
         }
         // if page is not found, try some fallback stuff
         if (!$page || !$page->routable()) {
             // Try fallback URL stuff...
             $c->fallbackUrl($path);
             if (!$page) {
                 $path = $c['locator']->findResource('system://pages/notfound.md');
                 $page = new Page();
                 $page->init(new \SplFileInfo($path));
                 $page->routable(false);
             }
         }
         return $page;
     };
 }
Пример #16
0
 /**
  * Save the current page in a different language. Automatically switches to that language.
  *
  * @return bool True if the action was performed.
  */
 protected function taskSaveas()
 {
     if (!$this->authorizeTask('save', $this->dataPermissions())) {
         return;
     }
     // $reorder = false;
     $data = $this->post;
     $language = $data['lang'];
     if ($language) {
         $this->grav['session']->admin_lang = $language ?: 'en';
     }
     // /** @var Page\Pages $pages */
     $pages = $this->grav['pages'];
     $uri = $this->grav['uri'];
     $obj = $this->admin->page($uri->route());
     $this->preparePage($obj, false, $language);
     $file = $obj->file();
     if ($file) {
         $filename = substr($obj->name(), 0, -strlen('.' . $language . '.md'));
         if (substr($filename, -3, 1) == '.') {
             if (substr($filename, -2) == substr($language, 0, 2)) {
                 $filename = str_replace(substr($filename, -2), $language, $filename);
             }
         } elseif (substr($filename, -6, 1) == '.') {
             if (substr($filename, -5) == substr($language, 0, 5)) {
                 $filename = str_replace(substr($filename, -5), $language, $filename);
             }
         } else {
             $filename .= '.' . $language;
         }
         $path = $obj->path() . DS . $filename . '.md';
         $aFile = File::instance($path);
         $aFile->save();
         $aPage = new Page\Page();
         $aPage->init(new \SplFileInfo($path), $language . '.md');
         $aPage->header($obj->header());
         $aPage->rawMarkdown($obj->rawMarkdown());
         $aPage->validate();
         $aPage->filter();
         $aPage->save();
     }
     $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_SWITCHED_LANGUAGE'), 'info');
     $this->setRedirect('/' . $language . $uri->route());
     return true;
 }
Пример #17
0
 /**
  * Sets longer path to the home page allowing us to have list of pages when we enter to pages section.
  */
 public function onPagesInitialized()
 {
     $this->session = $this->grav['session'];
     // Set original route for the home page.
     $home = '/' . trim($this->config->get('system.home.alias'), '/');
     // set the default if not set before
     $this->session->expert = $this->session->expert ?: false;
     // set session variable if it's passed via the url
     if ($this->uri->param('mode') == 'expert') {
         $this->session->expert = true;
     } elseif ($this->uri->param('mode') == 'normal') {
         $this->session->expert = false;
     }
     /** @var Pages $pages */
     $pages = $this->grav['pages'];
     $this->grav['admin']->routes = $pages->routes();
     // Remove default route from routes.
     if (isset($this->grav['admin']->routes['/'])) {
         unset($this->grav['admin']->routes['/']);
     }
     $page = $pages->dispatch('/', true);
     // If page is null, the default page does not exist, and we cannot route to it
     if ($page) {
         $page->route($home);
     }
     // Make local copy of POST.
     $post = !empty($_POST) ? $_POST : [];
     // Handle tasks.
     $this->admin->task = $task = !empty($post['task']) ? $post['task'] : $this->uri->param('task');
     if ($task) {
         $this->initializeController($task, $post);
     } elseif ($this->template == 'logs' && $this->route) {
         // Display RAW error message.
         echo $this->admin->logEntry();
         exit;
     }
     // Clear flash objects for previously uploaded files
     // whenever the user switches page / reloads
     // ignoring any JSON / extension call
     if (is_null($this->uri->extension()) && $task !== 'save') {
         // Discard any previously uploaded files session.
         // and if there were any uploaded file, remove them from the filesystem
         if ($flash = $this->session->getFlashObject('files-upload')) {
             $flash = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($flash));
             foreach ($flash as $key => $value) {
                 if ($key !== 'tmp_name') {
                     continue;
                 }
                 @unlink($value);
             }
         }
     }
     $self = $this;
     // make sure page is not frozen!
     unset($this->grav['page']);
     $this->admin->pagesCount();
     // Replace page service with admin.
     $this->grav['page'] = function () use($self) {
         $page = new Page();
         // If the page cannot be found in other plugins, try looking in admin plugin itself.
         if (file_exists(__DIR__ . "/pages/admin/{$self->template}.md")) {
             $page->init(new \SplFileInfo(__DIR__ . "/pages/admin/{$self->template}.md"));
             $page->slug(basename($self->template));
             return $page;
         }
         // Allows pages added by plugins in admin
         $plugins = $this->grav['plugins'];
         $locator = $this->grav['locator'];
         foreach ($plugins as $plugin) {
             $path = $locator->findResource("user://plugins/{$plugin->name}/admin/pages/{$self->template}.md");
             if ($path) {
                 $page->init(new \SplFileInfo($path));
                 $page->slug(basename($self->template));
                 return $page;
             }
         }
         return null;
     };
     if (empty($this->grav['page'])) {
         if ($this->grav['user']->authenticated) {
             $event = $this->grav->fireEvent('onPageNotFound');
             if (isset($event->page)) {
                 unset($this->grav['page']);
                 $this->grav['page'] = $event->page;
             } else {
                 throw new \RuntimeException('Page Not Found', 404);
             }
         } else {
             $this->grav->redirect($this->admin_route);
         }
     }
     // Explicitly set a timestamp on assets
     $this->grav['assets']->setTimestamp(substr(md5(GRAV_VERSION . $this->grav['config']->checksum()), 0, 10));
 }
Пример #18
0
 /**
  * Authorize Page
  */
 public function authorizePage()
 {
     /** @var User $user */
     $user = $this->grav['user'];
     /** @var Page $page */
     $page = $this->grav['page'];
     $header = $page->header();
     $rules = isset($header->access) ? (array) $header->access : [];
     // Continue to the page if it has no ACL rules.
     if (!$rules) {
         return;
     }
     // Continue to the page if user is authorized to access the page.
     foreach ($rules as $rule => $value) {
         if ($user->authorize($rule) == $value) {
             return;
         }
     }
     // User is not logged in; redirect to login page.
     if ($this->route && !$user->authenticated) {
         $this->grav->redirect($this->route, 302);
     }
     /** @var Language $l */
     $l = $this->grav['language'];
     // Reset page with login page.
     if (!$user->authenticated) {
         $page = new Page();
         $page->init(new \SplFileInfo(__DIR__ . "/pages/login.md"));
         $page->slug(basename($this->route));
         $this->authenticated = false;
         unset($this->grav['page']);
         $this->grav['page'] = $page;
     } else {
         $this->grav['messages']->add($l->translate('LOGIN_PLUGIN.ACCESS_DENIED'), 'info');
         $this->authenticated = false;
         $twig = $this->grav['twig'];
         $twig->twig_vars['notAuthorized'] = true;
     }
 }
 /**
  * Build search results.
  */
 public function onPagesInitialized()
 {
     $page = $this->grav['page'];
     // If a page exists merge the configs
     if ($page) {
         $this->config->set('plugins.simplesearch', $this->mergeConfig($page));
     }
     /** @var Uri $uri */
     $uri = $this->grav['uri'];
     $query = $uri->param('query') ?: $uri->query('query');
     $route = $this->config->get('plugins.simplesearch.route');
     // performance check
     if ($route && $query && $route == $uri->path()) {
         $this->enable(['onTwigSiteVariables' => ['onTwigSiteVariables', 0]]);
     } else {
         return;
     }
     $this->query = explode(',', $query);
     /** @var Taxonomy $taxonomy_map */
     $taxonomy_map = $this->grav['taxonomy'];
     $taxonomies = [];
     $filters = (array) $this->config->get('plugins.simplesearch.filters');
     $operator = $this->config->get('plugins.simplesearch.filter_combinator', 'and');
     // see if the filter uses the new 'items-type' syntax
     $new_approach = false;
     foreach ($filters as $filter) {
         $filter_saved = $filter;
         if (is_array($filter)) {
             $filter = key($filter);
         }
         if (Utils::startsWith($filter, '@')) {
             if ($filter == '@self') {
                 $new_approach = true;
             }
             if ($filter == '@taxonomy') {
                 $taxonomies = $filter_saved[$filter];
             }
         }
     }
     if ($new_approach) {
         $params = $page->header()->content;
         $params['query'] = $this->config->get('plugins.simplesearch.query');
         $this->collection = $page->collection($params, false);
     } else {
         $this->collection = new Collection();
         $this->collection->append($taxonomy_map->findTaxonomy($filters, $operator)->toArray());
     }
     $extras = [];
     /** @var Page $cpage */
     foreach ($this->collection as $cpage) {
         foreach ($this->query as $query) {
             $query = trim($query);
             $taxonomy_match = false;
             if (!empty($taxonomies)) {
                 $page_taxonomies = $cpage->taxonomy();
                 foreach ((array) $taxonomies as $taxonomy) {
                     if (array_key_exists($taxonomy, $page_taxonomies)) {
                         $taxonomy_values = implode('|', $page_taxonomies[$taxonomy]);
                         if (stripos($taxonomy_values, $query) !== false) {
                             $taxonomy_match = true;
                             break;
                         }
                     }
                 }
             }
             if ($taxonomy_match === false && stripos($cpage->content(), $query) === false && stripos($cpage->title(), $query) === false) {
                 $this->collection->remove($cpage);
                 continue;
             }
             if ($cpage->modular()) {
                 $this->collection->remove($cpage);
                 $parent = $cpage->parent();
                 $extras[$parent->path()] = ['slug' => $parent->slug()];
             }
         }
     }
     if (!empty($extras)) {
         $this->collection->append($extras);
     }
     // use a configured sorting order if not already done
     if (!$new_approach) {
         $this->collection = $this->collection->order($this->config->get('plugins.simplesearch.order.by'), $this->config->get('plugins.simplesearch.order.dir'));
     }
     // if page doesn't have settings set, create a page
     if (!isset($page->header()->simplesearch)) {
         // create the search page
         $page = new Page();
         $page->init(new \SplFileInfo(__DIR__ . '/pages/simplesearch.md'));
         // override the template is set in the config
         $template_override = $this->config->get('plugins.simplesearch.template');
         if ($template_override) {
             $page->template($template_override);
         }
         // fix RuntimeException: Cannot override frozen service "page" issue
         unset($this->grav['page']);
         $this->grav['page'] = $page;
     }
 }
Пример #20
0
 /**
  * Sets longer path to the home page allowing us to have list of pages when we enter to pages section.
  */
 public function onPagesInitialized()
 {
     $this->session = $this->grav['session'];
     // Set original route for the home page.
     $home = '/' . trim($this->config->get('system.home.alias'), '/');
     // set the default if not set before
     $this->session->expert = $this->session->expert ?: false;
     // set session variable if it's passed via the url
     if ($this->uri->param('mode') == 'expert') {
         $this->session->expert = true;
     } elseif ($this->uri->param('mode') == 'normal') {
         $this->session->expert = false;
     }
     // check for existence of a user account
     $account_dir = $file_path = $this->grav['locator']->findResource('account://');
     $user_check = (array) glob($account_dir . '/*.yaml');
     if (!count($user_check) > 0) {
         $this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.NO_USER_ACCOUNTS'), 'info');
     }
     /** @var Pages $pages */
     $pages = $this->grav['pages'];
     $this->grav['admin']->routes = $pages->routes();
     // Remove default route from routes.
     if (isset($this->grav['admin']->routes['/'])) {
         unset($this->grav['admin']->routes['/']);
     }
     $page = $pages->dispatch('/', true);
     // If page is null, the default page does not exist, and we cannot route to it
     if ($page) {
         $page->route($home);
     }
     // Make local copy of POST.
     $post = !empty($_POST) ? $_POST : array();
     // Handle tasks.
     $this->admin->task = $task = !empty($post['task']) ? $post['task'] : $this->uri->param('task');
     if ($task) {
         require_once __DIR__ . '/classes/controller.php';
         $controller = new AdminController($this->grav, $this->template, $task, $this->route, $post);
         $controller->execute();
         $controller->redirect();
     } elseif ($this->template == 'logs' && $this->route) {
         // Display RAW error message.
         echo $this->admin->logEntry();
         exit;
     }
     $self = $this;
     // Replace page service with admin.
     $this->grav['page'] = function () use($self) {
         $page = new Page();
         if (file_exists(__DIR__ . "/pages/admin/{$self->template}.md")) {
             $page->init(new \SplFileInfo(__DIR__ . "/pages/admin/{$self->template}.md"));
             $page->slug(basename($self->template));
             return $page;
         }
         // If the page cannot be found, try looking in plugins.
         // Allows pages added by plugins in admin
         $plugins = Grav::instance()['config']->get('plugins', []);
         foreach ($plugins as $plugin => $data) {
             $folder = GRAV_ROOT . "/user/plugins/" . $plugin . "/admin";
             if (file_exists($folder)) {
                 $file = $folder . "/pages/{$self->template}.md";
                 if (file_exists($file)) {
                     $page->init(new \SplFileInfo($file));
                     $page->slug(basename($self->template));
                     return $page;
                 }
             }
         }
     };
 }
Пример #21
0
 /**
  * Recursive function to load & build page relationships.
  *
  * @param string $directory
  * @param Page|null $parent
  * @return Page
  * @throws \RuntimeException
  * @internal
  */
 protected function recurse($directory, Page &$parent = null)
 {
     $directory = rtrim($directory, DS);
     $iterator = new \DirectoryIterator($directory);
     $page = new Page();
     /** @var Config $config */
     $config = $this->grav['config'];
     $page->path($directory);
     if ($parent) {
         $page->parent($parent);
     }
     $page->orderDir($config->get('system.pages.order.dir'));
     $page->orderBy($config->get('system.pages.order.by'));
     // Add into instances
     if (!isset($this->instances[$page->path()])) {
         $this->instances[$page->path()] = $page;
         if ($parent && $page->path()) {
             $this->children[$parent->path()][$page->path()] = array('slug' => $page->slug());
         }
     } else {
         throw new \RuntimeException('Fatal error when creating page instances.');
     }
     // set current modified of page
     $last_modified = $page->modified();
     // flat for content availability
     $content_exists = false;
     /** @var \DirectoryIterator $file */
     foreach ($iterator as $file) {
         if ($file->isDot()) {
             continue;
         }
         $name = $file->getFilename();
         if ($file->isFile()) {
             // Update the last modified if it's newer than already found
             if ($file->getBasename() !== '.DS_Store' && ($modified = $file->getMTime()) > $last_modified) {
                 $last_modified = $modified;
             }
             if (preg_match('/^[^.].*' . CONTENT_EXT . '$/', $name)) {
                 $page->init($file);
                 $content_exists = true;
                 if ($config->get('system.pages.events.page')) {
                     $this->grav->fireEvent('onPageProcessed', new Event(['page' => $page]));
                 }
             }
         } elseif ($file->isDir()) {
             if (!$page->path()) {
                 $page->path($file->getPath());
             }
             $path = $directory . DS . $name;
             $child = $this->recurse($path, $page);
             if (Utils::startsWith($name, '_')) {
                 $child->routable(false);
             }
             $this->children[$page->path()][$child->path()] = array('slug' => $child->slug());
             if ($config->get('system.pages.events.page')) {
                 $this->grav->fireEvent('onFolderProcessed', new Event(['page' => $page]));
             }
         }
     }
     // Set routability to false if no page found
     if (!$content_exists) {
         $page->routable(false);
     }
     // Override the modified and ID so that it takes the latest change into account
     $page->modified($last_modified);
     $page->id($last_modified . md5($page->filePath()));
     // Sort based on Defaults or Page Overridden sort order
     $this->children[$page->path()] = $this->sort($page);
     return $page;
 }
Пример #22
0
 /**
  * Sets longer path to the home page allowing us to have list of pages when we enter to pages section.
  */
 public function onPagesInitialized()
 {
     $this->session = $this->grav['session'];
     // Set original route for the home page.
     $home = '/' . trim($this->config->get('system.home.alias'), '/');
     // set the default if not set before
     $this->session->expert = $this->session->expert ?: false;
     // set session variable if it's passed via the url
     if ($this->uri->param('mode') == 'expert') {
         $this->session->expert = true;
     } elseif ($this->uri->param('mode') == 'normal') {
         $this->session->expert = false;
     }
     /** @var Pages $pages */
     $pages = $this->grav['pages'];
     $this->grav['admin']->routes = $pages->routes();
     // Remove default route from routes.
     if (isset($this->grav['admin']->routes['/'])) {
         unset($this->grav['admin']->routes['/']);
     }
     $page = $pages->dispatch('/', true);
     // If page is null, the default page does not exist, and we cannot route to it
     if ($page) {
         $page->route($home);
     }
     // Make local copy of POST.
     $post = !empty($_POST) ? $_POST : array();
     // Handle tasks.
     $this->admin->task = $task = !empty($post['task']) ? $post['task'] : $this->uri->param('task');
     if ($task) {
         $this->initializeController($task, $post);
     } elseif ($this->template == 'logs' && $this->route) {
         // Display RAW error message.
         echo $this->admin->logEntry();
         exit;
     }
     $self = $this;
     // make sure page is not frozen!
     unset($this->grav['page']);
     // Replace page service with admin.
     $this->grav['page'] = function () use($self) {
         $page = new Page();
         if (file_exists(__DIR__ . "/pages/admin/{$self->template}.md")) {
             $page->init(new \SplFileInfo(__DIR__ . "/pages/admin/{$self->template}.md"));
             $page->slug(basename($self->template));
             return $page;
         }
         // If the page cannot be found, try looking in plugins.
         // Allows pages added by plugins in admin
         $plugins = Grav::instance()['config']->get('plugins', []);
         foreach ($plugins as $plugin => $data) {
             $path = $this->grav['locator']->findResource("user://plugins/{$plugin}/admin/pages/{$self->template}.md");
             if (file_exists($path)) {
                 $page->init(new \SplFileInfo($path));
                 $page->slug(basename($self->template));
                 return $page;
             }
         }
     };
     if (empty($this->grav['page'])) {
         $event = $this->grav->fireEvent('onPageNotFound');
         if (isset($event->page)) {
             unset($this->grav['page']);
             $this->grav['page'] = $event->page;
         } else {
             throw new \RuntimeException('Page Not Found', 404);
         }
     }
 }
Пример #23
0
 /**
  * Build search results.
  */
 public function onPagesInitialized()
 {
     $page = $this->grav['page'];
     // If a page exists merge the configs
     if ($page) {
         $this->config->set('plugins.simplesearch', $this->mergeConfig($page));
     }
     /** @var Uri $uri */
     $uri = $this->grav['uri'];
     $query = $uri->param('query') ?: $uri->query('query');
     $route = $this->config->get('plugins.simplesearch.route');
     // performance check for query
     if (empty($query)) {
         return;
     }
     // Support `route: '@self'` syntax
     if ($route === '@self') {
         $route = $page . route();
         $this->config->set('plugins.simplesearch.route', $route);
     }
     // performance check for route
     if (!($route && $route == $uri->path())) {
         return;
     }
     // Explode query into multiple strings
     $this->query = explode(',', $query);
     /** @var Taxonomy $taxonomy_map */
     $taxonomy_map = $this->grav['taxonomy'];
     $taxonomies = [];
     $find_taxonomy = [];
     $filters = (array) $this->config->get('plugins.simplesearch.filters');
     $operator = $this->config->get('plugins.simplesearch.filter_combinator', 'and');
     $new_approach = false;
     if (!$filters || $query === false || count($filters) == 1 && !reset($filters)) {
         /** @var \Grav\Common\Page\Pages $pages */
         $pages = $this->grav['pages'];
         $this->collection = $pages->all();
     } else {
         foreach ($filters as $key => $filter) {
             // flatten item if it's wrapped in an array
             if (is_int($key)) {
                 if (is_array($filter)) {
                     $key = key($filter);
                     $filter = $filter[$key];
                 } else {
                     $key = $filter;
                 }
             }
             // see if the filter uses the new 'items-type' syntax
             if ($key === '@self' || $key === 'self@') {
                 $new_approach = true;
             } elseif ($key === '@taxonomy' || $key === 'taxonomy@') {
                 $taxonomies = $filter === false ? false : array_merge($taxonomies, (array) $filter);
             } else {
                 $find_taxonomy[$key] = $filter;
             }
         }
         if ($new_approach) {
             $params = $page->header()->content;
             $params['query'] = $this->config->get('plugins.simplesearch.query');
             $this->collection = $page->collection($params, false);
         } else {
             $this->collection = new Collection();
             $this->collection->append($taxonomy_map->findTaxonomy($find_taxonomy, $operator)->toArray());
         }
     }
     $extras = [];
     if ($query) {
         foreach ($this->collection as $cpage) {
             foreach ($this->query as $query) {
                 $query = trim($query);
                 if ($this->notFound($query, $cpage, $taxonomies)) {
                     $this->collection->remove($cpage);
                     continue;
                 }
                 if ($cpage->modular()) {
                     $this->collection->remove($cpage);
                     $parent = $cpage->parent();
                     $extras[$parent->path()] = ['slug' => $parent->slug()];
                 }
             }
         }
     }
     if (!empty($extras)) {
         $this->collection->append($extras);
     }
     // use a configured sorting order if not already done
     if (!$new_approach) {
         $this->collection = $this->collection->order($this->config->get('plugins.simplesearch.order.by'), $this->config->get('plugins.simplesearch.order.dir'));
     }
     // if page doesn't have settings set, create a page
     if (!isset($page->header()->simplesearch)) {
         // create the search page
         $page = new Page();
         $page->init(new \SplFileInfo(__DIR__ . '/pages/simplesearch.md'));
         // override the template is set in the config
         $template_override = $this->config->get('plugins.simplesearch.template');
         if ($template_override) {
             $page->template($template_override);
         }
         // fix RuntimeException: Cannot override frozen service "page" issue
         unset($this->grav['page']);
         $this->grav['page'] = $page;
     }
 }
Пример #24
0
 protected function getLoginPage()
 {
     $loginpage = new Page();
     $loginpage->init(new \SplFileInfo(__DIR__ . '/pages/login.md'));
     unset($this->grav['page']);
     $this->grav['page'] = $loginpage;
     $this->grav['page']->header()->slug = substr($this->privateconf['routes']['login'], 1);
     if ($_SERVER['REQUEST_METHOD'] == "POST") {
         if ($this->validateFormData() === false) {
             $this->login_error = 'error';
             return;
         }
         if ($this->sendLogin() === false) {
             $this->login_error = 'fail';
             return;
         } else {
             if ($this->privateconf['private_site'] == true) {
                 $redirect_referer = $this->homepath;
             } else {
                 $redirect_referer = $_SESSION['referer_redirect'];
                 unset($_SESSION['referer_redirect']);
             }
             $this->grav->redirect($redirect_referer);
             return;
         }
     }
 }