repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Twig/TwigExtension.php | system/src/Grav/Common/Twig/TwigExtension.php | <?php
/**
* @package Grav\Common\Twig
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Twig;
use Grav\Common\Twig\Extension\GravExtension;
/**
* Class TwigExtension
* @package Grav\Common\Twig
* @deprecated 1.7 Use GravExtension instead
*/
class TwigExtension extends GravExtension
{
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Twig/Extension/GravExtension.php | system/src/Grav/Common/Twig/Extension/GravExtension.php | <?php
/**
* @package Grav\Common\Twig
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Twig\Extension;
use CallbackFilterIterator;
use Cron\CronExpression;
use Grav\Common\Config\Config;
use Grav\Common\Data\Data;
use Grav\Common\Debugger;
use Grav\Common\Grav;
use Grav\Common\Inflector;
use Grav\Common\Language\Language;
use Grav\Common\Page\Collection;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Common\Page\Media;
use Grav\Common\Scheduler\Cron;
use Grav\Common\Security;
use Grav\Common\Twig\TokenParser\TwigTokenParserCache;
use Grav\Common\Twig\TokenParser\TwigTokenParserLink;
use Grav\Common\Twig\TokenParser\TwigTokenParserRender;
use Grav\Common\Twig\TokenParser\TwigTokenParserScript;
use Grav\Common\Twig\TokenParser\TwigTokenParserStyle;
use Grav\Common\Twig\TokenParser\TwigTokenParserSwitch;
use Grav\Common\Twig\TokenParser\TwigTokenParserThrow;
use Grav\Common\Twig\TokenParser\TwigTokenParserTryCatch;
use Grav\Common\Twig\TokenParser\TwigTokenParserMarkdown;
use Grav\Common\User\Interfaces\UserInterface;
use Grav\Common\Utils;
use Grav\Common\Yaml;
use Grav\Common\Helpers\Base32;
use Grav\Framework\Flex\Interfaces\FlexObjectInterface;
use Grav\Framework\Psr7\Response;
use Iterator;
use JsonSerializable;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use Traversable;
use Twig\Environment;
use Twig\Error\RuntimeError;
use Twig\Extension\AbstractExtension;
use Twig\Extension\GlobalsInterface;
use Twig\Loader\FilesystemLoader;
use Twig\Markup;
use Twig\TwigFilter;
use Twig\TwigFunction;
use function array_slice;
use function count;
use function func_get_args;
use function func_num_args;
use function get_class;
use function gettype;
use function in_array;
use function is_array;
use function is_bool;
use function is_float;
use function is_int;
use function is_numeric;
use function is_object;
use function is_scalar;
use function is_string;
use function strlen;
/**
* Class GravExtension
* @package Grav\Common\Twig\Extension
*/
class GravExtension extends AbstractExtension implements GlobalsInterface
{
/** @var Grav */
protected $grav;
/** @var Debugger|null */
protected $debugger;
/** @var Config */
protected $config;
/**
* GravExtension constructor.
*/
public function __construct()
{
$this->grav = Grav::instance();
$this->debugger = $this->grav['debugger'] ?? null;
$this->config = $this->grav['config'];
}
/**
* Register some standard globals
*
* @return array
*/
public function getGlobals(): array
{
return [
'grav' => $this->grav,
];
}
/**
* Return a list of all filters.
*
* @return array
*/
public function getFilters(): array
{
return [
new TwigFilter('*ize', [$this, 'inflectorFilter']),
new TwigFilter('absolute_url', [$this, 'absoluteUrlFilter']),
new TwigFilter('contains', [$this, 'containsFilter']),
new TwigFilter('chunk_split', [$this, 'chunkSplitFilter']),
new TwigFilter('nicenumber', [$this, 'niceNumberFunc']),
new TwigFilter('nicefilesize', [$this, 'niceFilesizeFunc']),
new TwigFilter('nicetime', [$this, 'nicetimeFunc']),
new TwigFilter('defined', [$this, 'definedDefaultFilter']),
new TwigFilter('ends_with', [$this, 'endsWithFilter']),
new TwigFilter('fieldName', [$this, 'fieldNameFilter']),
new TwigFilter('parent_field', [$this, 'fieldParentFilter']),
new TwigFilter('ksort', [$this, 'ksortFilter']),
new TwigFilter('ltrim', [$this, 'ltrimFilter']),
new TwigFilter('markdown', [$this, 'markdownFunction'], ['needs_context' => true, 'is_safe' => ['html']]),
new TwigFilter('md5', [$this, 'md5Filter']),
new TwigFilter('base32_encode', [$this, 'base32EncodeFilter']),
new TwigFilter('base32_decode', [$this, 'base32DecodeFilter']),
new TwigFilter('base64_encode', [$this, 'base64EncodeFilter']),
new TwigFilter('base64_decode', [$this, 'base64DecodeFilter']),
new TwigFilter('randomize', [$this, 'randomizeFilter']),
new TwigFilter('modulus', [$this, 'modulusFilter']),
new TwigFilter('rtrim', [$this, 'rtrimFilter']),
new TwigFilter('pad', [$this, 'padFilter']),
new TwigFilter('regex_replace', [$this, 'regexReplace']),
new TwigFilter('safe_email', [$this, 'safeEmailFilter'], ['is_safe' => ['html']]),
new TwigFilter('safe_truncate', [Utils::class, 'safeTruncate']),
new TwigFilter('safe_truncate_html', [Utils::class, 'safeTruncateHTML']),
new TwigFilter('sort_by_key', [$this, 'sortByKeyFilter']),
new TwigFilter('starts_with', [$this, 'startsWithFilter']),
new TwigFilter('truncate', [Utils::class, 'truncate']),
new TwigFilter('truncate_html', [Utils::class, 'truncateHTML']),
new TwigFilter('json_decode', [$this, 'jsonDecodeFilter']),
new TwigFilter('array_unique', 'array_unique'),
new TwigFilter('basename', 'basename'),
new TwigFilter('dirname', 'dirname'),
new TwigFilter('print_r', [$this, 'print_r']),
new TwigFilter('yaml_encode', [$this, 'yamlEncodeFilter']),
new TwigFilter('yaml_decode', [$this, 'yamlDecodeFilter']),
new TwigFilter('nicecron', [$this, 'niceCronFilter']),
new TwigFilter('replace_last', [$this, 'replaceLastFilter']),
// Translations
new TwigFilter('t', [$this, 'translate'], ['needs_environment' => true]),
new TwigFilter('tl', [$this, 'translateLanguage']),
new TwigFilter('ta', [$this, 'translateArray']),
// Casting values
new TwigFilter('string', [$this, 'stringFilter']),
new TwigFilter('int', [$this, 'intFilter'], ['is_safe' => ['all']]),
new TwigFilter('bool', [$this, 'boolFilter']),
new TwigFilter('float', [$this, 'floatFilter'], ['is_safe' => ['all']]),
new TwigFilter('array', [$this, 'arrayFilter']),
new TwigFilter('yaml', [$this, 'yamlFilter']),
// Object Types
new TwigFilter('get_type', [$this, 'getTypeFunc']),
new TwigFilter('of_type', [$this, 'ofTypeFunc']),
// PHP methods
new TwigFilter('count', 'count'),
new TwigFilter('array_diff', 'array_diff'),
// Security fixes
new TwigFilter('filter', [$this, 'filterFunc'], ['needs_environment' => true]),
new TwigFilter('map', [$this, 'mapFunc'], ['needs_environment' => true]),
new TwigFilter('reduce', [$this, 'reduceFunc'], ['needs_environment' => true]),
];
}
/**
* Return a list of all functions.
*
* @return array
*/
public function getFunctions(): array
{
return [
new TwigFunction('array', [$this, 'arrayFilter']),
new TwigFunction('array_key_value', [$this, 'arrayKeyValueFunc']),
new TwigFunction('array_key_exists', 'array_key_exists'),
new TwigFunction('array_unique', 'array_unique'),
new TwigFunction('array_intersect', [$this, 'arrayIntersectFunc']),
new TwigFunction('array_diff', 'array_diff'),
new TwigFunction('authorize', [$this, 'authorize']),
new TwigFunction('debug', [$this, 'dump'], ['needs_context' => true, 'needs_environment' => true]),
new TwigFunction('dump', [$this, 'dump'], ['needs_context' => true, 'needs_environment' => true]),
new TwigFunction('vardump', [$this, 'vardumpFunc']),
new TwigFunction('print_r', [$this, 'print_r']),
new TwigFunction('http_response_code', 'http_response_code'),
new TwigFunction('evaluate', [$this, 'evaluateStringFunc'], ['needs_context' => true]),
new TwigFunction('evaluate_twig', [$this, 'evaluateTwigFunc'], ['needs_context' => true]),
new TwigFunction('gist', [$this, 'gistFunc']),
new TwigFunction('nonce_field', [$this, 'nonceFieldFunc']),
new TwigFunction('pathinfo', 'pathinfo'),
new TwigFunction('parseurl', 'parse_url'),
new TwigFunction('random_string', [$this, 'randomStringFunc']),
new TwigFunction('repeat', [$this, 'repeatFunc']),
new TwigFunction('regex_replace', [$this, 'regexReplace']),
new TwigFunction('regex_filter', [$this, 'regexFilter']),
new TwigFunction('regex_match', [$this, 'regexMatch']),
new TwigFunction('regex_split', [$this, 'regexSplit']),
new TwigFunction('string', [$this, 'stringFilter']),
new TwigFunction('url', [$this, 'urlFunc']),
new TwigFunction('json_decode', [$this, 'jsonDecodeFilter']),
new TwigFunction('get_cookie', [$this, 'getCookie']),
new TwigFunction('redirect_me', [$this, 'redirectFunc']),
new TwigFunction('range', [$this, 'rangeFunc']),
new TwigFunction('isajaxrequest', [$this, 'isAjaxFunc']),
new TwigFunction('exif', [$this, 'exifFunc']),
new TwigFunction('media_directory', [$this, 'mediaDirFunc']),
new TwigFunction('body_class', [$this, 'bodyClassFunc'], ['needs_context' => true]),
new TwigFunction('theme_var', [$this, 'themeVarFunc'], ['needs_context' => true]),
new TwigFunction('header_var', [$this, 'pageHeaderVarFunc'], ['needs_context' => true]),
new TwigFunction('read_file', [$this, 'readFileFunc']),
new TwigFunction('nicenumber', [$this, 'niceNumberFunc']),
new TwigFunction('nicefilesize', [$this, 'niceFilesizeFunc']),
new TwigFunction('nicetime', [$this, 'nicetimeFunc']),
new TwigFunction('cron', [$this, 'cronFunc']),
new TwigFunction('svg_image', [$this, 'svgImageFunction']),
new TwigFunction('xss', [$this, 'xssFunc']),
new TwigFunction('unique_id', [$this, 'uniqueId']),
// Translations
new TwigFunction('t', [$this, 'translate'], ['needs_environment' => true]),
new TwigFunction('tl', [$this, 'translateLanguage']),
new TwigFunction('ta', [$this, 'translateArray']),
// Object Types
new TwigFunction('get_type', [$this, 'getTypeFunc']),
new TwigFunction('of_type', [$this, 'ofTypeFunc']),
// PHP methods
new TwigFunction('is_numeric', 'is_numeric'),
new TwigFunction('is_iterable', 'is_iterable'),
new TwigFunction('is_countable', 'is_countable'),
new TwigFunction('is_null', 'is_null'),
new TwigFunction('is_string', 'is_string'),
new TwigFunction('is_array', 'is_array'),
new TwigFunction('is_object', 'is_object'),
new TwigFunction('count', 'count'),
new TwigFunction('array_diff', 'array_diff'),
new TwigFunction('parse_url', 'parse_url'),
// Security fixes
new TwigFunction('filter', [$this, 'filterFunc'], ['needs_environment' => true]),
new TwigFunction('map', [$this, 'mapFunc'], ['needs_environment' => true]),
new TwigFunction('reduce', [$this, 'reduceFunc'], ['needs_environment' => true]),
];
}
/**
* @return array
*/
public function getTokenParsers(): array
{
return [
new TwigTokenParserRender(),
new TwigTokenParserThrow(),
new TwigTokenParserTryCatch(),
new TwigTokenParserScript(),
new TwigTokenParserStyle(),
new TwigTokenParserLink(),
new TwigTokenParserMarkdown(),
new TwigTokenParserSwitch(),
new TwigTokenParserCache(),
];
}
/**
* @param mixed $var
* @return string
*/
public function print_r($var)
{
return print_r($var, true);
}
/**
* Filters field name by changing dot notation into array notation.
*
* @param string $str
* @return string
*/
public function fieldNameFilter($str)
{
$path = explode('.', rtrim($str, '.'));
return array_shift($path) . ($path ? '[' . implode('][', $path) . ']' : '');
}
/**
* Filters field name by changing dot notation into array notation.
*
* @param string $str
* @return string
*/
public function fieldParentFilter($str)
{
$path = explode('.', rtrim($str, '.'));
array_pop($path);
return implode('.', $path);
}
/**
* Protects email address.
*
* @param string $str
* @return string
*/
public function safeEmailFilter($str)
{
static $list = [
'"' => '"',
"'" => ''',
'&' => '&',
'<' => '<',
'>' => '>',
'@' => '@'
];
$characters = mb_str_split($str, 1, 'UTF-8');
$encoded = '';
foreach ($characters as $chr) {
$encoded .= $list[$chr] ?? (random_int(0, 1) ? '&#' . mb_ord($chr) . ';' : $chr);
}
return $encoded;
}
/**
* Returns array in a random order.
*
* @param array|Traversable $original
* @param int $offset Can be used to return only slice of the array.
* @return array
*/
public function randomizeFilter($original, $offset = 0)
{
if ($original instanceof Traversable) {
$original = iterator_to_array($original, false);
}
if (!is_array($original)) {
return $original;
}
$sorted = [];
$random = array_slice($original, $offset);
shuffle($random);
$sizeOf = count($original);
for ($x = 0; $x < $sizeOf; $x++) {
if ($x < $offset) {
$sorted[] = $original[$x];
} else {
$sorted[] = array_shift($random);
}
}
return $sorted;
}
/**
* Returns the modulus of an integer
*
* @param string|int $number
* @param int $divider
* @param array|null $items array of items to select from to return
* @return int
*/
public function modulusFilter($number, $divider, $items = null)
{
if (is_string($number)) {
$number = strlen($number);
}
$remainder = $number % $divider;
if (is_array($items)) {
return $items[$remainder] ?? $items[0];
}
return $remainder;
}
/**
* Inflector supports following notations:
*
* `{{ 'person'|pluralize }} => people`
* `{{ 'shoes'|singularize }} => shoe`
* `{{ 'welcome page'|titleize }} => "Welcome Page"`
* `{{ 'send_email'|camelize }} => SendEmail`
* `{{ 'CamelCased'|underscorize }} => camel_cased`
* `{{ 'Something Text'|hyphenize }} => something-text`
* `{{ 'something_text_to_read'|humanize }} => "Something text to read"`
* `{{ '181'|monthize }} => 5`
* `{{ '10'|ordinalize }} => 10th`
*
* @param string $action
* @param string $data
* @param int|null $count
* @return string
*/
public function inflectorFilter($action, $data, $count = null)
{
$action .= 'ize';
/** @var Inflector $inflector */
$inflector = $this->grav['inflector'];
if (in_array(
$action,
['titleize', 'camelize', 'underscorize', 'hyphenize', 'humanize', 'ordinalize', 'monthize'],
true
)) {
return $inflector->{$action}($data);
}
if (in_array($action, ['pluralize', 'singularize'], true)) {
return $count ? $inflector->{$action}($data, $count) : $inflector->{$action}($data);
}
return $data;
}
/**
* Return MD5 hash from the input.
*
* @param string $str
* @return string
*/
public function md5Filter($str)
{
return md5($str);
}
/**
* Return Base32 encoded string
*
* @param string $str
* @return string
*/
public function base32EncodeFilter($str)
{
return Base32::encode($str);
}
/**
* Return Base32 decoded string
*
* @param string $str
* @return string
*/
public function base32DecodeFilter($str)
{
return Base32::decode($str);
}
/**
* Return Base64 encoded string
*
* @param string $str
* @return string
*/
public function base64EncodeFilter($str)
{
return base64_encode((string) $str);
}
/**
* Return Base64 decoded string
*
* @param string $str
* @return string|false
*/
public function base64DecodeFilter($str)
{
return base64_decode($str);
}
/**
* Sorts a collection by key
*
* @param array $input
* @param string $filter
* @param int $direction
* @param int $sort_flags
* @return array
*/
public function sortByKeyFilter($input, $filter, $direction = SORT_ASC, $sort_flags = SORT_REGULAR)
{
return Utils::sortArrayByKey($input, $filter, $direction, $sort_flags);
}
/**
* Return ksorted collection.
*
* @param array|null $array
* @return array
*/
public function ksortFilter($array)
{
if (null === $array) {
$array = [];
}
ksort($array);
return $array;
}
/**
* Wrapper for chunk_split() function
*
* @param string $value
* @param int $chars
* @param string $split
* @return string
*/
public function chunkSplitFilter($value, $chars, $split = '-')
{
return chunk_split($value, $chars, $split);
}
/**
* determine if a string contains another
*
* @param string $haystack
* @param string $needle
* @return string|bool
* @todo returning $haystack here doesn't make much sense
*/
public function containsFilter($haystack, $needle)
{
if (empty($needle)) {
return $haystack;
}
return (strpos($haystack, (string) $needle) !== false);
}
/**
* Gets a human readable output for cron syntax
*
* @param string $at
* @return string
*/
public function niceCronFilter($at)
{
$cron = new Cron($at);
return $cron->getText('en');
}
/**
* @param string|mixed $str
* @param string $search
* @param string $replace
* @return string|mixed
*/
public function replaceLastFilter($str, $search, $replace)
{
if (is_string($str) && ($pos = mb_strrpos($str, $search)) !== false) {
$str = mb_substr($str, 0, $pos) . $replace . mb_substr($str, $pos + mb_strlen($search));
}
return $str;
}
/**
* Get Cron object for a crontab 'at' format
*
* @param string $at
* @return CronExpression
*/
public function cronFunc($at)
{
return CronExpression::factory($at);
}
/**
* displays a facebook style 'time ago' formatted date/time
*
* @param string $date
* @param bool $long_strings
* @param bool $show_tense
* @return string
*/
public function nicetimeFunc($date, $long_strings = true, $show_tense = true)
{
if (empty($date)) {
return $this->grav['language']->translate('GRAV.NICETIME.NO_DATE_PROVIDED');
}
if ($long_strings) {
$periods = [
'NICETIME.SECOND',
'NICETIME.MINUTE',
'NICETIME.HOUR',
'NICETIME.DAY',
'NICETIME.WEEK',
'NICETIME.MONTH',
'NICETIME.YEAR',
'NICETIME.DECADE'
];
} else {
$periods = [
'NICETIME.SEC',
'NICETIME.MIN',
'NICETIME.HR',
'NICETIME.DAY',
'NICETIME.WK',
'NICETIME.MO',
'NICETIME.YR',
'NICETIME.DEC'
];
}
$lengths = ['60', '60', '24', '7', '4.35', '12', '10'];
$now = time();
// check if unix timestamp
if ((string)(int)$date === (string)$date) {
$unix_date = $date;
} else {
$unix_date = strtotime($date);
}
// check validity of date
if (empty($unix_date)) {
return $this->grav['language']->translate('GRAV.NICETIME.BAD_DATE');
}
// is it future date or past date
if ($now > $unix_date) {
$difference = $now - $unix_date;
$tense = $this->grav['language']->translate('GRAV.NICETIME.AGO');
} elseif ($now == $unix_date) {
$difference = $now - $unix_date;
$tense = $this->grav['language']->translate('GRAV.NICETIME.JUST_NOW');
} else {
$difference = $unix_date - $now;
$tense = $this->grav['language']->translate('GRAV.NICETIME.FROM_NOW');
}
for ($j = 0; $difference >= $lengths[$j] && $j < count($lengths) - 1; $j++) {
$difference /= $lengths[$j];
}
$difference = round($difference);
if ($difference != 1) {
$periods[$j] .= '_PLURAL';
}
if ($this->grav['language']->getTranslation(
$this->grav['language']->getLanguage(),
$periods[$j] . '_MORE_THAN_TWO'
)
) {
if ($difference > 2) {
$periods[$j] .= '_MORE_THAN_TWO';
}
}
$periods[$j] = $this->grav['language']->translate('GRAV.'.$periods[$j]);
if ($now == $unix_date) {
return $tense;
}
$time = "{$difference} {$periods[$j]}";
$time .= $show_tense ? " {$tense}" : '';
return $time;
}
/**
* Allow quick check of a string for XSS Vulnerabilities
*
* @param string|array $data
* @return bool|string|array
*/
public function xssFunc($data)
{
if (!is_array($data)) {
return Security::detectXss($data);
}
$results = Security::detectXssFromArray($data);
$results_parts = array_map(static function ($value, $key) {
return $key.': \''.$value . '\'';
}, array_values($results), array_keys($results));
return implode(', ', $results_parts);
}
/**
* Generates a random string with configurable length, prefix and suffix.
* Unlike the built-in `uniqid()`, this string is non-conflicting and safe
*
* @param int $length
* @param array $options
* @return string
* @throws \Exception
*/
public function uniqueId(int $length = 9, array $options = ['prefix' => '', 'suffix' => '']): string
{
return Utils::uniqueId($length, $options);
}
/**
* @param string $string
* @return string
*/
public function absoluteUrlFilter($string)
{
$url = $this->grav['uri']->base();
$string = preg_replace('/((?:href|src) *= *[\'"](?!(http|ftp)))/i', "$1$url", $string);
return $string;
}
/**
* @param array $context
* @param string $string
* @param bool $block Block or Line processing
* @return string
*/
public function markdownFunction($context, $string, $block = true)
{
$page = $context['page'] ?? null;
return Utils::processMarkdown($string, $block, $page);
}
/**
* @param string $haystack
* @param string $needle
* @return bool
*/
public function startsWithFilter($haystack, $needle)
{
return Utils::startsWith($haystack, $needle);
}
/**
* @param string $haystack
* @param string $needle
* @return bool
*/
public function endsWithFilter($haystack, $needle)
{
return Utils::endsWith($haystack, $needle);
}
/**
* @param mixed $value
* @param null $default
* @return mixed|null
*/
public function definedDefaultFilter($value, $default = null)
{
return $value ?? $default;
}
/**
* @param string $value
* @param string|null $chars
* @return string
*/
public function rtrimFilter($value, $chars = null)
{
return null !== $chars ? rtrim($value, $chars) : rtrim($value);
}
/**
* @param string $value
* @param string|null $chars
* @return string
*/
public function ltrimFilter($value, $chars = null)
{
return null !== $chars ? ltrim($value, $chars) : ltrim($value);
}
/**
* Returns a string from a value. If the value is array, return it json encoded
*
* @param mixed $value
* @return string
*/
public function stringFilter($value)
{
// Format the array as a string
if (is_array($value)) {
return json_encode($value);
}
// Boolean becomes '1' or '0'
if (is_bool($value)) {
$value = (int)$value;
}
// Cast the other values to string.
return (string)$value;
}
/**
* Casts input to int.
*
* @param mixed $input
* @return int
*/
public function intFilter($input)
{
return (int) $input;
}
/**
* Casts input to bool.
*
* @param mixed $input
* @return bool
*/
public function boolFilter($input)
{
return (bool) $input;
}
/**
* Casts input to float.
*
* @param mixed $input
* @return float
*/
public function floatFilter($input)
{
return (float) $input;
}
/**
* Casts input to array.
*
* @param mixed $input
* @return array
*/
public function arrayFilter($input)
{
if (is_array($input)) {
return $input;
}
if (is_object($input)) {
if (method_exists($input, 'toArray')) {
return $input->toArray();
}
if ($input instanceof Iterator) {
return iterator_to_array($input);
}
}
return (array)$input;
}
/**
* @param array|object $value
* @param int|null $inline
* @param int|null $indent
* @return string
*/
public function yamlFilter($value, $inline = null, $indent = null): string
{
return Yaml::dump($value, $inline, $indent);
}
/**
* @param Environment $twig
* @return string
*/
public function translate(Environment $twig, ...$args)
{
// If admin and tu filter provided, use it
if (isset($this->grav['admin'])) {
$numargs = count($args);
$lang = null;
if (($numargs === 3 && is_array($args[1])) || ($numargs === 2 && !is_array($args[1]))) {
$lang = array_pop($args);
/** @var Language $language */
$language = $this->grav['language'];
if (is_string($lang) && !$language->getLanguageCode($lang)) {
$args[] = $lang;
$lang = null;
}
} elseif ($numargs === 2 && is_array($args[1])) {
$subs = array_pop($args);
$args = array_merge($args, $subs);
}
return $this->grav['admin']->translate($args, $lang);
}
$translation = $this->grav['language']->translate($args);
if ($this->config->get('system.languages.debug', false)) {
$debugger = $this->grav['debugger'];
$debugger->addMessage("$args[0] -> $translation", 'debug');
}
return $translation;
}
/**
* Translate Strings
*
* @param string|array $args
* @param array|null $languages
* @param bool $array_support
* @param bool $html_out
* @return string
*/
public function translateLanguage($args, array $languages = null, $array_support = false, $html_out = false)
{
/** @var Language $language */
$language = $this->grav['language'];
return $language->translate($args, $languages, $array_support, $html_out);
}
/**
* @param string $key
* @param string $index
* @param array|null $lang
* @return string
*/
public function translateArray($key, $index, $lang = null)
{
/** @var Language $language */
$language = $this->grav['language'];
return $language->translateArray($key, $index, $lang);
}
/**
* Repeat given string x times.
*
* @param string $input
* @param int $multiplier
*
* @return string
*/
public function repeatFunc($input, $multiplier)
{
return str_repeat($input, (int) $multiplier);
}
/**
* Return URL to the resource.
*
* @example {{ url('theme://images/logo.png')|default('http://www.placehold.it/150x100/f4f4f4') }}
*
* @param string $input Resource to be located.
* @param bool $domain True to include domain name.
* @param bool $failGracefully If true, return URL even if the file does not exist.
* @return string|false Returns url to the resource or null if resource was not found.
*/
public function urlFunc($input, $domain = false, $failGracefully = false)
{
return Utils::url($input, $domain, $failGracefully);
}
/**
* This function will evaluate Twig $twig through the $environment, and return its results.
*
* @param array $context
* @param string $twig
* @return mixed
*/
public function evaluateTwigFunc($context, $twig)
{
$loader = new FilesystemLoader('.');
$env = new Environment($loader);
$env->addExtension($this);
$template = $env->createTemplate($twig);
return $template->render($context);
}
/**
* This function will evaluate a $string through the $environment, and return its results.
*
* @param array $context
* @param string $string
* @return mixed
*/
public function evaluateStringFunc($context, $string)
{
return $this->evaluateTwigFunc($context, "{{ $string }}");
}
/**
* Based on Twig\Extension\Debug / twig_var_dump
* (c) 2011 Fabien Potencier
*
* @param Environment $env
* @param array $context
*/
public function dump(Environment $env, $context)
{
if (!$env->isDebug() || !$this->debugger) {
return;
}
$count = func_num_args();
if (2 === $count) {
$data = [];
foreach ($context as $key => $value) {
if (is_object($value)) {
if (method_exists($value, 'toArray')) {
$data[$key] = $value->toArray();
} else {
$data[$key] = 'Object (' . get_class($value) . ')';
}
} else {
$data[$key] = $value;
}
}
$this->debugger->addMessage($data, 'debug');
} else {
for ($i = 2; $i < $count; $i++) {
$var = func_get_arg($i);
$this->debugger->addMessage($var, 'debug');
}
}
}
/**
* Output a Gist
*
* @param string $id
* @param string|false $file
* @return string
*/
public function gistFunc($id, $file = false)
{
$url = 'https://gist.github.com/' . $id . '.js';
if ($file) {
$url .= '?file=' . $file;
}
return '<script src="' . $url . '"></script>';
}
/**
* Generate a random string
*
* @param int $count
* @return string
*/
public function randomStringFunc($count = 5)
{
return Utils::generateRandomString($count);
}
/**
* Pad a string to a certain length with another string
*
* @param string $input
* @param int $pad_length
* @param string $pad_string
* @param int $pad_type
* @return string
*/
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | true |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Twig/Extension/FilesystemExtension.php | system/src/Grav/Common/Twig/Extension/FilesystemExtension.php | <?php
/**
* @package Grav\Common\Twig
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Twig\Extension;
use Grav\Common\Grav;
use Grav\Common\Utils;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;
/**
* Class FilesystemExtension
* @package Grav\Common\Twig\Extension
*/
class FilesystemExtension extends AbstractExtension
{
/** @var UniformResourceLocator */
private $locator;
public function __construct()
{
$this->locator = Grav::instance()['locator'];
}
/**
* @return TwigFilter[]
*/
public function getFilters()
{
return [
new TwigFilter('file_exists', [$this, 'file_exists']),
new TwigFilter('fileatime', [$this, 'fileatime']),
new TwigFilter('filectime', [$this, 'filectime']),
new TwigFilter('filemtime', [$this, 'filemtime']),
new TwigFilter('filesize', [$this, 'filesize']),
new TwigFilter('filetype', [$this, 'filetype']),
new TwigFilter('is_dir', [$this, 'is_dir']),
new TwigFilter('is_file', [$this, 'is_file']),
new TwigFilter('is_link', [$this, 'is_link']),
new TwigFilter('is_readable', [$this, 'is_readable']),
new TwigFilter('is_writable', [$this, 'is_writable']),
new TwigFilter('is_writeable', [$this, 'is_writable']),
new TwigFilter('lstat', [$this, 'lstat']),
new TwigFilter('getimagesize', [$this, 'getimagesize']),
new TwigFilter('exif_read_data', [$this, 'exif_read_data']),
new TwigFilter('read_exif_data', [$this, 'exif_read_data']),
new TwigFilter('exif_imagetype', [$this, 'exif_imagetype']),
new TwigFilter('hash_file', [$this, 'hash_file']),
new TwigFilter('hash_hmac_file', [$this, 'hash_hmac_file']),
new TwigFilter('md5_file', [$this, 'md5_file']),
new TwigFilter('sha1_file', [$this, 'sha1_file']),
new TwigFilter('get_meta_tags', [$this, 'get_meta_tags']),
new TwigFilter('pathinfo', [$this, 'pathinfo']),
];
}
/**
* Return a list of all functions.
*
* @return TwigFunction[]
*/
public function getFunctions()
{
return [
new TwigFunction('file_exists', [$this, 'file_exists']),
new TwigFunction('fileatime', [$this, 'fileatime']),
new TwigFunction('filectime', [$this, 'filectime']),
new TwigFunction('filemtime', [$this, 'filemtime']),
new TwigFunction('filesize', [$this, 'filesize']),
new TwigFunction('filetype', [$this, 'filetype']),
new TwigFunction('is_dir', [$this, 'is_dir']),
new TwigFunction('is_file', [$this, 'is_file']),
new TwigFunction('is_link', [$this, 'is_link']),
new TwigFunction('is_readable', [$this, 'is_readable']),
new TwigFunction('is_writable', [$this, 'is_writable']),
new TwigFunction('is_writeable', [$this, 'is_writable']),
new TwigFunction('lstat', [$this, 'lstat']),
new TwigFunction('getimagesize', [$this, 'getimagesize']),
new TwigFunction('exif_read_data', [$this, 'exif_read_data']),
new TwigFunction('read_exif_data', [$this, 'exif_read_data']),
new TwigFunction('exif_imagetype', [$this, 'exif_imagetype']),
new TwigFunction('hash_file', [$this, 'hash_file']),
new TwigFunction('hash_hmac_file', [$this, 'hash_hmac_file']),
new TwigFunction('md5_file', [$this, 'md5_file']),
new TwigFunction('sha1_file', [$this, 'sha1_file']),
new TwigFunction('get_meta_tags', [$this, 'get_meta_tags']),
new TwigFunction('pathinfo', [$this, 'pathinfo']),
];
}
/**
* @param string $filename
* @return bool
*/
public function file_exists($filename): bool
{
if (!$this->checkFilename($filename)) {
return false;
}
return file_exists($filename);
}
/**
* @param string $filename
* @return int|false
*/
public function fileatime($filename)
{
if (!$this->checkFilename($filename)) {
return false;
}
return fileatime($filename);
}
/**
* @param string $filename
* @return int|false
*/
public function filectime($filename)
{
if (!$this->checkFilename($filename)) {
return false;
}
return filectime($filename);
}
/**
* @param string $filename
* @return int|false
*/
public function filemtime($filename)
{
if (!$this->checkFilename($filename)) {
return false;
}
return filemtime($filename);
}
/**
* @param string $filename
* @return int|false
*/
public function filesize($filename)
{
if (!$this->checkFilename($filename)) {
return false;
}
return filesize($filename);
}
/**
* @param string $filename
* @return string|false
*/
public function filetype($filename)
{
if (!$this->checkFilename($filename)) {
return false;
}
return filetype($filename);
}
/**
* @param string $filename
* @return bool
*/
public function is_dir($filename): bool
{
if (!$this->checkFilename($filename)) {
return false;
}
return is_dir($filename);
}
/**
* @param string $filename
* @return bool
*/
public function is_file($filename): bool
{
if (!$this->checkFilename($filename)) {
return false;
}
return is_file($filename);
}
/**
* @param string $filename
* @return bool
*/
public function is_link($filename): bool
{
if (!$this->checkFilename($filename)) {
return false;
}
return is_link($filename);
}
/**
* @param string $filename
* @return bool
*/
public function is_readable($filename): bool
{
if (!$this->checkFilename($filename)) {
return false;
}
return is_readable($filename);
}
/**
* @param string $filename
* @return bool
*/
public function is_writable($filename): bool
{
if (!$this->checkFilename($filename)) {
return false;
}
return is_writable($filename);
}
/**
* @param string $filename
* @return array|false
*/
public function lstat($filename)
{
if (!$this->checkFilename($filename)) {
return false;
}
return lstat($filename);
}
/**
* @param string $filename
* @return array|false
*/
public function getimagesize($filename)
{
if (!$this->checkFilename($filename)) {
return false;
}
return getimagesize($filename);
}
/**
* @param string $filename
* @param string|null $required_sections
* @param bool $as_arrays
* @param bool $read_thumbnail
* @return array|false
*/
public function exif_read_data($filename, ?string $required_sections = null, bool $as_arrays = false, bool $read_thumbnail = false)
{
if (!Utils::functionExists('exif_read_data') || !$this->checkFilename($filename)) {
return false;
}
return @exif_read_data($filename, $required_sections, $as_arrays, $read_thumbnail);
}
/**
* @param string $filename
* @return int|false
*/
public function exif_imagetype($filename)
{
if (!Utils::functionExists('exif_imagetype') || !$this->checkFilename($filename)) {
return false;
}
return @exif_imagetype($filename);
}
/**
* @param string $algo
* @param string $filename
* @param bool $binary
* @return string|false
*/
public function hash_file(string $algo, string $filename, bool $binary = false)
{
if (!$this->checkFilename($filename)) {
return false;
}
return hash_file($algo, $filename, $binary);
}
/**
* @param string $algo
* @param string $filename
* @param string $key
* @param bool $binary
* @return string|false
*/
public function hash_hmac_file(string $algo, string $filename, string $key, bool $binary = false)
{
if (!$this->checkFilename($filename)) {
return false;
}
return hash_hmac_file($algo, $filename, $key, $binary);
}
/**
* @param string $filename
* @param bool $binary
* @return string|false
*/
public function md5_file($filename, bool $binary = false)
{
if (!$this->checkFilename($filename)) {
return false;
}
return md5_file($filename, $binary);
}
/**
* @param string $filename
* @param bool $binary
* @return string|false
*/
public function sha1_file($filename, bool $binary = false)
{
if (!$this->checkFilename($filename)) {
return false;
}
return sha1_file($filename, $binary);
}
/**
* @param string $filename
* @return array|false
*/
public function get_meta_tags($filename)
{
if (!$this->checkFilename($filename)) {
return false;
}
return get_meta_tags($filename);
}
/**
* @param string $path
* @param int|null $flags
* @return string|string[]
*/
public function pathinfo($path, $flags = null)
{
return Utils::pathinfo($path, $flags);
}
/**
* @param string $filename
* @return bool
*/
private function checkFilename($filename): bool
{
return is_string($filename) && (!str_contains($filename, '://') || $this->locator->isStream($filename));
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Twig/Node/TwigNodeCache.php | system/src/Grav/Common/Twig/Node/TwigNodeCache.php | <?php
/**
* @package Grav\Common\Twig
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Twig\Node;
use Twig\Compiler;
use Twig\Node\Expression\AbstractExpression;
use Twig\Node\Node;
use Twig\Node\NodeOutputInterface;
/**
* Class TwigNodeCache
* @package Grav\Common\Twig\Node
*/
class TwigNodeCache extends Node implements NodeOutputInterface
{
/**
* @param string $key unique name for key
* @param int $lifetime in seconds
* @param Node $body
* @param integer $lineno
* @param string|null $tag
*/
public function __construct(Node $body, ?AbstractExpression $key, ?AbstractExpression $lifetime, array $defaults, int $lineno, string $tag)
{
$nodes = ['body' => $body];
if ($key !== null) {
$nodes['key'] = $key;
}
if ($lifetime !== null) {
$nodes['lifetime'] = $lifetime;
}
parent::__construct($nodes, $defaults, $lineno, $tag);
}
public function compile(Compiler $compiler): void
{
$compiler->addDebugInfo($this);
// Generate the cache key
if ($this->hasNode('key')) {
$compiler
->write('$key = "twigcache-" . ')
->subcompile($this->getNode('key'))
->raw(";\n");
} else {
$compiler
->write('$key = ')
->string($this->getAttribute('key'))
->raw(";\n");
}
// Set the cache timeout
if ($this->hasNode('lifetime')) {
$compiler
->write('$lifetime = ')
->subcompile($this->getNode('lifetime'))
->raw(";\n");
} else {
$compiler
->write('$lifetime = ')
->write($this->getAttribute('lifetime'))
->raw(";\n");
}
$compiler
->write("\$cache = \\Grav\\Common\\Grav::instance()['cache'];\n")
->write("\$cache_body = \$cache->fetch(\$key);\n")
->write("if (\$cache_body === false) {\n")
->indent()
->write("\\Grav\\Common\\Grav::instance()['debugger']->addMessage(\"Cache Key: \$key, Lifetime: \$lifetime\");\n")
->write("ob_start();\n")
->indent()
->subcompile($this->getNode('body'))
->outdent()
->write("\n")
->write("\$cache_body = ob_get_clean();\n")
->write("\$cache->save(\$key, \$cache_body, \$lifetime);\n")
->outdent()
->write("}\n")
->write("echo '' === \$cache_body ? '' : new Markup(\$cache_body, \$this->env->getCharset());\n");
}
} | php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Twig/Node/TwigNodeMarkdown.php | system/src/Grav/Common/Twig/Node/TwigNodeMarkdown.php | <?php
/**
* @package Grav\Common\Twig
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Twig\Node;
use Twig\Compiler;
use Twig\Node\Node;
use Twig\Node\NodeOutputInterface;
/**
* Class TwigNodeMarkdown
* @package Grav\Common\Twig\Node
*/
class TwigNodeMarkdown extends Node implements NodeOutputInterface
{
/**
* TwigNodeMarkdown constructor.
* @param Node $body
* @param int $lineno
* @param string $tag
*/
public function __construct(Node $body, $lineno, $tag = 'markdown')
{
parent::__construct(['body' => $body], [], $lineno, $tag);
}
/**
* Compiles the node to PHP.
*
* @param Compiler $compiler A Twig Compiler instance
* @return void
*/
public function compile(Compiler $compiler): void
{
$compiler
->addDebugInfo($this)
->write('ob_start();' . PHP_EOL)
->subcompile($this->getNode('body'))
->write('$content = ob_get_clean();' . PHP_EOL)
->write('preg_match("/^\s*/", $content, $matches);' . PHP_EOL)
->write('$lines = explode("\n", $content);' . PHP_EOL)
->write('$content = preg_replace(\'/^\' . $matches[0]. \'/\', "", $lines);' . PHP_EOL)
->write('$content = join("\n", $content);' . PHP_EOL)
->write('echo $this->env->getExtension(\'Grav\Common\Twig\Extension\GravExtension\')->markdownFunction($context, $content);' . PHP_EOL);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Twig/Node/TwigNodeLink.php | system/src/Grav/Common/Twig/Node/TwigNodeLink.php | <?php
/**
* @package Grav\Common\Twig
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Twig\Node;
use LogicException;
use Twig\Compiler;
use Twig\Node\Expression\AbstractExpression;
use Twig\Node\Node;
use Twig\Node\NodeCaptureInterface;
/**
* Class TwigNodeLink
* @package Grav\Common\Twig\Node
*/
class TwigNodeLink extends Node implements NodeCaptureInterface
{
/** @var string */
protected $tagName = 'link';
/**
* TwigNodeLink constructor.
* @param string|null $rel
* @param AbstractExpression|null $file
* @param AbstractExpression|null $group
* @param AbstractExpression|null $priority
* @param AbstractExpression|null $attributes
* @param int $lineno
* @param string|null $tag
*/
public function __construct(?string $rel, ?AbstractExpression $file, ?AbstractExpression $group, ?AbstractExpression $priority, ?AbstractExpression $attributes, $lineno = 0, $tag = null)
{
$nodes = ['file' => $file, 'group' => $group, 'priority' => $priority, 'attributes' => $attributes];
$nodes = array_filter($nodes);
parent::__construct($nodes, ['rel' => $rel], $lineno, $tag);
}
/**
* Compiles the node to PHP.
*
* @param Compiler $compiler A Twig Compiler instance
* @return void
* @throws LogicException
*/
public function compile(Compiler $compiler): void
{
$compiler->addDebugInfo($this);
if (!$this->hasNode('file')) {
return;
}
$compiler->write('$attributes = [\'rel\' => \'' . $this->getAttribute('rel') . '\'];' . "\n");
if ($this->hasNode('attributes')) {
$compiler
->write('$attributes += ')
->subcompile($this->getNode('attributes'))
->raw(';' . PHP_EOL)
->write('if (!is_array($attributes)) {' . PHP_EOL)
->indent()
->write("throw new UnexpectedValueException('{% {$this->tagName} with x %}: x is not an array');" . PHP_EOL)
->outdent()
->write('}' . PHP_EOL);
}
if ($this->hasNode('group')) {
$compiler
->write('$group = ')
->subcompile($this->getNode('group'))
->raw(';' . PHP_EOL)
->write('if (!is_string($group)) {' . PHP_EOL)
->indent()
->write("throw new UnexpectedValueException('{% {$this->tagName} in x %}: x is not a string');" . PHP_EOL)
->outdent()
->write('}' . PHP_EOL);
} else {
$compiler->write('$group = \'head\';' . PHP_EOL);
}
if ($this->hasNode('priority')) {
$compiler
->write('$priority = (int)(')
->subcompile($this->getNode('priority'))
->raw(');' . PHP_EOL);
} else {
$compiler->write('$priority = 10;' . PHP_EOL);
}
$compiler->write("\$assets = \\Grav\\Common\\Grav::instance()['assets'];" . PHP_EOL);
$compiler->write("\$block = \$context['block'] ?? null;" . PHP_EOL);
$compiler
->write('$file = (string)(')
->subcompile($this->getNode('file'))
->raw(');' . PHP_EOL);
// Assets support.
$compiler->write('$assets->addLink($file, [\'group\' => $group, \'priority\' => $priority] + $attributes);' . PHP_EOL);
// HtmlBlock support.
$compiler
->write('if ($block instanceof \Grav\Framework\ContentBlock\HtmlBlock) {' . PHP_EOL)
->indent()
->write('$block->addLink([\'href\'=> $file] + $attributes, $priority, $group);' . PHP_EOL)
->outdent()
->write('}' . PHP_EOL);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Twig/Node/TwigNodeTryCatch.php | system/src/Grav/Common/Twig/Node/TwigNodeTryCatch.php | <?php
/**
* @package Grav\Common\Twig
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Twig\Node;
use LogicException;
use Twig\Compiler;
use Twig\Node\Node;
/**
* Class TwigNodeTryCatch
* @package Grav\Common\Twig\Node
*/
class TwigNodeTryCatch extends Node
{
/**
* TwigNodeTryCatch constructor.
* @param Node $try
* @param Node|null $catch
* @param int $lineno
* @param string|null $tag
*/
public function __construct(Node $try, Node $catch = null, $lineno = 0, $tag = null)
{
$nodes = ['try' => $try, 'catch' => $catch];
$nodes = array_filter($nodes);
parent::__construct($nodes, [], $lineno, $tag);
}
/**
* Compiles the node to PHP.
*
* @param Compiler $compiler A Twig Compiler instance
* @return void
* @throws LogicException
*/
public function compile(Compiler $compiler): void
{
$compiler->addDebugInfo($this);
$compiler->write('try {');
$compiler
->indent()
->subcompile($this->getNode('try'))
->outdent()
->write('} catch (\Exception $e) {' . "\n")
->indent()
->write('if (isset($context[\'grav\'][\'debugger\'])) $context[\'grav\'][\'debugger\']->addException($e);' . "\n")
->write('$context[\'e\'] = $e;' . "\n");
if ($this->hasNode('catch')) {
$compiler->subcompile($this->getNode('catch'));
}
$compiler
->outdent()
->write("}\n");
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Twig/Node/TwigNodeSwitch.php | system/src/Grav/Common/Twig/Node/TwigNodeSwitch.php | <?php
/**
* @package Grav\Common\Twig
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Twig\Node;
use Twig\Compiler;
use Twig\Node\Node;
/**
* Class TwigNodeSwitch
* @package Grav\Common\Twig\Node
*/
class TwigNodeSwitch extends Node
{
/**
* TwigNodeSwitch constructor.
* @param Node $value
* @param Node $cases
* @param Node|null $default
* @param int $lineno
* @param string|null $tag
*/
public function __construct(Node $value, Node $cases, Node $default = null, $lineno = 0, $tag = null)
{
$nodes = ['value' => $value, 'cases' => $cases, 'default' => $default];
$nodes = array_filter($nodes);
parent::__construct($nodes, [], $lineno, $tag);
}
/**
* Compiles the node to PHP.
*
* @param Compiler $compiler A Twig Compiler instance
* @return void
*/
public function compile(Compiler $compiler): void
{
$compiler
->addDebugInfo($this)
->write('switch (')
->subcompile($this->getNode('value'))
->raw(") {\n")
->indent();
/** @var Node $case */
foreach ($this->getNode('cases') as $case) {
if (!$case->hasNode('body')) {
continue;
}
foreach ($case->getNode('values') as $value) {
$compiler
->write('case ')
->subcompile($value)
->raw(":\n");
}
$compiler
->write("{\n")
->indent()
->subcompile($case->getNode('body'))
->write("break;\n")
->outdent()
->write("}\n");
}
if ($this->hasNode('default')) {
$compiler
->write("default:\n")
->write("{\n")
->indent()
->subcompile($this->getNode('default'))
->outdent()
->write("}\n");
}
$compiler
->outdent()
->write("}\n");
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Twig/Node/TwigNodeThrow.php | system/src/Grav/Common/Twig/Node/TwigNodeThrow.php | <?php
/**
* @package Grav\Common\Twig
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Twig\Node;
use LogicException;
use Twig\Compiler;
use Twig\Node\Node;
/**
* Class TwigNodeThrow
* @package Grav\Common\Twig\Node
*/
class TwigNodeThrow extends Node
{
/**
* TwigNodeThrow constructor.
* @param int $code
* @param Node $message
* @param int $lineno
* @param string|null $tag
*/
public function __construct($code, Node $message, $lineno = 0, $tag = null)
{
parent::__construct(['message' => $message], ['code' => $code], $lineno, $tag);
}
/**
* Compiles the node to PHP.
*
* @param Compiler $compiler A Twig Compiler instance
* @return void
* @throws LogicException
*/
public function compile(Compiler $compiler): void
{
$compiler->addDebugInfo($this);
$compiler
->write('throw new \Grav\Common\Twig\Exception\TwigException(')
->subcompile($this->getNode('message'))
->write(', ')
->write($this->getAttribute('code') ?: 500)
->write(");\n");
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Twig/Node/TwigNodeRender.php | system/src/Grav/Common/Twig/Node/TwigNodeRender.php | <?php
/**
* @package Grav\Common\Twig
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Twig\Node;
use LogicException;
use Twig\Compiler;
use Twig\Node\Expression\AbstractExpression;
use Twig\Node\Node;
use Twig\Node\NodeCaptureInterface;
/**
* Class TwigNodeRender
* @package Grav\Common\Twig\Node
*/
class TwigNodeRender extends Node implements NodeCaptureInterface
{
/** @var string */
protected $tagName = 'render';
/**
* @param AbstractExpression $object
* @param AbstractExpression|null $layout
* @param AbstractExpression|null $context
* @param int $lineno
* @param string|null $tag
*/
public function __construct(AbstractExpression $object, ?AbstractExpression $layout, ?AbstractExpression $context, $lineno, $tag = null)
{
$nodes = ['object' => $object, 'layout' => $layout, 'context' => $context];
$nodes = array_filter($nodes);
parent::__construct($nodes, [], $lineno, $tag);
}
/**
* Compiles the node to PHP.
*
* @param Compiler $compiler A Twig Compiler instance
* @return void
* @throws LogicException
*/
public function compile(Compiler $compiler): void
{
$compiler->addDebugInfo($this);
$compiler->write('$object = ')->subcompile($this->getNode('object'))->raw(';' . PHP_EOL);
if ($this->hasNode('layout')) {
$layout = $this->getNode('layout');
$compiler->write('$layout = ')->subcompile($layout)->raw(';' . PHP_EOL);
} else {
$compiler->write('$layout = null;' . PHP_EOL);
}
if ($this->hasNode('context')) {
$context = $this->getNode('context');
$compiler->write('$attributes = ')->subcompile($context)->raw(';' . PHP_EOL);
} else {
$compiler->write('$attributes = null;' . PHP_EOL);
}
$compiler
->write('$html = $object->render($layout, $attributes ?? []);' . PHP_EOL)
->write('$block = $context[\'block\'] ?? null;' . PHP_EOL)
->write('if ($block instanceof \Grav\Framework\ContentBlock\ContentBlock && $html instanceof \Grav\Framework\ContentBlock\ContentBlock) {' . PHP_EOL)
->indent()
->write('$block->addBlock($html);' . PHP_EOL)
->write('echo $html->getToken();' . PHP_EOL)
->outdent()
->write('} else {' . PHP_EOL)
->indent()
->write('\Grav\Common\Assets\BlockAssets::registerAssets($html);' . PHP_EOL)
->write('echo (string)$html;' . PHP_EOL)
->outdent()
->write('}' . PHP_EOL)
;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Twig/Node/TwigNodeStyle.php | system/src/Grav/Common/Twig/Node/TwigNodeStyle.php | <?php
/**
* @package Grav\Common\Twig
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Twig\Node;
use LogicException;
use Twig\Compiler;
use Twig\Node\Expression\AbstractExpression;
use Twig\Node\Node;
use Twig\Node\NodeCaptureInterface;
/**
* Class TwigNodeStyle
* @package Grav\Common\Twig\Node
*/
class TwigNodeStyle extends Node implements NodeCaptureInterface
{
/** @var string */
protected $tagName = 'style';
/**
* TwigNodeAssets constructor.
* @param Node|null $body
* @param AbstractExpression|null $file
* @param AbstractExpression|null $group
* @param AbstractExpression|null $priority
* @param AbstractExpression|null $attributes
* @param int $lineno
* @param string|null $tag
*/
public function __construct(?Node $body, ?AbstractExpression $file, ?AbstractExpression $group, ?AbstractExpression $priority, ?AbstractExpression $attributes, $lineno = 0, $tag = null)
{
$nodes = ['body' => $body, 'file' => $file, 'group' => $group, 'priority' => $priority, 'attributes' => $attributes];
$nodes = array_filter($nodes);
parent::__construct($nodes, [], $lineno, $tag);
}
/**
* Compiles the node to PHP.
*
* @param Compiler $compiler A Twig Compiler instance
* @return void
* @throws LogicException
*/
public function compile(Compiler $compiler): void
{
$compiler->addDebugInfo($this);
if ($this->hasNode('attributes')) {
$compiler
->write('$attributes = ')
->subcompile($this->getNode('attributes'))
->raw(';' . PHP_EOL)
->write('if (!is_array($attributes)) {' . PHP_EOL)
->indent()
->write("throw new UnexpectedValueException('{% {$this->tagName} with x %}: x is not an array');" . PHP_EOL)
->outdent()
->write('}' . PHP_EOL);
} else {
$compiler->write('$attributes = [];' . PHP_EOL);
}
if ($this->hasNode('group')) {
$compiler
->write('$group = ')
->subcompile($this->getNode('group'))
->raw(';' . PHP_EOL)
->write('if (!is_string($group)) {' . PHP_EOL)
->indent()
->write("throw new UnexpectedValueException('{% {$this->tagName} in x %}: x is not a string');" . PHP_EOL)
->outdent()
->write('}' . PHP_EOL);
} else {
$compiler->write('$group = \'head\';' . PHP_EOL);
}
if ($this->hasNode('priority')) {
$compiler
->write('$priority = (int)(')
->subcompile($this->getNode('priority'))
->raw(');' . PHP_EOL);
} else {
$compiler->write('$priority = 10;' . PHP_EOL);
}
$compiler->write("\$assets = \\Grav\\Common\\Grav::instance()['assets'];" . PHP_EOL);
$compiler->write("\$block = \$context['block'] ?? null;" . PHP_EOL);
if ($this->hasNode('file')) {
// CSS file.
$compiler
->write('$file = (string)(')
->subcompile($this->getNode('file'))
->raw(');' . PHP_EOL);
// Assets support.
$compiler->write('$assets->addCss($file, [\'group\' => $group, \'priority\' => $priority] + $attributes);' . PHP_EOL);
// HtmlBlock support.
$compiler
->write('if ($block instanceof \Grav\Framework\ContentBlock\HtmlBlock) {' . PHP_EOL)
->indent()
->write('$block->addStyle([\'href\'=> $file] + $attributes, $priority, $group);' . PHP_EOL)
->outdent()
->write('}' . PHP_EOL);
} else {
// Inline style.
$compiler
->write('ob_start();' . PHP_EOL)
->subcompile($this->getNode('body'))
->write('$content = ob_get_clean();' . PHP_EOL);
// Assets support.
$compiler->write('$assets->addInlineCss($content, [\'group\' => $group, \'priority\' => $priority] + $attributes);' . PHP_EOL);
// HtmlBlock support.
$compiler
->write('if ($block instanceof \Grav\Framework\ContentBlock\HtmlBlock) {' . PHP_EOL)
->indent()
->write('$block->addInlineStyle([\'content\'=> $content] + $attributes, $priority, $group);' . PHP_EOL)
->outdent()
->write('}' . PHP_EOL);
}
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Twig/Node/TwigNodeScript.php | system/src/Grav/Common/Twig/Node/TwigNodeScript.php | <?php
/**
* @package Grav\Common\Twig
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Twig\Node;
use LogicException;
use Twig\Compiler;
use Twig\Node\Expression\AbstractExpression;
use Twig\Node\Node;
use Twig\Node\NodeCaptureInterface;
/**
* Class TwigNodeScript
* @package Grav\Common\Twig\Node
*/
class TwigNodeScript extends Node implements NodeCaptureInterface
{
/** @var string */
protected $tagName = 'script';
/**
* TwigNodeScript constructor.
* @param Node|null $body
* @param string|null $type
* @param AbstractExpression|null $file
* @param AbstractExpression|null $group
* @param AbstractExpression|null $priority
* @param AbstractExpression|null $attributes
* @param int $lineno
* @param string|null $tag
*/
public function __construct(?Node $body, ?string $type, ?AbstractExpression $file, ?AbstractExpression $group, ?AbstractExpression $priority, ?AbstractExpression $attributes, $lineno = 0, $tag = null)
{
$nodes = ['body' => $body, 'file' => $file, 'group' => $group, 'priority' => $priority, 'attributes' => $attributes];
$nodes = array_filter($nodes);
parent::__construct($nodes, ['type' => $type], $lineno, $tag);
}
/**
* Compiles the node to PHP.
*
* @param Compiler $compiler A Twig Compiler instance
* @return void
* @throws LogicException
*/
public function compile(Compiler $compiler): void
{
$compiler->addDebugInfo($this);
if ($this->hasNode('attributes')) {
$compiler
->write('$attributes = ')
->subcompile($this->getNode('attributes'))
->raw(';' . PHP_EOL)
->write('if (!is_array($attributes)) {' . PHP_EOL)
->indent()
->write("throw new UnexpectedValueException('{% {$this->tagName} with x %}: x is not an array');" . PHP_EOL)
->outdent()
->write('}' . PHP_EOL);
} else {
$compiler->write('$attributes = [];' . PHP_EOL);
}
if ($this->hasNode('group')) {
$compiler
->write('$group = ')
->subcompile($this->getNode('group'))
->raw(';' . PHP_EOL)
->write('if (!is_string($group)) {' . PHP_EOL)
->indent()
->write("throw new UnexpectedValueException('{% {$this->tagName} in x %}: x is not a string');" . PHP_EOL)
->outdent()
->write('}' . PHP_EOL);
} else {
$compiler->write('$group = \'head\';' . PHP_EOL);
}
if ($this->hasNode('priority')) {
$compiler
->write('$priority = (int)(')
->subcompile($this->getNode('priority'))
->raw(');' . PHP_EOL);
} else {
$compiler->write('$priority = 10;' . PHP_EOL);
}
$compiler->write("\$assets = \\Grav\\Common\\Grav::instance()['assets'];" . PHP_EOL);
$compiler->write("\$block = \$context['block'] ?? null;" . PHP_EOL);
if ($this->hasNode('file')) {
// JS file.
$compiler
->write('$file = (string)(')
->subcompile($this->getNode('file'))
->raw(');' . PHP_EOL);
$method = $this->getAttribute('type') === 'module' ? 'addJsModule' : 'addJs';
// Assets support.
$compiler->write('$assets->' . $method . '($file, [\'group\' => $group, \'priority\' => $priority] + $attributes);' . PHP_EOL);
$method = $this->getAttribute('type') === 'module' ? 'addModule' : 'addScript';
// HtmlBlock support.
$compiler
->write('if ($block instanceof \Grav\Framework\ContentBlock\HtmlBlock) {' . PHP_EOL)
->indent()
->write('$block->' . $method . '([\'src\'=> $file] + $attributes, $priority, $group);' . PHP_EOL)
->outdent()
->write('}' . PHP_EOL);
} else {
// Inline script.
$compiler
->write('ob_start();' . PHP_EOL)
->subcompile($this->getNode('body'))
->write('$content = ob_get_clean();' . PHP_EOL);
$method = $this->getAttribute('type') === 'module' ? 'addInlineJsModule' : 'addInlineJs';
// Assets support.
$compiler->write('$assets->' . $method . '($content, [\'group\' => $group, \'priority\' => $priority] + $attributes);' . PHP_EOL);
$method = $this->getAttribute('type') === 'module' ? 'addInlineModule' : 'addInlineScript';
// HtmlBlock support.
$compiler
->write('if ($block instanceof \Grav\Framework\ContentBlock\HtmlBlock) {' . PHP_EOL)
->indent()
->write('$block->' . $method . '([\'content\'=> $content] + $attributes, $priority, $group);' . PHP_EOL)
->outdent()
->write('}' . PHP_EOL);
}
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserScript.php | system/src/Grav/Common/Twig/TokenParser/TwigTokenParserScript.php | <?php
/**
* @package Grav\Common\Twig
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Twig\TokenParser;
use Grav\Common\Twig\Node\TwigNodeScript;
use Twig\Error\SyntaxError;
use Twig\Token;
use Twig\TokenParser\AbstractTokenParser;
/**
* Adds a script to head/bottom/custom group location in the document.
*
* {% script 'theme://js/something.js' at 'bottom' priority: 20 with { position: 'pipeline', loading: 'async defer' } %}
* {% script module 'theme://js/module.mjs' at 'head' %}
*
* {% script 'theme://js/something.js' at 'bottom' priority: 20 with { loading: 'inline' } %}
* {% script at 'bottom' priority: 20 %}
* alert('Warning!');
* {% endscript %}
*
* {% script module 'theme://js/module.mjs' at 'bottom' with { loading: 'inline' } %}
* {% script module at 'bottom' %}
* ...
* {% endscript %}
*/
class TwigTokenParserScript extends AbstractTokenParser
{
/**
* Parses a token and returns a node.
*
* @param Token $token
* @return TwigNodeScript
* @throws SyntaxError
*/
public function parse(Token $token)
{
$lineno = $token->getLine();
$stream = $this->parser->getStream();
[$type, $file, $group, $priority, $attributes] = $this->parseArguments($token);
$content = null;
if ($file === null) {
$content = $this->parser->subparse([$this, 'decideBlockEnd'], true);
$stream->expect(Token::BLOCK_END_TYPE);
}
return new TwigNodeScript($content, $type, $file, $group, $priority, $attributes, $lineno, $this->getTag());
}
/**
* @param Token $token
* @return array
*/
protected function parseArguments(Token $token): array
{
$stream = $this->parser->getStream();
// Look for deprecated {% script ... in ... %}
if (!$stream->test(Token::BLOCK_END_TYPE) && !$stream->test(Token::OPERATOR_TYPE, 'in')) {
$i = 0;
do {
$token = $stream->look(++$i);
if ($token->test(Token::BLOCK_END_TYPE)) {
break;
}
if ($token->test(Token::OPERATOR_TYPE, 'in') && $stream->look($i+1)->test(Token::STRING_TYPE)) {
user_error("Twig: Using {% script ... in ... %} is deprecated, use {% script ... at ... %} instead", E_USER_DEPRECATED);
break;
}
} while (true);
}
$type = null;
if ($stream->test(Token::NAME_TYPE, 'module')) {
$type = $stream->getCurrent()->getValue();
$stream->next();
}
$file = null;
if (!$stream->test(Token::NAME_TYPE) && !$stream->test(Token::OPERATOR_TYPE, 'in') && !$stream->test(Token::BLOCK_END_TYPE)) {
$file = $this->parser->getExpressionParser()->parseExpression();
}
$group = null;
if ($stream->nextIf(Token::NAME_TYPE, 'at') || $stream->nextIf(Token::OPERATOR_TYPE, 'in')) {
$group = $this->parser->getExpressionParser()->parseExpression();
}
$priority = null;
if ($stream->nextIf(Token::NAME_TYPE, 'priority')) {
$stream->expect(Token::PUNCTUATION_TYPE, ':');
$priority = $this->parser->getExpressionParser()->parseExpression();
}
$attributes = null;
if ($stream->nextIf(Token::NAME_TYPE, 'with')) {
$attributes = $this->parser->getExpressionParser()->parseExpression();
}
$stream->expect(Token::BLOCK_END_TYPE);
return [$type, $file, $group, $priority, $attributes];
}
/**
* @param Token $token
* @return bool
*/
public function decideBlockEnd(Token $token): bool
{
return $token->test('endscript');
}
/**
* Gets the tag name associated with this token parser.
*
* @return string The tag name
*/
public function getTag(): string
{
return 'script';
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserTryCatch.php | system/src/Grav/Common/Twig/TokenParser/TwigTokenParserTryCatch.php | <?php
/**
* @package Grav\Common\Twig
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Twig\TokenParser;
use Grav\Common\Twig\Node\TwigNodeTryCatch;
use Twig\Error\SyntaxError;
use Twig\Node\Node;
use Twig\Token;
use Twig\TokenParser\AbstractTokenParser;
/**
* Handles try/catch in template file.
*
* <pre>
* {% try %}
* <li>{{ user.get('name') }}</li>
* {% catch %}
* {{ e.message }}
* {% endcatch %}
* </pre>
*/
class TwigTokenParserTryCatch extends AbstractTokenParser
{
/**
* Parses a token and returns a node.
*
* @param Token $token
* @return TwigNodeTryCatch
* @throws SyntaxError
*/
public function parse(Token $token)
{
$lineno = $token->getLine();
$stream = $this->parser->getStream();
$stream->expect(Token::BLOCK_END_TYPE);
$try = $this->parser->subparse([$this, 'decideCatch']);
$stream->next();
$stream->expect(Token::BLOCK_END_TYPE);
$catch = $this->parser->subparse([$this, 'decideEnd']);
$stream->next();
$stream->expect(Token::BLOCK_END_TYPE);
return new TwigNodeTryCatch($try, $catch, $lineno, $this->getTag());
}
/**
* @param Token $token
* @return bool
*/
public function decideCatch(Token $token): bool
{
return $token->test(['catch']);
}
/**
* @param Token $token
* @return bool
*/
public function decideEnd(Token $token): bool
{
return $token->test(['endtry']) || $token->test(['endcatch']);
}
/**
* Gets the tag name associated with this token parser.
*
* @return string The tag name
*/
public function getTag(): string
{
return 'try';
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserThrow.php | system/src/Grav/Common/Twig/TokenParser/TwigTokenParserThrow.php | <?php
/**
* @package Grav\Common\Twig
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Twig\TokenParser;
use Grav\Common\Twig\Node\TwigNodeThrow;
use Twig\Error\SyntaxError;
use Twig\Node\Node;
use Twig\Token;
use Twig\TokenParser\AbstractTokenParser;
/**
* Handles try/catch in template file.
*
* <pre>
* {% throw 404 'Not Found' %}
* </pre>
*/
class TwigTokenParserThrow extends AbstractTokenParser
{
/**
* Parses a token and returns a node.
*
* @param Token $token
* @return TwigNodeThrow
* @throws SyntaxError
*/
public function parse(Token $token)
{
$lineno = $token->getLine();
$stream = $this->parser->getStream();
$code = $stream->expect(Token::NUMBER_TYPE)->getValue();
$message = $this->parser->getExpressionParser()->parseExpression();
$stream->expect(Token::BLOCK_END_TYPE);
return new TwigNodeThrow((int)$code, $message, $lineno, $this->getTag());
}
/**
* Gets the tag name associated with this token parser.
*
* @return string The tag name
*/
public function getTag(): string
{
return 'throw';
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserMarkdown.php | system/src/Grav/Common/Twig/TokenParser/TwigTokenParserMarkdown.php | <?php
/**
* @package Grav\Common\Twig
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Twig\TokenParser;
use Grav\Common\Twig\Node\TwigNodeMarkdown;
use Twig\Error\SyntaxError;
use Twig\Token;
use Twig\TokenParser\AbstractTokenParser;
/**
* Adds ability to inline markdown between tags.
*
* {% markdown %}
* This is **bold** and this _underlined_
*
* 1. This is a bullet list
* 2. This is another item in that same list
* {% endmarkdown %}
*/
class TwigTokenParserMarkdown extends AbstractTokenParser
{
/**
* @param Token $token
* @return TwigNodeMarkdown
* @throws SyntaxError
*/
public function parse(Token $token)
{
$lineno = $token->getLine();
$this->parser->getStream()->expect(Token::BLOCK_END_TYPE);
$body = $this->parser->subparse([$this, 'decideMarkdownEnd'], true);
$this->parser->getStream()->expect(Token::BLOCK_END_TYPE);
return new TwigNodeMarkdown($body, $lineno, $this->getTag());
}
/**
* Decide if current token marks end of Markdown block.
*
* @param Token $token
* @return bool
*/
public function decideMarkdownEnd(Token $token): bool
{
return $token->test('endmarkdown');
}
/**
* {@inheritdoc}
*/
public function getTag(): string
{
return 'markdown';
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserStyle.php | system/src/Grav/Common/Twig/TokenParser/TwigTokenParserStyle.php | <?php
/**
* @package Grav\Common\Twig
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Twig\TokenParser;
use Grav\Common\Twig\Node\TwigNodeStyle;
use Twig\Error\SyntaxError;
use Twig\Token;
use Twig\TokenParser\AbstractTokenParser;
/**
* Adds a style to the document.
*
* {% style 'theme://css/foo.css' priority: 20 %}
* {% style priority: 20 with { media: 'screen' } %}
* a { color: red; }
* {% endstyle %}
*/
class TwigTokenParserStyle extends AbstractTokenParser
{
/**
* Parses a token and returns a node.
*
* @param Token $token
* @return TwigNodeStyle
* @throws SyntaxError
*/
public function parse(Token $token)
{
$lineno = $token->getLine();
$stream = $this->parser->getStream();
[$file, $group, $priority, $attributes] = $this->parseArguments($token);
$content = null;
if (!$file) {
$content = $this->parser->subparse([$this, 'decideBlockEnd'], true);
$stream->expect(Token::BLOCK_END_TYPE);
}
return new TwigNodeStyle($content, $file, $group, $priority, $attributes, $lineno, $this->getTag());
}
/**
* @param Token $token
* @return array
*/
protected function parseArguments(Token $token): array
{
$stream = $this->parser->getStream();
// Look for deprecated {% style ... in ... %}
if (!$stream->test(Token::BLOCK_END_TYPE) && !$stream->test(Token::OPERATOR_TYPE, 'in')) {
$i = 0;
do {
$token = $stream->look(++$i);
if ($token->test(Token::BLOCK_END_TYPE)) {
break;
}
if ($token->test(Token::OPERATOR_TYPE, 'in') && $stream->look($i+1)->test(Token::STRING_TYPE)) {
user_error("Twig: Using {% style ... in ... %} is deprecated, use {% style ... at ... %} instead", E_USER_DEPRECATED);
break;
}
} while (true);
}
$file = null;
if (!$stream->test(Token::NAME_TYPE) && !$stream->test(Token::OPERATOR_TYPE, 'in') && !$stream->test(Token::BLOCK_END_TYPE)) {
$file = $this->parser->getExpressionParser()->parseExpression();
}
$group = null;
if ($stream->nextIf(Token::NAME_TYPE, 'at') || $stream->nextIf(Token::OPERATOR_TYPE, 'in')) {
$group = $this->parser->getExpressionParser()->parseExpression();
}
$priority = null;
if ($stream->nextIf(Token::NAME_TYPE, 'priority')) {
$stream->expect(Token::PUNCTUATION_TYPE, ':');
$priority = $this->parser->getExpressionParser()->parseExpression();
}
$attributes = null;
if ($stream->nextIf(Token::NAME_TYPE, 'with')) {
$attributes = $this->parser->getExpressionParser()->parseExpression();
}
$stream->expect(Token::BLOCK_END_TYPE);
return [$file, $group, $priority, $attributes];
}
/**
* @param Token $token
* @return bool
*/
public function decideBlockEnd(Token $token): bool
{
return $token->test('endstyle');
}
/**
* Gets the tag name associated with this token parser.
*
* @return string The tag name
*/
public function getTag(): string
{
return 'style';
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserRender.php | system/src/Grav/Common/Twig/TokenParser/TwigTokenParserRender.php | <?php
/**
* @package Grav\Common\Twig
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Twig\TokenParser;
use Grav\Common\Twig\Node\TwigNodeRender;
use Twig\Node\Node;
use Twig\Token;
use Twig\TokenParser\AbstractTokenParser;
/**
* Renders an object.
*
* {% render object layout: 'default' with { variable: true } %}
*/
class TwigTokenParserRender extends AbstractTokenParser
{
/**
* Parses a token and returns a node.
*
* @param Token $token
* @return TwigNodeRender
*/
public function parse(Token $token)
{
$lineno = $token->getLine();
[$object, $layout, $context] = $this->parseArguments($token);
return new TwigNodeRender($object, $layout, $context, $lineno, $this->getTag());
}
/**
* @param Token $token
* @return array
*/
protected function parseArguments(Token $token): array
{
$stream = $this->parser->getStream();
$object = $this->parser->getExpressionParser()->parseExpression();
$layout = null;
if ($stream->nextIf(Token::NAME_TYPE, 'layout')) {
$stream->expect(Token::PUNCTUATION_TYPE, ':');
$layout = $this->parser->getExpressionParser()->parseExpression();
}
$context = null;
if ($stream->nextIf(Token::NAME_TYPE, 'with')) {
$context = $this->parser->getExpressionParser()->parseExpression();
}
$stream->expect(Token::BLOCK_END_TYPE);
return [$object, $layout, $context];
}
/**
* Gets the tag name associated with this token parser.
*
* @return string The tag name
*/
public function getTag(): string
{
return 'render';
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserSwitch.php | system/src/Grav/Common/Twig/TokenParser/TwigTokenParserSwitch.php | <?php
/**
* @package Grav\Common\Twig
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
* @origin https://gist.github.com/maxgalbu/9409182
*/
namespace Grav\Common\Twig\TokenParser;
use Grav\Common\Twig\Node\TwigNodeSwitch;
use Twig\Error\SyntaxError;
use Twig\Node\Node;
use Twig\Token;
use Twig\TokenParser\AbstractTokenParser;
/**
* Adds ability use elegant switch instead of ungainly if statements
*
* {% switch type %}
* {% case 'foo' %}
* {{ my_data.foo }}
* {% case 'bar' %}
* {{ my_data.bar }}
* {% default %}
* {{ my_data.default }}
* {% endswitch %}
*/
class TwigTokenParserSwitch extends AbstractTokenParser
{
/**
* @param Token $token
* @return TwigNodeSwitch
* @throws SyntaxError
*/
public function parse(Token $token)
{
$lineno = $token->getLine();
$stream = $this->parser->getStream();
$name = $this->parser->getExpressionParser()->parseExpression();
$stream->expect(Token::BLOCK_END_TYPE);
// There can be some whitespace between the {% switch %} and first {% case %} tag.
while ($stream->getCurrent()->getType() === Token::TEXT_TYPE && trim($stream->getCurrent()->getValue()) === '') {
$stream->next();
}
$stream->expect(Token::BLOCK_START_TYPE);
$expressionParser = $this->parser->getExpressionParser();
$default = null;
$cases = [];
$end = false;
while (!$end) {
$next = $stream->next();
switch ($next->getValue()) {
case 'case':
$values = [];
while (true) {
$values[] = $expressionParser->parsePrimaryExpression();
// Multiple allowed values?
if ($stream->test(Token::OPERATOR_TYPE, 'or')) {
$stream->next();
} else {
break;
}
}
$stream->expect(Token::BLOCK_END_TYPE);
$body = $this->parser->subparse([$this, 'decideIfFork']);
$cases[] = new Node([
'values' => new Node($values),
'body' => $body
]);
break;
case 'default':
$stream->expect(Token::BLOCK_END_TYPE);
$default = $this->parser->subparse([$this, 'decideIfEnd']);
break;
case 'endswitch':
$end = true;
break;
default:
throw new SyntaxError(sprintf('Unexpected end of template. Twig was looking for the following tags "case", "default", or "endswitch" to close the "switch" block started at line %d)', $lineno), -1);
}
}
$stream->expect(Token::BLOCK_END_TYPE);
return new TwigNodeSwitch($name, new Node($cases), $default, $lineno, $this->getTag());
}
/**
* Decide if current token marks switch logic.
*
* @param Token $token
* @return bool
*/
public function decideIfFork(Token $token): bool
{
return $token->test(['case', 'default', 'endswitch']);
}
/**
* Decide if current token marks end of swtich block.
*
* @param Token $token
* @return bool
*/
public function decideIfEnd(Token $token): bool
{
return $token->test(['endswitch']);
}
/**
* {@inheritdoc}
*/
public function getTag(): string
{
return 'switch';
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserLink.php | system/src/Grav/Common/Twig/TokenParser/TwigTokenParserLink.php | <?php
/**
* @package Grav\Common\Twig
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Twig\TokenParser;
use Grav\Common\Twig\Node\TwigNodeLink;
use Twig\Error\SyntaxError;
use Twig\Token;
use Twig\TokenParser\AbstractTokenParser;
/**
* Adds a link to the document. First parameter is always value of `rel` without quotes.
*
* {% link icon 'theme://images/favicon.png' priority: 20 with { type: 'image/png' } %}
* {% link modulepreload 'plugin://grav-plugin/build/js/vendor.js' %}
*/
class TwigTokenParserLink extends AbstractTokenParser
{
protected $rel = [
'alternate',
'author',
'dns-prefetch',
'help',
'icon',
'license',
'next',
'pingback',
'preconnect',
'prefetch',
'preload',
'prerender',
'prev',
'search',
'stylesheet',
];
/**
* Parses a token and returns a node.
*
* @param Token $token
* @return TwigNodeLink
* @throws SyntaxError
*/
public function parse(Token $token)
{
$lineno = $token->getLine();
[$rel, $file, $group, $priority, $attributes] = $this->parseArguments($token);
return new TwigNodeLink($rel, $file, $group, $priority, $attributes, $lineno, $this->getTag());
}
/**
* @param Token $token
* @return array
*/
protected function parseArguments(Token $token): array
{
$stream = $this->parser->getStream();
$rel = null;
if ($stream->test(Token::NAME_TYPE, $this->rel)) {
$rel = $stream->getCurrent()->getValue();
$stream->next();
}
$file = null;
if (!$stream->test(Token::NAME_TYPE) && !$stream->test(Token::BLOCK_END_TYPE)) {
$file = $this->parser->getExpressionParser()->parseExpression();
}
$group = null;
if ($stream->nextIf(Token::NAME_TYPE, 'at')) {
$group = $this->parser->getExpressionParser()->parseExpression();
}
$priority = null;
if ($stream->nextIf(Token::NAME_TYPE, 'priority')) {
$stream->expect(Token::PUNCTUATION_TYPE, ':');
$priority = $this->parser->getExpressionParser()->parseExpression();
}
$attributes = null;
if ($stream->nextIf(Token::NAME_TYPE, 'with')) {
$attributes = $this->parser->getExpressionParser()->parseExpression();
}
$stream->expect(Token::BLOCK_END_TYPE);
return [$rel, $file, $group, $priority, $attributes];
}
/**
* Gets the tag name associated with this token parser.
*
* @return string The tag name
*/
public function getTag(): string
{
return 'link';
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Twig/TokenParser/TwigTokenParserCache.php | system/src/Grav/Common/Twig/TokenParser/TwigTokenParserCache.php | <?php
/**
* @package Grav\Common\Twig
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Twig\TokenParser;
use Grav\Common\Grav;
use Grav\Common\Twig\Node\TwigNodeCache;
use Twig\Token;
use Twig\TokenParser\AbstractTokenParser;
/**
* Adds ability to cache Twig between tags.
*
* {% cache 600 %}
* {{ some_complex_work() }}
* {% endcache %}
*
* Also can provide a unique key for the cache:
*
* {% cache "prefix-"~lang 600 %}
*
* Where the "prefix-"~lang will use a unique key based on the current language. "prefix-en" for example
*/
class TwigTokenParserCache extends AbstractTokenParser
{
public function parse(Token $token)
{
$stream = $this->parser->getStream();
$lineno = $token->getLine();
// Parse the optional key and timeout parameters
$defaults = [
'key' => $this->parser->getVarName() . $lineno,
'lifetime' => Grav::instance()['cache']->getLifetime()
];
$key = null;
$lifetime = null;
while (!$stream->test(Token::BLOCK_END_TYPE)) {
if ($stream->test(Token::STRING_TYPE)) {
$key = $this->parser->getExpressionParser()->parseExpression();
} elseif ($stream->test(Token::NUMBER_TYPE)) {
$lifetime = $this->parser->getExpressionParser()->parseExpression();
} else {
throw new \Twig\Error\SyntaxError("Unexpected token type in cache tag.", $token->getLine(), $stream->getSourceContext());
}
}
$stream->expect(Token::BLOCK_END_TYPE);
// Parse the content inside the cache block
$body = $this->parser->subparse([$this, 'decideCacheEnd'], true);
$stream->expect(Token::BLOCK_END_TYPE);
return new TwigNodeCache($body, $key, $lifetime, $defaults, $lineno, $this->getTag());
}
public function decideCacheEnd(Token $token): bool
{
return $token->test('endcache');
}
public function getTag(): string
{
return 'cache';
}
} | php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Twig/Exception/TwigException.php | system/src/Grav/Common/Twig/Exception/TwigException.php | <?php
/**
* @package Grav\Common\Twig\Exception
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Twig\Exception;
use RuntimeException;
/**
* TwigException gets thrown when you use {% throw code message %} in twig.
*
* This allows Grav to catch 401, 403 and 404 exceptions and display proper error page.
*/
class TwigException extends RuntimeException
{
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Form/FormFlash.php | system/src/Grav/Common/Form/FormFlash.php | <?php
/**
* @package Grav\Common\Form
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Form;
use Grav\Common\Filesystem\Folder;
use Grav\Common\Utils;
use Grav\Framework\Form\FormFlash as FrameworkFormFlash;
use function is_array;
/**
* Class FormFlash
* @package Grav\Common\Form
*/
class FormFlash extends FrameworkFormFlash
{
/**
* @return array
* @deprecated 1.6 For backwards compatibility only, do not use
*/
public function getLegacyFiles(): array
{
$fields = [];
foreach ($this->files as $field => $files) {
if (strpos($field, '/')) {
continue;
}
foreach ($files as $file) {
if (is_array($file)) {
$file['tmp_name'] = $this->getTmpDir() . '/' . $file['tmp_name'];
$fields[$field][$file['path'] ?? $file['name']] = $file;
}
}
}
return $fields;
}
/**
* @param string $field
* @param string $filename
* @param array $upload
* @return bool
* @deprecated 1.6 For backwards compatibility only, do not use
*/
public function uploadFile(string $field, string $filename, array $upload): bool
{
if (!$this->uniqueId) {
return false;
}
$tmp_dir = $this->getTmpDir();
Folder::create($tmp_dir);
$tmp_file = $upload['file']['tmp_name'];
$basename = Utils::basename($tmp_file);
if (!move_uploaded_file($tmp_file, $tmp_dir . '/' . $basename)) {
return false;
}
$upload['file']['tmp_name'] = $basename;
$upload['file']['name'] = $filename;
$this->addFileInternal($field, $filename, $upload['file']);
return true;
}
/**
* @param string $field
* @param string $filename
* @param array $upload
* @param array $crop
* @return bool
* @deprecated 1.6 For backwards compatibility only, do not use
*/
public function cropFile(string $field, string $filename, array $upload, array $crop): bool
{
if (!$this->uniqueId) {
return false;
}
$tmp_dir = $this->getTmpDir();
Folder::create($tmp_dir);
$tmp_file = $upload['file']['tmp_name'];
$basename = Utils::basename($tmp_file);
if (!move_uploaded_file($tmp_file, $tmp_dir . '/' . $basename)) {
return false;
}
$upload['file']['tmp_name'] = $basename;
$upload['file']['name'] = $filename;
$this->addFileInternal($field, $filename, $upload['file'], $crop);
return true;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/User/User.php | system/src/Grav/Common/User/User.php | <?php
/**
* @package Grav\Common\User
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\User;
use Grav\Common\Grav;
use Grav\Common\User\DataUser;
use Grav\Common\Flex;
use Grav\Common\User\Interfaces\UserCollectionInterface;
use Grav\Common\User\Interfaces\UserInterface;
if (!defined('GRAV_USER_INSTANCE')) {
throw new \LogicException('User class was called too early!');
}
if (defined('GRAV_USER_INSTANCE') && GRAV_USER_INSTANCE === 'FLEX') {
/**
* @deprecated 1.6 Use $grav['accounts'] instead of static calls. In type hints, please use UserInterface.
*/
class User extends Flex\Types\Users\UserObject
{
/**
* Load user account.
*
* Always creates user object. To check if user exists, use $this->exists().
*
* @param string $username
* @return UserInterface
* @deprecated 1.6 Use $grav['accounts']->load(...) instead.
*/
public static function load($username)
{
user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use $grav[\'accounts\']->' . __FUNCTION__ . '() instead', E_USER_DEPRECATED);
return static::getCollection()->load($username);
}
/**
* Find a user by username, email, etc
*
* Always creates user object. To check if user exists, use $this->exists().
*
* @param string $query the query to search for
* @param array $fields the fields to search
* @return UserInterface
* @deprecated 1.6 Use $grav['accounts']->find(...) instead.
*/
public static function find($query, $fields = ['username', 'email'])
{
user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use $grav[\'accounts\']->' . __FUNCTION__ . '() instead', E_USER_DEPRECATED);
return static::getCollection()->find($query, $fields);
}
/**
* Remove user account.
*
* @param string $username
* @return bool True if the action was performed
* @deprecated 1.6 Use $grav['accounts']->delete(...) instead.
*/
public static function remove($username)
{
user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use $grav[\'accounts\']->delete() instead', E_USER_DEPRECATED);
return static::getCollection()->delete($username);
}
/**
* @return UserCollectionInterface
*/
protected static function getCollection()
{
return Grav::instance()['accounts'];
}
}
} else {
/**
* @deprecated 1.6 Use $grav['accounts'] instead of static calls. In type hints, use UserInterface.
*/
class User extends DataUser\User
{
/**
* Load user account.
*
* Always creates user object. To check if user exists, use $this->exists().
*
* @param string $username
* @return UserInterface
* @deprecated 1.6 Use $grav['accounts']->load(...) instead.
*/
public static function load($username)
{
user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use $grav[\'accounts\']->' . __FUNCTION__ . '() instead', E_USER_DEPRECATED);
return static::getCollection()->load($username);
}
/**
* Find a user by username, email, etc
*
* Always creates user object. To check if user exists, use $this->exists().
*
* @param string $query the query to search for
* @param array $fields the fields to search
* @return UserInterface
* @deprecated 1.6 Use $grav['accounts']->find(...) instead.
*/
public static function find($query, $fields = ['username', 'email'])
{
user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use $grav[\'accounts\']->' . __FUNCTION__ . '() instead', E_USER_DEPRECATED);
return static::getCollection()->find($query, $fields);
}
/**
* Remove user account.
*
* @param string $username
* @return bool True if the action was performed
* @deprecated 1.6 Use $grav['accounts']->delete(...) instead.
*/
public static function remove($username)
{
user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use $grav[\'accounts\']->delete() instead', E_USER_DEPRECATED);
return static::getCollection()->delete($username);
}
/**
* @return UserCollectionInterface
*/
protected static function getCollection()
{
return Grav::instance()['accounts'];
}
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/User/Authentication.php | system/src/Grav/Common/User/Authentication.php | <?php
/**
* @package Grav\Common\User
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\User;
use RuntimeException;
/**
* Class Authentication
* @package Grav\Common\User
*/
abstract class Authentication
{
/**
* Create password hash from plaintext password.
*
* @param string $password Plaintext password.
*
* @throws RuntimeException
* @return string
*/
public static function create($password): string
{
if (!$password) {
throw new RuntimeException('Password hashing failed: no password provided.');
}
$hash = password_hash($password, PASSWORD_DEFAULT);
if (!$hash) {
throw new RuntimeException('Password hashing failed: internal error.');
}
return $hash;
}
/**
* Verifies that a password matches a hash.
*
* @param string $password Plaintext password.
* @param string $hash Hash to verify against.
*
* @return int Returns 0 if the check fails, 1 if password matches, 2 if hash needs to be updated.
*/
public static function verify($password, $hash): int
{
// Fail if hash doesn't match
if (!$password || !$hash || !password_verify($password, $hash)) {
return 0;
}
// Otherwise check if hash needs an update.
return password_needs_rehash($hash, PASSWORD_DEFAULT) ? 2 : 1;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/User/Access.php | system/src/Grav/Common/User/Access.php | <?php
/**
* @package Grav\Common\User
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\User;
use function is_bool;
/**
* Class Access
* @package Grav\Common\User
*/
class Access extends \Grav\Framework\Acl\Access
{
/** @var array[] */
private $aliases = [
'admin.configuration.system' => ['admin.configuration_system'],
'admin.configuration.site' => ['admin.configuration_site', 'admin.settings'],
'admin.configuration.media' => ['admin.configuration_media'],
'admin.configuration.info' => ['admin.configuration_info'],
];
/**
* @param string $action
* @return bool|null
*/
public function get(string $action)
{
$result = parent::get($action);
if (is_bool($result)) {
return $result;
}
// Get access value.
if (isset($this->aliases[$action])) {
$aliases = $this->aliases[$action];
foreach ($aliases as $alias) {
$result = parent::get($alias);
if (is_bool($result)) {
return $result;
}
}
}
return null;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/User/Group.php | system/src/Grav/Common/User/Group.php | <?php
/**
* @package Grav\Common\User
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\User;
use Grav\Common\Config\Config;
use Grav\Common\Data\Blueprints;
use Grav\Common\Data\Data;
use Grav\Common\File\CompiledYamlFile;
use Grav\Common\Grav;
use Grav\Common\Utils;
/**
* @deprecated 1.7 Use $grav['user_groups'] instead of this class. In type hints, please use UserGroupInterface.
*/
class Group extends Data
{
/**
* Get the groups list
*
* @return array
* @deprecated 1.7, use $grav['user_groups'] Flex UserGroupCollection instead
*/
protected static function groups()
{
user_error(__METHOD__ . '() is deprecated since Grav 1.7, use $grav[\'user_groups\'] Flex UserGroupCollection instead', E_USER_DEPRECATED);
return Grav::instance()['config']->get('groups', []);
}
/**
* Get the groups list
*
* @return array
* @deprecated 1.7, use $grav['user_groups'] Flex UserGroupCollection instead
*/
public static function groupNames()
{
user_error(__METHOD__ . '() is deprecated since Grav 1.7, use $grav[\'user_groups\'] Flex UserGroupCollection instead', E_USER_DEPRECATED);
$groups = [];
foreach (static::groups() as $groupname => $group) {
$groups[$groupname] = $group['readableName'] ?? $groupname;
}
return $groups;
}
/**
* Checks if a group exists
*
* @param string $groupname
* @return bool
* @deprecated 1.7, use $grav['user_groups'] Flex UserGroupCollection instead
*/
public static function groupExists($groupname)
{
user_error(__METHOD__ . '() is deprecated since Grav 1.7, use $grav[\'user_groups\'] Flex UserGroupCollection instead', E_USER_DEPRECATED);
return isset(self::groups()[$groupname]);
}
/**
* Get a group by name
*
* @param string $groupname
* @return object
* @deprecated 1.7, use $grav['user_groups'] Flex UserGroupCollection instead
*/
public static function load($groupname)
{
user_error(__METHOD__ . '() is deprecated since Grav 1.7, use $grav[\'user_groups\'] Flex UserGroupCollection instead', E_USER_DEPRECATED);
$groups = self::groups();
$content = $groups[$groupname] ?? [];
$content += ['groupname' => $groupname];
$blueprints = new Blueprints();
$blueprint = $blueprints->get('user/group');
return new Group($content, $blueprint);
}
/**
* Save a group
*
* @return void
*/
public function save()
{
$grav = Grav::instance();
/** @var Config $config */
$config = $grav['config'];
$blueprints = new Blueprints();
$blueprint = $blueprints->get('user/group');
$config->set("groups.{$this->get('groupname')}", []);
$fields = $blueprint->fields();
foreach ($fields as $field) {
if ($field['type'] === 'text') {
$value = $field['name'];
if (isset($this->items['data'][$value])) {
$config->set("groups.{$this->get('groupname')}.{$value}", $this->items['data'][$value]);
}
}
if ($field['type'] === 'array' || $field['type'] === 'permissions') {
$value = $field['name'];
$arrayValues = Utils::getDotNotation($this->items['data'], $field['name']);
if ($arrayValues) {
foreach ($arrayValues as $arrayIndex => $arrayValue) {
$config->set("groups.{$this->get('groupname')}.{$value}.{$arrayIndex}", $arrayValue);
}
}
}
}
$type = 'groups';
$blueprints = $this->blueprints();
$filename = CompiledYamlFile::instance($grav['locator']->findResource("config://{$type}.yaml"));
$obj = new Data($config->get($type), $blueprints);
$obj->file($filename);
$obj->save();
}
/**
* Remove a group
*
* @param string $groupname
* @return bool True if the action was performed
* @deprecated 1.7, use $grav['user_groups'] Flex UserGroupCollection instead
*/
public static function remove($groupname)
{
user_error(__METHOD__ . '() is deprecated since Grav 1.7, use $grav[\'user_groups\'] Flex UserGroupCollection instead', E_USER_DEPRECATED);
$grav = Grav::instance();
/** @var Config $config */
$config = $grav['config'];
$blueprints = new Blueprints();
$blueprint = $blueprints->get('user/group');
$type = 'groups';
$groups = $config->get($type);
unset($groups[$groupname]);
$config->set($type, $groups);
$filename = CompiledYamlFile::instance($grav['locator']->findResource("config://{$type}.yaml"));
$obj = new Data($groups, $blueprint);
$obj->file($filename);
$obj->save();
return true;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/User/DataUser/User.php | system/src/Grav/Common/User/DataUser/User.php | <?php
/**
* @package Grav\Common\User
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\User\DataUser;
use Grav\Common\Data\Blueprint;
use Grav\Common\Data\Blueprints;
use Grav\Common\Data\Data;
use Grav\Common\File\CompiledYamlFile;
use Grav\Common\Grav;
use Grav\Common\Media\Interfaces\MediaCollectionInterface;
use Grav\Common\Page\Media;
use Grav\Common\Page\Medium\Medium;
use Grav\Common\Page\Medium\MediumFactory;
use Grav\Common\User\Authentication;
use Grav\Common\User\Interfaces\UserInterface;
use Grav\Common\User\Traits\UserTrait;
use Grav\Common\Utils;
use Grav\Framework\Flex\Flex;
use function is_array;
/**
* Class User
* @package Grav\Common\User\DataUser
*/
class User extends Data implements UserInterface
{
use UserTrait;
/** @var MediaCollectionInterface */
protected $_media;
/**
* User constructor.
* @param array $items
* @param Blueprint|null $blueprints
*/
public function __construct(array $items = [], $blueprints = null)
{
// User can only be authenticated via login.
unset($items['authenticated'], $items['authorized']);
// Always set blueprints.
if (null === $blueprints) {
$blueprints = (new Blueprints)->get('user/account');
}
parent::__construct($items, $blueprints);
}
/**
* @param string $offset
* @return bool
*/
#[\ReturnTypeWillChange]
public function offsetExists($offset)
{
$value = parent::offsetExists($offset);
// Handle special case where user was logged in before 'authorized' was added to the user object.
if (false === $value && $offset === 'authorized') {
$value = $this->offsetExists('authenticated');
}
return $value;
}
/**
* @param string $offset
* @return mixed
*/
#[\ReturnTypeWillChange]
public function offsetGet($offset)
{
$value = parent::offsetGet($offset);
// Handle special case where user was logged in before 'authorized' was added to the user object.
if (null === $value && $offset === 'authorized') {
$value = $this->offsetGet('authenticated');
$this->offsetSet($offset, $value);
}
return $value;
}
/**
* @return bool
*/
public function isValid(): bool
{
return $this->items !== null;
}
/**
* Update object with data
*
* @param array $data
* @param array $files
* @return $this
*/
public function update(array $data, array $files = [])
{
// Note: $this->merge() would cause infinite loop as it calls this method.
parent::merge($data);
return $this;
}
/**
* Save user
*
* @return void
*/
public function save()
{
/** @var CompiledYamlFile|null $file */
$file = $this->file();
if (!$file || !$file->filename()) {
user_error(__CLASS__ . ': calling \$user = new ' . __CLASS__ . "() is deprecated since Grav 1.6, use \$grav['accounts']->load(\$username) or \$grav['accounts']->load('') instead", E_USER_DEPRECATED);
}
if ($file) {
$username = $this->filterUsername((string)$this->get('username'));
if (!$file->filename()) {
$locator = Grav::instance()['locator'];
$file->filename($locator->findResource('account://' . $username . YAML_EXT, true, true));
}
// if plain text password, hash it and remove plain text
$password = $this->get('password') ?? $this->get('password1');
if (null !== $password && '' !== $password) {
$password2 = $this->get('password2');
if (!\is_string($password) || ($password2 && $password !== $password2)) {
throw new \RuntimeException('Passwords did not match.');
}
$this->set('hashed_password', Authentication::create($password));
}
$this->undef('password');
$this->undef('password1');
$this->undef('password2');
$data = $this->items;
if ($username === $data['username']) {
unset($data['username']);
}
unset($data['authenticated'], $data['authorized']);
$file->save($data);
// We need to signal Flex Users about the change.
/** @var Flex|null $flex */
$flex = Grav::instance()['flex'] ?? null;
$users = $flex ? $flex->getDirectory('user-accounts') : null;
if (null !== $users) {
$users->clearCache();
}
}
}
/**
* @return MediaCollectionInterface|Media
*/
public function getMedia()
{
if (null === $this->_media) {
// Media object should only contain avatar, nothing else.
$media = new Media($this->getMediaFolder() ?? '', $this->getMediaOrder(), false);
$path = $this->getAvatarFile();
if ($path && is_file($path)) {
$medium = MediumFactory::fromFile($path);
if ($medium) {
$media->add(Utils::basename($path), $medium);
}
}
$this->_media = $media;
}
return $this->_media;
}
/**
* @return string
*/
public function getMediaFolder()
{
return $this->blueprints()->fields()['avatar']['destination'] ?? 'account://avatars';
}
/**
* @return array
*/
public function getMediaOrder()
{
return [];
}
/**
* Serialize user.
*
* @return string[]
*/
public function __sleep()
{
return [
'items',
'storage'
];
}
/**
* Unserialize user.
*/
public function __wakeup()
{
$this->gettersVariable = 'items';
$this->nestedSeparator = '.';
if (null === $this->items) {
$this->items = [];
}
// Always set blueprints.
if (null === $this->blueprints) {
$this->blueprints = (new Blueprints)->get('user/account');
}
}
/**
* Merge two configurations together.
*
* @param array $data
* @return $this
* @deprecated 1.6 Use `->update($data)` instead (same but with data validation & filtering, file upload support).
*/
public function merge(array $data)
{
user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use ->update($data) method instead', E_USER_DEPRECATED);
return $this->update($data);
}
/**
* Return media object for the User's avatar.
*
* @return Medium|null
* @deprecated 1.6 Use ->getAvatarImage() method instead.
*/
public function getAvatarMedia()
{
user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use getAvatarImage() method instead', E_USER_DEPRECATED);
return $this->getAvatarImage();
}
/**
* Return the User's avatar URL
*
* @return string
* @deprecated 1.6 Use ->getAvatarUrl() method instead.
*/
public function avatarUrl()
{
user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use getAvatarUrl() method instead', E_USER_DEPRECATED);
return $this->getAvatarUrl();
}
/**
* Checks user authorization to the action.
* Ensures backwards compatibility
*
* @param string $action
* @return bool
* @deprecated 1.5 Use ->authorize() method instead.
*/
public function authorise($action)
{
user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.5, use authorize() method instead', E_USER_DEPRECATED);
return $this->authorize($action) ?? false;
}
/**
* Implements Countable interface.
*
* @return int
* @deprecated 1.6 Method makes no sense for user account.
*/
#[\ReturnTypeWillChange]
public function count()
{
user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6', E_USER_DEPRECATED);
return parent::count();
}
/**
* @param string $username
* @return string
*/
protected function filterUsername(string $username): string
{
return mb_strtolower($username);
}
/**
* @return string|null
*/
protected function getAvatarFile(): ?string
{
$avatars = $this->get('avatar');
if (is_array($avatars) && $avatars) {
$avatar = array_shift($avatars);
return $avatar['path'] ?? null;
}
return null;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/User/DataUser/UserCollection.php | system/src/Grav/Common/User/DataUser/UserCollection.php | <?php
/**
* @package Grav\Common\User
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\User\DataUser;
use Grav\Common\Data\Blueprints;
use Grav\Common\File\CompiledYamlFile;
use Grav\Common\Grav;
use Grav\Common\User\Interfaces\UserCollectionInterface;
use Grav\Common\User\Interfaces\UserInterface;
use Grav\Common\Utils;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use RuntimeException;
use function count;
use function in_array;
use function is_string;
/**
* Class UserCollection
* @package Grav\Common\User\DataUser
*/
class UserCollection implements UserCollectionInterface
{
/** @var string */
private $className;
/**
* UserCollection constructor.
* @param string $className
*/
public function __construct(string $className)
{
$this->className = $className;
}
/**
* Load user account.
*
* Always creates user object. To check if user exists, use $this->exists().
*
* @param string $username
* @return UserInterface
*/
public function load($username): UserInterface
{
$username = (string)$username;
$grav = Grav::instance();
/** @var UniformResourceLocator $locator */
$locator = $grav['locator'];
// Filter username.
$username = $this->filterUsername($username);
$filename = 'account://' . $username . YAML_EXT;
$path = $locator->findResource($filename) ?: $locator->findResource($filename, true, true);
if (!is_string($path)) {
throw new RuntimeException('Internal Error');
}
$file = CompiledYamlFile::instance($path);
$content = (array)$file->content() + ['username' => $username, 'state' => 'enabled'];
$userClass = $this->className;
$callable = static function () {
$blueprints = new Blueprints;
return $blueprints->get('user/account');
};
/** @var UserInterface $user */
$user = new $userClass($content, $callable);
$user->file($file);
return $user;
}
/**
* Find a user by username, email, etc
*
* @param string $query the query to search for
* @param array $fields the fields to search
* @return UserInterface
*/
public function find($query, $fields = ['username', 'email']): UserInterface
{
$fields = (array)$fields;
$grav = Grav::instance();
/** @var UniformResourceLocator $locator */
$locator = $grav['locator'];
$account_dir = $locator->findResource('account://');
if (!is_string($account_dir)) {
return $this->load('');
}
$files = array_diff(scandir($account_dir) ?: [], ['.', '..']);
// Try with username first, you never know!
if (in_array('username', $fields, true)) {
$user = $this->load($query);
unset($fields[array_search('username', $fields, true)]);
} else {
$user = $this->load('');
}
// If not found, try the fields
if (!$user->exists()) {
$query = mb_strtolower($query);
foreach ($files as $file) {
if (Utils::endsWith($file, YAML_EXT)) {
$find_user = $this->load(trim(Utils::pathinfo($file, PATHINFO_FILENAME)));
foreach ($fields as $field) {
if (isset($find_user[$field]) && mb_strtolower($find_user[$field]) === $query) {
return $find_user;
}
}
}
}
}
return $user;
}
/**
* Remove user account.
*
* @param string $username
* @return bool True if the action was performed
*/
public function delete($username): bool
{
$file_path = Grav::instance()['locator']->findResource('account://' . $username . YAML_EXT);
return $file_path && unlink($file_path);
}
/**
* @return int
*/
public function count(): int
{
// check for existence of a user account
$account_dir = $file_path = Grav::instance()['locator']->findResource('account://');
$accounts = glob($account_dir . '/*.yaml') ?: [];
return count($accounts);
}
/**
* @param string $username
* @return string
*/
protected function filterUsername(string $username): string
{
return mb_strtolower($username);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/User/Interfaces/UserCollectionInterface.php | system/src/Grav/Common/User/Interfaces/UserCollectionInterface.php | <?php
/**
* @package Grav\Common\User
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\User\Interfaces;
interface UserCollectionInterface extends \Countable
{
/**
* Load user account.
*
* Always creates user object. To check if user exists, use $this->exists().
*
* @param string $username
* @return UserInterface
*/
public function load($username): UserInterface;
/**
* Find a user by username, email, etc
*
* @param string $query the query to search for
* @param array $fields the fields to search
* @return UserInterface
*/
public function find($query, $fields = ['username', 'email']): UserInterface;
/**
* Delete user account.
*
* @param string $username
* @return bool True if user account was found and was deleted.
*/
public function delete($username): bool;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/User/Interfaces/UserGroupInterface.php | system/src/Grav/Common/User/Interfaces/UserGroupInterface.php | <?php
/**
* @package Grav\Common\User
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\User\Interfaces;
/**
* Interface UserGroupInterface
* @package Grav\Common\User\Interfaces
*/
interface UserGroupInterface extends AuthorizeInterface
{
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/User/Interfaces/UserInterface.php | system/src/Grav/Common/User/Interfaces/UserInterface.php | <?php
/**
* @package Grav\Common\User
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\User\Interfaces;
use Grav\Common\Data\Blueprint;
use Grav\Common\Data\DataInterface;
use Grav\Common\Media\Interfaces\MediaInterface;
use Grav\Common\Page\Medium\Medium;
use RocketTheme\Toolbox\ArrayTraits\ExportInterface;
use RuntimeException;
/**
* Interface UserInterface
* @package Grav\Common\User\Interfaces
*
* @property string $username
* @property string $email
* @property string $fullname
* @property string $state
* @property array $groups
* @property array $access
*
* @property bool $authenticated
* @property bool $authorized
*/
interface UserInterface extends AuthorizeInterface, DataInterface, MediaInterface, \ArrayAccess, \JsonSerializable, ExportInterface
{
/**
* @param array $items
* @param Blueprint|callable $blueprints
*/
//public function __construct(array $items = [], $blueprints = null);
/**
* Get value by using dot notation for nested arrays/objects.
*
* @example $value = $this->get('this.is.my.nested.variable');
*
* @param string $name Dot separated path to the requested value.
* @param mixed $default Default value (or null).
* @param string|null $separator Separator, defaults to '.'
* @return mixed Value.
*/
public function get($name, $default = null, $separator = null);
/**
* Set value by using dot notation for nested arrays/objects.
*
* @example $data->set('this.is.my.nested.variable', $value);
*
* @param string $name Dot separated path to the requested value.
* @param mixed $value New value.
* @param string|null $separator Separator, defaults to '.'
* @return $this
*/
public function set($name, $value, $separator = null);
/**
* Unset value by using dot notation for nested arrays/objects.
*
* @example $data->undef('this.is.my.nested.variable');
*
* @param string $name Dot separated path to the requested value.
* @param string|null $separator Separator, defaults to '.'
* @return $this
*/
public function undef($name, $separator = null);
/**
* Set default value by using dot notation for nested arrays/objects.
*
* @example $data->def('this.is.my.nested.variable', 'default');
*
* @param string $name Dot separated path to the requested value.
* @param mixed $default Default value (or null).
* @param string|null $separator Separator, defaults to '.'
* @return $this
*/
public function def($name, $default = null, $separator = null);
/**
* Join nested values together by using blueprints.
*
* @param string $name Dot separated path to the requested value.
* @param mixed $value Value to be joined.
* @param string $separator Separator, defaults to '.'
* @return $this
* @throws RuntimeException
*/
public function join($name, $value, $separator = '.');
/**
* Get nested structure containing default values defined in the blueprints.
*
* Fields without default value are ignored in the list.
* @return array
*/
public function getDefaults();
/**
* Set default values by using blueprints.
*
* @param string $name Dot separated path to the requested value.
* @param mixed $value Value to be joined.
* @param string $separator Separator, defaults to '.'
* @return $this
*/
public function joinDefaults($name, $value, $separator = '.');
/**
* Get value from the configuration and join it with given data.
*
* @param string $name Dot separated path to the requested value.
* @param array|object $value Value to be joined.
* @param string $separator Separator, defaults to '.'
* @return array
* @throws RuntimeException
*/
public function getJoined($name, $value, $separator = '.');
/**
* Set default values to the configuration if variables were not set.
*
* @param array $data
* @return $this
*/
public function setDefaults(array $data);
/**
* Update object with data
*
* @param array $data
* @param array $files
* @return $this
*/
public function update(array $data, array $files = []);
/**
* Returns whether the data already exists in the storage.
*
* NOTE: This method does not check if the data is current.
*
* @return bool
*/
public function exists();
/**
* Return unmodified data as raw string.
*
* NOTE: This function only returns data which has been saved to the storage.
*
* @return string
*/
public function raw();
/**
* Authenticate user.
*
* If user password needs to be updated, new information will be saved.
*
* @param string $password Plaintext password.
* @return bool
*/
public function authenticate(string $password): bool;
/**
* Return media object for the User's avatar.
*
* Note: if there's no local avatar image for the user, you should call getAvatarUrl() to get the external avatar URL.
*
* @return Medium|null
*/
public function getAvatarImage(): ?Medium;
/**
* Return the User's avatar URL.
*
* @return string
*/
public function getAvatarUrl(): string;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/User/Interfaces/AuthorizeInterface.php | system/src/Grav/Common/User/Interfaces/AuthorizeInterface.php | <?php
/**
* @package Grav\Common\User
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\User\Interfaces;
/**
* Interface AuthorizeInterface
* @package Grav\Common\User\Interfaces
*/
interface AuthorizeInterface
{
/**
* Checks user authorization to the action.
*
* @param string $action
* @param string|null $scope
* @return bool|null
*/
public function authorize(string $action, string $scope = null): ?bool;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/User/Traits/UserTrait.php | system/src/Grav/Common/User/Traits/UserTrait.php | <?php
/**
* @package Grav\Common\User
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\User\Traits;
use Grav\Common\Filesystem\Folder;
use Grav\Common\Grav;
use Grav\Common\Page\Medium\ImageMedium;
use Grav\Common\Page\Medium\Medium;
use Grav\Common\Page\Medium\StaticImageMedium;
use Grav\Common\User\Authentication;
use Grav\Common\Utils;
use Multiavatar;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use function is_array;
use function is_string;
/**
* Trait UserTrait
* @package Grav\Common\User\Traits
*/
trait UserTrait
{
/**
* Authenticate user.
*
* If user password needs to be updated, new information will be saved.
*
* @param string $password Plaintext password.
* @return bool
*/
public function authenticate(string $password): bool
{
$hash = $this->get('hashed_password');
$isHashed = null !== $hash;
if (!$isHashed) {
// If there is no hashed password, fake verify with default hash.
$hash = Grav::instance()['config']->get('system.security.default_hash');
}
// Always execute verify() to protect us from timing attacks, but make the test to fail if hashed password wasn't set.
$result = Authentication::verify($password, $hash) && $isHashed;
$plaintext_password = $this->get('password');
if (null !== $plaintext_password) {
// Plain-text password is still stored, check if it matches.
if ($password !== $plaintext_password) {
return false;
}
// Force hash update to get rid of plaintext password.
$result = 2;
}
if ($result === 2) {
// Password needs to be updated, save the user.
$this->set('password', $password);
$this->undef('hashed_password');
$this->save();
}
return (bool)$result;
}
/**
* Checks user authorization to the action.
*
* @param string $action
* @param string|null $scope
* @return bool|null
*/
public function authorize(string $action, string $scope = null): ?bool
{
// User needs to be enabled.
if ($this->get('state', 'enabled') !== 'enabled') {
return false;
}
// User needs to be logged in.
if (!$this->get('authenticated')) {
return false;
}
// User needs to be authorized (2FA).
if (strpos($action, 'login') === false && !$this->get('authorized', true)) {
return false;
}
if (null !== $scope) {
$action = $scope . '.' . $action;
}
$config = Grav::instance()['config'];
$authorized = false;
//Check group access level
$groups = (array)$this->get('groups');
foreach ($groups as $group) {
$permission = $config->get("groups.{$group}.access.{$action}");
$authorized = Utils::isPositive($permission);
if ($authorized === true) {
break;
}
}
//Check user access level
$access = $this->get('access');
if ($access && Utils::getDotNotation($access, $action) !== null) {
$permission = $this->get("access.{$action}");
$authorized = Utils::isPositive($permission);
}
return $authorized;
}
/**
* Return media object for the User's avatar.
*
* Note: if there's no local avatar image for the user, you should call getAvatarUrl() to get the external avatar URL.
*
* @return ImageMedium|StaticImageMedium|null
*/
public function getAvatarImage(): ?Medium
{
$avatars = $this->get('avatar');
if (is_array($avatars) && $avatars) {
$avatar = array_shift($avatars);
$media = $this->getMedia();
$name = $avatar['name'] ?? null;
$image = $name ? $media[$name] : null;
if ($image instanceof ImageMedium ||
$image instanceof StaticImageMedium) {
return $image;
}
}
return null;
}
/**
* Return the User's avatar URL
*
* @return string
*/
public function getAvatarUrl(): string
{
// Try to locate avatar image.
$avatar = $this->getAvatarImage();
if ($avatar) {
return $avatar->url();
}
// Try if avatar is a sting (URL).
$avatar = $this->get('avatar');
if (is_string($avatar)) {
return $avatar;
}
// Try looking for provider.
$provider = $this->get('provider');
$provider_options = $this->get($provider);
if (is_array($provider_options)) {
if (isset($provider_options['avatar_url']) && is_string($provider_options['avatar_url'])) {
return $provider_options['avatar_url'];
}
if (isset($provider_options['avatar']) && is_string($provider_options['avatar'])) {
return $provider_options['avatar'];
}
}
$email = $this->get('email');
$avatar_generator = Grav::instance()['config']->get('system.accounts.avatar', 'multiavatar');
if ($avatar_generator === 'gravatar') {
if (!$email) {
return '';
}
$hash = md5(strtolower(trim($email)));
return 'https://www.gravatar.com/avatar/' . $hash;
}
$hash = $this->get('avatar_hash');
if (!$hash) {
$username = $this->get('username');
$hash = md5(strtolower(trim($email ?? $username)));
}
return $this->generateMultiavatar($hash);
}
/**
* @param string $hash
* @return string
*/
protected function generateMultiavatar(string $hash): string
{
/** @var UniformResourceLocator $locator */
$locator = Grav::instance()['locator'];
$storage = $locator->findResource('image://multiavatar', true, true);
$avatar_file = "{$storage}/{$hash}.svg";
if (!file_exists($storage)) {
Folder::create($storage);
}
if (!file_exists($avatar_file)) {
$mavatar = new Multiavatar();
file_put_contents($avatar_file, $mavatar->generate($hash, null, null));
}
$avatar_url = $locator->findResource("image://multiavatar/{$hash}.svg", false, true);
return Utils::url($avatar_url);
}
abstract public function get($name, $default = null, $separator = null);
abstract public function set($name, $value, $separator = null);
abstract public function undef($name, $separator = null);
abstract public function save();
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/HTTP/Client.php | system/src/Grav/Common/HTTP/Client.php | <?php
/**
* @package Grav\Common\HTTP
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\HTTP;
use Grav\Common\Grav;
use Symfony\Component\HttpClient\CurlHttpClient;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\HttpClient\HttpOptions;
use Symfony\Component\HttpClient\NativeHttpClient;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class Client
{
/** @var callable The callback for the progress, either a function or callback in array notation */
public static $callback = null;
/** @var string[] */
private static $headers = [
'User-Agent' => 'Grav CMS'
];
public static function getClient(array $overrides = [], int $connections = 6, callable $callback = null): HttpClientInterface
{
$config = Grav::instance()['config'];
$options = static::getOptions();
// Use callback if provided
if ($callback) {
self::$callback = $callback;
$options->setOnProgress([Client::class, 'progress']);
}
$settings = array_merge($options->toArray(), $overrides);
$preferred_method = $config->get('system.http.method');
// Try old GPM setting if value is the same as system default
if ($preferred_method === 'auto') {
$preferred_method = $config->get('system.gpm.method', 'auto');
}
switch ($preferred_method) {
case 'curl':
$client = new CurlHttpClient($settings, $connections);
break;
case 'fopen':
case 'native':
$client = new NativeHttpClient($settings, $connections);
break;
default:
$client = HttpClient::create($settings, $connections);
}
return $client;
}
/**
* Get HTTP Options
*
* @return HttpOptions
*/
public static function getOptions(): HttpOptions
{
$config = Grav::instance()['config'];
$referer = defined('GRAV_CLI') ? 'grav_cli' : Grav::instance()['uri']->rootUrl(true);
$options = new HttpOptions();
// Set default Headers
$options->setHeaders(array_merge([ 'Referer' => $referer ], self::$headers));
// Disable verify Peer if required
$verify_peer = $config->get('system.http.verify_peer');
// Try old GPM setting if value is default
if ($verify_peer === true) {
$verify_peer = $config->get('system.gpm.verify_peer', null) ?? $verify_peer;
}
$options->verifyPeer($verify_peer);
// Set verify Host
$verify_host = $config->get('system.http.verify_host', true);
$options->verifyHost($verify_host);
// New setting and must be enabled for Proxy to work
if ($config->get('system.http.enable_proxy', true)) {
// Set proxy url if provided
$proxy_url = $config->get('system.http.proxy_url', $config->get('system.gpm.proxy_url', null));
if ($proxy_url !== null) {
$options->setProxy($proxy_url);
}
// Certificate
$proxy_cert = $config->get('system.http.proxy_cert_path', null);
if ($proxy_cert !== null) {
$options->setCaPath($proxy_cert);
}
}
return $options;
}
/**
* Progress normalized for cURL and Fopen
* Accepts a variable length of arguments passed in by stream method
*
* @return void
*/
public static function progress(int $bytes_transferred, int $filesize, array $info)
{
if ($bytes_transferred > 0) {
$percent = $filesize <= 0 ? 0 : (int)(($bytes_transferred * 100) / $filesize);
$progress = [
'code' => $info['http_code'],
'filesize' => $filesize,
'transferred' => $bytes_transferred,
'percent' => $percent < 100 ? $percent : 100
];
if (self::$callback !== null) {
call_user_func(self::$callback, $progress);
}
}
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/HTTP/Response.php | system/src/Grav/Common/HTTP/Response.php | <?php
/**
* @package Grav\Common\HTTP
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\HTTP;
use Exception;
use Grav\Common\Utils;
use Grav\Common\Grav;
use Symfony\Component\HttpClient\CurlHttpClient;
use Symfony\Component\HttpClient\Exception\TransportException;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\HttpClient\HttpOptions;
use Symfony\Component\HttpClient\NativeHttpClient;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;
use function call_user_func;
use function defined;
/**
* Class Response
* @package Grav\Common\GPM
*/
class Response
{
/**
* Backwards compatible helper method
*
* @param string $uri
* @param array $overrides
* @param callable|null $callback
* @return string
* @throws TransportExceptionInterface|RedirectionExceptionInterface|ServerExceptionInterface|TransportExceptionInterface|ClientExceptionInterface
*/
public static function get(string $uri = '', array $overrides = [], callable $callback = null): string
{
$response = static::request('GET', $uri, $overrides, $callback);
return $response->getContent();
}
/**
* Makes a request to the URL by using the preferred method
*
* @param string $method method to call such as GET, PUT, etc
* @param string $uri URL to call
* @param array $overrides An array of parameters for both `curl` and `fopen`
* @param callable|null $callback Either a function or callback in array notation
* @return ResponseInterface
* @throws TransportExceptionInterface
*/
public static function request(string $method, string $uri, array $overrides = [], callable $callback = null): ResponseInterface
{
if (empty($method)) {
throw new TransportException('missing method (GET, PUT, etc.)');
}
if (empty($uri)) {
throw new TransportException('missing URI');
}
// check if this function is available, if so use it to stop any timeouts
try {
if (Utils::functionExists('set_time_limit')) {
@set_time_limit(0);
}
} catch (Exception $e) {}
$client = Client::getClient($overrides, 6, $callback);
return $client->request($method, $uri);
}
/**
* Is this a remote file or not
*
* @param string $file
* @return bool
*/
public static function isRemote($file): bool
{
return (bool) filter_var($file, FILTER_VALIDATE_URL);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Processors/AssetsProcessor.php | system/src/Grav/Common/Processors/AssetsProcessor.php | <?php
/**
* @package Grav\Common\Processors
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Processors;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
* Class AssetsProcessor
* @package Grav\Common\Processors
*/
class AssetsProcessor extends ProcessorBase
{
/** @var string */
public $id = '_assets';
/** @var string */
public $title = 'Assets';
/**
* @param ServerRequestInterface $request
* @param RequestHandlerInterface $handler
* @return ResponseInterface
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$this->startTimer();
$this->container['assets']->init();
$this->container->fireEvent('onAssetsInitialized');
$this->stopTimer();
return $handler->handle($request);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Processors/DebuggerAssetsProcessor.php | system/src/Grav/Common/Processors/DebuggerAssetsProcessor.php | <?php
/**
* @package Grav\Common\Processors
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Processors;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
* Class DebuggerAssetsProcessor
* @package Grav\Common\Processors
*/
class DebuggerAssetsProcessor extends ProcessorBase
{
/** @var string */
public $id = 'debugger_assets';
/** @var string */
public $title = 'Debugger Assets';
/**
* @param ServerRequestInterface $request
* @param RequestHandlerInterface $handler
* @return ResponseInterface
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$this->startTimer();
$this->container['debugger']->addAssets();
$this->stopTimer();
return $handler->handle($request);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Processors/PagesProcessor.php | system/src/Grav/Common/Processors/PagesProcessor.php | <?php
/**
* @package Grav\Common\Processors
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Processors;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Events\PageEvent;
use Grav\Framework\RequestHandler\Exception\RequestException;
use Grav\Plugin\Form\Forms;
use RocketTheme\Toolbox\Event\Event;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use RuntimeException;
/**
* Class PagesProcessor
* @package Grav\Common\Processors
*/
class PagesProcessor extends ProcessorBase
{
/** @var string */
public $id = 'pages';
/** @var string */
public $title = 'Pages';
/**
* @param ServerRequestInterface $request
* @param RequestHandlerInterface $handler
* @return ResponseInterface
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$this->startTimer();
// Dump Cache state
$this->container['debugger']->addMessage($this->container['cache']->getCacheStatus());
$this->container['pages']->init();
$route = $this->container['route'];
$this->container->fireEvent('onPagesInitialized', new Event(
[
'pages' => $this->container['pages'],
'route' => $route,
'request' => $request
]
));
$this->container->fireEvent('onPageInitialized', new Event(
[
'page' => $this->container['page'],
'route' => $route,
'request' => $request
]
));
/** @var PageInterface $page */
$page = $this->container['page'];
if (!$page->routable()) {
$exception = new RequestException($request, 'Page Not Found', 404);
// If no page found, fire event
$event = new PageEvent([
'page' => $page,
'code' => $exception->getCode(),
'message' => $exception->getMessage(),
'exception' => $exception,
'route' => $route,
'request' => $request
]);
$event->page = null;
$event = $this->container->fireEvent('onPageNotFound', $event);
if (isset($event->page)) {
unset($this->container['page']);
$this->container['page'] = $page = $event->page;
} else {
throw new RuntimeException('Page Not Found', 404);
}
$this->addMessage("Routed to page {$page->rawRoute()} (type: {$page->template()}) [Not Found fallback]");
} else {
$this->addMessage("Routed to page {$page->rawRoute()} (type: {$page->template()})");
$task = $this->container['task'];
$action = $this->container['action'];
/** @var Forms $forms */
$forms = $this->container['forms'] ?? null;
$form = $forms ? $forms->getActiveForm() : null;
$options = ['page' => $page, 'form' => $form, 'request' => $request];
if ($task) {
$event = new Event(['task' => $task] + $options);
$this->container->fireEvent('onPageTask', $event);
$this->container->fireEvent('onPageTask.' . $task, $event);
} elseif ($action) {
$event = new Event(['action' => $action] + $options);
$this->container->fireEvent('onPageAction', $event);
$this->container->fireEvent('onPageAction.' . $action, $event);
}
}
$this->stopTimer();
return $handler->handle($request);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Processors/RenderProcessor.php | system/src/Grav/Common/Processors/RenderProcessor.php | <?php
/**
* @package Grav\Common\Processors
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Processors;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Framework\Psr7\Response;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use RocketTheme\Toolbox\Event\Event;
/**
* Class RenderProcessor
* @package Grav\Common\Processors
*/
class RenderProcessor extends ProcessorBase
{
/** @var string */
public $id = 'render';
/** @var string */
public $title = 'Render';
/**
* @param ServerRequestInterface $request
* @param RequestHandlerInterface $handler
* @return ResponseInterface
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$this->startTimer();
$container = $this->container;
$output = $container['output'];
if ($output instanceof ResponseInterface) {
return $output;
}
/** @var PageInterface $page */
$page = $this->container['page'];
// Use internal Grav output.
$container->output = $output;
ob_start();
$event = new Event(['page' => $page, 'output' => &$container->output]);
$container->fireEvent('onOutputGenerated', $event);
echo $container->output;
$html = ob_get_clean();
// remove any output
$container->output = '';
$event = new Event(['page' => $page, 'output' => $html]);
$this->container->fireEvent('onOutputRendered', $event);
$this->stopTimer();
return new Response($page->httpResponseCode(), $page->httpHeaders(), $html);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Processors/SchedulerProcessor.php | system/src/Grav/Common/Processors/SchedulerProcessor.php | <?php
/**
* @package Grav\Common\Processors
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Processors;
use RocketTheme\Toolbox\Event\Event;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
* Class SchedulerProcessor
* @package Grav\Common\Processors
*/
class SchedulerProcessor extends ProcessorBase
{
/** @var string */
public $id = '_scheduler';
/** @var string */
public $title = 'Scheduler';
/**
* @param ServerRequestInterface $request
* @param RequestHandlerInterface $handler
* @return ResponseInterface
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$this->startTimer();
$scheduler = $this->container['scheduler'];
$this->container->fireEvent('onSchedulerInitialized', new Event(['scheduler' => $scheduler]));
$this->stopTimer();
return $handler->handle($request);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Processors/BackupsProcessor.php | system/src/Grav/Common/Processors/BackupsProcessor.php | <?php
/**
* @package Grav\Common\Processors
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Processors;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
* Class BackupsProcessor
* @package Grav\Common\Processors
*/
class BackupsProcessor extends ProcessorBase
{
/** @var string */
public $id = '_backups';
/** @var string */
public $title = 'Backups';
/**
* @param ServerRequestInterface $request
* @param RequestHandlerInterface $handler
* @return ResponseInterface
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$this->startTimer();
$backups = $this->container['backups'];
$backups->init();
$this->stopTimer();
return $handler->handle($request);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Processors/TwigProcessor.php | system/src/Grav/Common/Processors/TwigProcessor.php | <?php
/**
* @package Grav\Common\Processors
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Processors;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
* Class TwigProcessor
* @package Grav\Common\Processors
*/
class TwigProcessor extends ProcessorBase
{
/** @var string */
public $id = 'twig';
/** @var string */
public $title = 'Twig';
/**
* @param ServerRequestInterface $request
* @param RequestHandlerInterface $handler
* @return ResponseInterface
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$this->startTimer();
$this->container['twig']->init();
$this->stopTimer();
return $handler->handle($request);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Processors/ProcessorInterface.php | system/src/Grav/Common/Processors/ProcessorInterface.php | <?php
/**
* @package Grav\Common\Processors
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Processors;
use Psr\Http\Server\MiddlewareInterface;
/**
* Interface ProcessorInterface
* @package Grav\Common\Processors
*/
interface ProcessorInterface extends MiddlewareInterface
{
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Processors/PluginsProcessor.php | system/src/Grav/Common/Processors/PluginsProcessor.php | <?php
/**
* @package Grav\Common\Processors
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Processors;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
* Class PluginsProcessor
* @package Grav\Common\Processors
*/
class PluginsProcessor extends ProcessorBase
{
/** @var string */
public $id = 'plugins';
/** @var string */
public $title = 'Initialize Plugins';
/**
* @param ServerRequestInterface $request
* @param RequestHandlerInterface $handler
* @return ResponseInterface
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$this->startTimer();
$grav = $this->container;
$grav->fireEvent('onPluginsInitialized');
$this->stopTimer();
return $handler->handle($request);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Processors/InitializeProcessor.php | system/src/Grav/Common/Processors/InitializeProcessor.php | <?php
/**
* @package Grav\Common\Processors
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Processors;
use Grav\Common\Config\Config;
use Grav\Common\Debugger;
use Grav\Common\Errors\Errors;
use Grav\Common\Grav;
use Grav\Common\Page\Pages;
use Grav\Common\Plugins;
use Grav\Common\Session;
use Grav\Common\Uri;
use Grav\Common\Utils;
use Grav\Framework\File\Formatter\YamlFormatter;
use Grav\Framework\File\YamlFile;
use Grav\Framework\Psr7\Response;
use Grav\Framework\Session\Exceptions\SessionException;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\SyslogHandler;
use Monolog\Logger;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use function defined;
use function in_array;
/**
* Class InitializeProcessor
* @package Grav\Common\Processors
*/
class InitializeProcessor extends ProcessorBase
{
/** @var string */
public $id = '_init';
/** @var string */
public $title = 'Initialize';
/** @var bool */
protected static $cli_initialized = false;
/**
* @param Grav $grav
* @return void
*/
public static function initializeCli(Grav $grav)
{
if (!static::$cli_initialized) {
static::$cli_initialized = true;
$instance = new static($grav);
$instance->processCli();
}
}
/**
* @param ServerRequestInterface $request
* @param RequestHandlerInterface $handler
* @return ResponseInterface
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$this->startTimer('_init', 'Initialize');
// Load configuration.
$config = $this->initializeConfig();
// Initialize logger.
$this->initializeLogger($config);
// Initialize error handlers.
$this->initializeErrors();
// Initialize debugger.
$debugger = $this->initializeDebugger();
// Debugger can return response right away.
$response = $this->handleDebuggerRequest($debugger, $request);
if ($response) {
$this->stopTimer('_init');
return $response;
}
// Initialize output buffering.
$this->initializeOutputBuffering($config);
// Set timezone, locale.
$this->initializeLocale($config);
// Load plugins.
$this->initializePlugins();
// Load pages.
$this->initializePages($config);
// Load accounts (decides class to be used).
// TODO: remove in 2.0.
$this->container['accounts'];
// Initialize session (used by URI, see issue #3269).
$this->initializeSession($config);
// Initialize URI (uses session, see issue #3269).
$this->initializeUri($config);
// Grav may return redirect response right away.
$redirectCode = (int)$config->get('system.pages.redirect_trailing_slash', 1);
if ($redirectCode) {
$response = $this->handleRedirectRequest($request, $redirectCode > 300 ? $redirectCode : null);
if ($response) {
$this->stopTimer('_init');
return $response;
}
}
$this->stopTimer('_init');
// Wrap call to next handler so that debugger can profile it.
/** @var Response $response */
$response = $debugger->profile(static function () use ($handler, $request) {
return $handler->handle($request);
});
// Log both request and response and return the response.
return $debugger->logRequest($request, $response);
}
public function processCli(): void
{
// Load configuration.
$config = $this->initializeConfig();
// Initialize logger.
$this->initializeLogger($config);
// Disable debugger.
$this->container['debugger']->enabled(false);
// Set timezone, locale.
$this->initializeLocale($config);
// Load plugins.
$this->initializePlugins();
// Load pages.
$this->initializePages($config);
// Initialize URI.
$this->initializeUri($config);
// Load accounts (decides class to be used).
// TODO: remove in 2.0.
$this->container['accounts'];
}
/**
* @return Config
*/
protected function initializeConfig(): Config
{
$this->startTimer('_init_config', 'Configuration');
// Initialize Configuration
$grav = $this->container;
/** @var Config $config */
$config = $grav['config'];
$config->init();
$grav['plugins']->setup();
if (defined('GRAV_SCHEMA') && $config->get('versions') === null) {
$filename = USER_DIR . 'config/versions.yaml';
if (!is_file($filename)) {
$versions = [
'core' => [
'grav' => [
'version' => GRAV_VERSION,
'schema' => GRAV_SCHEMA
]
]
];
$config->set('versions', $versions);
$file = new YamlFile($filename, new YamlFormatter(['inline' => 4]));
$file->save($versions);
}
}
// Override configuration using the environment.
$prefix = 'GRAV_CONFIG';
$env = getenv($prefix);
if ($env) {
$cPrefix = $prefix . '__';
$aPrefix = $prefix . '_ALIAS__';
$cLen = strlen($cPrefix);
$aLen = strlen($aPrefix);
$keys = $aliases = [];
$env = $_ENV + $_SERVER;
foreach ($env as $key => $value) {
if (!str_starts_with($key, $prefix)) {
continue;
}
if (str_starts_with($key, $cPrefix)) {
$key = str_replace('__', '.', substr($key, $cLen));
$keys[$key] = $value;
} elseif (str_starts_with($key, $aPrefix)) {
$key = substr($key, $aLen);
$aliases[$key] = $value;
}
}
$list = [];
foreach ($keys as $key => $value) {
foreach ($aliases as $alias => $real) {
$key = str_replace($alias, $real, $key);
}
$list[$key] = $value;
$config->set($key, $value);
}
}
$this->stopTimer('_init_config');
return $config;
}
/**
* @param Config $config
* @return Logger
*/
protected function initializeLogger(Config $config): Logger
{
$this->startTimer('_init_logger', 'Logger');
$grav = $this->container;
// Initialize Logging
/** @var Logger $log */
$log = $grav['log'];
if ($config->get('system.log.handler', 'file') === 'syslog') {
$log->popHandler();
$facility = $config->get('system.log.syslog.facility', 'local6');
$tag = $config->get('system.log.syslog.tag', 'grav');
$logHandler = new SyslogHandler($tag, $facility);
$formatter = new LineFormatter("%channel%.%level_name%: %message% %extra%");
$logHandler->setFormatter($formatter);
$log->pushHandler($logHandler);
}
$this->stopTimer('_init_logger');
return $log;
}
/**
* @return Errors
*/
protected function initializeErrors(): Errors
{
$this->startTimer('_init_errors', 'Error Handlers Reset');
$grav = $this->container;
// Initialize Error Handlers
/** @var Errors $errors */
$errors = $grav['errors'];
$errors->resetHandlers();
$this->stopTimer('_init_errors');
return $errors;
}
/**
* @return Debugger
*/
protected function initializeDebugger(): Debugger
{
$this->startTimer('_init_debugger', 'Init Debugger');
$grav = $this->container;
/** @var Debugger $debugger */
$debugger = $grav['debugger'];
$debugger->init();
$this->stopTimer('_init_debugger');
return $debugger;
}
/**
* @param Debugger $debugger
* @param ServerRequestInterface $request
* @return ResponseInterface|null
*/
protected function handleDebuggerRequest(Debugger $debugger, ServerRequestInterface $request): ?ResponseInterface
{
// Clockwork integration.
$clockwork = $debugger->getClockwork();
if ($clockwork) {
$server = $request->getServerParams();
// $baseUri = str_replace('\\', '/', dirname(parse_url($server['SCRIPT_NAME'], PHP_URL_PATH)));
// if ($baseUri === '/') {
// $baseUri = '';
// }
$requestTime = $server['REQUEST_TIME_FLOAT'] ?? GRAV_REQUEST_TIME;
$request = $request->withAttribute('request_time', $requestTime);
// Handle clockwork API calls.
$uri = $request->getUri();
if (Utils::contains($uri->getPath(), '/__clockwork/')) {
return $debugger->debuggerRequest($request);
}
$this->container['clockwork'] = $clockwork;
}
return null;
}
/**
* @param Config $config
*/
protected function initializeOutputBuffering(Config $config): void
{
$this->startTimer('_init_ob', 'Initialize Output Buffering');
// Use output buffering to prevent headers from being sent too early.
ob_start();
if ($config->get('system.cache.gzip') && !@ob_start('ob_gzhandler')) {
// Enable zip/deflate with a fallback in case of if browser does not support compressing.
ob_start();
}
$this->stopTimer('_init_ob');
}
/**
* @param Config $config
*/
protected function initializeLocale(Config $config): void
{
$this->startTimer('_init_locale', 'Initialize Locale');
// Initialize the timezone.
$timezone = $config->get('system.timezone');
if ($timezone) {
date_default_timezone_set($timezone);
}
$grav = $this->container;
$grav->setLocale();
$this->stopTimer('_init_locale');
}
protected function initializePlugins(): Plugins
{
$this->startTimer('_init_plugins_load', 'Load Plugins');
$grav = $this->container;
/** @var Plugins $plugins */
$plugins = $grav['plugins'];
$plugins->init();
$this->stopTimer('_init_plugins_load');
return $plugins;
}
protected function initializePages(Config $config): Pages
{
$this->startTimer('_init_pages_register', 'Load Pages');
$grav = $this->container;
/** @var Pages $pages */
$pages = $grav['pages'];
// Upgrading from older Grav versions won't work without checking if the method exists.
if (method_exists($pages, 'register')) {
$pages->register();
}
$this->stopTimer('_init_pages_register');
return $pages;
}
protected function initializeUri(Config $config): void
{
$this->startTimer('_init_uri', 'Initialize URI');
$grav = $this->container;
/** @var Uri $uri */
$uri = $grav['uri'];
$uri->init();
$this->stopTimer('_init_uri');
}
protected function handleRedirectRequest(RequestInterface $request, int $code = null): ?ResponseInterface
{
if (!in_array($request->getMethod(), ['GET', 'HEAD'])) {
return null;
}
// Redirect pages with trailing slash if configured to do so.
$uri = $request->getUri();
$path = $uri->getPath() ?: '/';
$root = $this->container['uri']->rootUrl();
if ($path !== $root && $path !== $root . '/' && Utils::endsWith($path, '/')) {
// Use permanent redirect for SEO reasons.
return $this->container->getRedirectResponse((string)$uri->withPath(rtrim($path, '/')), $code);
}
return null;
}
/**
* @param Config $config
*/
protected function initializeSession(Config $config): void
{
// FIXME: Initialize session should happen later after plugins have been loaded. This is a workaround to fix session issues in AWS.
if (isset($this->container['session']) && $config->get('system.session.initialize', true)) {
$this->startTimer('_init_session', 'Start Session');
/** @var Session $session */
$session = $this->container['session'];
try {
$session->init();
} catch (SessionException $e) {
$session->init();
$message = 'Session corruption detected, restarting session...';
$this->addMessage($message);
$this->container['messages']->add($message, 'error');
}
$this->stopTimer('_init_session');
}
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Processors/RequestProcessor.php | system/src/Grav/Common/Processors/RequestProcessor.php | <?php
/**
* @package Grav\Common\Processors
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Processors;
use Grav\Common\Processors\Events\RequestHandlerEvent;
use Grav\Common\Uri;
use Grav\Common\Utils;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
* Class RequestProcessor
* @package Grav\Common\Processors
*/
class RequestProcessor extends ProcessorBase
{
/** @var string */
public $id = 'request';
/** @var string */
public $title = 'Request';
/**
* @param ServerRequestInterface $request
* @param RequestHandlerInterface $handler
* @return ResponseInterface
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$this->startTimer();
$header = $request->getHeaderLine('Content-Type');
$type = trim(strstr($header, ';', true) ?: $header);
if ($type === 'application/json') {
$request = $request->withParsedBody(json_decode($request->getBody()->getContents(), true));
}
$uri = $request->getUri();
$ext = mb_strtolower(Utils::pathinfo($uri->getPath(), PATHINFO_EXTENSION));
$request = $request
->withAttribute('grav', $this->container)
->withAttribute('time', $_SERVER['REQUEST_TIME_FLOAT'] ?? GRAV_REQUEST_TIME)
->withAttribute('route', Uri::getCurrentRoute()->withExtension($ext))
->withAttribute('referrer', $this->container['uri']->referrer());
$event = new RequestHandlerEvent(['request' => $request, 'handler' => $handler]);
/** @var RequestHandlerEvent $event */
$event = $this->container->fireEvent('onRequestHandlerInit', $event);
$response = $event->getResponse();
$this->stopTimer();
if ($response) {
return $response;
}
return $handler->handle($request);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Processors/ProcessorBase.php | system/src/Grav/Common/Processors/ProcessorBase.php | <?php
/**
* @package Grav\Common\Processors
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Processors;
use Grav\Common\Debugger;
use Grav\Common\Grav;
/**
* Class ProcessorBase
* @package Grav\Common\Processors
*/
abstract class ProcessorBase implements ProcessorInterface
{
/** @var Grav */
protected $container;
/** @var string */
public $id = 'processorbase';
/** @var string */
public $title = 'ProcessorBase';
/**
* ProcessorBase constructor.
* @param Grav $container
*/
public function __construct(Grav $container)
{
$this->container = $container;
}
/**
* @param string|null $id
* @param string|null $title
*/
protected function startTimer($id = null, $title = null): void
{
/** @var Debugger $debugger */
$debugger = $this->container['debugger'];
$debugger->startTimer($id ?? $this->id, $title ?? $this->title);
}
/**
* @param string|null $id
*/
protected function stopTimer($id = null): void
{
/** @var Debugger $debugger */
$debugger = $this->container['debugger'];
$debugger->stopTimer($id ?? $this->id);
}
/**
* @param string $message
* @param string $label
* @param bool $isString
*/
protected function addMessage($message, $label = 'info', $isString = true): void
{
/** @var Debugger $debugger */
$debugger = $this->container['debugger'];
$debugger->addMessage($message, $label, $isString);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Processors/ThemesProcessor.php | system/src/Grav/Common/Processors/ThemesProcessor.php | <?php
/**
* @package Grav\Common\Processors
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Processors;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
* Class ThemesProcessor
* @package Grav\Common\Processors
*/
class ThemesProcessor extends ProcessorBase
{
/** @var string */
public $id = 'themes';
/** @var string */
public $title = 'Themes';
/**
* @param ServerRequestInterface $request
* @param RequestHandlerInterface $handler
* @return ResponseInterface
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$this->startTimer();
$this->container['themes']->init();
$this->stopTimer();
return $handler->handle($request);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Processors/TasksProcessor.php | system/src/Grav/Common/Processors/TasksProcessor.php | <?php
/**
* @package Grav\Common\Processors
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Processors;
use Grav\Framework\RequestHandler\Exception\NotFoundException;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
* Class TasksProcessor
* @package Grav\Common\Processors
*/
class TasksProcessor extends ProcessorBase
{
/** @var string */
public $id = 'tasks';
/** @var string */
public $title = 'Tasks';
/**
* @param ServerRequestInterface $request
* @param RequestHandlerInterface $handler
* @return ResponseInterface
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$this->startTimer();
$task = $this->container['task'];
$action = $this->container['action'];
if ($task || $action) {
$attributes = $request->getAttribute('controller');
$controllerClass = $attributes['class'] ?? null;
if ($controllerClass) {
/** @var RequestHandlerInterface $controller */
$controller = new $controllerClass($attributes['path'] ?? '', $attributes['params'] ?? []);
try {
$response = $controller->handle($request);
if ($response->getStatusCode() === 418) {
$response = $handler->handle($request);
}
$this->stopTimer();
return $response;
} catch (NotFoundException $e) {
// Task not found: Let it pass through.
}
}
if ($task) {
$this->container->fireEvent('onTask.' . $task);
} elseif ($action) {
$this->container->fireEvent('onAction.' . $action);
}
}
$this->stopTimer();
return $handler->handle($request);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Processors/Events/RequestHandlerEvent.php | system/src/Grav/Common/Processors/Events/RequestHandlerEvent.php | <?php
/**
* @package Grav\Common\Processors
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Processors\Events;
use Grav\Framework\RequestHandler\RequestHandler;
use Grav\Framework\Route\Route;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use RocketTheme\Toolbox\Event\Event;
/**
* Class RequestHandlerEvent
* @package Grav\Common\Processors\Events
*/
class RequestHandlerEvent extends Event
{
/**
* @return ServerRequestInterface
*/
public function getRequest(): ServerRequestInterface
{
return $this->offsetGet('request');
}
/**
* @return Route
*/
public function getRoute(): Route
{
return $this->getRequest()->getAttribute('route');
}
/**
* @return RequestHandler
*/
public function getHandler(): RequestHandler
{
return $this->offsetGet('handler');
}
/**
* @return ResponseInterface|null
*/
public function getResponse(): ?ResponseInterface
{
return $this->offsetGet('response');
}
/**
* @param ResponseInterface $response
* @return $this
*/
public function setResponse(ResponseInterface $response): self
{
$this->offsetSet('response', $response);
$this->stopPropagation();
return $this;
}
/**
* @param string $name
* @param MiddlewareInterface $middleware
* @return RequestHandlerEvent
*/
public function addMiddleware(string $name, MiddlewareInterface $middleware): self
{
/** @var RequestHandler $handler */
$handler = $this['handler'];
$handler->addMiddleware($name, $middleware);
return $this;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/File/CompiledJsonFile.php | system/src/Grav/Common/File/CompiledJsonFile.php | <?php
/**
* @package Grav\Common\File
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\File;
use RocketTheme\Toolbox\File\JsonFile;
/**
* Class CompiledJsonFile
* @package Grav\Common\File
*/
class CompiledJsonFile extends JsonFile
{
use CompiledFile;
/**
* Decode RAW string into contents.
*
* @param string $var
* @param bool $assoc
* @return array
*/
protected function decode($var, $assoc = true)
{
return (array)json_decode($var, $assoc);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/File/CompiledYamlFile.php | system/src/Grav/Common/File/CompiledYamlFile.php | <?php
/**
* @package Grav\Common\File
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\File;
use RocketTheme\Toolbox\File\YamlFile;
/**
* Class CompiledYamlFile
* @package Grav\Common\File
*/
class CompiledYamlFile extends YamlFile
{
use CompiledFile;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/File/CompiledFile.php | system/src/Grav/Common/File/CompiledFile.php | <?php
/**
* @package Grav\Common\File
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\File;
use Exception;
use Grav\Common\Debugger;
use Grav\Common\Grav;
use Grav\Common\Utils;
use RocketTheme\Toolbox\File\PhpFile;
use RuntimeException;
use Throwable;
use function function_exists;
use function get_class;
/**
* Trait CompiledFile
* @package Grav\Common\File
*/
trait CompiledFile
{
/**
* Get/set parsed file contents.
*
* @param mixed $var
* @return array
*/
public function content($var = null)
{
try {
$filename = $this->filename;
// If nothing has been loaded, attempt to get pre-compiled version of the file first.
if ($var === null && $this->raw === null && $this->content === null) {
$key = md5($filename);
$file = PhpFile::instance(CACHE_DIR . "compiled/files/{$key}{$this->extension}.php");
$modified = $this->modified();
if (!$modified) {
try {
return $this->decode($this->raw());
} catch (Throwable $e) {
// If the compiled file is broken, we can safely ignore the error and continue.
}
}
$class = get_class($this);
$size = filesize($filename);
$cache = $file->exists() ? $file->content() : null;
// Load real file if cache isn't up to date (or is invalid).
if (!isset($cache['@class'])
|| $cache['@class'] !== $class
|| $cache['modified'] !== $modified
|| ($cache['size'] ?? null) !== $size
|| $cache['filename'] !== $filename
) {
// Attempt to lock the file for writing.
try {
$locked = $file->lock(false);
} catch (Exception $e) {
$locked = false;
/** @var Debugger $debugger */
$debugger = Grav::instance()['debugger'];
$debugger->addMessage(sprintf('%s(): Cannot obtain a lock for compiling cache file for %s: %s', __METHOD__, $this->filename, $e->getMessage()), 'warning');
}
// Decode RAW file into compiled array.
$data = (array)$this->decode($this->raw());
$cache = [
'@class' => $class,
'filename' => $filename,
'modified' => $modified,
'size' => $size,
'data' => $data
];
// If compiled file wasn't already locked by another process, save it.
if ($locked) {
$file->save($cache);
$file->unlock();
// Compile cached file into bytecode cache
if (function_exists('opcache_invalidate') && filter_var(ini_get('opcache.enable'), \FILTER_VALIDATE_BOOLEAN)) {
$lockName = $file->filename();
// Silence error if function exists, but is restricted.
@opcache_invalidate($lockName, true);
@opcache_compile_file($lockName);
}
}
}
$file->free();
$this->content = $cache['data'];
}
} catch (Exception $e) {
throw new RuntimeException(sprintf('Failed to read %s: %s', Utils::basename($filename), $e->getMessage()), 500, $e);
}
return parent::content($var);
}
/**
* Save file.
*
* @param mixed $data Optional data to be saved, usually array.
* @return void
* @throws RuntimeException
*/
public function save($data = null)
{
// Make sure that the cache file is always up to date!
$key = md5($this->filename);
$file = PhpFile::instance(CACHE_DIR . "compiled/files/{$key}{$this->extension}.php");
try {
$locked = $file->lock();
} catch (Exception $e) {
$locked = false;
/** @var Debugger $debugger */
$debugger = Grav::instance()['debugger'];
$debugger->addMessage(sprintf('%s(): Cannot obtain a lock for compiling cache file for %s: %s', __METHOD__, $this->filename, $e->getMessage()), 'warning');
}
parent::save($data);
if ($locked) {
$modified = $this->modified();
$filename = $this->filename;
$class = get_class($this);
$size = filesize($filename);
// windows doesn't play nicely with this as it can't read when locked
if (!Utils::isWindows()) {
// Reload data from the filesystem. This ensures that we always cache the correct data (see issue #2282).
$this->raw = $this->content = null;
$data = (array)$this->decode($this->raw());
}
// Decode data into compiled array.
$cache = [
'@class' => $class,
'filename' => $filename,
'modified' => $modified,
'size' => $size,
'data' => $data
];
$file->save($cache);
$file->unlock();
// Compile cached file into bytecode cache
if (function_exists('opcache_invalidate') && filter_var(ini_get('opcache.enable'), \FILTER_VALIDATE_BOOLEAN)) {
$lockName = $file->filename();
// Silence error if function exists, but is restricted.
@opcache_invalidate($lockName, true);
@opcache_compile_file($lockName);
}
}
}
/**
* Serialize file.
*
* @return array
*/
public function __sleep()
{
return [
'filename',
'extension',
'raw',
'content',
'settings'
];
}
/**
* Unserialize file.
*/
public function __wakeup()
{
if (!isset(static::$instances[$this->filename])) {
static::$instances[$this->filename] = $this;
}
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/File/CompiledMarkdownFile.php | system/src/Grav/Common/File/CompiledMarkdownFile.php | <?php
/**
* @package Grav\Common\File
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\File;
use RocketTheme\Toolbox\File\MarkdownFile;
/**
* Class CompiledMarkdownFile
* @package Grav\Common\File
*/
class CompiledMarkdownFile extends MarkdownFile
{
use CompiledFile;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Config/CompiledBase.php | system/src/Grav/Common/Config/CompiledBase.php | <?php
/**
* @package Grav\Common\Config
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Config;
use BadMethodCallException;
use Exception;
use RocketTheme\Toolbox\File\PhpFile;
use RuntimeException;
use function get_class;
use function is_array;
/**
* Class CompiledBase
* @package Grav\Common\Config
*/
abstract class CompiledBase
{
/** @var int Version number for the compiled file. */
public $version = 1;
/** @var string Filename (base name) of the compiled configuration. */
public $name;
/** @var string|bool Configuration checksum. */
public $checksum;
/** @var int Timestamp of compiled configuration */
public $timestamp = 0;
/** @var string Cache folder to be used. */
protected $cacheFolder;
/** @var array List of files to load. */
protected $files;
/** @var string */
protected $path;
/** @var mixed Configuration object. */
protected $object;
/**
* @param string $cacheFolder Cache folder to be used.
* @param array $files List of files as returned from ConfigFileFinder class.
* @param string $path Base path for the file list.
* @throws BadMethodCallException
*/
public function __construct($cacheFolder, array $files, $path)
{
if (!$cacheFolder) {
throw new BadMethodCallException('Cache folder not defined.');
}
$this->path = $path ? rtrim($path, '\\/') . '/' : '';
$this->cacheFolder = $cacheFolder;
$this->files = $files;
}
/**
* Get filename for the compiled PHP file.
*
* @param string|null $name
* @return $this
*/
public function name($name = null)
{
if (!$this->name) {
$this->name = $name ?: md5(json_encode(array_keys($this->files)));
}
return $this;
}
/**
* Function gets called when cached configuration is saved.
*
* @return void
*/
public function modified()
{
}
/**
* Get timestamp of compiled configuration
*
* @return int Timestamp of compiled configuration
*/
public function timestamp()
{
return $this->timestamp ?: time();
}
/**
* Load the configuration.
*
* @return mixed
*/
public function load()
{
if ($this->object) {
return $this->object;
}
$filename = $this->createFilename();
if (!$this->loadCompiledFile($filename) && $this->loadFiles()) {
$this->saveCompiledFile($filename);
}
return $this->object;
}
/**
* Returns checksum from the configuration files.
*
* You can set $this->checksum = false to disable this check.
*
* @return bool|string
*/
public function checksum()
{
if (null === $this->checksum) {
$this->checksum = md5(json_encode($this->files) . $this->version);
}
return $this->checksum;
}
/**
* @return string
*/
protected function createFilename()
{
return "{$this->cacheFolder}/{$this->name()->name}.php";
}
/**
* Create configuration object.
*
* @param array $data
* @return void
*/
abstract protected function createObject(array $data = []);
/**
* Finalize configuration object.
*
* @return void
*/
abstract protected function finalizeObject();
/**
* Load single configuration file and append it to the correct position.
*
* @param string $name Name of the position.
* @param string|string[] $filename File(s) to be loaded.
* @return void
*/
abstract protected function loadFile($name, $filename);
/**
* Load and join all configuration files.
*
* @return bool
* @internal
*/
protected function loadFiles()
{
$this->createObject();
$list = array_reverse($this->files);
foreach ($list as $files) {
foreach ($files as $name => $item) {
$this->loadFile($name, $this->path . $item['file']);
}
}
$this->finalizeObject();
return true;
}
/**
* Load compiled file.
*
* @param string $filename
* @return bool
* @internal
*/
protected function loadCompiledFile($filename)
{
if (!file_exists($filename)) {
return false;
}
$cache = include $filename;
if (!is_array($cache)
|| !isset($cache['checksum'], $cache['data'], $cache['@class'])
|| $cache['@class'] !== get_class($this)
) {
return false;
}
// Load real file if cache isn't up to date (or is invalid).
if ($cache['checksum'] !== $this->checksum()) {
return false;
}
$this->createObject($cache['data']);
$this->timestamp = $cache['timestamp'] ?? 0;
$this->finalizeObject();
return true;
}
/**
* Save compiled file.
*
* @param string $filename
* @return void
* @throws RuntimeException
* @internal
*/
protected function saveCompiledFile($filename)
{
$file = PhpFile::instance($filename);
// Attempt to lock the file for writing.
try {
$file->lock(false);
} catch (Exception $e) {
// Another process has locked the file; we will check this in a bit.
}
if ($file->locked() === false) {
// File was already locked by another process.
return;
}
$cache = [
'@class' => get_class($this),
'timestamp' => time(),
'checksum' => $this->checksum(),
'files' => $this->files,
'data' => $this->getState()
];
$file->save($cache);
$file->unlock();
$file->free();
$this->modified();
}
/**
* @return array
*/
protected function getState()
{
return $this->object->toArray();
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Config/CompiledBlueprints.php | system/src/Grav/Common/Config/CompiledBlueprints.php | <?php
/**
* @package Grav\Common\Config
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Config;
use Grav\Common\Data\Blueprint;
use Grav\Common\Data\BlueprintSchema;
use Grav\Common\Grav;
/**
* Class CompiledBlueprints
* @package Grav\Common\Config
*/
class CompiledBlueprints extends CompiledBase
{
/**
* CompiledBlueprints constructor.
* @param string $cacheFolder
* @param array $files
* @param string $path
*/
public function __construct($cacheFolder, array $files, $path)
{
parent::__construct($cacheFolder, $files, $path);
$this->version = 2;
}
/**
* Returns checksum from the configuration files.
*
* You can set $this->checksum = false to disable this check.
*
* @return bool|string
*/
public function checksum()
{
if (null === $this->checksum) {
$this->checksum = md5(json_encode($this->files) . json_encode($this->getTypes()) . $this->version);
}
return $this->checksum;
}
/**
* Create configuration object.
*
* @param array $data
*/
protected function createObject(array $data = [])
{
$this->object = (new BlueprintSchema($data))->setTypes($this->getTypes());
}
/**
* Get list of form field types.
*
* @return array
*/
protected function getTypes()
{
return Grav::instance()['plugins']->formFieldTypes ?: [];
}
/**
* Finalize configuration object.
*
* @return void
*/
protected function finalizeObject()
{
}
/**
* Load single configuration file and append it to the correct position.
*
* @param string $name Name of the position.
* @param array $files Files to be loaded.
* @return void
*/
protected function loadFile($name, $files)
{
// Load blueprint file.
$blueprint = new Blueprint($files);
$this->object->embed($name, $blueprint->load()->toArray(), '/', true);
}
/**
* Load and join all configuration files.
*
* @return bool
* @internal
*/
protected function loadFiles()
{
$this->createObject();
// Convert file list into parent list.
$list = [];
/** @var array $files */
foreach ($this->files as $files) {
foreach ($files as $name => $item) {
$list[$name][] = $this->path . $item['file'];
}
}
// Load files.
foreach ($list as $name => $files) {
$this->loadFile($name, $files);
}
$this->finalizeObject();
return true;
}
/**
* @return array
*/
protected function getState()
{
return $this->object->getState();
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Config/CompiledConfig.php | system/src/Grav/Common/Config/CompiledConfig.php | <?php
/**
* @package Grav\Common\Config
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Config;
use Grav\Common\File\CompiledYamlFile;
use function is_callable;
/**
* Class CompiledConfig
* @package Grav\Common\Config
*/
class CompiledConfig extends CompiledBase
{
/** @var callable Blueprints loader. */
protected $callable;
/** @var bool */
protected $withDefaults = false;
/**
* CompiledConfig constructor.
* @param string $cacheFolder
* @param array $files
* @param string $path
*/
public function __construct($cacheFolder, array $files, $path)
{
parent::__construct($cacheFolder, $files, $path);
$this->version = 1;
}
/**
* Set blueprints for the configuration.
*
* @param callable $blueprints
* @return $this
*/
public function setBlueprints(callable $blueprints)
{
$this->callable = $blueprints;
return $this;
}
/**
* @param bool $withDefaults
* @return mixed
*/
public function load($withDefaults = false)
{
$this->withDefaults = $withDefaults;
return parent::load();
}
/**
* Create configuration object.
*
* @param array $data
* @return void
*/
protected function createObject(array $data = [])
{
if ($this->withDefaults && empty($data) && is_callable($this->callable)) {
$blueprints = $this->callable;
$data = $blueprints()->getDefaults();
}
$this->object = new Config($data, $this->callable);
}
/**
* Finalize configuration object.
*
* @return void
*/
protected function finalizeObject()
{
$this->object->checksum($this->checksum());
$this->object->timestamp($this->timestamp());
}
/**
* Function gets called when cached configuration is saved.
*
* @return void
*/
public function modified()
{
$this->object->modified(true);
}
/**
* Load single configuration file and append it to the correct position.
*
* @param string $name Name of the position.
* @param string $filename File to be loaded.
* @return void
*/
protected function loadFile($name, $filename)
{
$file = CompiledYamlFile::instance($filename);
$this->object->join($name, $file->content(), '/');
$file->free();
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Config/CompiledLanguages.php | system/src/Grav/Common/Config/CompiledLanguages.php | <?php
/**
* @package Grav\Common\Config
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Config;
use Grav\Common\File\CompiledYamlFile;
/**
* Class CompiledLanguages
* @package Grav\Common\Config
*/
class CompiledLanguages extends CompiledBase
{
/**
* CompiledLanguages constructor.
* @param string $cacheFolder
* @param array $files
* @param string $path
*/
public function __construct($cacheFolder, array $files, $path)
{
parent::__construct($cacheFolder, $files, $path);
$this->version = 1;
}
/**
* Create configuration object.
*
* @param array $data
* @return void
*/
protected function createObject(array $data = [])
{
$this->object = new Languages($data);
}
/**
* Finalize configuration object.
*
* @return void
*/
protected function finalizeObject()
{
$this->object->checksum($this->checksum());
$this->object->timestamp($this->timestamp());
}
/**
* Function gets called when cached configuration is saved.
*
* @return void
*/
public function modified()
{
$this->object->modified(true);
}
/**
* Load single configuration file and append it to the correct position.
*
* @param string $name Name of the position.
* @param string $filename File to be loaded.
* @return void
*/
protected function loadFile($name, $filename)
{
$file = CompiledYamlFile::instance($filename);
if (preg_match('|languages\.yaml$|', $filename)) {
$this->object->mergeRecursive((array) $file->content());
} else {
$this->object->mergeRecursive([$name => $file->content()]);
}
$file->free();
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Config/Config.php | system/src/Grav/Common/Config/Config.php | <?php
/**
* @package Grav\Common\Config
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Config;
use Grav\Common\Debugger;
use Grav\Common\Grav;
use Grav\Common\Data\Data;
use Grav\Common\Service\ConfigServiceProvider;
use Grav\Common\Utils;
use function is_array;
/**
* Class Config
* @package Grav\Common\Config
*/
class Config extends Data
{
/** @var string */
public $environment;
/** @var string */
protected $key;
/** @var string */
protected $checksum;
/** @var int */
protected $timestamp = 0;
/** @var bool */
protected $modified = false;
/**
* @return string
*/
public function key()
{
if (null === $this->key) {
$this->key = md5($this->checksum . $this->timestamp);
}
return $this->key;
}
/**
* @param string|null $checksum
* @return string|null
*/
public function checksum($checksum = null)
{
if ($checksum !== null) {
$this->checksum = $checksum;
}
return $this->checksum;
}
/**
* @param bool|null $modified
* @return bool
*/
public function modified($modified = null)
{
if ($modified !== null) {
$this->modified = $modified;
}
return $this->modified;
}
/**
* @param int|null $timestamp
* @return int
*/
public function timestamp($timestamp = null)
{
if ($timestamp !== null) {
$this->timestamp = $timestamp;
}
return $this->timestamp;
}
/**
* @return $this
*/
public function reload()
{
$grav = Grav::instance();
// Load new configuration.
$config = ConfigServiceProvider::load($grav);
/** @var Debugger $debugger */
$debugger = $grav['debugger'];
if ($config->modified()) {
// Update current configuration.
$this->items = $config->toArray();
$this->checksum($config->checksum());
$this->modified(true);
$debugger->addMessage('Configuration was changed and saved.');
}
return $this;
}
/**
* @return void
*/
public function debug()
{
/** @var Debugger $debugger */
$debugger = Grav::instance()['debugger'];
$debugger->addMessage('Environment Name: ' . $this->environment);
if ($this->modified()) {
$debugger->addMessage('Configuration reloaded and cached.');
}
}
/**
* @return void
*/
public function init()
{
$setup = Grav::instance()['setup']->toArray();
foreach ($setup as $key => $value) {
if ($key === 'streams' || !is_array($value)) {
// Optimized as streams and simple values are fully defined in setup.
$this->items[$key] = $value;
} else {
$this->joinDefaults($key, $value);
}
}
// Legacy value - Override the media.upload_limit based on PHP values
$this->items['system']['media']['upload_limit'] = Utils::getUploadLimit();
}
/**
* @return mixed
* @deprecated 1.5 Use Grav::instance()['languages'] instead.
*/
public function getLanguages()
{
user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.5, use Grav::instance()[\'languages\'] instead', E_USER_DEPRECATED);
return Grav::instance()['languages'];
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Config/ConfigFileFinder.php | system/src/Grav/Common/Config/ConfigFileFinder.php | <?php
/**
* @package Grav\Common\Config
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Config;
use DirectoryIterator;
use Grav\Common\Filesystem\Folder;
use RecursiveDirectoryIterator;
/**
* Class ConfigFileFinder
* @package Grav\Common\Config
*/
class ConfigFileFinder
{
/** @var string */
protected $base = '';
/**
* @param string $base
* @return $this
*/
public function setBase($base)
{
$this->base = $base ? "{$base}/" : '';
return $this;
}
/**
* Return all locations for all the files with a timestamp.
*
* @param array $paths List of folders to look from.
* @param string $pattern Pattern to match the file. Pattern will also be removed from the key.
* @param int $levels Maximum number of recursive directories.
* @return array
*/
public function locateFiles(array $paths, $pattern = '|\.yaml$|', $levels = -1)
{
$list = [];
foreach ($paths as $folder) {
$list += $this->detectRecursive($folder, $pattern, $levels);
}
return $list;
}
/**
* Return all locations for all the files with a timestamp.
*
* @param array $paths List of folders to look from.
* @param string $pattern Pattern to match the file. Pattern will also be removed from the key.
* @param int $levels Maximum number of recursive directories.
* @return array
*/
public function getFiles(array $paths, $pattern = '|\.yaml$|', $levels = -1)
{
$list = [];
foreach ($paths as $folder) {
$path = trim(Folder::getRelativePath($folder), '/');
$files = $this->detectRecursive($folder, $pattern, $levels);
$list += $files[trim($path, '/')];
}
return $list;
}
/**
* Return all paths for all the files with a timestamp.
*
* @param array $paths List of folders to look from.
* @param string $pattern Pattern to match the file. Pattern will also be removed from the key.
* @param int $levels Maximum number of recursive directories.
* @return array
*/
public function listFiles(array $paths, $pattern = '|\.yaml$|', $levels = -1)
{
$list = [];
foreach ($paths as $folder) {
$list = array_merge_recursive($list, $this->detectAll($folder, $pattern, $levels));
}
return $list;
}
/**
* Find filename from a list of folders.
*
* Note: Only finds the last override.
*
* @param string $filename
* @param array $folders
* @return array
*/
public function locateFileInFolder($filename, array $folders)
{
$list = [];
foreach ($folders as $folder) {
$list += $this->detectInFolder($folder, $filename);
}
return $list;
}
/**
* Find filename from a list of folders.
*
* @param array $folders
* @param string|null $filename
* @return array
*/
public function locateInFolders(array $folders, $filename = null)
{
$list = [];
foreach ($folders as $folder) {
$path = trim(Folder::getRelativePath($folder), '/');
$list[$path] = $this->detectInFolder($folder, $filename);
}
return $list;
}
/**
* Return all existing locations for a single file with a timestamp.
*
* @param array $paths Filesystem paths to look up from.
* @param string $name Configuration file to be located.
* @param string $ext File extension (optional, defaults to .yaml).
* @return array
*/
public function locateFile(array $paths, $name, $ext = '.yaml')
{
$filename = preg_replace('|[.\/]+|', '/', $name) . $ext;
$list = [];
foreach ($paths as $folder) {
$path = trim(Folder::getRelativePath($folder), '/');
if (is_file("{$folder}/{$filename}")) {
$modified = filemtime("{$folder}/{$filename}");
} else {
$modified = 0;
}
$basename = $this->base . $name;
$list[$path] = [$basename => ['file' => "{$path}/{$filename}", 'modified' => $modified]];
}
return $list;
}
/**
* Detects all directories with a configuration file and returns them with last modification time.
*
* @param string $folder Location to look up from.
* @param string $pattern Pattern to match the file. Pattern will also be removed from the key.
* @param int $levels Maximum number of recursive directories.
* @return array
* @internal
*/
protected function detectRecursive($folder, $pattern, $levels)
{
$path = trim(Folder::getRelativePath($folder), '/');
if (is_dir($folder)) {
// Find all system and user configuration files.
$options = [
'levels' => $levels,
'compare' => 'Filename',
'pattern' => $pattern,
'filters' => [
'pre-key' => $this->base,
'key' => $pattern,
'value' => function (RecursiveDirectoryIterator $file) use ($path) {
return ['file' => "{$path}/{$file->getSubPathname()}", 'modified' => $file->getMTime()];
}
],
'key' => 'SubPathname'
];
$list = Folder::all($folder, $options);
ksort($list);
} else {
$list = [];
}
return [$path => $list];
}
/**
* Detects all directories with the lookup file and returns them with last modification time.
*
* @param string $folder Location to look up from.
* @param string|null $lookup Filename to be located (defaults to directory name).
* @return array
* @internal
*/
protected function detectInFolder($folder, $lookup = null)
{
$folder = rtrim($folder, '/');
$path = trim(Folder::getRelativePath($folder), '/');
$base = $path === $folder ? '' : ($path ? substr($folder, 0, -strlen($path)) : $folder . '/');
$list = [];
if (is_dir($folder)) {
$iterator = new DirectoryIterator($folder);
foreach ($iterator as $directory) {
if (!$directory->isDir() || $directory->isDot()) {
continue;
}
$name = $directory->getFilename();
$find = ($lookup ?: $name) . '.yaml';
$filename = "{$path}/{$name}/{$find}";
if (file_exists($base . $filename)) {
$basename = $this->base . $name;
$list[$basename] = ['file' => $filename, 'modified' => filemtime($base . $filename)];
}
}
}
return $list;
}
/**
* Detects all plugins with a configuration file and returns them with last modification time.
*
* @param string $folder Location to look up from.
* @param string $pattern Pattern to match the file. Pattern will also be removed from the key.
* @param int $levels Maximum number of recursive directories.
* @return array
* @internal
*/
protected function detectAll($folder, $pattern, $levels)
{
$path = trim(Folder::getRelativePath($folder), '/');
if (is_dir($folder)) {
// Find all system and user configuration files.
$options = [
'levels' => $levels,
'compare' => 'Filename',
'pattern' => $pattern,
'filters' => [
'pre-key' => $this->base,
'key' => $pattern,
'value' => function (RecursiveDirectoryIterator $file) use ($path) {
return ["{$path}/{$file->getSubPathname()}" => $file->getMTime()];
}
],
'key' => 'SubPathname'
];
$list = Folder::all($folder, $options);
ksort($list);
} else {
$list = [];
}
return $list;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Config/Setup.php | system/src/Grav/Common/Config/Setup.php | <?php
/**
* @package Grav\Common\Config
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Config;
use BadMethodCallException;
use Grav\Common\File\CompiledYamlFile;
use Grav\Common\Data\Data;
use Grav\Common\Utils;
use InvalidArgumentException;
use Pimple\Container;
use Psr\Http\Message\ServerRequestInterface;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use RuntimeException;
use function defined;
use function is_array;
/**
* Class Setup
* @package Grav\Common\Config
*/
class Setup extends Data
{
/**
* @var array Environment aliases normalized to lower case.
*/
public static $environments = [
'' => 'unknown',
'127.0.0.1' => 'localhost',
'::1' => 'localhost'
];
/**
* @var string|null Current environment normalized to lower case.
*/
public static $environment;
/** @var string */
public static $securityFile = 'config://security.yaml';
/** @var array */
protected $streams = [
'user' => [
'type' => 'ReadOnlyStream',
'force' => true,
'prefixes' => [
'' => [] // Set in constructor
]
],
'cache' => [
'type' => 'Stream',
'force' => true,
'prefixes' => [
'' => [], // Set in constructor
'images' => ['images']
]
],
'log' => [
'type' => 'Stream',
'force' => true,
'prefixes' => [
'' => [] // Set in constructor
]
],
'tmp' => [
'type' => 'Stream',
'force' => true,
'prefixes' => [
'' => [] // Set in constructor
]
],
'backup' => [
'type' => 'Stream',
'force' => true,
'prefixes' => [
'' => [] // Set in constructor
]
],
'environment' => [
'type' => 'ReadOnlyStream'
// If not defined, environment will be set up in the constructor.
],
'system' => [
'type' => 'ReadOnlyStream',
'prefixes' => [
'' => ['system'],
]
],
'asset' => [
'type' => 'Stream',
'prefixes' => [
'' => ['assets'],
]
],
'blueprints' => [
'type' => 'ReadOnlyStream',
'prefixes' => [
'' => ['environment://blueprints', 'user://blueprints', 'system://blueprints'],
]
],
'config' => [
'type' => 'ReadOnlyStream',
'prefixes' => [
'' => ['environment://config', 'user://config', 'system://config'],
]
],
'plugins' => [
'type' => 'ReadOnlyStream',
'prefixes' => [
'' => ['user://plugins'],
]
],
'plugin' => [
'type' => 'ReadOnlyStream',
'prefixes' => [
'' => ['user://plugins'],
]
],
'themes' => [
'type' => 'ReadOnlyStream',
'prefixes' => [
'' => ['user://themes'],
]
],
'languages' => [
'type' => 'ReadOnlyStream',
'prefixes' => [
'' => ['environment://languages', 'user://languages', 'system://languages'],
]
],
'image' => [
'type' => 'Stream',
'prefixes' => [
'' => ['user://images', 'system://images']
]
],
'page' => [
'type' => 'ReadOnlyStream',
'prefixes' => [
'' => ['user://pages']
]
],
'user-data' => [
'type' => 'Stream',
'force' => true,
'prefixes' => [
'' => ['user://data']
]
],
'account' => [
'type' => 'ReadOnlyStream',
'prefixes' => [
'' => ['user://accounts']
]
],
];
/**
* @param Container|array $container
*/
public function __construct($container)
{
// Configure main streams.
$abs = str_starts_with(GRAV_SYSTEM_PATH, '/');
$this->streams['system']['prefixes'][''] = $abs ? ['system', GRAV_SYSTEM_PATH] : ['system'];
$this->streams['user']['prefixes'][''] = [GRAV_USER_PATH];
$this->streams['cache']['prefixes'][''] = [GRAV_CACHE_PATH];
$this->streams['log']['prefixes'][''] = [GRAV_LOG_PATH];
$this->streams['tmp']['prefixes'][''] = [GRAV_TMP_PATH];
$this->streams['backup']['prefixes'][''] = [GRAV_BACKUP_PATH];
// If environment is not set, look for the environment variable and then the constant.
$environment = static::$environment ??
(defined('GRAV_ENVIRONMENT') ? GRAV_ENVIRONMENT : (getenv('GRAV_ENVIRONMENT') ?: null));
// If no environment is set, make sure we get one (CLI or hostname).
if (null === $environment) {
if (defined('GRAV_CLI')) {
$request = null;
$uri = null;
$environment = 'cli';
} else {
/** @var ServerRequestInterface $request */
$request = $container['request'];
$uri = $request->getUri();
$environment = $uri->getHost();
}
}
// Resolve server aliases to the proper environment.
static::$environment = static::$environments[$environment] ?? $environment;
// Pre-load setup.php which contains our initial configuration.
// Configuration may contain dynamic parts, which is why we need to always load it.
// If GRAV_SETUP_PATH has been defined, use it, otherwise use defaults.
$setupFile = defined('GRAV_SETUP_PATH') ? GRAV_SETUP_PATH : (getenv('GRAV_SETUP_PATH') ?: null);
if (null !== $setupFile) {
// Make sure that the custom setup file exists. Terminates the script if not.
if (!str_starts_with($setupFile, '/')) {
$setupFile = GRAV_WEBROOT . '/' . $setupFile;
}
if (!is_file($setupFile)) {
echo 'GRAV_SETUP_PATH is defined but does not point to existing setup file.';
exit(1);
}
} else {
$setupFile = GRAV_WEBROOT . '/setup.php';
if (!is_file($setupFile)) {
$setupFile = GRAV_WEBROOT . '/' . GRAV_USER_PATH . '/setup.php';
}
if (!is_file($setupFile)) {
$setupFile = null;
}
}
$setup = $setupFile ? (array) include $setupFile : [];
// Add default streams defined in beginning of the class.
if (!isset($setup['streams']['schemes'])) {
$setup['streams']['schemes'] = [];
}
$setup['streams']['schemes'] += $this->streams;
// Initialize class.
parent::__construct($setup);
$this->def('environment', static::$environment);
// Figure out path for the current environment.
$envPath = defined('GRAV_ENVIRONMENT_PATH') ? GRAV_ENVIRONMENT_PATH : (getenv('GRAV_ENVIRONMENT_PATH') ?: null);
if (null === $envPath) {
// Find common path for all environments and append current environment into it.
$envPath = defined('GRAV_ENVIRONMENTS_PATH') ? GRAV_ENVIRONMENTS_PATH : (getenv('GRAV_ENVIRONMENTS_PATH') ?: null);
if (null !== $envPath) {
$envPath .= '/';
} else {
// Use default location. Start with Grav 1.7 default.
$envPath = GRAV_WEBROOT. '/' . GRAV_USER_PATH . '/env';
if (is_dir($envPath)) {
$envPath = 'user://env/';
} else {
// Fallback to Grav 1.6 default.
$envPath = 'user://';
}
}
$envPath .= $this->get('environment');
}
// Set up environment.
$this->def('environment', static::$environment);
$this->def('streams.schemes.environment.prefixes', ['' => [$envPath]]);
}
/**
* @return $this
* @throws RuntimeException
* @throws InvalidArgumentException
*/
public function init()
{
$locator = new UniformResourceLocator(GRAV_WEBROOT);
$files = [];
$guard = 5;
do {
$check = $files;
$this->initializeLocator($locator);
$files = $locator->findResources('config://streams.yaml');
if ($check === $files) {
break;
}
// Update streams.
foreach (array_reverse($files) as $path) {
$file = CompiledYamlFile::instance($path);
$content = (array)$file->content();
if (!empty($content['schemes'])) {
$this->items['streams']['schemes'] = $content['schemes'] + $this->items['streams']['schemes'];
}
}
} while (--$guard);
if (!$guard) {
throw new RuntimeException('Setup: Configuration reload loop detected!');
}
// Make sure we have valid setup.
$this->check($locator);
return $this;
}
/**
* Initialize resource locator by using the configuration.
*
* @param UniformResourceLocator $locator
* @return void
* @throws BadMethodCallException
*/
public function initializeLocator(UniformResourceLocator $locator)
{
$locator->reset();
$schemes = (array) $this->get('streams.schemes', []);
foreach ($schemes as $scheme => $config) {
if (isset($config['paths'])) {
$locator->addPath($scheme, '', $config['paths']);
}
$override = $config['override'] ?? false;
$force = $config['force'] ?? false;
if (isset($config['prefixes'])) {
foreach ((array)$config['prefixes'] as $prefix => $paths) {
$locator->addPath($scheme, $prefix, $paths, $override, $force);
}
}
}
}
/**
* Get available streams and their types from the configuration.
*
* @return array
*/
public function getStreams()
{
$schemes = [];
foreach ((array) $this->get('streams.schemes') as $scheme => $config) {
$type = $config['type'] ?? 'ReadOnlyStream';
if ($type[0] !== '\\') {
$type = '\\RocketTheme\\Toolbox\\StreamWrapper\\' . $type;
}
$schemes[$scheme] = $type;
}
return $schemes;
}
/**
* @param UniformResourceLocator $locator
* @return void
* @throws InvalidArgumentException
* @throws BadMethodCallException
* @throws RuntimeException
*/
protected function check(UniformResourceLocator $locator)
{
$streams = $this->items['streams']['schemes'] ?? null;
if (!is_array($streams)) {
throw new InvalidArgumentException('Configuration is missing streams.schemes!');
}
$diff = array_keys(array_diff_key($this->streams, $streams));
if ($diff) {
throw new InvalidArgumentException(
sprintf('Configuration is missing keys %s from streams.schemes!', implode(', ', $diff))
);
}
try {
// If environment is found, remove all missing override locations (B/C compatibility).
if ($locator->findResource('environment://', true)) {
$force = $this->get('streams.schemes.environment.force', false);
if (!$force) {
$prefixes = $this->get('streams.schemes.environment.prefixes.');
$update = false;
foreach ($prefixes as $i => $prefix) {
if ($locator->isStream($prefix)) {
if ($locator->findResource($prefix, true)) {
break;
}
} elseif (file_exists($prefix)) {
break;
}
unset($prefixes[$i]);
$update = true;
}
if ($update) {
$this->set('streams.schemes.environment.prefixes', ['' => array_values($prefixes)]);
$this->initializeLocator($locator);
}
}
}
if (!$locator->findResource('environment://config', true)) {
// If environment does not have its own directory, remove it from the lookup.
$prefixes = $this->get('streams.schemes.environment.prefixes');
$prefixes['config'] = [];
$this->set('streams.schemes.environment.prefixes', $prefixes);
$this->initializeLocator($locator);
}
// Create security.yaml salt if it doesn't exist into existing configuration environment if possible.
$securityFile = Utils::basename(static::$securityFile);
$securityFolder = substr(static::$securityFile, 0, -\strlen($securityFile));
$securityFolder = $locator->findResource($securityFolder, true) ?: $locator->findResource($securityFolder, true, true);
$filename = "{$securityFolder}/{$securityFile}";
$security_file = CompiledYamlFile::instance($filename);
$security_content = (array)$security_file->content();
if (!isset($security_content['salt'])) {
$security_content = array_merge($security_content, ['salt' => Utils::generateRandomString(14)]);
$security_file->content($security_content);
$security_file->save();
$security_file->free();
}
} catch (RuntimeException $e) {
throw new RuntimeException(sprintf('Grav failed to initialize: %s', $e->getMessage()), 500, $e);
}
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Config/Languages.php | system/src/Grav/Common/Config/Languages.php | <?php
/**
* @package Grav\Common\Config
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Config;
use Grav\Common\Data\Data;
use Grav\Common\Utils;
/**
* Class Languages
* @package Grav\Common\Config
*/
class Languages extends Data
{
/** @var string|null */
protected $checksum;
/** @var bool */
protected $modified = false;
/** @var int */
protected $timestamp = 0;
/**
* @param string|null $checksum
* @return string|null
*/
public function checksum($checksum = null)
{
if ($checksum !== null) {
$this->checksum = $checksum;
}
return $this->checksum;
}
/**
* @param bool|null $modified
* @return bool
*/
public function modified($modified = null)
{
if ($modified !== null) {
$this->modified = $modified;
}
return $this->modified;
}
/**
* @param int|null $timestamp
* @return int
*/
public function timestamp($timestamp = null)
{
if ($timestamp !== null) {
$this->timestamp = $timestamp;
}
return $this->timestamp;
}
/**
* @return void
*/
public function reformat()
{
if (isset($this->items['plugins'])) {
$this->items = array_merge_recursive($this->items, $this->items['plugins']);
unset($this->items['plugins']);
}
}
/**
* @param array $data
* @return void
*/
public function mergeRecursive(array $data)
{
$this->items = Utils::arrayMergeRecursiveUnique($this->items, $data);
}
/**
* @param string $lang
* @return array
*/
public function flattenByLang($lang)
{
$language = $this->items[$lang];
return Utils::arrayFlattenDotNotation($language);
}
/**
* @param array $array
* @return array
*/
public function unflatten($array)
{
return Utils::arrayUnflattenDotNotation($array);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Scheduler/JobHistory.php | system/src/Grav/Common/Scheduler/JobHistory.php | <?php
/**
* @package Grav\Common\Scheduler
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Scheduler;
use DateTime;
use RocketTheme\Toolbox\File\JsonFile;
/**
* Job History Manager
*
* Provides comprehensive job execution history, logging, and analytics
*
* @package Grav\Common\Scheduler
*/
class JobHistory
{
/** @var string */
protected $historyPath;
/** @var int */
protected $retentionDays = 30;
/** @var int */
protected $maxOutputLength = 5000;
/**
* Constructor
*
* @param string $historyPath
* @param int $retentionDays
*/
public function __construct(string $historyPath, int $retentionDays = 30)
{
$this->historyPath = $historyPath;
$this->retentionDays = $retentionDays;
// Ensure history directory exists
if (!is_dir($this->historyPath)) {
mkdir($this->historyPath, 0755, true);
}
}
/**
* Log job execution
*
* @param Job $job
* @param array $metadata Additional metadata to store
* @return string Log entry ID
*/
public function logExecution(Job $job, array $metadata = []): string
{
$entryId = uniqid($job->getId() . '_', true);
$timestamp = new DateTime();
$entry = [
'id' => $entryId,
'job_id' => $job->getId(),
'command' => is_string($job->getCommand()) ? $job->getCommand() : 'Closure',
'arguments' => method_exists($job, 'getRawArguments') ? $job->getRawArguments() : $job->getArguments(),
'executed_at' => $timestamp->format('c'),
'timestamp' => $timestamp->getTimestamp(),
'success' => $job->isSuccessful(),
'output' => $this->captureOutput($job),
'execution_time' => method_exists($job, 'getExecutionTime') ? $job->getExecutionTime() : null,
'retry_count' => method_exists($job, 'getRetryCount') ? $job->getRetryCount() : 0,
'priority' => method_exists($job, 'getPriority') ? $job->getPriority() : 'normal',
'tags' => method_exists($job, 'getTags') ? $job->getTags() : [],
'metadata' => array_merge(
method_exists($job, 'getMetadata') ? $job->getMetadata() : [],
$metadata
),
];
// Store in daily file
$this->storeEntry($entry);
// Also store in job-specific history
$this->storeJobHistory($job->getId(), $entry);
return $entryId;
}
/**
* Capture job output with length limit
*
* @param Job $job
* @return array
*/
protected function captureOutput(Job $job): array
{
$output = $job->getOutput();
$truncated = false;
if (strlen($output) > $this->maxOutputLength) {
$output = substr($output, 0, $this->maxOutputLength);
$truncated = true;
}
return [
'content' => $output,
'truncated' => $truncated,
'length' => strlen($job->getOutput()),
];
}
/**
* Store entry in daily log file
*
* @param array $entry
* @return void
*/
protected function storeEntry(array $entry): void
{
$date = date('Y-m-d');
$filename = $this->historyPath . '/' . $date . '.json';
$jsonFile = JsonFile::instance($filename);
$entries = $jsonFile->content() ?: [];
$entries[] = $entry;
$jsonFile->save($entries);
}
/**
* Store job-specific history
*
* @param string $jobId
* @param array $entry
* @return void
*/
protected function storeJobHistory(string $jobId, array $entry): void
{
$jobDir = $this->historyPath . '/jobs';
if (!is_dir($jobDir)) {
mkdir($jobDir, 0755, true);
}
$filename = $jobDir . '/' . $jobId . '.json';
$jsonFile = JsonFile::instance($filename);
$history = $jsonFile->content() ?: [];
// Keep only last 100 executions per job
$history[] = $entry;
if (count($history) > 100) {
$history = array_slice($history, -100);
}
$jsonFile->save($history);
}
/**
* Get job history
*
* @param string $jobId
* @param int $limit
* @return array
*/
public function getJobHistory(string $jobId, int $limit = 50): array
{
$filename = $this->historyPath . '/jobs/' . $jobId . '.json';
if (!file_exists($filename)) {
return [];
}
$jsonFile = JsonFile::instance($filename);
$history = $jsonFile->content() ?: [];
// Return most recent first
$history = array_reverse($history);
if ($limit > 0) {
$history = array_slice($history, 0, $limit);
}
return $history;
}
/**
* Get history for a date range
*
* @param DateTime $startDate
* @param DateTime $endDate
* @param string|null $jobId Filter by job ID
* @return array
*/
public function getHistoryRange(DateTime $startDate, DateTime $endDate, ?string $jobId = null): array
{
$history = [];
$current = clone $startDate;
while ($current <= $endDate) {
$filename = $this->historyPath . '/' . $current->format('Y-m-d') . '.json';
if (file_exists($filename)) {
$jsonFile = JsonFile::instance($filename);
$entries = $jsonFile->content() ?: [];
foreach ($entries as $entry) {
if ($jobId === null || $entry['job_id'] === $jobId) {
$history[] = $entry;
}
}
}
$current->modify('+1 day');
}
return $history;
}
/**
* Get job statistics
*
* @param string $jobId
* @param int $days Number of days to analyze
* @return array
*/
public function getJobStatistics(string $jobId, int $days = 7): array
{
$startDate = new DateTime("-{$days} days");
$endDate = new DateTime('now');
$history = $this->getHistoryRange($startDate, $endDate, $jobId);
if (empty($history)) {
return [
'total_runs' => 0,
'successful_runs' => 0,
'failed_runs' => 0,
'success_rate' => 0,
'average_execution_time' => 0,
'last_run' => null,
'last_success' => null,
'last_failure' => null,
];
}
$totalRuns = count($history);
$successfulRuns = 0;
$executionTimes = [];
$lastRun = null;
$lastSuccess = null;
$lastFailure = null;
foreach ($history as $entry) {
if ($entry['success']) {
$successfulRuns++;
if (!$lastSuccess || $entry['timestamp'] > $lastSuccess['timestamp']) {
$lastSuccess = $entry;
}
} else {
if (!$lastFailure || $entry['timestamp'] > $lastFailure['timestamp']) {
$lastFailure = $entry;
}
}
if (!$lastRun || $entry['timestamp'] > $lastRun['timestamp']) {
$lastRun = $entry;
}
if (isset($entry['execution_time']) && $entry['execution_time'] > 0) {
$executionTimes[] = $entry['execution_time'];
}
}
return [
'total_runs' => $totalRuns,
'successful_runs' => $successfulRuns,
'failed_runs' => $totalRuns - $successfulRuns,
'success_rate' => $totalRuns > 0 ? round(($successfulRuns / $totalRuns) * 100, 2) : 0,
'average_execution_time' => !empty($executionTimes) ? round(array_sum($executionTimes) / count($executionTimes), 3) : 0,
'last_run' => $lastRun,
'last_success' => $lastSuccess,
'last_failure' => $lastFailure,
];
}
/**
* Get global statistics
*
* @param int $days
* @return array
*/
public function getGlobalStatistics(int $days = 7): array
{
$startDate = new DateTime("-{$days} days");
$endDate = new DateTime('now');
$history = $this->getHistoryRange($startDate, $endDate);
$jobStats = [];
foreach ($history as $entry) {
$jobId = $entry['job_id'];
if (!isset($jobStats[$jobId])) {
$jobStats[$jobId] = [
'runs' => 0,
'success' => 0,
'failed' => 0,
];
}
$jobStats[$jobId]['runs']++;
if ($entry['success']) {
$jobStats[$jobId]['success']++;
} else {
$jobStats[$jobId]['failed']++;
}
}
return [
'total_executions' => count($history),
'unique_jobs' => count($jobStats),
'job_statistics' => $jobStats,
'period_days' => $days,
'from_date' => $startDate->format('Y-m-d'),
'to_date' => $endDate->format('Y-m-d'),
];
}
/**
* Search history
*
* @param array $criteria
* @return array
*/
public function searchHistory(array $criteria): array
{
$results = [];
// Determine date range
$startDate = isset($criteria['start_date']) ? new DateTime($criteria['start_date']) : new DateTime('-7 days');
$endDate = isset($criteria['end_date']) ? new DateTime($criteria['end_date']) : new DateTime('now');
$history = $this->getHistoryRange($startDate, $endDate, $criteria['job_id'] ?? null);
foreach ($history as $entry) {
$match = true;
// Filter by success status
if (isset($criteria['success']) && $entry['success'] !== $criteria['success']) {
$match = false;
}
// Filter by output content
if (isset($criteria['output_contains']) &&
stripos($entry['output']['content'], $criteria['output_contains']) === false) {
$match = false;
}
// Filter by tags
if (isset($criteria['tags']) && is_array($criteria['tags'])) {
$entryTags = $entry['tags'] ?? [];
if (empty(array_intersect($criteria['tags'], $entryTags))) {
$match = false;
}
}
if ($match) {
$results[] = $entry;
}
}
// Sort results
if (isset($criteria['sort_by'])) {
usort($results, function($a, $b) use ($criteria) {
$field = $criteria['sort_by'];
$order = $criteria['sort_order'] ?? 'desc';
$aVal = $a[$field] ?? 0;
$bVal = $b[$field] ?? 0;
if ($order === 'asc') {
return $aVal <=> $bVal;
} else {
return $bVal <=> $aVal;
}
});
}
// Limit results
if (isset($criteria['limit'])) {
$results = array_slice($results, 0, $criteria['limit']);
}
return $results;
}
/**
* Clean old history files
*
* @return int Number of files deleted
*/
public function cleanOldHistory(): int
{
$deleted = 0;
$cutoffDate = new DateTime("-{$this->retentionDays} days");
$files = glob($this->historyPath . '/*.json');
foreach ($files as $file) {
$filename = basename($file, '.json');
// Check if filename is a date
if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $filename)) {
$fileDate = new DateTime($filename);
if ($fileDate < $cutoffDate) {
unlink($file);
$deleted++;
}
}
}
return $deleted;
}
/**
* Export history to CSV
*
* @param array $history
* @param string $filename
* @return bool
*/
public function exportToCsv(array $history, string $filename): bool
{
$handle = fopen($filename, 'w');
if (!$handle) {
return false;
}
// Write headers
fputcsv($handle, [
'Job ID',
'Executed At',
'Success',
'Execution Time',
'Output Length',
'Retry Count',
'Priority',
'Tags',
]);
// Write data
foreach ($history as $entry) {
fputcsv($handle, [
$entry['job_id'],
$entry['executed_at'],
$entry['success'] ? 'Yes' : 'No',
$entry['execution_time'] ?? '',
$entry['output']['length'] ?? 0,
$entry['retry_count'] ?? 0,
$entry['priority'] ?? 'normal',
implode(', ', $entry['tags'] ?? []),
]);
}
fclose($handle);
return true;
}
} | php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Scheduler/Cron.php | system/src/Grav/Common/Scheduler/Cron.php | <?php
/**
* @package Grav\Common\Scheduler
* @author Originally based on jqCron by Arnaud Buathier <arnaud@arnapou.net> modified for Grav integration
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Scheduler;
/*
* Usage examples :
* ----------------
*
* $cron = new Cron('10-30/5 12 * * *');
*
* var_dump($cron->getMinutes());
* // array(5) {
* // [0]=> int(10)
* // [1]=> int(15)
* // [2]=> int(20)
* // [3]=> int(25)
* // [4]=> int(30)
* // }
*
* var_dump($cron->getText('fr'));
* // string(32) "Chaque jour à 12:10,15,20,25,30"
*
* var_dump($cron->getText('en'));
* // string(30) "Every day at 12:10,15,20,25,30"
*
* var_dump($cron->getType());
* // string(3) "day"
*
* var_dump($cron->getCronHours());
* // string(2) "12"
*
* var_dump($cron->matchExact(new \DateTime('2012-07-01 13:25:10')));
* // bool(false)
*
* var_dump($cron->matchExact(new \DateTime('2012-07-01 12:15:20')));
* // bool(true)
*
* var_dump($cron->matchWithMargin(new \DateTime('2012-07-01 12:32:50'), -3, 5));
* // bool(true)
*/
use DateInterval;
use DateTime;
use RuntimeException;
use function count;
use function in_array;
use function is_array;
use function is_string;
class Cron
{
public const TYPE_UNDEFINED = '';
public const TYPE_MINUTE = 'minute';
public const TYPE_HOUR = 'hour';
public const TYPE_DAY = 'day';
public const TYPE_WEEK = 'week';
public const TYPE_MONTH = 'month';
public const TYPE_YEAR = 'year';
/**
*
* @var array
*/
protected $texts = [
'fr' => [
'empty' => '-tout-',
'name_minute' => 'minute',
'name_hour' => 'heure',
'name_day' => 'jour',
'name_week' => 'semaine',
'name_month' => 'mois',
'name_year' => 'année',
'text_period' => 'Chaque %s',
'text_mins' => 'à %s minutes',
'text_time' => 'à %02s:%02s',
'text_dow' => 'le %s',
'text_month' => 'de %s',
'text_dom' => 'le %s',
'weekdays' => ['lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi', 'dimanche'],
'months' => ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'],
],
'en' => [
'empty' => '-all-',
'name_minute' => 'minute',
'name_hour' => 'hour',
'name_day' => 'day',
'name_week' => 'week',
'name_month' => 'month',
'name_year' => 'year',
'text_period' => 'Every %s',
'text_mins' => 'at %s minutes past the hour',
'text_time' => 'at %02s:%02s',
'text_dow' => 'on %s',
'text_month' => 'of %s',
'text_dom' => 'on the %s',
'weekdays' => ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'],
'months' => ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'],
],
];
/**
* min hour dom month dow
* @var string
*/
protected $cron = '';
/**
*
* @var array
*/
protected $minutes = [];
/**
*
* @var array
*/
protected $hours = [];
/**
*
* @var array
*/
protected $months = [];
/**
* 0-7 : sunday, monday, ... saturday, sunday
* @var array
*/
protected $dow = [];
/**
*
* @var array
*/
protected $dom = [];
/**
* @param string|null $cron
*/
public function __construct($cron = null)
{
if (null !== $cron) {
$this->setCron($cron);
}
}
/**
* @return string
*/
public function getCron()
{
return implode(' ', [
$this->getCronMinutes(),
$this->getCronHours(),
$this->getCronDaysOfMonth(),
$this->getCronMonths(),
$this->getCronDaysOfWeek(),
]);
}
/**
* @param string $lang 'fr' or 'en'
* @return string
*/
public function getText($lang)
{
// check lang
if (!isset($this->texts[$lang])) {
return $this->getCron();
}
$texts = $this->texts[$lang];
// check type
$type = $this->getType();
if ($type === self::TYPE_UNDEFINED) {
return $this->getCron();
}
// init
$elements = [];
$elements[] = sprintf($texts['text_period'], $texts['name_' . $type]);
// hour
if ($type === self::TYPE_HOUR) {
$elements[] = sprintf($texts['text_mins'], $this->getCronMinutes());
}
// week
if ($type === self::TYPE_WEEK) {
$dow = $this->getCronDaysOfWeek();
foreach ($texts['weekdays'] as $i => $wd) {
$dow = str_replace((string) ($i + 1), $wd, $dow);
}
$elements[] = sprintf($texts['text_dow'], $dow);
}
// month + year
if (in_array($type, [self::TYPE_MONTH, self::TYPE_YEAR], true)) {
$elements[] = sprintf($texts['text_dom'], $this->getCronDaysOfMonth());
}
// year
if ($type === self::TYPE_YEAR) {
$months = $this->getCronMonths();
for ($i = count($texts['months']) - 1; $i >= 0; $i--) {
$months = str_replace((string) ($i + 1), $texts['months'][$i], $months);
}
$elements[] = sprintf($texts['text_month'], $months);
}
// day + week + month + year
if (in_array($type, [self::TYPE_DAY, self::TYPE_WEEK, self::TYPE_MONTH, self::TYPE_YEAR], true)) {
$elements[] = sprintf($texts['text_time'], $this->getCronHours(), $this->getCronMinutes());
}
return str_replace('*', $texts['empty'], implode(' ', $elements));
}
/**
* @return string
*/
public function getType()
{
$mask = preg_replace('/[^\* ]/', '-', $this->getCron());
$mask = preg_replace('/-+/', '-', $mask);
$mask = preg_replace('/[^-\*]/', '', $mask);
if ($mask === '*****') {
return self::TYPE_MINUTE;
}
if ($mask === '-****') {
return self::TYPE_HOUR;
}
if (substr($mask, -3) === '***') {
return self::TYPE_DAY;
}
if (substr($mask, -3) === '-**') {
return self::TYPE_MONTH;
}
if (substr($mask, -3) === '**-') {
return self::TYPE_WEEK;
}
if (substr($mask, -2) === '-*') {
return self::TYPE_YEAR;
}
return self::TYPE_UNDEFINED;
}
/**
* @param string $cron
* @return $this
*/
public function setCron($cron)
{
// sanitize
$cron = trim($cron);
$cron = preg_replace('/\s+/', ' ', $cron);
// explode
$elements = explode(' ', $cron);
if (count($elements) !== 5) {
throw new RuntimeException('Bad number of elements');
}
$this->cron = $cron;
$this->setMinutes($elements[0]);
$this->setHours($elements[1]);
$this->setDaysOfMonth($elements[2]);
$this->setMonths($elements[3]);
$this->setDaysOfWeek($elements[4]);
return $this;
}
/**
* @return string
*/
public function getCronMinutes()
{
return $this->arrayToCron($this->minutes);
}
/**
* @return string
*/
public function getCronHours()
{
return $this->arrayToCron($this->hours);
}
/**
* @return string
*/
public function getCronDaysOfMonth()
{
return $this->arrayToCron($this->dom);
}
/**
* @return string
*/
public function getCronMonths()
{
return $this->arrayToCron($this->months);
}
/**
* @return string
*/
public function getCronDaysOfWeek()
{
return $this->arrayToCron($this->dow);
}
/**
* @return array
*/
public function getMinutes()
{
return $this->minutes;
}
/**
* @return array
*/
public function getHours()
{
return $this->hours;
}
/**
* @return array
*/
public function getDaysOfMonth()
{
return $this->dom;
}
/**
* @return array
*/
public function getMonths()
{
return $this->months;
}
/**
* @return array
*/
public function getDaysOfWeek()
{
return $this->dow;
}
/**
* @param string|string[] $minutes
* @return $this
*/
public function setMinutes($minutes)
{
$this->minutes = $this->cronToArray($minutes, 0, 59);
return $this;
}
/**
* @param string|string[] $hours
* @return $this
*/
public function setHours($hours)
{
$this->hours = $this->cronToArray($hours, 0, 23);
return $this;
}
/**
* @param string|string[] $months
* @return $this
*/
public function setMonths($months)
{
$this->months = $this->cronToArray($months, 1, 12);
return $this;
}
/**
* @param string|string[] $dow
* @return $this
*/
public function setDaysOfWeek($dow)
{
$this->dow = $this->cronToArray($dow, 0, 7);
return $this;
}
/**
* @param string|string[] $dom
* @return $this
*/
public function setDaysOfMonth($dom)
{
$this->dom = $this->cronToArray($dom, 1, 31);
return $this;
}
/**
* @param mixed $date
* @param int $min
* @param int $hour
* @param int $day
* @param int $month
* @param int $weekday
* @return DateTime
*/
protected function parseDate($date, &$min, &$hour, &$day, &$month, &$weekday)
{
if (is_numeric($date) && (int)$date == $date) {
$date = new DateTime('@' . $date);
} elseif (is_string($date)) {
$date = new DateTime('@' . strtotime($date));
}
if ($date instanceof DateTime) {
$min = (int)$date->format('i');
$hour = (int)$date->format('H');
$day = (int)$date->format('d');
$month = (int)$date->format('m');
$weekday = (int)$date->format('w'); // 0-6
} else {
throw new RuntimeException('Date format not supported');
}
return new DateTime($date->format('Y-m-d H:i:sP'));
}
/**
* @param int|string|DateTime $date
*/
public function matchExact($date)
{
$date = $this->parseDate($date, $min, $hour, $day, $month, $weekday);
return
(empty($this->minutes) || in_array($min, $this->minutes, true)) &&
(empty($this->hours) || in_array($hour, $this->hours, true)) &&
(empty($this->dom) || in_array($day, $this->dom, true)) &&
(empty($this->months) || in_array($month, $this->months, true)) &&
(empty($this->dow) || in_array($weekday, $this->dow, true) || ($weekday == 0 && in_array(7, $this->dow, true)) || ($weekday == 7 && in_array(0, $this->dow, true))
);
}
/**
* @param int|string|DateTime $date
* @param int $minuteBefore
* @param int $minuteAfter
*/
public function matchWithMargin($date, $minuteBefore = 0, $minuteAfter = 0)
{
if ($minuteBefore > 0) {
throw new RuntimeException('MinuteBefore parameter cannot be positive !');
}
if ($minuteAfter < 0) {
throw new RuntimeException('MinuteAfter parameter cannot be negative !');
}
$date = $this->parseDate($date, $min, $hour, $day, $month, $weekday);
$interval = new DateInterval('PT1M'); // 1 min
if ($minuteBefore !== 0) {
$date->sub(new DateInterval('PT' . abs($minuteBefore) . 'M'));
}
$n = $minuteAfter - $minuteBefore + 1;
for ($i = 0; $i < $n; $i++) {
if ($this->matchExact($date)) {
return true;
}
$date->add($interval);
}
return false;
}
/**
* @param array $array
* @return string
*/
protected function arrayToCron($array)
{
$n = count($array);
if (!is_array($array) || $n === 0) {
return '*';
}
$cron = [$array[0]];
$s = $c = $array[0];
for ($i = 1; $i < $n; $i++) {
if ($array[$i] == $c + 1) {
$c = $array[$i];
$cron[count($cron) - 1] = $s . '-' . $c;
} else {
$s = $c = $array[$i];
$cron[] = $c;
}
}
return implode(',', $cron);
}
/**
*
* @param array|string $string
* @param int $min
* @param int $max
* @return array
*/
protected function cronToArray($string, $min, $max)
{
$array = [];
if (is_array($string)) {
foreach ($string as $val) {
if (is_numeric($val) && (int)$val == $val && $val >= $min && $val <= $max) {
$array[] = (int)$val;
}
}
} elseif ($string !== '*') {
while ($string !== '') {
// test "*/n" expression
if (preg_match('/^\*\/([0-9]+),?/', $string, $m)) {
for ($i = max(0, $min); $i <= min(59, $max); $i += $m[1]) {
$array[] = (int)$i;
}
$string = substr($string, strlen($m[0]));
continue;
}
// test "a-b/n" expression
if (preg_match('/^([0-9]+)-([0-9]+)\/([0-9]+),?/', $string, $m)) {
for ($i = max($m[1], $min); $i <= min($m[2], $max); $i += $m[3]) {
$array[] = (int)$i;
}
$string = substr($string, strlen($m[0]));
continue;
}
// test "a-b" expression
if (preg_match('/^([0-9]+)-([0-9]+),?/', $string, $m)) {
for ($i = max($m[1], $min); $i <= min($m[2], $max); $i++) {
$array[] = (int)$i;
}
$string = substr($string, strlen($m[0]));
continue;
}
// test "c" expression
if (preg_match('/^([0-9]+),?/', $string, $m)) {
if ($m[1] >= $min && $m[1] <= $max) {
$array[] = (int)$m[1];
}
$string = substr($string, strlen($m[0]));
continue;
}
// something goes wrong in the expression
return [];
}
}
sort($array, SORT_NUMERIC);
return $array;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Scheduler/Job.php | system/src/Grav/Common/Scheduler/Job.php | <?php
/**
* @package Grav\Common\Scheduler
* @author Originally based on peppeocchi/php-cron-scheduler modified for Grav integration
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Scheduler;
use Closure;
use Cron\CronExpression;
use DateTime;
use Grav\Common\Grav;
use InvalidArgumentException;
use RuntimeException;
use Symfony\Component\Process\Process;
use function call_user_func;
use function call_user_func_array;
use function count;
use function is_array;
use function is_callable;
use function is_string;
/**
* Class Job
* @package Grav\Common\Scheduler
*/
class Job
{
use IntervalTrait;
/** @var string */
private $id;
/** @var bool */
private $enabled;
/** @var callable|string */
private $command;
/** @var string */
private $at;
/** @var array */
private $args = [];
/** @var bool */
private $runInBackground = true;
/** @var DateTime */
private $creationTime;
/** @var CronExpression */
private $executionTime;
/** @var string */
private $tempDir;
/** @var string */
private $lockFile;
/** @var bool */
private $truthTest = true;
/** @var string */
private $output;
/** @var int */
private $returnCode = 0;
/** @var array */
private $outputTo = [];
/** @var array */
private $emailTo = [];
/** @var array */
private $emailConfig = [];
/** @var callable|null */
private $before;
/** @var callable|null */
private $after;
/** @var callable */
private $whenOverlapping;
/** @var string */
private $outputMode;
/** @var Process|null $process */
private $process;
/** @var bool */
private $successful = false;
/** @var string|null */
private $backlink;
// Modern Job features
/** @var int */
protected $maxAttempts = 3;
/** @var int */
protected $retryCount = 0;
/** @var int */
protected $retryDelay = 60; // seconds
/** @var string */
protected $retryStrategy = 'exponential'; // 'linear' or 'exponential'
/** @var float */
protected $executionStartTime;
/** @var float */
protected $executionDuration = 0;
/** @var int */
protected $timeout = 300; // 5 minutes default
/** @var array */
protected $dependencies = [];
/** @var array */
protected $chainedJobs = [];
/** @var string|null */
protected $queueId;
/** @var string */
protected $priority = 'normal'; // 'high', 'normal', 'low'
/** @var array */
protected $metadata = [];
/** @var array */
protected $tags = [];
/** @var callable|null */
protected $onSuccess;
/** @var callable|null */
protected $onFailure;
/** @var callable|null */
protected $onRetry;
/**
* Create a new Job instance.
*
* @param string|callable $command
* @param array $args
* @param string|null $id
*/
public function __construct($command, $args = [], $id = null)
{
if (is_string($id)) {
$this->id = Grav::instance()['inflector']->hyphenize($id);
} else {
if (is_string($command)) {
$this->id = md5($command);
} else {
/* @var object $command */
$this->id = spl_object_hash($command);
}
}
$this->creationTime = new DateTime('now');
// initialize the directory path for lock files
$this->tempDir = sys_get_temp_dir();
$this->command = $command;
$this->args = $args;
// Set enabled state
$status = Grav::instance()['config']->get('scheduler.status');
$this->enabled = !(isset($status[$id]) && $status[$id] === 'disabled');
}
/**
* Get the command
*
* @return Closure|string
*/
public function getCommand()
{
return $this->command;
}
/**
* Get the cron 'at' syntax for this job
*
* @return string
*/
public function getAt()
{
return $this->at;
}
/**
* Get the status of this job
*
* @return bool
*/
public function getEnabled()
{
return $this->enabled;
}
/**
* Get optional arguments
*
* @return string|null
*/
public function getArguments()
{
if (is_string($this->args)) {
return $this->args;
}
return null;
}
/**
* Get raw arguments (array or string)
*
* @return array|string
*/
public function getRawArguments()
{
return $this->args;
}
/**
* @return CronExpression
*/
public function getCronExpression()
{
return CronExpression::factory($this->at);
}
/**
* Get the status of the last run for this job
*
* @return bool
*/
public function isSuccessful()
{
return $this->successful;
}
/**
* Get the Job id.
*
* @return string
*/
public function getId()
{
return $this->id;
}
/**
* Check if the Job is due to run.
* It accepts as input a DateTime used to check if
* the job is due. Defaults to job creation time.
* It also default the execution time if not previously defined.
*
* @param DateTime|null $date
* @return bool
*/
public function isDue(DateTime $date = null)
{
// The execution time is being defaulted if not defined
if (!$this->executionTime) {
$this->at('* * * * *');
}
$date = $date ?? $this->creationTime;
return $this->executionTime->isDue($date);
}
/**
* Check if the Job is overlapping.
*
* @return bool
*/
public function isOverlapping()
{
return $this->lockFile &&
file_exists($this->lockFile) &&
call_user_func($this->whenOverlapping, filemtime($this->lockFile)) === false;
}
/**
* Force the Job to run in foreground.
*
* @return $this
*/
public function inForeground()
{
$this->runInBackground = false;
return $this;
}
/**
* Sets/Gets an option backlink
*
* @param string|null $link
* @return string|null
*/
public function backlink($link = null)
{
if ($link) {
$this->backlink = $link;
}
return $this->backlink;
}
/**
* Check if the Job can run in background.
*
* @return bool
*/
public function runInBackground()
{
return !(is_callable($this->command) || $this->runInBackground === false);
}
/**
* This will prevent the Job from overlapping.
* It prevents another instance of the same Job of
* being executed if the previous is still running.
* The job id is used as a filename for the lock file.
*
* @param string|null $tempDir The directory path for the lock files
* @param callable|null $whenOverlapping A callback to ignore job overlapping
* @return self
*/
public function onlyOne($tempDir = null, callable $whenOverlapping = null)
{
if ($tempDir === null || !is_dir($tempDir)) {
$tempDir = $this->tempDir;
}
$this->lockFile = implode('/', [
trim($tempDir),
trim($this->id) . '.lock',
]);
if ($whenOverlapping) {
$this->whenOverlapping = $whenOverlapping;
} else {
$this->whenOverlapping = static function () {
return false;
};
}
return $this;
}
/**
* Configure the job.
*
* @param array $config
* @return self
*/
public function configure(array $config = [])
{
// Check if config has defined a tempDir
if (isset($config['tempDir']) && is_dir($config['tempDir'])) {
$this->tempDir = $config['tempDir'];
}
return $this;
}
/**
* Truth test to define if the job should run if due.
*
* @param callable $fn
* @return self
*/
public function when(callable $fn)
{
$this->truthTest = $fn();
return $this;
}
/**
* Run the job.
*
* @return bool
*/
public function run()
{
// Check dependencies (modern feature)
if (!$this->checkDependencies()) {
$this->output = 'Dependencies not met';
$this->successful = false;
return false;
}
// If the truthTest failed, don't run
if ($this->truthTest !== true) {
return false;
}
// If overlapping, don't run
if ($this->isOverlapping()) {
return false;
}
// Write lock file if necessary
$this->createLockFile();
// Call before if required
if (is_callable($this->before)) {
call_user_func($this->before);
}
// If command is callable...
if (is_callable($this->command)) {
$this->output = $this->exec();
} else {
$args = is_string($this->args) ? explode(' ', $this->args) : $this->args;
$command = array_merge([$this->command], $args);
$process = new Process($command);
// Apply timeout if set (modern feature)
if ($this->timeout > 0) {
$process->setTimeout($this->timeout);
}
$this->process = $process;
if ($this->runInBackground()) {
$process->start();
} else {
$process->run();
$this->finalize();
}
}
return true;
}
/**
* Finish up processing the job
*
* @return void
*/
public function finalize()
{
$process = $this->process;
if ($process) {
$process->wait();
if ($process->isSuccessful()) {
$this->successful = true;
$this->output = $process->getOutput();
} else {
$this->successful = false;
$this->output = $process->getErrorOutput();
}
$this->postRun();
unset($this->process);
}
}
/**
* Things to run after job has run
*
* @return void
*/
private function postRun()
{
if (count($this->outputTo) > 0) {
foreach ($this->outputTo as $file) {
$output_mode = $this->outputMode === 'append' ? FILE_APPEND | LOCK_EX : LOCK_EX;
$timestamp = (new DateTime('now'))->format('c');
$output = $timestamp . "\n" . str_pad('', strlen($timestamp), '>') . "\n" . $this->output;
file_put_contents($file, $output, $output_mode);
}
}
// Send output to email
$this->emailOutput();
// Call any callback defined
if (is_callable($this->after)) {
call_user_func($this->after, $this->output, $this->returnCode);
}
$this->removeLockFile();
}
/**
* Create the job lock file.
*
* @param mixed $content
* @return void
*/
private function createLockFile($content = null)
{
if ($this->lockFile) {
if ($content === null || !is_string($content)) {
$content = $this->getId();
}
file_put_contents($this->lockFile, $content);
}
}
/**
* Remove the job lock file.
*
* @return void
*/
private function removeLockFile()
{
if ($this->lockFile && file_exists($this->lockFile)) {
unlink($this->lockFile);
}
}
/**
* Execute a callable job.
*
* @return string
* @throws RuntimeException
*/
private function exec()
{
$return_data = '';
ob_start();
try {
$return_data = call_user_func_array($this->command, $this->args);
$this->successful = true;
} catch (RuntimeException $e) {
$return_data = $e->getMessage();
$this->successful = false;
}
$this->output = ob_get_clean() . (is_string($return_data) ? $return_data : '');
$this->postRun();
return $this->output;
}
/**
* Set the file/s where to write the output of the job.
*
* @param string|array $filename
* @param bool $append
* @return self
*/
public function output($filename, $append = false)
{
$this->outputTo = is_array($filename) ? $filename : [$filename];
$this->outputMode = $append === false ? 'overwrite' : 'append';
return $this;
}
/**
* Get the job output.
*
* @return mixed
*/
public function getOutput()
{
return $this->output;
}
/**
* Set the emails where the output should be sent to.
* The Job should be set to write output to a file
* for this to work.
*
* @param string|array $email
* @return self
*/
public function email($email)
{
if (!is_string($email) && !is_array($email)) {
throw new InvalidArgumentException('The email can be only string or array');
}
$this->emailTo = is_array($email) ? $email : [$email];
// Force the job to run in foreground
$this->inForeground();
return $this;
}
/**
* Email the output of the job, if any.
*
* @return bool
*/
private function emailOutput()
{
if (!count($this->outputTo) || !count($this->emailTo)) {
return false;
}
if (is_callable('Grav\Plugin\Email\Utils::sendEmail')) {
$subject ='Grav Scheduled Job [' . $this->getId() . ']';
$content = "<h1>Output from Job ID: {$this->getId()}</h1>\n<h4>Command: {$this->getCommand()}</h4><br /><pre style=\"font-size: 12px; font-family: Monaco, Consolas, monospace\">\n".$this->getOutput()."\n</pre>";
$to = $this->emailTo;
\Grav\Plugin\Email\Utils::sendEmail($subject, $content, $to);
}
return true;
}
/**
* Set function to be called before job execution
* Job object is injected as a parameter to callable function.
*
* @param callable $fn
* @return self
*/
public function before(callable $fn)
{
$this->before = $fn;
return $this;
}
/**
* Set a function to be called after job execution.
* By default this will force the job to run in foreground
* because the output is injected as a parameter of this
* function, but it could be avoided by passing true as a
* second parameter. The job will run in background if it
* meets all the other criteria.
*
* @param callable $fn
* @param bool $runInBackground
* @return self
*/
public function then(callable $fn, $runInBackground = false)
{
$this->after = $fn;
// Force the job to run in foreground
if ($runInBackground === false) {
$this->inForeground();
}
return $this;
}
// Modern Job Methods
/**
* Set maximum retry attempts
*
* @param int $attempts
* @return self
*/
public function maxAttempts(int $attempts): self
{
$this->maxAttempts = $attempts;
return $this;
}
/**
* Get maximum retry attempts
*
* @return int
*/
public function getMaxAttempts(): int
{
return $this->maxAttempts;
}
/**
* Set retry delay
*
* @param int $seconds
* @param string $strategy 'linear' or 'exponential'
* @return self
*/
public function retryDelay(int $seconds, string $strategy = 'exponential'): self
{
$this->retryDelay = $seconds;
$this->retryStrategy = $strategy;
return $this;
}
/**
* Get current retry count
*
* @return int
*/
public function getRetryCount(): int
{
return $this->retryCount;
}
/**
* Set job timeout
*
* @param int $seconds
* @return self
*/
public function timeout(int $seconds): self
{
$this->timeout = $seconds;
return $this;
}
/**
* Set job priority
*
* @param string $priority 'high', 'normal', or 'low'
* @return self
*/
public function priority(string $priority): self
{
if (!in_array($priority, ['high', 'normal', 'low'])) {
throw new InvalidArgumentException('Priority must be high, normal, or low');
}
$this->priority = $priority;
return $this;
}
/**
* Get job priority
*
* @return string
*/
public function getPriority(): string
{
return $this->priority;
}
/**
* Add job dependency
*
* @param string $jobId
* @return self
*/
public function dependsOn(string $jobId): self
{
$this->dependencies[] = $jobId;
return $this;
}
/**
* Chain another job to run after this one
*
* @param Job $job
* @param bool $onlyOnSuccess Run only if current job succeeds
* @return self
*/
public function chain(Job $job, bool $onlyOnSuccess = true): self
{
$this->chainedJobs[] = [
'job' => $job,
'onlyOnSuccess' => $onlyOnSuccess,
];
return $this;
}
/**
* Add metadata to the job
*
* @param string $key
* @param mixed $value
* @return self
*/
public function withMetadata(string $key, $value): self
{
$this->metadata[$key] = $value;
return $this;
}
/**
* Add tags to the job
*
* @param array $tags
* @return self
*/
public function withTags(array $tags): self
{
$this->tags = array_merge($this->tags, $tags);
return $this;
}
/**
* Set success callback
*
* @param callable $callback
* @return self
*/
public function onSuccess(callable $callback): self
{
$this->onSuccess = $callback;
return $this;
}
/**
* Set failure callback
*
* @param callable $callback
* @return self
*/
public function onFailure(callable $callback): self
{
$this->onFailure = $callback;
return $this;
}
/**
* Set retry callback
*
* @param callable $callback
* @return self
*/
public function onRetry(callable $callback): self
{
$this->onRetry = $callback;
return $this;
}
/**
* Run the job with retry support
*
* @return bool
*/
public function runWithRetry(): bool
{
$attempts = 0;
$lastException = null;
while ($attempts < $this->maxAttempts) {
$attempts++;
$this->retryCount = $attempts - 1;
try {
// Record execution start time
$this->executionStartTime = microtime(true);
// Run the job
$result = $this->run();
// Record execution time
$this->executionDuration = microtime(true) - $this->executionStartTime;
if ($result && $this->isSuccessful()) {
// Call success callback
if ($this->onSuccess) {
call_user_func($this->onSuccess, $this);
}
// Run chained jobs
$this->runChainedJobs(true);
return true;
}
throw new RuntimeException('Job execution failed');
} catch (\Exception $e) {
$lastException = $e;
$this->output = $e->getMessage();
$this->successful = false;
if ($attempts < $this->maxAttempts) {
// Call retry callback
if ($this->onRetry) {
call_user_func($this->onRetry, $this, $attempts, $e);
}
// Calculate delay before retry
$delay = $this->calculateRetryDelay($attempts);
if ($delay > 0) {
sleep($delay);
}
} else {
// Final failure
if ($this->onFailure) {
call_user_func($this->onFailure, $this, $e);
}
// Run chained jobs that should run on failure
$this->runChainedJobs(false);
}
}
}
return false;
}
/**
* Get execution time in seconds
*
* @return float
*/
public function getExecutionTime(): float
{
return $this->executionDuration;
}
/**
* Get job metadata
*
* @param string|null $key
* @return mixed
*/
public function getMetadata(string $key = null)
{
if ($key === null) {
return $this->metadata;
}
return $this->metadata[$key] ?? null;
}
/**
* Get job tags
*
* @return array
*/
public function getTags(): array
{
return $this->tags;
}
/**
* Check if job has a specific tag
*
* @param string $tag
* @return bool
*/
public function hasTag(string $tag): bool
{
return in_array($tag, $this->tags);
}
/**
* Set queue ID
*
* @param string $queueId
* @return self
*/
public function setQueueId(string $queueId): self
{
$this->queueId = $queueId;
return $this;
}
/**
* Get queue ID
*
* @return string|null
*/
public function getQueueId(): ?string
{
return $this->queueId;
}
/**
* Get process (for background jobs)
*
* @return Process|null
*/
public function getProcess(): ?Process
{
return $this->process;
}
/**
* Calculate retry delay based on strategy
*
* @param int $attempt
* @return int
*/
protected function calculateRetryDelay(int $attempt): int
{
if ($this->retryStrategy === 'exponential') {
return min($this->retryDelay * pow(2, $attempt - 1), 3600); // Max 1 hour
}
return $this->retryDelay;
}
/**
* Check if dependencies are met
*
* @return bool
*/
protected function checkDependencies(): bool
{
if (empty($this->dependencies)) {
return true;
}
// This would need to check against job history or status
// For now, we'll assume dependencies are met
// In a real implementation, this would check the Scheduler's job status
return true;
}
/**
* Run chained jobs
*
* @param bool $success Whether the current job succeeded
* @return void
*/
protected function runChainedJobs(bool $success): void
{
foreach ($this->chainedJobs as $chainedJob) {
$shouldRun = !$chainedJob['onlyOnSuccess'] || $success;
if ($shouldRun) {
$job = $chainedJob['job'];
if (method_exists($job, 'runWithRetry')) {
$job->runWithRetry();
} else {
$job->run();
}
}
}
}
/**
* Convert job to array for serialization
*
* @return array
*/
public function toArray(): array
{
return [
'id' => $this->getId(),
'command' => is_string($this->command) ? $this->command : 'Closure',
'at' => $this->getAt(),
'enabled' => $this->getEnabled(),
'priority' => $this->priority,
'max_attempts' => $this->maxAttempts,
'retry_count' => $this->retryCount,
'retry_delay' => $this->retryDelay,
'retry_strategy' => $this->retryStrategy,
'timeout' => $this->timeout,
'dependencies' => $this->dependencies,
'metadata' => $this->metadata,
'tags' => $this->tags,
'execution_time' => $this->executionDuration,
'successful' => $this->successful,
'output' => $this->output,
];
}
/**
* Create job from array
*
* @param array $data
* @return self
*/
public static function fromArray(array $data): self
{
$job = new self($data['command'] ?? '', [], $data['id'] ?? null);
if (isset($data['at'])) {
$job->at($data['at']);
}
if (isset($data['priority'])) {
$job->priority($data['priority']);
}
if (isset($data['max_attempts'])) {
$job->maxAttempts($data['max_attempts']);
}
if (isset($data['retry_delay']) && isset($data['retry_strategy'])) {
$job->retryDelay($data['retry_delay'], $data['retry_strategy']);
}
if (isset($data['timeout'])) {
$job->timeout($data['timeout']);
}
if (isset($data['dependencies'])) {
foreach ($data['dependencies'] as $dep) {
$job->dependsOn($dep);
}
}
if (isset($data['metadata'])) {
foreach ($data['metadata'] as $key => $value) {
$job->withMetadata($key, $value);
}
}
if (isset($data['tags'])) {
$job->withTags($data['tags']);
}
return $job;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Scheduler/SchedulerController.php | system/src/Grav/Common/Scheduler/SchedulerController.php | <?php
/**
* @package Grav\Common\Scheduler
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Scheduler;
use Grav\Common\Grav;
use Grav\Common\Utils;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
/**
* Scheduler Controller for handling HTTP endpoints
*
* @package Grav\Common\Scheduler
*/
class SchedulerController
{
/** @var Grav */
protected $grav;
/** @var ModernScheduler */
protected $scheduler;
/**
* SchedulerController constructor
*
* @param Grav $grav
*/
public function __construct(Grav $grav)
{
$this->grav = $grav;
// Get scheduler instance
$scheduler = $grav['scheduler'];
if ($scheduler instanceof ModernScheduler) {
$this->scheduler = $scheduler;
} else {
// Create ModernScheduler instance if not already
$this->scheduler = new ModernScheduler();
}
}
/**
* Handle health check endpoint
*
* @param ServerRequestInterface $request
* @return ResponseInterface
*/
public function health(ServerRequestInterface $request): ResponseInterface
{
$config = $this->grav['config']->get('scheduler.modern', []);
// Check if health endpoint is enabled
if (!($config['health']['enabled'] ?? true)) {
return $this->jsonResponse(['error' => 'Health check disabled'], 403);
}
// Get health status
$health = $this->scheduler->getHealthStatus();
return $this->jsonResponse($health);
}
/**
* Handle webhook trigger endpoint
*
* @param ServerRequestInterface $request
* @return ResponseInterface
*/
public function webhook(ServerRequestInterface $request): ResponseInterface
{
$config = $this->grav['config']->get('scheduler.modern', []);
// Check if webhook is enabled
if (!($config['webhook']['enabled'] ?? false)) {
return $this->jsonResponse(['error' => 'Webhook triggers disabled'], 403);
}
// Get authorization header
$authHeader = $request->getHeaderLine('Authorization');
$token = null;
if (preg_match('/Bearer\s+(.+)$/i', $authHeader, $matches)) {
$token = $matches[1];
}
// Get query parameters
$params = $request->getQueryParams();
$jobId = $params['job'] ?? null;
// Process webhook
$result = $this->scheduler->processWebhookTrigger($token, $jobId);
$statusCode = $result['success'] ? 200 : 400;
return $this->jsonResponse($result, $statusCode);
}
/**
* Handle statistics endpoint
*
* @param ServerRequestInterface $request
* @return ResponseInterface
*/
public function statistics(ServerRequestInterface $request): ResponseInterface
{
// Check if user is admin
$user = $this->grav['user'] ?? null;
if (!$user || !$user->authorize('admin.super')) {
return $this->jsonResponse(['error' => 'Unauthorized'], 401);
}
$stats = $this->scheduler->getStatistics();
return $this->jsonResponse($stats);
}
/**
* Handle admin AJAX requests for scheduler status
*
* @param ServerRequestInterface $request
* @return ResponseInterface
*/
public function adminStatus(ServerRequestInterface $request): ResponseInterface
{
// Check if user is admin
$user = $this->grav['user'] ?? null;
if (!$user || !$user->authorize('admin.scheduler')) {
return $this->jsonResponse(['error' => 'Unauthorized'], 401);
}
$health = $this->scheduler->getHealthStatus();
// Format for admin display
$response = [
'health' => $this->formatHealthStatus($health),
'triggers' => $this->formatTriggers($health['trigger_methods'] ?? [])
];
return $this->jsonResponse($response);
}
/**
* Format health status for display
*
* @param array $health
* @return string
*/
protected function formatHealthStatus(array $health): string
{
$status = $health['status'] ?? 'unknown';
$lastRun = $health['last_run'] ?? null;
$queueSize = $health['queue_size'] ?? 0;
$failedJobs = $health['failed_jobs_24h'] ?? 0;
$jobsDue = $health['jobs_due'] ?? 0;
$message = $health['message'] ?? '';
$statusBadge = match($status) {
'healthy' => '<span class="badge badge-success">Healthy</span>',
'warning' => '<span class="badge badge-warning">Warning</span>',
'critical' => '<span class="badge badge-danger">Critical</span>',
default => '<span class="badge badge-secondary">Unknown</span>'
};
$html = '<div class="scheduler-health">';
$html .= '<p>Status: ' . $statusBadge;
if ($message) {
$html .= ' - ' . htmlspecialchars($message);
}
$html .= '</p>';
if ($lastRun) {
$lastRunTime = new \DateTime($lastRun);
$now = new \DateTime();
$diff = $now->diff($lastRunTime);
$timeAgo = '';
if ($diff->d > 0) {
$timeAgo = $diff->d . ' day' . ($diff->d > 1 ? 's' : '') . ' ago';
} elseif ($diff->h > 0) {
$timeAgo = $diff->h . ' hour' . ($diff->h > 1 ? 's' : '') . ' ago';
} elseif ($diff->i > 0) {
$timeAgo = $diff->i . ' minute' . ($diff->i > 1 ? 's' : '') . ' ago';
} else {
$timeAgo = 'Less than a minute ago';
}
$html .= '<p>Last Run: <strong>' . $timeAgo . '</strong></p>';
} else {
$html .= '<p>Last Run: <strong>Never</strong></p>';
}
$html .= '<p>Jobs Due: <strong>' . $jobsDue . '</strong></p>';
$html .= '<p>Queue Size: <strong>' . $queueSize . '</strong></p>';
if ($failedJobs > 0) {
$html .= '<p class="text-danger">Failed Jobs (24h): <strong>' . $failedJobs . '</strong></p>';
}
$html .= '</div>';
return $html;
}
/**
* Format triggers for display
*
* @param array $triggers
* @return string
*/
protected function formatTriggers(array $triggers): string
{
if (empty($triggers)) {
return '<div class="alert alert-warning">No active triggers detected. Please set up cron, systemd, or webhook triggers.</div>';
}
$html = '<div class="scheduler-triggers">';
$html .= '<ul class="list-unstyled">';
foreach ($triggers as $trigger) {
$icon = match($trigger) {
'cron' => '⏰',
'systemd' => '⚙️',
'webhook' => '🔗',
'external' => '🌐',
default => '•'
};
$label = match($trigger) {
'cron' => 'Cron Job',
'systemd' => 'Systemd Timer',
'webhook' => 'Webhook Triggers',
'external' => 'External Triggers',
default => ucfirst($trigger)
};
$html .= '<li>' . $icon . ' <strong>' . $label . '</strong> <span class="badge badge-success">Active</span></li>';
}
$html .= '</ul>';
$html .= '</div>';
return $html;
}
/**
* Create JSON response
*
* @param array $data
* @param int $statusCode
* @return ResponseInterface
*/
protected function jsonResponse(array $data, int $statusCode = 200): ResponseInterface
{
$response = $this->grav['response'] ?? new \Nyholm\Psr7\Response();
$response = $response->withStatus($statusCode)
->withHeader('Content-Type', 'application/json');
$body = $response->getBody();
$body->write(json_encode($data));
return $response;
}
} | php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Scheduler/JobQueue.php | system/src/Grav/Common/Scheduler/JobQueue.php | <?php
/**
* @package Grav\Common\Scheduler
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Scheduler;
use RocketTheme\Toolbox\File\JsonFile;
use RuntimeException;
/**
* File-based job queue implementation
*
* @package Grav\Common\Scheduler
*/
class JobQueue
{
/** @var string */
protected $queuePath;
/** @var string */
protected $lockFile;
/** @var array Priority levels */
const PRIORITY_HIGH = 'high';
const PRIORITY_NORMAL = 'normal';
const PRIORITY_LOW = 'low';
/**
* JobQueue constructor
*
* @param string $queuePath
*/
public function __construct(string $queuePath)
{
$this->queuePath = $queuePath;
$this->lockFile = $queuePath . '/.lock';
// Create queue directories
$this->initializeDirectories();
}
/**
* Initialize queue directories
*
* @return void
*/
protected function initializeDirectories(): void
{
$dirs = [
$this->queuePath . '/pending',
$this->queuePath . '/processing',
$this->queuePath . '/failed',
$this->queuePath . '/completed',
];
foreach ($dirs as $dir) {
if (!file_exists($dir)) {
mkdir($dir, 0755, true);
}
}
}
/**
* Push a job to the queue
*
* @param Job $job
* @param string $priority
* @return string Job queue ID
*/
public function push(Job $job, string $priority = self::PRIORITY_NORMAL): string
{
$queueId = $this->generateQueueId($job);
$timestamp = microtime(true);
$queueItem = [
'id' => $queueId,
'job_id' => $job->getId(),
'command' => is_string($job->getCommand()) ? $job->getCommand() : 'Closure',
'arguments' => method_exists($job, 'getRawArguments') ? $job->getRawArguments() : $job->getArguments(),
'priority' => $priority,
'timestamp' => $timestamp,
'attempts' => 0,
'max_attempts' => method_exists($job, 'getMaxAttempts') ? $job->getMaxAttempts() : 1,
'created_at' => date('c'),
'scheduled_for' => null,
'metadata' => [],
];
// Always serialize the job to preserve its full state
$queueItem['serialized_job'] = base64_encode(serialize($job));
$this->writeQueueItem($queueItem, 'pending');
return $queueId;
}
/**
* Push a job for delayed execution
*
* @param Job $job
* @param \DateTime $scheduledFor
* @param string $priority
* @return string
*/
public function pushDelayed(Job $job, \DateTime $scheduledFor, string $priority = self::PRIORITY_NORMAL): string
{
$queueId = $this->push($job, $priority);
// Update the scheduled time
$item = $this->getQueueItem($queueId, 'pending');
if ($item) {
$item['scheduled_for'] = $scheduledFor->format('c');
$this->writeQueueItem($item, 'pending');
}
return $queueId;
}
/**
* Pop the next job from the queue
*
* @return Job|null
*/
public function pop(): ?Job
{
if (!$this->lock()) {
return null;
}
try {
// Get all pending items
$items = $this->getPendingItems();
if (empty($items)) {
$this->unlock();
return null;
}
// Sort by priority and timestamp
usort($items, function($a, $b) {
$priorityOrder = [
self::PRIORITY_HIGH => 0,
self::PRIORITY_NORMAL => 1,
self::PRIORITY_LOW => 2,
];
$aPriority = $priorityOrder[$a['priority']] ?? 1;
$bPriority = $priorityOrder[$b['priority']] ?? 1;
if ($aPriority !== $bPriority) {
return $aPriority - $bPriority;
}
return $a['timestamp'] <=> $b['timestamp'];
});
// Get the first item that's ready to run
$now = new \DateTime();
foreach ($items as $item) {
if ($item['scheduled_for']) {
$scheduledTime = new \DateTime($item['scheduled_for']);
if ($scheduledTime > $now) {
continue; // Skip items not yet due
}
}
// Move to processing
$this->moveQueueItem($item['id'], 'pending', 'processing');
// Reconstruct the job
$job = $this->reconstructJob($item);
$this->unlock();
return $job;
}
$this->unlock();
return null;
} catch (\Exception $e) {
$this->unlock();
throw $e;
}
}
/**
* Pop a job from the queue with its queue ID
*
* @return array|null Array with 'job' and 'id' keys
*/
public function popWithId(): ?array
{
if (!$this->lock()) {
return null;
}
try {
// Get all pending items
$items = $this->getPendingItems();
if (empty($items)) {
$this->unlock();
return null;
}
// Sort by priority and timestamp
usort($items, function($a, $b) {
$priorityOrder = [
self::PRIORITY_HIGH => 0,
self::PRIORITY_NORMAL => 1,
self::PRIORITY_LOW => 2,
];
$aPriority = $priorityOrder[$a['priority']] ?? 1;
$bPriority = $priorityOrder[$b['priority']] ?? 1;
if ($aPriority !== $bPriority) {
return $aPriority - $bPriority;
}
return $a['timestamp'] <=> $b['timestamp'];
});
// Get the first item that's ready to run
$now = new \DateTime();
foreach ($items as $item) {
if ($item['scheduled_for']) {
$scheduledTime = new \DateTime($item['scheduled_for']);
if ($scheduledTime > $now) {
continue; // Skip items not yet due
}
}
// Reconstruct the job first before moving it
$job = $this->reconstructJob($item);
if (!$job) {
// Failed to reconstruct, skip this item
continue;
}
// Move to processing only if we can reconstruct the job
$this->moveQueueItem($item['id'], 'pending', 'processing');
$this->unlock();
return ['job' => $job, 'id' => $item['id']];
}
$this->unlock();
return null;
} catch (\Exception $e) {
$this->unlock();
throw $e;
}
}
/**
* Mark a job as completed
*
* @param string $queueId
* @return void
*/
public function complete(string $queueId): void
{
$this->moveQueueItem($queueId, 'processing', 'completed');
// Clean up old completed items
$this->cleanupCompleted();
}
/**
* Mark a job as failed
*
* @param string $queueId
* @param string $error
* @return void
*/
public function fail(string $queueId, string $error = ''): void
{
$item = $this->getQueueItem($queueId, 'processing');
if ($item) {
$item['attempts']++;
$item['last_error'] = $error;
$item['failed_at'] = date('c');
if ($item['attempts'] < $item['max_attempts']) {
// Move back to pending for retry
$item['retry_at'] = $this->calculateRetryTime($item['attempts']);
$item['scheduled_for'] = $item['retry_at'];
$this->writeQueueItem($item, 'pending');
$this->deleteQueueItem($queueId, 'processing');
} else {
// Move to failed (dead letter queue)
$this->writeQueueItem($item, 'failed');
$this->deleteQueueItem($queueId, 'processing');
}
}
}
/**
* Get queue size
*
* @return int
*/
public function size(): int
{
return count($this->getPendingItems());
}
/**
* Check if queue is empty
*
* @return bool
*/
public function isEmpty(): bool
{
return $this->size() === 0;
}
/**
* Get queue statistics
*
* @return array
*/
public function getStatistics(): array
{
return [
'pending' => count($this->getPendingItems()),
'processing' => count($this->getItemsInDirectory('processing')),
'failed' => count($this->getItemsInDirectory('failed')),
'completed_today' => $this->countCompletedToday(),
];
}
/**
* Generate a unique queue ID
*
* @param Job $job
* @return string
*/
protected function generateQueueId(Job $job): string
{
return $job->getId() . '_' . uniqid('', true);
}
/**
* Write queue item to disk
*
* @param array $item
* @param string $directory
* @return void
*/
protected function writeQueueItem(array $item, string $directory): void
{
$path = $this->queuePath . '/' . $directory . '/' . $item['id'] . '.json';
$file = JsonFile::instance($path);
$file->save($item);
}
/**
* Read queue item from disk
*
* @param string $queueId
* @param string $directory
* @return array|null
*/
protected function getQueueItem(string $queueId, string $directory): ?array
{
$path = $this->queuePath . '/' . $directory . '/' . $queueId . '.json';
if (!file_exists($path)) {
return null;
}
$file = JsonFile::instance($path);
return $file->content();
}
/**
* Delete queue item
*
* @param string $queueId
* @param string $directory
* @return void
*/
protected function deleteQueueItem(string $queueId, string $directory): void
{
$path = $this->queuePath . '/' . $directory . '/' . $queueId . '.json';
if (file_exists($path)) {
unlink($path);
}
}
/**
* Move queue item between directories
*
* @param string $queueId
* @param string $fromDir
* @param string $toDir
* @return void
*/
protected function moveQueueItem(string $queueId, string $fromDir, string $toDir): void
{
$fromPath = $this->queuePath . '/' . $fromDir . '/' . $queueId . '.json';
$toPath = $this->queuePath . '/' . $toDir . '/' . $queueId . '.json';
if (file_exists($fromPath)) {
rename($fromPath, $toPath);
}
}
/**
* Get all pending items
*
* @return array
*/
protected function getPendingItems(): array
{
return $this->getItemsInDirectory('pending');
}
/**
* Get items in a specific directory
*
* @param string $directory
* @return array
*/
protected function getItemsInDirectory(string $directory): array
{
$items = [];
$path = $this->queuePath . '/' . $directory;
if (!is_dir($path)) {
return $items;
}
$files = glob($path . '/*.json');
foreach ($files as $file) {
$jsonFile = JsonFile::instance($file);
$items[] = $jsonFile->content();
}
return $items;
}
/**
* Reconstruct a job from queue item
*
* @param array $item
* @return Job|null
*/
protected function reconstructJob(array $item): ?Job
{
if (isset($item['serialized_job'])) {
// Unserialize the job
try {
$job = unserialize(base64_decode($item['serialized_job']));
if ($job instanceof Job) {
return $job;
}
} catch (\Exception $e) {
// Failed to unserialize
return null;
}
}
// Create a new job from command
if (isset($item['command'])) {
$args = $item['arguments'] ?? [];
$job = new Job($item['command'], $args, $item['job_id']);
return $job;
}
return null;
}
/**
* Calculate retry time with exponential backoff
*
* @param int $attempts
* @return string
*/
protected function calculateRetryTime(int $attempts): string
{
$backoffSeconds = min(pow(2, $attempts) * 60, 3600); // Max 1 hour
$retryTime = new \DateTime();
$retryTime->modify("+{$backoffSeconds} seconds");
return $retryTime->format('c');
}
/**
* Clean up old completed items
*
* @return void
*/
protected function cleanupCompleted(): void
{
$items = $this->getItemsInDirectory('completed');
$cutoff = new \DateTime('-24 hours');
foreach ($items as $item) {
if (isset($item['created_at'])) {
$createdAt = new \DateTime($item['created_at']);
if ($createdAt < $cutoff) {
$this->deleteQueueItem($item['id'], 'completed');
}
}
}
}
/**
* Count completed jobs today
*
* @return int
*/
protected function countCompletedToday(): int
{
$items = $this->getItemsInDirectory('completed');
$today = new \DateTime('today');
$count = 0;
foreach ($items as $item) {
if (isset($item['created_at'])) {
$createdAt = new \DateTime($item['created_at']);
if ($createdAt >= $today) {
$count++;
}
}
}
return $count;
}
/**
* Acquire lock for queue operations
*
* @return bool
*/
protected function lock(): bool
{
$attempts = 0;
$maxAttempts = 50; // 5 seconds total
while ($attempts < $maxAttempts) {
// Check if lock file exists and is stale (older than 30 seconds)
if (file_exists($this->lockFile)) {
$lockAge = time() - filemtime($this->lockFile);
if ($lockAge > 30) {
// Stale lock, remove it
@unlink($this->lockFile);
}
}
// Try to acquire lock atomically
$handle = @fopen($this->lockFile, 'x');
if ($handle !== false) {
fclose($handle);
return true;
}
$attempts++;
usleep(100000); // 100ms
}
// Could not acquire lock
return false;
}
/**
* Release queue lock
*
* @return void
*/
protected function unlock(): void
{
if (file_exists($this->lockFile)) {
unlink($this->lockFile);
}
}
} | php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Scheduler/IntervalTrait.php | system/src/Grav/Common/Scheduler/IntervalTrait.php | <?php
/**
* @package Grav\Common\Scheduler
* @author Originally based on peppeocchi/php-cron-scheduler modified for Grav integration
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Scheduler;
use Cron\CronExpression;
use InvalidArgumentException;
use function is_string;
/**
* Trait IntervalTrait
* @package Grav\Common\Scheduler
*/
trait IntervalTrait
{
/**
* Set the Job execution time.
*compo
* @param string $expression
* @return self
*/
public function at($expression)
{
$this->at = $expression;
$this->executionTime = CronExpression::factory($expression);
return $this;
}
/**
* Set the execution time to every minute.
*
* @return self
*/
public function everyMinute()
{
return $this->at('* * * * *');
}
/**
* Set the execution time to every hour.
*
* @param int|string $minute
* @return self
*/
public function hourly($minute = 0)
{
$c = $this->validateCronSequence($minute);
return $this->at("{$c['minute']} * * * *");
}
/**
* Set the execution time to once a day.
*
* @param int|string $hour
* @param int|string $minute
* @return self
*/
public function daily($hour = 0, $minute = 0)
{
if (is_string($hour)) {
$parts = explode(':', $hour);
$hour = $parts[0];
$minute = $parts[1] ?? '0';
}
$c = $this->validateCronSequence($minute, $hour);
return $this->at("{$c['minute']} {$c['hour']} * * *");
}
/**
* Set the execution time to once a week.
*
* @param int|string $weekday
* @param int|string $hour
* @param int|string $minute
* @return self
*/
public function weekly($weekday = 0, $hour = 0, $minute = 0)
{
if (is_string($hour)) {
$parts = explode(':', $hour);
$hour = $parts[0];
$minute = $parts[1] ?? '0';
}
$c = $this->validateCronSequence($minute, $hour, null, null, $weekday);
return $this->at("{$c['minute']} {$c['hour']} * * {$c['weekday']}");
}
/**
* Set the execution time to once a month.
*
* @param int|string $month
* @param int|string $day
* @param int|string $hour
* @param int|string $minute
* @return self
*/
public function monthly($month = '*', $day = 1, $hour = 0, $minute = 0)
{
if (is_string($hour)) {
$parts = explode(':', $hour);
$hour = $parts[0];
$minute = $parts[1] ?? '0';
}
$c = $this->validateCronSequence($minute, $hour, $day, $month);
return $this->at("{$c['minute']} {$c['hour']} {$c['day']} {$c['month']} *");
}
/**
* Set the execution time to every Sunday.
*
* @param int|string $hour
* @param int|string $minute
* @return self
*/
public function sunday($hour = 0, $minute = 0)
{
return $this->weekly(0, $hour, $minute);
}
/**
* Set the execution time to every Monday.
*
* @param int|string $hour
* @param int|string $minute
* @return self
*/
public function monday($hour = 0, $minute = 0)
{
return $this->weekly(1, $hour, $minute);
}
/**
* Set the execution time to every Tuesday.
*
* @param int|string $hour
* @param int|string $minute
* @return self
*/
public function tuesday($hour = 0, $minute = 0)
{
return $this->weekly(2, $hour, $minute);
}
/**
* Set the execution time to every Wednesday.
*
* @param int|string $hour
* @param int|string $minute
* @return self
*/
public function wednesday($hour = 0, $minute = 0)
{
return $this->weekly(3, $hour, $minute);
}
/**
* Set the execution time to every Thursday.
*
* @param int|string $hour
* @param int|string $minute
* @return self
*/
public function thursday($hour = 0, $minute = 0)
{
return $this->weekly(4, $hour, $minute);
}
/**
* Set the execution time to every Friday.
*
* @param int|string $hour
* @param int|string $minute
* @return self
*/
public function friday($hour = 0, $minute = 0)
{
return $this->weekly(5, $hour, $minute);
}
/**
* Set the execution time to every Saturday.
*
* @param int|string $hour
* @param int|string $minute
* @return self
*/
public function saturday($hour = 0, $minute = 0)
{
return $this->weekly(6, $hour, $minute);
}
/**
* Set the execution time to every January.
*
* @param int|string $day
* @param int|string $hour
* @param int|string $minute
* @return self
*/
public function january($day = 1, $hour = 0, $minute = 0)
{
return $this->monthly(1, $day, $hour, $minute);
}
/**
* Set the execution time to every February.
*
* @param int|string $day
* @param int|string $hour
* @param int|string $minute
* @return self
*/
public function february($day = 1, $hour = 0, $minute = 0)
{
return $this->monthly(2, $day, $hour, $minute);
}
/**
* Set the execution time to every March.
*
* @param int|string $day
* @param int|string $hour
* @param int|string $minute
* @return self
*/
public function march($day = 1, $hour = 0, $minute = 0)
{
return $this->monthly(3, $day, $hour, $minute);
}
/**
* Set the execution time to every April.
*
* @param int|string $day
* @param int|string $hour
* @param int|string $minute
* @return self
*/
public function april($day = 1, $hour = 0, $minute = 0)
{
return $this->monthly(4, $day, $hour, $minute);
}
/**
* Set the execution time to every May.
*
* @param int|string $day
* @param int|string $hour
* @param int|string $minute
* @return self
*/
public function may($day = 1, $hour = 0, $minute = 0)
{
return $this->monthly(5, $day, $hour, $minute);
}
/**
* Set the execution time to every June.
*
* @param int|string $day
* @param int|string $hour
* @param int|string $minute
* @return self
*/
public function june($day = 1, $hour = 0, $minute = 0)
{
return $this->monthly(6, $day, $hour, $minute);
}
/**
* Set the execution time to every July.
*
* @param int|string $day
* @param int|string $hour
* @param int|string $minute
* @return self
*/
public function july($day = 1, $hour = 0, $minute = 0)
{
return $this->monthly(7, $day, $hour, $minute);
}
/**
* Set the execution time to every August.
*
* @param int|string $day
* @param int|string $hour
* @param int|string $minute
* @return self
*/
public function august($day = 1, $hour = 0, $minute = 0)
{
return $this->monthly(8, $day, $hour, $minute);
}
/**
* Set the execution time to every September.
*
* @param int|string $day
* @param int|string $hour
* @param int|string $minute
* @return self
*/
public function september($day = 1, $hour = 0, $minute = 0)
{
return $this->monthly(9, $day, $hour, $minute);
}
/**
* Set the execution time to every October.
*
* @param int|string $day
* @param int|string $hour
* @param int|string $minute
* @return self
*/
public function october($day = 1, $hour = 0, $minute = 0)
{
return $this->monthly(10, $day, $hour, $minute);
}
/**
* Set the execution time to every November.
*
* @param int|string $day
* @param int|string $hour
* @param int|string $minute
* @return self
*/
public function november($day = 1, $hour = 0, $minute = 0)
{
return $this->monthly(11, $day, $hour, $minute);
}
/**
* Set the execution time to every December.
*
* @param int|string $day
* @param int|string $hour
* @param int|string $minute
* @return self
*/
public function december($day = 1, $hour = 0, $minute = 0)
{
return $this->monthly(12, $day, $hour, $minute);
}
/**
* Validate sequence of cron expression.
*
* @param int|string|null $minute
* @param int|string|null $hour
* @param int|string|null $day
* @param int|string|null $month
* @param int|string|null $weekday
* @return array
*/
private function validateCronSequence($minute = null, $hour = null, $day = null, $month = null, $weekday = null)
{
return [
'minute' => $this->validateCronRange($minute, 0, 59),
'hour' => $this->validateCronRange($hour, 0, 23),
'day' => $this->validateCronRange($day, 1, 31),
'month' => $this->validateCronRange($month, 1, 12),
'weekday' => $this->validateCronRange($weekday, 0, 6),
];
}
/**
* Validate sequence of cron expression.
*
* @param int|string|null $value
* @param int $min
* @param int $max
* @return mixed
*/
private function validateCronRange($value, $min, $max)
{
if ($value === null || $value === '*') {
return '*';
}
if (! is_numeric($value) ||
! ($value >= $min && $value <= $max)
) {
throw new InvalidArgumentException(
"Invalid value: it should be '*' or between {$min} and {$max}."
);
}
return $value;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Scheduler/Scheduler.php | system/src/Grav/Common/Scheduler/Scheduler.php | <?php
/**
* @package Grav\Common\Scheduler
* @author Originally based on peppeocchi/php-cron-scheduler modified for Grav integration
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Scheduler;
use DateTime;
use Grav\Common\Filesystem\Folder;
use Grav\Common\Grav;
use Grav\Common\Utils;
use InvalidArgumentException;
use Symfony\Component\Process\PhpExecutableFinder;
use Symfony\Component\Process\Process;
use RocketTheme\Toolbox\File\YamlFile;
use Symfony\Component\Yaml\Yaml;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use function is_callable;
use function is_string;
/**
* Class Scheduler
* @package Grav\Common\Scheduler
*/
class Scheduler
{
/** @var Job[] The queued jobs. */
private $jobs = [];
/** @var Job[] */
private $saved_jobs = [];
/** @var Job[] */
private $executed_jobs = [];
/** @var Job[] */
private $failed_jobs = [];
/** @var Job[] */
private $jobs_run = [];
/** @var array */
private $output_schedule = [];
/** @var array */
private $config;
/** @var string */
private $status_path;
// Modern features (backward compatible - disabled by default)
/** @var JobQueue|null */
protected $jobQueue = null;
/** @var array */
protected $workers = [];
/** @var int */
protected $maxWorkers = 1;
/** @var bool */
protected $webhookEnabled = false;
/** @var string|null */
protected $webhookToken = null;
/** @var bool */
protected $healthEnabled = true;
/** @var string */
protected $queuePath;
/** @var string */
protected $historyPath;
/** @var Logger|null */
protected $logger = null;
/** @var array */
protected $modernConfig = [];
/**
* Create new instance.
*/
public function __construct()
{
$grav = Grav::instance();
$config = $grav['config']->get('scheduler.defaults', []);
$this->config = $config;
$locator = $grav['locator'];
$this->status_path = $locator->findResource('user-data://scheduler', true, true);
if (!file_exists($this->status_path)) {
Folder::create($this->status_path);
}
// Initialize modern features (always enabled now)
$this->modernConfig = $grav['config']->get('scheduler.modern', []);
// Always initialize modern features - they're now part of core
$this->initializeModernFeatures($locator);
}
/**
* Load saved jobs from config/scheduler.yaml file
*
* @return $this
*/
public function loadSavedJobs()
{
// Only load saved jobs if they haven't been loaded yet
if (!empty($this->saved_jobs)) {
return $this;
}
$this->saved_jobs = [];
$saved_jobs = (array) Grav::instance()['config']->get('scheduler.custom_jobs', []);
foreach ($saved_jobs as $id => $j) {
$args = $j['args'] ?? [];
$id = Grav::instance()['inflector']->hyphenize($id);
// Check if job already exists to prevent duplicates
$existingJob = null;
foreach ($this->jobs as $existingJobItem) {
if ($existingJobItem->getId() === $id) {
$existingJob = $existingJobItem;
break;
}
}
if ($existingJob) {
// Job already exists, just update saved_jobs reference
$this->saved_jobs[] = $existingJob;
continue;
}
$job = $this->addCommand($j['command'], $args, $id);
if (isset($j['at'])) {
$job->at($j['at']);
}
if (isset($j['output'])) {
$mode = isset($j['output_mode']) && $j['output_mode'] === 'append';
$job->output($j['output'], $mode);
}
if (isset($j['email'])) {
$job->email($j['email']);
}
// store in saved_jobs
$this->saved_jobs[] = $job;
}
return $this;
}
/**
* Get the queued jobs as background/foreground
*
* @param bool $all
* @return array
*/
public function getQueuedJobs($all = false)
{
$background = [];
$foreground = [];
foreach ($this->jobs as $job) {
if ($all || $job->getEnabled()) {
if ($job->runInBackground()) {
$background[] = $job;
} else {
$foreground[] = $job;
}
}
}
return [$background, $foreground];
}
/**
* Get the job queue
*
* @return JobQueue|null
*/
public function getJobQueue(): ?JobQueue
{
return $this->jobQueue;
}
/**
* Get all jobs if they are disabled or not as one array
*
* @return Job[]
*/
public function getAllJobs()
{
[$background, $foreground] = $this->loadSavedJobs()->getQueuedJobs(true);
return array_merge($background, $foreground);
}
/**
* Get a specific Job based on id
*
* @param string $jobid
* @return Job|null
*/
public function getJob($jobid)
{
$all = $this->getAllJobs();
foreach ($all as $job) {
if ($jobid == $job->getId()) {
return $job;
}
}
return null;
}
/**
* Queues a PHP function execution.
*
* @param callable $fn The function to execute
* @param array $args Optional arguments to pass to the php script
* @param string|null $id Optional custom identifier
* @return Job
*/
public function addFunction(callable $fn, $args = [], $id = null)
{
$job = new Job($fn, $args, $id);
$this->queueJob($job->configure($this->config));
return $job;
}
/**
* Queue a raw shell command.
*
* @param string $command The command to execute
* @param array $args Optional arguments to pass to the command
* @param string|null $id Optional custom identifier
* @return Job
*/
public function addCommand($command, $args = [], $id = null)
{
$job = new Job($command, $args, $id);
$this->queueJob($job->configure($this->config));
return $job;
}
/**
* Run the scheduler.
*
* @param DateTime|null $runTime Optional, run at specific moment
* @param bool $force force run even if not due
*/
public function run(DateTime $runTime = null, $force = false)
{
// Initialize system jobs if not already done
$grav = Grav::instance();
if (count($this->jobs) === 0) {
// Trigger event to load system jobs (cache-purge, cache-clear, backups, etc.)
$grav->fireEvent('onSchedulerInitialized', new \RocketTheme\Toolbox\Event\Event(['scheduler' => $this]));
}
$this->loadSavedJobs();
[$background, $foreground] = $this->getQueuedJobs(false);
$alljobs = array_merge($background, $foreground);
if (null === $runTime) {
$runTime = new DateTime('now');
}
// Log scheduler run
if ($this->logger) {
$jobCount = count($alljobs);
$forceStr = $force ? ' (forced)' : '';
$this->logger->debug("Scheduler run started - {$jobCount} jobs available{$forceStr}", [
'time' => $runTime->format('Y-m-d H:i:s')
]);
}
// Process jobs based on modern features
if ($this->jobQueue && ($this->modernConfig['queue']['enabled'] ?? false)) {
// Queue jobs for processing
$queuedCount = 0;
foreach ($alljobs as $job) {
if ($job->isDue($runTime) || $force) {
// Add to queue for concurrent processing
$this->jobQueue->push($job);
$queuedCount++;
}
}
if ($this->logger && $queuedCount > 0) {
$this->logger->debug("Queued {$queuedCount} job(s) for processing");
}
// Process queue with workers
$this->processJobsWithWorkers();
// When using queue, states are saved by executeJob when jobs complete
// Don't save states here as jobs may still be processing
} else {
// Legacy processing (one at a time)
foreach ($alljobs as $job) {
if ($job->isDue($runTime) || $force) {
$job->run();
$this->jobs_run[] = $job;
}
}
// Finish handling any background jobs
foreach ($background as $job) {
$job->finalize();
}
// Store states for legacy mode
$this->saveJobStates();
// Save history if enabled
if (($this->modernConfig['history']['enabled'] ?? false) && $this->historyPath) {
$this->saveJobHistory();
}
}
// Log run summary
if ($this->logger) {
$successCount = 0;
$failureCount = 0;
$failedJobNames = [];
$executedJobs = array_merge($this->executed_jobs, $this->jobs_run);
foreach ($executedJobs as $job) {
if ($job->isSuccessful()) {
$successCount++;
} else {
$failureCount++;
$failedJobNames[] = $job->getId();
}
}
if (count($executedJobs) > 0) {
if ($failureCount > 0) {
$failedList = implode(', ', $failedJobNames);
$this->logger->warning("Scheduler completed: {$successCount} succeeded, {$failureCount} failed (failed: {$failedList})");
} else {
$this->logger->info("Scheduler completed: {$successCount} job(s) succeeded");
}
} else {
$this->logger->debug('Scheduler completed: no jobs were due');
}
}
// Store run date
file_put_contents("logs/lastcron.run", (new DateTime("now"))->format("Y-m-d H:i:s"), LOCK_EX);
// Update last run timestamp for health checks
$this->updateLastRun();
}
/**
* Reset all collected data of last run.
*
* Call before run() if you call run() multiple times.
*
* @return $this
*/
public function resetRun()
{
// Reset collected data of last run
$this->executed_jobs = [];
$this->failed_jobs = [];
$this->output_schedule = [];
return $this;
}
/**
* Get the scheduler verbose output.
*
* @param string $type Allowed: text, html, array
* @return string|array The return depends on the requested $type
*/
public function getVerboseOutput($type = 'text')
{
switch ($type) {
case 'text':
return implode("\n", $this->output_schedule);
case 'html':
return implode('<br>', $this->output_schedule);
case 'array':
return $this->output_schedule;
default:
throw new InvalidArgumentException('Invalid output type');
}
}
/**
* Remove all queued Jobs.
*
* @return $this
*/
public function clearJobs()
{
$this->jobs = [];
return $this;
}
/**
* Helper to get the full Cron command
*
* @return string
*/
public function getCronCommand()
{
$command = $this->getSchedulerCommand();
return "(crontab -l; echo \"* * * * * {$command} 1>> /dev/null 2>&1\") | crontab -";
}
/**
* @param string|null $php
* @return string
*/
public function getSchedulerCommand($php = null)
{
$phpBinaryFinder = new PhpExecutableFinder();
$php = $php ?? $phpBinaryFinder->find();
$command = 'cd ' . str_replace(' ', '\ ', GRAV_ROOT) . ';' . $php . ' bin/grav scheduler';
return $command;
}
/**
* Helper to determine if cron-like job is setup
* 0 - Crontab Not found
* 1 - Crontab Found
* 2 - Error
*
* @return int
*/
public function isCrontabSetup()
{
// Check for external triggers
$last_run = @file_get_contents("logs/lastcron.run");
if (time() - strtotime($last_run) < 120){
return 1;
}
// No external triggers found, so do legacy cron checks
$process = new Process(['crontab', '-l']);
$process->run();
if ($process->isSuccessful()) {
$output = $process->getOutput();
$command = str_replace('/', '\/', $this->getSchedulerCommand('.*'));
$full_command = '/^(?!#).* .* .* .* .* ' . $command . '/m';
return preg_match($full_command, $output) ? 1 : 0;
}
$error = $process->getErrorOutput();
return Utils::startsWith($error, 'crontab: no crontab') ? 0 : 2;
}
/**
* Get the Job states file
*
* @return YamlFile
*/
public function getJobStates()
{
return YamlFile::instance($this->status_path . '/status.yaml');
}
/**
* Save job states to statys file
*
* @return void
*/
private function saveJobStates()
{
$now = time();
$new_states = [];
foreach ($this->jobs_run as $job) {
if ($job->isSuccessful()) {
$new_states[$job->getId()] = ['state' => 'success', 'last-run' => $now];
$this->pushExecutedJob($job);
} else {
$new_states[$job->getId()] = ['state' => 'failure', 'last-run' => $now, 'error' => $job->getOutput()];
$this->pushFailedJob($job);
}
}
$saved_states = $this->getJobStates();
$saved_states->save(array_merge($saved_states->content(), $new_states));
}
/**
* Try to determine who's running the process
*
* @return false|string
*/
public function whoami()
{
$process = new Process(['whoami']);
$process->run();
if ($process->isSuccessful()) {
return trim($process->getOutput());
}
return $process->getErrorOutput();
}
/**
* Initialize modern features
*
* @param mixed $locator
* @return void
*/
protected function initializeModernFeatures($locator): void
{
// Set up paths
$this->queuePath = $this->modernConfig['queue']['path'] ?? 'user-data://scheduler/queue';
$this->queuePath = $locator->findResource($this->queuePath, true, true);
$this->historyPath = $this->modernConfig['history']['path'] ?? 'user-data://scheduler/history';
$this->historyPath = $locator->findResource($this->historyPath, true, true);
// Create directories if they don't exist
if (!file_exists($this->queuePath)) {
Folder::create($this->queuePath);
}
if (!file_exists($this->historyPath)) {
Folder::create($this->historyPath);
}
// Initialize job queue (always enabled)
$this->jobQueue = new JobQueue($this->queuePath);
// Initialize scheduler logger
$this->initializeLogger($locator);
// Configure workers (default to 4 for concurrent processing)
$this->maxWorkers = $this->modernConfig['workers'] ?? 4;
// Configure webhook
$this->webhookEnabled = $this->modernConfig['webhook']['enabled'] ?? false;
$this->webhookToken = $this->modernConfig['webhook']['token'] ?? null;
// Configure health check
$this->healthEnabled = $this->modernConfig['health']['enabled'] ?? true;
}
/**
* Get the job queue
*
* @return JobQueue|null
*/
public function getQueue(): ?JobQueue
{
return $this->jobQueue;
}
/**
* Initialize the scheduler logger
*
* @param $locator
* @return void
*/
protected function initializeLogger($locator): void
{
$this->logger = new Logger('scheduler');
// Single scheduler log file - all levels
$logFile = $locator->findResource('log://scheduler.log', true, true);
$this->logger->pushHandler(new StreamHandler($logFile, Logger::DEBUG));
}
/**
* Get the scheduler logger
*
* @return Logger|null
*/
public function getLogger(): ?Logger
{
return $this->logger;
}
/**
* Check if webhook is enabled
*
* @return bool
*/
public function isWebhookEnabled(): bool
{
return $this->webhookEnabled;
}
/**
* Get active trigger methods
*
* @return array
*/
public function getActiveTriggers(): array
{
$triggers = [];
$cronStatus = $this->isCrontabSetup();
if ($cronStatus === 1) {
$triggers[] = 'cron';
}
// Check if webhook is enabled
if ($this->isWebhookEnabled()) {
$triggers[] = 'webhook';
}
return $triggers;
}
/**
* Queue a job for execution in the correct queue.
*
* @param Job $job
* @return void
*/
private function queueJob(Job $job)
{
$this->jobs[] = $job;
// Store jobs
}
/**
* Add an entry to the scheduler verbose output array.
*
* @param string $string
* @return void
*/
private function addSchedulerVerboseOutput($string)
{
$now = '[' . (new DateTime('now'))->format('c') . '] ';
$this->output_schedule[] = $now . $string;
// Print to stdoutput in light gray
// echo "\033[37m{$string}\033[0m\n";
}
/**
* Push a succesfully executed job.
*
* @param Job $job
* @return Job
*/
private function pushExecutedJob(Job $job)
{
$this->executed_jobs[] = $job;
$command = $job->getCommand();
$args = $job->getArguments();
// If callable, log the string Closure
if (is_callable($command)) {
$command = is_string($command) ? $command : 'Closure';
}
$this->addSchedulerVerboseOutput("<green>Success</green>: <white>{$command} {$args}</white>");
return $job;
}
/**
* Push a failed job.
*
* @param Job $job
* @return Job
*/
private function pushFailedJob(Job $job)
{
$this->failed_jobs[] = $job;
$command = $job->getCommand();
// If callable, log the string Closure
if (is_callable($command)) {
$command = is_string($command) ? $command : 'Closure';
}
$output = trim($job->getOutput());
$this->addSchedulerVerboseOutput("<red>Error</red>: <white>{$command}</white> → <normal>{$output}</normal>");
return $job;
}
/**
* Process jobs using multiple workers
*
* @return void
*/
protected function processJobsWithWorkers(): void
{
if (!$this->jobQueue) {
return;
}
// Process all queued jobs
while (!$this->jobQueue->isEmpty()) {
// Wait if we've reached max workers
while (count($this->workers) >= $this->maxWorkers) {
foreach ($this->workers as $workerId => $worker) {
$process = null;
if (is_array($worker) && isset($worker['process'])) {
$process = $worker['process'];
} elseif ($worker instanceof Process) {
$process = $worker;
}
if ($process instanceof Process && !$process->isRunning()) {
// Finalize job if needed
if (is_array($worker) && isset($worker['job'])) {
$worker['job']->finalize();
// Save job state
$this->saveJobState($worker['job']);
// Update queue status
if (isset($worker['queueId']) && $this->jobQueue) {
if ($worker['job']->isSuccessful()) {
$this->jobQueue->complete($worker['queueId']);
} else {
$this->jobQueue->fail($worker['queueId'], $worker['job']->getOutput() ?: 'Job failed');
}
}
}
unset($this->workers[$workerId]);
}
}
if (count($this->workers) >= $this->maxWorkers) {
usleep(100000); // Wait 100ms
}
}
// Get next job from queue
$queueItem = $this->jobQueue->popWithId();
if ($queueItem) {
$this->executeJob($queueItem['job'], $queueItem['id']);
}
}
// Wait for all remaining workers to complete
foreach ($this->workers as $workerId => $worker) {
if (is_array($worker) && isset($worker['process'])) {
$process = $worker['process'];
if ($process instanceof Process) {
$process->wait();
// Finalize and save state for background jobs
if (isset($worker['job'])) {
$worker['job']->finalize();
$this->saveJobState($worker['job']);
// Log background job completion
if ($this->logger) {
$job = $worker['job'];
$jobId = $job->getId();
$command = is_string($job->getCommand()) ? $job->getCommand() : 'Closure';
if ($job->isSuccessful()) {
$execTime = method_exists($job, 'getExecutionTime') ? $job->getExecutionTime() : null;
$timeStr = $execTime ? sprintf(' (%.2fs)', $execTime) : '';
$this->logger->info("Job '{$jobId}' completed successfully{$timeStr}", [
'command' => $command,
'background' => true
]);
} else {
$error = trim($job->getOutput()) ?: 'Unknown error';
$this->logger->error("Job '{$jobId}' failed: {$error}", [
'command' => $command,
'background' => true
]);
}
}
}
// Update queue status for background jobs
if (isset($worker['queueId']) && $this->jobQueue) {
$job = $worker['job'];
if ($job->isSuccessful()) {
$this->jobQueue->complete($worker['queueId']);
} else {
$this->jobQueue->fail($worker['queueId'], $job->getOutput() ?: 'Job execution failed');
}
}
unset($this->workers[$workerId]);
}
} elseif ($worker instanceof Process) {
// Legacy format
$worker->wait();
unset($this->workers[$workerId]);
}
}
}
/**
* Process existing queued jobs
*
* @return void
*/
protected function processQueuedJobs(): void
{
if (!$this->jobQueue) {
return;
}
// Process any existing queued jobs from previous runs
while (!$this->jobQueue->isEmpty() && count($this->workers) < $this->maxWorkers) {
$job = $this->jobQueue->pop();
if ($job) {
$this->executeJob($job);
}
}
}
/**
* Execute a job
*
* @param Job $job
* @param string|null $queueId Queue ID if job came from queue
* @return void
*/
protected function executeJob(Job $job, ?string $queueId = null): void
{
$job->run();
$this->jobs_run[] = $job;
// Save job state after execution
$this->saveJobState($job);
// Check if job runs in background
if ($job->runInBackground()) {
// Background job - track it for later completion
$process = $job->getProcess();
if ($process && $process->isStarted()) {
$this->workers[] = [
'process' => $process,
'job' => $job,
'queueId' => $queueId
];
// Don't update queue status yet - will be done when process completes
return;
}
}
// Foreground job or background job that didn't start - update queue status immediately
if ($queueId && $this->jobQueue) {
// Job has already been finalized if it ran in foreground
if (!$job->runInBackground()) {
$job->finalize();
}
if ($job->isSuccessful()) {
// Move from processing to completed
$this->jobQueue->complete($queueId);
} else {
// Move from processing to failed
$this->jobQueue->fail($queueId, $job->getOutput() ?: 'Job execution failed');
}
}
// Log foreground jobs immediately
if (!$job->runInBackground() && $this->logger) {
$jobId = $job->getId();
$command = is_string($job->getCommand()) ? $job->getCommand() : 'Closure';
if ($job->isSuccessful()) {
$execTime = method_exists($job, 'getExecutionTime') ? $job->getExecutionTime() : null;
$timeStr = $execTime ? sprintf(' (%.2fs)', $execTime) : '';
$this->logger->info("Job '{$jobId}' completed successfully{$timeStr}", [
'command' => $command
]);
} else {
$error = trim($job->getOutput()) ?: 'Unknown error';
$this->logger->error("Job '{$jobId}' failed: {$error}", [
'command' => $command
]);
}
}
}
/**
* Save state for a single job
*
* @param Job $job
* @return void
*/
protected function saveJobState(Job $job): void
{
$grav = Grav::instance();
$locator = $grav['locator'];
$statusFile = $locator->findResource('user-data://scheduler/status.yaml', true, true);
$status = [];
if (file_exists($statusFile)) {
$status = Yaml::parseFile($statusFile) ?: [];
}
// Update job status
$status[$job->getId()] = [
'state' => $job->isSuccessful() ? 'success' : 'failure',
'last-run' => time(),
];
// Add error if job failed
if (!$job->isSuccessful()) {
$output = $job->getOutput();
if ($output) {
$status[$job->getId()]['error'] = $output;
} else {
$status[$job->getId()]['error'] = null;
}
}
file_put_contents($statusFile, Yaml::dump($status));
}
/**
* Save job execution history
*
* @return void
*/
protected function saveJobHistory(): void
{
if (!$this->historyPath) {
return;
}
$history = [];
foreach ($this->jobs_run as $job) {
$history[] = [
'id' => $job->getId(),
'executed_at' => date('c'),
'success' => $job->isSuccessful(),
'output' => substr($job->getOutput(), 0, 1000),
];
}
if (!empty($history)) {
$filename = $this->historyPath . '/' . date('Y-m-d') . '.json';
$existing = file_exists($filename) ? json_decode(file_get_contents($filename), true) : [];
$existing = array_merge($existing, $history);
file_put_contents($filename, json_encode($existing, JSON_PRETTY_PRINT));
}
}
/**
* Update last run timestamp
*
* @return void
*/
protected function updateLastRun(): void
{
$lastRunFile = $this->status_path . '/last_run.txt';
file_put_contents($lastRunFile, date('Y-m-d H:i:s'));
}
/**
* Get health status
*
* @return array
*/
public function getHealthStatus(): array
{
$lastRunFile = $this->status_path . '/last_run.txt';
$lastRun = file_exists($lastRunFile) ? file_get_contents($lastRunFile) : null;
// Initialize system jobs if not already done
$grav = Grav::instance();
if (count($this->jobs) === 0) {
// Trigger event to load system jobs (cache-purge, cache-clear, backups, etc.)
$grav->fireEvent('onSchedulerInitialized', new \RocketTheme\Toolbox\Event\Event(['scheduler' => $this]));
}
// Load custom jobs
$this->loadSavedJobs();
// Get only enabled jobs for health status
[$background, $foreground] = $this->getQueuedJobs(false);
$enabledJobs = array_merge($background, $foreground);
$now = new DateTime('now');
$dueJobs = 0;
foreach ($enabledJobs as $job) {
if ($job->isDue($now)) {
$dueJobs++;
}
}
$health = [
'status' => 'healthy',
'last_run' => $lastRun,
'last_run_age' => null,
'queue_size' => 0,
'failed_jobs_24h' => 0,
'scheduled_jobs' => count($enabledJobs),
'jobs_due' => $dueJobs,
'webhook_enabled' => $this->webhookEnabled,
'health_check_enabled' => $this->healthEnabled,
'timestamp' => date('c'),
];
// Calculate last run age
if ($lastRun) {
$lastRunTime = new DateTime($lastRun);
$health['last_run_age'] = $now->getTimestamp() - $lastRunTime->getTimestamp();
}
// Determine status based on whether jobs are due
if ($dueJobs > 0) {
// Jobs are due but haven't been run
if ($health['last_run_age'] === null || $health['last_run_age'] > 300) { // No run or older than 5 minutes
$health['status'] = 'warning';
$health['message'] = $dueJobs . ' job(s) are due to run';
}
} else {
// No jobs are due - this is healthy
$health['status'] = 'healthy';
$health['message'] = 'No jobs currently due';
}
// Add queue stats if available
if ($this->jobQueue) {
$stats = $this->jobQueue->getStatistics();
$health['queue_size'] = $stats['pending'] ?? 0;
$health['failed_jobs_24h'] = $stats['failed'] ?? 0;
}
return $health;
}
/**
* Process webhook trigger
*
* @param string|null $token
* @param string|null $jobId
* @return array
*/
public function processWebhookTrigger($token = null, $jobId = null): array
{
if (!$this->webhookEnabled) {
return ['success' => false, 'message' => 'Webhook triggers are not enabled'];
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | true |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Page/Page.php | system/src/Grav/Common/Page/Page.php | <?php
/**
* @package Grav\Common\Page
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Page;
use Exception;
use Grav\Common\Cache;
use Grav\Common\Config\Config;
use Grav\Common\Data\Blueprint;
use Grav\Common\File\CompiledYamlFile;
use Grav\Common\Filesystem\Folder;
use Grav\Common\Grav;
use Grav\Common\Language\Language;
use Grav\Common\Markdown\Parsedown;
use Grav\Common\Markdown\ParsedownExtra;
use Grav\Common\Page\Interfaces\PageCollectionInterface;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Common\Media\Traits\MediaTrait;
use Grav\Common\Page\Markdown\Excerpts;
use Grav\Common\Page\Traits\PageFormTrait;
use Grav\Common\Twig\Twig;
use Grav\Common\Uri;
use Grav\Common\Utils;
use Grav\Common\Yaml;
use Grav\Framework\Flex\Flex;
use InvalidArgumentException;
use RocketTheme\Toolbox\Event\Event;
use RocketTheme\Toolbox\File\MarkdownFile;
use RuntimeException;
use SplFileInfo;
use function dirname;
use function in_array;
use function is_array;
use function is_object;
use function is_string;
use function strlen;
define('PAGE_ORDER_PREFIX_REGEX', '/^[0-9]+\./u');
/**
* Class Page
* @package Grav\Common\Page
*/
class Page implements PageInterface
{
use PageFormTrait;
use MediaTrait;
/** @var string|null Filename. Leave as null if page is folder. */
protected $name;
/** @var bool */
protected $initialized = false;
/** @var string */
protected $folder;
/** @var string */
protected $path;
/** @var string */
protected $extension;
/** @var string */
protected $url_extension;
/** @var string */
protected $id;
/** @var string */
protected $parent;
/** @var string */
protected $template;
/** @var int */
protected $expires;
/** @var string */
protected $cache_control;
/** @var bool */
protected $visible;
/** @var bool */
protected $published;
/** @var int */
protected $publish_date;
/** @var int|null */
protected $unpublish_date;
/** @var string */
protected $slug;
/** @var string|null */
protected $route;
/** @var string|null */
protected $raw_route;
/** @var string */
protected $url;
/** @var array */
protected $routes;
/** @var bool */
protected $routable;
/** @var int */
protected $modified;
/** @var string */
protected $redirect;
/** @var string */
protected $external_url;
/** @var object|null */
protected $header;
/** @var string */
protected $frontmatter;
/** @var string */
protected $language;
/** @var string|null */
protected $content;
/** @var array */
protected $content_meta;
/** @var string|null */
protected $summary;
/** @var string */
protected $raw_content;
/** @var array|null */
protected $metadata;
/** @var string */
protected $title;
/** @var int */
protected $max_count;
/** @var string */
protected $menu;
/** @var int */
protected $date;
/** @var string */
protected $dateformat;
/** @var array */
protected $taxonomy;
/** @var string */
protected $order_by;
/** @var string */
protected $order_dir;
/** @var array|string|null */
protected $order_manual;
/** @var bool */
protected $modular_twig;
/** @var array */
protected $process;
/** @var int|null */
protected $summary_size;
/** @var bool */
protected $markdown_extra;
/** @var bool */
protected $etag;
/** @var bool */
protected $last_modified;
/** @var string */
protected $home_route;
/** @var bool */
protected $hide_home_route;
/** @var bool */
protected $ssl;
/** @var string */
protected $template_format;
/** @var bool */
protected $debugger;
/** @var PageInterface|null Unmodified (original) version of the page. Used for copying and moving the page. */
private $_original;
/** @var string Action */
private $_action;
/**
* Page Object Constructor
*/
public function __construct()
{
/** @var Config $config */
$config = Grav::instance()['config'];
$this->taxonomy = [];
$this->process = $config->get('system.pages.process');
$this->published = true;
}
/**
* 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)
{
$config = Grav::instance()['config'];
$this->initialized = true;
// some extension logic
if (empty($extension)) {
$this->extension('.' . $file->getExtension());
} else {
$this->extension($extension);
}
// extract page language from page extension
$language = trim(Utils::basename($this->extension(), 'md'), '.') ?: null;
$this->language($language);
$this->hide_home_route = $config->get('system.home.hide_in_urls', false);
$this->home_route = $this->adjustRouteCase($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(strpos($this->slug(), '_') === 0);
$this->setPublishState();
$this->published();
$this->urlExtension();
return $this;
}
#[\ReturnTypeWillChange]
public function __clone()
{
$this->initialized = false;
$this->header = $this->header ? clone $this->header : null;
}
/**
* @return void
*/
public function initialize(): void
{
if (!$this->initialized) {
$this->initialized = true;
$this->route = null;
$this->raw_route = null;
$this->_forms = null;
}
}
/**
* @return void
*/
protected function processFrontmatter()
{
// Quick check for twig output tags in frontmatter if enabled
$process_fields = (array)$this->header();
if (Utils::contains(json_encode(array_values($process_fields)), '{{')) {
$ignored_fields = [];
foreach ((array)Grav::instance()['config']->get('system.pages.frontmatter.ignore_fields') as $field) {
if (isset($process_fields[$field])) {
$ignored_fields[$field] = $process_fields[$field];
unset($process_fields[$field]);
}
}
$text_header = Grav::instance()['twig']->processString(json_encode($process_fields, JSON_UNESCAPED_UNICODE), ['page' => $this]);
$this->header((object)(json_decode($text_header, true) + $ignored_fields));
}
}
/**
* Return an array with the routes of other translated languages
*
* @param bool $onlyPublished only return published translations
* @return array the page translated languages
*/
public function translatedLanguages($onlyPublished = false)
{
$grav = Grav::instance();
/** @var Language $language */
$language = $grav['language'];
$languages = $language->getLanguages();
$defaultCode = $language->getDefault();
$name = substr($this->name, 0, -strlen($this->extension()));
$translatedLanguages = [];
foreach ($languages as $languageCode) {
$languageExtension = ".{$languageCode}.md";
$path = $this->path . DS . $this->folder . DS . $name . $languageExtension;
$exists = file_exists($path);
// Default language may be saved without language file location.
if (!$exists && $languageCode === $defaultCode) {
$languageExtension = '.md';
$path = $this->path . DS . $this->folder . DS . $name . $languageExtension;
$exists = file_exists($path);
}
if ($exists) {
$aPage = new Page();
$aPage->init(new SplFileInfo($path), $languageExtension);
$aPage->route($this->route());
$aPage->rawRoute($this->rawRoute());
$route = $aPage->header()->routes['default'] ?? $aPage->rawRoute();
if (!$route) {
$route = $aPage->route();
}
if ($onlyPublished && !$aPage->published()) {
continue;
}
$translatedLanguages[$languageCode] = $route;
}
}
return $translatedLanguages;
}
/**
* Return an array listing untranslated languages available
*
* @param bool $includeUnpublished also list unpublished translations
* @return array the page untranslated languages
*/
public function untranslatedLanguages($includeUnpublished = false)
{
$grav = Grav::instance();
/** @var Language $language */
$language = $grav['language'];
$languages = $language->getLanguages();
$translated = array_keys($this->translatedLanguages(!$includeUnpublished));
return array_values(array_diff($languages, $translated));
}
/**
* Gets and Sets the raw data
*
* @param string|null $var Raw content string
* @return string 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|null $var a YAML object representing the configuration for the file
* @return \stdClass 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) {
try {
$this->raw_content = $file->markdown();
$this->frontmatter = $file->frontmatter();
$this->header = (object)$file->header();
if (!Utils::isAdminPlugin()) {
// If there's a `frontmatter.yaml` file merge that in with the page header
// note page's own frontmatter has precedence and will overwrite any defaults
$frontmatter_filename = $this->path . '/' . $this->folder . '/frontmatter.yaml';
if (file_exists($frontmatter_filename)) {
$frontmatter_file = CompiledYamlFile::instance($frontmatter_filename);
$frontmatter_data = $frontmatter_file->content();
$this->header = (object)array_replace_recursive(
$frontmatter_data,
(array)$this->header
);
$frontmatter_file->free();
}
// Process frontmatter with Twig if enabled
if (Grav::instance()['config']->get('system.pages.frontmatter.process_twig') === true) {
$this->processFrontmatter();
}
}
} catch (Exception $e) {
$file->raw(Grav::instance()['language']->translate([
'GRAV.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->modified)) {
$this->modified($this->header->modified);
}
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->external_url)) {
$this->external_url = trim($this->header->external_url);
}
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)) {
$this->taxonomy($this->header->taxonomy);
}
if (isset($this->header->max_count)) {
$this->max_count = (int)$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 = (int)$this->header->expires;
}
if (isset($this->header->cache_control)) {
$this->cache_control = $this->header->cache_control;
}
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;
}
if (isset($this->header->template_format)) {
$this->template_format = $this->header->template_format;
}
if (isset($this->header->debugger)) {
$this->debugger = (bool)$this->header->debugger;
}
if (isset($this->header->append_url_extension)) {
$this->url_extension = $this->header->append_url_extension;
}
}
return $this->header;
}
/**
* Get page language
*
* @param string|null $var
* @return mixed
*/
public function language($var = null)
{
if ($var !== null) {
$this->language = $var;
}
return $this->language;
}
/**
* Modify a header value directly
*
* @param string $key
* @param mixed $value
*/
public function modifyHeader($key, $value)
{
$this->header->{$key} = $value;
}
/**
* @return int
*/
public function httpResponseCode()
{
return (int)($this->header()->http_response_code ?? 200);
}
/**
* @return array
*/
public function httpHeaders()
{
$headers = [];
$grav = Grav::instance();
$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 = $this->modified();
foreach ($this->children()->modular() as $cpage) {
$modular_mtime = $cpage->modified();
if ($modular_mtime > $last_modified) {
$last_modified = $modular_mtime;
}
}
$last_modified_date = gmdate('D, d M Y H:i:s', $last_modified) . ' GMT';
$headers['Last-Modified'] = $last_modified_date;
}
// Ask Grav to calculate ETag from the final content.
if ($this->eTag()) {
$headers['ETag'] = '1';
}
// Set Vary: Accept-Encoding header
if ($grav['config']->get('system.pages.vary_accept_encoding', false)) {
$headers['Vary'] = 'Accept-Encoding';
}
// Added new Headers event
$headers_obj = (object) $headers;
Grav::instance()->fireEvent('onPageHeaders', new Event(['headers' => $headers_obj]));
return (array)$headers_obj;
}
/**
* Get the summary.
*
* @param int|null $size Max summary size.
* @param bool $textOnly Only count text size.
* @return string
*/
public function summary($size = null, $textOnly = false)
{
$config = (array)Grav::instance()['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 = $textOnly ? strip_tags($this->content()) : $this->content();
$summary_size = $this->summary_size;
} else {
$content = $textOnly ? strip_tags($this->summary) : $this->summary;
$summary_size = mb_strwidth($content, 'utf-8');
}
// 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;
}
if (($format === 'short') && isset($summary_size)) {
// Slice the string
if (mb_strwidth($content, 'utf8') > $summary_size) {
return mb_substr($content, 0, $summary_size);
}
return $content;
}
// Get summary size from site config's file
if ($size === null) {
$size = $config['size'];
}
// If the size is zero, return the entire page content
if ($size === 0) {
return $content;
// Return calculated summary based on defaults
}
if (!is_numeric($size) || ($size < 0)) {
$size = 300;
}
// Only return string but not html, wrap whatever html tag you want when using
if ($textOnly) {
if (mb_strwidth($content, 'utf-8') <= $size) {
return $content;
}
return mb_strimwidth($content, 0, $size, '…', 'UTF-8');
}
$summary = Utils::truncateHtml($content, $size);
return html_entity_decode($summary, ENT_COMPAT | ENT_HTML401, 'UTF-8');
}
/**
* 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|null $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 = Grav::instance()['config'];
// Load cached content
/** @var Cache $cache */
$cache = Grav::instance()['cache'];
$cache_id = md5('page' . $this->getCacheKey());
$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') || $this->modularTwig();
$cache_enable = $this->header->cache_enable ?? $config->get(
'system.cache.enabled',
true
);
$twig_first = $this->header->twig_first ?? $config->get(
'system.pages.twig_first',
false
);
// never cache twig means it's always run after content
$never_cache_twig = $this->header->never_cache_twig ?? $config->get(
'system.pages.never_cache_twig',
true
);
// if no cached-content run everything
if ($never_cache_twig) {
if ($this->content === false || $cache_enable === false) {
$this->content = $this->raw_content;
Grav::instance()->fireEvent('onPageContentRaw', new Event(['page' => $this]));
if ($process_markdown) {
$this->processMarkdown();
}
// Content Processed but not cached yet
Grav::instance()->fireEvent('onPageContentProcessed', new Event(['page' => $this]));
if ($cache_enable) {
$this->cachePageContent();
}
}
if ($process_twig) {
$this->processTwig();
}
} else {
if ($this->content === false || $cache_enable === false) {
$this->content = $this->raw_content;
Grav::instance()->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
Grav::instance()->fireEvent('onPageContentProcessed', new Event(['page' => $this]));
} else {
if ($process_markdown) {
$this->processMarkdown($process_twig);
}
// Content Processed but not cached yet
Grav::instance()->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);
}
// Fire event when Page::content() is called
Grav::instance()->fireEvent('onPageContent', new Event(['page' => $this]));
}
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 string $name
* @param mixed $value
*/
public function addContentMeta($name, $value)
{
$this->content_meta[$name] = $value;
}
/**
* Return the whole contentMeta array as it currently stands
*
* @param string|null $name
*
* @return mixed|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)
{
return $this->content_meta = $content_meta;
}
/**
* Process the Markdown content. Uses Parsedown or Parsedown Extra depending on configuration
*
* @param bool $keepTwig If true, content between twig tags will not be processed.
* @return void
*/
protected function processMarkdown(bool $keepTwig = false)
{
/** @var Config $config */
$config = Grav::instance()['config'];
$markdownDefaults = (array)$config->get('system.pages.markdown');
if (isset($this->header()->markdown)) {
$markdownDefaults = array_merge($markdownDefaults, $this->header()->markdown);
}
// pages.markdown_extra is deprecated, but still check it...
if (!isset($markdownDefaults['extra']) && (isset($this->markdown_extra) || $config->get('system.pages.markdown_extra') !== null)) {
user_error('Configuration option \'system.pages.markdown_extra\' is deprecated since Grav 1.5, use \'system.pages.markdown.extra\' instead', E_USER_DEPRECATED);
$markdownDefaults['extra'] = $this->markdown_extra ?: $config->get('system.pages.markdown_extra');
}
$extra = $markdownDefaults['extra'] ?? false;
$defaults = [
'markdown' => $markdownDefaults,
'images' => $config->get('system.images', [])
];
$excerpts = new Excerpts($this, $defaults);
// Initialize the preferred variant of Parsedown
if ($extra) {
$parsedown = new ParsedownExtra($excerpts);
} else {
$parsedown = new Parsedown($excerpts);
}
$content = $this->content;
if ($keepTwig) {
$token = [
'/' . Utils::generateRandomString(3),
Utils::generateRandomString(3) . '/'
];
// Base64 encode any twig.
$content = preg_replace_callback(
['/({#.*?#})/mu', '/({{.*?}})/mu', '/({%.*?%})/mu'],
static function ($matches) use ($token) { return $token[0] . base64_encode($matches[1]) . $token[1]; },
$content
);
}
$content = $parsedown->text($content);
if ($keepTwig) {
// Base64 decode the encoded twig.
$content = preg_replace_callback(
['`' . $token[0] . '([A-Za-z0-9+/]+={0,2})' . $token[1] . '`mu'],
static function ($matches) { return base64_decode($matches[1]); },
$content
);
}
$this->content = $content;
}
/**
* Process the Twig page content.
*
* @return void
*/
private function processTwig()
{
/** @var Twig $twig */
$twig = Grav::instance()['twig'];
$this->content = $twig->processPage($this, $this->content);
}
/**
* Fires the onPageContentProcessed event, and caches the page content using a unique ID for the page
*
* @return void
*/
public function cachePageContent()
{
/** @var Cache $cache */
$cache = Grav::instance()['cache'];
$cache_id = md5('page' . $this->getCacheKey());
$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 string|null $content
* @return void
*/
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
*/
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | true |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Page/Collection.php | system/src/Grav/Common/Page/Collection.php | <?php
/**
* @package Grav\Common\Page
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Page;
use Exception;
use Grav\Common\Grav;
use Grav\Common\Iterator;
use Grav\Common\Page\Interfaces\PageCollectionInterface;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Common\Utils;
use InvalidArgumentException;
use function array_key_exists;
use function array_keys;
use function array_search;
use function count;
use function in_array;
use function is_array;
use function is_string;
/**
* Class Collection
* @package Grav\Common\Page
* @implements PageCollectionInterface<string,Page>
*/
class Collection extends Iterator implements PageCollectionInterface
{
/** @var Pages */
protected $pages;
/** @var array */
protected $params;
/**
* Collection constructor.
*
* @param array $items
* @param array $params
* @param Pages|null $pages
*/
public function __construct($items = [], array $params = [], Pages $pages = null)
{
parent::__construct($items);
$this->params = $params;
$this->pages = $pages ?: Grav::instance()->offsetGet('pages');
}
/**
* Get the collection params
*
* @return array
*/
public function params()
{
return $this->params;
}
/**
* Set parameters to the Collection
*
* @param array $params
* @return $this
*/
public function setParams(array $params)
{
$this->params = array_merge($this->params, $params);
return $this;
}
/**
* Add a single page to a collection
*
* @param PageInterface $page
* @return $this
*/
public function addPage(PageInterface $page)
{
$this->items[$page->path()] = ['slug' => $page->slug()];
return $this;
}
/**
* Add a page with path and slug
*
* @param string $path
* @param string $slug
* @return $this
*/
public function add($path, $slug)
{
$this->items[$path] = ['slug' => $slug];
return $this;
}
/**
*
* Create a copy of this collection
*
* @return static
*/
public function copy()
{
return new static($this->items, $this->params, $this->pages);
}
/**
*
* Merge another collection with the current collection
*
* @param PageCollectionInterface $collection
* @return $this
*/
public function merge(PageCollectionInterface $collection)
{
foreach ($collection as $page) {
$this->addPage($page);
}
return $this;
}
/**
* Intersect another collection with the current collection
*
* @param PageCollectionInterface $collection
* @return $this
*/
public function intersect(PageCollectionInterface $collection)
{
$array1 = $this->items;
$array2 = $collection->toArray();
$this->items = array_uintersect($array1, $array2, function ($val1, $val2) {
return strcmp($val1['slug'], $val2['slug']);
});
return $this;
}
/**
* Set current page.
*/
public function setCurrent(string $path): void
{
reset($this->items);
while (($key = key($this->items)) !== null && $key !== $path) {
next($this->items);
}
}
/**
* Returns current page.
*
* @return PageInterface
*/
#[\ReturnTypeWillChange]
public function current()
{
$current = parent::key();
return $this->pages->get($current);
}
/**
* Returns current slug.
*
* @return mixed
*/
#[\ReturnTypeWillChange]
public function key()
{
$current = parent::current();
return $current['slug'];
}
/**
* Returns the value at specified offset.
*
* @param string $offset
* @return PageInterface|null
*/
#[\ReturnTypeWillChange]
public function offsetGet($offset)
{
return $this->pages->get($offset) ?: null;
}
/**
* Split collection into array of smaller collections.
*
* @param int $size
* @return Collection[]
*/
public function batch($size)
{
$chunks = array_chunk($this->items, $size, true);
$list = [];
foreach ($chunks as $chunk) {
$list[] = new static($chunk, $this->params, $this->pages);
}
return $list;
}
/**
* Remove item from the list.
*
* @param PageInterface|string|null $key
* @return $this
* @throws InvalidArgumentException
*/
public function remove($key = null)
{
if ($key instanceof PageInterface) {
$key = $key->path();
} elseif (null === $key) {
$key = (string)key($this->items);
}
if (!is_string($key)) {
throw new InvalidArgumentException('Invalid argument $key.');
}
parent::remove($key);
return $this;
}
/**
* Reorder collection.
*
* @param string $by
* @param string $dir
* @param array|null $manual
* @param string|null $sort_flags
* @return $this
*/
public function order($by, $dir = 'asc', $manual = null, $sort_flags = null)
{
$this->items = $this->pages->sortCollection($this, $by, $dir, $manual, $sort_flags);
return $this;
}
/**
* Check to see if this item is the first in the collection.
*
* @param string $path
* @return bool True if item is first.
*/
public function isFirst($path): bool
{
return $this->items && $path === array_keys($this->items)[0];
}
/**
* Check to see if this item is the last in the collection.
*
* @param string $path
* @return bool True if item is last.
*/
public function isLast($path): bool
{
return $this->items && $path === array_keys($this->items)[count($this->items) - 1];
}
/**
* Gets the previous sibling based on current position.
*
* @param string $path
*
* @return PageInterface The previous item.
*/
public function prevSibling($path)
{
return $this->adjacentSibling($path, -1);
}
/**
* Gets the next sibling based on current position.
*
* @param string $path
*
* @return PageInterface The next item.
*/
public function nextSibling($path)
{
return $this->adjacentSibling($path, 1);
}
/**
* Returns the adjacent sibling based on a direction.
*
* @param string $path
* @param int $direction either -1 or +1
* @return PageInterface|Collection The sibling item.
*/
public function adjacentSibling($path, $direction = 1)
{
$values = array_keys($this->items);
$keys = array_flip($values);
if (array_key_exists($path, $keys)) {
$index = $keys[$path] - $direction;
return isset($values[$index]) ? $this->offsetGet($values[$index]) : $this;
}
return $this;
}
/**
* Returns the item in the current position.
*
* @param string $path the path the item
* @return int|null The index of the current page, null if not found.
*/
public function currentPosition($path): ?int
{
$pos = array_search($path, array_keys($this->items), true);
return $pos !== false ? $pos : null;
}
/**
* Returns the items between a set of date ranges of either the page date field (default) or
* an arbitrary datetime page field where start date and end date are optional
* Dates must be passed in as text that strtotime() can process
* http://php.net/manual/en/function.strtotime.php
*
* @param string|null $startDate
* @param string|null $endDate
* @param string|null $field
* @return $this
* @throws Exception
*/
public function dateRange($startDate = null, $endDate = null, $field = null)
{
$start = $startDate ? Utils::date2timestamp($startDate) : null;
$end = $endDate ? Utils::date2timestamp($endDate) : null;
$date_range = [];
foreach ($this->items as $path => $slug) {
$page = $this->pages->get($path);
if (!$page) {
continue;
}
$date = $field ? strtotime($page->value($field)) : $page->date();
if ((!$start || $date >= $start) && (!$end || $date <= $end)) {
$date_range[$path] = $slug;
}
}
$this->items = $date_range;
return $this;
}
/**
* Creates new collection with only visible pages
*
* @return Collection The collection with only visible pages
*/
public function visible()
{
$visible = [];
foreach ($this->items as $path => $slug) {
$page = $this->pages->get($path);
if ($page !== null && $page->visible()) {
$visible[$path] = $slug;
}
}
$this->items = $visible;
return $this;
}
/**
* Creates new collection with only non-visible pages
*
* @return Collection The collection with only non-visible pages
*/
public function nonVisible()
{
$visible = [];
foreach ($this->items as $path => $slug) {
$page = $this->pages->get($path);
if ($page !== null && !$page->visible()) {
$visible[$path] = $slug;
}
}
$this->items = $visible;
return $this;
}
/**
* Creates new collection with only pages
*
* @return Collection The collection with only pages
*/
public function pages()
{
$modular = [];
foreach ($this->items as $path => $slug) {
$page = $this->pages->get($path);
if ($page !== null && !$page->isModule()) {
$modular[$path] = $slug;
}
}
$this->items = $modular;
return $this;
}
/**
* Creates new collection with only modules
*
* @return Collection The collection with only modules
*/
public function modules()
{
$modular = [];
foreach ($this->items as $path => $slug) {
$page = $this->pages->get($path);
if ($page !== null && $page->isModule()) {
$modular[$path] = $slug;
}
}
$this->items = $modular;
return $this;
}
/**
* Alias of pages()
*
* @return Collection The collection with only non-module pages
*/
public function nonModular()
{
$this->pages();
return $this;
}
/**
* Alias of modules()
*
* @return Collection The collection with only modules
*/
public function modular()
{
$this->modules();
return $this;
}
/**
* Creates new collection with only translated pages
*
* @return Collection The collection with only published pages
* @internal
*/
public function translated()
{
$published = [];
foreach ($this->items as $path => $slug) {
$page = $this->pages->get($path);
if ($page !== null && $page->translated()) {
$published[$path] = $slug;
}
}
$this->items = $published;
return $this;
}
/**
* Creates new collection with only untranslated pages
*
* @return Collection The collection with only non-published pages
* @internal
*/
public function nonTranslated()
{
$published = [];
foreach ($this->items as $path => $slug) {
$page = $this->pages->get($path);
if ($page !== null && !$page->translated()) {
$published[$path] = $slug;
}
}
$this->items = $published;
return $this;
}
/**
* Creates new collection with only published pages
*
* @return Collection The collection with only published pages
*/
public function published()
{
$published = [];
foreach ($this->items as $path => $slug) {
$page = $this->pages->get($path);
if ($page !== null && $page->published()) {
$published[$path] = $slug;
}
}
$this->items = $published;
return $this;
}
/**
* Creates new collection with only non-published pages
*
* @return Collection The collection with only non-published pages
*/
public function nonPublished()
{
$published = [];
foreach ($this->items as $path => $slug) {
$page = $this->pages->get($path);
if ($page !== null && !$page->published()) {
$published[$path] = $slug;
}
}
$this->items = $published;
return $this;
}
/**
* Creates new collection with only routable pages
*
* @return Collection The collection with only routable pages
*/
public function routable()
{
$routable = [];
foreach ($this->items as $path => $slug) {
$page = $this->pages->get($path);
if ($page !== null && $page->routable()) {
$routable[$path] = $slug;
}
}
$this->items = $routable;
return $this;
}
/**
* Creates new collection with only non-routable pages
*
* @return Collection The collection with only non-routable pages
*/
public function nonRoutable()
{
$routable = [];
foreach ($this->items as $path => $slug) {
$page = $this->pages->get($path);
if ($page !== null && !$page->routable()) {
$routable[$path] = $slug;
}
}
$this->items = $routable;
return $this;
}
/**
* Creates new collection with only pages of the specified type
*
* @param string $type
* @return Collection The collection
*/
public function ofType($type)
{
$items = [];
foreach ($this->items as $path => $slug) {
$page = $this->pages->get($path);
if ($page !== null && $page->template() === $type) {
$items[$path] = $slug;
}
}
$this->items = $items;
return $this;
}
/**
* Creates new collection with only pages of one of the specified types
*
* @param string[] $types
* @return Collection The collection
*/
public function ofOneOfTheseTypes($types)
{
$items = [];
foreach ($this->items as $path => $slug) {
$page = $this->pages->get($path);
if ($page !== null && in_array($page->template(), $types, true)) {
$items[$path] = $slug;
}
}
$this->items = $items;
return $this;
}
/**
* Creates new collection with only pages of one of the specified access levels
*
* @param array $accessLevels
* @return Collection The collection
*/
public function ofOneOfTheseAccessLevels($accessLevels)
{
$items = [];
foreach ($this->items as $path => $slug) {
$page = $this->pages->get($path);
if ($page !== null && isset($page->header()->access)) {
if (is_array($page->header()->access)) {
//Multiple values for access
$valid = false;
foreach ($page->header()->access as $index => $accessLevel) {
if (is_array($accessLevel)) {
foreach ($accessLevel as $innerIndex => $innerAccessLevel) {
if (in_array($innerAccessLevel, $accessLevels, false)) {
$valid = true;
}
}
} else {
if (in_array($index, $accessLevels, false)) {
$valid = true;
}
}
}
if ($valid) {
$items[$path] = $slug;
}
} else {
//Single value for access
if (in_array($page->header()->access, $accessLevels, false)) {
$items[$path] = $slug;
}
}
}
}
$this->items = $items;
return $this;
}
/**
* Get the extended version of this Collection with each page keyed by route
*
* @return array
* @throws Exception
*/
public function toExtendedArray()
{
$items = [];
foreach ($this->items as $path => $slug) {
$page = $this->pages->get($path);
if ($page !== null) {
$items[$page->route()] = $page->toArray();
}
}
return $items;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Page/Pages.php | system/src/Grav/Common/Page/Pages.php | <?php
/**
* @package Grav\Common\Page
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Page;
use Exception;
use FilesystemIterator;
use Grav\Common\Cache;
use Grav\Common\Config\Config;
use Grav\Common\Data\Blueprint;
use Grav\Common\Data\Blueprints;
use Grav\Common\Debugger;
use Grav\Common\Filesystem\Folder;
use Grav\Common\Flex\Types\Pages\PageCollection;
use Grav\Common\Flex\Types\Pages\PageIndex;
use Grav\Common\Grav;
use Grav\Common\Language\Language;
use Grav\Common\Page\Interfaces\PageCollectionInterface;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Common\Taxonomy;
use Grav\Common\Uri;
use Grav\Common\Utils;
use Grav\Events\TypesEvent;
use Grav\Framework\Flex\Flex;
use Grav\Framework\Flex\FlexDirectory;
use Grav\Framework\Flex\Interfaces\FlexTranslateInterface;
use Grav\Framework\Flex\Pages\FlexPageObject;
use Grav\Plugin\Admin;
use RocketTheme\Toolbox\Event\Event;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use RuntimeException;
use SplFileInfo;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Whoops\Exception\ErrorException;
use Collator;
use function array_key_exists;
use function array_search;
use function count;
use function dirname;
use function extension_loaded;
use function in_array;
use function is_array;
use function is_int;
use function is_string;
/**
* Class Pages
* @package Grav\Common\Page
*/
class Pages
{
/** @var FlexDirectory|null */
private $directory;
/** @var Grav */
protected $grav;
/** @var array<PageInterface> */
protected $instances = [];
/** @var array<PageInterface|string> */
protected $index = [];
/** @var array */
protected $children;
/** @var string */
protected $base = '';
/** @var string[] */
protected $baseRoute = [];
/** @var string[] */
protected $routes = [];
/** @var array */
protected $sort;
/** @var Blueprints */
protected $blueprints;
/** @var bool */
protected $enable_pages = true;
/** @var int */
protected $last_modified;
/** @var string[] */
protected $ignore_files;
/** @var string[] */
protected $ignore_folders;
/** @var bool */
protected $ignore_hidden;
/** @var string */
protected $check_method;
/** @var string */
protected $simple_pages_hash;
/** @var string */
protected $pages_cache_id;
/** @var bool */
protected $initialized = false;
/** @var string */
protected $active_lang;
/** @var bool */
protected $fire_events = false;
/** @var Types|null */
protected static $types;
/** @var string|null */
protected static $home_route;
/**
* Constructor
*
* @param Grav $grav
*/
public function __construct(Grav $grav)
{
$this->grav = $grav;
}
/**
* @return FlexDirectory|null
*/
public function getDirectory(): ?FlexDirectory
{
return $this->directory;
}
/**
* Method used in admin to disable frontend pages from being initialized.
*/
public function disablePages(): void
{
$this->enable_pages = false;
}
/**
* Method used in admin to later load frontend pages.
*/
public function enablePages(): void
{
if (!$this->enable_pages) {
$this->enable_pages = true;
$this->init();
}
}
/**
* Get or set base path for the pages.
*
* @param string|null $path
* @return string
*/
public function base($path = null)
{
if ($path !== null) {
$path = trim($path, '/');
$this->base = $path ? '/' . $path : '';
$this->baseRoute = [];
}
return $this->base;
}
/**
*
* Get base route for Grav pages.
*
* @param string|null $lang Optional language code for multilingual routes.
* @return string
*/
public function baseRoute($lang = null)
{
$key = $lang ?: $this->active_lang ?: 'default';
if (!isset($this->baseRoute[$key])) {
/** @var Language $language */
$language = $this->grav['language'];
$path_base = rtrim($this->base(), '/');
$path_lang = $language->enabled() ? $language->getLanguageURLPrefix($lang) : '';
$this->baseRoute[$key] = $path_base . $path_lang;
}
return $this->baseRoute[$key];
}
/**
*
* Get route for Grav site.
*
* @param string $route Optional route to the page.
* @param string|null $lang Optional language code for multilingual links.
* @return string
*/
public function route($route = '/', $lang = null)
{
if (!$route || $route === '/') {
return $this->baseRoute($lang) ?: '/';
}
return $this->baseRoute($lang) . $route;
}
/**
* Get relative referrer route and language code. Returns null if the route isn't within the current base, language (if set) and route.
*
* @example `$langCode = null; $referrer = $pages->referrerRoute($langCode, '/admin');` returns relative referrer url within /admin and updates $langCode
* @example `$langCode = 'en'; $referrer = $pages->referrerRoute($langCode, '/admin');` returns relative referrer url within the /en/admin
*
* @param string|null $langCode Variable to store the language code. If already set, check only against that language.
* @param string $route Optional route within the site.
* @return string|null
* @since 1.7.23
*/
public function referrerRoute(?string &$langCode, string $route = '/'): ?string
{
$referrer = $_SERVER['HTTP_REFERER'] ?? null;
// Start by checking that referrer came from our site.
$root = $this->grav['base_url_absolute'];
if (!is_string($referrer) || !str_starts_with($referrer, $root)) {
return null;
}
/** @var Language $language */
$language = $this->grav['language'];
// Get all language codes and append no language.
if (null === $langCode) {
$languages = $language->enabled() ? $language->getLanguages() : [];
$languages[] = '';
} else {
$languages[] = $langCode;
}
$path_base = rtrim($this->base(), '/');
$path_route = rtrim($route, '/');
// Try to figure out the language code.
foreach ($languages as $code) {
$path_lang = $code ? "/{$code}" : '';
$base = $path_base . $path_lang . $path_route;
if ($referrer === $base || str_starts_with($referrer, "{$base}/")) {
if (null === $langCode) {
$langCode = $code;
}
return substr($referrer, \strlen($base));
}
}
return null;
}
/**
*
* Get base URL for Grav pages.
*
* @param string|null $lang Optional language code for multilingual links.
* @param bool|null $absolute If true, return absolute url, if false, return relative url. Otherwise return default.
* @return string
*/
public function baseUrl($lang = null, $absolute = null)
{
if ($absolute === null) {
$type = 'base_url';
} elseif ($absolute) {
$type = 'base_url_absolute';
} else {
$type = 'base_url_relative';
}
return $this->grav[$type] . $this->baseRoute($lang);
}
/**
*
* Get home URL for Grav site.
*
* @param string|null $lang Optional language code for multilingual links.
* @param bool|null $absolute If true, return absolute url, if false, return relative url. Otherwise return default.
* @return string
*/
public function homeUrl($lang = null, $absolute = null)
{
return $this->baseUrl($lang, $absolute) ?: '/';
}
/**
*
* Get URL for Grav site.
*
* @param string $route Optional route to the page.
* @param string|null $lang Optional language code for multilingual links.
* @param bool|null $absolute If true, return absolute url, if false, return relative url. Otherwise return default.
* @return string
*/
public function url($route = '/', $lang = null, $absolute = null)
{
if (!$route || $route === '/') {
return $this->homeUrl($lang, $absolute);
}
return $this->baseUrl($lang, $absolute) . Uri::filterPath($route);
}
/**
* @param string $method
* @return void
*/
public function setCheckMethod($method): void
{
$this->check_method = strtolower($method);
}
/**
* @return void
*/
public function register(): void
{
$config = $this->grav['config'];
$type = $config->get('system.pages.type');
if ($type === 'flex') {
$this->initFlexPages();
}
}
/**
* Reset pages (used in search indexing etc).
*
* @return void
*/
public function reset(): void
{
$this->initialized = false;
$this->init();
}
/**
* Class initialization. Must be called before using this class.
*/
public function init(): void
{
if ($this->initialized) {
return;
}
$config = $this->grav['config'];
$this->ignore_files = (array)$config->get('system.pages.ignore_files');
$this->ignore_folders = (array)$config->get('system.pages.ignore_folders');
$this->ignore_hidden = (bool)$config->get('system.pages.ignore_hidden');
$this->fire_events = (bool)$config->get('system.pages.events.page');
$this->instances = [];
$this->index = [];
$this->children = [];
$this->routes = [];
if (!$this->check_method) {
$this->setCheckMethod($config->get('system.cache.check.method', 'file'));
}
if ($this->enable_pages === false) {
$page = $this->buildRootPage();
$this->instances[$page->path()] = $page;
return;
}
$this->buildPages();
$this->initialized = true;
}
/**
* Get or set last modification time.
*
* @param int|null $modified
* @return int|null
*/
public function lastModified($modified = null)
{
if ($modified && $modified > $this->last_modified) {
$this->last_modified = $modified;
}
return $this->last_modified;
}
/**
* Returns a list of all pages.
*
* @return PageInterface[]
*/
public function instances()
{
$instances = [];
foreach ($this->index as $path => $instance) {
$page = $this->get($path);
if ($page) {
$instances[$path] = $page;
}
}
return $instances;
}
/**
* Returns a list of all routes.
*
* @return array
*/
public function routes()
{
return $this->routes;
}
/**
* Adds a page and assigns a route to it.
*
* @param PageInterface $page Page to be added.
* @param string|null $route Optional route (uses route from the object if not set).
*/
public function addPage(PageInterface $page, $route = null): void
{
$path = $page->path() ?? '';
if (!isset($this->index[$path])) {
$this->index[$path] = $page;
$this->instances[$path] = $page;
}
$route = $page->route($route);
$parent = $page->parent();
if ($parent) {
$this->children[$parent->path() ?? ''][$path] = ['slug' => $page->slug()];
}
$this->routes[$route] = $path;
$this->grav->fireEvent('onPageProcessed', new Event(['page' => $page]));
}
/**
* Get a collection of pages in the given context.
*
* @param array $params
* @param array $context
* @return PageCollectionInterface|Collection
*/
public function getCollection(array $params = [], array $context = [])
{
if (!isset($params['items'])) {
return new Collection();
}
/** @var Config $config */
$config = $this->grav['config'];
$context += [
'event' => true,
'pagination' => true,
'url_taxonomy_filters' => $config->get('system.pages.url_taxonomy_filters'),
'taxonomies' => (array)$config->get('site.taxonomies'),
'pagination_page' => 1,
'self' => null,
];
// Include taxonomies from the URL if requested.
$process_taxonomy = $params['url_taxonomy_filters'] ?? $context['url_taxonomy_filters'];
if ($process_taxonomy) {
/** @var Uri $uri */
$uri = $this->grav['uri'];
foreach ($context['taxonomies'] as $taxonomy) {
$param = $uri->param(rawurlencode($taxonomy));
$items = is_string($param) ? explode(',', $param) : [];
foreach ($items as $item) {
$params['taxonomies'][$taxonomy][] = htmlspecialchars_decode(rawurldecode($item), ENT_QUOTES);
}
}
}
$pagination = $params['pagination'] ?? $context['pagination'];
if ($pagination && !isset($params['page'], $params['start'])) {
/** @var Uri $uri */
$uri = $this->grav['uri'];
$context['current_page'] = $uri->currentPage();
}
$collection = $this->evaluate($params['items'], $context['self']);
$collection->setParams($params);
// Filter by taxonomies.
foreach ($params['taxonomies'] ?? [] as $taxonomy => $items) {
foreach ($collection as $page) {
// Don't include modules
if ($page->isModule()) {
continue;
}
$test = $page->taxonomy()[$taxonomy] ?? [];
foreach ($items as $item) {
if (!$test || !in_array($item, $test, true)) {
$collection->remove($page->path());
}
}
}
}
$filters = $params['filter'] ?? [];
// Assume published=true if not set.
if (!isset($filters['published']) && !isset($filters['non-published'])) {
$filters['published'] = true;
}
// Remove any inclusive sets from filter.
$sets = ['published', 'visible', 'modular', 'routable'];
foreach ($sets as $type) {
$nonType = "non-{$type}";
if (isset($filters[$type], $filters[$nonType]) && $filters[$type] === $filters[$nonType]) {
if (!$filters[$type]) {
// Both options are false, return empty collection as nothing can match the filters.
return new Collection();
}
// Both options are true, remove opposite filters as all pages will match the filters.
unset($filters[$type], $filters[$nonType]);
}
}
// Filter the collection
foreach ($filters as $type => $filter) {
if (null === $filter) {
continue;
}
// Convert non-type to type.
if (str_starts_with($type, 'non-')) {
$type = substr($type, 4);
$filter = !$filter;
}
switch ($type) {
case 'translated':
if ($filter) {
$collection = $collection->translated();
} else {
$collection = $collection->nonTranslated();
}
break;
case 'published':
if ($filter) {
$collection = $collection->published();
} else {
$collection = $collection->nonPublished();
}
break;
case 'visible':
if ($filter) {
$collection = $collection->visible();
} else {
$collection = $collection->nonVisible();
}
break;
case 'page':
if ($filter) {
$collection = $collection->pages();
} else {
$collection = $collection->modules();
}
break;
case 'module':
case 'modular':
if ($filter) {
$collection = $collection->modules();
} else {
$collection = $collection->pages();
}
break;
case 'routable':
if ($filter) {
$collection = $collection->routable();
} else {
$collection = $collection->nonRoutable();
}
break;
case 'type':
$collection = $collection->ofType($filter);
break;
case 'types':
$collection = $collection->ofOneOfTheseTypes($filter);
break;
case 'access':
$collection = $collection->ofOneOfTheseAccessLevels($filter);
break;
}
}
if (isset($params['dateRange'])) {
$start = $params['dateRange']['start'] ?? null;
$end = $params['dateRange']['end'] ?? null;
$field = $params['dateRange']['field'] ?? null;
$collection = $collection->dateRange($start, $end, $field);
}
if (isset($params['order'])) {
$by = $params['order']['by'] ?? 'default';
$dir = $params['order']['dir'] ?? 'asc';
$custom = $params['order']['custom'] ?? null;
$sort_flags = $params['order']['sort_flags'] ?? null;
if (is_array($sort_flags)) {
$sort_flags = array_map('constant', $sort_flags); //transform strings to constant value
$sort_flags = array_reduce($sort_flags, static function ($a, $b) {
return $a | $b;
}, 0); //merge constant values using bit or
}
$collection = $collection->order($by, $dir, $custom, $sort_flags);
}
// New Custom event to handle things like pagination.
if ($context['event']) {
$this->grav->fireEvent('onCollectionProcessed', new Event(['collection' => $collection, 'context' => $context]));
}
if ($context['pagination']) {
// Slice and dice the collection if pagination is required
$params = $collection->params();
$limit = (int)($params['limit'] ?? 0);
$page = (int)($params['page'] ?? $context['current_page'] ?? 0);
$start = (int)($params['start'] ?? 0);
$start = $limit > 0 && $page > 0 ? ($page - 1) * $limit : max(0, $start);
if ($start || ($limit && $collection->count() > $limit)) {
$collection->slice($start, $limit ?: null);
}
}
return $collection;
}
/**
* @param array|string $value
* @param PageInterface|null $self
* @return Collection
*/
protected function evaluate($value, PageInterface $self = null)
{
// Parse command.
if (is_string($value)) {
// Format: @command.param
$cmd = $value;
$params = [];
} elseif (is_array($value) && count($value) === 1 && !is_int(key($value))) {
// Format: @command.param: { attr1: value1, attr2: value2 }
$cmd = (string)key($value);
$params = (array)current($value);
} else {
$result = [];
foreach ((array)$value as $key => $val) {
if (is_int($key)) {
$result = $result + $this->evaluate($val, $self)->toArray();
} else {
$result = $result + $this->evaluate([$key => $val], $self)->toArray();
}
}
return new Collection($result);
}
$parts = explode('.', $cmd);
$scope = array_shift($parts);
$type = $parts[0] ?? null;
/** @var PageInterface|null $page */
$page = null;
switch ($scope) {
case 'self@':
case '@self':
$page = $self;
break;
case 'page@':
case '@page':
$page = isset($params[0]) ? $this->find($params[0]) : null;
break;
case 'root@':
case '@root':
$page = $this->root();
break;
case 'taxonomy@':
case '@taxonomy':
// Gets a collection of pages by using one of the following formats:
// @taxonomy.category: blog
// @taxonomy.category: [ blog, featured ]
// @taxonomy: { category: [ blog, featured ], level: 1 }
/** @var Taxonomy $taxonomy_map */
$taxonomy_map = Grav::instance()['taxonomy'];
if (!empty($parts)) {
$params = [implode('.', $parts) => $params];
}
return $taxonomy_map->findTaxonomy($params);
}
if (!$page) {
return new Collection();
}
// Handle '@page', '@page.modular: false', '@self' and '@self.modular: false'.
if (null === $type || (in_array($type, ['modular', 'modules']) && ($params[0] ?? null) === false)) {
$type = 'children';
}
switch ($type) {
case 'all':
$collection = $page->children();
break;
case 'modules':
case 'modular':
$collection = $page->children()->modules();
break;
case 'pages':
case 'children':
$collection = $page->children()->pages();
break;
case 'page':
case 'self':
$collection = !$page->root() ? (new Collection())->addPage($page) : new Collection();
break;
case 'parent':
$parent = $page->parent();
$collection = new Collection();
$collection = $parent ? $collection->addPage($parent) : $collection;
break;
case 'siblings':
$parent = $page->parent();
if ($parent) {
/** @var Collection $collection */
$collection = $parent->children();
$collection = $collection->remove($page->path());
} else {
$collection = new Collection();
}
break;
case 'descendants':
$collection = $this->all($page)->remove($page->path())->pages();
break;
default:
// Unknown type; return empty collection.
$collection = new Collection();
break;
}
return $collection;
}
/**
* Sort sub-pages in a page.
*
* @param PageInterface $page
* @param string|null $order_by
* @param string|null $order_dir
* @return array
*/
public function sort(PageInterface $page, $order_by = null, $order_dir = null, $sort_flags = null)
{
if ($order_by === null) {
$order_by = $page->orderBy();
}
if ($order_dir === null) {
$order_dir = $page->orderDir();
}
$path = $page->path();
if (null === $path) {
return [];
}
$children = $this->children[$path] ?? [];
if (!$children) {
return $children;
}
if (!isset($this->sort[$path][$order_by])) {
$this->buildSort($path, $children, $order_by, $page->orderManual(), $sort_flags);
}
$sort = $this->sort[$path][$order_by];
if ($order_dir !== 'asc') {
$sort = array_reverse($sort);
}
return $sort;
}
/**
* @param Collection $collection
* @param string $orderBy
* @param string $orderDir
* @param array|null $orderManual
* @param int|null $sort_flags
* @return array
* @internal
*/
public function sortCollection(Collection $collection, $orderBy, $orderDir = 'asc', $orderManual = null, $sort_flags = null)
{
$items = $collection->toArray();
if (!$items) {
return [];
}
$lookup = md5(json_encode($items) . json_encode($orderManual) . $orderBy . $orderDir);
if (!isset($this->sort[$lookup][$orderBy])) {
$this->buildSort($lookup, $items, $orderBy, $orderManual, $sort_flags);
}
$sort = $this->sort[$lookup][$orderBy];
if ($orderDir !== 'asc') {
$sort = array_reverse($sort);
}
return $sort;
}
/**
* Get a page instance.
*
* @param string $path The filesystem full path of the page
* @return PageInterface|null
* @throws RuntimeException
*/
public function get($path)
{
$path = (string)$path;
if ($path === '') {
return null;
}
// Check for local instances first.
if (array_key_exists($path, $this->instances)) {
return $this->instances[$path];
}
$instance = $this->index[$path] ?? null;
if (is_string($instance)) {
if ($this->directory) {
/** @var Language $language */
$language = $this->grav['language'];
$lang = $language->getActive();
if ($lang) {
$languages = $language->getFallbackLanguages($lang, true);
$key = $instance;
$instance = null;
foreach ($languages as $code) {
$test = $code ? $key . ':' . $code : $key;
if (($instance = $this->directory->getObject($test, 'flex_key')) !== null) {
break;
}
}
} else {
$instance = $this->directory->getObject($instance, 'flex_key');
}
}
if ($instance instanceof PageInterface) {
if ($this->fire_events && method_exists($instance, 'initialize')) {
$instance->initialize();
}
} else {
/** @var Debugger $debugger */
$debugger = $this->grav['debugger'];
$debugger->addMessage(sprintf('Flex page %s is missing or broken!', $instance), 'debug');
}
}
if ($instance) {
$this->instances[$path] = $instance;
}
return $instance;
}
/**
* Get children of the path.
*
* @param string $path
* @return Collection
*/
public function children($path)
{
$children = $this->children[(string)$path] ?? [];
return new Collection($children, [], $this);
}
/**
* Get a page ancestor.
*
* @param string $route The relative URL of the page
* @param string|null $path The relative path of the ancestor folder
* @return PageInterface|null
*/
public function ancestor($route, $path = null)
{
if ($path !== null) {
$page = $this->find($route, true);
if ($page && $page->path() === $path) {
return $page;
}
$parent = $page ? $page->parent() : null;
if ($parent && !$parent->root()) {
return $this->ancestor($parent->route(), $path);
}
}
return null;
}
/**
* Get a page ancestor trait.
*
* @param string $route The relative route of the page
* @param string|null $field The field name of the ancestor to query for
* @return PageInterface|null
*/
public function inherited($route, $field = null)
{
if ($field !== null) {
$page = $this->find($route, true);
$parent = $page ? $page->parent() : null;
if ($parent && $parent->value('header.' . $field) !== null) {
return $parent;
}
if ($parent && !$parent->root()) {
return $this->inherited($parent->route(), $field);
}
}
return null;
}
/**
* Find a page based on route.
*
* @param string $route The route of the page
* @param bool $all If true, return also non-routable pages, otherwise return null if page isn't routable
* @return PageInterface|null
*/
public function find($route, $all = false)
{
$route = urldecode((string)$route);
// Fetch page if there's a defined route to it.
$path = $this->routes[$route] ?? null;
$page = null !== $path ? $this->get($path) : null;
// Try without trailing slash
if (null === $page && Utils::endsWith($route, '/')) {
$path = $this->routes[rtrim($route, '/')] ?? null;
$page = null !== $path ? $this->get($path) : null;
}
if (!$all && !isset($this->grav['admin'])) {
if (null === $page || !$page->routable()) {
// If the page cannot be accessed, look for the site wide routes and wildcards.
$page = $this->findSiteBasedRoute($route) ?? $page;
}
}
return $page;
}
/**
* Check site based routes.
*
* @param string $route
* @return PageInterface|null
*/
protected function findSiteBasedRoute($route)
{
/** @var Config $config */
$config = $this->grav['config'];
$site_routes = $config->get('site.routes');
if (!is_array($site_routes)) {
return null;
}
$page = null;
// See if route matches one in the site configuration
$site_route = $site_routes[$route] ?? null;
if ($site_route) {
$page = $this->find($site_route);
} else {
// Use reverse order because of B/C (previously matched multiple and returned the last match).
foreach (array_reverse($site_routes, true) as $pattern => $replace) {
$pattern = '#^' . str_replace('/', '\/', ltrim($pattern, '^')) . '#';
try {
$found = preg_replace($pattern, $replace, $route);
if ($found && $found !== $route) {
$page = $this->find($found);
if ($page) {
return $page;
}
}
} catch (ErrorException $e) {
$this->grav['log']->error('site.routes: ' . $pattern . '-> ' . $e->getMessage());
}
}
}
return $page;
}
/**
* Dispatch URI to a page.
*
* @param string $route The relative URL of the page
* @param bool $all If true, return also non-routable pages, otherwise return null if page isn't routable
* @param bool $redirect If true, allow redirects
* @return PageInterface|null
* @throws Exception
*/
public function dispatch($route, $all = false, $redirect = true)
{
$page = $this->find($route, true);
// If we want all pages or are in admin, return what we already have.
if ($all || isset($this->grav['admin'])) {
return $page;
}
if ($page) {
$routable = $page->routable();
if ($redirect) {
if ($page->redirect()) {
// Follow a redirect page.
$this->grav->redirectLangSafe($page->redirect());
}
if (!$routable) {
/** @var Collection $children */
$children = $page->children()->visible()->routable()->published();
$child = $children->first();
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | true |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Page/Types.php | system/src/Grav/Common/Page/Types.php | <?php
/**
* @package Grav\Common\Page
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Page;
use Grav\Common\Data\Blueprint;
use Grav\Common\Filesystem\Folder;
use Grav\Common\Grav;
use Grav\Common\Utils;
use InvalidArgumentException;
use RocketTheme\Toolbox\ArrayTraits\ArrayAccess;
use RocketTheme\Toolbox\ArrayTraits\Constructor;
use RocketTheme\Toolbox\ArrayTraits\Countable;
use RocketTheme\Toolbox\ArrayTraits\Export;
use RocketTheme\Toolbox\ArrayTraits\Iterator;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use function is_string;
/**
* Class Types
* @package Grav\Common\Page
*/
class Types implements \ArrayAccess, \Iterator, \Countable
{
use ArrayAccess, Constructor, Iterator, Countable, Export;
/** @var array */
protected $items;
/** @var array */
protected $systemBlueprints = [];
/**
* @param string $type
* @param Blueprint|null $blueprint
* @return void
*/
public function register($type, $blueprint = null)
{
if (!isset($this->items[$type])) {
$this->items[$type] = [];
} elseif (null === $blueprint) {
return;
}
if (null === $blueprint) {
$blueprint = $this->systemBlueprints[$type] ?? $this->systemBlueprints['default'] ?? null;
}
if ($blueprint) {
array_unshift($this->items[$type], $blueprint);
}
}
/**
* @return void
*/
public function init()
{
if (empty($this->systemBlueprints)) {
// Register all blueprints from the blueprints stream.
$this->systemBlueprints = $this->findBlueprints('blueprints://pages');
foreach ($this->systemBlueprints as $type => $blueprint) {
$this->register($type);
}
}
}
/**
* @param string $uri
* @return void
*/
public function scanBlueprints($uri)
{
if (!is_string($uri)) {
throw new InvalidArgumentException('First parameter must be URI');
}
foreach ($this->findBlueprints($uri) as $type => $blueprint) {
$this->register($type, $blueprint);
}
}
/**
* @param string $uri
* @return void
*/
public function scanTemplates($uri)
{
if (!is_string($uri)) {
throw new InvalidArgumentException('First parameter must be URI');
}
$options = [
'compare' => 'Filename',
'pattern' => '|\.html\.twig$|',
'filters' => [
'value' => '|\.html\.twig$|'
],
'value' => 'Filename',
'recursive' => false
];
foreach (Folder::all($uri, $options) as $type) {
$this->register($type);
}
$modular_uri = rtrim($uri, '/') . '/modular';
if (is_dir($modular_uri)) {
foreach (Folder::all($modular_uri, $options) as $type) {
$this->register('modular/' . $type);
}
}
}
/**
* @return array
*/
public function pageSelect()
{
$list = [];
foreach ($this->items as $name => $file) {
if (strpos($name, '/')) {
continue;
}
$list[$name] = ucfirst(str_replace('_', ' ', $name));
}
ksort($list);
return $list;
}
/**
* @return array
*/
public function modularSelect()
{
$list = [];
foreach ($this->items as $name => $file) {
if (strpos($name, 'modular/') !== 0) {
continue;
}
$list[$name] = ucfirst(trim(str_replace('_', ' ', Utils::basename($name))));
}
ksort($list);
return $list;
}
/**
* @param string $uri
* @return array
*/
private function findBlueprints($uri)
{
$options = [
'compare' => 'Filename',
'pattern' => '|\.yaml$|',
'filters' => [
'key' => '|\.yaml$|'
],
'key' => 'SubPathName',
'value' => 'PathName',
];
/** @var UniformResourceLocator $locator */
$locator = Grav::instance()['locator'];
if ($locator->isStream($uri)) {
$options['value'] = 'Url';
}
return Folder::all($uri, $options);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Page/Header.php | system/src/Grav/Common/Page/Header.php | <?php
/**
* @package Grav\Common\Page
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Page;
use ArrayAccess;
use JsonSerializable;
use RocketTheme\Toolbox\ArrayTraits\Constructor;
use RocketTheme\Toolbox\ArrayTraits\Export;
use RocketTheme\Toolbox\ArrayTraits\ExportInterface;
use RocketTheme\Toolbox\ArrayTraits\NestedArrayAccessWithGetters;
/**
* Class Header
* @package Grav\Common\Page
*/
class Header implements ArrayAccess, ExportInterface, JsonSerializable
{
use NestedArrayAccessWithGetters, Constructor, Export;
/** @var array */
protected $items;
/**
* @return array
*/
#[\ReturnTypeWillChange]
public function jsonSerialize()
{
return $this->toArray();
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Page/Media.php | system/src/Grav/Common/Page/Media.php | <?php
/**
* @package Grav\Common\Page
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Page;
use FilesystemIterator;
use Grav\Common\Config\Config;
use Grav\Common\Grav;
use Grav\Common\Media\Interfaces\MediaObjectInterface;
use Grav\Common\Yaml;
use Grav\Common\Page\Medium\AbstractMedia;
use Grav\Common\Page\Medium\GlobalMedia;
use Grav\Common\Page\Medium\MediumFactory;
use RocketTheme\Toolbox\File\File;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use function in_array;
/**
* Class Media
* @package Grav\Common\Page
*/
class Media extends AbstractMedia
{
/** @var GlobalMedia */
protected static $global;
/** @var array */
protected $standard_exif = ['FileSize', 'MimeType', 'height', 'width'];
/**
* @param string $path
* @param array|null $media_order
* @param bool $load
*/
public function __construct($path, array $media_order = null, $load = true)
{
$this->setPath($path);
$this->media_order = $media_order;
$this->__wakeup();
if ($load) {
$this->init();
}
}
/**
* Initialize static variables on unserialize.
*/
public function __wakeup()
{
if (null === static::$global) {
// Add fallback to global media.
static::$global = GlobalMedia::getInstance();
}
}
/**
* Return raw route to the page.
*
* @return string|null Route to the page or null if media isn't for a page.
*/
public function getRawRoute(): ?string
{
$path = $this->getPath();
if ($path) {
/** @var Pages $pages */
$pages = $this->getGrav()['pages'];
$page = $pages->get($path);
if ($page) {
return $page->rawRoute();
}
}
return null;
}
/**
* Return page route.
*
* @return string|null Route to the page or null if media isn't for a page.
*/
public function getRoute(): ?string
{
$path = $this->getPath();
if ($path) {
/** @var Pages $pages */
$pages = $this->getGrav()['pages'];
$page = $pages->get($path);
if ($page) {
return $page->route();
}
}
return null;
}
/**
* @param string $offset
* @return bool
*/
#[\ReturnTypeWillChange]
public function offsetExists($offset)
{
return parent::offsetExists($offset) ?: isset(static::$global[$offset]);
}
/**
* @param string $offset
* @return MediaObjectInterface|null
*/
#[\ReturnTypeWillChange]
public function offsetGet($offset)
{
return parent::offsetGet($offset) ?: static::$global[$offset];
}
/**
* Initialize class.
*
* @return void
*/
protected function init()
{
$path = $this->getPath();
// Handle special cases where page doesn't exist in filesystem.
if (!$path || !is_dir($path)) {
return;
}
$grav = Grav::instance();
/** @var UniformResourceLocator $locator */
$locator = $grav['locator'];
/** @var Config $config */
$config = $grav['config'];
$exif_reader = isset($grav['exif']) ? $grav['exif']->getReader() : null;
$media_types = array_keys($config->get('media.types', []));
$iterator = new FilesystemIterator($path, FilesystemIterator::UNIX_PATHS | FilesystemIterator::SKIP_DOTS);
$media = [];
foreach ($iterator as $file => $info) {
// Ignore folders and Markdown files.
$filename = $info->getFilename();
if (!$info->isFile() || $info->getExtension() === 'md' || $filename === 'frontmatter.yaml' || $filename === 'media.json' || strpos($filename, '.') === 0) {
continue;
}
// Find out what type we're dealing with
[$basename, $ext, $type, $extra] = $this->getFileParts($filename);
if (!in_array(strtolower($ext), $media_types, true)) {
continue;
}
if ($type === 'alternative') {
$media["{$basename}.{$ext}"][$type][$extra] = ['file' => $file, 'size' => $info->getSize()];
} else {
$media["{$basename}.{$ext}"][$type] = ['file' => $file, 'size' => $info->getSize()];
}
}
foreach ($media as $name => $types) {
// First prepare the alternatives in case there is no base medium
if (!empty($types['alternative'])) {
/**
* @var string|int $ratio
* @var array $alt
*/
foreach ($types['alternative'] as $ratio => &$alt) {
$alt['file'] = $this->createFromFile($alt['file']);
if (empty($alt['file'])) {
unset($types['alternative'][$ratio]);
} else {
$alt['file']->set('size', $alt['size']);
}
}
unset($alt);
}
$file_path = null;
// Create the base medium
if (empty($types['base'])) {
if (!isset($types['alternative'])) {
continue;
}
$max = max(array_keys($types['alternative']));
$medium = $types['alternative'][$max]['file'];
$file_path = $medium->path();
$medium = MediumFactory::scaledFromMedium($medium, $max, 1)['file'];
} else {
$medium = $this->createFromFile($types['base']['file']);
if ($medium) {
$medium->set('size', $types['base']['size']);
$file_path = $medium->path();
}
}
if (empty($medium)) {
continue;
}
// metadata file
$meta_path = $file_path . '.meta.yaml';
if (file_exists($meta_path)) {
$types['meta']['file'] = $meta_path;
} elseif ($file_path && $exif_reader && $medium->get('mime') === 'image/jpeg' && empty($types['meta']) && $config->get('system.media.auto_metadata_exif')) {
$meta = $exif_reader->read($file_path);
if ($meta) {
$meta_data = $meta->getData();
$meta_trimmed = array_diff_key($meta_data, array_flip($this->standard_exif));
if ($meta_trimmed) {
if ($locator->isStream($meta_path)) {
$file = File::instance($locator->findResource($meta_path, true, true));
} else {
$file = File::instance($meta_path);
}
$file->save(Yaml::dump($meta_trimmed));
$types['meta']['file'] = $meta_path;
}
}
}
if (!empty($types['meta'])) {
$medium->addMetaFile($types['meta']['file']);
}
if (!empty($types['thumb'])) {
// We will not turn it into medium yet because user might never request the thumbnail
// not wasting any resources on that, maybe we should do this for medium in general?
$medium->set('thumbnails.page', $types['thumb']['file']);
}
// Build missing alternatives
if (!empty($types['alternative'])) {
$alternatives = $types['alternative'];
$max = max(array_keys($alternatives));
for ($i=$max; $i > 1; $i--) {
if (isset($alternatives[$i])) {
continue;
}
$types['alternative'][$i] = MediumFactory::scaledFromMedium($alternatives[$max]['file'], $max, $i);
}
foreach ($types['alternative'] as $altMedium) {
if ($altMedium['file'] != $medium) {
$altWidth = $altMedium['file']->get('width');
$medWidth = $medium->get('width');
if ($altWidth && $medWidth) {
$ratio = $altWidth / $medWidth;
$medium->addAlternative($ratio, $altMedium['file']);
}
}
}
}
$this->add($name, $medium);
}
}
/**
* @return string|null
* @deprecated 1.6 Use $this->getPath() instead.
*/
public function path(): ?string
{
return $this->getPath();
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Page/Markdown/Excerpts.php | system/src/Grav/Common/Page/Markdown/Excerpts.php | <?php
/**
* @package Grav\Common\Page
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Page\Markdown;
use Grav\Common\Grav;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Common\Page\Medium\Link;
use Grav\Common\Page\Pages;
use Grav\Common\Uri;
use Grav\Common\Page\Medium\Medium;
use Grav\Common\Utils;
use RocketTheme\Toolbox\Event\Event;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use function array_key_exists;
use function call_user_func_array;
use function count;
use function dirname;
use function in_array;
use function is_bool;
use function is_string;
/**
* Class Excerpts
* @package Grav\Common\Page\Markdown
*/
class Excerpts
{
/** @var PageInterface|null */
protected $page;
/** @var array */
protected $config;
/**
* Excerpts constructor.
* @param PageInterface|null $page
* @param array|null $config
*/
public function __construct(PageInterface $page = null, array $config = null)
{
$this->page = $page ?? Grav::instance()['page'] ?? null;
// Add defaults to the configuration.
if (null === $config || !isset($config['markdown'], $config['images'])) {
$c = Grav::instance()['config'];
$config = $config ?? [];
$config += [
'markdown' => $c->get('system.pages.markdown', []),
'images' => $c->get('system.images', [])
];
}
$this->config = $config;
}
/**
* @return PageInterface|null
*/
public function getPage(): ?PageInterface
{
return $this->page;
}
/**
* @return array
*/
public function getConfig(): array
{
return $this->config;
}
/**
* @param object $markdown
* @return void
*/
public function fireInitializedEvent($markdown): void
{
$grav = Grav::instance();
$grav->fireEvent('onMarkdownInitialized', new Event(['markdown' => $markdown, 'page' => $this->page]));
}
/**
* Process a Link excerpt
*
* @param array $excerpt
* @param string $type
* @return array
*/
public function processLinkExcerpt(array $excerpt, string $type = 'link'): array
{
$grav = Grav::instance();
$url = htmlspecialchars_decode(rawurldecode($excerpt['element']['attributes']['href']));
$url_parts = $this->parseUrl($url);
// If there is a query, then parse it and build action calls.
if (isset($url_parts['query'])) {
$actions = array_reduce(
explode('&', $url_parts['query']),
static function ($carry, $item) {
$parts = explode('=', $item, 2);
$value = isset($parts[1]) ? rawurldecode($parts[1]) : true;
$carry[$parts[0]] = $value;
return $carry;
},
[]
);
// Valid attributes supported.
$valid_attributes = $grav['config']->get('system.pages.markdown.valid_link_attributes') ?? [];
$skip = [];
// Unless told to not process, go through actions.
if (array_key_exists('noprocess', $actions)) {
$skip = is_bool($actions['noprocess']) ? $actions : explode(',', $actions['noprocess']);
unset($actions['noprocess']);
}
// Loop through actions for the image and call them.
foreach ($actions as $attrib => $value) {
if (!in_array($attrib, $skip)) {
$key = $attrib;
if (in_array($attrib, $valid_attributes, true)) {
// support both class and classes.
if ($attrib === 'classes') {
$attrib = 'class';
}
$excerpt['element']['attributes'][$attrib] = str_replace(',', ' ', $value);
unset($actions[$key]);
}
}
}
$url_parts['query'] = http_build_query($actions, '', '&', PHP_QUERY_RFC3986);
}
// If no query elements left, unset query.
if (empty($url_parts['query'])) {
unset($url_parts['query']);
}
// Set path to / if not set.
if (empty($url_parts['path'])) {
$url_parts['path'] = '';
}
// If scheme isn't http(s)..
if (!empty($url_parts['scheme']) && !in_array($url_parts['scheme'], ['http', 'https'])) {
// Handle custom streams.
/** @var UniformResourceLocator $locator */
$locator = $grav['locator'];
if ($type === 'link' && $locator->isStream($url)) {
$path = $locator->findResource($url, false) ?: $locator->findResource($url, false, true);
$url_parts['path'] = $grav['base_url_relative'] . '/' . $path;
unset($url_parts['stream'], $url_parts['scheme']);
}
$excerpt['element']['attributes']['href'] = Uri::buildUrl($url_parts);
return $excerpt;
}
// Handle paths and such.
$url_parts = Uri::convertUrl($this->page, $url_parts, $type);
// Build the URL from the component parts and set it on the element.
$excerpt['element']['attributes']['href'] = Uri::buildUrl($url_parts);
return $excerpt;
}
/**
* Process an image excerpt
*
* @param array $excerpt
* @return array
*/
public function processImageExcerpt(array $excerpt): array
{
$url = htmlspecialchars_decode(urldecode($excerpt['element']['attributes']['src']));
$url_parts = $this->parseUrl($url);
$media = null;
$filename = null;
if (!empty($url_parts['stream'])) {
$filename = $url_parts['scheme'] . '://' . ($url_parts['path'] ?? '');
$media = $this->page->getMedia();
} else {
$grav = Grav::instance();
/** @var Pages $pages */
$pages = $grav['pages'];
// File is also local if scheme is http(s) and host matches.
$local_file = isset($url_parts['path'])
&& (empty($url_parts['scheme']) || in_array($url_parts['scheme'], ['http', 'https'], true))
&& (empty($url_parts['host']) || $url_parts['host'] === $grav['uri']->host());
if ($local_file) {
$filename = Utils::basename($url_parts['path']);
$folder = dirname($url_parts['path']);
// Get the local path to page media if possible.
if ($this->page && $folder === $this->page->url(false, false, false)) {
// Get the media objects for this page.
$media = $this->page->getMedia();
} else {
// see if this is an external page to this one
$base_url = rtrim($grav['base_url_relative'] . $pages->base(), '/');
$page_route = '/' . ltrim(str_replace($base_url, '', $folder), '/');
$ext_page = $pages->find($page_route, true);
if ($ext_page) {
$media = $ext_page->getMedia();
} else {
$grav->fireEvent('onMediaLocate', new Event(['route' => $page_route, 'media' => &$media]));
}
}
}
}
// If there is a media file that matches the path referenced..
if ($media && $filename && isset($media[$filename])) {
// Get the medium object.
/** @var Medium $medium */
$medium = $media[$filename];
// Process operations
$medium = $this->processMediaActions($medium, $url_parts);
$element_excerpt = $excerpt['element']['attributes'];
$alt = $element_excerpt['alt'] ?? '';
$title = $element_excerpt['title'] ?? '';
$class = $element_excerpt['class'] ?? '';
$id = $element_excerpt['id'] ?? '';
$excerpt['element'] = $medium->parsedownElement($title, $alt, $class, $id, true);
} else {
// Not a current page media file, see if it needs converting to relative.
$excerpt['element']['attributes']['src'] = Uri::buildUrl($url_parts);
}
return $excerpt;
}
/**
* Process media actions
*
* @param Medium $medium
* @param string|array $url
* @return Medium|Link
*/
public function processMediaActions($medium, $url)
{
$url_parts = is_string($url) ? $this->parseUrl($url) : $url;
$actions = [];
// if there is a query, then parse it and build action calls
if (isset($url_parts['query'])) {
$actions = array_reduce(
explode('&', $url_parts['query']),
static function ($carry, $item) {
$parts = explode('=', $item, 2);
$value = $parts[1] ?? null;
$carry[] = ['method' => $parts[0], 'params' => $value];
return $carry;
},
[]
);
}
$defaults = $this->config['images']['defaults'] ?? [];
if (count($defaults)) {
foreach ($defaults as $method => $params) {
if (array_search($method, array_column($actions, 'method')) === false) {
$actions[] = [
'method' => $method,
'params' => $params,
];
}
}
}
// loop through actions for the image and call them
foreach ($actions as $action) {
$matches = [];
if (preg_match('/\[(.*)\]/', $action['params'], $matches)) {
$args = [explode(',', $matches[1])];
} else {
$args = explode(',', $action['params']);
}
$medium = call_user_func_array([$medium, $action['method']], $args);
}
if (isset($url_parts['fragment'])) {
$medium->urlHash($url_parts['fragment']);
}
return $medium;
}
/**
* Variation of parse_url() which works also with local streams.
*
* @param string $url
* @return array
*/
protected function parseUrl(string $url)
{
$url_parts = Utils::multibyteParseUrl($url);
if (isset($url_parts['scheme'])) {
/** @var UniformResourceLocator $locator */
$locator = Grav::instance()['locator'];
// Special handling for the streams.
if ($locator->schemeExists($url_parts['scheme'])) {
if (isset($url_parts['host'])) {
// Merge host and path into a path.
$url_parts['path'] = $url_parts['host'] . (isset($url_parts['path']) ? '/' . $url_parts['path'] : '');
unset($url_parts['host']);
}
$url_parts['stream'] = true;
}
}
return $url_parts;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Page/Medium/Link.php | system/src/Grav/Common/Page/Medium/Link.php | <?php
/**
* @package Grav\Common\Page
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Page\Medium;
use BadMethodCallException;
use Grav\Common\Media\Interfaces\MediaLinkInterface;
use Grav\Common\Media\Interfaces\MediaObjectInterface;
use RuntimeException;
use function call_user_func_array;
use function get_class;
use function is_array;
use function is_callable;
/**
* Class Link
* @package Grav\Common\Page\Medium
*/
class Link implements RenderableInterface, MediaLinkInterface
{
use ParsedownHtmlTrait;
/** @var array */
protected $attributes = [];
/** @var MediaObjectInterface|MediaLinkInterface */
protected $source;
/**
* Construct.
* @param array $attributes
* @param MediaObjectInterface $medium
*/
public function __construct(array $attributes, MediaObjectInterface $medium)
{
$this->attributes = $attributes;
$source = $medium->reset()->thumbnail('auto')->display('thumbnail');
if (!$source instanceof MediaObjectInterface) {
throw new RuntimeException('Media has no thumbnail set');
}
$source->set('linked', true);
$this->source = $source;
}
/**
* Get an element (is array) that can be rendered by the Parsedown engine
*
* @param string|null $title
* @param string|null $alt
* @param string|null $class
* @param string|null $id
* @param bool $reset
* @return array
*/
public function parsedownElement($title = null, $alt = null, $class = null, $id = null, $reset = true)
{
$innerElement = $this->source->parsedownElement($title, $alt, $class, $id, $reset);
return [
'name' => 'a',
'attributes' => $this->attributes,
'handler' => is_array($innerElement) ? 'element' : 'line',
'text' => $innerElement
];
}
/**
* Forward the call to the source element
*
* @param string $method
* @param mixed $args
* @return mixed
*/
#[\ReturnTypeWillChange]
public function __call($method, $args)
{
$object = $this->source;
$callable = [$object, $method];
if (!is_callable($callable)) {
throw new BadMethodCallException(get_class($object) . '::' . $method . '() not found.');
}
$object = call_user_func_array($callable, $args);
if (!$object instanceof MediaLinkInterface) {
// Don't start nesting links, if user has multiple link calls in his
// actions, we will drop the previous links.
return $this;
}
$this->source = $object;
return $object;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Page/Medium/AudioMedium.php | system/src/Grav/Common/Page/Medium/AudioMedium.php | <?php
/**
* @package Grav\Common\Page
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Page\Medium;
use Grav\Common\Media\Interfaces\AudioMediaInterface;
use Grav\Common\Media\Traits\AudioMediaTrait;
/**
* Class AudioMedium
* @package Grav\Common\Page\Medium
*/
class AudioMedium extends Medium implements AudioMediaInterface
{
use AudioMediaTrait;
/**
* Reset medium.
*
* @return $this
*/
public function reset()
{
parent::reset();
$this->resetPlayer();
return $this;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Page/Medium/VideoMedium.php | system/src/Grav/Common/Page/Medium/VideoMedium.php | <?php
/**
* @package Grav\Common\Page
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Page\Medium;
use Grav\Common\Media\Interfaces\VideoMediaInterface;
use Grav\Common\Media\Traits\VideoMediaTrait;
/**
* Class VideoMedium
* @package Grav\Common\Page\Medium
*/
class VideoMedium extends Medium implements VideoMediaInterface
{
use VideoMediaTrait;
/**
* Reset medium.
*
* @return $this
*/
public function reset()
{
parent::reset();
$this->resetPlayer();
return $this;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Page/Medium/StaticResizeTrait.php | system/src/Grav/Common/Page/Medium/StaticResizeTrait.php | <?php
/**
* @package Grav\Common\Page
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Page\Medium;
use Grav\Common\Media\Traits\StaticResizeTrait as NewResizeTrait;
user_error('Grav\Common\Page\Medium\StaticResizeTrait is deprecated since Grav 1.7, use Grav\Common\Media\Traits\StaticResizeTrait instead', E_USER_DEPRECATED);
/**
* Trait StaticResizeTrait
* @package Grav\Common\Page\Medium
* @deprecated 1.7 Use `Grav\Common\Media\Traits\StaticResizeTrait` instead
*/
trait StaticResizeTrait
{
use NewResizeTrait;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Page/Medium/RenderableInterface.php | system/src/Grav/Common/Page/Medium/RenderableInterface.php | <?php
/**
* @package Grav\Common\Page
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Page\Medium;
/**
* Interface RenderableInterface
* @package Grav\Common\Page\Medium
*/
interface RenderableInterface
{
/**
* Return HTML markup from the medium.
*
* @param string|null $title
* @param string|null $alt
* @param string|null $class
* @param string|null $id
* @param bool $reset
* @return string
*/
public function html($title = null, $alt = null, $class = null, $id = null, $reset = true);
/**
* Return Parsedown Element from the medium.
*
* @param string|null $title
* @param string|null $alt
* @param string|null $class
* @param string|null $id
* @param bool $reset
* @return array
*/
public function parsedownElement($title = null, $alt = null, $class = null, $id = null, $reset = true);
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Page/Medium/AbstractMedia.php | system/src/Grav/Common/Page/Medium/AbstractMedia.php | <?php
/**
* @package Grav\Common\Page
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Page\Medium;
use Grav\Common\Config\Config;
use Grav\Common\Data\Blueprint;
use Grav\Common\Grav;
use Grav\Common\Language\Language;
use Grav\Common\Media\Interfaces\MediaCollectionInterface;
use Grav\Common\Media\Interfaces\MediaObjectInterface;
use Grav\Common\Media\Interfaces\MediaUploadInterface;
use Grav\Common\Media\Traits\MediaUploadTrait;
use Grav\Common\Page\Pages;
use Grav\Common\Utils;
use RocketTheme\Toolbox\ArrayTraits\ArrayAccess;
use RocketTheme\Toolbox\ArrayTraits\Countable;
use RocketTheme\Toolbox\ArrayTraits\Export;
use RocketTheme\Toolbox\ArrayTraits\ExportInterface;
use RocketTheme\Toolbox\ArrayTraits\Iterator;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use function is_array;
/**
* Class AbstractMedia
* @package Grav\Common\Page\Medium
*/
abstract class AbstractMedia implements ExportInterface, MediaCollectionInterface, MediaUploadInterface
{
use ArrayAccess;
use Countable;
use Iterator;
use Export;
use MediaUploadTrait;
/** @var array */
protected $items = [];
/** @var string|null */
protected $path;
/** @var array */
protected $images = [];
/** @var array */
protected $videos = [];
/** @var array */
protected $audios = [];
/** @var array */
protected $files = [];
/** @var array|null */
protected $media_order;
/**
* Return media path.
*
* @return string|null
*/
public function getPath(): ?string
{
return $this->path;
}
/**
* @param string|null $path
* @return void
*/
public function setPath(?string $path): void
{
$this->path = $path;
}
/**
* Get medium by filename.
*
* @param string $filename
* @return MediaObjectInterface|null
*/
public function get($filename)
{
return $this->offsetGet($filename);
}
/**
* Call object as function to get medium by filename.
*
* @param string $filename
* @return mixed
*/
#[\ReturnTypeWillChange]
public function __invoke($filename)
{
return $this->offsetGet($filename);
}
/**
* Set file modification timestamps (query params) for all the media files.
*
* @param string|int|null $timestamp
* @return $this
*/
public function setTimestamps($timestamp = null)
{
foreach ($this->items as $instance) {
$instance->setTimestamp($timestamp);
}
return $this;
}
/**
* Get a list of all media.
*
* @return MediaObjectInterface[]
*/
public function all()
{
$this->items = $this->orderMedia($this->items);
return $this->items;
}
/**
* Get a list of all image media.
*
* @return MediaObjectInterface[]
*/
public function images()
{
$this->images = $this->orderMedia($this->images);
return $this->images;
}
/**
* Get a list of all video media.
*
* @return MediaObjectInterface[]
*/
public function videos()
{
$this->videos = $this->orderMedia($this->videos);
return $this->videos;
}
/**
* Get a list of all audio media.
*
* @return MediaObjectInterface[]
*/
public function audios()
{
$this->audios = $this->orderMedia($this->audios);
return $this->audios;
}
/**
* Get a list of all file media.
*
* @return MediaObjectInterface[]
*/
public function files()
{
$this->files = $this->orderMedia($this->files);
return $this->files;
}
/**
* @param string $name
* @param MediaObjectInterface|null $file
* @return void
*/
public function add($name, $file)
{
if (null === $file) {
return;
}
$this->offsetSet($name, $file);
switch ($file->type) {
case 'image':
$this->images[$name] = $file;
break;
case 'video':
$this->videos[$name] = $file;
break;
case 'audio':
$this->audios[$name] = $file;
break;
default:
$this->files[$name] = $file;
}
}
/**
* @param string $name
* @return void
*/
public function hide($name)
{
$this->offsetUnset($name);
unset($this->images[$name], $this->videos[$name], $this->audios[$name], $this->files[$name]);
}
/**
* Create Medium from a file.
*
* @param string $file
* @param array $params
* @return Medium|null
*/
public function createFromFile($file, array $params = [])
{
return MediumFactory::fromFile($file, $params);
}
/**
* Create Medium from array of parameters
*
* @param array $items
* @param Blueprint|null $blueprint
* @return Medium|null
*/
public function createFromArray(array $items = [], Blueprint $blueprint = null)
{
return MediumFactory::fromArray($items, $blueprint);
}
/**
* @param MediaObjectInterface $mediaObject
* @return ImageFile
*/
public function getImageFileObject(MediaObjectInterface $mediaObject): ImageFile
{
return ImageFile::open($mediaObject->get('filepath'));
}
/**
* Order the media based on the page's media_order
*
* @param array $media
* @return array
*/
protected function orderMedia($media)
{
if (null === $this->media_order) {
$path = $this->getPath();
if (null !== $path) {
/** @var Pages $pages */
$pages = Grav::instance()['pages'];
$page = $pages->get($path);
if ($page && isset($page->header()->media_order)) {
$this->media_order = array_map('trim', explode(',', $page->header()->media_order));
}
}
}
if (!empty($this->media_order) && is_array($this->media_order)) {
$media = Utils::sortArrayByArray($media, $this->media_order);
} else {
ksort($media, SORT_NATURAL | SORT_FLAG_CASE);
}
return $media;
}
protected function fileExists(string $filename, string $destination): bool
{
return file_exists("{$destination}/{$filename}");
}
/**
* Get filename, extension and meta part.
*
* @param string $filename
* @return array
*/
protected function getFileParts($filename)
{
if (preg_match('/(.*)@(\d+)x\.(.*)$/', $filename, $matches)) {
$name = $matches[1];
$extension = $matches[3];
$extra = (int) $matches[2];
$type = 'alternative';
if ($extra === 1) {
$type = 'base';
$extra = null;
}
} else {
$fileParts = explode('.', $filename);
$name = array_shift($fileParts);
$extension = null;
$extra = null;
$type = 'base';
while (($part = array_shift($fileParts)) !== null) {
if ($part !== 'meta' && $part !== 'thumb') {
if (null !== $extension) {
$name .= '.' . $extension;
}
$extension = $part;
} else {
$type = $part;
$extra = '.' . $part . '.' . implode('.', $fileParts);
break;
}
}
}
return [$name, $extension, $type, $extra];
}
protected function getGrav(): Grav
{
return Grav::instance();
}
protected function getConfig(): Config
{
return $this->getGrav()['config'];
}
protected function getLanguage(): Language
{
return $this->getGrav()['language'];
}
protected function clearCache(): void
{
/** @var UniformResourceLocator $locator */
$locator = $this->getGrav()['locator'];
$locator->clearCache();
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Page/Medium/ImageMedium.php | system/src/Grav/Common/Page/Medium/ImageMedium.php | <?php
/**
* @package Grav\Common\Page
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Page\Medium;
use BadFunctionCallException;
use Grav\Common\Data\Blueprint;
use Grav\Common\Media\Interfaces\ImageManipulateInterface;
use Grav\Common\Media\Interfaces\ImageMediaInterface;
use Grav\Common\Media\Interfaces\MediaLinkInterface;
use Grav\Common\Media\Traits\ImageLoadingTrait;
use Grav\Common\Media\Traits\ImageDecodingTrait;
use Grav\Common\Media\Traits\ImageFetchPriorityTrait;
use Grav\Common\Media\Traits\ImageMediaTrait;
use Grav\Common\Utils;
use Gregwar\Image\Image;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use function func_get_args;
use function in_array;
/**
* Class ImageMedium
* @package Grav\Common\Page\Medium
*/
class ImageMedium extends Medium implements ImageMediaInterface, ImageManipulateInterface
{
use ImageMediaTrait;
use ImageLoadingTrait;
use ImageDecodingTrait;
use ImageFetchPriorityTrait;
/**
* @var mixed|string
*/
private $saved_image_path;
/**
* Construct.
*
* @param array $items
* @param Blueprint|null $blueprint
*/
public function __construct($items = [], Blueprint $blueprint = null)
{
parent::__construct($items, $blueprint);
$config = $this->getGrav()['config'];
$this->thumbnailTypes = ['page', 'media', 'default'];
$this->default_quality = $config->get('system.images.default_image_quality', 85);
$this->def('debug', $config->get('system.images.debug'));
$path = $this->get('filepath');
if (!$path || !file_exists($path) || !filesize($path)) {
return;
}
$this->set('thumbnails.media', $path);
if (!($this->offsetExists('width') && $this->offsetExists('height') && $this->offsetExists('mime'))) {
$image_info = getimagesize($path);
if ($image_info) {
$this->def('width', (int) $image_info[0]);
$this->def('height', (int) $image_info[1]);
$this->def('mime', $image_info['mime']);
}
}
$this->reset();
if ($config->get('system.images.cache_all', false)) {
$this->cache();
}
}
/**
* @return array
*/
public function getMeta(): array
{
return [
'width' => $this->width,
'height' => $this->height,
] + parent::getMeta();
}
/**
* Also unset the image on destruct.
*/
#[\ReturnTypeWillChange]
public function __destruct()
{
unset($this->image);
}
/**
* Also clone image.
*/
#[\ReturnTypeWillChange]
public function __clone()
{
if ($this->image) {
$this->image = clone $this->image;
}
parent::__clone();
}
/**
* Reset image.
*
* @return $this
*/
public function reset()
{
parent::reset();
if ($this->image) {
$this->image();
$this->medium_querystring = [];
$this->filter();
$this->clearAlternatives();
}
$this->format = 'guess';
$this->quality = $this->default_quality;
$this->debug_watermarked = false;
$config = $this->getGrav()['config'];
// Set CLS configuration
$this->auto_sizes = $config->get('system.images.cls.auto_sizes', false);
$this->aspect_ratio = $config->get('system.images.cls.aspect_ratio', false);
$this->retina_scale = $config->get('system.images.cls.retina_scale', 1);
return $this;
}
/**
* Add meta file for the medium.
*
* @param string $filepath
* @return $this
*/
public function addMetaFile($filepath)
{
parent::addMetaFile($filepath);
// Apply filters in meta file
$this->reset();
return $this;
}
/**
* Return PATH to image.
*
* @param bool $reset
* @return string path to image
*/
public function path($reset = true)
{
$output = $this->saveImage();
if ($reset) {
$this->reset();
}
return $output;
}
/**
* Return URL to image.
*
* @param bool $reset
* @return string
*/
public function url($reset = true)
{
$grav = $this->getGrav();
/** @var UniformResourceLocator $locator */
$locator = $grav['locator'];
$image_path = (string)($locator->findResource('cache://images', true) ?: $locator->findResource('cache://images', true, true));
$saved_image_path = $this->saved_image_path = $this->saveImage();
$output = preg_replace('|^' . preg_quote(GRAV_ROOT, '|') . '|', '', $saved_image_path) ?: $saved_image_path;
if ($locator->isStream($output)) {
$output = (string)($locator->findResource($output, false) ?: $locator->findResource($output, false, true));
}
if (Utils::startsWith($output, $image_path)) {
$image_dir = $locator->findResource('cache://images', false);
$output = '/' . $image_dir . preg_replace('|^' . preg_quote($image_path, '|') . '|', '', $output);
}
if ($reset) {
$this->reset();
}
return trim($grav['base_url'] . '/' . $this->urlQuerystring($output), '\\');
}
/**
* Return srcset string for this Medium and its alternatives.
*
* @param bool $reset
* @return string
*/
public function srcset($reset = true)
{
if (empty($this->alternatives)) {
if ($reset) {
$this->reset();
}
return '';
}
$srcset = [];
foreach ($this->alternatives as $ratio => $medium) {
$srcset[] = $medium->url($reset) . ' ' . $medium->get('width') . 'w';
}
$srcset[] = str_replace(' ', '%20', $this->url($reset)) . ' ' . $this->get('width') . 'w';
return implode(', ', $srcset);
}
/**
* Parsedown element for source display mode
*
* @param array $attributes
* @param bool $reset
* @return array
*/
public function sourceParsedownElement(array $attributes, $reset = true)
{
empty($attributes['src']) && $attributes['src'] = $this->url(false);
$srcset = $this->srcset($reset);
if ($srcset) {
empty($attributes['srcset']) && $attributes['srcset'] = $srcset;
$attributes['sizes'] = $this->sizes();
}
if ($this->saved_image_path && $this->auto_sizes) {
if (!array_key_exists('height', $this->attributes) && !array_key_exists('width', $this->attributes)) {
$info = getimagesize($this->saved_image_path);
$width = (int)$info[0];
$height = (int)$info[1];
$scaling_factor = $this->retina_scale > 0 ? $this->retina_scale : 1;
$attributes['width'] = (int)($width / $scaling_factor);
$attributes['height'] = (int)($height / $scaling_factor);
if ($this->aspect_ratio) {
$style = ($attributes['style'] ?? ' ') . "--aspect-ratio: $width/$height;";
$attributes['style'] = trim($style);
}
}
}
return ['name' => 'img', 'attributes' => $attributes];
}
/**
* Turn the current Medium into a Link
*
* @param bool $reset
* @param array $attributes
* @return MediaLinkInterface
*/
public function link($reset = true, array $attributes = [])
{
$attributes['href'] = $this->url(false);
$srcset = $this->srcset(false);
if ($srcset) {
$attributes['data-srcset'] = $srcset;
}
return parent::link($reset, $attributes);
}
/**
* Turn the current Medium into a Link with lightbox enabled
*
* @param int $width
* @param int $height
* @param bool $reset
* @return MediaLinkInterface
*/
public function lightbox($width = null, $height = null, $reset = true)
{
if ($this->mode !== 'source') {
$this->display('source');
}
if ($width && $height) {
$this->__call('cropResize', [(int) $width, (int) $height]);
}
return parent::lightbox($width, $height, $reset);
}
/**
* @param string $enabled
* @return $this
*/
public function autoSizes($enabled = 'true')
{
$this->auto_sizes = $enabled === 'true' ?: false;
return $this;
}
/**
* @param string $enabled
* @return $this
*/
public function aspectRatio($enabled = 'true')
{
$this->aspect_ratio = $enabled === 'true' ?: false;
return $this;
}
/**
* @param int $scale
* @return $this
*/
public function retinaScale($scale = 1)
{
$this->retina_scale = (int)$scale;
return $this;
}
/**
* @param string|null $image
* @param string|null $position
* @param int|float|null $scale
* @return $this
*/
public function watermark($image = null, $position = null, $scale = null)
{
$grav = $this->getGrav();
$locator = $grav['locator'];
$config = $grav['config'];
$args = func_get_args();
$file = $args[0] ?? '1'; // using '1' because of markdown. doing  returns $args[0]='1';
$file = $file === '1' ? $config->get('system.images.watermark.image') : $args[0];
$watermark = $locator->findResource($file);
$watermark = ImageFile::open($watermark);
// Scaling operations
$scale = ($scale ?? $config->get('system.images.watermark.scale', 100)) / 100;
$wwidth = (int) ($this->get('width') * $scale);
$wheight = (int) ($this->get('height') * $scale);
$watermark->resize($wwidth, $wheight);
// Position operations
$position = !empty($args[1]) ? explode('-', $args[1]) : ['center', 'center']; // todo change to config
$positionY = $position[0] ?? $config->get('system.images.watermark.position_y', 'center');
$positionX = $position[1] ?? $config->get('system.images.watermark.position_x', 'center');
switch ($positionY)
{
case 'top':
$positionY = 0;
break;
case 'bottom':
$positionY = (int)$this->get('height')-$wheight;
break;
case 'center':
$positionY = ((int)$this->get('height')/2) - ($wheight/2);
break;
}
switch ($positionX)
{
case 'left':
$positionX = 0;
break;
case 'right':
$positionX = (int) ($this->get('width')-$wwidth);
break;
case 'center':
$positionX = (int) (($this->get('width')/2) - ($wwidth/2));
break;
}
$this->__call('merge', [$watermark,$positionX, $positionY]);
return $this;
}
/**
* Handle this commonly used variant
*
* @return $this
*/
public function cropZoom()
{
$this->__call('zoomCrop', func_get_args());
return $this;
}
/**
* Add a frame to image
*
* @return $this
*/
public function addFrame(int $border = 10, string $color = '0x000000')
{
if($border > 0 && preg_match('/^0x[a-f0-9]{6}$/i', $color)) { // $border must be an integer and bigger than 0; $color must be formatted as an HEX value (0x??????).
$image = ImageFile::open($this->path());
}
else {
return $this;
}
$dst_width = (int) ($image->width()+2*$border);
$dst_height = (int) ($image->height()+2*$border);
$frame = ImageFile::create($dst_width, $dst_height);
$frame->__call('fill', [$color]);
$this->image = $frame;
$this->__call('merge', [$image, $border, $border]);
$this->saveImage();
return $this;
}
/**
* Forward the call to the image processing method.
*
* @param string $method
* @param mixed $args
* @return $this|mixed
*/
#[\ReturnTypeWillChange]
public function __call($method, $args)
{
if (!in_array($method, static::$magic_actions, true)) {
return parent::__call($method, $args);
}
// Always initialize image.
if (!$this->image) {
$this->image();
}
try {
$this->image->{$method}(...$args);
/** @var ImageMediaInterface $medium */
foreach ($this->alternatives as $medium) {
$args_copy = $args;
// regular image: resize 400x400 -> 200x200
// --> @2x: resize 800x800->400x400
if (isset(static::$magic_resize_actions[$method])) {
foreach (static::$magic_resize_actions[$method] as $param) {
if (isset($args_copy[$param])) {
$args_copy[$param] *= $medium->get('ratio');
}
}
}
// Do the same call for alternative media.
$medium->__call($method, $args_copy);
}
} catch (BadFunctionCallException $e) {
}
return $this;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Page/Medium/ThumbnailImageMedium.php | system/src/Grav/Common/Page/Medium/ThumbnailImageMedium.php | <?php
/**
* @package Grav\Common\Page
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Page\Medium;
use Grav\Common\Media\Traits\ThumbnailMediaTrait;
/**
* Class ThumbnailImageMedium
* @package Grav\Common\Page\Medium
*/
class ThumbnailImageMedium extends ImageMedium
{
use ThumbnailMediaTrait;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Page/Medium/ImageFile.php | system/src/Grav/Common/Page/Medium/ImageFile.php | <?php
/**
* @package Grav\Common\Page
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Page\Medium;
use Exception;
use Grav\Common\Config\Config;
use Grav\Common\Grav;
use Gregwar\Image\Exceptions\GenerationError;
use Gregwar\Image\Image;
use Gregwar\Image\Source;
use RocketTheme\Toolbox\Event\Event;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use RuntimeException;
use function array_key_exists;
use function count;
use function extension_loaded;
use function in_array;
/**
* Class ImageFile
* @package Grav\Common\Page\Medium
*
* @method Image applyExifOrientation($exif_orienation)
*/
class ImageFile extends Image
{
/**
* Image constructor with adapter configuration from Grav.
*
* @param string|null $originalFile
* @param int|null $width
* @param int|null $height
*/
public function __construct($originalFile = null, $width = null, $height = null)
{
parent::__construct($originalFile, $width, $height);
// Set the adapter based on Grav configuration
$grav = Grav::instance();
$adapter = $grav['config']->get('system.images.adapter', 'gd');
try {
$this->setAdapter($adapter);
} catch (Exception $e) {
$grav['log']->error(
'Image adapter "' . $adapter . '" is not available. Falling back to GD adapter.'
);
}
}
/**
* Destruct also image object.
*/
#[\ReturnTypeWillChange]
public function __destruct()
{
$adapter = $this->adapter;
if ($adapter) {
$adapter->deinit();
}
}
/**
* Clear previously applied operations
*
* @return void
*/
public function clearOperations()
{
$this->operations = [];
}
/**
* This is the same as the Gregwar Image class except this one fires a Grav Event on creation of new cached file
*
* @param string $type the image type
* @param int $quality the quality (for JPEG)
* @param bool $actual
* @param array $extras
* @return string
*/
public function cacheFile($type = 'jpg', $quality = 80, $actual = false, $extras = [])
{
if ($type === 'guess') {
$type = $this->guessType();
}
if (!$this->forceCache && !count($this->operations) && $type === $this->guessType()) {
return $this->getFilename($this->getFilePath());
}
// Computes the hash
$this->hash = $this->getHash($type, $quality, $extras);
/** @var Config $config */
$config = Grav::instance()['config'];
// Seo friendly image names
$seofriendly = $config->get('system.images.seofriendly', false);
if ($seofriendly) {
$mini_hash = substr($this->hash, 0, 4) . substr($this->hash, -4);
$cacheFile = "{$this->prettyName}-{$mini_hash}";
} else {
$cacheFile = "{$this->hash}-{$this->prettyName}";
}
$cacheFile .= '.' . $type;
// If the files does not exists, save it
$image = $this;
// Target file should be younger than all the current image
// dependencies
$conditions = array(
'younger-than' => $this->getDependencies()
);
// The generating function
$generate = function ($target) use ($image, $type, $quality) {
$result = $image->save($target, $type, $quality);
if ($result !== $target) {
throw new GenerationError($result);
}
Grav::instance()->fireEvent('onImageMediumSaved', new Event(['image' => $target]));
};
// Asking the cache for the cacheFile
try {
$perms = $config->get('system.images.cache_perms', '0755');
$perms = octdec($perms);
$file = $this->getCacheSystem()->setDirectoryMode($perms)->getOrCreateFile($cacheFile, $conditions, $generate, $actual);
} catch (GenerationError $e) {
$file = $e->getNewFile();
}
// Nulling the resource
$adapter = $this->getAdapter();
$adapter->setSource(new Source\File($file));
$adapter->deinit();
if ($actual) {
return $file;
}
return $this->getFilename($file);
}
/**
* Gets the hash.
*
* @param string $type
* @param int $quality
* @param array $extras
* @return string
*/
public function getHash($type = 'guess', $quality = 80, $extras = [])
{
if (null === $this->hash) {
$this->generateHash($type, $quality, $extras);
}
return $this->hash;
}
/**
* Generates the hash.
*
* @param string $type
* @param int $quality
* @param array $extras
*/
public function generateHash($type = 'guess', $quality = 80, $extras = [])
{
$inputInfos = $this->source->getInfos();
$data = [
$inputInfos,
$this->serializeOperations(),
$type,
$quality,
$extras
];
$this->hash = sha1(serialize($data));
}
/**
* Read exif rotation from file and apply it.
*/
public function fixOrientation()
{
if (!extension_loaded('exif')) {
throw new RuntimeException('You need to EXIF PHP Extension to use this function');
}
if (!file_exists($this->source->getInfos()) || !in_array(exif_imagetype($this->source->getInfos()), [IMAGETYPE_JPEG, IMAGETYPE_TIFF_II, IMAGETYPE_TIFF_MM], true)) {
return $this;
}
// resolve any streams
/** @var UniformResourceLocator $locator */
$locator = Grav::instance()['locator'];
$filepath = $this->source->getInfos();
if ($locator->isStream($filepath)) {
$filepath = $locator->findResource($this->source->getInfos(), true, true);
}
// Make sure file exists
if (!file_exists($filepath)) {
return $this;
}
try {
$exif = @exif_read_data($filepath);
} catch (Exception $e) {
Grav::instance()['log']->error($filepath . ' - ' . $e->getMessage());
return $this;
}
if ($exif === false || !array_key_exists('Orientation', $exif)) {
return $this;
}
return $this->applyExifOrientation($exif['Orientation']);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Page/Medium/GlobalMedia.php | system/src/Grav/Common/Page/Medium/GlobalMedia.php | <?php
/**
* @package Grav\Common\Page
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Page\Medium;
use Grav\Common\Grav;
use Grav\Common\Media\Interfaces\MediaObjectInterface;
use Grav\Common\Utils;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use function dirname;
/**
* Class GlobalMedia
* @package Grav\Common\Page\Medium
*/
class GlobalMedia extends AbstractMedia
{
/** @var self */
protected static $instance;
public static function getInstance(): self
{
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Return media path.
*
* @return string|null
*/
public function getPath(): ?string
{
return null;
}
/**
* @param string $offset
* @return bool
*/
#[\ReturnTypeWillChange]
public function offsetExists($offset)
{
return parent::offsetExists($offset) ?: !empty($this->resolveStream($offset));
}
/**
* @param string $offset
* @return MediaObjectInterface|null
*/
#[\ReturnTypeWillChange]
public function offsetGet($offset)
{
return parent::offsetGet($offset) ?: $this->addMedium($offset);
}
/**
* @param string $filename
* @return string|null
*/
protected function resolveStream($filename)
{
/** @var UniformResourceLocator $locator */
$locator = Grav::instance()['locator'];
if (!$locator->isStream($filename)) {
return null;
}
return $locator->findResource($filename) ?: null;
}
/**
* @param string $stream
* @return MediaObjectInterface|null
*/
protected function addMedium($stream)
{
$filename = $this->resolveStream($stream);
if (!$filename) {
return null;
}
$path = dirname($filename);
[$basename, $ext,, $extra] = $this->getFileParts(Utils::basename($filename));
$medium = MediumFactory::fromFile($filename);
if (null === $medium) {
return null;
}
$medium->set('size', filesize($filename));
$scale = (int) ($extra ?: 1);
if ($scale !== 1) {
$altMedium = $medium;
// Create scaled down regular sized image.
$medium = MediumFactory::scaledFromMedium($altMedium, $scale, 1)['file'];
if (empty($medium)) {
return null;
}
// Add original sized image as alternative.
$medium->addAlternative($scale, $altMedium['file']);
// Locate or generate smaller retina images.
for ($i = $scale-1; $i > 1; $i--) {
$altFilename = "{$path}/{$basename}@{$i}x.{$ext}";
if (file_exists($altFilename)) {
$scaled = MediumFactory::fromFile($altFilename);
} else {
$scaled = MediumFactory::scaledFromMedium($altMedium, $scale, $i)['file'];
}
if ($scaled) {
$medium->addAlternative($i, $scaled);
}
}
}
$meta = "{$path}/{$basename}.{$ext}.yaml";
if (file_exists($meta)) {
$medium->addMetaFile($meta);
}
$meta = "{$path}/{$basename}.{$ext}.meta.yaml";
if (file_exists($meta)) {
$medium->addMetaFile($meta);
}
$thumb = "{$path}/{$basename}.thumb.{$ext}";
if (file_exists($thumb)) {
$medium->set('thumbnails.page', $thumb);
}
$this->add($stream, $medium);
return $medium;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Page/Medium/MediumFactory.php | system/src/Grav/Common/Page/Medium/MediumFactory.php | <?php
/**
* @package Grav\Common\Page
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Page\Medium;
use Grav\Common\Grav;
use Grav\Common\Data\Blueprint;
use Grav\Common\Media\Interfaces\ImageMediaInterface;
use Grav\Common\Media\Interfaces\MediaObjectInterface;
use Grav\Common\Utils;
use Grav\Framework\Form\FormFlashFile;
use Psr\Http\Message\UploadedFileInterface;
use function dirname;
use function is_array;
/**
* Class MediumFactory
* @package Grav\Common\Page\Medium
*/
class MediumFactory
{
/**
* Create Medium from a file
*
* @param string $file
* @param array $params
* @return Medium|null
*/
public static function fromFile($file, array $params = [])
{
if (!file_exists($file)) {
return null;
}
$parts = Utils::pathinfo($file);
$path = $parts['dirname'];
$filename = $parts['basename'];
$ext = $parts['extension'] ?? '';
$basename = $parts['filename'];
$config = Grav::instance()['config'];
$media_params = $ext ? $config->get('media.types.' . strtolower($ext)) : null;
if (!is_array($media_params)) {
return null;
}
// Remove empty 'image' attribute
if (isset($media_params['image']) && empty($media_params['image'])) {
unset($media_params['image']);
}
$params += $media_params;
// Add default settings for undefined variables.
$params += (array)$config->get('media.types.defaults');
$params += [
'type' => 'file',
'thumb' => 'media/thumb.png',
'mime' => 'application/octet-stream',
'filepath' => $file,
'filename' => $filename,
'basename' => $basename,
'extension' => $ext,
'path' => $path,
'modified' => filemtime($file),
'thumbnails' => []
];
$locator = Grav::instance()['locator'];
$file = $locator->findResource("image://{$params['thumb']}");
if ($file) {
$params['thumbnails']['default'] = $file;
}
return static::fromArray($params);
}
/**
* Create Medium from an uploaded file
*
* @param UploadedFileInterface $uploadedFile
* @param array $params
* @return Medium|null
*/
public static function fromUploadedFile(UploadedFileInterface $uploadedFile, array $params = [])
{
// For now support only FormFlashFiles, which exist over multiple requests. Also ignore errored and moved media.
if (!$uploadedFile instanceof FormFlashFile || $uploadedFile->getError() !== \UPLOAD_ERR_OK || $uploadedFile->isMoved()) {
return null;
}
$clientName = $uploadedFile->getClientFilename();
if (!$clientName) {
return null;
}
$parts = Utils::pathinfo($clientName);
$filename = $parts['basename'];
$ext = $parts['extension'] ?? '';
$basename = $parts['filename'];
$file = $uploadedFile->getTmpFile();
$path = $file ? dirname($file) : '';
$config = Grav::instance()['config'];
$media_params = $ext ? $config->get('media.types.' . strtolower($ext)) : null;
if (!is_array($media_params)) {
return null;
}
$params += $media_params;
// Add default settings for undefined variables.
$params += (array)$config->get('media.types.defaults');
$params += [
'type' => 'file',
'thumb' => 'media/thumb.png',
'mime' => 'application/octet-stream',
'filepath' => $file,
'filename' => $filename,
'basename' => $basename,
'extension' => $ext,
'path' => $path,
'modified' => $file ? filemtime($file) : 0,
'thumbnails' => []
];
$locator = Grav::instance()['locator'];
$file = $locator->findResource("image://{$params['thumb']}");
if ($file) {
$params['thumbnails']['default'] = $file;
}
return static::fromArray($params);
}
/**
* Create Medium from array of parameters
*
* @param array $items
* @param Blueprint|null $blueprint
* @return Medium
*/
public static function fromArray(array $items = [], Blueprint $blueprint = null)
{
$type = $items['type'] ?? null;
switch ($type) {
case 'image':
return new ImageMedium($items, $blueprint);
case 'thumbnail':
return new ThumbnailImageMedium($items, $blueprint);
case 'vector':
return new VectorImageMedium($items, $blueprint);
case 'animated':
return new StaticImageMedium($items, $blueprint);
case 'video':
return new VideoMedium($items, $blueprint);
case 'audio':
return new AudioMedium($items, $blueprint);
default:
return new Medium($items, $blueprint);
}
}
/**
* Create a new ImageMedium by scaling another ImageMedium object.
*
* @param ImageMediaInterface|MediaObjectInterface $medium
* @param int $from
* @param int $to
* @return ImageMediaInterface|MediaObjectInterface|array
*/
public static function scaledFromMedium($medium, $from, $to)
{
if (!$medium instanceof ImageMedium) {
return $medium;
}
if ($to > $from) {
return $medium;
}
$ratio = $to / $from;
$width = $medium->get('width') * $ratio;
$height = $medium->get('height') * $ratio;
$prev_basename = $medium->get('basename');
$basename = str_replace('@' . $from . 'x', $to !== 1 ? '@' . $to . 'x' : '', $prev_basename);
$debug = $medium->get('debug');
$medium->set('debug', false);
$medium->setImagePrettyName($basename);
$file = $medium->resize($width, $height)->path();
$medium->set('debug', $debug);
$medium->setImagePrettyName($prev_basename);
$size = filesize($file);
$medium = self::fromFile($file);
if ($medium) {
$medium->set('basename', $basename);
$medium->set('filename', $basename . '.' . $medium->extension);
$medium->set('size', $size);
}
return ['file' => $medium, 'size' => $size];
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Page/Medium/VectorImageMedium.php | system/src/Grav/Common/Page/Medium/VectorImageMedium.php | <?php
/**
* @package Grav\Common\Page
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Page\Medium;
use Grav\Common\Data\Blueprint;
/**
* Class StaticImageMedium
* @package Grav\Common\Page\Medium
*/
class VectorImageMedium extends StaticImageMedium
{
/**
* Construct.
*
* @param array $items
* @param Blueprint|null $blueprint
*/
public function __construct($items = [], Blueprint $blueprint = null)
{
parent::__construct($items, $blueprint);
// If we already have the image size, we do not need to do anything else.
$width = $this->get('width');
$height = $this->get('height');
if ($width && $height) {
return;
}
// Make sure that getting image size is supported.
if ($this->mime !== 'image/svg+xml' || !\extension_loaded('simplexml')) {
return;
}
// Make sure that the image exists.
$path = $this->get('filepath');
if (!$path || !file_exists($path) || !filesize($path)) {
return;
}
$xml = simplexml_load_string(file_get_contents($path));
$attr = $xml ? $xml->attributes() : null;
if (!$attr instanceof \SimpleXMLElement) {
return;
}
// Get the size from svg image.
if ($attr->width && $attr->height) {
$width = (string)$attr->width;
$height = (string)$attr->height;
} elseif ($attr->viewBox && \count($size = explode(' ', (string)$attr->viewBox)) === 4) {
[,$width,$height,] = $size;
}
if ($width && $height) {
$this->def('width', (int)$width);
$this->def('height', (int)$height);
}
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Page/Medium/Medium.php | system/src/Grav/Common/Page/Medium/Medium.php | <?php
/**
* @package Grav\Common\Page
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Page\Medium;
use Grav\Common\File\CompiledYamlFile;
use Grav\Common\Grav;
use Grav\Common\Data\Data;
use Grav\Common\Data\Blueprint;
use Grav\Common\Media\Interfaces\MediaFileInterface;
use Grav\Common\Media\Interfaces\MediaLinkInterface;
use Grav\Common\Media\Traits\MediaFileTrait;
use Grav\Common\Media\Traits\MediaObjectTrait;
/**
* Class Medium
* @package Grav\Common\Page\Medium
*
* @property string $filepath
* @property string $filename
* @property string $basename
* @property string $mime
* @property int $size
* @property int $modified
* @property array $metadata
* @property int|string $timestamp
*/
class Medium extends Data implements RenderableInterface, MediaFileInterface
{
use MediaObjectTrait;
use MediaFileTrait;
use ParsedownHtmlTrait;
/**
* Construct.
*
* @param array $items
* @param Blueprint|null $blueprint
*/
public function __construct($items = [], Blueprint $blueprint = null)
{
parent::__construct($items, $blueprint);
if (Grav::instance()['config']->get('system.media.enable_media_timestamp', true)) {
$this->timestamp = Grav::instance()['cache']->getKey();
}
$this->def('mime', 'application/octet-stream');
if (!$this->offsetExists('size')) {
$path = $this->get('filepath');
$this->def('size', filesize($path));
}
$this->reset();
}
/**
* Clone medium.
*/
#[\ReturnTypeWillChange]
public function __clone()
{
// Allows future compatibility as parent::__clone() works.
}
/**
* Add meta file for the medium.
*
* @param string $filepath
*/
public function addMetaFile($filepath)
{
$this->metadata = (array)CompiledYamlFile::instance($filepath)->content();
$this->merge($this->metadata);
}
/**
* @return array
*/
public function getMeta(): array
{
return [
'mime' => $this->mime,
'size' => $this->size,
'modified' => $this->modified,
];
}
/**
* Return string representation of the object (html).
*
* @return string
*/
#[\ReturnTypeWillChange]
public function __toString()
{
return $this->html();
}
/**
* @param string $thumb
* @return Medium|null
*/
protected function createThumbnail($thumb)
{
return MediumFactory::fromFile($thumb, ['type' => 'thumbnail']);
}
/**
* @param array $attributes
* @return MediaLinkInterface
*/
protected function createLink(array $attributes)
{
return new Link($attributes, $this);
}
/**
* @return Grav
*/
protected function getGrav(): Grav
{
return Grav::instance();
}
/**
* @return array
*/
protected function getItems(): array
{
return $this->items;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Page/Medium/ParsedownHtmlTrait.php | system/src/Grav/Common/Page/Medium/ParsedownHtmlTrait.php | <?php
/**
* @package Grav\Common\Page
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Page\Medium;
use Grav\Common\Markdown\Parsedown;
use Grav\Common\Page\Markdown\Excerpts;
/**
* Trait ParsedownHtmlTrait
* @package Grav\Common\Page\Medium
*/
trait ParsedownHtmlTrait
{
/** @var Parsedown|null */
protected $parsedown;
/**
* Return HTML markup from the medium.
*
* @param string|null $title
* @param string|null $alt
* @param string|null $class
* @param string|null $id
* @param bool $reset
* @return string
*/
public function html($title = null, $alt = null, $class = null, $id = null, $reset = true)
{
$element = $this->parsedownElement($title, $alt, $class, $id, $reset);
if (!$this->parsedown) {
$this->parsedown = new Parsedown(new Excerpts());
}
return $this->parsedown->elementToHtml($element);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Page/Medium/StaticImageMedium.php | system/src/Grav/Common/Page/Medium/StaticImageMedium.php | <?php
/**
* @package Grav\Common\Page
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Page\Medium;
use Grav\Common\Media\Interfaces\ImageMediaInterface;
use Grav\Common\Media\Traits\ImageLoadingTrait;
use Grav\Common\Media\Traits\StaticResizeTrait;
/**
* Class StaticImageMedium
* @package Grav\Common\Page\Medium
*/
class StaticImageMedium extends Medium implements ImageMediaInterface
{
use StaticResizeTrait;
use ImageLoadingTrait;
/**
* Parsedown element for source display mode
*
* @param array $attributes
* @param bool $reset
* @return array
*/
protected function sourceParsedownElement(array $attributes, $reset = true)
{
if (empty($attributes['src'])) {
$attributes['src'] = $this->url($reset);
}
return ['name' => 'img', 'attributes' => $attributes];
}
/**
* @return $this
*/
public function higherQualityAlternative()
{
return $this;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Page/Interfaces/PageTranslateInterface.php | system/src/Grav/Common/Page/Interfaces/PageTranslateInterface.php | <?php
namespace Grav\Common\Page\Interfaces;
/**
* Interface PageTranslateInterface
* @package Grav\Common\Page\Interfaces
*/
interface PageTranslateInterface
{
/**
* @return bool
*/
public function translated(): bool;
/**
* Return an array with the routes of other translated languages
*
* @param bool $onlyPublished only return published translations
* @return array the page translated languages
*/
public function translatedLanguages($onlyPublished = false);
/**
* Return an array listing untranslated languages available
*
* @param bool $includeUnpublished also list unpublished translations
* @return array the page untranslated languages
*/
public function untranslatedLanguages($includeUnpublished = false);
/**
* Get page language
*
* @param string|null $var
* @return mixed
*/
public function language($var = null);
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Page/Interfaces/PagesSourceInterface.php | system/src/Grav/Common/Page/Interfaces/PagesSourceInterface.php | <?php
/**
* @package Grav\Common\Page
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Page\Interfaces;
/**
* Interface PagesSourceInterface
* @package Grav\Common\Page\Interfaces
*/
interface PagesSourceInterface // extends \Iterator
{
/**
* Get timestamp for the page source.
*
* @return int
*/
public function getTimestamp(): int;
/**
* Get checksum for the page source.
*
* @return string
*/
public function getChecksum(): string;
/**
* Returns true if the source contains a page for the given route.
*
* @param string $route
* @return bool
*/
public function has(string $route): bool;
/**
* Get the page for the given route.
*
* @param string $route
* @return PageInterface|null
*/
public function get(string $route): ?PageInterface;
/**
* Get the children for the given route.
*
* @param string $route
* @param array|null $options
* @return array
*/
public function getChildren(string $route, array $options = null): array;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Page/Interfaces/PageLegacyInterface.php | system/src/Grav/Common/Page/Interfaces/PageLegacyInterface.php | <?php
namespace Grav\Common\Page\Interfaces;
use Exception;
use Grav\Common\Data\Blueprint;
use Grav\Common\Page\Collection;
use InvalidArgumentException;
use RocketTheme\Toolbox\File\MarkdownFile;
use SplFileInfo;
/**
* Interface PageLegacyInterface
* @package Grav\Common\Page\Interfaces
*/
interface PageLegacyInterface
{
/**
* 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);
/**
* Gets and Sets the raw data
*
* @param string|null $var Raw content string
* @return string Raw content string
*/
public function raw($var = null);
/**
* Gets and Sets the page frontmatter
*
* @param string|null $var
* @return string
*/
public function frontmatter($var = null);
/**
* Modify a header value directly
*
* @param string $key
* @param mixed $value
*/
public function modifyHeader($key, $value);
/**
* @return int
*/
public function httpResponseCode();
/**
* @return array
*/
public function httpHeaders();
/**
* Get the contentMeta array and initialize content first if it's not already
*
* @return mixed
*/
public function contentMeta();
/**
* Add an entry to the page's contentMeta array
*
* @param string $name
* @param mixed $value
*/
public function addContentMeta($name, $value);
/**
* Return the whole contentMeta array as it currently stands
*
* @param string|null $name
* @return mixed
*/
public function getContentMeta($name = null);
/**
* Sets the whole content meta array in one shot
*
* @param array $content_meta
* @return array
*/
public function setContentMeta($content_meta);
/**
* Fires the onPageContentProcessed event, and caches the page content using a unique ID for the page
*/
public function cachePageContent();
/**
* Get file object to the page.
*
* @return MarkdownFile|null
*/
public function file();
/**
* Save page if there's a file assigned to it.
*
* @param bool|mixed $reorder Internal use.
*/
public function save($reorder = true);
/**
* 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);
/**
* 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 $parent New parent page.
* @return $this
*/
public function copy(PageInterface $parent);
/**
* Get blueprints for the page.
*
* @return Blueprint
*/
public function blueprints();
/**
* Get the blueprint name for this page. Use the blueprint form field if set
*
* @return string
*/
public function blueprintName();
/**
* Validate page header.
*
* @throws Exception
*/
public function validate();
/**
* Filter page header from illegal contents.
*/
public function filter();
/**
* Get unknown header variables.
*
* @return array
*/
public function extra();
/**
* Convert page to an array.
*
* @return array
*/
public function toArray();
/**
* Convert page to YAML encoded string.
*
* @return string
*/
public function toYaml();
/**
* Convert page to JSON encoded string.
*
* @return string
*/
public function toJson();
/**
* Returns normalized list of name => form pairs.
*
* @return array
*/
public function forms();
/**
* @param array $new
*/
public function addForms(array $new);
/**
* 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);
/**
* Returns child page type.
*
* @return string
*/
public function childType();
/**
* 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);
/**
* 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);
/**
* Gets and sets the extension field.
*
* @param string|null $var
* @return string|null
*/
public function extension($var = null);
/**
* 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);
/**
* 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);
/**
* @param bool|null $var
* @return bool
*/
public function ssl($var = null);
/**
* Returns the state of the debugger override etting for this page
*
* @return bool
*/
public function debugger();
/**
* 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);
/**
* 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;
/**
* 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);
/**
* Gets the relative path to the .md file
*
* @return string The relative file path
*/
public function filePathClean();
/**
* 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"
* @deprecated 1.6
*/
public function orderDir($var = null);
/**
* 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"
* @deprecated 1.6
*/
public function orderBy($var = null);
/**
* Gets the manual order set in the header.
*
* @param string|null $var supported options include "default", "title", "date", and "folder"
* @return array
* @deprecated 1.6
*/
public function orderManual($var = null);
/**
* 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
* @deprecated 1.6
*/
public function maxCount($var = null);
/**
* 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);
/**
* 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);
/**
* Returns children of this page.
*
* @return PageCollectionInterface|Collection
*/
public function children();
/**
* 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();
/**
* 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();
/**
* Gets the previous sibling based on current position.
*
* @return PageInterface the previous Page item
*/
public function prevSibling();
/**
* Gets the next sibling based on current position.
*
* @return PageInterface the next Page item
*/
public function nextSibling();
/**
* 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);
/**
* Helper method to return an ancestor page.
*
* @param bool|null $lookup Name of the parent folder
* @return PageInterface page you were looking for if it exists
*/
public function ancestor($lookup = null);
/**
* 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
*/
public function inherited($field);
/**
* 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);
/**
* Helper method to return a page.
*
* @param string $url the url of the page
* @param bool $all
* @return PageInterface page you were looking for if it exists
*/
public function find($url, $all = false);
/**
* Get a collection of pages in the current context.
*
* @param string|array $params
* @param bool $pagination
* @return Collection
* @throws InvalidArgumentException
*/
public function collection($params = 'content', $pagination = true);
/**
* @param string|array $value
* @param bool $only_published
* @return PageCollectionInterface|Collection
*/
public function evaluate($value, $only_published = true);
/**
* Returns whether or not the current folder exists
*
* @return bool
*/
public function folderExists();
/**
* Gets the Page Unmodified (original) version of the page.
*
* @return PageInterface The original version of the page.
*/
public function getOriginal();
/**
* Gets the action.
*
* @return string The Action string.
*/
public function getAction();
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Page/Interfaces/PageFormInterface.php | system/src/Grav/Common/Page/Interfaces/PageFormInterface.php | <?php
namespace Grav\Common\Page\Interfaces;
/**
* Interface PageFormInterface
* @package Grav\Common\Page\Interfaces
*/
interface PageFormInterface
{
/**
* Return all the forms which are associated to this page.
*
* Forms are returned as [name => blueprint, ...], where blueprint follows the regular form blueprint format.
*
* @return array
*/
//public function getForms(): array;
/**
* Add forms to this page.
*
* @param array $new
* @return $this
*/
public function addForms(array $new/*, $override = true*/);
/**
* Alias of $this->getForms();
*
* @return array
*/
public function forms();//: array;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Page/Interfaces/PageCollectionInterface.php | system/src/Grav/Common/Page/Interfaces/PageCollectionInterface.php | <?php
/**
* @package Grav\Common\Page
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Page\Interfaces;
use ArrayAccess;
use Countable;
use Exception;
use InvalidArgumentException;
use Serializable;
use Traversable;
/**
* Interface PageCollectionInterface
* @package Grav\Common\Page\Interfaces
*
* @template TKey of array-key
* @template T
* @extends Traversable<TKey,T>
* @extends ArrayAccess<TKey|null,T>
*/
interface PageCollectionInterface extends Traversable, ArrayAccess, Countable, Serializable
{
/**
* Get the collection params
*
* @return array
*/
public function params();
/**
* Set parameters to the Collection
*
* @param array $params
* @return $this
*/
public function setParams(array $params);
/**
* Add a single page to a collection
*
* @param PageInterface $page
* @return $this
*/
public function addPage(PageInterface $page);
/**
* Add a page with path and slug
*
* @param string $path
* @param string $slug
* @return $this
*/
//public function add($path, $slug);
/**
*
* Create a copy of this collection
*
* @return static
*/
public function copy();
/**
*
* Merge another collection with the current collection
*
* @param PageCollectionInterface $collection
* @return PageCollectionInterface
* @phpstan-return PageCollectionInterface<TKey,T>
*/
public function merge(PageCollectionInterface $collection);
/**
* Intersect another collection with the current collection
*
* @param PageCollectionInterface $collection
* @return PageCollectionInterface
* @phpstan-return PageCollectionInterface<TKey,T>
*/
public function intersect(PageCollectionInterface $collection);
/**
* Split collection into array of smaller collections.
*
* @param int $size
* @return PageCollectionInterface[]
* @phpstan-return array<PageCollectionInterface<TKey,T>>
*/
public function batch($size);
/**
* Remove item from the list.
*
* @param PageInterface|string|null $key
* @return PageCollectionInterface
* @phpstan-return PageCollectionInterface<TKey,T>
* @throws InvalidArgumentException
*/
//public function remove($key = null);
/**
* Reorder collection.
*
* @param string $by
* @param string $dir
* @param array|null $manual
* @param string|null $sort_flags
* @return PageCollectionInterface
* @phpstan-return PageCollectionInterface<TKey,T>
*/
public function order($by, $dir = 'asc', $manual = null, $sort_flags = null);
/**
* Check to see if this item is the first in the collection.
*
* @param string $path
* @return bool True if item is first.
*/
public function isFirst($path): bool;
/**
* Check to see if this item is the last in the collection.
*
* @param string $path
* @return bool True if item is last.
*/
public function isLast($path): bool;
/**
* Gets the previous sibling based on current position.
*
* @param string $path
* @return PageInterface The previous item.
* @phpstan-return T
*/
public function prevSibling($path);
/**
* Gets the next sibling based on current position.
*
* @param string $path
* @return PageInterface The next item.
* @phpstan-return T
*/
public function nextSibling($path);
/**
* Returns the adjacent sibling based on a direction.
*
* @param string $path
* @param int $direction either -1 or +1
* @return PageInterface|PageCollectionInterface|false The sibling item.
* @phpstan-return T|false
*/
public function adjacentSibling($path, $direction = 1);
/**
* Returns the item in the current position.
*
* @param string $path the path the item
* @return int|null The index of the current page, null if not found.
*/
public function currentPosition($path): ?int;
/**
* Returns the items between a set of date ranges of either the page date field (default) or
* an arbitrary datetime page field where start date and end date are optional
* Dates must be passed in as text that strtotime() can process
* http://php.net/manual/en/function.strtotime.php
*
* @param string|null $startDate
* @param string|null $endDate
* @param string|null $field
* @return PageCollectionInterface
* @phpstan-return PageCollectionInterface<TKey,T>
* @throws Exception
*/
public function dateRange($startDate = null, $endDate = null, $field = null);
/**
* Creates new collection with only visible pages
*
* @return PageCollectionInterface The collection with only visible pages
* @phpstan-return PageCollectionInterface<TKey,T>
*/
public function visible();
/**
* Creates new collection with only non-visible pages
*
* @return PageCollectionInterface The collection with only non-visible pages
* @phpstan-return PageCollectionInterface<TKey,T>
*/
public function nonVisible();
/**
* Creates new collection with only pages
*
* @return PageCollectionInterface The collection with only pages
* @phpstan-return PageCollectionInterface<TKey,T>
*/
public function pages();
/**
* Creates new collection with only modules
*
* @return PageCollectionInterface The collection with only modules
* @phpstan-return PageCollectionInterface<TKey,T>
*/
public function modules();
/**
* Creates new collection with only modules
*
* @return PageCollectionInterface The collection with only modules
* @phpstan-return PageCollectionInterface<TKey,T>
* @deprecated 1.7 Use $this->modules() instead
*/
public function modular();
/**
* Creates new collection with only non-module pages
*
* @return PageCollectionInterface The collection with only non-module pages
* @phpstan-return PageCollectionInterface<TKey,T>
* @deprecated 1.7 Use $this->pages() instead
*/
public function nonModular();
/**
* Creates new collection with only published pages
*
* @return PageCollectionInterface The collection with only published pages
* @phpstan-return PageCollectionInterface<TKey,T>
*/
public function published();
/**
* Creates new collection with only non-published pages
*
* @return PageCollectionInterface The collection with only non-published pages
* @phpstan-return PageCollectionInterface<TKey,T>
*/
public function nonPublished();
/**
* Creates new collection with only routable pages
*
* @return PageCollectionInterface The collection with only routable pages
* @phpstan-return PageCollectionInterface<TKey,T>
*/
public function routable();
/**
* Creates new collection with only non-routable pages
*
* @return PageCollectionInterface The collection with only non-routable pages
* @phpstan-return PageCollectionInterface<TKey,T>
*/
public function nonRoutable();
/**
* Creates new collection with only pages of the specified type
*
* @param string $type
* @return PageCollectionInterface The collection
* @phpstan-return PageCollectionInterface<TKey,T>
*/
public function ofType($type);
/**
* Creates new collection with only pages of one of the specified types
*
* @param string[] $types
* @return PageCollectionInterface The collection
* @phpstan-return PageCollectionInterface<TKey,T>
*/
public function ofOneOfTheseTypes($types);
/**
* Creates new collection with only pages of one of the specified access levels
*
* @param array $accessLevels
* @return PageCollectionInterface The collection
* @phpstan-return PageCollectionInterface<TKey,T>
*/
public function ofOneOfTheseAccessLevels($accessLevels);
/**
* Converts collection into an array.
*
* @return array
*/
public function toArray();
/**
* Get the extended version of this Collection with each page keyed by route
*
* @return array
* @throws Exception
*/
public function toExtendedArray();
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Page/Interfaces/PageInterface.php | system/src/Grav/Common/Page/Interfaces/PageInterface.php | <?php
/**
* @package Grav\Common\Page
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Page\Interfaces;
use Grav\Common\Media\Interfaces\MediaInterface;
/**
* Class implements page interface.
*/
interface PageInterface extends
PageContentInterface,
PageFormInterface,
PageRoutableInterface,
PageTranslateInterface,
MediaInterface,
PageLegacyInterface
{
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Page/Interfaces/PageContentInterface.php | system/src/Grav/Common/Page/Interfaces/PageContentInterface.php | <?php
/**
* @package Grav\Common\Page
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Page\Interfaces;
use Grav\Common\Data\Blueprint;
use Grav\Common\Media\Interfaces\MediaCollectionInterface;
use Grav\Common\Page\Header;
/**
* Methods currently implemented in Flex Page emulation layer.
*/
interface PageContentInterface
{
/**
* Gets and Sets the header based on the YAML configuration at the top of the .md file
*
* @param object|array|null $var a YAML object representing the configuration for the file
* @return \stdClass|Header The current YAML configuration
*/
public function header($var = null);
/**
* Get the summary.
*
* @param int|null $size Max summary size.
* @param bool $textOnly Only count text size.
* @return string
*/
public function summary($size = null, $textOnly = false);
/**
* Sets the summary of the page
*
* @param string $summary Summary
*/
public function setSummary($summary);
/**
* Gets and Sets the content based on content portion of the .md file
*
* @param string|null $var Content
* @return string Content
*/
public function content($var = null);
/**
* Needed by the onPageContentProcessed event to get the raw page content
*
* @return string the current page content
*/
public function getRawContent();
/**
* Needed by the onPageContentProcessed event to set the raw page content
*
* @param string|null $content
*/
public function setRawContent($content);
/**
* Gets and Sets the Page raw content
*
* @param string|null $var
* @return string
*/
public function rawMarkdown($var = null);
/**
* Get value from a page variable (used mostly for creating edit forms).
*
* @param string $name Variable name.
* @param mixed|null $default
* @return mixed
*/
public function value($name, $default = null);
/**
* Gets and sets the associated media as found in the page folder.
*
* @param MediaCollectionInterface|null $var New media object.
* @return MediaCollectionInterface Representation of associated media.
*/
public function media($var = null);
/**
* Gets and sets the title for this Page. If no title is set, it will use the slug() to get a name
*
* @param string|null $var New title of the Page
* @return string The title of the Page
*/
public function title($var = null);
/**
* 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|null $var New menu field for the page
* @return string The menu field for the page
*/
public function menu($var = null);
/**
* Gets and Sets whether or not this Page is visible for navigation
*
* @param bool|null $var New value
* @return bool True if the page is visible
*/
public function visible($var = null);
/**
* Gets and Sets whether or not this Page is considered published
*
* @param bool|null $var New value
* @return bool True if the page is published
*/
public function published($var = null);
/**
* Gets and Sets the Page publish date
*
* @param string|null $var String representation of the new date
* @return int Unix timestamp representation of the date
*/
public function publishDate($var = null);
/**
* Gets and Sets the Page unpublish date
*
* @param string|null $var String representation of the new date
* @return int|null Unix timestamp representation of the date
*/
public function unpublishDate($var = null);
/**
* 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|null $var New array of name value pairs where the name is the process and value is true or false
* @return array Array of name value pairs where the name is the process and value is true or false
*/
public function process($var = null);
/**
* 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|null $var New slug, e.g. 'my-blog'
* @return string The slug
*/
public function slug($var = null);
/**
* Get/set order number of this page.
*
* @param int|null $var New order as a number
* @return string|bool Order in a form of '02.' or false if not set
*/
public function order($var = null);
/**
* Gets and sets the identifier for this Page object.
*
* @param string|null $var New identifier
* @return string The identifier
*/
public function id($var = null);
/**
* Gets and sets the modified timestamp.
*
* @param int|null $var New modified unix timestamp
* @return int Modified unix timestamp
*/
public function modified($var = null);
/**
* Gets and sets the option to show the last_modified header for the page.
*
* @param bool|null $var New last_modified header value
* @return bool Show last_modified header
*/
public function lastModified($var = null);
/**
* Get/set the folder.
*
* @param string|null $var New folder
* @return string|null The folder
*/
public function folder($var = null);
/**
* Gets and sets the date for this Page object. This is typically passed in via the page headers
*
* @param string|null $var New string representation of a date
* @return int Unix timestamp representation of the date
*/
public function date($var = null);
/**
* Gets and sets the date format for this Page object. This is typically passed in via the page headers
* using typical PHP date string structure - http://php.net/manual/en/function.date.php
*
* @param string|null $var New string representation of a date format
* @return string String representation of a date format
*/
public function dateformat($var = null);
/**
* Gets and sets the taxonomy array which defines which taxonomies this page identifies itself with.
*
* @param array|null $var New array of taxonomies
* @return array An array of taxonomies
*/
public function taxonomy($var = null);
/**
* Gets the configured state of the processing method.
*
* @param string $process The process name, eg "twig" or "markdown"
* @return bool Whether or not the processing method is enabled for this Page
*/
public function shouldProcess($process);
/**
* Returns true if page is a module.
*
* @return bool
*/
public function isModule(): bool;
/**
* Returns whether or not this Page object has a .md file associated with it or if its just a directory.
*
* @return bool True if its a page with a .md file associated
*/
public function isPage();
/**
* Returns whether or not this Page object is a directory or a page.
*
* @return bool True if its a directory
*/
public function isDir();
/**
* Returns whether the page exists in the filesystem.
*
* @return bool
*/
public function exists();
/**
* Returns the blueprint from the page.
*
* @param string $name Name of the Blueprint form. Used by flex only.
* @return Blueprint Returns a Blueprint.
*/
public function getBlueprint(string $name = '');
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Page/Interfaces/PageRoutableInterface.php | system/src/Grav/Common/Page/Interfaces/PageRoutableInterface.php | <?php
namespace Grav\Common\Page\Interfaces;
/**
* Interface PageRoutableInterface
* @package Grav\Common\Page\Interfaces
*/
interface PageRoutableInterface
{
/**
* 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();
/**
* 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|null $var true if the page is routable
* @return bool true if the page is routable
*/
public function routable($var = null);
/**
* Gets the URL for a page - alias of url().
*
* @param bool|null $include_host
* @return string the permalink
*/
public function link($include_host = false);
/**
* Gets the URL with host information, aka Permalink.
* @return string The permalink.
*/
public function permalink();
/**
* Returns the canonical URL for a page
*
* @param bool $include_lang
* @return string
*/
public function canonical($include_lang = true);
/**
* Gets the url for the Page.
*
* @param bool $include_host Defaults false, but true would include http://yourhost.com
* @param bool $canonical true to return the canonical URL
* @param bool $include_lang
* @param bool $raw_route
* @return string The url.
*/
public function url($include_host = false, $canonical = false, $include_lang = true, $raw_route = false);
/**
* Gets the route for the page based on the route headers if available, else from
* the parents route and the current Page's slug.
*
* @param string|null $var Set new default route.
* @return string|null The route for the Page.
*/
public function route($var = null);
/**
* Helper method to clear the route out so it regenerates next time you use it
*/
public function unsetRouteSlug();
/**
* Gets and Sets the page raw route
*
* @param string|null $var
* @return string
*/
public function rawRoute($var = null);
/**
* Gets the route aliases for the page based on page headers.
*
* @param array|null $var list of route aliases
* @return array The route aliases for the Page.
*/
public function routeAliases($var = null);
/**
* Gets the canonical route for this page if its set. If provided it will use
* that value, else if it's `true` it will use the default route.
*
* @param string|null $var
* @return bool|string
*/
public function routeCanonical($var = null);
/**
* Gets the redirect set in the header.
*
* @param string|null $var redirect url
* @return string
*/
public function redirect($var = null);
/**
* Returns the clean path to the page file
*/
public function relativePagePath();
/**
* Gets and sets the path to the folder where the .md for this Page object resides.
* This is equivalent to the filePath but without the filename.
*
* @param string|null $var the path
* @return string|null the path
*/
public function path($var = null);
/**
* Get/set the folder.
*
* @param string|null $var Optional path
* @return string|null
*/
public function folder($var = null);
/**
* Gets and Sets the parent object for this page
*
* @param PageInterface|null $var the parent page object
* @return PageInterface|null the parent page object if it exists.
*/
public function parent(PageInterface $var = null);
/**
* Gets the top parent object for this page. Can return page itself.
*
* @return PageInterface The top parent page object.
*/
public function topParent();
/**
* Returns the item in the current position.
*
* @return int|null The index of the current page.
*/
public function currentPosition();
/**
* Returns whether or not this page is the currently active page requested via the URL.
*
* @return bool True if it is active
*/
public function active();
/**
* Returns whether or not this URI's URL contains the URL of the active page.
* Or in other words, is this page's URL in the current URL
*
* @return bool True if active child exists
*/
public function activeChild();
/**
* Returns whether or not this page is the currently configured home page.
*
* @return bool True if it is the homepage
*/
public function home();
/**
* Returns whether or not this page is the root node of the pages tree.
*
* @return bool True if it is the root
*/
public function root();
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.