<commit_before><?php
namespace Grav\Common\Page;

use Exception;
use Grav\Common\Filesystem\Folder;
use Grav\Common\Config\Config;
use Grav\Common\GravTrait;
use Grav\Common\Language\Language;
use Grav\Common\Utils;
use Grav\Common\Cache;
use Grav\Common\Twig;
use Grav\Common\Uri;
use Grav\Common\Grav;
use Grav\Common\Taxonomy;
use Grav\Common\Markdown\Parsedown;
use Grav\Common\Markdown\ParsedownExtra;
use Grav\Common\Data\Blueprint;
use RocketTheme\Toolbox\Event\Event;
use RocketTheme\Toolbox\File\MarkdownFile;
use Symfony\Component\Yaml\Exception\ParseException;
use Symfony\Component\Yaml\Yaml;

define('PAGE_ORDER_PREFIX_REGEX', '/^[0-9]+\./u');

/**
 * The Page object, or "Page" object is the main powerhouse of Grav.  It contains all the information
 * related to the nested pages structure that represents the content. Each page has several attributes that
 * can be retrieved via public functions. Also each page can potentially contain an array of sub-pages.
 * Recursively traversing the page structure allows Grav to create navigation systems.
 *
 * @author  RocketTheme
 * @license MIT
 */
class Page
{
    use GravTrait;

    /**
     * @var string Filename. Leave as null if page is folder.
     */
    protected $name;
    protected $folder;
    protected $path;
    protected $extension;
    protected $url_extension;

    protected $id;
    protected $parent;
    protected $template;
    protected $expires;
    protected $visible;
    protected $published;
    protected $publish_date;
    protected $unpublish_date;
    protected $slug;
    protected $route;
    protected $raw_route;
    protected $url;
    protected $routes;
    protected $routable;
    protected $modified;
    protected $redirect;
    protected $items;
    protected $header;
    protected $frontmatter;
    protected $language;
    protected $content;
    protected $content_meta;
    protected $summary;
    protected $raw_content;
    protected $pagination;
    protected $media;
    protected $metadata;
    protected $title;
    protected $max_count;
    protected $menu;
    protected $date;
    protected $dateformat;
    protected $taxonomy;
    protected $order_by;
    protected $order_dir;
    protected $order_manual;
    protected $modular;
    protected $modular_twig;
    protected $process;
    protected $summary_size;
    protected $markdown_extra;
    protected $etag;
    protected $last_modified;
    protected $home_route;
    protected $hide_home_route;
    protected $ssl;

    /**
     * @var Page Unmodified (original) version of the page. Used for copying and moving the page.
     */
    private $_original;

    /**
     * @var string Action
     */
    private $_action;

    /**
     * Page Object Constructor
     *
     * @return $this
     */
    public function __construct()
    {
        /** @var Config $config */
        $config = self::getGrav()['config'];

        $this->taxonomy = [];
        $this->process = $config->get('system.pages.process');
        $this->published = true;

        return $this;
    }

    /**
     * Initializes the page instance variables based on a file
     *
     * @param  \SplFileInfo $file The file information for the .md file that the page represents
     * @param  string       $extension
     *
     * @return $this
     */
    public function init(\SplFileInfo $file, $extension = null)
    {
        $config = self::getGrav()['config'];

        $this->hide_home_route = $config->get('system.home.hide_in_urls', false);
        $this->home_route = $config->get('system.home.alias');
        $this->filePath($file->getPathName());
        $this->modified($file->getMTime());
        $this->id($this->modified() . md5($this->filePath()));
        $this->routable(true);
        $this->header();
        $this->date();
        $this->metadata();
        $this->url();
        $this->visible();
        $this->modularTwig($this->slug[0] == '_');
        $this->setPublishState();
        $this->published();
        $this->urlExtension();

        // some extension logic
        if (empty($extension)) {
            $this->extension('.' . $file->getExtension());
        } else {
            $this->extension($extension);
        }

        // extract page language from page extension
        $language = trim(basename($this->extension(), 'md'), '.') ?: null;
        $this->language($language);

        return $this;
    }

    /**
     * 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;
    }

    /**
     * Return an array listing untranslated languages available
     * @return array the page untranslated languages
     */
    public function untranslatedLanguages()
    {
        $filename = substr($this->name, 0, -(strlen($this->extension())));
        $config = self::getGrav()['config'];
        $languages = $config->get('system.languages.supported', []);
        $untranslatedLanguages = [];

        foreach ($languages as $language) {
            $path = $this->path . DS . $this->folder . DS . $filename . '.' . $language . '.md';
            if (!file_exists($path)) {
                $untranslatedLanguages[] = $language;
            }
        }

        return $untranslatedLanguages;
    }

    /**
     * Gets and Sets the raw data
     *
     * @param  string $var Raw content string
     *
     * @return Object      Raw content string
     */
    public function raw($var = null)
    {
        $file = $this->file();

        if ($var) {
            // First update file object.
            if ($file) {
                $file->raw($var);
            }

            // Reset header and content.
            $this->modified = time();
            $this->id($this->modified() . md5($this->filePath()));
            $this->header = null;
            $this->content = null;
            $this->summary = null;
        }

        return $file ? $file->raw() : '';
    }

    /**
     * Gets and Sets the page frontmatter
     *
     * @param string|null $var
     *
     * @return string
     */
    public function frontmatter($var = null)
    {

        if ($var) {
            $this->frontmatter = (string)$var;

            // Update also file object.
            $file = $this->file();
            if ($file) {
                $file->frontmatter((string)$var);
            }

            // Force content re-processing.
            $this->id(time() . md5($this->filePath()));
        }
        if (!$this->frontmatter) {
            $this->header();
        }

        return $this->frontmatter;
    }

    /**
     * Gets and Sets the header based on the YAML configuration at the top of the .md file
     *
     * @param  object|array $var a YAML object representing the configuration for the file
     *
     * @return object      the current YAML configuration
     */
    public function header($var = null)
    {
        if ($var) {
            $this->header = (object)$var;

            // Update also file object.
            $file = $this->file();
            if ($file) {
                $file->header((array)$var);
            }

            // Force content re-processing.
            $this->id(time() . md5($this->filePath()));
        }
        if (!$this->header) {
            $file = $this->file();
            if ($file) {
                // Set some options
                $file->settings(['native' => true, 'compat' => true]);
                try {
                    $this->raw_content = $file->markdown();
                    $this->frontmatter = $file->frontmatter();
                    $this->header = (object)$file->header();
                } catch (ParseException $e) {
                    $file->raw(self::getGrav()['language']->translate([
                        'FRONTMATTER_ERROR_PAGE',
                        $this->slug(),
                        $file->filename(),
                        $e->getMessage(),
                        $file->raw()
                    ]));
                    $this->raw_content = $file->markdown();
                    $this->frontmatter = $file->frontmatter();
                    $this->header = (object)$file->header();
                }
                $var = true;
            }
        }

        if ($var) {
            if (isset($this->header->slug)) {
                $this->slug = trim($this->header->slug);
            }
            if (isset($this->header->routes)) {
                $this->routes = (array)($this->header->routes);
            }
            if (isset($this->header->title)) {
                $this->title = trim($this->header->title);
            }
            if (isset($this->header->language)) {
                $this->language = trim($this->header->language);
            }
            if (isset($this->header->template)) {
                $this->template = trim($this->header->template);
            }
            if (isset($this->header->menu)) {
                $this->menu = trim($this->header->menu);
            }
            if (isset($this->header->routable)) {
                $this->routable = (bool)$this->header->routable;
            }
            if (isset($this->header->visible)) {
                $this->visible = (bool)$this->header->visible;
            }
            if (isset($this->header->redirect)) {
                $this->redirect = trim($this->header->redirect);
            }
            if (isset($this->header->order_dir)) {
                $this->order_dir = trim($this->header->order_dir);
            }
            if (isset($this->header->order_by)) {
                $this->order_by = trim($this->header->order_by);
            }
            if (isset($this->header->order_manual)) {
                $this->order_manual = (array)$this->header->order_manual;
            }
            if (isset($this->header->dateformat)) {
                $this->dateformat($this->header->dateformat);
            }
            if (isset($this->header->date)) {
                $this->date($this->header->date);
            }
            if (isset($this->header->markdown_extra)) {
                $this->markdown_extra = (bool)$this->header->markdown_extra;
            }
            if (isset($this->header->taxonomy)) {
                foreach ((array)$this->header->taxonomy as $taxonomy => $taxitems) {
                    $this->taxonomy[$taxonomy] = (array)$taxitems;
                }
            }
            if (isset($this->header->max_count)) {
                $this->max_count = intval($this->header->max_count);
            }
            if (isset($this->header->process)) {
                foreach ((array)$this->header->process as $process => $status) {
                    $this->process[$process] = (bool)$status;
                }
            }
            if (isset($this->header->published)) {
                $this->published = (bool)$this->header->published;
            }
            if (isset($this->header->publish_date)) {
                $this->publishDate($this->header->publish_date);
            }
            if (isset($this->header->unpublish_date)) {
                $this->unpublishDate($this->header->unpublish_date);
            }
            if (isset($this->header->expires)) {
                $this->expires = intval($this->header->expires);
            }
            if (isset($this->header->etag)) {
                $this->etag = (bool)$this->header->etag;
            }
            if (isset($this->header->last_modified)) {
                $this->last_modified = (bool)$this->header->last_modified;
            }
            if (isset($this->header->ssl)) {
                $this->ssl = (bool) $this->header->ssl;
            }
        }

        return $this->header;
    }

    /**
     * Get page language
     *
     * @param $var
     *
     * @return mixed
     */
    public function language($var = null)
    {
        if ($var !== null) {
            $this->language = $var;
        }

        return $this->language;
    }

    /**
     * Modify a header value directly
     *
     * @param $key
     * @param $value
     */
    public function modifyHeader($key, $value)
    {
        $this->header->{$key} = $value;
    }

    /**
     * Get the summary.
     *
     * @param  int $size Max summary size.
     *
     * @return string
     */
    public function summary($size = null)
    {
        $config = (array)self::getGrav()['config']->get('site.summary');
        if (isset($this->header->summary)) {
            $config = array_merge($config, $this->header->summary);
        }

        // Return summary based on settings in site config file
        if (!$config['enabled']) {
            return $this->content();
        }

        // Set up variables to process summary from page or from custom summary
        if ($this->summary === null) {
            $content = $this->content();
            $summary_size = $this->summary_size;
        } else {
            $content = $this->summary;
            $summary_size = mb_strlen($this->summary);
        }

        // Return calculated summary based on summary divider's position
        $format = $config['format'];
        // Return entire page content on wrong/ unknown format
        if (!in_array($format, ['short', 'long'])) {
            return $content;
        } elseif (($format === 'short') && isset($summary_size)) {
            return mb_substr($content, 0, $summary_size);
        }

        // Get summary size from site config's file
        if (is_null($size)) {
            $size = $config['size'];
        }

        // If the size is zero, return the entire page content
        if ($size === 0) {
            return $content;
            // Return calculated summary based on defaults
        } elseif (!is_numeric($size) || ($size < 0)) {
            $size = 300;
        }

        return Utils::truncateHTML($content, $size);
    }

    /**
     * Sets the summary of the page
     *
     * @param string $summary Summary
     */
    public function setSummary($summary)
    {
        $this->summary = $summary;
    }

    /**
     * Gets and Sets the content based on content portion of the .md file
     *
     * @param  string $var Content
     *
     * @return string      Content
     */
    public function content($var = null)
    {
        if ($var !== null) {
            $this->raw_content = $var;

            // Update file object.
            $file = $this->file();
            if ($file) {
                $file->markdown($var);
            }

            // Force re-processing.
            $this->id(time() . md5($this->filePath()));
            $this->content = null;
        }
        // If no content, process it
        if ($this->content === null) {
            // Get media
            $this->media();

            /** @var Config $config */
            $config = self::getGrav()['config'];

            // Load cached content
            /** @var Cache $cache */
            $cache = self::getGrav()['cache'];
            $cache_id = md5('page' . $this->id());
            $content_obj = $cache->fetch($cache_id);

            if (is_array($content_obj)) {
                $this->content = $content_obj['content'];
                $this->content_meta = $content_obj['content_meta'];
            } else {
                $this->content = $content_obj;
            }


            $process_markdown = $this->shouldProcess('markdown');
            $process_twig = $this->shouldProcess('twig');
            $cache_enable = isset($this->header->cache_enable) ? $this->header->cache_enable : $config->get('system.cache.enabled',
                true);
            $twig_first = isset($this->header->twig_first) ? $this->header->twig_first : $config->get('system.pages.twig_first',
                true);


            // if no cached-content run everything
            if ($this->content === false || $cache_enable === false) {
                $this->content = $this->raw_content;
                self::getGrav()->fireEvent('onPageContentRaw', new Event(['page' => $this]));

                if ($twig_first) {
                    if ($process_twig) {
                        $this->processTwig();
                    }
                    if ($process_markdown) {
                        $this->processMarkdown();
                    }

                    // Content Processed but not cached yet
                    self::getGrav()->fireEvent('onPageContentProcessed', new Event(['page' => $this]));

                } else {
                    if ($process_markdown) {
                        $this->processMarkdown();
                    }

                    // Content Processed but not cached yet
                    self::getGrav()->fireEvent('onPageContentProcessed', new Event(['page' => $this]));

                    if ($process_twig) {
                        $this->processTwig();
                    }
                }

                if ($cache_enable) {
                    $this->cachePageContent();
                }
            }

            // Handle summary divider
            $delimiter = $config->get('site.summary.delimiter', '===');
            $divider_pos = mb_strpos($this->content, "<p>{$delimiter}</p>");
            if ($divider_pos !== false) {
                $this->summary_size = $divider_pos;
                $this->content = str_replace("<p>{$delimiter}</p>", '', $this->content);
            }

        }

        return $this->content;
    }

    /**
     * Get the contentMeta array and initialize content first if it's not already
     *
     * @return mixed
     */
    public function contentMeta()
    {
        if ($this->content === null) {
            $this->content();
        }
        return $this->getContentMeta();
    }

    /**
     * Add an entry to the page's contentMeta array
     *
     * @param $name
     * @param $value
     */
    public function addContentMeta($name, $value)
    {
        $this->content_meta[$name] = $value;
    }

    /**
     * Return the whole contentMeta array as it currently stands
     *
     * @return mixed
     */
    public function getContentMeta()
    {
        return $this->content_meta;
    }

    /**
     * Sets the whole content meta array in one shot
     *
     * @param $content_meta
     * @return mixed
     */
    public function setContentMeta($content_meta)
    {
        return $this->content_meta = $content_meta;
    }

    /**
     * Process the Markdown content.  Uses Parsedown or Parsedown Extra depending on configuration
     */
    protected function processMarkdown()
    {
        /** @var Config $config */
        $config = self::getGrav()['config'];

        $defaults = (array)$config->get('system.pages.markdown');
        if (isset($this->header()->markdown)) {
            $defaults = array_merge($defaults, $this->header()->markdown);
        }

        // pages.markdown_extra is deprecated, but still check it...
        if (!isset($defaults['extra']) && (isset($this->markdown_extra) || $config->get('system.pages.markdown_extra') !== null)) {
            $defaults['extra'] = $this->markdown_extra ?: $config->get('system.pages.markdown_extra');
        }

        // Initialize the preferred variant of Parsedown
        if ($defaults['extra']) {
            $parsedown = new ParsedownExtra($this, $defaults);
        } else {
            $parsedown = new Parsedown($this, $defaults);
        }

        $this->content = $parsedown->text($this->content);
    }


    /**
     * Process the Twig page content.
     */
    private function processTwig()
    {
        $twig = self::getGrav()['twig'];
        $this->content = $twig->processPage($this, $this->content);
    }

    /**
     * Fires the onPageContentProcessed event, and caches the page content using a unique ID for the page
     */
    private function cachePageContent()
    {
        $cache = self::getGrav()['cache'];
        $cache_id = md5('page' . $this->id());
        $cache->save($cache_id, ['content' => $this->content, 'content_meta' => $this->content_meta]);
    }

    /**
     * Needed by the onPageContentProcessed event to get the raw page content
     *
     * @return string   the current page content
     */
    public function getRawContent()
    {
        return $this->content;
    }

    /**
     * Needed by the onPageContentProcessed event to set the raw page content
     *
     * @param $content
     */
    public function setRawContent($content)
    {
        $this->content = $content;
    }

    /**
     * Get value from a page variable (used mostly for creating edit forms).
     *
     * @param string $name Variable name.
     * @param mixed  $default
     *
     * @return mixed
     */
    public function value($name, $default = null)
    {
        if ($name == 'content') {
            return $this->raw_content;
        }
        if ($name == 'route') {
            return $this->parent()->rawRoute();
        }
        if ($name == 'order') {
            $order = $this->order();

            return $order ? (int)$this->order() : '';
        }
        if ($name == 'ordering') {
            return (bool)$this->order();
        }
        if ($name == 'folder') {
            $regex = '/^[0-9]+\./u';

            return preg_replace($regex, '', $this->folder);
        }
        if ($name == 'name') {
            $language = $this->language() ? '.' . $this->language() : '';
            $name_val = str_replace($language . '.md', '', $this->name());
            if ($this->modular()) {
                return 'modular/' . $name_val;
            }

            return $name_val;
        }
        if ($name == 'media') {
            return $this->media()->all();
        }
        if ($name == 'media.file') {
            return $this->media()->files();
        }
        if ($name == 'media.video') {
            return $this->media()->videos();
        }
        if ($name == 'media.image') {
            return $this->media()->images();
        }
        if ($name == 'media.audio') {
            return $this->media()->audios();
        }

        $path = explode('.', $name);
        $scope = array_shift($path);

        if ($name == 'frontmatter') {
            return $this->frontmatter;
        }

        if ($scope == 'header') {
            $current = $this->header();
            foreach ($path as $field) {
                if (is_object($current) && isset($current->{$field})) {
                    $current = $current->{$field};
                } elseif (is_array($current) && isset($current[$field])) {
                    $current = $current[$field];
                } else {
                    return $default;
                }
            }

            return $current;
        }

        return $default;
    }

    /**
     * Gets and Sets the Page raw content
     *
     * @param null $var
     *
     * @return null
     */
    public function rawMarkdown($var = null)
    {
        if ($var !== null) {
            $this->raw_content = $var;
        }

        return $this->raw_content;
    }

    /**
     * Get file object to the page.
     *
     * @return MarkdownFile|null
     */
    public function file()
    {
        if ($this->name) {
            return MarkdownFile::instance($this->filePath());
        }

        return null;
    }

    /**
     * Save page if there's a file assigned to it.
     *
     * @param bool $reorder Internal use.
     */
    public function save($reorder = true)
    {
        // Perform move, copy or reordering if needed.
        $this->doRelocation($reorder);

        $file = $this->file();
        if ($file) {
            $file->filename($this->filePath());
            $file->header((array)$this->header());
            $file->markdown($this->raw_content);
            $file->save();
        }
    }

    /**
     * Prepare move page to new location. Moves also everything that's under the current page.
     *
     * You need to call $this->save() in order to perform the move.
     *
     * @param Page $parent New parent page.
     *
     * @return $this
     */
    public function move(Page $parent)
    {
        if (!$this->_original) {
            $clone = clone $this;
            $this->_original = $clone;
        }

        $this->_action = 'move';
        $this->parent($parent);
        $this->id(time() . md5($this->filePath()));

        if ($parent->path()) {
            $this->path($parent->path() . '/' . $this->folder());
        }

        if ($parent->route()) {
            $this->route($parent->route() . '/' . $this->slug());
        } else {
            $this->route(self::getGrav()['pages']->root()->route() . '/' . $this->slug());
        }

        return $this;
    }

    /**
     * Prepare a copy from the page. Copies also everything that's under the current page.
     *
     * Returns a new Page object for the copy.
     * You need to call $this->save() in order to perform the move.
     *
     * @param Page $parent New parent page.
     *
     * @return $this
     */
    public function copy($parent)
    {
        $this->move($parent);
        $this->_action = 'copy';

        return $this;
    }

    /**
     * Get blueprints for the page.
     *
     * @return Blueprint
     */
    public function blueprints()
    {
        /** @var Pages $pages */
        $pages = self::getGrav()['pages'];

        $blueprint = $pages->blueprints($this->blueprintName());
        $fields = $blueprint->fields();
        $edit_mode = isset(self::getGrav()['admin']) ? self::getGrav()['config']->get('plugins.admin.edit_mode') : null;

        // override if you only want 'normal' mode
        if (empty($fields) && ($edit_mode == 'auto' || $edit_mode == 'normal')) {
            $blueprint = $pages->blueprints('default');
        }

        // override if you only want 'expert' mode
        if (!empty($fields) && $edit_mode == 'expert') {
            $blueprint = $pages->blueprints('');
        }

        return $blueprint;
    }

    /**
     * Get the blueprint name for this page.  Use the blueprint form field if set
     *
     * @return string
     */
    public function blueprintName()
    {
        $blueprint_name = filter_input(INPUT_POST, 'blueprint', FILTER_SANITIZE_STRING) ?: $this->template();

        return $blueprint_name;
    }

    /**
     * Validate page header.
     *
     * @throws Exception
     */
    public function validate()
    {
        $blueprints = $this->blueprints();
        $blueprints->validate($this->toArray());
    }

    /**
     * Filter page header from illegal contents.
     */
    public function filter()
    {
        $blueprints = $this->blueprints();
        $values = $blueprints->filter($this->toArray());
        if ($values && isset($values['header'])) {
            $this->header($values['header']);
        }
    }

    /**
     * Get unknown header variables.
     *
     * @return array
     */
    public function extra()
    {
        $blueprints = $this->blueprints();

        return $blueprints->extra($this->toArray()['header'], 'header.');
    }

    /**
     * Convert page to an array.
     *
     * @return array
     */
    public function toArray()
    {
        return [
            'header'  => (array)$this->header(),
            'content' => (string)$this->value('content')
        ];
    }

    /**
     * Convert page to YAML encoded string.
     *
     * @return string
     */
    public function toYaml()
    {
        return Yaml::dump($this->toArray(), 10);
    }

    /**
     * Convert page to JSON encoded string.
     *
     * @return string
     */
    public function toJson()
    {
        return json_encode($this->toArray());
    }

    /**
     * Gets and sets the associated media as found in the page folder.
     *
     * @param  Media $var Representation of associated media.
     *
     * @return Media      Representation of associated media.
     */
    public function media($var = null)
    {
        /** @var Cache $cache */
        $cache = self::getGrav()['cache'];

        if ($var) {
            $this->media = $var;
        }
        if ($this->media === null) {
            // Use cached media if possible.
            $media_cache_id = md5('media' . $this->id());
            if (!$media = $cache->fetch($media_cache_id)) {
                $media = new Media($this->path());
                $cache->save($media_cache_id, $media);
            }
            $this->media = $media;
        }

        return $this->media;
    }

    /**
     * Gets and sets the name field.  If no name field is set, it will return 'default.md'.
     *
     * @param  string $var The name of this page.
     *
     * @return string      The name of this page.
     */
    public function name($var = null)
    {
        if ($var !== null) {
            $this->name = $var;
        }

        return empty($this->name) ? 'default.md' : $this->name;
    }

    /**
     * Returns child page type.
     *
     * @return string
     */
    public function childType()
    {
        return isset($this->header->child_type) ? (string)$this->header->child_type : 'default';
    }

    /**
     * Gets and sets the template field. This is used to find the correct Twig template file to render.
     * If no field is set, it will return the name without the .md extension
     *
     * @param  string $var the template name
     *
     * @return string      the template name
     */
    public function template($var = null)
    {
        if ($var !== null) {
            $this->template = $var;
        }
        if (empty($this->template)) {
            $this->template = ($this->modular() ? 'modular/' : '') . str_replace($this->extension(), '', $this->name());
        }

        return $this->template;
    }

    /**
     * Gets and sets the extension field.
     *
     * @param null $var
     *
     * @return null|string
     */
    public function extension($var = null)
    {
        if ($var !== null) {
            $this->extension = $var;
        }
        if (empty($this->extension)) {
            $this->extension = '.' . pathinfo($this->name(), PATHINFO_EXTENSION);
        }

        return $this->extension;
    }

    /**
     * Returns the page extension, got from the page `url_extension` config and falls back to the
     * system config `system.pages.append_url_extension`.
     *
     * @return string      The extension of this page. For example `.html`
     */
    public function urlExtension()
    {
        if ($this->home()) {
            return '';
        }

        // if not set in the page get the value from system config
        if (empty($this->url_extension)) {
            $this->url_extension = trim(isset($this->header->append_url_extension) ? $this->header->append_url_extension : self::getGrav()['config']->get('system.pages.append_url_extension', false));
        }

        return $this->url_extension;
    }

    /**
     * Gets and sets the expires field. If not set will return the default
     *
     * @param  int $var The new expires value.
     *
     * @return int      The expires value
     */
    public function expires($var = null)
    {
        if ($var !== null) {
            $this->expires = $var;
        }

        return empty($this->expires) ? self::getGrav()['config']->get('system.pages.expires') : $this->expires;
    }

    /**
     * Gets and sets the title for this Page.  If no title is set, it will use the slug() to get a name
     *
     * @param  string $var the title of the Page
     *
     * @return string      the title of the Page
     */
    public function title($var = null)
    {
        if ($var !== null) {
            $this->title = $var;
        }
        if (empty($this->title)) {
            $this->title = ucfirst($this->slug());
        }

        return $this->title;
    }

    /**
     * Gets and sets the menu name for this Page.  This is the text that can be used specifically for navigation.
     * If no menu field is set, it will use the title()
     *
     * @param  string $var the menu field for the page
     *
     * @return string      the menu field for the page
     */
    public function menu($var = null)
    {
        if ($var !== null) {
            $this->menu = $var;
        }
        if (empty($this->menu)) {
            $this->menu = $this->title();
        }

        return $this->menu;
    }

    /**
     * Gets and Sets whether or not this Page is visible for navigation
     *
     * @param  bool $var true if the page is visible
     *
     * @return bool      true if the page is visible
     */
    public function visible($var = null)
    {
        if ($var !== null) {
            $this->visible = (bool)$var;
        }

        if ($this->visible === null) {
            // Set item visibility in menu if folder is different from slug
            // eg folder = 01.Home and slug = Home
            $regex = '/^[0-9]+\./u';
            if (preg_match($regex, $this->folder)) {
                $this->visible = true;
            } else {
                $this->visible = false;
            }
        }

        return $this->visible;
    }

    /**
     * Gets and Sets whether or not this Page is considered published
     *
     * @param  bool $var true if the page is published
     *
     * @return bool      true if the page is published
     */
    public function published($var = null)
    {
        if ($var !== null) {
            $this->published = (bool)$var;
        }

        // If not published, should not be visible in menus either
        if ($this->published === false) {
            $this->visible = false;
        }

        return $this->published;
    }

    /**
     * Gets and Sets the Page publish date
     *
     * @param  string $var string representation of a date
     *
     * @return int         unix timestamp representation of the date
     */
    public function publishDate($var = null)
    {
        if ($var !== null) {
            $this->publish_date = Utils::date2timestamp($var, $this->dateformat);
        }

        return $this->publish_date;
    }

    /**
     * Gets and Sets the Page unpublish date
     *
     * @param  string $var string representation of a date
     *
     * @return int|null         unix timestamp representation of the date
     */
    public function unpublishDate($var = null)
    {
        if ($var !== null) {
            $this->unpublish_date = Utils::date2timestamp($var, $this->dateformat);
        }

        return $this->unpublish_date;
    }

    /**
     * Gets and Sets whether or not this Page is routable, ie you can reach it
     * via a URL.
     * The page must be *routable* and *published*
     *
     * @param  bool $var true if the page is routable
     *
     * @return bool      true if the page is routable
     */
    public function routable($var = null)
    {
        if ($var !== null) {
            $this->routable = (bool)$var;
        }

        return $this->routable && $this->published();
    }

    public function ssl($var = null)
    {
        if ($var !== null) {
            $this->ssl = (bool) $var;
        }

        return $this->ssl;
    }

    /**
     * Gets and Sets the process setup for this Page. This is multi-dimensional array that consists of
     * a simple array of arrays with the form array("markdown"=>true) for example
     *
     * @param  array $var an Array of name value pairs where the name is the process and value is true or false
     *
     * @return array      an Array of name value pairs where the name is the process and value is true or false
     */
    public function process($var = null)
    {
        if ($var !== null) {
            $this->process = (array)$var;
        }

        return $this->process;
    }

    /**
     * Function to merge page metadata tags and build an array of Metadata objects
     * that can then be rendered in the page.
     *
     * @param  array $var an Array of metadata values to set
     *
     * @return array      an Array of metadata values for the page
     */
    public function metadata($var = null)
    {
        if ($var !== null) {
            $this->metadata = (array)$var;
        }

        // if not metadata yet, process it.
        if (null === $this->metadata) {
            $header_tag_http_equivs = ['content-type', 'default-style', 'refresh'];

            $this->metadata = [];

            $metadata = [];
            // Set the Generator tag
            $metadata['generator'] = 'GravCMS';

            // Get initial metadata for the page
            $metadata = array_merge($metadata, self::getGrav()['config']->get('site.metadata'));

            if (isset($this->header->metadata)) {
                // Merge any site.metadata settings in with page metadata
                $metadata = array_merge($metadata, $this->header->metadata);
            }

            // Build an array of meta objects..
            foreach ((array)$metadata as $key => $value) {
                // If this is a property type metadata: "og", "twitter", "facebook" etc
                // Backward compatibility for nested arrays in metas
                if (is_array($value)) {
                    foreach ($value as $property => $prop_value) {
                        $prop_key                  = $key . ":" . $property;
                        $this->metadata[$prop_key] = ['name' => $prop_key, 'property' => $prop_key, 'content' => htmlspecialchars($prop_value, ENT_QUOTES)];
                    }
                } else {
                    // If it this is a standard meta data type
                    if ($value) {
                        if (in_array($key, $header_tag_http_equivs)) {
                            $this->metadata[$key] = ['http_equiv' => $key, 'content' => htmlspecialchars($value, ENT_QUOTES)];
                        } else {
                            // if it's a social metadata with separator, render as property
                            $separator    = strpos($key, ':');
                            $hasSeparator = $separator && $separator < strlen($key) - 1;
                            $entry        = ['name' => $key, 'content' => htmlspecialchars($value, ENT_QUOTES)];

                            if ($hasSeparator) {
                                $entry['property'] = $key;
                            }

                            $this->metadata[$key] = $entry;
                        }
                    }
                }
            }
        }

        return $this->metadata;
    }

    /**
     * Gets and Sets the slug for the Page. The slug is used in the URL routing. If not set it uses
     * the parent folder from the path
     *
     * @param  string $var the slug, e.g. 'my-blog'
     *
     * @return string      the slug
     */
    public function slug($var = null)
    {
        if ($var !== null) {
            $this->slug = $var;
        }

        if (empty($this->slug)) {
            $this->slug = preg_replace(PAGE_ORDER_PREFIX_REGEX, '', $this->folder);
        }

        return $this->slug;<commit_msg>log error on invalid slug - only when setting the value from frontmatter<commit_after><?php
namespace Grav\Common\Page;

use Exception;
use Grav\Common\Filesystem\Folder;
use Grav\Common\Config\Config;
use Grav\Common\GravTrait;
use Grav\Common\Language\Language;
use Grav\Common\Utils;
use Grav\Common\Cache;
use Grav\Common\Twig;
use Grav\Common\Uri;
use Grav\Common\Grav;
use Grav\Common\Taxonomy;
use Grav\Common\Markdown\Parsedown;
use Grav\Common\Markdown\ParsedownExtra;
use Grav\Common\Data\Blueprint;
use RocketTheme\Toolbox\Event\Event;
use RocketTheme\Toolbox\File\MarkdownFile;
use Symfony\Component\Yaml\Exception\ParseException;
use Symfony\Component\Yaml\Yaml;

define('PAGE_ORDER_PREFIX_REGEX', '/^[0-9]+\./u');

/**
 * The Page object, or "Page" object is the main powerhouse of Grav.  It contains all the information
 * related to the nested pages structure that represents the content. Each page has several attributes that
 * can be retrieved via public functions. Also each page can potentially contain an array of sub-pages.
 * Recursively traversing the page structure allows Grav to create navigation systems.
 *
 * @author  RocketTheme
 * @license MIT
 */
class Page
{
    use GravTrait;

    /**
     * @var string Filename. Leave as null if page is folder.
     */
    protected $name;
    protected $folder;
    protected $path;
    protected $extension;
    protected $url_extension;

    protected $id;
    protected $parent;
    protected $template;
    protected $expires;
    protected $visible;
    protected $published;
    protected $publish_date;
    protected $unpublish_date;
    protected $slug;
    protected $route;
    protected $raw_route;
    protected $url;
    protected $routes;
    protected $routable;
    protected $modified;
    protected $redirect;
    protected $items;
    protected $header;
    protected $frontmatter;
    protected $language;
    protected $content;
    protected $content_meta;
    protected $summary;
    protected $raw_content;
    protected $pagination;
    protected $media;
    protected $metadata;
    protected $title;
    protected $max_count;
    protected $menu;
    protected $date;
    protected $dateformat;
    protected $taxonomy;
    protected $order_by;
    protected $order_dir;
    protected $order_manual;
    protected $modular;
    protected $modular_twig;
    protected $process;
    protected $summary_size;
    protected $markdown_extra;
    protected $etag;
    protected $last_modified;
    protected $home_route;
    protected $hide_home_route;
    protected $ssl;

    /**
     * @var Page Unmodified (original) version of the page. Used for copying and moving the page.
     */
    private $_original;

    /**
     * @var string Action
     */
    private $_action;

    /**
     * Page Object Constructor
     *
     * @return $this
     */
    public function __construct()
    {
        /** @var Config $config */
        $config = self::getGrav()['config'];

        $this->taxonomy = [];
        $this->process = $config->get('system.pages.process');
        $this->published = true;

        return $this;
    }

    /**
     * Initializes the page instance variables based on a file
     *
     * @param  \SplFileInfo $file The file information for the .md file that the page represents
     * @param  string       $extension
     *
     * @return $this
     */
    public function init(\SplFileInfo $file, $extension = null)
    {
        $config = self::getGrav()['config'];

        $this->hide_home_route = $config->get('system.home.hide_in_urls', false);
        $this->home_route = $config->get('system.home.alias');
        $this->filePath($file->getPathName());
        $this->modified($file->getMTime());
        $this->id($this->modified() . md5($this->filePath()));
        $this->routable(true);
        $this->header();
        $this->date();
        $this->metadata();
        $this->url();
        $this->visible();
        $this->modularTwig($this->slug[0] == '_');
        $this->setPublishState();
        $this->published();
        $this->urlExtension();

        // some extension logic
        if (empty($extension)) {
            $this->extension('.' . $file->getExtension());
        } else {
            $this->extension($extension);
        }

        // extract page language from page extension
        $language = trim(basename($this->extension(), 'md'), '.') ?: null;
        $this->language($language);

        return $this;
    }

    /**
     * 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;
    }

    /**
     * Return an array listing untranslated languages available
     * @return array the page untranslated languages
     */
    public function untranslatedLanguages()
    {
        $filename = substr($this->name, 0, -(strlen($this->extension())));
        $config = self::getGrav()['config'];
        $languages = $config->get('system.languages.supported', []);
        $untranslatedLanguages = [];

        foreach ($languages as $language) {
            $path = $this->path . DS . $this->folder . DS . $filename . '.' . $language . '.md';
            if (!file_exists($path)) {
                $untranslatedLanguages[] = $language;
            }
        }

        return $untranslatedLanguages;
    }

    /**
     * Gets and Sets the raw data
     *
     * @param  string $var Raw content string
     *
     * @return Object      Raw content string
     */
    public function raw($var = null)
    {
        $file = $this->file();

        if ($var) {
            // First update file object.
            if ($file) {
                $file->raw($var);
            }

            // Reset header and content.
            $this->modified = time();
            $this->id($this->modified() . md5($this->filePath()));
            $this->header = null;
            $this->content = null;
            $this->summary = null;
        }

        return $file ? $file->raw() : '';
    }

    /**
     * Gets and Sets the page frontmatter
     *
     * @param string|null $var
     *
     * @return string
     */
    public function frontmatter($var = null)
    {

        if ($var) {
            $this->frontmatter = (string)$var;

            // Update also file object.
            $file = $this->file();
            if ($file) {
                $file->frontmatter((string)$var);
            }

            // Force content re-processing.
            $this->id(time() . md5($this->filePath()));
        }
        if (!$this->frontmatter) {
            $this->header();
        }

        return $this->frontmatter;
    }

    /**
     * Gets and Sets the header based on the YAML configuration at the top of the .md file
     *
     * @param  object|array $var a YAML object representing the configuration for the file
     *
     * @return object      the current YAML configuration
     */
    public function header($var = null)
    {
        if ($var) {
            $this->header = (object)$var;

            // Update also file object.
            $file = $this->file();
            if ($file) {
                $file->header((array)$var);
            }

            // Force content re-processing.
            $this->id(time() . md5($this->filePath()));
        }
        if (!$this->header) {
            $file = $this->file();
            if ($file) {
                // Set some options
                $file->settings(['native' => true, 'compat' => true]);
                try {
                    $this->raw_content = $file->markdown();
                    $this->frontmatter = $file->frontmatter();
                    $this->header = (object)$file->header();
                } catch (ParseException $e) {
                    $file->raw(self::getGrav()['language']->translate([
                        'FRONTMATTER_ERROR_PAGE',
                        $this->slug(),
                        $file->filename(),
                        $e->getMessage(),
                        $file->raw()
                    ]));
                    $this->raw_content = $file->markdown();
                    $this->frontmatter = $file->frontmatter();
                    $this->header = (object)$file->header();
                }
                $var = true;
            }
        }

        if ($var) {
            if (isset($this->header->slug)) {
                $this->slug(($this->header->slug));
            }
            if (isset($this->header->routes)) {
                $this->routes = (array)($this->header->routes);
            }
            if (isset($this->header->title)) {
                $this->title = trim($this->header->title);
            }
            if (isset($this->header->language)) {
                $this->language = trim($this->header->language);
            }
            if (isset($this->header->template)) {
                $this->template = trim($this->header->template);
            }
            if (isset($this->header->menu)) {
                $this->menu = trim($this->header->menu);
            }
            if (isset($this->header->routable)) {
                $this->routable = (bool)$this->header->routable;
            }
            if (isset($this->header->visible)) {
                $this->visible = (bool)$this->header->visible;
            }
            if (isset($this->header->redirect)) {
                $this->redirect = trim($this->header->redirect);
            }
            if (isset($this->header->order_dir)) {
                $this->order_dir = trim($this->header->order_dir);
            }
            if (isset($this->header->order_by)) {
                $this->order_by = trim($this->header->order_by);
            }
            if (isset($this->header->order_manual)) {
                $this->order_manual = (array)$this->header->order_manual;
            }
            if (isset($this->header->dateformat)) {
                $this->dateformat($this->header->dateformat);
            }
            if (isset($this->header->date)) {
                $this->date($this->header->date);
            }
            if (isset($this->header->markdown_extra)) {
                $this->markdown_extra = (bool)$this->header->markdown_extra;
            }
            if (isset($this->header->taxonomy)) {
                foreach ((array)$this->header->taxonomy as $taxonomy => $taxitems) {
                    $this->taxonomy[$taxonomy] = (array)$taxitems;
                }
            }
            if (isset($this->header->max_count)) {
                $this->max_count = intval($this->header->max_count);
            }
            if (isset($this->header->process)) {
                foreach ((array)$this->header->process as $process => $status) {
                    $this->process[$process] = (bool)$status;
                }
            }
            if (isset($this->header->published)) {
                $this->published = (bool)$this->header->published;
            }
            if (isset($this->header->publish_date)) {
                $this->publishDate($this->header->publish_date);
            }
            if (isset($this->header->unpublish_date)) {
                $this->unpublishDate($this->header->unpublish_date);
            }
            if (isset($this->header->expires)) {
                $this->expires = intval($this->header->expires);
            }
            if (isset($this->header->etag)) {
                $this->etag = (bool)$this->header->etag;
            }
            if (isset($this->header->last_modified)) {
                $this->last_modified = (bool)$this->header->last_modified;
            }
            if (isset($this->header->ssl)) {
                $this->ssl = (bool) $this->header->ssl;
            }
        }

        return $this->header;
    }

    /**
     * Get page language
     *
     * @param $var
     *
     * @return mixed
     */
    public function language($var = null)
    {
        if ($var !== null) {
            $this->language = $var;
        }

        return $this->language;
    }

    /**
     * Modify a header value directly
     *
     * @param $key
     * @param $value
     */
    public function modifyHeader($key, $value)
    {
        $this->header->{$key} = $value;
    }

    /**
     * Get the summary.
     *
     * @param  int $size Max summary size.
     *
     * @return string
     */
    public function summary($size = null)
    {
        $config = (array)self::getGrav()['config']->get('site.summary');
        if (isset($this->header->summary)) {
            $config = array_merge($config, $this->header->summary);
        }

        // Return summary based on settings in site config file
        if (!$config['enabled']) {
            return $this->content();
        }

        // Set up variables to process summary from page or from custom summary
        if ($this->summary === null) {
            $content = $this->content();
            $summary_size = $this->summary_size;
        } else {
            $content = $this->summary;
            $summary_size = mb_strlen($this->summary);
        }

        // Return calculated summary based on summary divider's position
        $format = $config['format'];
        // Return entire page content on wrong/ unknown format
        if (!in_array($format, ['short', 'long'])) {
            return $content;
        } elseif (($format === 'short') && isset($summary_size)) {
            return mb_substr($content, 0, $summary_size);
        }

        // Get summary size from site config's file
        if (is_null($size)) {
            $size = $config['size'];
        }

        // If the size is zero, return the entire page content
        if ($size === 0) {
            return $content;
            // Return calculated summary based on defaults
        } elseif (!is_numeric($size) || ($size < 0)) {
            $size = 300;
        }

        return Utils::truncateHTML($content, $size);
    }

    /**
     * Sets the summary of the page
     *
     * @param string $summary Summary
     */
    public function setSummary($summary)
    {
        $this->summary = $summary;
    }

    /**
     * Gets and Sets the content based on content portion of the .md file
     *
     * @param  string $var Content
     *
     * @return string      Content
     */
    public function content($var = null)
    {
        if ($var !== null) {
            $this->raw_content = $var;

            // Update file object.
            $file = $this->file();
            if ($file) {
                $file->markdown($var);
            }

            // Force re-processing.
            $this->id(time() . md5($this->filePath()));
            $this->content = null;
        }
        // If no content, process it
        if ($this->content === null) {
            // Get media
            $this->media();

            /** @var Config $config */
            $config = self::getGrav()['config'];

            // Load cached content
            /** @var Cache $cache */
            $cache = self::getGrav()['cache'];
            $cache_id = md5('page' . $this->id());
            $content_obj = $cache->fetch($cache_id);

            if (is_array($content_obj)) {
                $this->content = $content_obj['content'];
                $this->content_meta = $content_obj['content_meta'];
            } else {
                $this->content = $content_obj;
            }


            $process_markdown = $this->shouldProcess('markdown');
            $process_twig = $this->shouldProcess('twig');
            $cache_enable = isset($this->header->cache_enable) ? $this->header->cache_enable : $config->get('system.cache.enabled',
                true);
            $twig_first = isset($this->header->twig_first) ? $this->header->twig_first : $config->get('system.pages.twig_first',
                true);


            // if no cached-content run everything
            if ($this->content === false || $cache_enable === false) {
                $this->content = $this->raw_content;
                self::getGrav()->fireEvent('onPageContentRaw', new Event(['page' => $this]));

                if ($twig_first) {
                    if ($process_twig) {
                        $this->processTwig();
                    }
                    if ($process_markdown) {
                        $this->processMarkdown();
                    }

                    // Content Processed but not cached yet
                    self::getGrav()->fireEvent('onPageContentProcessed', new Event(['page' => $this]));

                } else {
                    if ($process_markdown) {
                        $this->processMarkdown();
                    }

                    // Content Processed but not cached yet
                    self::getGrav()->fireEvent('onPageContentProcessed', new Event(['page' => $this]));

                    if ($process_twig) {
                        $this->processTwig();
                    }
                }

                if ($cache_enable) {
                    $this->cachePageContent();
                }
            }

            // Handle summary divider
            $delimiter = $config->get('site.summary.delimiter', '===');
            $divider_pos = mb_strpos($this->content, "<p>{$delimiter}</p>");
            if ($divider_pos !== false) {
                $this->summary_size = $divider_pos;
                $this->content = str_replace("<p>{$delimiter}</p>", '', $this->content);
            }

        }

        return $this->content;
    }

    /**
     * Get the contentMeta array and initialize content first if it's not already
     *
     * @return mixed
     */
    public function contentMeta()
    {
        if ($this->content === null) {
            $this->content();
        }
        return $this->getContentMeta();
    }

    /**
     * Add an entry to the page's contentMeta array
     *
     * @param $name
     * @param $value
     */
    public function addContentMeta($name, $value)
    {
        $this->content_meta[$name] = $value;
    }

    /**
     * Return the whole contentMeta array as it currently stands
     *
     * @return mixed
     */
    public function getContentMeta()
    {
        return $this->content_meta;
    }

    /**
     * Sets the whole content meta array in one shot
     *
     * @param $content_meta
     * @return mixed
     */
    public function setContentMeta($content_meta)
    {
        return $this->content_meta = $content_meta;
    }

    /**
     * Process the Markdown content.  Uses Parsedown or Parsedown Extra depending on configuration
     */
    protected function processMarkdown()
    {
        /** @var Config $config */
        $config = self::getGrav()['config'];

        $defaults = (array)$config->get('system.pages.markdown');
        if (isset($this->header()->markdown)) {
            $defaults = array_merge($defaults, $this->header()->markdown);
        }

        // pages.markdown_extra is deprecated, but still check it...
        if (!isset($defaults['extra']) && (isset($this->markdown_extra) || $config->get('system.pages.markdown_extra') !== null)) {
            $defaults['extra'] = $this->markdown_extra ?: $config->get('system.pages.markdown_extra');
        }

        // Initialize the preferred variant of Parsedown
        if ($defaults['extra']) {
            $parsedown = new ParsedownExtra($this, $defaults);
        } else {
            $parsedown = new Parsedown($this, $defaults);
        }

        $this->content = $parsedown->text($this->content);
    }


    /**
     * Process the Twig page content.
     */
    private function processTwig()
    {
        $twig = self::getGrav()['twig'];
        $this->content = $twig->processPage($this, $this->content);
    }

    /**
     * Fires the onPageContentProcessed event, and caches the page content using a unique ID for the page
     */
    private function cachePageContent()
    {
        $cache = self::getGrav()['cache'];
        $cache_id = md5('page' . $this->id());
        $cache->save($cache_id, ['content' => $this->content, 'content_meta' => $this->content_meta]);
    }

    /**
     * Needed by the onPageContentProcessed event to get the raw page content
     *
     * @return string   the current page content
     */
    public function getRawContent()
    {
        return $this->content;
    }

    /**
     * Needed by the onPageContentProcessed event to set the raw page content
     *
     * @param $content
     */
    public function setRawContent($content)
    {
        $this->content = $content;
    }

    /**
     * Get value from a page variable (used mostly for creating edit forms).
     *
     * @param string $name Variable name.
     * @param mixed  $default
     *
     * @return mixed
     */
    public function value($name, $default = null)
    {
        if ($name == 'content') {
            return $this->raw_content;
        }
        if ($name == 'route') {
            return $this->parent()->rawRoute();
        }
        if ($name == 'order') {
            $order = $this->order();

            return $order ? (int)$this->order() : '';
        }
        if ($name == 'ordering') {
            return (bool)$this->order();
        }
        if ($name == 'folder') {
            $regex = '/^[0-9]+\./u';

            return preg_replace($regex, '', $this->folder);
        }
        if ($name == 'name') {
            $language = $this->language() ? '.' . $this->language() : '';
            $name_val = str_replace($language . '.md', '', $this->name());
            if ($this->modular()) {
                return 'modular/' . $name_val;
            }

            return $name_val;
        }
        if ($name == 'media') {
            return $this->media()->all();
        }
        if ($name == 'media.file') {
            return $this->media()->files();
        }
        if ($name == 'media.video') {
            return $this->media()->videos();
        }
        if ($name == 'media.image') {
            return $this->media()->images();
        }
        if ($name == 'media.audio') {
            return $this->media()->audios();
        }

        $path = explode('.', $name);
        $scope = array_shift($path);

        if ($name == 'frontmatter') {
            return $this->frontmatter;
        }

        if ($scope == 'header') {
            $current = $this->header();
            foreach ($path as $field) {
                if (is_object($current) && isset($current->{$field})) {
                    $current = $current->{$field};
                } elseif (is_array($current) && isset($current[$field])) {
                    $current = $current[$field];
                } else {
                    return $default;
                }
            }

            return $current;
        }

        return $default;
    }

    /**
     * Gets and Sets the Page raw content
     *
     * @param null $var
     *
     * @return null
     */
    public function rawMarkdown($var = null)
    {
        if ($var !== null) {
            $this->raw_content = $var;
        }

        return $this->raw_content;
    }

    /**
     * Get file object to the page.
     *
     * @return MarkdownFile|null
     */
    public function file()
    {
        if ($this->name) {
            return MarkdownFile::instance($this->filePath());
        }

        return null;
    }

    /**
     * Save page if there's a file assigned to it.
     *
     * @param bool $reorder Internal use.
     */
    public function save($reorder = true)
    {
        // Perform move, copy or reordering if needed.
        $this->doRelocation($reorder);

        $file = $this->file();
        if ($file) {
            $file->filename($this->filePath());
            $file->header((array)$this->header());
            $file->markdown($this->raw_content);
            $file->save();
        }
    }

    /**
     * Prepare move page to new location. Moves also everything that's under the current page.
     *
     * You need to call $this->save() in order to perform the move.
     *
     * @param Page $parent New parent page.
     *
     * @return $this
     */
    public function move(Page $parent)
    {
        if (!$this->_original) {
            $clone = clone $this;
            $this->_original = $clone;
        }

        $this->_action = 'move';
        $this->parent($parent);
        $this->id(time() . md5($this->filePath()));

        if ($parent->path()) {
            $this->path($parent->path() . '/' . $this->folder());
        }

        if ($parent->route()) {
            $this->route($parent->route() . '/' . $this->slug());
        } else {
            $this->route(self::getGrav()['pages']->root()->route() . '/' . $this->slug());
        }

        return $this;
    }

    /**
     * Prepare a copy from the page. Copies also everything that's under the current page.
     *
     * Returns a new Page object for the copy.
     * You need to call $this->save() in order to perform the move.
     *
     * @param Page $parent New parent page.
     *
     * @return $this
     */
    public function copy($parent)
    {
        $this->move($parent);
        $this->_action = 'copy';

        return $this;
    }

    /**
     * Get blueprints for the page.
     *
     * @return Blueprint
     */
    public function blueprints()
    {
        /** @var Pages $pages */
        $pages = self::getGrav()['pages'];

        $blueprint = $pages->blueprints($this->blueprintName());
        $fields = $blueprint->fields();
        $edit_mode = isset(self::getGrav()['admin']) ? self::getGrav()['config']->get('plugins.admin.edit_mode') : null;

        // override if you only want 'normal' mode
        if (empty($fields) && ($edit_mode == 'auto' || $edit_mode == 'normal')) {
            $blueprint = $pages->blueprints('default');
        }

        // override if you only want 'expert' mode
        if (!empty($fields) && $edit_mode == 'expert') {
            $blueprint = $pages->blueprints('');
        }

        return $blueprint;
    }

    /**
     * Get the blueprint name for this page.  Use the blueprint form field if set
     *
     * @return string
     */
    public function blueprintName()
    {
        $blueprint_name = filter_input(INPUT_POST, 'blueprint', FILTER_SANITIZE_STRING) ?: $this->template();

        return $blueprint_name;
    }

    /**
     * Validate page header.
     *
     * @throws Exception
     */
    public function validate()
    {
        $blueprints = $this->blueprints();
        $blueprints->validate($this->toArray());
    }

    /**
     * Filter page header from illegal contents.
     */
    public function filter()
    {
        $blueprints = $this->blueprints();
        $values = $blueprints->filter($this->toArray());
        if ($values && isset($values['header'])) {
            $this->header($values['header']);
        }
    }

    /**
     * Get unknown header variables.
     *
     * @return array
     */
    public function extra()
    {
        $blueprints = $this->blueprints();

        return $blueprints->extra($this->toArray()['header'], 'header.');
    }

    /**
     * Convert page to an array.
     *
     * @return array
     */
    public function toArray()
    {
        return [
            'header'  => (array)$this->header(),
            'content' => (string)$this->value('content')
        ];
    }

    /**
     * Convert page to YAML encoded string.
     *
     * @return string
     */
    public function toYaml()
    {
        return Yaml::dump($this->toArray(), 10);
    }

    /**
     * Convert page to JSON encoded string.
     *
     * @return string
     */
    public function toJson()
    {
        return json_encode($this->toArray());
    }

    /**
     * Gets and sets the associated media as found in the page folder.
     *
     * @param  Media $var Representation of associated media.
     *
     * @return Media      Representation of associated media.
     */
    public function media($var = null)
    {
        /** @var Cache $cache */
        $cache = self::getGrav()['cache'];

        if ($var) {
            $this->media = $var;
        }
        if ($this->media === null) {
            // Use cached media if possible.
            $media_cache_id = md5('media' . $this->id());
            if (!$media = $cache->fetch($media_cache_id)) {
                $media = new Media($this->path());
                $cache->save($media_cache_id, $media);
            }
            $this->media = $media;
        }

        return $this->media;
    }

    /**
     * Gets and sets the name field.  If no name field is set, it will return 'default.md'.
     *
     * @param  string $var The name of this page.
     *
     * @return string      The name of this page.
     */
    public function name($var = null)
    {
        if ($var !== null) {
            $this->name = $var;
        }

        return empty($this->name) ? 'default.md' : $this->name;
    }

    /**
     * Returns child page type.
     *
     * @return string
     */
    public function childType()
    {
        return isset($this->header->child_type) ? (string)$this->header->child_type : 'default';
    }

    /**
     * Gets and sets the template field. This is used to find the correct Twig template file to render.
     * If no field is set, it will return the name without the .md extension
     *
     * @param  string $var the template name
     *
     * @return string      the template name
     */
    public function template($var = null)
    {
        if ($var !== null) {
            $this->template = $var;
        }
        if (empty($this->template)) {
            $this->template = ($this->modular() ? 'modular/' : '') . str_replace($this->extension(), '', $this->name());
        }

        return $this->template;
    }

    /**
     * Gets and sets the extension field.
     *
     * @param null $var
     *
     * @return null|string
     */
    public function extension($var = null)
    {
        if ($var !== null) {
            $this->extension = $var;
        }
        if (empty($this->extension)) {
            $this->extension = '.' . pathinfo($this->name(), PATHINFO_EXTENSION);
        }

        return $this->extension;
    }

    /**
     * Returns the page extension, got from the page `url_extension` config and falls back to the
     * system config `system.pages.append_url_extension`.
     *
     * @return string      The extension of this page. For example `.html`
     */
    public function urlExtension()
    {
        if ($this->home()) {
            return '';
        }

        // if not set in the page get the value from system config
        if (empty($this->url_extension)) {
            $this->url_extension = trim(isset($this->header->append_url_extension) ? $this->header->append_url_extension : self::getGrav()['config']->get('system.pages.append_url_extension', false));
        }

        return $this->url_extension;
    }

    /**
     * Gets and sets the expires field. If not set will return the default
     *
     * @param  int $var The new expires value.
     *
     * @return int      The expires value
     */
    public function expires($var = null)
    {
        if ($var !== null) {
            $this->expires = $var;
        }

        return empty($this->expires) ? self::getGrav()['config']->get('system.pages.expires') : $this->expires;
    }

    /**
     * Gets and sets the title for this Page.  If no title is set, it will use the slug() to get a name
     *
     * @param  string $var the title of the Page
     *
     * @return string      the title of the Page
     */
    public function title($var = null)
    {
        if ($var !== null) {
            $this->title = $var;
        }
        if (empty($this->title)) {
            $this->title = ucfirst($this->slug());
        }

        return $this->title;
    }

    /**
     * Gets and sets the menu name for this Page.  This is the text that can be used specifically for navigation.
     * If no menu field is set, it will use the title()
     *
     * @param  string $var the menu field for the page
     *
     * @return string      the menu field for the page
     */
    public function menu($var = null)
    {
        if ($var !== null) {
            $this->menu = $var;
        }
        if (empty($this->menu)) {
            $this->menu = $this->title();
        }

        return $this->menu;
    }

    /**
     * Gets and Sets whether or not this Page is visible for navigation
     *
     * @param  bool $var true if the page is visible
     *
     * @return bool      true if the page is visible
     */
    public function visible($var = null)
    {
        if ($var !== null) {
            $this->visible = (bool)$var;
        }

        if ($this->visible === null) {
            // Set item visibility in menu if folder is different from slug
            // eg folder = 01.Home and slug = Home
            $regex = '/^[0-9]+\./u';
            if (preg_match($regex, $this->folder)) {
                $this->visible = true;
            } else {
                $this->visible = false;
            }
        }

        return $this->visible;
    }

    /**
     * Gets and Sets whether or not this Page is considered published
     *
     * @param  bool $var true if the page is published
     *
     * @return bool      true if the page is published
     */
    public function published($var = null)
    {
        if ($var !== null) {
            $this->published = (bool)$var;
        }

        // If not published, should not be visible in menus either
        if ($this->published === false) {
            $this->visible = false;
        }

        return $this->published;
    }

    /**
     * Gets and Sets the Page publish date
     *
     * @param  string $var string representation of a date
     *
     * @return int         unix timestamp representation of the date
     */
    public function publishDate($var = null)
    {
        if ($var !== null) {
            $this->publish_date = Utils::date2timestamp($var, $this->dateformat);
        }

        return $this->publish_date;
    }

    /**
     * Gets and Sets the Page unpublish date
     *
     * @param  string $var string representation of a date
     *
     * @return int|null         unix timestamp representation of the date
     */
    public function unpublishDate($var = null)
    {
        if ($var !== null) {
            $this->unpublish_date = Utils::date2timestamp($var, $this->dateformat);
        }

        return $this->unpublish_date;
    }

    /**
     * Gets and Sets whether or not this Page is routable, ie you can reach it
     * via a URL.
     * The page must be *routable* and *published*
     *
     * @param  bool $var true if the page is routable
     *
     * @return bool      true if the page is routable
     */
    public function routable($var = null)
    {
        if ($var !== null) {
            $this->routable = (bool)$var;
        }

        return $this->routable && $this->published();
    }

    public function ssl($var = null)
    {
        if ($var !== null) {
            $this->ssl = (bool) $var;
        }

        return $this->ssl;
    }

    /**
     * Gets and Sets the process setup for this Page. This is multi-dimensional array that consists of
     * a simple array of arrays with the form array("markdown"=>true) for example
     *
     * @param  array $var an Array of name value pairs where the name is the process and value is true or false
     *
     * @return array      an Array of name value pairs where the name is the process and value is true or false
     */
    public function process($var = null)
    {
        if ($var !== null) {
            $this->process = (array)$var;
        }

        return $this->process;
    }

    /**
     * Function to merge page metadata tags and build an array of Metadata objects
     * that can then be rendered in the page.
     *
     * @param  array $var an Array of metadata values to set
     *
     * @return array      an Array of metadata values for the page
     */
    public function metadata($var = null)
    {
        if ($var !== null) {
            $this->metadata = (array)$var;
        }

        // if not metadata yet, process it.
        if (null === $this->metadata) {
            $header_tag_http_equivs = ['content-type', 'default-style', 'refresh'];

            $this->metadata = [];

            $metadata = [];
            // Set the Generator tag
            $metadata['generator'] = 'GravCMS';

            // Get initial metadata for the page
            $metadata = array_merge($metadata, self::getGrav()['config']->get('site.metadata'));

            if (isset($this->header->metadata)) {
                // Merge any site.metadata settings in with page metadata
                $metadata = array_merge($metadata, $this->header->metadata);
            }

            // Build an array of meta objects..
            foreach ((array)$metadata as $key => $value) {
                // If this is a property type metadata: "og", "twitter", "facebook" etc
                // Backward compatibility for nested arrays in metas
                if (is_array($value)) {
                    foreach ($value as $property => $prop_value) {
                        $prop_key                  = $key . ":" . $property;
                        $this->metadata[$prop_key] = ['name' => $prop_key, 'property' => $prop_key, 'content' => htmlspecialchars($prop_value, ENT_QUOTES)];
                    }
                } else {
                    // If it this is a standard meta data type
                    if ($value) {
                        if (in_array($key, $header_tag_http_equivs)) {
                            $this->metadata[$key] = ['http_equiv' => $key, 'content' => htmlspecialchars($value, ENT_QUOTES)];
                        } else {
                            // if it's a social metadata with separator, render as property
                            $separator    = strpos($key, ':');
                            $hasSeparator = $separator && $separator < strlen($key) - 1;
                            $entry        = ['name' => $key, 'content' => htmlspecialchars($value, ENT_QUOTES)];

                            if ($hasSeparator) {
                                $entry['property'] = $key;
                            }

                            $this->metadata[$key] = $entry;
                        }
                    }
                }
            }
        }

        return $this->metadata;
    }

    /**
     * Gets and Sets the slug for the Page. The slug is used in the URL routing. If not set it uses
     * the parent folder from the path
     *
     * @param  string $var the slug, e.g. 'my-blog'
     *
     * @return string      the slug
     */
    public function slug($var = null)
    {
        if ($var !== null) {
            $this->slug = $var;
            if(!preg_match('/^[a-z0-9][-a-z0-9]*$/', $this->slug)){
                Grav::instance()['log']->notice("Invalid slug set in YAML frontmatter: " . $this->rawRoute() . " => ".  $this->slug);
            }
        }

        if (empty($this->slug)) {
            $this->slug = strtolower(preg_replace(PAGE_ORDER_PREFIX_REGEX, '', $this->folder));
        }



        return $this->slug;
{'fraction_non_alphanumeric': 0.14405891163255116, 'fraction_numerical': 0.0008237643534697953, 'mean_word_length': 1.6721251334044824, 'pattern_counts': {'":': 2, '<': 17, '<?xml version=': 0, '>': 1006, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5280719', 'n_tokens_mistral': 22571, 'n_tokens_neox': 21764, 'n_words': 5591}