/** * 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; } } }
/** * Create form for the given page. * * @param Page $page * @param null $name * @param null $form */ public function __construct(Page $page, $name = null, $form = null) { parent::__construct(); $this->page = $page->route(); $header = $page->header(); $this->rules = isset($header->rules) ? $header->rules : []; $this->header_data = isset($header->data) ? $header->data : []; if ($form) { $this->items = $form; } else { if (isset($header->form)) { $this->items = $header->form; // for backwards compatibility } } // Add form specific rules. if (!empty($this->items['rules']) && is_array($this->items['rules'])) { $this->rules += $this->items['rules']; } // Set form name if not set. if ($name && !is_int($name)) { $this->items['name'] = $name; } elseif (empty($this->items['name'])) { $this->items['name'] = $page->slug(); } // Set form id if not set. if (empty($this->items['id'])) { $inflector = new Inflector(); $this->items['id'] = $inflector->hyphenize($this->items['name']); } // Reset and initialize the form $this->reset(); }
/** * 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; }
private function mergeConfig(Page $page) { $defaults = (array) $this->grav['config']->get('plugins.jscomments'); if (isset($page->header()->jscomments)) { if (is_array($page->header()->jscomments)) { $this->grav['config']->set('plugins.jscomments', array_replace_recursive($defaults, $page->header()->jscomments)); } } }
/** * 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; }
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']); }
private function mergeConfig(Page $page, $params = []) { $this->config = new Data((array) $this->grav['config']->get('plugins.simple_form')); if (isset($page->header()->simple_form)) { if (is_array($page->header()->simple_form)) { $this->config = new Data(array_replace_recursive($this->config->toArray(), $page->header()->simple_form)); } else { $this->config->set('enabled', $page->header()->simple_form); } } $this->config = new Data(array_replace_recursive($this->config->toArray(), $params)); }
/** * Create form for the given page. * * @param Page $page */ public function __construct(Page $page) { $this->page = $page; $header = $page->header(); $this->rules = isset($header->rules) ? $header->rules : array(); $this->data = isset($header->data) ? $header->data : array(); $this->items = $header->form; // Set form name if not set. if (empty($this->items['name'])) { $this->items['name'] = $page->slug(); } }
/** * 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(); }
/** * Create form for the given page. * * @param Page $page */ public function __construct(Page $page) { $this->page = $page; $header = $page->header(); $this->rules = isset($header->rules) ? $header->rules : array(); $this->data = isset($header->data) ? $header->data : array(); $this->items = $header->form; // Set form name if not set. if (empty($this->items['name'])) { $this->items['name'] = $page->slug(); } $this->reset(); // Fire event self::getGrav()->fireEvent('onFormInitialized', new Event(['form' => $this])); }
/** * Takes an individual page and processes the taxonomies configured in its header. It * then adds those taxonomies to the map * * @param Page $page the page to process * @param array $page_taxonomy */ public function addTaxonomy(Page $page, $page_taxonomy = null) { if (!$page_taxonomy) { $page_taxonomy = $page->taxonomy(); } /** @var Config $config */ $config = $this->grav['config']; if ($config->get('site.taxonomies') && count($page_taxonomy) > 0) { foreach ((array) $config->get('site.taxonomies') as $taxonomy) { if (isset($page_taxonomy[$taxonomy])) { foreach ((array) $page_taxonomy[$taxonomy] as $item) { // TODO: move to pages class? $this->taxonomy_map[$taxonomy][(string) $item][$page->path()] = array('slug' => $page->slug()); } } } } }
/** * Takes an individual page and processes the taxonomies configured in its header. It * then adds those taxonomies to the map * * @param Page $page the page to process * @param array $page_taxonomy */ public function addTaxonomy(Page $page, $page_taxonomy = null) { if (!$page_taxonomy) { $page_taxonomy = $page->taxonomy(); } if (!$page->published() || empty($page_taxonomy)) { return; } /** @var Config $config */ $config = $this->grav['config']; if ($config->get('site.taxonomies')) { foreach ((array) $config->get('site.taxonomies') as $taxonomy) { if (isset($page_taxonomy[$taxonomy])) { foreach ((array) $page_taxonomy[$taxonomy] as $item) { $this->taxonomy_map[$taxonomy][(string) $item][$page->path()] = ['slug' => $page->slug()]; } } } } }
/** * Hash a given text. * * Called whenever a tag must be hashed when a function insert an * atomic element in the text stream. Passing $text to through this * function gives a unique text-token which will be reverted back when * calling unhash. * * @param string $text The text to be hashed * * @return string Return a unique text-token which will be * reverted back when calling unhash. */ protected function hash($text) { static $counter = 0; // Swap back any tag hash found in $text so we do not have to `unhash` // multiple times at the end. $text = $this->unhash($text); // Then hash the block $key = implode("A", array('shortcodes', $this->page->id(), ++$counter, 'S')); $this->hashes[$key] = $text; // String that will replace the tag return $key; }
private function addDropdown(Page $page, array $configuration) { $dropdownItems = array(); $children = $page->children(); foreach ($children as $child) { if (!$child->published()) { continue; } $dropdownItems[] = $this->addLink($child, $configuration); } $dropdown = $this->addLink($page, $configuration, 'dropdown'); $dropdown['items'] = $dropdownItems; return $dropdown; }
/** * Get Page informations * update content * save page * * @param Page Page that has to be saved * @return void - calls ajaxoutput */ public function savePage(\Grav\Common\Page\Page $page) { // get local names for some objects $input = $this->post; $user = $this->grav['user']; // Check Permissions for Save if ($user->authenticated && $user->authorize("site.editor")) { var_dump($input); // Fill content last because it also renders the output. if (isset($input['content'])) { $page->rawMarkdown((string) $input['content']); } } else { $this->json_response = ['status' => 'unauthorized', 'message' => 'You have insufficient permissions for editing. Make sure you logged in.']; return; } }
/** * Gets and Sets the parent object for this page * * @param Page $var the parent page object * @return Page|null the parent page object if it exists. */ public function parent(Page $var = null) { if ($var) { $this->parent = $var->path(); return $var; } /** @var Pages $pages */ $pages = self::getGrav()['pages']; return $pages->get($this->parent); }
/** * @param Page $page * @return mixed */ private function getFormName(Page $page) { $name = filter_input(INPUT_POST, '__form-name__'); if (!$name) { $name = $page->slug(); } return $name; }
/** * 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; }
/** * 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; }
/** * Add a single page to a collection * * @param Page $page * * @return $this */ public function addPage(Page $page) { $this->items[$page->path()] = ['slug' => $page->slug()]; return $this; }
/** * Merge global and page theme settings * * @param Page $page The page to merge the page theme configurations * with the theme settings. * @param bool $default The default value in case no theme setting was * found. * * @return array */ protected function mergeThemeConfig(Page $page, $default = null) { while ($page && !$page->root()) { if (isset($page->header()->theme)) { $theme = $page->header()->theme; if ($theme === '@default') { $theme = $default; } return $theme; } $page = $page->parent(); } return $default; }
/** * 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)); }
/** * 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; } }
/** * Twig process that renders a page item. It supports two variations: * 1) Handles modular pages by rendering a specific page based on its modular twig template * 2) Renders individual page items for twig processing before the site rendering * * @param Page $item The page item to render * @param string $content Optional content override * @return string The rendered output * @throws \Twig_Error_Loader */ public function processPage(Page $item, $content = null) { $content = $content !== null ? $content : $item->content(); // override the twig header vars for local resolution $this->grav->fireEvent('onTwigPageVariables'); $twig_vars = $this->twig_vars; $twig_vars['page'] = $item; $twig_vars['media'] = $item->media(); $twig_vars['header'] = $item->header(); $local_twig = clone $this->twig; $modular_twig = $item->modularTwig(); $process_twig = isset($item->header()->process['twig']) ? $item->header()->process['twig'] : false; try { // Process Modular Twig if ($modular_twig) { $twig_vars['content'] = $content; $template = $item->template() . TEMPLATE_EXT; $output = $content = $local_twig->render($template, $twig_vars); } // Process in-page Twig if (!$modular_twig || $modular_twig && $process_twig) { $name = '@Page:' . $item->path(); $this->setTemplate($name, $content); $output = $local_twig->render($name, $twig_vars); } } catch (\Twig_Error_Loader $e) { throw new \RuntimeException($e->getRawMessage(), 404, $e); } return $output; }
/** * 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; } }
/** * 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; }
/** * Returns the page creating it if it does not exist. * * @param $path * @return Page */ protected function getPage($path) { /** @var Pages $pages */ $pages = $this->grav['pages']; if ($path && $path[0] != '/') { $path = "/{$path}"; } $page = $path ? $pages->dispatch($path, true) : $pages->root(); if (!$page) { $slug = basename($path); $ppath = dirname($path); // Find or create parent(s). $parent = $this->getPage($ppath != '/' ? $ppath : ''); // Create page. $page = new Page(); $page->parent($parent); $page->filePath($parent->path() . '/' . $slug . '/' . $page->name()); // Add routing information. $pages->addPage($page, $path); // Determine page type. if (isset($this->session->{$page->route()})) { // Found the type and header from the session. $data = $this->session->{$page->route()}; $page->name($data['type'] . '.md'); $page->header(['title' => $data['title']]); $page->frontmatter(Yaml::dump((array) $page->header())); } else { // Find out the type by looking at the parent. $type = $parent->childType() ? $parent->childType() : $parent->blueprints()->get('child_type', 'default'); $page->name($type . CONTENT_EXT); $page->header(); } $page->modularTwig($slug[0] == '_'); } return $page; }
/** * Merge global and page configurations. * * @param Page $page The page to merge the configurations with the * plugin settings. * * @param bool $deep Should you use deep or shallow merging * * @return \Grav\Common\Data\Data */ protected function mergeConfig(Page $page, $deep = false) { $class_name = $this->name; $class_name_merged = $class_name . '.merged'; $defaults = $this->config->get('plugins.' . $class_name, array()); $header = array(); if (isset($page->header()->{$class_name_merged})) { $merged = $page->header()->{$class_name_merged}; if (count($merged) > 0) { return $merged; } else { return new Data($defaults); } } // Get default plugin configurations and retrieve page header configuration if (isset($page->header()->{$class_name})) { if ($deep) { $header = array_replace_recursive($defaults, $page->header()->{$class_name}); } else { $header = array_merge($defaults, $page->header()->{$class_name}); } } else { $header = $defaults; } // Create new config object and set it on the page object so it's cached for next time $config = new Data($header); $page->modifyHeader($class_name_merged, $config); // Return configurations as a new data config class return $config; }
/** * Merge global and page configurations. * * @param Page $page The page to merge the configurations with the * plugin settings. * @param bool $deep Should you use deep or shallow merging * @param array $params Array of additional configuration options to * merge with the plugin settings. * * @return \Grav\Common\Data\Data */ protected function mergeConfig(Page $page, $deep = false, $params = []) { $class_name = $this->name; $class_name_merged = $class_name . '.merged'; $defaults = $this->config->get('plugins.' . $class_name, []); $page_header = $page->header(); $header = []; if (!isset($page_header->{$class_name_merged}) && isset($page_header->{$class_name})) { // Get default plugin configurations and retrieve page header configuration $config = $page_header->{$class_name}; if (is_bool($config)) { // Overwrite enabled option with boolean value in page header $config = ['enabled' => $config]; } // Merge page header settings using deep or shallow merging technique if ($deep) { $header = array_replace_recursive($defaults, $config); } else { $header = array_merge($defaults, $config); } // Create new config object and set it on the page object so it's cached for next time $page->modifyHeader($class_name_merged, new Data($header)); } else { if (isset($page_header->{$class_name_merged})) { $merged = $page_header->{$class_name_merged}; $header = $merged->toArray(); } } if (empty($header)) { $header = $defaults; } // Merge additional parameter with configuration options if ($deep) { $header = array_replace_recursive($header, $params); } else { $header = array_merge($header, $params); } // Return configurations as a new data config class return new Data($header); }
/** * Prepare a page to be stored: update its folder, name, template, header and content * * @param \Grav\Common\Page\Page $page * @param bool $clean_header */ protected function preparePage(\Grav\Common\Page\Page $page, $clean_header = false, $language = null) { $input = $this->post; if (isset($input['order'])) { $order = max(0, (int) isset($input['order']) ? $input['order'] : $page->value('order')); $ordering = $order ? sprintf('%02d.', $order) : ''; $slug = empty($input['folder']) ? $page->value('folder') : (string) $input['folder']; $page->folder($ordering . $slug); } if (isset($input['name']) && !empty($input['name'])) { $type = (string) strtolower($input['name']); $name = preg_replace('|.*/|', '', $type); if ($language) { $name .= '.' . $language; } else { $language = $this->grav['language']; if ($language->enabled()) { $name .= '.' . $language->getLanguage(); } } $name .= '.md'; $page->name($name); $page->template($type); // unset some header things, template for now as we've just set that if (isset($input['header']['template'])) { unset($input['header']['template']); } } // Special case for Expert mode: build the raw, unset content if (isset($input['frontmatter']) && isset($input['content'])) { $page->raw("---\n" . (string) $input['frontmatter'] . "\n---\n" . (string) $input['content']); unset($input['content']); } if (isset($input['header'])) { $header = $input['header']; foreach ($header as $key => $value) { if ($key == 'metadata') { foreach ($header['metadata'] as $key2 => $value2) { if (isset($input['toggleable_header']['metadata'][$key2]) && !$input['toggleable_header']['metadata'][$key2]) { $header['metadata'][$key2] = ''; } } } elseif ($key == 'taxonomy') { foreach ($header[$key] as $taxkey => $taxonomy) { if (is_array($taxonomy) && count($taxonomy) == 1 && trim($taxonomy[0]) == '') { unset($header[$key][$taxkey]); } } } else { if (isset($input['toggleable_header'][$key]) && !$input['toggleable_header'][$key]) { $header[$key] = null; } } } if ($clean_header) { $header = Utils::arrayFilterRecursive($header, function ($k, $v) { return !(is_null($v) || $v === ''); }); } $page->header((object) $header); $page->frontmatter(Yaml::dump((array) $page->header())); } // Fill content last because it also renders the output. if (isset($input['content'])) { $page->rawMarkdown((string) $input['content']); } }