12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124 |
- <?php
- /**
- * @package Grav\Framework\Flex
- *
- * @copyright Copyright (c) 2015 - 2023 Trilby Media, LLC. All rights reserved.
- * @license MIT License; see LICENSE file for details.
- */
- namespace Grav\Framework\Flex\Pages\Traits;
- use Exception;
- use Grav\Common\Grav;
- use Grav\Common\Page\Collection;
- use Grav\Common\Page\Interfaces\PageCollectionInterface;
- use Grav\Common\Page\Interfaces\PageInterface;
- use Grav\Common\Page\Pages;
- use Grav\Common\Utils;
- use Grav\Common\Yaml;
- use Grav\Framework\File\Formatter\MarkdownFormatter;
- use Grav\Framework\File\Formatter\YamlFormatter;
- use Grav\Framework\Filesystem\Filesystem;
- use Grav\Framework\Flex\Interfaces\FlexCollectionInterface;
- use Grav\Framework\Flex\Interfaces\FlexIndexInterface;
- use Grav\Framework\Flex\Pages\FlexPageCollection;
- use Grav\Framework\Flex\Pages\FlexPageIndex;
- use Grav\Framework\Flex\Pages\FlexPageObject;
- use InvalidArgumentException;
- use RocketTheme\Toolbox\File\MarkdownFile;
- use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
- use RuntimeException;
- use SplFileInfo;
- use function in_array;
- use function is_array;
- use function is_string;
- use function strlen;
- /**
- * Implements PageLegacyInterface
- */
- trait PageLegacyTrait
- {
- /** @var array|null */
- private $_content_meta;
- /** @var array|null */
- private $_metadata;
- /**
- * 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|null $extension
- * @return $this
- */
- public function init(SplFileInfo $file, $extension = null)
- {
- // TODO:
- throw new RuntimeException(__METHOD__ . '(): Not Implemented');
- }
- /**
- * Gets and Sets the raw data
- *
- * @param string|null $var Raw content string
- * @return string Raw content string
- */
- public function raw($var = null): string
- {
- if (null !== $var) {
- // TODO:
- throw new RuntimeException(__METHOD__ . '(string): Not Implemented');
- }
- $storage = $this->getFlexDirectory()->getStorage();
- if (method_exists($storage, 'readRaw')) {
- return $storage->readRaw($this->getStorageKey());
- }
- $array = $this->prepareStorage();
- $formatter = new MarkdownFormatter();
- return $formatter->encode($array);
- }
- /**
- * Gets and Sets the page frontmatter
- *
- * @param string|null $var
- * @return string
- */
- public function frontmatter($var = null): string
- {
- if (null !== $var) {
- $formatter = new YamlFormatter();
- $this->setProperty('frontmatter', $var);
- $this->setProperty('header', $formatter->decode($var));
- return $var;
- }
- $storage = $this->getFlexDirectory()->getStorage();
- if (method_exists($storage, 'readFrontmatter')) {
- return $storage->readFrontmatter($this->getStorageKey());
- }
- $array = $this->prepareStorage();
- $formatter = new YamlFormatter();
- return $formatter->encode($array['header'] ?? []);
- }
- /**
- * Modify a header value directly
- *
- * @param string $key
- * @param string|array $value
- * @return void
- */
- public function modifyHeader($key, $value): void
- {
- $this->setNestedProperty("header.{$key}", $value);
- }
- /**
- * @return int
- */
- public function httpResponseCode(): int
- {
- $code = (int)$this->getNestedProperty('header.http_response_code');
- return $code ?: 200;
- }
- /**
- * @return array
- */
- public function httpHeaders(): array
- {
- $headers = [];
- $format = $this->templateFormat();
- $cache_control = $this->cacheControl();
- $expires = $this->expires();
- // Set Content-Type header.
- $headers['Content-Type'] = Utils::getMimeByExtension($format, 'text/html');
- // Calculate Expires Headers if set to > 0.
- if ($expires > 0) {
- $expires_date = gmdate('D, d M Y H:i:s', time() + $expires) . ' GMT';
- if (!$cache_control) {
- $headers['Cache-Control'] = 'max-age=' . $expires;
- }
- $headers['Expires'] = $expires_date;
- }
- // Set Cache-Control header.
- if ($cache_control) {
- $headers['Cache-Control'] = strtolower($cache_control);
- }
- // Set Last-Modified header.
- if ($this->lastModified()) {
- $last_modified_date = gmdate('D, d M Y H:i:s', $this->modified()) . ' GMT';
- $headers['Last-Modified'] = $last_modified_date;
- }
- // Calculate ETag based on the serialized page and modified time.
- if ($this->eTag()) {
- $headers['ETag'] = '1';
- }
- // Set Vary: Accept-Encoding header.
- $grav = Grav::instance();
- if ($grav['config']->get('system.pages.vary_accept_encoding', false)) {
- $headers['Vary'] = 'Accept-Encoding';
- }
- return $headers;
- }
- /**
- * Get the contentMeta array and initialize content first if it's not already
- *
- * @return array
- */
- public function contentMeta(): array
- {
- // Content meta is generated during the content is being rendered, so make sure we have done it.
- $this->content();
- return $this->_content_meta ?? [];
- }
- /**
- * Add an entry to the page's contentMeta array
- *
- * @param string $name
- * @param string $value
- * @return void
- */
- public function addContentMeta($name, $value): void
- {
- $this->_content_meta[$name] = $value;
- }
- /**
- * Return the whole contentMeta array as it currently stands
- *
- * @param string|null $name
- * @return string|array|null
- */
- public function getContentMeta($name = null)
- {
- if ($name) {
- return $this->_content_meta[$name] ?? null;
- }
- return $this->_content_meta ?? [];
- }
- /**
- * Sets the whole content meta array in one shot
- *
- * @param array $content_meta
- * @return array
- */
- public function setContentMeta($content_meta): array
- {
- return $this->_content_meta = $content_meta;
- }
- /**
- * Fires the onPageContentProcessed event, and caches the page content using a unique ID for the page
- */
- public function cachePageContent(): void
- {
- $value = [
- 'checksum' => $this->getCacheChecksum(),
- 'content' => $this->_content,
- 'content_meta' => $this->_content_meta
- ];
- $cache = $this->getCache('render');
- $key = md5($this->getCacheKey() . '-content');
- $cache->set($key, $value);
- }
- /**
- * Get file object to the page.
- *
- * @return MarkdownFile|null
- */
- public function file(): ?MarkdownFile
- {
- // TODO:
- throw new RuntimeException(__METHOD__ . '(): Not Implemented');
- }
- /**
- * 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 PageInterface $parent New parent page.
- * @return $this
- */
- public function move(PageInterface $parent)
- {
- if ($this->route() === $parent->route()) {
- throw new RuntimeException('Failed: Cannot set page parent to self');
- }
- $rawRoute = $this->rawRoute();
- if ($rawRoute && Utils::startsWith($parent->rawRoute(), $rawRoute)) {
- throw new RuntimeException('Failed: Cannot set page parent to a child of current page');
- }
- $this->storeOriginal();
- // TODO:
- throw new RuntimeException(__METHOD__ . '(): Not Implemented');
- }
- /**
- * 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 PageInterface|null $parent New parent page.
- * @return $this
- */
- public function copy(PageInterface $parent = null)
- {
- $this->storeOriginal();
- $filesystem = Filesystem::getInstance(false);
- $parentStorageKey = ltrim($filesystem->dirname("/{$this->getMasterKey()}"), '/');
- /** @var FlexPageIndex<FlexPageObject,FlexPageCollection<FlexPageObject>> $index */
- $index = $this->getFlexDirectory()->getIndex();
- if ($parent) {
- if ($parent instanceof FlexPageObject) {
- $k = $parent->getMasterKey();
- if ($k !== $parentStorageKey) {
- $parentStorageKey = $k;
- }
- } else {
- throw new RuntimeException('Cannot copy page, parent is of unknown type');
- }
- } else {
- $parent = $parentStorageKey
- ? $this->getFlexDirectory()->getObject($parentStorageKey, 'storage_key')
- : (method_exists($index, 'getRoot') ? $index->getRoot() : null);
- }
- // Find non-existing key.
- $parentKey = $parent ? $parent->getKey() : '';
- if ($this instanceof FlexPageObject) {
- $key = trim($parentKey . '/' . $this->folder(), '/');
- $key = preg_replace(static::PAGE_ORDER_PREFIX_REGEX, '', $key);
- \assert(is_string($key));
- } else {
- $key = trim($parentKey . '/' . Utils::basename($this->getKey()), '/');
- }
- if ($index->containsKey($key)) {
- $key = preg_replace('/\d+$/', '', $key);
- $i = 1;
- do {
- $i++;
- $test = "{$key}{$i}";
- } while ($index->containsKey($test));
- $key = $test;
- }
- $folder = Utils::basename($key);
- // Get the folder name.
- $order = $this->getProperty('order');
- if ($order) {
- $order++;
- }
- $parts = [];
- if ($parentStorageKey !== '') {
- $parts[] = $parentStorageKey;
- }
- $parts[] = $order ? sprintf('%02d.%s', $order, $folder) : $folder;
- // Finally update the object.
- $this->setKey($key);
- $this->setStorageKey(implode('/', $parts));
- $this->markAsCopy();
- return $this;
- }
- /**
- * Get the blueprint name for this page. Use the blueprint form field if set
- *
- * @return string
- */
- public function blueprintName(): string
- {
- if (!isset($_POST['blueprint'])) {
- return $this->template();
- }
- $post_value = $_POST['blueprint'];
- $sanitized_value = htmlspecialchars(strip_tags($post_value), ENT_QUOTES, 'UTF-8');
- return $sanitized_value ?: $this->template();
- }
- /**
- * Validate page header.
- *
- * @return void
- * @throws Exception
- */
- public function validate(): void
- {
- $blueprint = $this->getBlueprint();
- $blueprint->validate($this->toArray());
- }
- /**
- * Filter page header from illegal contents.
- *
- * @return void
- */
- public function filter(): void
- {
- $blueprints = $this->getBlueprint();
- $values = $blueprints->filter($this->toArray());
- if ($values && isset($values['header'])) {
- $this->header($values['header']);
- }
- }
- /**
- * Get unknown header variables.
- *
- * @return array
- */
- public function extra(): array
- {
- $data = $this->prepareStorage();
- return $this->getBlueprint()->extra((array)($data['header'] ?? []), 'header.');
- }
- /**
- * Convert page to an array.
- *
- * @return array
- */
- public function toArray(): array
- {
- return [
- 'header' => (array)$this->header(),
- 'content' => (string)$this->getFormValue('content')
- ];
- }
- /**
- * Convert page to YAML encoded string.
- *
- * @return string
- */
- public function toYaml(): string
- {
- return Yaml::dump($this->toArray(), 20);
- }
- /**
- * Convert page to JSON encoded string.
- *
- * @return string
- */
- public function toJson(): string
- {
- $json = json_encode($this->toArray());
- if (!is_string($json)) {
- throw new RuntimeException('Internal error');
- }
- return $json;
- }
- /**
- * Gets and sets the name field. If no name field is set, it will return 'default.md'.
- *
- * @param string|null $var The name of this page.
- * @return string The name of this page.
- */
- public function name($var = null): string
- {
- return $this->loadProperty(
- 'name',
- $var,
- function ($value) {
- $value = $value ?? $this->getMetaData()['template'] ?? 'default';
- if (!preg_match('/\.md$/', $value)) {
- $language = $this->language();
- if ($language) {
- // TODO: better language support
- $value .= ".{$language}";
- }
- $value .= '.md';
- }
- $value = preg_replace('|^modular/|', '', $value);
- $this->unsetProperty('template');
- return $value;
- }
- );
- }
- /**
- * Returns child page type.
- *
- * @return string
- */
- public function childType(): string
- {
- return (string)$this->getNestedProperty('header.child_type');
- }
- /**
- * 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|null $var the template name
- * @return string the template name
- */
- public function template($var = null): string
- {
- return $this->loadHeaderProperty(
- 'template',
- $var,
- function ($value) {
- return trim($value ?? (($this->isModule() ? 'modular/' : '') . str_replace($this->extension(), '', $this->name())));
- }
- );
- }
- /**
- * Allows a page to override the output render format, usually the extension provided in the URL.
- * (e.g. `html`, `json`, `xml`, etc).
- *
- * @param string|null $var
- * @return string
- */
- public function templateFormat($var = null): string
- {
- return $this->loadHeaderProperty(
- 'template_format',
- $var,
- function ($value) {
- return ltrim($value ?? $this->getNestedProperty('header.append_url_extension') ?: Utils::getPageFormat(), '.');
- }
- );
- }
- /**
- * Gets and sets the extension field.
- *
- * @param string|null $var
- * @return string
- */
- public function extension($var = null): string
- {
- if (null !== $var) {
- $this->setProperty('format', $var);
- }
- $language = $this->language();
- if ($language) {
- $language = '.' . $language;
- }
- $format = '.' . ($this->getProperty('format') ?? Utils::pathinfo($this->name(), PATHINFO_EXTENSION));
- return $language . $format;
- }
- /**
- * Gets and sets the expires field. If not set will return the default
- *
- * @param int|null $var The new expires value.
- * @return int The expires value
- */
- public function expires($var = null): int
- {
- return $this->loadHeaderProperty(
- 'expires',
- $var,
- static function ($value) {
- return (int)($value ?? Grav::instance()['config']->get('system.pages.expires'));
- }
- );
- }
- /**
- * Gets and sets the cache-control property. If not set it will return the default value (null)
- * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control for more details on valid options
- *
- * @param string|null $var
- * @return string|null
- */
- public function cacheControl($var = null): ?string
- {
- return $this->loadHeaderProperty(
- 'cache_control',
- $var,
- static function ($value) {
- return ((string)($value ?? Grav::instance()['config']->get('system.pages.cache_control'))) ?: null;
- }
- );
- }
- /**
- * @param bool|null $var
- * @return bool|null
- */
- public function ssl($var = null): ?bool
- {
- return $this->loadHeaderProperty(
- 'ssl',
- $var,
- static function ($value) {
- return $value ? (bool)$value : null;
- }
- );
- }
- /**
- * Returns the state of the debugger override setting for this page
- *
- * @return bool
- */
- public function debugger(): bool
- {
- return (bool)$this->getNestedProperty('header.debugger', true);
- }
- /**
- * Function to merge page metadata tags and build an array of Metadata objects
- * that can then be rendered in the page.
- *
- * @param array|null $var an Array of metadata values to set
- * @return array an Array of metadata values for the page
- */
- public function metadata($var = null): array
- {
- if ($var !== null) {
- $this->_metadata = (array)$var;
- }
- // if not metadata yet, process it.
- if (null === $this->_metadata) {
- $this->_metadata = [];
- $config = Grav::instance()['config'];
- // Set the Generator tag
- $defaultMetadata = ['generator' => 'GravCMS'];
- $siteMetadata = $config->get('site.metadata', []);
- $headerMetadata = $this->getNestedProperty('header.metadata', []);
- // Get initial metadata for the page
- $metadata = array_merge($defaultMetadata, $siteMetadata, $headerMetadata);
- $header_tag_http_equivs = ['content-type', 'default-style', 'refresh', 'x-ua-compatible', 'content-security-policy'];
- $escape = !$config->get('system.strict_mode.twig_compat', false) || $config->get('system.twig.autoescape', true);
- // Build an array of meta objects..
- foreach ($metadata as $key => $value) {
- // Lowercase the key
- $key = strtolower($key);
- // 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' => $escape ? htmlspecialchars($prop_value, ENT_QUOTES | ENT_HTML5, 'UTF-8') : $prop_value
- ];
- }
- } elseif ($value) {
- // If it this is a standard meta data type
- if (in_array($key, $header_tag_http_equivs, true)) {
- $this->_metadata[$key] = [
- 'http_equiv' => $key,
- 'content' => $escape ? htmlspecialchars($value, ENT_COMPAT, 'UTF-8') : $value
- ];
- } elseif ($key === 'charset') {
- $this->_metadata[$key] = ['charset' => $escape ? htmlspecialchars($value, ENT_QUOTES | ENT_HTML5, 'UTF-8') : $value];
- } else {
- // if it's a social metadata with separator, render as property
- $separator = strpos($key, ':');
- $hasSeparator = $separator && $separator < strlen($key) - 1;
- $entry = [
- 'content' => $escape ? htmlspecialchars($value, ENT_QUOTES | ENT_HTML5, 'UTF-8') : $value
- ];
- if ($hasSeparator && !Utils::startsWith($key, 'twitter')) {
- $entry['property'] = $key;
- } else {
- $entry['name'] = $key;
- }
- $this->_metadata[$key] = $entry;
- }
- }
- }
- }
- return $this->_metadata;
- }
- /**
- * Reset the metadata and pull from header again
- */
- public function resetMetadata(): void
- {
- $this->_metadata = null;
- }
- /**
- * Gets and sets the option to show the etag header for the page.
- *
- * @param bool|null $var show etag header
- * @return bool show etag header
- */
- public function eTag($var = null): bool
- {
- return $this->loadHeaderProperty(
- 'etag',
- $var,
- static function ($value) {
- return (bool)($value ?? Grav::instance()['config']->get('system.pages.etag'));
- }
- );
- }
- /**
- * Gets and sets the path to the .md file for this Page object.
- *
- * @param string|null $var the file path
- * @return string|null the file path
- */
- public function filePath($var = null): ?string
- {
- if (null !== $var) {
- // TODO:
- throw new RuntimeException(__METHOD__ . '(string): Not Implemented');
- }
- $folder = $this->getStorageFolder();
- if (!$folder) {
- return null;
- }
- /** @var UniformResourceLocator $locator */
- $locator = Grav::instance()['locator'];
- $folder = $locator->isStream($folder) ? $locator->getResource($folder) : GRAV_ROOT . "/{$folder}";
- return $folder . '/' . ($this->isPage() ? $this->name() : 'default.md');
- }
- /**
- * Gets the relative path to the .md file
- *
- * @return string|null The relative file path
- */
- public function filePathClean(): ?string
- {
- $folder = $this->getStorageFolder();
- if (!$folder) {
- return null;
- }
- /** @var UniformResourceLocator $locator */
- $locator = Grav::instance()['locator'];
- $folder = $locator->isStream($folder) ? $locator->getResource($folder, false) : $folder;
- return $folder . '/' . ($this->isPage() ? $this->name() : 'default.md');
- }
- /**
- * Gets and sets the order by which any sub-pages should be sorted.
- *
- * @param string|null $var the order, either "asc" or "desc"
- * @return string the order, either "asc" or "desc"
- */
- public function orderDir($var = null): string
- {
- return $this->loadHeaderProperty(
- 'order_dir',
- $var,
- static function ($value) {
- return strtolower(trim($value) ?: Grav::instance()['config']->get('system.pages.order.dir')) === 'desc' ? 'desc' : 'asc';
- }
- );
- }
- /**
- * Gets and sets the order by which the sub-pages should be sorted.
- *
- * default - is the order based on the file system, ie 01.Home before 02.Advark
- * title - is the order based on the title set in the pages
- * date - is the order based on the date set in the pages
- * folder - is the order based on the name of the folder with any numerics omitted
- *
- * @param string|null $var supported options include "default", "title", "date", and "folder"
- * @return string supported options include "default", "title", "date", and "folder"
- */
- public function orderBy($var = null): string
- {
- return $this->loadHeaderProperty(
- 'order_by',
- $var,
- static function ($value) {
- return trim($value) ?: Grav::instance()['config']->get('system.pages.order.by');
- }
- );
- }
- /**
- * Gets the manual order set in the header.
- *
- * @param string|null $var supported options include "default", "title", "date", and "folder"
- * @return array
- */
- public function orderManual($var = null): array
- {
- return $this->loadHeaderProperty(
- 'order_manual',
- $var,
- static function ($value) {
- return (array)$value;
- }
- );
- }
- /**
- * Gets and sets the maxCount field which describes how many sub-pages should be displayed if the
- * sub_pages header property is set for this page object.
- *
- * @param int|null $var the maximum number of sub-pages
- * @return int the maximum number of sub-pages
- */
- public function maxCount($var = null): int
- {
- return $this->loadHeaderProperty(
- 'max_count',
- $var,
- static function ($value) {
- return (int)($value ?? Grav::instance()['config']->get('system.pages.list.count'));
- }
- );
- }
- /**
- * Gets and sets the modular var that helps identify this page is a modular child
- *
- * @param bool|null $var true if modular_twig
- * @return bool true if modular_twig
- * @deprecated 1.7 Use ->isModule() or ->modularTwig() method instead.
- */
- public function modular($var = null): bool
- {
- user_error(__METHOD__ . '() is deprecated since Grav 1.7, use ->isModule() or ->modularTwig() method instead', E_USER_DEPRECATED);
- return $this->modularTwig($var);
- }
- /**
- * Gets and sets the modular_twig var that helps identify this page as a modular child page that will need
- * twig processing handled differently from a regular page.
- *
- * @param bool|null $var true if modular_twig
- * @return bool true if modular_twig
- */
- public function modularTwig($var = null): bool
- {
- if ($var !== null) {
- $this->setProperty('modular_twig', (bool)$var);
- if ($var) {
- $this->visible(false);
- }
- }
- return (bool)($this->getProperty('modular_twig') ?? strpos($this->slug(), '_') === 0);
- }
- /**
- * Returns children of this page.
- *
- * @return PageCollectionInterface|FlexIndexInterface
- */
- public function children()
- {
- $meta = $this->getMetaData();
- $keys = array_keys($meta['children'] ?? []);
- $prefix = $this->getMasterKey();
- if ($prefix) {
- foreach ($keys as &$key) {
- $key = $prefix . '/' . $key;
- }
- unset($key);
- }
- return $this->getFlexDirectory()->getIndex($keys, 'storage_key');
- }
- /**
- * Check to see if this item is the first in an array of sub-pages.
- *
- * @return bool True if item is first.
- */
- public function isFirst(): bool
- {
- $parent = $this->parent();
- $children = $parent ? $parent->children() : null;
- if ($children instanceof FlexCollectionInterface) {
- $children = $children->withKeyField();
- }
- return $children instanceof PageCollectionInterface ? $children->isFirst($this->getKey()) : true;
- }
- /**
- * Check to see if this item is the last in an array of sub-pages.
- *
- * @return bool True if item is last
- */
- public function isLast(): bool
- {
- $parent = $this->parent();
- $children = $parent ? $parent->children() : null;
- if ($children instanceof FlexCollectionInterface) {
- $children = $children->withKeyField();
- }
- return $children instanceof PageCollectionInterface ? $children->isLast($this->getKey()) : true;
- }
- /**
- * Gets the previous sibling based on current position.
- *
- * @return PageInterface|false the previous Page item
- */
- public function prevSibling()
- {
- return $this->adjacentSibling(-1);
- }
- /**
- * Gets the next sibling based on current position.
- *
- * @return PageInterface|false the next Page item
- */
- public function nextSibling()
- {
- return $this->adjacentSibling(1);
- }
- /**
- * Returns the adjacent sibling based on a direction.
- *
- * @param int $direction either -1 or +1
- * @return PageInterface|false the sibling page
- */
- public function adjacentSibling($direction = 1)
- {
- $parent = $this->parent();
- $children = $parent ? $parent->children() : null;
- if ($children instanceof FlexCollectionInterface) {
- $children = $children->withKeyField();
- }
- if ($children instanceof PageCollectionInterface) {
- $child = $children->adjacentSibling($this->getKey(), $direction);
- if ($child instanceof PageInterface) {
- return $child;
- }
- }
- return false;
- }
- /**
- * Helper method to return an ancestor page.
- *
- * @param string|null $lookup Name of the parent folder
- * @return PageInterface|null page you were looking for if it exists
- */
- public function ancestor($lookup = null)
- {
- /** @var Pages $pages */
- $pages = Grav::instance()['pages'];
- return $pages->ancestor($this->getProperty('parent_route'), $lookup);
- }
- /**
- * Helper method to return an ancestor page to inherit from. The current
- * page object is returned.
- *
- * @param string $field Name of the parent folder
- * @return PageInterface|null
- */
- public function inherited($field)
- {
- [$inherited, $currentParams] = $this->getInheritedParams($field);
- $this->modifyHeader($field, $currentParams);
- return $inherited;
- }
- /**
- * Helper method to return an ancestor field only to inherit from. The
- * first occurrence of an ancestor field will be returned if at all.
- *
- * @param string $field Name of the parent folder
- * @return array
- */
- public function inheritedField($field): array
- {
- [, $currentParams] = $this->getInheritedParams($field);
- return $currentParams;
- }
- /**
- * Method that contains shared logic for inherited() and inheritedField()
- *
- * @param string $field Name of the parent folder
- * @return array
- */
- protected function getInheritedParams($field): array
- {
- /** @var Pages $pages */
- $pages = Grav::instance()['pages'];
- $inherited = $pages->inherited($this->getProperty('parent_route'), $field);
- $inheritedParams = $inherited ? (array)$inherited->value('header.' . $field) : [];
- $currentParams = (array)$this->getFormValue('header.' . $field);
- if ($inheritedParams && is_array($inheritedParams)) {
- $currentParams = array_replace_recursive($inheritedParams, $currentParams);
- }
- return [$inherited, $currentParams];
- }
- /**
- * Helper method to return a page.
- *
- * @param string $url the url of the page
- * @param bool $all
- * @return PageInterface|null page you were looking for if it exists
- */
- public function find($url, $all = false)
- {
- /** @var Pages $pages */
- $pages = Grav::instance()['pages'];
- return $pages->find($url, $all);
- }
- /**
- * Get a collection of pages in the current context.
- *
- * @param string|array $params
- * @param bool $pagination
- * @return PageCollectionInterface|Collection
- * @throws InvalidArgumentException
- */
- public function collection($params = 'content', $pagination = true)
- {
- if (is_string($params)) {
- // Look into a page header field.
- $params = (array)$this->getFormValue('header.' . $params);
- } elseif (!is_array($params)) {
- throw new InvalidArgumentException('Argument should be either header variable name or array of parameters');
- }
- if (!$pagination) {
- $params['pagination'] = false;
- }
- $context = [
- 'pagination' => $pagination,
- 'self' => $this
- ];
- /** @var Pages $pages */
- $pages = Grav::instance()['pages'];
- return $pages->getCollection($params, $context);
- }
- /**
- * @param string|array $value
- * @param bool $only_published
- * @return PageCollectionInterface|Collection
- */
- public function evaluate($value, $only_published = true)
- {
- $params = [
- 'items' => $value,
- 'published' => $only_published
- ];
- $context = [
- 'event' => false,
- 'pagination' => false,
- 'url_taxonomy_filters' => false,
- 'self' => $this
- ];
- /** @var Pages $pages */
- $pages = Grav::instance()['pages'];
- return $pages->getCollection($params, $context);
- }
- /**
- * Returns whether or not the current folder exists
- *
- * @return bool
- */
- public function folderExists(): bool
- {
- return $this->exists() || is_dir($this->getStorageFolder() ?? '');
- }
- /**
- * Gets the action.
- *
- * @return string|null The Action string.
- */
- public function getAction(): ?string
- {
- $meta = $this->getMetaData();
- if (!empty($meta['copy'])) {
- return 'copy';
- }
- if (isset($meta['storage_key']) && $this->getStorageKey() !== $meta['storage_key']) {
- return 'move';
- }
- return null;
- }
- }
|