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/Page/Traits/PageFormTrait.php | system/src/Grav/Common/Page/Traits/PageFormTrait.php | <?php
namespace Grav\Common\Page\Traits;
use Grav\Common\Grav;
use RocketTheme\Toolbox\Event\Event;
use function is_array;
/**
* Trait PageFormTrait
* @package Grav\Common\Page\Traits
*/
trait PageFormTrait
{
/** @var array|null */
private $_forms;
/**
* 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
{
if (null === $this->_forms) {
$header = $this->header();
// Call event to allow filling the page header form dynamically (e.g. use case: Comments plugin)
$grav = Grav::instance();
$grav->fireEvent('onFormPageHeaderProcessed', new Event(['page' => $this, 'header' => $header]));
$rules = $header->rules ?? null;
if (!is_array($rules)) {
$rules = [];
}
$forms = [];
// First grab page.header.form
$form = $this->normalizeForm($header->form ?? null, null, $rules);
if ($form) {
$forms[$form['name']] = $form;
}
// Append page.header.forms (override singular form if it clashes)
$headerForms = $header->forms ?? null;
if (is_array($headerForms)) {
foreach ($headerForms as $name => $form) {
$form = $this->normalizeForm($form, $name, $rules);
if ($form) {
$forms[$form['name']] = $form;
}
}
}
$this->_forms = $forms;
}
return $this->_forms;
}
/**
* Add forms to this page.
*
* @param array $new
* @param bool $override
* @return $this
*/
public function addForms(array $new, $override = true)
{
// Initialize forms.
$this->forms();
foreach ($new as $name => $form) {
$form = $this->normalizeForm($form, $name);
$name = $form['name'] ?? null;
if ($name && ($override || !isset($this->_forms[$name]))) {
$this->_forms[$name] = $form;
}
}
return $this;
}
/**
* Alias of $this->getForms();
*
* @return array
*/
public function forms(): array
{
return $this->getForms();
}
/**
* @param array|null $form
* @param string|null $name
* @param array $rules
* @return array|null
*/
protected function normalizeForm($form, $name = null, array $rules = []): ?array
{
if (!is_array($form)) {
return null;
}
// Ignore numeric indexes on name.
if (!$name || (string)(int)$name === (string)$name) {
$name = null;
}
$name = $name ?? $form['name'] ?? $this->slug();
$formRules = $form['rules'] ?? null;
if (!is_array($formRules)) {
$formRules = [];
}
return ['name' => $name, 'rules' => $rules + $formRules] + $form;
}
abstract public function header($var = null);
abstract public function slug($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/Filesystem/ZipArchiver.php | system/src/Grav/Common/Filesystem/ZipArchiver.php | <?php
/**
* @package Grav\Common\Filesystem
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Filesystem;
use InvalidArgumentException;
use RuntimeException;
use ZipArchive;
use function extension_loaded;
use function strlen;
/**
* Class ZipArchiver
* @package Grav\Common\Filesystem
*/
class ZipArchiver extends Archiver
{
/**
* @param string $destination
* @param callable|null $status
* @return $this
*/
public function extract($destination, callable $status = null)
{
$zip = new ZipArchive();
$archive = $zip->open($this->archive_file);
if ($archive === true) {
Folder::create($destination);
if (!$zip->extractTo($destination)) {
throw new RuntimeException('ZipArchiver: ZIP failed to extract ' . $this->archive_file . ' to ' . $destination);
}
$zip->close();
return $this;
}
throw new RuntimeException('ZipArchiver: Failed to open ' . $this->archive_file);
}
/**
* @param string $source
* @param callable|null $status
* @return $this
*/
public function compress($source, callable $status = null)
{
if (!extension_loaded('zip')) {
throw new InvalidArgumentException('ZipArchiver: Zip PHP module not installed...');
}
// Get real path for our folder
$rootPath = realpath($source);
if (!$rootPath) {
throw new InvalidArgumentException('ZipArchiver: ' . $source . ' cannot be found...');
}
$zip = new ZipArchive();
$result = $zip->open($this->archive_file, ZipArchive::CREATE);
if ($result !== true) {
$error = 'unknown error';
if ($result === ZipArchive::ER_NOENT) {
$error = 'file does not exist';
} elseif ($result === ZipArchive::ER_EXISTS) {
$error = 'file already exists';
} elseif ($result === ZipArchive::ER_OPEN) {
$error = 'cannot open file';
} elseif ($result === ZipArchive::ER_READ) {
$error = 'read error';
} elseif ($result === ZipArchive::ER_SEEK) {
$error = 'seek error';
}
throw new InvalidArgumentException('ZipArchiver: ' . $this->archive_file . ' cannot be created: ' . $error);
}
$files = $this->getArchiveFiles($rootPath);
$status && $status([
'type' => 'count',
'steps' => iterator_count($files),
]);
foreach ($files as $file) {
$filePath = $file->getPathname();
$relativePath = ltrim(substr($filePath, strlen($rootPath)), '/');
if ($file->isDir()) {
$zip->addEmptyDir($relativePath);
} else {
$zip->addFile($filePath, $relativePath);
}
$status && $status([
'type' => 'progress',
]);
}
$status && $status([
'type' => 'message',
'message' => 'Compressing...'
]);
$zip->close();
return $this;
}
/**
* @param array $folders
* @param callable|null $status
* @return $this
*/
public function addEmptyFolders($folders, callable $status = null)
{
if (!extension_loaded('zip')) {
throw new InvalidArgumentException('ZipArchiver: Zip PHP module not installed...');
}
$zip = new ZipArchive();
$result = $zip->open($this->archive_file);
if ($result !== true) {
$error = 'unknown error';
if ($result === ZipArchive::ER_NOENT) {
$error = 'file does not exist';
} elseif ($result === ZipArchive::ER_EXISTS) {
$error = 'file already exists';
} elseif ($result === ZipArchive::ER_OPEN) {
$error = 'cannot open file';
} elseif ($result === ZipArchive::ER_READ) {
$error = 'read error';
} elseif ($result === ZipArchive::ER_SEEK) {
$error = 'seek error';
}
throw new InvalidArgumentException('ZipArchiver: ' . $this->archive_file . ' cannot be opened: ' . $error);
}
$status && $status([
'type' => 'message',
'message' => 'Adding empty folders...'
]);
foreach ($folders as $folder) {
if ($zip->addEmptyDir($folder) === false) {
$status && $status([
'type' => 'message',
'message' => 'Warning: Could not add empty directory: ' . $folder
]);
}
$status && $status([
'type' => 'progress',
]);
}
$zip->close();
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/Filesystem/Archiver.php | system/src/Grav/Common/Filesystem/Archiver.php | <?php
/**
* @package Grav\Common\Filesystem
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Filesystem;
use FilesystemIterator;
use Grav\Common\Utils;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use function function_exists;
/**
* Class Archiver
* @package Grav\Common\Filesystem
*/
abstract class Archiver
{
/** @var array */
protected $options = [
'exclude_files' => ['.DS_Store'],
'exclude_paths' => []
];
/** @var string */
protected $archive_file;
/**
* @param string $compression
* @return ZipArchiver
*/
public static function create($compression)
{
if ($compression === 'zip') {
return new ZipArchiver();
}
return new ZipArchiver();
}
/**
* @param string $archive_file
* @return $this
*/
public function setArchive($archive_file)
{
$this->archive_file = $archive_file;
return $this;
}
/**
* @param array $options
* @return $this
*/
public function setOptions($options)
{
// Set infinite PHP execution time if possible.
if (Utils::functionExists('set_time_limit')) {
@set_time_limit(0);
}
$this->options = $options + $this->options;
return $this;
}
/**
* @param string $folder
* @param callable|null $status
* @return $this
*/
abstract public function compress($folder, callable $status = null);
/**
* @param string $destination
* @param callable|null $status
* @return $this
*/
abstract public function extract($destination, callable $status = null);
/**
* @param array $folders
* @param callable|null $status
* @return $this
*/
abstract public function addEmptyFolders($folders, callable $status = null);
/**
* @param string $rootPath
* @return RecursiveIteratorIterator
*/
protected function getArchiveFiles($rootPath)
{
$exclude_paths = $this->options['exclude_paths'];
$exclude_files = $this->options['exclude_files'];
$dirItr = new RecursiveDirectoryIterator($rootPath, RecursiveDirectoryIterator::SKIP_DOTS | FilesystemIterator::FOLLOW_SYMLINKS | FilesystemIterator::UNIX_PATHS);
$filterItr = new RecursiveDirectoryFilterIterator($dirItr, $rootPath, $exclude_paths, $exclude_files);
$files = new RecursiveIteratorIterator($filterItr, RecursiveIteratorIterator::SELF_FIRST);
return $files;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Filesystem/RecursiveFolderFilterIterator.php | system/src/Grav/Common/Filesystem/RecursiveFolderFilterIterator.php | <?php
/**
* @package Grav\Common\Filesystem
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Filesystem;
use Grav\Common\Grav;
use RecursiveIterator;
use SplFileInfo;
use function in_array;
/**
* Class RecursiveFolderFilterIterator
* @package Grav\Common\Filesystem
*/
class RecursiveFolderFilterIterator extends \RecursiveFilterIterator
{
/** @var array */
protected static $ignore_folders;
/**
* Create a RecursiveFilterIterator from a RecursiveIterator
*
* @param RecursiveIterator $iterator
* @param array $ignore_folders
*/
public function __construct(RecursiveIterator $iterator, $ignore_folders = [])
{
parent::__construct($iterator);
if (empty($ignore_folders)) {
$ignore_folders = Grav::instance()['config']->get('system.pages.ignore_folders');
}
$this::$ignore_folders = $ignore_folders;
}
/**
* Check whether the current element of the iterator is acceptable
*
* @return bool true if the current element is acceptable, otherwise false.
*/
public function accept() :bool
{
/** @var SplFileInfo $current */
$current = $this->current();
return $current->isDir() && !in_array($current->getFilename(), $this::$ignore_folders, true);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Filesystem/RecursiveDirectoryFilterIterator.php | system/src/Grav/Common/Filesystem/RecursiveDirectoryFilterIterator.php | <?php
/**
* @package Grav\Common\Filesystem
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Filesystem;
use RecursiveFilterIterator;
use RecursiveIterator;
use SplFileInfo;
use function in_array;
/**
* Class RecursiveDirectoryFilterIterator
* @package Grav\Common\Filesystem
*/
class RecursiveDirectoryFilterIterator extends RecursiveFilterIterator
{
/** @var string */
protected static $root;
/** @var array */
protected static $ignore_folders;
/** @var array */
protected static $ignore_files;
/**
* Create a RecursiveFilterIterator from a RecursiveIterator
*
* @param RecursiveIterator $iterator
* @param string $root
* @param array $ignore_folders
* @param array $ignore_files
*/
public function __construct(RecursiveIterator $iterator, $root, $ignore_folders, $ignore_files)
{
parent::__construct($iterator);
$this::$root = $root;
$this::$ignore_folders = $ignore_folders;
$this::$ignore_files = $ignore_files;
}
/**
* Check whether the current element of the iterator is acceptable
*
* @return bool true if the current element is acceptable, otherwise false.
*/
public function accept() :bool
{
/** @var SplFileInfo $file */
$file = $this->current();
$filename = $file->getFilename();
$relative_filename = str_replace($this::$root . '/', '', $file->getPathname());
if ($file->isDir()) {
// Check if the directory path is in the ignore list
if (in_array($relative_filename, $this::$ignore_folders, true)) {
return false;
}
// Check if any parent directory is in the ignore list
foreach ($this::$ignore_folders as $ignore_folder) {
$ignore_folder = trim($ignore_folder, '/');
if (strpos($relative_filename, $ignore_folder . '/') === 0 || $relative_filename === $ignore_folder) {
return false;
}
}
if (!$this->matchesPattern($filename, $this::$ignore_files)) {
return true;
}
} elseif ($file->isFile() && !$this->matchesPattern($filename, $this::$ignore_files)) {
return true;
}
return false;
}
/**
* Check if filename matches any pattern in the list
*
* @param string $filename
* @param array $patterns
* @return bool
*/
protected function matchesPattern($filename, $patterns)
{
foreach ($patterns as $pattern) {
// Check for exact match
if ($filename === $pattern) {
return true;
}
// Check for extension patterns like .pdf
if (strpos($pattern, '.') === 0 && substr($filename, -strlen($pattern)) === $pattern) {
return true;
}
// Check for wildcard patterns
if (strpos($pattern, '*') !== false) {
$regex = '/^' . str_replace('\\*', '.*', preg_quote($pattern, '/')) . '$/';
if (preg_match($regex, $filename)) {
return true;
}
}
}
return false;
}
/**
* @return RecursiveDirectoryFilterIterator|RecursiveFilterIterator
*/
public function getChildren() :RecursiveFilterIterator
{
/** @var RecursiveDirectoryFilterIterator $iterator */
$iterator = $this->getInnerIterator();
return new self($iterator->getChildren(), $this::$root, $this::$ignore_folders, $this::$ignore_files);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Filesystem/Folder.php | system/src/Grav/Common/Filesystem/Folder.php | <?php
/**
* @package Grav\Common\Filesystem
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Filesystem;
use DirectoryIterator;
use Exception;
use FilesystemIterator;
use Grav\Common\Grav;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use RegexIterator;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use RuntimeException;
use function count;
use function dirname;
use function is_callable;
/**
* Class Folder
* @package Grav\Common\Filesystem
*/
abstract class Folder
{
/**
* Recursively find the last modified time under given path.
*
* @param array $paths
* @return int
*/
public static function lastModifiedFolder(array $paths): int
{
$last_modified = 0;
/** @var UniformResourceLocator $locator */
$locator = Grav::instance()['locator'];
$flags = RecursiveDirectoryIterator::SKIP_DOTS;
foreach ($paths as $path) {
if (!file_exists($path)) {
return 0;
}
if ($locator->isStream($path)) {
$directory = $locator->getRecursiveIterator($path, $flags);
} else {
$directory = new RecursiveDirectoryIterator($path, $flags);
}
$filter = new RecursiveFolderFilterIterator($directory);
$iterator = new RecursiveIteratorIterator($filter, RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $dir) {
$dir_modified = $dir->getMTime();
if ($dir_modified > $last_modified) {
$last_modified = $dir_modified;
}
}
}
return $last_modified;
}
/**
* Recursively find the last modified time under given path by file.
*
* @param array $paths
* @param string $extensions which files to search for specifically
* @return int
*/
public static function lastModifiedFile(array $paths, $extensions = 'md|yaml'): int
{
$last_modified = 0;
/** @var UniformResourceLocator $locator */
$locator = Grav::instance()['locator'];
$flags = RecursiveDirectoryIterator::SKIP_DOTS;
foreach($paths as $path) {
if (!file_exists($path)) {
return 0;
}
if ($locator->isStream($path)) {
$directory = $locator->getRecursiveIterator($path, $flags);
} else {
$directory = new RecursiveDirectoryIterator($path, $flags);
}
$recursive = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::SELF_FIRST);
$iterator = new RegexIterator($recursive, '/^.+\.'.$extensions.'$/i');
/** @var RecursiveDirectoryIterator $file */
foreach ($iterator as $file) {
try {
$file_modified = $file->getMTime();
if ($file_modified > $last_modified) {
$last_modified = $file_modified;
}
} catch (Exception $e) {
Grav::instance()['log']->error('Could not process file: ' . $e->getMessage());
}
}
}
return $last_modified;
}
/**
* Recursively md5 hash all files in a path
*
* @param array $paths
* @return string
*/
public static function hashAllFiles(array $paths): string
{
$files = [];
foreach ($paths as $path) {
if (file_exists($path)) {
$flags = RecursiveDirectoryIterator::SKIP_DOTS;
/** @var UniformResourceLocator $locator */
$locator = Grav::instance()['locator'];
if ($locator->isStream($path)) {
$directory = $locator->getRecursiveIterator($path, $flags);
} else {
$directory = new RecursiveDirectoryIterator($path, $flags);
}
$iterator = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $file) {
$files[] = $file->getPathname() . '?'. $file->getMTime();
}
}
}
return md5(serialize($files));
}
/**
* Get relative path between target and base path. If path isn't relative, return full path.
*
* @param string $path
* @param string $base
* @return string
*/
public static function getRelativePath($path, $base = GRAV_ROOT)
{
if ($base) {
$base = preg_replace('![\\\/]+!', '/', $base);
$path = preg_replace('![\\\/]+!', '/', $path);
if (strpos($path, $base) === 0) {
$path = ltrim(substr($path, strlen($base)), '/');
}
}
return $path;
}
/**
* Get relative path between target and base path. If path isn't relative, return full path.
*
* @param string $path
* @param string $base
* @return string
*/
public static function getRelativePathDotDot($path, $base)
{
// Normalize paths.
$base = preg_replace('![\\\/]+!', '/', $base);
$path = preg_replace('![\\\/]+!', '/', $path);
if ($path === $base) {
return '';
}
$baseParts = explode('/', ltrim($base, '/'));
$pathParts = explode('/', ltrim($path, '/'));
array_pop($baseParts);
$lastPart = array_pop($pathParts);
foreach ($baseParts as $i => $directory) {
if (isset($pathParts[$i]) && $pathParts[$i] === $directory) {
unset($baseParts[$i], $pathParts[$i]);
} else {
break;
}
}
$pathParts[] = $lastPart;
$path = str_repeat('../', count($baseParts)) . implode('/', $pathParts);
return '' === $path
|| strpos($path, '/') === 0
|| false !== ($colonPos = strpos($path, ':')) && ($colonPos < ($slashPos = strpos($path, '/')) || false === $slashPos)
? "./$path" : $path;
}
/**
* Shift first directory out of the path.
*
* @param string $path
* @return string|null
*/
public static function shift(&$path)
{
$parts = explode('/', trim($path, '/'), 2);
$result = array_shift($parts);
$path = array_shift($parts);
return $result ?: null;
}
/**
* Return recursive list of all files and directories under given path.
*
* @param string $path
* @param array $params
* @return array
* @throws RuntimeException
*/
public static function all($path, array $params = [])
{
if (!$path) {
throw new RuntimeException("Path doesn't exist.");
}
if (!file_exists($path)) {
return [];
}
$compare = isset($params['compare']) ? 'get' . $params['compare'] : null;
$pattern = $params['pattern'] ?? null;
$filters = $params['filters'] ?? null;
$recursive = $params['recursive'] ?? true;
$levels = $params['levels'] ?? -1;
$key = isset($params['key']) ? 'get' . $params['key'] : null;
$value = 'get' . ($params['value'] ?? ($recursive ? 'SubPathname' : 'Filename'));
$folders = $params['folders'] ?? true;
$files = $params['files'] ?? true;
/** @var UniformResourceLocator $locator */
$locator = Grav::instance()['locator'];
if ($recursive) {
$flags = RecursiveDirectoryIterator::SKIP_DOTS + FilesystemIterator::UNIX_PATHS
+ FilesystemIterator::CURRENT_AS_SELF + FilesystemIterator::FOLLOW_SYMLINKS;
if ($locator->isStream($path)) {
$directory = $locator->getRecursiveIterator($path, $flags);
} else {
$directory = new RecursiveDirectoryIterator($path, $flags);
}
$iterator = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::SELF_FIRST);
$iterator->setMaxDepth(max($levels, -1));
} else {
if ($locator->isStream($path)) {
$iterator = $locator->getIterator($path);
} else {
$iterator = new FilesystemIterator($path);
}
}
$results = [];
/** @var RecursiveDirectoryIterator $file */
foreach ($iterator as $file) {
// Ignore hidden files.
if (strpos($file->getFilename(), '.') === 0 && $file->isFile()) {
continue;
}
if (!$folders && $file->isDir()) {
continue;
}
if (!$files && $file->isFile()) {
continue;
}
if ($compare && $pattern && !preg_match($pattern, $file->{$compare}())) {
continue;
}
$fileKey = $key ? $file->{$key}() : null;
$filePath = $file->{$value}();
if ($filters) {
if (isset($filters['key'])) {
$pre = !empty($filters['pre-key']) ? $filters['pre-key'] : '';
$fileKey = $pre . preg_replace($filters['key'], '', $fileKey);
}
if (isset($filters['value'])) {
$filter = $filters['value'];
if (is_callable($filter)) {
$filePath = $filter($file);
} else {
$filePath = preg_replace($filter, '', $filePath);
}
}
}
if ($fileKey !== null) {
$results[$fileKey] = $filePath;
} else {
$results[] = $filePath;
}
}
return $results;
}
/**
* Recursively copy directory in filesystem.
*
* @param string $source
* @param string $target
* @param string|null $ignore Ignore files matching pattern (regular expression).
* @return void
* @throws RuntimeException
*/
public static function copy($source, $target, $ignore = null)
{
$source = rtrim($source, '\\/');
$target = rtrim($target, '\\/');
if (!is_dir($source)) {
throw new RuntimeException('Cannot copy non-existing folder.');
}
// Make sure that path to the target exists before copying.
self::create($target);
$success = true;
// Go through all sub-directories and copy everything.
$files = self::all($source);
foreach ($files as $file) {
if ($ignore && preg_match($ignore, $file)) {
continue;
}
$src = $source .'/'. $file;
$dst = $target .'/'. $file;
if (is_dir($src)) {
// Create current directory (if it doesn't exist).
if (!is_dir($dst)) {
$success &= @mkdir($dst, 0777, true);
}
} else {
// Or copy current file.
$success &= @copy($src, $dst);
}
}
if (!$success) {
$error = error_get_last();
throw new RuntimeException($error['message'] ?? 'Unknown error');
}
// Make sure that the change will be detected when caching.
@touch(dirname($target));
}
/**
* Move directory in filesystem.
*
* @param string $source
* @param string $target
* @return void
* @throws RuntimeException
*/
public static function move($source, $target)
{
if (!file_exists($source) || !is_dir($source)) {
// Rename fails if source folder does not exist.
throw new RuntimeException('Cannot move non-existing folder.');
}
// Don't do anything if the source is the same as the new target
if ($source === $target) {
return;
}
if (strpos($target, $source . '/') === 0) {
throw new RuntimeException('Cannot move folder to itself');
}
if (file_exists($target)) {
// Rename fails if target folder exists.
throw new RuntimeException('Cannot move files to existing folder/file.');
}
// Make sure that path to the target exists before moving.
self::create(dirname($target));
// Silence warnings (chmod failed etc).
@rename($source, $target);
// Rename function can fail while still succeeding, so let's check if the folder exists.
if (is_dir($source)) {
// Rename doesn't support moving folders across filesystems. Use copy instead.
self::copy($source, $target);
self::delete($source);
}
// Make sure that the change will be detected when caching.
@touch(dirname($source));
@touch(dirname($target));
@touch($target);
}
/**
* Recursively delete directory from filesystem.
*
* @param string $target
* @param bool $include_target
* @return bool
* @throws RuntimeException
*/
public static function delete($target, $include_target = true)
{
if (!is_dir($target)) {
return false;
}
$success = self::doDelete($target, $include_target);
if (!$success) {
$error = error_get_last();
throw new RuntimeException($error['message'] ?? 'Unknown error');
}
// Make sure that the change will be detected when caching.
if ($include_target) {
@touch(dirname($target));
} else {
@touch($target);
}
return $success;
}
/**
* @param string $folder
* @return void
* @throws RuntimeException
*/
public static function mkdir($folder)
{
self::create($folder);
}
/**
* @param string $folder
* @return void
* @throws RuntimeException
*/
public static function create($folder)
{
// Silence error for open_basedir; should fail in mkdir instead.
if (@is_dir($folder)) {
return;
}
$success = @mkdir($folder, 0777, true);
if (!$success) {
// Take yet another look, make sure that the folder doesn't exist.
clearstatcache(true, $folder);
if (!@is_dir($folder)) {
throw new RuntimeException(sprintf('Unable to create directory: %s', $folder));
}
}
}
/**
* Recursive copy of one directory to another
*
* @param string $src
* @param string $dest
* @return bool
* @throws RuntimeException
*/
public static function rcopy($src, $dest)
{
// If the src is not a directory do a simple file copy
if (!is_dir($src)) {
copy($src, $dest);
return true;
}
// If the destination directory does not exist create it
if (!is_dir($dest)) {
static::create($dest);
}
// Open the source directory to read in files
$i = new DirectoryIterator($src);
foreach ($i as $f) {
if ($f->isFile()) {
copy($f->getRealPath(), "{$dest}/" . $f->getFilename());
} else {
if (!$f->isDot() && $f->isDir()) {
static::rcopy($f->getRealPath(), "{$dest}/{$f}");
}
}
}
return true;
}
/**
* Does a directory contain children
*
* @param string $directory
* @return int|false
*/
public static function countChildren($directory)
{
if (!is_dir($directory)) {
return false;
}
$directories = glob($directory . '/*', GLOB_ONLYDIR);
return $directories ? count($directories) : false;
}
/**
* @param string $folder
* @param bool $include_target
* @return bool
* @internal
*/
protected static function doDelete($folder, $include_target = true)
{
// Special case for symbolic links.
if ($include_target && is_link($folder)) {
return @unlink($folder);
}
// Go through all items in filesystem and recursively remove everything.
$files = scandir($folder, SCANDIR_SORT_NONE);
$files = $files ? array_diff($files, ['.', '..']) : [];
foreach ($files as $file) {
$path = "{$folder}/{$file}";
is_dir($path) ? self::doDelete($path) : @unlink($path);
}
return $include_target ? @rmdir($folder) : true;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Language/LanguageCodes.php | system/src/Grav/Common/Language/LanguageCodes.php | <?php
/**
* @package Grav\Common\Language
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Language;
/**
* Class LanguageCodes
* @package Grav\Common\Language
*/
class LanguageCodes
{
/** @var array */
protected static $codes = [
'af' => [ 'name' => 'Afrikaans', 'nativeName' => 'Afrikaans' ],
'ak' => [ 'name' => 'Akan', 'nativeName' => 'Akan' ], // unverified native name
'ast' => [ 'name' => 'Asturian', 'nativeName' => 'Asturianu' ],
'ar' => [ 'name' => 'Arabic', 'nativeName' => 'عربي', 'orientation' => 'rtl'],
'as' => [ 'name' => 'Assamese', 'nativeName' => 'অসমীয়া' ],
'be' => [ 'name' => 'Belarusian', 'nativeName' => 'Беларуская' ],
'bg' => [ 'name' => 'Bulgarian', 'nativeName' => 'Български' ],
'bn' => [ 'name' => 'Bengali', 'nativeName' => 'বাংলা' ],
'bn-BD' => [ 'name' => 'Bengali (Bangladesh)', 'nativeName' => 'বাংলা (বাংলাদেশ)' ],
'bn-IN' => [ 'name' => 'Bengali (India)', 'nativeName' => 'বাংলা (ভারত)' ],
'br' => [ 'name' => 'Breton', 'nativeName' => 'Brezhoneg' ],
'bs' => [ 'name' => 'Bosnian', 'nativeName' => 'Bosanski' ],
'ca' => [ 'name' => 'Catalan', 'nativeName' => 'Català' ],
'ca-valencia'=> [ 'name' => 'Catalan (Valencian)', 'nativeName' => 'Català (valencià)' ], // not iso-639-1. a=l10n-drivers
'cs' => [ 'name' => 'Czech', 'nativeName' => 'Čeština' ],
'cy' => [ 'name' => 'Welsh', 'nativeName' => 'Cymraeg' ],
'da' => [ 'name' => 'Danish', 'nativeName' => 'Dansk' ],
'de' => [ 'name' => 'German', 'nativeName' => 'Deutsch' ],
'de-AT' => [ 'name' => 'German (Austria)', 'nativeName' => 'Deutsch (Österreich)' ],
'de-CH' => [ 'name' => 'German (Switzerland)', 'nativeName' => 'Deutsch (Schweiz)' ],
'de-DE' => [ 'name' => 'German (Germany)', 'nativeName' => 'Deutsch (Deutschland)' ],
'dsb' => [ 'name' => 'Lower Sorbian', 'nativeName' => 'Dolnoserbšćina' ], // iso-639-2
'el' => [ 'name' => 'Greek', 'nativeName' => 'Ελληνικά' ],
'en' => [ 'name' => 'English', 'nativeName' => 'English' ],
'en-AU' => [ 'name' => 'English (Australian)', 'nativeName' => 'English (Australian)' ],
'en-CA' => [ 'name' => 'English (Canadian)', 'nativeName' => 'English (Canadian)' ],
'en-GB' => [ 'name' => 'English (British)', 'nativeName' => 'English (British)' ],
'en-NZ' => [ 'name' => 'English (New Zealand)', 'nativeName' => 'English (New Zealand)' ],
'en-US' => [ 'name' => 'English (US)', 'nativeName' => 'English (US)' ],
'en-ZA' => [ 'name' => 'English (South African)', 'nativeName' => 'English (South African)' ],
'eo' => [ 'name' => 'Esperanto', 'nativeName' => 'Esperanto' ],
'es' => [ 'name' => 'Spanish', 'nativeName' => 'Español' ],
'es-AR' => [ 'name' => 'Spanish (Argentina)', 'nativeName' => 'Español (de Argentina)' ],
'es-CL' => [ 'name' => 'Spanish (Chile)', 'nativeName' => 'Español (de Chile)' ],
'es-ES' => [ 'name' => 'Spanish (Spain)', 'nativeName' => 'Español (de España)' ],
'es-MX' => [ 'name' => 'Spanish (Mexico)', 'nativeName' => 'Español (de México)' ],
'et' => [ 'name' => 'Estonian', 'nativeName' => 'Eesti keel' ],
'eu' => [ 'name' => 'Basque', 'nativeName' => 'Euskara' ],
'fa' => [ 'name' => 'Persian', 'nativeName' => 'فارسی' , 'orientation' => 'rtl' ],
'fi' => [ 'name' => 'Finnish', 'nativeName' => 'Suomi' ],
'fj-FJ' => [ 'name' => 'Fijian', 'nativeName' => 'Vosa vaka-Viti' ],
'fr' => [ 'name' => 'French', 'nativeName' => 'Français' ],
'fr-CA' => [ 'name' => 'French (Canada)', 'nativeName' => 'Français (Canada)' ],
'fr-FR' => [ 'name' => 'French (France)', 'nativeName' => 'Français (France)' ],
'fur' => [ 'name' => 'Friulian', 'nativeName' => 'Furlan' ],
'fur-IT' => [ 'name' => 'Friulian', 'nativeName' => 'Furlan' ],
'fy' => [ 'name' => 'Frisian', 'nativeName' => 'Frysk' ],
'fy-NL' => [ 'name' => 'Frisian', 'nativeName' => 'Frysk' ],
'ga' => [ 'name' => 'Irish', 'nativeName' => 'Gaeilge' ],
'ga-IE' => [ 'name' => 'Irish (Ireland)', 'nativeName' => 'Gaeilge (Éire)' ],
'gd' => [ 'name' => 'Gaelic (Scotland)', 'nativeName' => 'Gàidhlig' ],
'gl' => [ 'name' => 'Galician', 'nativeName' => 'Galego' ],
'gu' => [ 'name' => 'Gujarati', 'nativeName' => 'ગુજરાતી' ],
'gu-IN' => [ 'name' => 'Gujarati', 'nativeName' => 'ગુજરાતી' ],
'he' => [ 'name' => 'Hebrew', 'nativeName' => 'עברית', 'orientation' => 'rtl' ],
'hi' => [ 'name' => 'Hindi', 'nativeName' => 'हिन्दी' ],
'hi-IN' => [ 'name' => 'Hindi (India)', 'nativeName' => 'हिन्दी (भारत)' ],
'hr' => [ 'name' => 'Croatian', 'nativeName' => 'Hrvatski' ],
'hsb' => [ 'name' => 'Upper Sorbian', 'nativeName' => 'Hornjoserbsce' ],
'hu' => [ 'name' => 'Hungarian', 'nativeName' => 'Magyar' ],
'hy' => [ 'name' => 'Armenian', 'nativeName' => 'Հայերեն' ],
'hy-AM' => [ 'name' => 'Armenian', 'nativeName' => 'Հայերեն' ],
'id' => [ 'name' => 'Indonesian', 'nativeName' => 'Bahasa Indonesia' ],
'is' => [ 'name' => 'Icelandic', 'nativeName' => 'íslenska' ],
'it' => [ 'name' => 'Italian', 'nativeName' => 'Italiano' ],
'ja' => [ 'name' => 'Japanese', 'nativeName' => '日本語' ],
'ja-JP' => [ 'name' => 'Japanese', 'nativeName' => '日本語' ], // not iso-639-1
'ka' => [ 'name' => 'Georgian', 'nativeName' => 'ქართული' ],
'kk' => [ 'name' => 'Kazakh', 'nativeName' => 'Қазақ' ],
'km' => [ 'name' => 'Khmer', 'nativeName' => 'Khmer' ],
'kn' => [ 'name' => 'Kannada', 'nativeName' => 'ಕನ್ನಡ' ],
'ko' => [ 'name' => 'Korean', 'nativeName' => '한국어' ],
'ku' => [ 'name' => 'Kurdish', 'nativeName' => 'Kurdî' ],
'la' => [ 'name' => 'Latin', 'nativeName' => 'Latina' ],
'lb' => [ 'name' => 'Luxembourgish', 'nativeName' => 'Lëtzebuergesch' ],
'lg' => [ 'name' => 'Luganda', 'nativeName' => 'Luganda' ],
'lo' => [ 'name' => 'Lao', 'nativeName' => 'Lao' ],
'lt' => [ 'name' => 'Lithuanian', 'nativeName' => 'Lietuvių' ],
'lv' => [ 'name' => 'Latvian', 'nativeName' => 'Latviešu' ],
'mai' => [ 'name' => 'Maithili', 'nativeName' => 'मैथिली মৈথিলী' ],
'mg' => [ 'name' => 'Malagasy', 'nativeName' => 'Malagasy' ],
'mi' => [ 'name' => 'Maori (Aotearoa)', 'nativeName' => 'Māori (Aotearoa)' ],
'mk' => [ 'name' => 'Macedonian', 'nativeName' => 'Македонски' ],
'ml' => [ 'name' => 'Malayalam', 'nativeName' => 'മലയാളം' ],
'mn' => [ 'name' => 'Mongolian', 'nativeName' => 'Монгол' ],
'mr' => [ 'name' => 'Marathi', 'nativeName' => 'मराठी' ],
'my' => [ 'name' => 'Myanmar (Burmese)', 'nativeName' => 'ဗမာी' ],
'no' => [ 'name' => 'Norwegian', 'nativeName' => 'Norsk' ],
'nb' => [ 'name' => 'Norwegian', 'nativeName' => 'Norsk' ],
'nb-NO' => [ 'name' => 'Norwegian (Bokmål)', 'nativeName' => 'Norsk bokmål' ],
'ne-NP' => [ 'name' => 'Nepali', 'nativeName' => 'नेपाली' ],
'nn-NO' => [ 'name' => 'Norwegian (Nynorsk)', 'nativeName' => 'Norsk nynorsk' ],
'nl' => [ 'name' => 'Dutch', 'nativeName' => 'Nederlands' ],
'nr' => [ 'name' => 'Ndebele, South', 'nativeName' => 'IsiNdebele' ],
'nso' => [ 'name' => 'Northern Sotho', 'nativeName' => 'Sepedi' ],
'oc' => [ 'name' => 'Occitan (Lengadocian)', 'nativeName' => 'Occitan (lengadocian)' ],
'or' => [ 'name' => 'Oriya', 'nativeName' => 'ଓଡ଼ିଆ' ],
'pa' => [ 'name' => 'Punjabi', 'nativeName' => 'ਪੰਜਾਬੀ' ],
'pa-IN' => [ 'name' => 'Punjabi', 'nativeName' => 'ਪੰਜਾਬੀ' ],
'pl' => [ 'name' => 'Polish', 'nativeName' => 'Polski' ],
'pt' => [ 'name' => 'Portuguese', 'nativeName' => 'Português' ],
'pt-BR' => [ 'name' => 'Portuguese (Brazilian)', 'nativeName' => 'Português (do Brasil)' ],
'pt-PT' => [ 'name' => 'Portuguese (Portugal)', 'nativeName' => 'Português (Europeu)' ],
'ro' => [ 'name' => 'Romanian', 'nativeName' => 'Română' ],
'rm' => [ 'name' => 'Romansh', 'nativeName' => 'Rumantsch' ],
'ru' => [ 'name' => 'Russian', 'nativeName' => 'Русский' ],
'rw' => [ 'name' => 'Kinyarwanda', 'nativeName' => 'Ikinyarwanda' ],
'si' => [ 'name' => 'Sinhala', 'nativeName' => 'සිංහල' ],
'sk' => [ 'name' => 'Slovak', 'nativeName' => 'Slovenčina' ],
'sl' => [ 'name' => 'Slovenian', 'nativeName' => 'Slovensko' ],
'son' => [ 'name' => 'Songhai', 'nativeName' => 'Soŋay' ],
'sq' => [ 'name' => 'Albanian', 'nativeName' => 'Shqip' ],
'sr' => [ 'name' => 'Serbian', 'nativeName' => 'Српски' ],
'sr-Latn' => [ 'name' => 'Serbian', 'nativeName' => 'Srpski' ], // follows RFC 4646
'ss' => [ 'name' => 'Siswati', 'nativeName' => 'siSwati' ],
'st' => [ 'name' => 'Southern Sotho', 'nativeName' => 'Sesotho' ],
'sv' => [ 'name' => 'Swedish', 'nativeName' => 'Svenska' ],
'sv-SE' => [ 'name' => 'Swedish', 'nativeName' => 'Svenska' ],
'sw' => [ 'name' => 'Swahili', 'nativeName' => 'Swahili' ],
'ta' => [ 'name' => 'Tamil', 'nativeName' => 'தமிழ்' ],
'ta-IN' => [ 'name' => 'Tamil (India)', 'nativeName' => 'தமிழ் (இந்தியா)' ],
'ta-LK' => [ 'name' => 'Tamil (Sri Lanka)', 'nativeName' => 'தமிழ் (இலங்கை)' ],
'te' => [ 'name' => 'Telugu', 'nativeName' => 'తెలుగు' ],
'th' => [ 'name' => 'Thai', 'nativeName' => 'ไทย' ],
'tlh' => [ 'name' => 'Klingon', 'nativeName' => 'Klingon' ],
'tn' => [ 'name' => 'Tswana', 'nativeName' => 'Setswana' ],
'tr' => [ 'name' => 'Turkish', 'nativeName' => 'Türkçe' ],
'ts' => [ 'name' => 'Tsonga', 'nativeName' => 'Xitsonga' ],
'tt' => [ 'name' => 'Tatar', 'nativeName' => 'Tatarça' ],
'tt-RU' => [ 'name' => 'Tatar', 'nativeName' => 'Tatarça' ],
'uk' => [ 'name' => 'Ukrainian', 'nativeName' => 'Українська' ],
'ur' => [ 'name' => 'Urdu', 'nativeName' => 'اُردو', 'orientation' => 'rtl' ],
've' => [ 'name' => 'Venda', 'nativeName' => 'Tshivenḓa' ],
'vi' => [ 'name' => 'Vietnamese', 'nativeName' => 'Tiếng Việt' ],
'wo' => [ 'name' => 'Wolof', 'nativeName' => 'Wolof' ],
'xh' => [ 'name' => 'Xhosa', 'nativeName' => 'isiXhosa' ],
'yi' => [ 'name' => 'Yiddish', 'nativeName' => 'ייִדיש', 'orientation' => 'rtl' ],
'ydd' => [ 'name' => 'Yiddish', 'nativeName' => 'ייִדיש', 'orientation' => 'rtl' ],
'zh' => [ 'name' => 'Chinese (Simplified)', 'nativeName' => '中文 (简体)' ],
'zh-CN' => [ 'name' => 'Chinese (Simplified)', 'nativeName' => '中文 (简体)' ],
'zh-TW' => [ 'name' => 'Chinese (Traditional)', 'nativeName' => '正體中文 (繁體)' ],
'zu' => [ 'name' => 'Zulu', 'nativeName' => 'isiZulu' ]
];
/**
* @param string $code
* @return string|false
*/
public static function getName($code)
{
return static::get($code, 'name');
}
/**
* @param string $code
* @return string|false
*/
public static function getNativeName($code)
{
if (isset(static::$codes[$code])) {
return static::get($code, 'nativeName');
}
if (preg_match('/[a-zA-Z]{2}-[a-zA-Z]{2}/', $code)) {
return static::get(substr($code, 0, 2), 'nativeName') . ' (' . substr($code, -2) . ')';
}
return $code;
}
/**
* @param string $code
* @return string
*/
public static function getOrientation($code)
{
return static::$codes[$code]['orientation'] ?? 'ltr';
}
/**
* @param string $code
* @return bool
*/
public static function isRtl($code)
{
return static::getOrientation($code) === 'rtl';
}
/**
* @param array $keys
* @return array
*/
public static function getNames(array $keys)
{
$results = [];
foreach ($keys as $key) {
if (isset(static::$codes[$key])) {
$results[$key] = static::$codes[$key];
}
}
return $results;
}
/**
* @param string $code
* @param string $type
* @return string|false
*/
public static function get($code, $type)
{
return static::$codes[$code][$type] ?? false;
}
/**
* @param bool $native
* @return array
*/
public static function getList($native = true)
{
$list = [];
foreach (static::$codes as $key => $names) {
$list[$key] = $native ? $names['nativeName'] : $names['name'];
}
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/Language/Language.php | system/src/Grav/Common/Language/Language.php | <?php
/**
* @package Grav\Common\Language
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Language;
use Grav\Common\Debugger;
use Grav\Common\Grav;
use Grav\Common\Config\Config;
use Negotiation\AcceptLanguage;
use Negotiation\LanguageNegotiator;
use function array_key_exists;
use function count;
use function in_array;
use function is_array;
use function is_string;
/**
* Class Language
* @package Grav\Common\Language
*/
class Language
{
/** @var Grav */
protected $grav;
/** @var Config */
protected $config;
/** @var bool */
protected $enabled = true;
/** @var array */
protected $languages = [];
/** @var array */
protected $fallback_languages = [];
/** @var array */
protected $fallback_extensions = [];
/** @var array */
protected $page_extensions = [];
/** @var string|false */
protected $default;
/** @var string|false */
protected $active;
/** @var array */
protected $http_accept_language;
/** @var bool */
protected $lang_in_url = false;
/**
* Constructor
*
* @param Grav $grav
*/
public function __construct(Grav $grav)
{
$this->grav = $grav;
$this->config = $grav['config'];
$languages = $this->config->get('system.languages.supported', []);
foreach ($languages as &$language) {
$language = (string)$language;
}
unset($language);
$this->languages = $languages;
$this->init();
}
/**
* Initialize the default and enabled languages
*
* @return void
*/
public function init()
{
$default = $this->config->get('system.languages.default_lang');
if (null !== $default) {
$default = (string)$default;
}
// Note that reset returns false on empty languages.
$this->default = $default ?? reset($this->languages);
$this->resetFallbackPageExtensions();
if (empty($this->languages)) {
// If no languages are set, turn of multi-language support.
$this->enabled = false;
} elseif ($default && !in_array($default, $this->languages, true)) {
// If default language isn't in the language list, we need to add it.
array_unshift($this->languages, $default);
}
}
/**
* Ensure that languages are enabled
*
* @return bool
*/
public function enabled()
{
return $this->enabled;
}
/**
* Returns true if language debugging is turned on.
*
* @return bool
*/
public function isDebug(): bool
{
return !$this->config->get('system.languages.translations', true);
}
/**
* Gets the array of supported languages
*
* @return array
*/
public function getLanguages()
{
return $this->languages;
}
/**
* Sets the current supported languages manually
*
* @param array $langs
* @return void
*/
public function setLanguages($langs)
{
$this->languages = $langs;
$this->init();
}
/**
* Gets a pipe-separated string of available languages
*
* @param string|null $delimiter Delimiter to be quoted.
* @return string
*/
public function getAvailable($delimiter = null)
{
$languagesArray = $this->languages; //Make local copy
$languagesArray = array_map(static function ($value) use ($delimiter) {
return preg_quote($value, $delimiter);
}, $languagesArray);
sort($languagesArray);
return implode('|', array_reverse($languagesArray));
}
/**
* Gets language, active if set, else default
*
* @return string|false
*/
public function getLanguage()
{
return $this->active ?: $this->default;
}
/**
* Gets current default language
*
* @return string|false
*/
public function getDefault()
{
return $this->default;
}
/**
* Sets default language manually
*
* @param string $lang
* @return string|bool
*/
public function setDefault($lang)
{
$lang = (string)$lang;
if ($this->validate($lang)) {
$this->default = $lang;
return $lang;
}
return false;
}
/**
* Gets current active language
*
* @return string|false
*/
public function getActive()
{
return $this->active;
}
/**
* Sets active language manually
*
* @param string|false $lang
* @return string|false
*/
public function setActive($lang)
{
$lang = (string)$lang;
if ($this->validate($lang)) {
/** @var Debugger $debugger */
$debugger = $this->grav['debugger'];
$debugger->addMessage('Active language set to ' . $lang, 'debug');
$this->active = $lang;
return $lang;
}
return false;
}
/**
* Sets the active language based on the first part of the URL
*
* @param string $uri
* @return string
*/
public function setActiveFromUri($uri)
{
$regex = '/(^\/(' . $this->getAvailable() . '))(?:\/|\?|$)/i';
// if languages set
if ($this->enabled()) {
// Try setting language from prefix of URL (/en/blah/blah).
if (preg_match($regex, $uri, $matches)) {
$this->lang_in_url = true;
$this->setActive($matches[2]);
$uri = preg_replace("/\\" . $matches[1] . '/', '', $uri, 1);
// Store in session if language is different.
if (isset($this->grav['session']) && $this->grav['session']->isStarted()
&& $this->config->get('system.languages.session_store_active', true)
&& $this->grav['session']->active_language != $this->active
) {
$this->grav['session']->active_language = $this->active;
}
} else {
// Try getting language from the session, else no active.
if (isset($this->grav['session']) && $this->grav['session']->isStarted() &&
$this->config->get('system.languages.session_store_active', true)) {
$this->setActive($this->grav['session']->active_language ?: null);
}
// if still null, try from http_accept_language header
if ($this->active === null &&
$this->config->get('system.languages.http_accept_language') &&
$accept = $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? false) {
$negotiator = new LanguageNegotiator();
$best_language = $negotiator->getBest($accept, $this->languages);
if ($best_language instanceof AcceptLanguage) {
$this->setActive($best_language->getType());
} else {
$this->setActive($this->getDefault());
}
}
}
}
return $uri;
}
/**
* Get a URL prefix based on configuration
*
* @param string|null $lang
* @return string
*/
public function getLanguageURLPrefix($lang = null)
{
if (!$this->enabled()) {
return '';
}
// if active lang is not passed in, use current active
if (!$lang) {
$lang = $this->getLanguage();
}
return $this->isIncludeDefaultLanguage($lang) ? '/' . $lang : '';
}
/**
* Test to see if language is default and language should be included in the URL
*
* @param string|null $lang
* @return bool
*/
public function isIncludeDefaultLanguage($lang = null)
{
if (!$this->enabled()) {
return false;
}
// if active lang is not passed in, use current active
if (!$lang) {
$lang = $this->getLanguage();
}
return !($this->default === $lang && $this->config->get('system.languages.include_default_lang') === false);
}
/**
* Simple getter to tell if a language was found in the URL
*
* @return bool
*/
public function isLanguageInUrl()
{
return (bool) $this->lang_in_url;
}
/**
* Get full list of used language page extensions: [''=>'.md', 'en'=>'.en.md', ...]
*
* @param string|null $fileExtension
* @return array
*/
public function getPageExtensions($fileExtension = null)
{
$fileExtension = $fileExtension ?: CONTENT_EXT;
if (!isset($this->fallback_extensions[$fileExtension])) {
$extensions[''] = $fileExtension;
foreach ($this->languages as $code) {
$extensions[$code] = ".{$code}{$fileExtension}";
}
$this->fallback_extensions[$fileExtension] = $extensions;
}
return $this->fallback_extensions[$fileExtension];
}
/**
* Gets an array of valid extensions with active first, then fallback extensions
*
* @param string|null $fileExtension
* @param string|null $languageCode
* @param bool $assoc Return values in ['en' => '.en.md', ...] format.
* @return array Key is the language code, value is the file extension to be used.
*/
public function getFallbackPageExtensions(string $fileExtension = null, string $languageCode = null, bool $assoc = false)
{
$fileExtension = $fileExtension ?: CONTENT_EXT;
$key = $fileExtension . '-' . ($languageCode ?? 'default') . '-' . (int)$assoc;
if (!isset($this->fallback_extensions[$key])) {
$all = $this->getPageExtensions($fileExtension);
$list = [];
$fallback = $this->getFallbackLanguages($languageCode, true);
foreach ($fallback as $code) {
$ext = $all[$code] ?? null;
if (null !== $ext) {
$list[$code] = $ext;
}
}
if (!$assoc) {
$list = array_values($list);
}
$this->fallback_extensions[$key] = $list;
}
return $this->fallback_extensions[$key];
}
/**
* Resets the fallback_languages value.
*
* Useful to re-initialize the pages and change site language at runtime, example:
*
* ```
* $this->grav['language']->setActive('it');
* $this->grav['language']->resetFallbackPageExtensions();
* $this->grav['pages']->init();
* ```
*
* @return void
*/
public function resetFallbackPageExtensions()
{
$this->fallback_languages = [];
$this->fallback_extensions = [];
$this->page_extensions = [];
}
/**
* Gets an array of languages with active first, then fallback languages.
*
*
* @param string|null $languageCode
* @param bool $includeDefault If true, list contains '', which can be used for default
* @return array
*/
public function getFallbackLanguages(string $languageCode = null, bool $includeDefault = false)
{
// Handle default.
if ($languageCode === '' || !$this->enabled()) {
return [''];
}
$default = $this->getDefault() ?? 'en';
$active = $languageCode ?? $this->getActive() ?? $default;
$key = $active . '-' . (int)$includeDefault;
if (!isset($this->fallback_languages[$key])) {
$fallback = $this->config->get('system.languages.content_fallback.' . $active);
$fallback_languages = [];
if (null === $fallback && $this->config->get('system.languages.pages_fallback_only', false)) {
user_error('Configuration option `system.languages.pages_fallback_only` is deprecated since Grav 1.7, use `system.languages.content_fallback` instead', E_USER_DEPRECATED);
// Special fallback list returns itself and all the previous items in reverse order:
// active: 'v2', languages: ['v1', 'v2', 'v3', 'v4'] => ['v2', 'v1', '']
if ($includeDefault) {
$fallback_languages[''] = '';
}
foreach ($this->languages as $code) {
$fallback_languages[$code] = $code;
if ($code === $active) {
break;
}
}
$fallback_languages = array_reverse($fallback_languages);
} else {
if (null === $fallback) {
$fallback = [$default];
} elseif (!is_array($fallback)) {
$fallback = is_string($fallback) && $fallback !== '' ? explode(',', $fallback) : [];
}
array_unshift($fallback, $active);
$fallback = array_unique($fallback);
foreach ($fallback as $code) {
// Default fallback list has active language followed by default language and extensionless file:
// active: 'fi', default: 'en', languages: ['sv', 'en', 'de', 'fi'] => ['fi', 'en', '']
$fallback_languages[$code] = $code;
if ($includeDefault && $code === $default) {
$fallback_languages[''] = '';
}
}
}
$fallback_languages = array_values($fallback_languages);
$this->fallback_languages[$key] = $fallback_languages;
}
return $this->fallback_languages[$key];
}
/**
* Ensures the language is valid and supported
*
* @param string $lang
* @return bool
*/
public function validate($lang)
{
return in_array($lang, $this->languages, true);
}
/**
* Translate a key and possibly arguments into a string using current lang and fallbacks
*
* @param string|array $args The first argument is the lookup key value
* Other arguments can be passed and replaced in the translation with sprintf syntax
* @param array|null $languages
* @param bool $array_support
* @param bool $html_out
* @return string|string[]
*/
public function translate($args, array $languages = null, $array_support = false, $html_out = false)
{
if (is_array($args)) {
$lookup = array_shift($args);
} else {
$lookup = $args;
$args = [];
}
if (!$this->isDebug()) {
if ($lookup && $this->enabled() && empty($languages)) {
$languages = $this->getTranslatedLanguages();
}
$languages = $languages ?: ['en'];
foreach ((array)$languages as $lang) {
$translation = $this->getTranslation($lang, $lookup, $array_support);
if ($translation) {
if (is_string($translation) && count($args) >= 1) {
return vsprintf($translation, $args);
}
return $translation;
}
}
} elseif ($array_support) {
return [$lookup];
}
if ($html_out) {
return '<span class="untranslated">' . $lookup . '</span>';
}
return $lookup;
}
/**
* Translate Array
*
* @param string $key
* @param string $index
* @param array|null $languages
* @param bool $html_out
* @return string
*/
public function translateArray($key, $index, $languages = null, $html_out = false)
{
if ($this->isDebug()) {
return $key . '[' . $index . ']';
}
if ($key && empty($languages) && $this->enabled()) {
$languages = $this->getTranslatedLanguages();
}
$languages = $languages ?: ['en'];
foreach ((array)$languages as $lang) {
$translation_array = (array)Grav::instance()['languages']->get($lang . '.' . $key, null);
if ($translation_array && array_key_exists($index, $translation_array)) {
return $translation_array[$index];
}
}
if ($html_out) {
return '<span class="untranslated">' . $key . '[' . $index . ']</span>';
}
return $key . '[' . $index . ']';
}
/**
* Lookup the translation text for a given lang and key
*
* @param string $lang lang code
* @param string $key key to lookup with
* @param bool $array_support
* @return string|string[]
*/
public function getTranslation($lang, $key, $array_support = false)
{
if ($this->isDebug()) {
return $key;
}
$translation = Grav::instance()['languages']->get($lang . '.' . $key, null);
if (!$array_support && is_array($translation)) {
return (string)array_shift($translation);
}
return $translation;
}
/**
* Get the browser accepted languages
*
* @param array $accept_langs
* @return array
* @deprecated 1.6 No longer used - using content negotiation.
*/
public function getBrowserLanguages($accept_langs = [])
{
user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, no longer used', E_USER_DEPRECATED);
if (empty($this->http_accept_language)) {
if (empty($accept_langs) && isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
$accept_langs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
} else {
return $accept_langs;
}
$langs = [];
foreach (explode(',', $accept_langs) as $k => $pref) {
// split $pref again by ';q='
// and decorate the language entries by inverted position
if (false !== ($i = strpos($pref, ';q='))) {
$langs[substr($pref, 0, $i)] = [(float)substr($pref, $i + 3), -$k];
} else {
$langs[$pref] = [1, -$k];
}
}
arsort($langs);
// no need to undecorate, because we're only interested in the keys
$this->http_accept_language = array_keys($langs);
}
return $this->http_accept_language;
}
/**
* Accessible wrapper to LanguageCodes
*
* @param string $code
* @param string $type
* @return string|false
*/
public function getLanguageCode($code, $type = 'name')
{
return LanguageCodes::get($code, $type);
}
/**
* @return array
*/
#[\ReturnTypeWillChange]
public function __debugInfo()
{
$vars = get_object_vars($this);
unset($vars['grav'], $vars['config']);
return $vars;
}
/**
* @return array
*/
protected function getTranslatedLanguages(): array
{
if ($this->config->get('system.languages.translations_fallback', true)) {
$languages = $this->getFallbackLanguages();
} else {
$languages = [$this->getLanguage()];
}
$languages[] = 'en';
return array_values(array_unique($languages));
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Flex/FlexIndex.php | system/src/Grav/Common/Flex/FlexIndex.php | <?php
declare(strict_types=1);
/**
* @package Grav\Common\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Flex;
use Grav\Common\Flex\Traits\FlexGravTrait;
use Grav\Common\Flex\Traits\FlexIndexTrait;
/**
* Class FlexIndex
*
* @package Grav\Common\Flex
* @template T of \Grav\Framework\Flex\Interfaces\FlexObjectInterface
* @template C of \Grav\Framework\Flex\Interfaces\FlexCollectionInterface
* @extends \Grav\Framework\Flex\FlexIndex<T,C>
*/
abstract class FlexIndex extends \Grav\Framework\Flex\FlexIndex
{
use FlexGravTrait;
use FlexIndexTrait;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Flex/FlexCollection.php | system/src/Grav/Common/Flex/FlexCollection.php | <?php
declare(strict_types=1);
/**
* @package Grav\Common\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Flex;
use Grav\Common\Flex\Traits\FlexCollectionTrait;
use Grav\Common\Flex\Traits\FlexGravTrait;
/**
* Class FlexCollection
*
* @package Grav\Common\Flex
* @template T of \Grav\Framework\Flex\Interfaces\FlexObjectInterface
* @extends \Grav\Framework\Flex\FlexCollection<T>
*/
abstract class FlexCollection extends \Grav\Framework\Flex\FlexCollection
{
use FlexGravTrait;
use FlexCollectionTrait;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Flex/FlexObject.php | system/src/Grav/Common/Flex/FlexObject.php | <?php
declare(strict_types=1);
/**
* @package Grav\Common\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Flex;
use Grav\Common\Flex\Traits\FlexGravTrait;
use Grav\Common\Flex\Traits\FlexObjectTrait;
use Grav\Common\Media\Interfaces\MediaInterface;
use Grav\Framework\Flex\Traits\FlexMediaTrait;
use function is_array;
/**
* Class FlexObject
*
* @package Grav\Common\Flex
*/
abstract class FlexObject extends \Grav\Framework\Flex\FlexObject implements MediaInterface
{
use FlexGravTrait;
use FlexObjectTrait;
use FlexMediaTrait;
/**
* {@inheritdoc}
* @see FlexObjectInterface::getFormValue()
*/
public function getFormValue(string $name, $default = null, string $separator = null)
{
$value = $this->getNestedProperty($name, null, $separator);
// Handle media order field.
if (null === $value && $name === 'media_order') {
return implode(',', $this->getMediaOrder());
}
// Handle media fields.
$settings = $this->getFieldSettings($name);
if (($settings['media_field'] ?? false) === true) {
return $this->parseFileProperty($value, $settings);
}
return $value ?? $default;
}
/**
* {@inheritdoc}
* @see FlexObjectInterface::prepareStorage()
*/
public function prepareStorage(): array
{
// Remove extra content from media fields.
$fields = $this->getMediaFields();
foreach ($fields as $field) {
$data = $this->getNestedProperty($field);
if (is_array($data)) {
foreach ($data as $name => &$image) {
unset($image['image_url'], $image['thumb_url']);
}
unset($image);
$this->setNestedProperty($field, $data);
}
}
return parent::prepareStorage();
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Flex/Types/Users/UserObject.php | system/src/Grav/Common/Flex/Types/Users/UserObject.php | <?php
declare(strict_types=1);
/**
* @package Grav\Common\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Flex\Types\Users;
use Closure;
use Countable;
use Grav\Common\Config\Config;
use Grav\Common\Data\Blueprint;
use Grav\Common\Flex\FlexObject;
use Grav\Common\Flex\Traits\FlexGravTrait;
use Grav\Common\Flex\Traits\FlexObjectTrait;
use Grav\Common\Flex\Types\Users\Traits\UserObjectLegacyTrait;
use Grav\Common\Grav;
use Grav\Common\Media\Interfaces\MediaCollectionInterface;
use Grav\Common\Media\Interfaces\MediaUploadInterface;
use Grav\Common\Page\Media;
use Grav\Common\Page\Medium\MediumFactory;
use Grav\Common\User\Access;
use Grav\Common\User\Authentication;
use Grav\Common\Flex\Types\UserGroups\UserGroupCollection;
use Grav\Common\Flex\Types\UserGroups\UserGroupIndex;
use Grav\Common\User\Interfaces\UserInterface;
use Grav\Common\User\Traits\UserTrait;
use Grav\Common\Utils;
use Grav\Framework\Contracts\Relationships\ToOneRelationshipInterface;
use Grav\Framework\File\Formatter\JsonFormatter;
use Grav\Framework\File\Formatter\YamlFormatter;
use Grav\Framework\Filesystem\Filesystem;
use Grav\Framework\Flex\Flex;
use Grav\Framework\Flex\FlexDirectory;
use Grav\Framework\Flex\Storage\FileStorage;
use Grav\Framework\Flex\Traits\FlexMediaTrait;
use Grav\Framework\Flex\Traits\FlexRelationshipsTrait;
use Grav\Framework\Form\FormFlashFile;
use Grav\Framework\Media\MediaIdentifier;
use Grav\Framework\Media\UploadedMediaObject;
use Psr\Http\Message\UploadedFileInterface;
use RocketTheme\Toolbox\Event\Event;
use RocketTheme\Toolbox\File\FileInterface;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use RuntimeException;
use function is_array;
use function is_bool;
use function is_object;
/**
* Flex User
*
* Flex User is mostly compatible with the older User class, except on few key areas:
*
* - Constructor parameters have been changed. Old code creating a new user does not work.
* - Serializer has been changed -- existing sessions will be killed.
*
* @package Grav\Common\User
*
* @property string $username
* @property string $email
* @property string $fullname
* @property string $state
* @property array $groups
* @property array $access
* @property bool $authenticated
* @property bool $authorized
*/
class UserObject extends FlexObject implements UserInterface, Countable
{
use FlexGravTrait;
use FlexObjectTrait;
use FlexMediaTrait {
getMedia as private getFlexMedia;
getMediaFolder as private getFlexMediaFolder;
}
use UserTrait;
use UserObjectLegacyTrait;
use FlexRelationshipsTrait;
/** @var Closure|null */
static public $authorizeCallable;
/** @var Closure|null */
static public $isAuthorizedCallable;
/** @var array|null */
protected $_uploads_original;
/** @var FileInterface|null */
protected $_storage;
/** @var UserGroupIndex */
protected $_groups;
/** @var Access */
protected $_access;
/** @var array|null */
protected $access;
/**
* @return array
*/
public static function getCachedMethods(): array
{
return [
'authorize' => 'session',
'load' => false,
'find' => false,
'remove' => false,
'get' => true,
'set' => false,
'undef' => false,
'def' => false,
] + parent::getCachedMethods();
}
/**
* UserObject constructor.
* @param array $elements
* @param string $key
* @param FlexDirectory $directory
* @param bool $validate
*/
public function __construct(array $elements, $key, FlexDirectory $directory, bool $validate = false)
{
// User can only be authenticated via login.
unset($elements['authenticated'], $elements['authorized']);
// Define username if it's not set.
if (!isset($elements['username'])) {
$storageKey = $elements['__META']['storage_key'] ?? null;
$storage = $directory->getStorage();
if (null !== $storageKey && method_exists($storage, 'normalizeKey') && $key === $storage->normalizeKey($storageKey)) {
$elements['username'] = $storageKey;
} else {
$elements['username'] = $key;
}
}
// Define state if it isn't set.
if (!isset($elements['state'])) {
$elements['state'] = 'enabled';
}
parent::__construct($elements, $key, $directory, $validate);
}
public function __clone()
{
$this->_access = null;
$this->_groups = null;
parent::__clone();
}
/**
* @return void
*/
public function onPrepareRegistration(): void
{
if (!$this->getProperty('access')) {
/** @var Config $config */
$config = Grav::instance()['config'];
$groups = $config->get('plugins.login.user_registration.groups', '');
$access = $config->get('plugins.login.user_registration.access', ['site' => ['login' => true]]);
$this->setProperty('groups', $groups);
$this->setProperty('access', $access);
}
}
/**
* Helper to get content editor will fall back if not set
*
* @return string
*/
public function getContentEditor(): string
{
return $this->getProperty('content_editor', 'default');
}
/**
* 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)
{
return $this->getNestedProperty($name, $default, $separator);
}
/**
* 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)
{
$this->setNestedProperty($name, $value, $separator);
return $this;
}
/**
* 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)
{
$this->unsetNestedProperty($name, $separator);
return $this;
}
/**
* 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)
{
$this->defNestedProperty($name, $default, $separator);
return $this;
}
/**
* @param UserInterface|null $user
* @return bool
*/
public function isMyself(?UserInterface $user = null): bool
{
if (null === $user) {
$user = $this->getActiveUser();
if ($user && !$user->authenticated) {
$user = null;
}
}
return $user && $this->username === $user->username;
}
/**
* 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
{
if ($scope === 'test') {
// Special scope to test user permissions.
$scope = null;
} else {
// User needs to be enabled.
if ($this->getProperty('state') !== 'enabled') {
return false;
}
// User needs to be logged in.
if (!$this->getProperty('authenticated')) {
return false;
}
if (strpos($action, 'login') === false && !$this->getProperty('authorized')) {
// User needs to be authorized (2FA).
return false;
}
// Workaround bug in Login::isUserAuthorizedForPage() <= Login v3.0.4
if ((string)(int)$action === $action) {
return false;
}
}
// Check custom application access.
$authorizeCallable = static::$authorizeCallable;
if ($authorizeCallable instanceof Closure) {
$callable = $authorizeCallable->bindTo($this, $this);
$authorized = $callable($action, $scope);
if (is_bool($authorized)) {
return $authorized;
}
}
// Check user access.
$access = $this->getAccess();
$authorized = $access->authorize($action, $scope);
if (is_bool($authorized)) {
return $authorized;
}
// Check group access.
$authorized = $this->getGroups()->authorize($action, $scope);
if (is_bool($authorized)) {
return $authorized;
}
// If any specific rule isn't hit, check if user is a superuser.
return $access->authorize('admin.super') === true;
}
/**
* @param string $property
* @param mixed $default
* @return mixed
*/
public function getProperty($property, $default = null)
{
$value = parent::getProperty($property, $default);
if ($property === 'avatar') {
$settings = $this->getMediaFieldSettings($property);
$value = $this->parseFileProperty($value, $settings);
}
return $value;
}
/**
* @return UserGroupIndex
*/
public function getRoles(): UserGroupIndex
{
return $this->getGroups();
}
/**
* Convert object into an array.
*
* @return array
*/
public function toArray()
{
$array = $this->jsonSerialize();
$settings = $this->getMediaFieldSettings('avatar');
$array['avatar'] = $this->parseFileProperty($array['avatar'] ?? null, $settings);
return $array;
}
/**
* Convert object into YAML string.
*
* @param int $inline The level where you switch to inline YAML.
* @param int $indent The amount of spaces to use for indentation of nested nodes.
* @return string A YAML string representing the object.
*/
public function toYaml($inline = 5, $indent = 2)
{
$yaml = new YamlFormatter(['inline' => $inline, 'indent' => $indent]);
return $yaml->encode($this->toArray());
}
/**
* Convert object into JSON string.
*
* @return string
*/
public function toJson()
{
$json = new JsonFormatter();
return $json->encode($this->toArray());
}
/**
* 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|null $separator Separator, defaults to '.'
* @return $this
* @throws RuntimeException
*/
public function join($name, $value, $separator = null)
{
$separator = $separator ?? '.';
$old = $this->get($name, null, $separator);
if ($old !== null) {
if (!is_array($old)) {
throw new RuntimeException('Value ' . $old);
}
if (is_object($value)) {
$value = (array) $value;
} elseif (!is_array($value)) {
throw new RuntimeException('Value ' . $value);
}
$value = $this->getBlueprint()->mergeData($old, $value, $name, $separator);
}
$this->set($name, $value, $separator);
return $this;
}
/**
* Get nested structure containing default values defined in the blueprints.
*
* Fields without default value are ignored in the list.
* @return array
*/
public function getDefaults()
{
return $this->getBlueprint()->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|null $separator Separator, defaults to '.'
* @return $this
*/
public function joinDefaults($name, $value, $separator = null)
{
if (is_object($value)) {
$value = (array) $value;
}
$old = $this->get($name, null, $separator);
if ($old !== null) {
$value = $this->getBlueprint()->mergeData($value, $old, $name, $separator ?? '.');
}
$this->setNestedProperty($name, $value, $separator);
return $this;
}
/**
* 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 = null)
{
if (is_object($value)) {
$value = (array) $value;
} elseif (!is_array($value)) {
throw new RuntimeException('Value ' . $value);
}
$old = $this->get($name, null, $separator);
if ($old === null) {
// No value set; no need to join data.
return $value;
}
if (!is_array($old)) {
throw new RuntimeException('Value ' . $old);
}
// Return joined data.
return $this->getBlueprint()->mergeData($old, $value, $name, $separator ?? '.');
}
/**
* Set default values to the configuration if variables were not set.
*
* @param array $data
* @return $this
*/
public function setDefaults(array $data)
{
$this->setElements($this->getBlueprint()->mergeData($data, $this->toArray()));
return $this;
}
/**
* Validate by blueprints.
*
* @return $this
* @throws \Exception
*/
public function validate()
{
$this->getBlueprint()->validate($this->toArray());
return $this;
}
/**
* Filter all items by using blueprints.
* @return $this
*/
public function filter()
{
$this->setElements($this->getBlueprint()->filter($this->toArray()));
return $this;
}
/**
* Get extra items which haven't been defined in blueprints.
*
* @return array
*/
public function extra()
{
return $this->getBlueprint()->extra($this->toArray());
}
/**
* Return unmodified data as raw string.
*
* NOTE: This function only returns data which has been saved to the storage.
*
* @return string
*/
public function raw()
{
$file = $this->file();
return $file ? $file->raw() : '';
}
/**
* Set or get the data storage.
*
* @param FileInterface|null $storage Optionally enter a new storage.
* @return FileInterface|null
*/
public function file(FileInterface $storage = null)
{
if (null !== $storage) {
$this->_storage = $storage;
}
return $this->_storage;
}
/**
* @return bool
*/
public function isValid(): bool
{
return $this->getProperty('state') !== null;
}
/**
* Save user
*
* @return static
*/
public function save()
{
// TODO: We may want to handle this in the storage layer in the future.
$key = $this->getStorageKey();
if (!$key || strpos($key, '@@')) {
$storage = $this->getFlexDirectory()->getStorage();
if ($storage instanceof FileStorage) {
$this->setStorageKey($this->getKey());
}
}
$password = $this->getProperty('password') ?? $this->getProperty('password1');
if (null !== $password && '' !== $password) {
$password2 = $this->getProperty('password2');
if (!\is_string($password) || ($password2 && $password !== $password2)) {
throw new \RuntimeException('Passwords did not match.');
}
$this->setProperty('hashed_password', Authentication::create($password));
}
$this->unsetProperty('password');
$this->unsetProperty('password1');
$this->unsetProperty('password2');
// Backwards compatibility with older plugins.
$fireEvents = $this->isAdminSite() && $this->getFlexDirectory()->getConfig('object.compat.events', true);
$grav = $this->getContainer();
if ($fireEvents) {
$self = $this;
$grav->fireEvent('onAdminSave', new Event(['type' => 'flex', 'directory' => $this->getFlexDirectory(), 'object' => &$self]));
if ($self !== $this) {
throw new RuntimeException('Switching Flex User object during onAdminSave event is not supported! Please update plugin.');
}
}
$instance = parent::save();
// Backwards compatibility with older plugins.
if ($fireEvents) {
$grav->fireEvent('onAdminAfterSave', new Event(['type' => 'flex', 'directory' => $this->getFlexDirectory(), 'object' => $this]));
}
return $instance;
}
/**
* @return array
*/
public function prepareStorage(): array
{
$elements = parent::prepareStorage();
// Do not save authorization information.
unset($elements['authenticated'], $elements['authorized']);
return $elements;
}
/**
* @return MediaCollectionInterface
*/
public function getMedia()
{
/** @var Media $media */
$media = $this->getFlexMedia();
// Deal with shared avatar folder.
$path = $this->getAvatarFile();
if ($path && !$media[$path] && is_file($path)) {
$medium = MediumFactory::fromFile($path);
if ($medium) {
$media->add($path, $medium);
$name = Utils::basename($path);
if ($name !== $path) {
$media->add($name, $medium);
}
}
}
return $media;
}
/**
* @return string|null
*/
public function getMediaFolder(): ?string
{
$folder = $this->getFlexMediaFolder();
// Check for shared media
if (!$folder && !$this->getFlexDirectory()->getMediaFolder()) {
$this->_loadMedia = false;
$folder = $this->getBlueprint()->fields()['avatar']['destination'] ?? 'account://avatars';
}
return $folder;
}
/**
* @param string $name
* @return array|object|null
* @internal
*/
public function initRelationship(string $name)
{
switch ($name) {
case 'media':
$list = [];
foreach ($this->getMedia()->all() as $filename => $object) {
$list[] = $this->buildMediaObject(null, $filename, $object);
}
return $list;
case 'avatar':
return $this->buildMediaObject('avatar', basename($this->getAvatarUrl()), $this->getAvatarImage());
}
throw new \InvalidArgumentException(sprintf('%s: Relationship %s does not exist', $this->getFlexType(), $name));
}
/**
* @return bool Return true if relationships were updated.
*/
protected function updateRelationships(): bool
{
$modified = $this->getRelationships()->getModified();
if ($modified) {
foreach ($modified as $relationship) {
$name = $relationship->getName();
switch ($name) {
case 'avatar':
\assert($relationship instanceof ToOneRelationshipInterface);
$this->updateAvatarRelationship($relationship);
break;
default:
throw new \InvalidArgumentException(sprintf('%s: Relationship %s cannot be modified', $this->getFlexType(), $name), 400);
}
}
$this->resetRelationships();
return true;
}
return false;
}
/**
* @param ToOneRelationshipInterface $relationship
*/
protected function updateAvatarRelationship(ToOneRelationshipInterface $relationship): void
{
$files = [];
$avatar = $this->getAvatarImage();
if ($avatar) {
$files['avatar'][$avatar->filename] = null;
}
$identifier = $relationship->getIdentifier();
if ($identifier) {
\assert($identifier instanceof MediaIdentifier);
$object = $identifier->getObject();
if ($object instanceof UploadedMediaObject) {
$uploadedFile = $object->getUploadedFile();
if ($uploadedFile) {
$files['avatar'][$uploadedFile->getClientFilename()] = $uploadedFile;
}
}
}
$this->update([], $files);
}
/**
* @param string $name
* @return Blueprint
*/
protected function doGetBlueprint(string $name = ''): Blueprint
{
$blueprint = $this->getFlexDirectory()->getBlueprint($name ? '.' . $name : $name);
// HACK: With folder storage we need to ignore the avatar destination.
if ($this->getFlexDirectory()->getMediaFolder()) {
$field = $blueprint->get('form/fields/avatar');
if ($field) {
unset($field['destination']);
$blueprint->set('form/fields/avatar', $field);
}
}
return $blueprint;
}
/**
* @param UserInterface $user
* @param string $action
* @param string $scope
* @param bool $isMe
* @return bool|null
*/
protected function isAuthorizedOverride(UserInterface $user, string $action, string $scope, bool $isMe = false): ?bool
{
// Check custom application access.
$isAuthorizedCallable = static::$isAuthorizedCallable;
if ($isAuthorizedCallable instanceof Closure) {
$callable = $isAuthorizedCallable->bindTo($this, $this);
$authorized = $callable($user, $action, $scope, $isMe);
if (is_bool($authorized)) {
return $authorized;
}
}
if ($user instanceof self && $user->getStorageKey() === $this->getStorageKey()) {
// User cannot delete his own account, otherwise he has full access.
return $action !== 'delete';
}
return parent::isAuthorizedOverride($user, $action, $scope, $isMe);
}
/**
* @return string|null
*/
protected function getAvatarFile(): ?string
{
$avatars = $this->getElement('avatar');
if (is_array($avatars) && $avatars) {
$avatar = array_shift($avatars);
return $avatar['path'] ?? null;
}
return null;
}
/**
* Gets the associated media collection (original images).
*
* @return MediaCollectionInterface Representation of associated media.
*/
protected function getOriginalMedia()
{
$folder = $this->getMediaFolder();
if ($folder) {
$folder .= '/original';
}
return (new Media($folder ?? '', $this->getMediaOrder()))->setTimestamps();
}
/**
* @param array $files
* @return void
*/
protected function setUpdatedMedia(array $files): void
{
/** @var UniformResourceLocator $locator */
$locator = Grav::instance()['locator'];
$media = $this->getMedia();
if (!$media instanceof MediaUploadInterface) {
return;
}
$filesystem = Filesystem::getInstance(false);
$list = [];
$list_original = [];
foreach ($files as $field => $group) {
// Ignore files without a field.
if ($field === '') {
continue;
}
$field = (string)$field;
// Load settings for the field.
$settings = $this->getMediaFieldSettings($field);
foreach ($group as $filename => $file) {
if ($file) {
// File upload.
$filename = $file->getClientFilename();
/** @var FormFlashFile $file */
$data = $file->jsonSerialize();
unset($data['tmp_name'], $data['path']);
} else {
// File delete.
$data = null;
}
if ($file) {
// Check file upload against media limits (except for max size).
$filename = $media->checkUploadedFile($file, $filename, ['filesize' => 0] + $settings);
}
$self = $settings['self'];
if ($this->_loadMedia && $self) {
$filepath = $filename;
} else {
$filepath = "{$settings['destination']}/{$filename}";
// For backwards compatibility we are always using relative path from the installation root.
if ($locator->isStream($filepath)) {
$filepath = $locator->findResource($filepath, false, true);
}
}
// Special handling for original images.
if (strpos($field, '/original')) {
if ($this->_loadMedia && $self) {
$list_original[$filename] = [$file, $settings];
}
continue;
}
// Calculate path without the retina scaling factor.
$realpath = $filesystem->pathname($filepath) . str_replace(['@3x', '@2x'], '', Utils::basename($filepath));
$list[$filename] = [$file, $settings];
$path = str_replace('.', "\n", $field);
if (null !== $data) {
$data['name'] = $filename;
$data['path'] = $filepath;
$this->setNestedProperty("{$path}\n{$realpath}", $data, "\n");
} else {
$this->unsetNestedProperty("{$path}\n{$realpath}", "\n");
}
}
}
$this->clearMediaCache();
$this->_uploads = $list;
$this->_uploads_original = $list_original;
}
protected function saveUpdatedMedia(): void
{
$media = $this->getMedia();
if (!$media instanceof MediaUploadInterface) {
throw new RuntimeException('Internal error UO101');
}
// Upload/delete original sized images.
/**
* @var string $filename
* @var UploadedFileInterface|array|null $file
*/
foreach ($this->_uploads_original ?? [] as $filename => $file) {
$filename = 'original/' . $filename;
if (is_array($file)) {
[$file, $settings] = $file;
} else {
$settings = null;
}
if ($file instanceof UploadedFileInterface) {
$media->copyUploadedFile($file, $filename, $settings);
} else {
$media->deleteFile($filename, $settings);
}
}
// Upload/delete altered files.
/**
* @var string $filename
* @var UploadedFileInterface|array|null $file
*/
foreach ($this->getUpdatedMedia() as $filename => $file) {
if (is_array($file)) {
[$file, $settings] = $file;
} else {
$settings = null;
}
if ($file instanceof UploadedFileInterface) {
$media->copyUploadedFile($file, $filename, $settings);
} else {
$media->deleteFile($filename, $settings);
}
}
$this->setUpdatedMedia([]);
$this->clearMediaCache();
}
/**
* @return array
*/
protected function doSerialize(): array
{
return [
'type' => $this->getFlexType(),
'key' => $this->getKey(),
'elements' => $this->jsonSerialize(),
'storage' => $this->getMetaData()
];
}
/**
* @return UserGroupIndex
*/
protected function getUserGroups()
{
$grav = Grav::instance();
/** @var Flex $flex */
$flex = $grav['flex'];
/** @var UserGroupCollection|null $groups */
$groups = $flex->getDirectory('user-groups');
if ($groups) {
/** @var UserGroupIndex $index */
$index = $groups->getIndex();
return $index;
}
return $grav['user_groups'];
}
/**
* @return UserGroupIndex
*/
protected function getGroups()
{
if (null === $this->_groups) {
/** @var UserGroupIndex $groups */
$groups = $this->getUserGroups()->select((array)$this->getProperty('groups'));
$this->_groups = $groups;
}
return $this->_groups;
}
/**
* @return Access
*/
protected function getAccess(): Access
{
if (null === $this->_access) {
$this->_access = new Access($this->getProperty('access'));
}
return $this->_access;
}
/**
* @param mixed $value
* @return array
*/
protected function offsetLoad_access($value): array
{
if (!$value instanceof Access) {
$value = new Access($value);
}
return $value->jsonSerialize();
}
/**
* @param mixed $value
* @return array
*/
protected function offsetPrepare_access($value): array
{
return $this->offsetLoad_access($value);
}
/**
* @param array|null $value
* @return array|null
*/
protected function offsetSerialize_access(?array $value): ?array
{
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/Flex/Types/Users/UserCollection.php | system/src/Grav/Common/Flex/Types/Users/UserCollection.php | <?php
declare(strict_types=1);
/**
* @package Grav\Common\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Flex\Types\Users;
use Grav\Common\Flex\FlexCollection;
use Grav\Common\User\Interfaces\UserCollectionInterface;
use Grav\Common\User\Interfaces\UserInterface;
use function is_string;
/**
* Class UserCollection
* @package Grav\Common\Flex\Types\Users
*
* @extends FlexCollection<UserObject>
*/
class UserCollection extends FlexCollection implements UserCollectionInterface
{
/**
* @return array
*/
public static function getCachedMethods(): array
{
return [
'authorize' => 'session',
] + parent::getCachedMethods();
}
/**
* Load user account.
*
* Always creates user object. To check if user exists, use $this->exists().
*
* @param string $username
* @return UserObject
*/
public function load($username): UserInterface
{
$username = (string)$username;
if ($username !== '') {
$key = $this->filterUsername($username);
$user = $this->get($key);
if ($user) {
return $user;
}
} else {
$key = '';
}
$directory = $this->getFlexDirectory();
/** @var UserObject $object */
$object = $directory->createObject(
[
'username' => $username,
'state' => 'enabled'
],
$key
);
return $object;
}
/**
* Find a user by username, email, etc
*
* @param string $query the query to search for
* @param string|string[] $fields the fields to search
* @return UserObject
*/
public function find($query, $fields = ['username', 'email']): UserInterface
{
if (is_string($query) && $query !== '') {
foreach ((array)$fields as $field) {
if ($field === 'key') {
$user = $this->get($query);
} elseif ($field === 'storage_key') {
$user = $this->withKeyField('storage_key')->get($query);
} elseif ($field === 'flex_key') {
$user = $this->withKeyField('flex_key')->get($query);
} elseif ($field === 'username') {
$user = $this->get($this->filterUsername($query));
} else {
$user = parent::find($query, $field);
}
if ($user instanceof UserObject) {
return $user;
}
}
}
return $this->load('');
}
/**
* Delete user account.
*
* @param string $username
* @return bool True if user account was found and was deleted.
*/
public function delete($username): bool
{
$user = $this->load($username);
$exists = $user->exists();
if ($exists) {
$user->delete();
}
return $exists;
}
/**
* @param string $key
* @return string
*/
protected function filterUsername(string $key): string
{
$storage = $this->getFlexDirectory()->getStorage();
if (method_exists($storage, 'normalizeKey')) {
return $storage->normalizeKey($key);
}
return mb_strtolower($key);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Flex/Types/Users/UserIndex.php | system/src/Grav/Common/Flex/Types/Users/UserIndex.php | <?php
declare(strict_types=1);
/**
* @package Grav\Common\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Flex\Types\Users;
use Grav\Common\Debugger;
use Grav\Common\File\CompiledYamlFile;
use Grav\Common\Flex\FlexIndex;
use Grav\Common\Grav;
use Grav\Common\User\Interfaces\UserCollectionInterface;
use Grav\Common\User\Interfaces\UserInterface;
use Grav\Framework\Flex\Interfaces\FlexStorageInterface;
use Monolog\Logger;
use function count;
use function is_string;
/**
* Class UserIndex
* @package Grav\Common\Flex\Types\Users
*
* @extends FlexIndex<UserObject,UserCollection>
*/
class UserIndex extends FlexIndex implements UserCollectionInterface
{
public const VERSION = parent::VERSION . '.2';
/**
* @param FlexStorageInterface $storage
* @return array
*/
public static function loadEntriesFromStorage(FlexStorageInterface $storage): array
{
// Load saved index.
$index = static::loadIndex($storage);
$version = $index['version'] ?? 0;
$force = static::VERSION !== $version;
// TODO: Following check flex index to be out of sync after some saves, disabled until better solution is found.
//$timestamp = $index['timestamp'] ?? 0;
//if (!$force && $timestamp && $timestamp > time() - 1) {
// return $index['index'];
//}
// Load up-to-date index.
$entries = parent::loadEntriesFromStorage($storage);
return static::updateIndexFile($storage, $index['index'], $entries, ['force_update' => $force]);
}
/**
* @param array $meta
* @param array $data
* @param FlexStorageInterface $storage
* @return void
*/
public static function updateObjectMeta(array &$meta, array $data, FlexStorageInterface $storage): void
{
// Username can also be number and stored as such.
$key = (string)($data['username'] ?? $meta['key'] ?? $meta['storage_key']);
$meta['key'] = static::filterUsername($key, $storage);
$meta['email'] = isset($data['email']) ? mb_strtolower($data['email']) : null;
}
/**
* Load user account.
*
* Always creates user object. To check if user exists, use $this->exists().
*
* @param string $username
* @return UserObject
*/
public function load($username): UserInterface
{
$username = (string)$username;
if ($username !== '') {
$key = static::filterUsername($username, $this->getFlexDirectory()->getStorage());
$user = $this->get($key);
if ($user) {
return $user;
}
} else {
$key = '';
}
$directory = $this->getFlexDirectory();
/** @var UserObject $object */
$object = $directory->createObject(
[
'username' => $username,
'state' => 'enabled'
],
$key
);
return $object;
}
/**
* Delete user account.
*
* @param string $username
* @return bool True if user account was found and was deleted.
*/
public function delete($username): bool
{
$user = $this->load($username);
$exists = $user->exists();
if ($exists) {
$user->delete();
}
return $exists;
}
/**
* Find a user by username, email, etc
*
* @param string $query the query to search for
* @param array $fields the fields to search
* @return UserObject
*/
public function find($query, $fields = ['username', 'email']): UserInterface
{
if (is_string($query) && $query !== '') {
foreach ((array)$fields as $field) {
if ($field === 'key') {
$user = $this->get($query);
} elseif ($field === 'storage_key') {
$user = $this->withKeyField('storage_key')->get($query);
} elseif ($field === 'flex_key') {
$user = $this->withKeyField('flex_key')->get($query);
} elseif ($field === 'email') {
$email = mb_strtolower($query);
$user = $this->withKeyField('email')->get($email);
} elseif ($field === 'username') {
$username = static::filterUsername($query, $this->getFlexDirectory()->getStorage());
$user = $this->get($username);
} else {
$user = $this->__call('find', [$query, $field]);
}
if ($user) {
return $user;
}
}
}
return $this->load('');
}
/**
* @param string $key
* @param FlexStorageInterface $storage
* @return string
*/
protected static function filterUsername(string $key, FlexStorageInterface $storage): string
{
return method_exists($storage, 'normalizeKey') ? $storage->normalizeKey($key) : $key;
}
/**
* @param FlexStorageInterface $storage
* @return CompiledYamlFile|null
*/
protected static function getIndexFile(FlexStorageInterface $storage)
{
// Load saved index file.
$grav = Grav::instance();
$locator = $grav['locator'];
$filename = $locator->findResource('user-data://flex/indexes/accounts.yaml', true, true);
return CompiledYamlFile::instance($filename);
}
/**
* @param array $entries
* @param array $added
* @param array $updated
* @param array $removed
*/
protected static function onChanges(array $entries, array $added, array $updated, array $removed): void
{
$message = sprintf('Flex: User index updated, %d objects (%d added, %d updated, %d removed).', count($entries), count($added), count($updated), count($removed));
$grav = Grav::instance();
/** @var Logger $logger */
$logger = $grav['log'];
$logger->addDebug($message);
/** @var Debugger $debugger */
$debugger = $grav['debugger'];
$debugger->addMessage($message, 'debug');
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Flex/Types/Users/Traits/UserObjectLegacyTrait.php | system/src/Grav/Common/Flex/Types/Users/Traits/UserObjectLegacyTrait.php | <?php
declare(strict_types=1);
/**
* @package Grav\Common\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Flex\Types\Users\Traits;
use Grav\Common\Page\Medium\ImageMedium;
use Grav\Common\Page\Medium\StaticImageMedium;
use function count;
/**
* Trait UserObjectLegacyTrait
* @package Grav\Common\Flex\Types\Users\Traits
*/
trait UserObjectLegacyTrait
{
/**
* 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);
$this->setElements($this->getBlueprint()->mergeData($this->toArray(), $data));
return $this;
}
/**
* Return media object for the User's avatar.
*
* @return ImageMedium|StaticImageMedium|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 count($this->jsonSerialize());
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Flex/Types/Users/Storage/UserFileStorage.php | system/src/Grav/Common/Flex/Types/Users/Storage/UserFileStorage.php | <?php
declare(strict_types=1);
/**
* @package Grav\Common\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Flex\Types\Users\Storage;
use Grav\Framework\Flex\Storage\FileStorage;
/**
* Class UserFileStorage
* @package Grav\Common\Flex\Types\Users\Storage
*/
class UserFileStorage extends FileStorage
{
/**
* {@inheritdoc}
* @see FlexStorageInterface::getMediaPath()
*/
public function getMediaPath(string $key = null): ?string
{
// There is no media support for file storage (fallback to common location).
return null;
}
/**
* Prepares the row for saving and returns the storage key for the record.
*
* @param array $row
*/
protected function prepareRow(array &$row): void
{
parent::prepareRow($row);
$access = $row['access'] ?? [];
unset($row['access']);
if ($access) {
$row['access'] = $access;
}
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Flex/Types/Users/Storage/UserFolderStorage.php | system/src/Grav/Common/Flex/Types/Users/Storage/UserFolderStorage.php | <?php
declare(strict_types=1);
/**
* @package Grav\Common\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Flex\Types\Users\Storage;
use Grav\Framework\Flex\Storage\FolderStorage;
/**
* Class UserFolderStorage
* @package Grav\Common\Flex\Types\Users\Storage
*/
class UserFolderStorage extends FolderStorage
{
/**
* Prepares the row for saving and returns the storage key for the record.
*
* @param array $row
*/
protected function prepareRow(array &$row): void
{
parent::prepareRow($row);
$access = $row['access'] ?? [];
unset($row['access']);
if ($access) {
$row['access'] = $access;
}
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Flex/Types/Generic/GenericObject.php | system/src/Grav/Common/Flex/Types/Generic/GenericObject.php | <?php
declare(strict_types=1);
/**
* @package Grav\Common\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Flex\Types\Generic;
use Grav\Common\Flex\FlexObject;
/**
* Class GenericObject
* @package Grav\Common\Flex\Generic
*/
class GenericObject extends FlexObject
{
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Flex/Types/Generic/GenericIndex.php | system/src/Grav/Common/Flex/Types/Generic/GenericIndex.php | <?php
declare(strict_types=1);
/**
* @package Grav\Common\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Flex\Types\Generic;
use Grav\Common\Flex\FlexIndex;
/**
* Class GenericIndex
* @package Grav\Common\Flex\Generic
*
* @extends FlexIndex<GenericObject,GenericCollection>
*/
class GenericIndex extends FlexIndex
{
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Flex/Types/Generic/GenericCollection.php | system/src/Grav/Common/Flex/Types/Generic/GenericCollection.php | <?php
declare(strict_types=1);
/**
* @package Grav\Common\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Flex\Types\Generic;
use Grav\Common\Flex\FlexCollection;
/**
* Class GenericCollection
* @package Grav\Common\Flex\Generic
*
* @extends FlexCollection<GenericObject>
*/
class GenericCollection extends FlexCollection
{
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Flex/Types/Pages/PageIndex.php | system/src/Grav/Common/Flex/Types/Pages/PageIndex.php | <?php
declare(strict_types=1);
/**
* @package Grav\Common\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Flex\Types\Pages;
use Exception;
use Grav\Common\Debugger;
use Grav\Common\File\CompiledJsonFile;
use Grav\Common\File\CompiledYamlFile;
use Grav\Common\Flex\Traits\FlexGravTrait;
use Grav\Common\Flex\Traits\FlexIndexTrait;
use Grav\Common\Grav;
use Grav\Common\Language\Language;
use Grav\Common\Page\Header;
use Grav\Common\Page\Interfaces\PageCollectionInterface;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Common\User\Interfaces\UserInterface;
use Grav\Common\Utils;
use Grav\Framework\Flex\FlexDirectory;
use Grav\Framework\Flex\Interfaces\FlexStorageInterface;
use Grav\Framework\Flex\Pages\FlexPageIndex;
use InvalidArgumentException;
use RuntimeException;
use function array_slice;
use function count;
use function in_array;
use function is_array;
use function is_string;
/**
* Class GravPageObject
* @package Grav\Plugin\FlexObjects\Types\GravPages
*
* @template T of PageObject
* @template C of PageCollection
* @extends FlexPageIndex<T,C>
* @implements PageCollectionInterface<string,T>
*
* @method PageIndex withModules(bool $bool = true)
* @method PageIndex withPages(bool $bool = true)
* @method PageIndex withTranslation(bool $bool = true, string $languageCode = null, bool $fallback = null)
*/
class PageIndex extends FlexPageIndex implements PageCollectionInterface
{
use FlexGravTrait;
use FlexIndexTrait;
public const VERSION = parent::VERSION . '.5';
public const ORDER_LIST_REGEX = '/(\/\d+)\.[^\/]+/u';
public const PAGE_ROUTE_REGEX = '/\/\d+\./u';
/** @var PageObject|array */
protected $_root;
/** @var array|null */
protected $_params;
/**
* @param array $entries
* @param FlexDirectory|null $directory
*/
public function __construct(array $entries = [], FlexDirectory $directory = null)
{
// Remove root if it's taken.
if (isset($entries[''])) {
$this->_root = $entries[''];
unset($entries['']);
}
parent::__construct($entries, $directory);
}
/**
* @param FlexStorageInterface $storage
* @return array
*/
public static function loadEntriesFromStorage(FlexStorageInterface $storage): array
{
// Load saved index.
$index = static::loadIndex($storage);
$version = $index['version'] ?? 0;
$force = static::VERSION !== $version;
// TODO: Following check flex index to be out of sync after some saves, disabled until better solution is found.
//$timestamp = $index['timestamp'] ?? 0;
//if (!$force && $timestamp && $timestamp > time() - 1) {
// return $index['index'];
//}
// Load up to date index.
$entries = parent::loadEntriesFromStorage($storage);
return static::updateIndexFile($storage, $index['index'], $entries, ['include_missing' => true, 'force_update' => $force]);
}
/**
* @param string $key
* @return PageObject|null
* @phpstan-return T|null
*/
public function get($key)
{
if (mb_strpos($key, '|') !== false) {
[$key, $params] = explode('|', $key, 2);
}
$element = parent::get($key);
if (null === $element) {
return null;
}
if (isset($params)) {
$element = $element->getTranslation(ltrim($params, '.'));
}
\assert(null === $element || $element instanceof PageObject);
return $element;
}
/**
* @return PageInterface
*/
public function getRoot()
{
$root = $this->_root;
if (is_array($root)) {
$directory = $this->getFlexDirectory();
$storage = $directory->getStorage();
$defaults = [
'header' => [
'routable' => false,
'permissions' => [
'inherit' => false
]
]
];
$row = $storage->readRows(['' => null])[''] ?? null;
if (null !== $row) {
if (isset($row['__ERROR'])) {
/** @var Debugger $debugger */
$debugger = Grav::instance()['debugger'];
$message = sprintf('Flex Pages: root page is broken in storage: %s', $row['__ERROR']);
$debugger->addException(new RuntimeException($message));
$debugger->addMessage($message, 'error');
$row = ['__META' => $root];
}
} else {
$row = ['__META' => $root];
}
$row = array_merge_recursive($defaults, $row);
/** @var PageObject $root */
$root = $this->getFlexDirectory()->createObject($row, '/', false);
$root->name('root.md');
$root->root(true);
$this->_root = $root;
}
return $root;
}
/**
* @param string|null $languageCode
* @param bool|null $fallback
* @return static
* @phpstan-return static<T,C>
*/
public function withTranslated(string $languageCode = null, bool $fallback = null)
{
if (null === $languageCode) {
return $this;
}
$entries = $this->translateEntries($this->getEntries(), $languageCode, $fallback);
$params = ['language' => $languageCode, 'language_fallback' => $fallback] + $this->getParams();
return $this->createFrom($entries)->setParams($params);
}
/**
* @return string|null
*/
public function getLanguage(): ?string
{
return $this->_params['language'] ?? null;
}
/**
* Get the collection params
*
* @return array
*/
public function getParams(): array
{
return $this->_params ?? [];
}
/**
* Get the collection param
*
* @param string $name
* @return mixed
*/
public function getParam(string $name)
{
return $this->_params[$name] ?? null;
}
/**
* Set parameters to the Collection
*
* @param array $params
* @return $this
*/
public function setParams(array $params)
{
$this->_params = $this->_params ? array_merge($this->_params, $params) : $params;
return $this;
}
/**
* Set a parameter to the Collection
*
* @param string $name
* @param mixed $value
* @return $this
*/
public function setParam(string $name, $value)
{
$this->_params[$name] = $value;
return $this;
}
/**
* Get the collection params
*
* @return array
*/
public function params(): array
{
return $this->getParams();
}
/**
* {@inheritdoc}
* @see FlexCollectionInterface::getCacheKey()
*/
public function getCacheKey(): string
{
return $this->getTypePrefix() . $this->getFlexType() . '.' . sha1(json_encode($this->getKeys()) . $this->getKeyField() . $this->getLanguage());
}
/**
* Filter pages by given filters.
*
* - search: string
* - page_type: string|string[]
* - modular: bool
* - visible: bool
* - routable: bool
* - published: bool
* - page: bool
* - translated: bool
*
* @param array $filters
* @param bool $recursive
* @return static
* @phpstan-return static<T,C>
*/
public function filterBy(array $filters, bool $recursive = false)
{
if (!$filters) {
return $this;
}
if ($recursive) {
return $this->__call('filterBy', [$filters, true]);
}
$list = [];
$index = $this;
foreach ($filters as $key => $value) {
switch ($key) {
case 'search':
$index = $index->search((string)$value);
break;
case 'page_type':
if (!is_array($value)) {
$value = is_string($value) && $value !== '' ? explode(',', $value) : [];
}
$index = $index->ofOneOfTheseTypes($value);
break;
case 'routable':
$index = $index->withRoutable((bool)$value);
break;
case 'published':
$index = $index->withPublished((bool)$value);
break;
case 'visible':
$index = $index->withVisible((bool)$value);
break;
case 'module':
$index = $index->withModules((bool)$value);
break;
case 'page':
$index = $index->withPages((bool)$value);
break;
case 'folder':
$index = $index->withPages(!$value);
break;
case 'translated':
$index = $index->withTranslation((bool)$value);
break;
default:
$list[$key] = $value;
}
}
return $list ? $index->filterByParent($list) : $index;
}
/**
* @param array $filters
* @return static
* @phpstan-return static<T,C>
*/
protected function filterByParent(array $filters)
{
/** @var static $index */
$index = parent::filterBy($filters);
return $index;
}
/**
* @param array $options
* @return array
*/
public function getLevelListing(array $options): array
{
// Undocumented B/C
$order = $options['order'] ?? 'asc';
if ($order === SORT_ASC) {
$options['order'] = 'asc';
} elseif ($order === SORT_DESC) {
$options['order'] = 'desc';
}
$options += [
'field' => null,
'route' => null,
'leaf_route' => null,
'sortby' => null,
'order' => 'asc',
'lang' => null,
'filters' => [],
];
$options['filters'] += [
'type' => ['root', 'dir'],
];
$key = 'page.idx.lev.' . sha1(json_encode($options, JSON_THROW_ON_ERROR) . $this->getCacheKey());
$checksum = $this->getCacheChecksum();
$cache = $this->getCache('object');
/** @var Debugger $debugger */
$debugger = Grav::instance()['debugger'];
$result = null;
try {
$cached = $cache->get($key);
$test = $cached[0] ?? null;
$result = $test === $checksum ? ($cached[1] ?? null) : null;
} catch (\Psr\SimpleCache\InvalidArgumentException $e) {
$debugger->addException($e);
}
try {
if (null === $result) {
$result = $this->getLevelListingRecurse($options);
$cache->set($key, [$checksum, $result]);
}
} catch (\Psr\SimpleCache\InvalidArgumentException $e) {
$debugger->addException($e);
}
return $result;
}
/**
* @param array $entries
* @param string|null $keyField
* @return static
* @phpstan-return static<T,C>
*/
protected function createFrom(array $entries, string $keyField = null)
{
/** @var static $index */
$index = parent::createFrom($entries, $keyField);
$index->_root = $this->getRoot();
return $index;
}
/**
* @param array $entries
* @param string $lang
* @param bool|null $fallback
* @return array
*/
protected function translateEntries(array $entries, string $lang, bool $fallback = null): array
{
$languages = $this->getFallbackLanguages($lang, $fallback);
foreach ($entries as $key => &$entry) {
// Find out which version of the page we should load.
$translations = $this->getLanguageTemplates((string)$key);
if (!$translations) {
// No translations found, is this a folder?
continue;
}
// Find a translation.
$template = null;
foreach ($languages as $code) {
if (isset($translations[$code])) {
$template = $translations[$code];
break;
}
}
// We couldn't find a translation, remove entry from the list.
if (!isset($code, $template)) {
unset($entries['key']);
continue;
}
// Get the main key without template and language.
[$main_key,] = explode('|', $entry['storage_key'] . '|', 2);
// Update storage key and language.
$entry['storage_key'] = $main_key . '|' . $template . '.' . $code;
$entry['lang'] = $code;
}
unset($entry);
return $entries;
}
/**
* @return array
*/
protected function getLanguageTemplates(string $key): array
{
$meta = $this->getMetaData($key);
$template = $meta['template'] ?? 'folder';
$translations = $meta['markdown'] ?? [];
$list = [];
foreach ($translations as $code => $search) {
if (isset($search[$template])) {
// Use main template if possible.
$list[$code] = $template;
} elseif (!empty($search)) {
// Fall back to first matching template.
$list[$code] = key($search);
}
}
return $list;
}
/**
* @param string|null $languageCode
* @param bool|null $fallback
* @return array
*/
protected function getFallbackLanguages(string $languageCode = null, bool $fallback = null): array
{
$fallback = $fallback ?? true;
if (!$fallback && null !== $languageCode) {
return [$languageCode];
}
$grav = Grav::instance();
/** @var Language $language */
$language = $grav['language'];
$languageCode = $languageCode ?? '';
if ($languageCode === '' && $fallback) {
return $language->getFallbackLanguages(null, true);
}
return $fallback ? $language->getFallbackLanguages($languageCode, true) : [$languageCode];
}
/**
* @param array $options
* @return array
*/
protected function getLevelListingRecurse(array $options): array
{
$filters = $options['filters'] ?? [];
$field = $options['field'];
$route = $options['route'];
$leaf_route = $options['leaf_route'];
$sortby = $options['sortby'];
$order = $options['order'];
$language = $options['lang'];
$status = 'error';
$response = [];
$extra = null;
// Handle leaf_route
$leaf = null;
if ($leaf_route && $route !== $leaf_route) {
$nodes = explode('/', $leaf_route);
$sub_route = '/' . implode('/', array_slice($nodes, 1, $options['level']++));
$options['route'] = $sub_route;
[$status,,$leaf,$extra] = $this->getLevelListingRecurse($options);
}
// Handle no route, assume page tree root
if (!$route) {
$page = $this->getRoot();
} else {
$page = $this->get(trim($route, '/'));
}
$path = $page ? $page->path() : null;
if ($field) {
// Get forced filters from the field.
$blueprint = $page ? $page->getBlueprint() : $this->getFlexDirectory()->getBlueprint();
$settings = $blueprint->schema()->getProperty($field);
$filters = array_merge([], $filters, $settings['filters'] ?? []);
}
// Clean up filter.
$filter_type = (array)($filters['type'] ?? []);
unset($filters['type']);
$filters = array_filter($filters, static function($val) { return $val !== null && $val !== ''; });
if ($page) {
$status = 'success';
$msg = 'PLUGIN_ADMIN.PAGE_ROUTE_FOUND';
if ($page->root() && (!$filter_type || in_array('root', $filter_type, true))) {
if ($field) {
$response[] = [
'name' => '<root>',
'value' => '/',
'item-key' => '',
'filename' => '.',
'extension' => '',
'type' => 'root',
'modified' => $page->modified(),
'size' => 0,
'symlink' => false,
'has-children' => false
];
} else {
$response[] = [
'item-key' => '-root-',
'icon' => 'root',
'title' => 'Root', // FIXME
'route' => [
'display' => '<root>', // FIXME
'raw' => '_root',
],
'modified' => $page->modified(),
'extras' => [
'template' => $page->template(),
//'lang' => null,
//'translated' => null,
'langs' => [],
'published' => false,
'visible' => false,
'routable' => false,
'tags' => ['root', 'non-routable'],
'actions' => ['edit'], // FIXME
]
];
}
}
/** @var PageCollection|PageIndex $children */
$children = $page->children();
/** @var PageIndex $children */
$children = $children->getIndex();
$selectedChildren = $children->filterBy($filters + ['language' => $language], true);
/** @var Header $header */
$header = $page->header();
if (!$field && $header->get('admin.children_display_order', 'collection') === 'collection' && ($orderby = $header->get('content.order.by'))) {
// Use custom sorting by page header.
$sortby = $orderby;
$order = $header->get('content.order.dir', $order);
$custom = $header->get('content.order.custom');
}
if ($sortby) {
// Sort children.
$selectedChildren = $selectedChildren->order($sortby, $order, $custom ?? null);
}
/** @var UserInterface|null $user */
$user = Grav::instance()['user'] ?? null;
/** @var PageObject $child */
foreach ($selectedChildren as $child) {
$selected = $child->path() === $extra;
$includeChildren = is_array($leaf) && !empty($leaf) && $selected;
if ($field) {
$child_count = count($child->children());
$payload = [
'name' => $child->menu(),
'value' => $child->rawRoute(),
'item-key' => Utils::basename($child->rawRoute() ?? ''),
'filename' => $child->folder(),
'extension' => $child->extension(),
'type' => 'dir',
'modified' => $child->modified(),
'size' => $child_count,
'symlink' => false,
'has-children' => $child_count > 0
];
} else {
$lang = $child->findTranslation($language) ?? 'n/a';
/** @var PageObject $child */
$child = $child->getTranslation($language) ?? $child;
// TODO: all these features are independent from each other, we cannot just have one icon/color to catch all.
// TODO: maybe icon by home/modular/page/folder (or even from blueprints) and color by visibility etc..
if ($child->home()) {
$icon = 'home';
} elseif ($child->isModule()) {
$icon = 'modular';
} elseif ($child->visible()) {
$icon = 'visible';
} elseif ($child->isPage()) {
$icon = 'page';
} else {
// TODO: add support
$icon = 'folder';
}
$tags = [
$child->published() ? 'published' : 'non-published',
$child->visible() ? 'visible' : 'non-visible',
$child->routable() ? 'routable' : 'non-routable'
];
$extras = [
'template' => $child->template(),
'lang' => $lang ?: null,
'translated' => $lang ? $child->hasTranslation($language, false) : null,
'langs' => $child->getAllLanguages(true) ?: null,
'published' => $child->published(),
'published_date' => $this->jsDate($child->publishDate()),
'unpublished_date' => $this->jsDate($child->unpublishDate()),
'visible' => $child->visible(),
'routable' => $child->routable(),
'tags' => $tags,
'actions' => $this->getListingActions($child, $user),
];
$extras = array_filter($extras, static function ($v) {
return $v !== null;
});
/** @var PageIndex $tmp */
$tmp = $child->children()->getIndex();
$child_count = $tmp->count();
$count = $filters ? $tmp->filterBy($filters, true)->count() : null;
$route = $child->getRoute();
$route = $route ? ($route->toString(false) ?: '/') : '';
$payload = [
'item-key' => htmlspecialchars(Utils::basename($child->rawRoute() ?? $child->getKey())),
'icon' => $icon,
'title' => htmlspecialchars($child->menu()),
'route' => [
'display' => htmlspecialchars($route) ?: null,
'raw' => htmlspecialchars($child->rawRoute()),
],
'modified' => $this->jsDate($child->modified()),
'child_count' => $child_count ?: null,
'count' => $count ?? null,
'filters_hit' => $filters ? ($child->filterBy($filters, false) ?: null) : null,
'extras' => $extras
];
$payload = array_filter($payload, static function ($v) {
return $v !== null;
});
}
// Add children if any
if ($includeChildren) {
$payload['children'] = array_values($leaf);
}
$response[] = $payload;
}
} else {
$msg = 'PLUGIN_ADMIN.PAGE_ROUTE_NOT_FOUND';
}
if ($field) {
$temp_array = [];
foreach ($response as $index => $item) {
$temp_array[$item['type']][$index] = $item;
}
$sorted = Utils::sortArrayByArray($temp_array, $filter_type);
$response = Utils::arrayFlatten($sorted);
}
return [$status, $msg, $response, $path];
}
/**
* @param PageObject $object
* @param UserInterface $user
* @return array
*/
protected function getListingActions(PageObject $object, UserInterface $user): array
{
$actions = [];
if ($object->isAuthorized('read', null, $user)) {
$actions[] = 'preview';
$actions[] = 'edit';
}
if ($object->isAuthorized('update', null, $user)) {
$actions[] = 'copy';
$actions[] = 'move';
}
if ($object->isAuthorized('delete', null, $user)) {
$actions[] = 'delete';
}
return $actions;
}
/**
* @param FlexStorageInterface $storage
* @return CompiledJsonFile|CompiledYamlFile|null
*/
protected static function getIndexFile(FlexStorageInterface $storage)
{
if (!method_exists($storage, 'isIndexed') || !$storage->isIndexed()) {
return null;
}
// Load saved index file.
$grav = Grav::instance();
$locator = $grav['locator'];
$filename = $locator->findResource('user-data://flex/indexes/pages.json', true, true);
return CompiledJsonFile::instance($filename);
}
/**
* @param int|null $timestamp
* @return string|null
*/
private function jsDate(int $timestamp = null): ?string
{
if (!$timestamp) {
return null;
}
$config = Grav::instance()['config'];
$dateFormat = $config->get('system.pages.dateformat.long');
return date($dateFormat, $timestamp) ?: null;
}
/**
* Add a single page to a collection
*
* @param PageInterface $page
* @return PageCollection
* @phpstan-return C
*/
public function addPage(PageInterface $page)
{
return $this->getCollection()->addPage($page);
}
/**
*
* Create a copy of this collection
*
* @return static
* @phpstan-return static<T,C>
*/
public function copy()
{
return clone $this;
}
/**
*
* Merge another collection with the current collection
*
* @param PageCollectionInterface $collection
* @return PageCollection
* @phpstan-return C
*/
public function merge(PageCollectionInterface $collection)
{
return $this->getCollection()->merge($collection);
}
/**
* Intersect another collection with the current collection
*
* @param PageCollectionInterface $collection
* @return PageCollection
* @phpstan-return C
*/
public function intersect(PageCollectionInterface $collection)
{
return $this->getCollection()->intersect($collection);
}
/**
* Split collection into array of smaller collections.
*
* @param int $size
* @return PageCollection[]
* @phpstan-return C[]
*/
public function batch($size)
{
return $this->getCollection()->batch($size);
}
/**
* Remove item from the list.
*
* @param string $key
* @return PageObject|null
* @phpstan-return T|null
* @throws InvalidArgumentException
*/
public function remove($key)
{
return $this->getCollection()->remove($key);
}
/**
* Reorder collection.
*
* @param string $by
* @param string $dir
* @param array $manual
* @param string $sort_flags
* @return static
* @phpstan-return static<T,C>
*/
public function order($by, $dir = 'asc', $manual = null, $sort_flags = null)
{
/** @var PageCollectionInterface $collection */
$collection = $this->__call('order', [$by, $dir, $manual, $sort_flags]);
return $collection;
}
/**
* 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
{
/** @var bool $result */
$result = $this->__call('isFirst', [$path]);
return $result;
}
/**
* 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
{
/** @var bool $result */
$result = $this->__call('isLast', [$path]);
return $result;
}
/**
* Gets the previous sibling based on current position.
*
* @param string $path
* @return PageObject|null The previous item.
* @phpstan-return T|null
*/
public function prevSibling($path)
{
/** @var PageObject|null $result */
$result = $this->__call('prevSibling', [$path]);
return $result;
}
/**
* Gets the next sibling based on current position.
*
* @param string $path
* @return PageObject|null The next item.
* @phpstan-return T|null
*/
public function nextSibling($path)
{
/** @var PageObject|null $result */
$result = $this->__call('nextSibling', [$path]);
return $result;
}
/**
* Returns the adjacent sibling based on a direction.
*
* @param string $path
* @param int $direction either -1 or +1
* @return PageObject|false The sibling item.
* @phpstan-return T|false
*/
public function adjacentSibling($path, $direction = 1)
{
/** @var PageObject|false $result */
$result = $this->__call('adjacentSibling', [$path, $direction]);
return $result;
}
/**
* 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
{
/** @var int|null $result */
$result = $this->__call('currentPosition', [$path]);
return $result;
}
/**
* 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 static
* @phpstan-return static<T,C>
* @throws Exception
*/
public function dateRange($startDate = null, $endDate = null, $field = null)
{
$collection = $this->__call('dateRange', [$startDate, $endDate, $field]);
return $collection;
}
/**
* Mimicks Pages class.
*
* @return $this
* @deprecated 1.7 Not needed anymore in Flex Pages (does nothing).
*/
public function all()
{
return $this;
}
/**
* Creates new collection with only visible pages
*
* @return static The collection with only visible pages
* @phpstan-return static<T,C>
*/
public function visible()
{
$collection = $this->__call('visible', []);
return $collection;
}
/**
* Creates new collection with only non-visible pages
*
* @return static The collection with only non-visible pages
* @phpstan-return static<T,C>
*/
public function nonVisible()
{
$collection = $this->__call('nonVisible', []);
return $collection;
}
/**
* Creates new collection with only non-modular pages
*
* @return static The collection with only non-modular pages
* @phpstan-return static<T,C>
*/
public function pages()
{
$collection = $this->__call('pages', []);
return $collection;
}
/**
* Creates new collection with only modular pages
*
* @return static The collection with only modular pages
* @phpstan-return static<T,C>
*/
public function modules()
{
$collection = $this->__call('modules', []);
return $collection;
}
/**
* Creates new collection with only modular pages
*
* @return static The collection with only modular pages
* @phpstan-return static<T,C>
*/
public function modular()
{
return $this->modules();
}
/**
* Creates new collection with only non-modular pages
*
* @return static The collection with only non-modular pages
* @phpstan-return static<T,C>
*/
public function nonModular()
{
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | true |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Flex/Types/Pages/PageObject.php | system/src/Grav/Common/Flex/Types/Pages/PageObject.php | <?php
declare(strict_types=1);
/**
* @package Grav\Common\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Flex\Types\Pages;
use Grav\Common\Data\Blueprint;
use Grav\Common\Flex\Traits\FlexGravTrait;
use Grav\Common\Flex\Traits\FlexObjectTrait;
use Grav\Common\Grav;
use Grav\Common\Flex\Types\Pages\Traits\PageContentTrait;
use Grav\Common\Flex\Types\Pages\Traits\PageLegacyTrait;
use Grav\Common\Flex\Types\Pages\Traits\PageRoutableTrait;
use Grav\Common\Flex\Types\Pages\Traits\PageTranslateTrait;
use Grav\Common\Language\Language;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Common\Page\Pages;
use Grav\Common\User\Interfaces\UserInterface;
use Grav\Common\Utils;
use Grav\Framework\Filesystem\Filesystem;
use Grav\Framework\Flex\Interfaces\FlexObjectInterface;
use Grav\Framework\Flex\Pages\FlexPageObject;
use Grav\Framework\Object\ObjectCollection;
use Grav\Framework\Route\Route;
use Grav\Framework\Route\RouteFactory;
use Grav\Plugin\Admin\Admin;
use RocketTheme\Toolbox\Event\Event;
use RuntimeException;
use stdClass;
use function array_key_exists;
use function count;
use function func_get_args;
use function in_array;
use function is_array;
/**
* Class GravPageObject
* @package Grav\Plugin\FlexObjects\Types\GravPages
*
* @property string $name
* @property string $slug
* @property string $route
* @property string $folder
* @property int|false $order
* @property string $template
* @property string $language
*/
class PageObject extends FlexPageObject
{
use FlexGravTrait;
use FlexObjectTrait;
use PageContentTrait;
use PageLegacyTrait;
use PageRoutableTrait;
use PageTranslateTrait;
/** @var string Language code, eg: 'en' */
protected $language;
/** @var string File format, eg. 'md' */
protected $format;
/** @var bool */
private $_initialized = false;
/**
* @return array
*/
public static function getCachedMethods(): array
{
return [
'path' => true,
'full_order' => true,
'filterBy' => true,
'translated' => false,
] + parent::getCachedMethods();
}
/**
* @return void
*/
public function initialize(): void
{
if (!$this->_initialized) {
Grav::instance()->fireEvent('onPageProcessed', new Event(['page' => $this]));
$this->_initialized = true;
}
}
/**
* @param string|array $query
* @return Route|null
*/
public function getRoute($query = []): ?Route
{
$path = $this->route();
if (null === $path) {
return null;
}
$route = RouteFactory::createFromString($path);
if ($lang = $route->getLanguage()) {
$grav = Grav::instance();
if (!$grav['config']->get('system.languages.include_default_lang')) {
/** @var Language $language */
$language = $grav['language'];
if ($lang === $language->getDefault()) {
$route = $route->withLanguage('');
}
}
}
if (is_array($query)) {
foreach ($query as $key => $value) {
$route = $route->withQueryParam($key, $value);
}
} else {
$route = $route->withAddedPath($query);
}
return $route;
}
/**
* @inheritdoc PageInterface
*/
public function getFormValue(string $name, $default = null, string $separator = null)
{
$test = new stdClass();
$value = $this->pageContentValue($name, $test);
if ($value !== $test) {
return $value;
}
switch ($name) {
case 'name':
// TODO: this should not be template!
return $this->getProperty('template');
case 'route':
$filesystem = Filesystem::getInstance(false);
$key = $filesystem->dirname($this->hasKey() ? '/' . $this->getKey() : '/');
return $key !== '/' ? $key : null;
case 'full_route':
return $this->hasKey() ? '/' . $this->getKey() : '';
case 'full_order':
return $this->full_order();
case 'lang':
return $this->getLanguage() ?? '';
case 'translations':
return $this->getLanguages();
}
return parent::getFormValue($name, $default, $separator);
}
/**
* {@inheritdoc}
* @see FlexObjectInterface::getCacheKey()
*/
public function getCacheKey(): string
{
$cacheKey = parent::getCacheKey();
if ($cacheKey) {
/** @var Language $language */
$language = Grav::instance()['language'];
$cacheKey .= '_' . $language->getActive();
}
return $cacheKey;
}
/**
* @param array $variables
* @return array
*/
protected function onBeforeSave(array $variables)
{
$reorder = $variables[0] ?? true;
$meta = $this->getMetaData();
if (($meta['copy'] ?? false) === true) {
$this->folder = $this->getKey();
}
// Figure out storage path to the new route.
$parentKey = $this->getProperty('parent_key');
if ($parentKey !== '') {
$parentRoute = $this->getProperty('route');
// Root page cannot be moved.
if ($this->root()) {
throw new RuntimeException(sprintf('Root page cannot be moved to %s', $parentRoute));
}
// Make sure page isn't being moved under itself.
$key = $this->getStorageKey();
/** @var PageObject|null $parent */
$parent = $parentKey !== false ? $this->getFlexDirectory()->getObject($parentKey, 'storage_key') : null;
if (!$parent) {
// Page cannot be moved to non-existing location.
throw new RuntimeException(sprintf('Page /%s cannot be moved to non-existing path %s', $key, $parentRoute));
}
// TODO: make sure that the page doesn't exist yet if moved/copied.
}
if ($reorder === true && !$this->root()) {
$reorder = $this->_reorder;
}
// Force automatic reorder if item is supposed to be added to the last.
if (!is_array($reorder) && (int)$this->order() >= 999999) {
$reorder = [];
}
// Reorder siblings.
$siblings = is_array($reorder) ? ($this->reorderSiblings($reorder) ?? []) : [];
$data = $this->prepareStorage();
unset($data['header']);
foreach ($siblings as $sibling) {
$data = $sibling->prepareStorage();
unset($data['header']);
}
return ['reorder' => $reorder, 'siblings' => $siblings];
}
/**
* @param array $variables
* @return array
*/
protected function onSave(array $variables): array
{
/** @var PageCollection $siblings */
$siblings = $variables['siblings'];
/** @var PageObject $sibling */
foreach ($siblings as $sibling) {
$sibling->save(false);
}
return $variables;
}
/**
* @param array $variables
*/
protected function onAfterSave(array $variables): void
{
$this->getFlexDirectory()->reloadIndex();
}
/**
* @param UserInterface|null $user
*/
public function check(UserInterface $user = null): void
{
parent::check($user);
if ($user && $this->isMoved()) {
$parentKey = $this->getProperty('parent_key');
/** @var PageObject|null $parent */
$parent = $this->getFlexDirectory()->getObject($parentKey, 'storage_key');
if (!$parent || !$parent->isAuthorized('create', null, $user)) {
throw new \RuntimeException('Forbidden', 403);
}
}
}
/**
* @param array|bool $reorder
* @return static
*/
public function save($reorder = true)
{
$variables = $this->onBeforeSave(func_get_args());
// Backwards compatibility with older plugins.
$fireEvents = $reorder && $this->isAdminSite() && $this->getFlexDirectory()->getConfig('object.compat.events', true);
$grav = $this->getContainer();
if ($fireEvents) {
$self = $this;
$grav->fireEvent('onAdminSave', new Event(['type' => 'flex', 'directory' => $this->getFlexDirectory(), 'object' => &$self]));
if ($self !== $this) {
throw new RuntimeException('Switching Flex Page object during onAdminSave event is not supported! Please update plugin.');
}
}
/** @var static $instance */
$instance = parent::save();
$variables = $this->onSave($variables);
$this->onAfterSave($variables);
// Backwards compatibility with older plugins.
if ($fireEvents) {
$grav->fireEvent('onAdminAfterSave', new Event(['type' => 'flex', 'directory' => $this->getFlexDirectory(), 'object' => $this]));
}
// Reset original after save events have all been called.
$this->_originalObject = null;
return $instance;
}
/**
* @return static
*/
public function delete()
{
$result = parent::delete();
// Backwards compatibility with older plugins.
$fireEvents = $this->isAdminSite() && $this->getFlexDirectory()->getConfig('object.compat.events', true);
if ($fireEvents) {
$this->getContainer()->fireEvent('onAdminAfterDelete', new Event(['object' => $this]));
}
return $result;
}
/**
* Prepare move page to new location. Moves also everything that's under the current page.
*
* You need to call $this->save() in order to perform the move.
*
* @param PageInterface $parent New parent page.
* @return $this
*/
public function move(PageInterface $parent)
{
if (!$parent instanceof FlexObjectInterface) {
throw new RuntimeException('Failed: Parent is not Flex Object');
}
$this->_reorder = [];
$this->setProperty('parent_key', $parent->getStorageKey());
$this->storeOriginal();
return $this;
}
/**
* @param UserInterface $user
* @param string $action
* @param string $scope
* @param bool $isMe
* @return bool|null
*/
protected function isAuthorizedOverride(UserInterface $user, string $action, string $scope, bool $isMe): ?bool
{
// Special case: creating a new page means checking parent for its permissions.
if ($action === 'create' && !$this->exists()) {
$parent = $this->parent();
if ($parent && method_exists($parent, 'isAuthorized')) {
return $parent->isAuthorized($action, $scope, $user);
}
return false;
}
return parent::isAuthorizedOverride($user, $action, $scope, $isMe);
}
/**
* @return bool
*/
protected function isMoved(): bool
{
$storageKey = $this->getMasterKey();
$filesystem = Filesystem::getInstance(false);
$oldParentKey = ltrim($filesystem->dirname("/{$storageKey}"), '/');
$newParentKey = $this->getProperty('parent_key');
return $this->exists() && $oldParentKey !== $newParentKey;
}
/**
* @param array $ordering
* @return PageCollection|null
* @phpstan-return ObjectCollection<string,PageObject>|null
*/
protected function reorderSiblings(array $ordering)
{
$storageKey = $this->getMasterKey();
$isMoved = $this->isMoved();
$order = !$isMoved ? $this->order() : false;
if ($order !== false) {
$order = (int)$order;
}
$parent = $this->parent();
if (!$parent) {
throw new RuntimeException('Cannot reorder a page which has no parent');
}
/** @var PageCollection $siblings */
$siblings = $parent->children();
$siblings = $siblings->getCollection()->withOrdered();
// Handle special case where ordering isn't given.
if ($ordering === []) {
if ($order >= 999999) {
// Set ordering to point to be the last item, ignoring the object itself.
$order = 0;
foreach ($siblings as $sibling) {
if ($sibling->getKey() !== $this->getKey()) {
$order = max($order, (int)$sibling->order());
}
}
$this->order($order + 1);
}
// Do not change sibling ordering.
return null;
}
$siblings = $siblings->orderBy(['order' => 'ASC']);
if ($storageKey !== null) {
if ($order !== false) {
// Add current page back to the list if it's ordered.
$siblings->set($storageKey, $this);
} else {
// Remove old copy of the current page from the siblings list.
$siblings->remove($storageKey);
}
}
// Add missing siblings into the end of the list, keeping the previous ordering between them.
foreach ($siblings as $sibling) {
$folder = (string)$sibling->getProperty('folder');
$basename = preg_replace('|^\d+\.|', '', $folder);
if (!in_array($basename, $ordering, true)) {
$ordering[] = $basename;
}
}
// Reorder.
$ordering = array_flip(array_values($ordering));
$count = count($ordering);
foreach ($siblings as $sibling) {
$folder = (string)$sibling->getProperty('folder');
$basename = preg_replace('|^\d+\.|', '', $folder);
$newOrder = $ordering[$basename] ?? null;
$newOrder = null !== $newOrder ? $newOrder + 1 : (int)$sibling->order() + $count;
$sibling->order($newOrder);
}
$siblings = $siblings->orderBy(['order' => 'ASC']);
$siblings->removeElement($this);
// If menu item was moved, just make it to be the last in order.
if ($isMoved && $this->order() !== false) {
$parentKey = $this->getProperty('parent_key');
if ($parentKey === '') {
/** @var PageIndex $index */
$index = $this->getFlexDirectory()->getIndex();
$newParent = $index->getRoot();
} else {
$newParent = $this->getFlexDirectory()->getObject($parentKey, 'storage_key');
if (!$newParent instanceof PageInterface) {
throw new RuntimeException("New parent page '{$parentKey}' not found.");
}
}
/** @var PageCollection $newSiblings */
$newSiblings = $newParent->children();
$newSiblings = $newSiblings->getCollection()->withOrdered();
$order = 0;
foreach ($newSiblings as $sibling) {
$order = max($order, (int)$sibling->order());
}
$this->order($order + 1);
}
return $siblings;
}
/**
* @return string
*/
public function full_order(): string
{
$route = $this->path() . '/' . $this->folder();
return preg_replace(PageIndex::ORDER_LIST_REGEX, '\\1', $route) ?? $route;
}
/**
* @param string $name
* @return Blueprint
*/
protected function doGetBlueprint(string $name = ''): Blueprint
{
try {
// Make sure that pages has been initialized.
Pages::getTypes();
// TODO: We need to move raw blueprint logic to Grav itself to remove admin dependency here.
if ($name === 'raw') {
// Admin RAW mode.
if ($this->isAdminSite()) {
/** @var Admin $admin */
$admin = Grav::instance()['admin'];
$template = $this->isModule() ? 'modular_raw' : ($this->root() ? 'root_raw' : 'raw');
return $admin->blueprints("admin/pages/{$template}");
}
}
$template = $this->getProperty('template') . ($name ? '.' . $name : '');
$blueprint = $this->getFlexDirectory()->getBlueprint($template, 'blueprints://pages');
} catch (RuntimeException $e) {
$template = 'default' . ($name ? '.' . $name : '');
$blueprint = $this->getFlexDirectory()->getBlueprint($template, 'blueprints://pages');
}
$isNew = $blueprint->get('initialized', false) === false;
if ($isNew === true && $name === '') {
// Support onBlueprintCreated event just like in Pages::blueprints($template)
$blueprint->set('initialized', true);
$blueprint->setFilename($template);
Grav::instance()->fireEvent('onBlueprintCreated', new Event(['blueprint' => $blueprint, 'type' => $template]));
}
return $blueprint;
}
/**
* @param array $options
* @return array
*/
public function getLevelListing(array $options): array
{
$index = $this->getFlexDirectory()->getIndex();
if (!is_callable([$index, 'getLevelListing'])) {
return [];
}
// Deal with relative paths.
$initial = $options['initial'] ?? null;
$var = $initial ? 'leaf_route' : 'route';
$route = $options[$var] ?? '';
if ($route !== '' && !str_starts_with($route, '/')) {
$filesystem = Filesystem::getInstance();
$route = "/{$this->getKey()}/{$route}";
$route = $filesystem->normalize($route);
$options[$var] = $route;
}
[$status, $message, $response,] = $index->getLevelListing($options);
return [$status, $message, $response, $options[$var] ?? null];
}
/**
* Filter page (true/false) by given filters.
*
* - search: string
* - extension: string
* - module: bool
* - visible: bool
* - routable: bool
* - published: bool
* - page: bool
* - translated: bool
*
* @param array $filters
* @param bool $recursive
* @return bool
*/
public function filterBy(array $filters, bool $recursive = false): bool
{
$language = $filters['language'] ?? null;
if (null !== $language) {
/** @var PageObject $test */
$test = $this->getTranslation($language) ?? $this;
} else {
$test = $this;
}
foreach ($filters as $key => $value) {
switch ($key) {
case 'search':
$matches = $test->search((string)$value) > 0.0;
break;
case 'page_type':
$types = $value ? explode(',', $value) : [];
$matches = in_array($test->template(), $types, true);
break;
case 'extension':
$matches = Utils::contains((string)$value, $test->extension());
break;
case 'routable':
$matches = $test->isRoutable() === (bool)$value;
break;
case 'published':
$matches = $test->isPublished() === (bool)$value;
break;
case 'visible':
$matches = $test->isVisible() === (bool)$value;
break;
case 'module':
$matches = $test->isModule() === (bool)$value;
break;
case 'page':
$matches = $test->isPage() === (bool)$value;
break;
case 'folder':
$matches = $test->isPage() === !$value;
break;
case 'translated':
$matches = $test->hasTranslation() === (bool)$value;
break;
default:
$matches = true;
break;
}
// If current filter does not match, we still may have match as a parent.
if ($matches === false) {
if (!$recursive) {
return false;
}
/** @var PageIndex $index */
$index = $this->children()->getIndex();
return $index->filterBy($filters, true)->count() > 0;
}
}
return true;
}
/**
* {@inheritdoc}
* @see FlexObjectInterface::exists()
*/
public function exists(): bool
{
return $this->root ?: parent::exists();
}
/**
* @return array
*/
public function __debugInfo(): array
{
$list = parent::__debugInfo();
return $list + [
'_content_meta:private' => $this->getContentMeta(),
'_content:private' => $this->getRawContent()
];
}
/**
* @param array $elements
* @param bool $extended
*/
protected function filterElements(array &$elements, bool $extended = false): void
{
// Change parent page if needed.
if (array_key_exists('route', $elements) && isset($elements['folder'], $elements['name'])) {
$elements['template'] = $elements['name'];
// Figure out storage path to the new route.
$parentKey = trim($elements['route'] ?? '', '/');
if ($parentKey !== '') {
/** @var PageObject|null $parent */
$parent = $this->getFlexDirectory()->getObject($parentKey);
$parentKey = $parent ? $parent->getStorageKey() : $parentKey;
}
$elements['parent_key'] = $parentKey;
}
// Deal with ordering=bool and order=page1,page2,page3.
if ($this->root()) {
// Root page doesn't have ordering.
unset($elements['ordering'], $elements['order']);
} elseif (array_key_exists('ordering', $elements) && array_key_exists('order', $elements)) {
// Store ordering.
$ordering = $elements['order'] ?? null;
$this->_reorder = !empty($ordering) ? explode(',', $ordering) : [];
$order = false;
if ((bool)($elements['ordering'] ?? false)) {
$order = $this->order();
if ($order === false) {
$order = 999999;
}
}
$elements['order'] = $order;
}
parent::filterElements($elements, true);
}
/**
* @return array
*/
public function prepareStorage(): array
{
$meta = $this->getMetaData();
$oldLang = $meta['lang'] ?? '';
$newLang = $this->getProperty('lang') ?? '';
// Always clone the page to the new language.
if ($oldLang !== $newLang) {
$meta['clone'] = true;
}
// Make sure that certain elements are always sent to the storage layer.
$elements = [
'__META' => $meta,
'storage_key' => $this->getStorageKey(),
'parent_key' => $this->getProperty('parent_key'),
'order' => $this->getProperty('order'),
'folder' => preg_replace('|^\d+\.|', '', $this->getProperty('folder') ?? ''),
'template' => preg_replace('|modular/|', '', $this->getProperty('template') ?? ''),
'lang' => $newLang
] + parent::prepareStorage();
return $elements;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Flex/Types/Pages/PageCollection.php | system/src/Grav/Common/Flex/Types/Pages/PageCollection.php | <?php
declare(strict_types=1);
/**
* @package Grav\Common\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Flex\Types\Pages;
use Exception;
use Grav\Common\Flex\Traits\FlexCollectionTrait;
use Grav\Common\Flex\Traits\FlexGravTrait;
use Grav\Common\Grav;
use Grav\Common\Page\Header;
use Grav\Common\Page\Interfaces\PageCollectionInterface;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Common\Utils;
use Grav\Framework\Flex\Pages\FlexPageCollection;
use Collator;
use InvalidArgumentException;
use RuntimeException;
use function array_search;
use function count;
use function extension_loaded;
use function in_array;
use function is_array;
use function is_string;
/**
* Class GravPageCollection
* @package Grav\Plugin\FlexObjects\Types\GravPages
*
* @template T as PageObject
* @extends FlexPageCollection<T>
* @implements PageCollectionInterface<string,T>
*
* Incompatibilities with Grav\Common\Page\Collection:
* $page = $collection->key() will not work at all
* $clone = clone $collection does not clone objects inside the collection, does it matter?
* $string = (string)$collection returns collection id instead of comma separated list
* $collection->add() incompatible method signature
* $collection->remove() incompatible method signature
* $collection->filter() incompatible method signature (takes closure instead of callable)
* $collection->prev() does not rewind the internal pointer
* AND most methods are immutable; they do not update the current collection, but return updated one
*
* @method PageIndex getIndex()
*/
class PageCollection extends FlexPageCollection implements PageCollectionInterface
{
use FlexGravTrait;
use FlexCollectionTrait;
/** @var array|null */
protected $_params;
/**
* @return array
*/
public static function getCachedMethods(): array
{
return [
// Collection specific methods
'getRoot' => false,
'getParams' => false,
'setParams' => false,
'params' => false,
'addPage' => false,
'merge' => false,
'intersect' => false,
'prev' => false,
'nth' => false,
'random' => false,
'append' => false,
'batch' => false,
'order' => false,
// Collection filtering
'dateRange' => true,
'visible' => true,
'nonVisible' => true,
'pages' => true,
'modules' => true,
'modular' => true,
'nonModular' => true,
'published' => true,
'nonPublished' => true,
'routable' => true,
'nonRoutable' => true,
'ofType' => true,
'ofOneOfTheseTypes' => true,
'ofOneOfTheseAccessLevels' => true,
'withOrdered' => true,
'withModules' => true,
'withPages' => true,
'withTranslation' => true,
'filterBy' => true,
'toExtendedArray' => false,
'getLevelListing' => false,
] + parent::getCachedMethods();
}
/**
* @return PageInterface
*/
public function getRoot()
{
return $this->getIndex()->getRoot();
}
/**
* Get the collection params
*
* @return array
*/
public function getParams(): array
{
return $this->_params ?? [];
}
/**
* Set parameters to the Collection
*
* @param array $params
* @return $this
*/
public function setParams(array $params)
{
$this->_params = $this->_params ? array_merge($this->_params, $params) : $params;
return $this;
}
/**
* Get the collection params
*
* @return array
*/
public function params(): array
{
return $this->getParams();
}
/**
* Add a single page to a collection
*
* @param PageInterface $page
* @return $this
*/
public function addPage(PageInterface $page)
{
if (!$page instanceof PageObject) {
throw new InvalidArgumentException('$page is not a flex page.');
}
// FIXME: support other keys.
$this->set($page->getKey(), $page);
return $this;
}
/**
*
* Merge another collection with the current collection
*
* @param PageCollectionInterface $collection
* @return static
* @phpstan-return static<T>
*/
public function merge(PageCollectionInterface $collection)
{
throw new RuntimeException(__METHOD__ . '(): Not Implemented');
}
/**
* Intersect another collection with the current collection
*
* @param PageCollectionInterface $collection
* @return static
* @phpstan-return static<T>
*/
public function intersect(PageCollectionInterface $collection)
{
throw new RuntimeException(__METHOD__ . '(): Not Implemented');
}
/**
* Set current page.
*/
public function setCurrent(string $path): void
{
throw new RuntimeException(__METHOD__ . '(): Not Implemented');
}
/**
* Return previous item.
*
* @return PageInterface|false
* @phpstan-return T|false
*/
public function prev()
{
// FIXME: this method does not rewind the internal pointer!
$key = (string)$this->key();
$prev = $this->prevSibling($key);
return $prev !== $this->current() ? $prev : false;
}
/**
* Return nth item.
* @param int $key
* @return PageInterface|bool
* @phpstan-return T|false
*/
public function nth($key)
{
return $this->slice($key, 1)[0] ?? false;
}
/**
* Pick one or more random entries.
*
* @param int $num Specifies how many entries should be picked.
* @return static
* @phpstan-return static<T>
*/
public function random($num = 1)
{
return $this->createFrom($this->shuffle()->slice(0, $num));
}
/**
* Append new elements to the list.
*
* @param array $items Items to be appended. Existing keys will be overridden with the new values.
* @return static
* @phpstan-return static<T>
*/
public function append($items)
{
throw new RuntimeException(__METHOD__ . '(): Not Implemented');
}
/**
* Split collection into array of smaller collections.
*
* @param int $size
* @return static[]
* @phpstan-return static<T>[]
*/
public function batch($size): array
{
$chunks = $this->chunk($size);
$list = [];
foreach ($chunks as $chunk) {
$list[] = $this->createFrom($chunk);
}
return $list;
}
/**
* Reorder collection.
*
* @param string $by
* @param string $dir
* @param array|null $manual
* @param int|null $sort_flags
* @return static
* @phpstan-return static<T>
*/
public function order($by, $dir = 'asc', $manual = null, $sort_flags = null)
{
if (!$this->count()) {
return $this;
}
if ($by === 'random') {
return $this->shuffle();
}
$keys = $this->buildSort($by, $dir, $manual, $sort_flags);
return $this->createFrom(array_replace(array_flip($keys), $this->toArray()) ?? []);
}
/**
* @param string $order_by
* @param string $order_dir
* @param array|null $manual
* @param int|null $sort_flags
* @return array
*/
protected function buildSort($order_by = 'default', $order_dir = 'asc', $manual = null, $sort_flags = null): array
{
// do this header query work only once
$header_query = null;
$header_default = null;
if (strpos($order_by, 'header.') === 0) {
$query = explode('|', str_replace('header.', '', $order_by), 2);
$header_query = array_shift($query) ?? '';
$header_default = array_shift($query);
}
$list = [];
foreach ($this as $key => $child) {
switch ($order_by) {
case 'title':
$list[$key] = $child->title();
break;
case 'date':
$list[$key] = $child->date();
$sort_flags = SORT_REGULAR;
break;
case 'modified':
$list[$key] = $child->modified();
$sort_flags = SORT_REGULAR;
break;
case 'publish_date':
$list[$key] = $child->publishDate();
$sort_flags = SORT_REGULAR;
break;
case 'unpublish_date':
$list[$key] = $child->unpublishDate();
$sort_flags = SORT_REGULAR;
break;
case 'slug':
$list[$key] = $child->slug();
break;
case 'basename':
$list[$key] = Utils::basename($key);
break;
case 'folder':
$list[$key] = $child->folder();
break;
case 'manual':
case 'default':
default:
if (is_string($header_query)) {
/** @var Header $child_header */
$child_header = $child->header();
$header_value = $child_header->get($header_query);
if (is_array($header_value)) {
$list[$key] = implode(',', $header_value);
} elseif ($header_value) {
$list[$key] = $header_value;
} else {
$list[$key] = $header_default ?: $key;
}
$sort_flags = $sort_flags ?: SORT_REGULAR;
break;
}
$list[$key] = $key;
$sort_flags = $sort_flags ?: SORT_REGULAR;
}
}
if (null === $sort_flags) {
$sort_flags = SORT_NATURAL | SORT_FLAG_CASE;
}
// else just sort the list according to specified key
if (extension_loaded('intl') && Grav::instance()['config']->get('system.intl_enabled')) {
$locale = setlocale(LC_COLLATE, '0'); //`setlocale` with a '0' param returns the current locale set
$col = Collator::create($locale);
if ($col) {
$col->setAttribute(Collator::NUMERIC_COLLATION, Collator::ON);
if (($sort_flags & SORT_NATURAL) === SORT_NATURAL) {
$list = preg_replace_callback('~([0-9]+)\.~', static function ($number) {
return sprintf('%032d.', $number[0]);
}, $list);
if (!is_array($list)) {
throw new RuntimeException('Internal Error');
}
$list_vals = array_values($list);
if (is_numeric(array_shift($list_vals))) {
$sort_flags = Collator::SORT_REGULAR;
} else {
$sort_flags = Collator::SORT_STRING;
}
}
$col->asort($list, $sort_flags);
} else {
asort($list, $sort_flags);
}
} else {
asort($list, $sort_flags);
}
// Move manually ordered items into the beginning of the list. Order of the unlisted items does not change.
if (is_array($manual) && !empty($manual)) {
$i = count($manual);
$new_list = [];
foreach ($list as $key => $dummy) {
$child = $this[$key] ?? null;
$order = $child ? array_search($child->slug, $manual, true) : false;
if ($order === false) {
$order = $i++;
}
$new_list[$key] = (int)$order;
}
$list = $new_list;
// Apply manual ordering to the list.
asort($list, SORT_NUMERIC);
}
if ($order_dir !== 'asc') {
$list = array_reverse($list);
}
return array_keys($list);
}
/**
* Mimicks Pages class.
*
* @return $this
* @deprecated 1.7 Not needed anymore in Flex Pages (does nothing).
*/
public function all()
{
return $this;
}
/**
* 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 static
* @phpstan-return static<T>
* @throws Exception
*/
public function dateRange($startDate = null, $endDate = null, $field = null)
{
$start = $startDate ? Utils::date2timestamp($startDate) : null;
$end = $endDate ? Utils::date2timestamp($endDate) : null;
$entries = [];
foreach ($this as $key => $object) {
if (!$object) {
continue;
}
$date = $field ? strtotime($object->getNestedProperty($field)) : $object->date();
if ((!$start || $date >= $start) && (!$end || $date <= $end)) {
$entries[$key] = $object;
}
}
return $this->createFrom($entries);
}
/**
* Creates new collection with only visible pages
*
* @return static The collection with only visible pages
* @phpstan-return static<T>
*/
public function visible()
{
$entries = [];
foreach ($this as $key => $object) {
if ($object && $object->visible()) {
$entries[$key] = $object;
}
}
return $this->createFrom($entries);
}
/**
* Creates new collection with only non-visible pages
*
* @return static The collection with only non-visible pages
* @phpstan-return static<T>
*/
public function nonVisible()
{
$entries = [];
foreach ($this as $key => $object) {
if ($object && !$object->visible()) {
$entries[$key] = $object;
}
}
return $this->createFrom($entries);
}
/**
* Creates new collection with only pages
*
* @return static The collection with only pages
* @phpstan-return static<T>
*/
public function pages()
{
$entries = [];
/**
* @var int|string $key
* @var PageInterface|null $object
*/
foreach ($this as $key => $object) {
if ($object && !$object->isModule()) {
$entries[$key] = $object;
}
}
return $this->createFrom($entries);
}
/**
* Creates new collection with only modules
*
* @return static The collection with only modules
* @phpstan-return static<T>
*/
public function modules()
{
$entries = [];
/**
* @var int|string $key
* @var PageInterface|null $object
*/
foreach ($this as $key => $object) {
if ($object && $object->isModule()) {
$entries[$key] = $object;
}
}
return $this->createFrom($entries);
}
/**
* Alias of modules()
*
* @return static
* @phpstan-return static<T>
*/
public function modular()
{
return $this->modules();
}
/**
* Alias of pages()
*
* @return static
* @phpstan-return static<T>
*/
public function nonModular()
{
return $this->pages();
}
/**
* Creates new collection with only published pages
*
* @return static The collection with only published pages
* @phpstan-return static<T>
*/
public function published()
{
$entries = [];
foreach ($this as $key => $object) {
if ($object && $object->published()) {
$entries[$key] = $object;
}
}
return $this->createFrom($entries);
}
/**
* Creates new collection with only non-published pages
*
* @return static The collection with only non-published pages
* @phpstan-return static<T>
*/
public function nonPublished()
{
$entries = [];
foreach ($this as $key => $object) {
if ($object && !$object->published()) {
$entries[$key] = $object;
}
}
return $this->createFrom($entries);
}
/**
* Creates new collection with only routable pages
*
* @return static The collection with only routable pages
* @phpstan-return static<T>
*/
public function routable()
{
$entries = [];
foreach ($this as $key => $object) {
if ($object && $object->routable()) {
$entries[$key] = $object;
}
}
return $this->createFrom($entries);
}
/**
* Creates new collection with only non-routable pages
*
* @return static The collection with only non-routable pages
* @phpstan-return static<T>
*/
public function nonRoutable()
{
$entries = [];
foreach ($this as $key => $object) {
if ($object && !$object->routable()) {
$entries[$key] = $object;
}
}
return $this->createFrom($entries);
}
/**
* Creates new collection with only pages of the specified type
*
* @param string $type
* @return static The collection
* @phpstan-return static<T>
*/
public function ofType($type)
{
$entries = [];
foreach ($this as $key => $object) {
if ($object && $object->template() === $type) {
$entries[$key] = $object;
}
}
return $this->createFrom($entries);
}
/**
* Creates new collection with only pages of one of the specified types
*
* @param string[] $types
* @return static The collection
* @phpstan-return static<T>
*/
public function ofOneOfTheseTypes($types)
{
$entries = [];
foreach ($this as $key => $object) {
if ($object && in_array($object->template(), $types, true)) {
$entries[$key] = $object;
}
}
return $this->createFrom($entries);
}
/**
* Creates new collection with only pages of one of the specified access levels
*
* @param array $accessLevels
* @return static The collection
* @phpstan-return static<T>
*/
public function ofOneOfTheseAccessLevels($accessLevels)
{
$entries = [];
foreach ($this as $key => $object) {
if ($object && isset($object->header()->access)) {
if (is_array($object->header()->access)) {
//Multiple values for access
$valid = false;
foreach ($object->header()->access as $index => $accessLevel) {
if (is_array($accessLevel)) {
foreach ($accessLevel as $innerIndex => $innerAccessLevel) {
if (in_array($innerAccessLevel, $accessLevels)) {
$valid = true;
}
}
} else {
if (in_array($index, $accessLevels)) {
$valid = true;
}
}
}
if ($valid) {
$entries[$key] = $object;
}
} else {
//Single value for access
if (in_array($object->header()->access, $accessLevels)) {
$entries[$key] = $object;
}
}
}
}
return $this->createFrom($entries);
}
/**
* @param bool $bool
* @return static
* @phpstan-return static<T>
*/
public function withOrdered(bool $bool = true)
{
$list = array_keys(array_filter($this->call('isOrdered', [$bool])));
return $this->select($list);
}
/**
* @param bool $bool
* @return static
* @phpstan-return static<T>
*/
public function withModules(bool $bool = true)
{
$list = array_keys(array_filter($this->call('isModule', [$bool])));
return $this->select($list);
}
/**
* @param bool $bool
* @return static
* @phpstan-return static<T>
*/
public function withPages(bool $bool = true)
{
$list = array_keys(array_filter($this->call('isPage', [$bool])));
return $this->select($list);
}
/**
* @param bool $bool
* @param string|null $languageCode
* @param bool|null $fallback
* @return static
* @phpstan-return static<T>
*/
public function withTranslation(bool $bool = true, string $languageCode = null, bool $fallback = null)
{
$list = array_keys(array_filter($this->call('hasTranslation', [$languageCode, $fallback])));
return $bool ? $this->select($list) : $this->unselect($list);
}
/**
* @param string|null $languageCode
* @param bool|null $fallback
* @return PageIndex
*/
public function withTranslated(string $languageCode = null, bool $fallback = null)
{
return $this->getIndex()->withTranslated($languageCode, $fallback);
}
/**
* Filter pages by given filters.
*
* - search: string
* - page_type: string|string[]
* - modular: bool
* - visible: bool
* - routable: bool
* - published: bool
* - page: bool
* - translated: bool
*
* @param array $filters
* @param bool $recursive
* @return static
* @phpstan-return static<T>
*/
public function filterBy(array $filters, bool $recursive = false)
{
$list = array_keys(array_filter($this->call('filterBy', [$filters, $recursive])));
return $this->select($list);
}
/**
* Get the extended version of this Collection with each page keyed by route
*
* @return array
* @throws Exception
*/
public function toExtendedArray(): array
{
$entries = [];
foreach ($this as $key => $object) {
if ($object) {
$entries[$object->route()] = $object->toArray();
}
}
return $entries;
}
/**
* @param array $options
* @return array
*/
public function getLevelListing(array $options): array
{
/** @var PageIndex $index */
$index = $this->getIndex();
return method_exists($index, 'getLevelListing') ? $index->getLevelListing($options) : [];
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Flex/Types/Pages/Traits/PageRoutableTrait.php | system/src/Grav/Common/Flex/Types/Pages/Traits/PageRoutableTrait.php | <?php
declare(strict_types=1);
/**
* @package Grav\Common\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Flex\Types\Pages\Traits;
use Grav\Common\Grav;
use Grav\Common\Page\Interfaces\PageCollectionInterface;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Common\Page\Pages;
use Grav\Common\Uri;
use Grav\Common\Utils;
use Grav\Framework\Filesystem\Filesystem;
use RuntimeException;
/**
* Implements PageRoutableInterface.
*/
trait PageRoutableTrait
{
/**
* 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)
{
if (Utils::isAdminPlugin()) {
return parent::parent();
}
if (null !== $var) {
throw new RuntimeException('Not Implemented');
}
if ($this->root()) {
return null;
}
/** @var Pages $pages */
$pages = Grav::instance()['pages'];
$filesystem = Filesystem::getInstance(false);
// FIXME: this does not work, needs to use $pages->get() with cached parent id!
$key = $this->getKey();
$parent_route = $filesystem->dirname('/' . $key);
return $parent_route !== '/' ? $pages->find($parent_route) : $pages->root();
}
/**
* Returns the item in the current position.
*
* @return int|null the index of the current page.
*/
public function currentPosition(): ?int
{
$path = $this->path();
$parent = $this->parent();
$collection = $parent ? $parent->collection('content', false) : null;
if (null !== $path && $collection instanceof PageCollectionInterface) {
return $collection->currentPosition($path);
}
return 1;
}
/**
* 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(): bool
{
$grav = Grav::instance();
$uri_path = rtrim(urldecode($grav['uri']->path()), '/') ?: '/';
$routes = $grav['pages']->routes();
return isset($routes[$uri_path]) && $routes[$uri_path] === $this->path();
}
/**
* 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(): bool
{
$grav = Grav::instance();
/** @var Uri $uri */
$uri = $grav['uri'];
/** @var Pages $pages */
$pages = $grav['pages'];
$uri_path = rtrim(urldecode($uri->path()), '/');
$routes = $pages->routes();
if (isset($routes[$uri_path])) {
$page = $pages->find($uri->route());
/** @var PageInterface|null $child_page */
$child_page = $page ? $page->parent() : null;
while ($child_page && !$child_page->root()) {
if ($this->path() === $child_page->path()) {
return true;
}
$child_page = $child_page->parent();
}
}
return false;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Flex/Types/Pages/Traits/PageLegacyTrait.php | system/src/Grav/Common/Flex/Types/Pages/Traits/PageLegacyTrait.php | <?php
declare(strict_types=1);
/**
* @package Grav\Common\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Flex\Types\Pages\Traits;
use Grav\Common\Grav;
use Grav\Common\Page\Collection;
use Grav\Common\Page\Interfaces\PageCollectionInterface;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Common\Page\Pages;
use Grav\Common\Utils;
use Grav\Framework\Flex\Interfaces\FlexIndexInterface;
use InvalidArgumentException;
use function is_array;
use function is_string;
/**
* Implements PageLegacyInterface.
*/
trait PageLegacyTrait
{
/**
* Returns children of this page.
*
* @return FlexIndexInterface|PageCollectionInterface|Collection
*/
public function children()
{
if (Utils::isAdminPlugin()) {
return parent::children();
}
/** @var Pages $pages */
$pages = Grav::instance()['pages'];
$path = $this->path() ?? '';
return $pages->children($path);
}
/**
* Check to see if this item is the first in an array of sub-pages.
*
* @return bool True if item is first.
*/
public function isFirst(): bool
{
if (Utils::isAdminPlugin()) {
return parent::isFirst();
}
$path = $this->path();
$parent = $this->parent();
$collection = $parent ? $parent->collection('content', false) : null;
if (null !== $path && $collection instanceof PageCollectionInterface) {
return $collection->isFirst($path);
}
return true;
}
/**
* Check to see if this item is the last in an array of sub-pages.
*
* @return bool True if item is last
*/
public function isLast(): bool
{
if (Utils::isAdminPlugin()) {
return parent::isLast();
}
$path = $this->path();
$parent = $this->parent();
$collection = $parent ? $parent->collection('content', false) : null;
if (null !== $path && $collection instanceof PageCollectionInterface) {
return $collection->isLast($path);
}
return true;
}
/**
* 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)
{
if (Utils::isAdminPlugin()) {
return parent::adjacentSibling($direction);
}
$path = $this->path();
$parent = $this->parent();
$collection = $parent ? $parent->collection('content', false) : null;
if (null !== $path && $collection instanceof PageCollectionInterface) {
$child = $collection->adjacentSibling($path, $direction);
if ($child instanceof PageInterface) {
return $child;
}
}
return false;
}
/**
* Helper method to return an ancestor page.
*
* @param string|null $lookup Name of the parent folder
* @return PageInterface|null page you were looking for if it exists
*/
public function ancestor($lookup = null)
{
if (Utils::isAdminPlugin()) {
return parent::ancestor($lookup);
}
/** @var Pages $pages */
$pages = Grav::instance()['pages'];
return $pages->ancestor($this->getProperty('parent_route'), $lookup);
}
/**
* Method that contains shared logic for inherited() and inheritedField()
*
* @param string $field Name of the parent folder
* @return array
*/
protected function getInheritedParams($field): array
{
if (Utils::isAdminPlugin()) {
return parent::getInheritedParams($field);
}
/** @var Pages $pages */
$pages = Grav::instance()['pages'];
$inherited = $pages->inherited($this->getProperty('parent_route'), $field);
$inheritedParams = $inherited ? (array)$inherited->value('header.' . $field) : [];
$currentParams = (array)$this->getFormValue('header.' . $field);
if ($inheritedParams && is_array($inheritedParams)) {
$currentParams = array_replace_recursive($inheritedParams, $currentParams);
}
return [$inherited, $currentParams];
}
/**
* Helper method to return a page.
*
* @param string $url the url of the page
* @param bool $all
* @return PageInterface|null page you were looking for if it exists
*/
public function find($url, $all = false)
{
if (Utils::isAdminPlugin()) {
return parent::find($url, $all);
}
/** @var Pages $pages */
$pages = Grav::instance()['pages'];
return $pages->find($url, $all);
}
/**
* Get a collection of pages in the current context.
*
* @param string|array $params
* @param bool $pagination
* @return PageCollectionInterface|Collection
* @throws InvalidArgumentException
*/
public function collection($params = 'content', $pagination = true)
{
if (Utils::isAdminPlugin()) {
return parent::collection($params, $pagination);
}
if (is_string($params)) {
// Look into a page header field.
$params = (array)$this->getFormValue('header.' . $params);
} elseif (!is_array($params)) {
throw new InvalidArgumentException('Argument should be either header variable name or array of parameters');
}
$context = [
'pagination' => $pagination,
'self' => $this
];
/** @var Pages $pages */
$pages = Grav::instance()['pages'];
return $pages->getCollection($params, $context);
}
/**
* @param string|array $value
* @param bool $only_published
* @return PageCollectionInterface|Collection
*/
public function evaluate($value, $only_published = true)
{
if (Utils::isAdminPlugin()) {
return parent::collection($value, $only_published);
}
$params = [
'items' => $value,
'published' => $only_published
];
$context = [
'event' => false,
'pagination' => false,
'url_taxonomy_filters' => false,
'self' => $this
];
/** @var Pages $pages */
$pages = Grav::instance()['pages'];
return $pages->getCollection($params, $context);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Flex/Types/Pages/Traits/PageTranslateTrait.php | system/src/Grav/Common/Flex/Types/Pages/Traits/PageTranslateTrait.php | <?php
declare(strict_types=1);
/**
* @package Grav\Common\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Flex\Types\Pages\Traits;
use Grav\Common\Grav;
use Grav\Common\Language\Language;
use Grav\Common\Page\Page;
use Grav\Common\Utils;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use SplFileInfo;
/**
* Implements PageTranslateInterface
*/
trait PageTranslateTrait
{
/**
* 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): array
{
if (Utils::isAdminPlugin()) {
return parent::translatedLanguages();
}
$translated = $this->getLanguageTemplates();
if (!$translated) {
return $translated;
}
$grav = Grav::instance();
/** @var Language $language */
$language = $grav['language'];
/** @var UniformResourceLocator $locator */
$locator = $grav['locator'];
$languages = $language->getLanguages();
$languages[] = '';
$defaultCode = $language->getDefault();
if (isset($translated[$defaultCode])) {
unset($translated['']);
}
foreach ($translated as $key => &$template) {
$template .= $key !== '' ? ".{$key}.md" : '.md';
}
unset($template);
$translated = array_intersect_key($translated, array_flip($languages));
$folder = $this->getStorageFolder();
if (!$folder) {
return [];
}
$folder = $locator->isStream($folder) ? $locator->getResource($folder) : GRAV_ROOT . "/{$folder}";
$list = array_fill_keys($languages, null);
foreach ($translated as $languageCode => $languageFile) {
$languageExtension = $languageCode ? ".{$languageCode}.md" : '.md';
$path = "{$folder}/{$languageFile}";
// FIXME: use flex, also rawRoute() does not fully work?
$aPage = new Page();
$aPage->init(new SplFileInfo($path), $languageExtension);
if ($onlyPublished && !$aPage->published()) {
continue;
}
$header = $aPage->header();
// @phpstan-ignore-next-line
$routes = $header->routes ?? [];
$route = $routes['default'] ?? $aPage->rawRoute();
if (!$route) {
$route = $aPage->route();
}
$list[$languageCode ?: $defaultCode] = $route ?? '';
}
$list = array_filter($list, static function ($var) {
return null !== $var;
});
// Hack to get the same result as with old pages.
foreach ($list as &$path) {
if ($path === '') {
$path = null;
}
}
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/Flex/Types/Pages/Traits/PageContentTrait.php | system/src/Grav/Common/Flex/Types/Pages/Traits/PageContentTrait.php | <?php
declare(strict_types=1);
/**
* @package Grav\Common\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Flex\Types\Pages\Traits;
use Grav\Common\Utils;
/**
* Implements PageContentInterface.
*/
trait PageContentTrait
{
/**
* @inheritdoc
*/
public function id($var = null): string
{
$property = 'id';
$value = null === $var ? $this->getProperty($property) : null;
if (null === $value) {
$value = $this->language() . ($var ?? ($this->modified() . md5($this->filePath() ?? $this->getKey())));
$this->setProperty($property, $value);
if ($this->doHasProperty($property)) {
$value = $this->getProperty($property);
}
}
return $value;
}
/**
* @inheritdoc
*/
public function date($var = null): int
{
return $this->loadHeaderProperty(
'date',
$var,
function ($value) {
$value = $value ? Utils::date2timestamp($value, $this->getProperty('dateformat')) : false;
if (!$value) {
// Get the specific translation updated date.
$meta = $this->getMetaData();
$language = $meta['lang'] ?? '';
$template = $this->getProperty('template');
$value = $meta['markdown'][$language][$template] ?? 0;
}
return $value ?: $this->modified();
}
);
}
/**
* @inheritdoc
* @param bool $bool
*/
public function isPage(bool $bool = true): bool
{
$meta = $this->getMetaData();
return empty($meta['markdown']) !== $bool;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Flex/Types/Pages/Storage/PageStorage.php | system/src/Grav/Common/Flex/Types/Pages/Storage/PageStorage.php | <?php
declare(strict_types=1);
/**
* @package Grav\Common\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Flex\Types\Pages\Storage;
use FilesystemIterator;
use Grav\Common\Debugger;
use Grav\Common\Flex\Types\Pages\PageIndex;
use Grav\Common\Grav;
use Grav\Common\Language\Language;
use Grav\Common\Utils;
use Grav\Framework\Filesystem\Filesystem;
use Grav\Framework\Flex\Storage\FolderStorage;
use RocketTheme\Toolbox\File\MarkdownFile;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use RuntimeException;
use SplFileInfo;
use function in_array;
use function is_string;
/**
* Class GravPageStorage
* @package Grav\Plugin\FlexObjects\Types\GravPages
*/
class PageStorage extends FolderStorage
{
/** @var bool */
protected $ignore_hidden;
/** @var array */
protected $ignore_files;
/** @var array */
protected $ignore_folders;
/** @var bool */
protected $include_default_lang_file_extension;
/** @var bool */
protected $recurse;
/** @var string */
protected $base_path;
/** @var int */
protected $flags;
/** @var string */
protected $regex;
/**
* @param array $options
*/
protected function initOptions(array $options): void
{
parent::initOptions($options);
$this->flags = FilesystemIterator::KEY_AS_FILENAME | FilesystemIterator::CURRENT_AS_FILEINFO
| FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS;
$grav = Grav::instance();
$config = $grav['config'];
$this->ignore_hidden = (bool)$config->get('system.pages.ignore_hidden');
$this->ignore_files = (array)$config->get('system.pages.ignore_files');
$this->ignore_folders = (array)$config->get('system.pages.ignore_folders');
$this->include_default_lang_file_extension = (bool)$config->get('system.languages.include_default_lang_file_extension', true);
$this->recurse = (bool)($options['recurse'] ?? true);
$this->regex = '/(\.([\w\d_-]+))?\.md$/D';
}
/**
* @param string $key
* @param bool $variations
* @return array
*/
public function parseKey(string $key, bool $variations = true): array
{
if (mb_strpos($key, '|') !== false) {
[$key, $params] = explode('|', $key, 2);
} else {
$params = '';
}
$key = ltrim($key, '/');
$keys = parent::parseKey($key, false) + ['params' => $params];
if ($variations) {
$keys += $this->parseParams($key, $params);
}
return $keys;
}
/**
* @param string $key
* @return string
*/
public function readFrontmatter(string $key): string
{
$path = $this->getPathFromKey($key);
$file = $this->getFile($path);
try {
if ($file instanceof MarkdownFile) {
$frontmatter = $file->frontmatter();
} else {
$frontmatter = $file->raw();
}
} catch (RuntimeException $e) {
$frontmatter = 'ERROR: ' . $e->getMessage();
} finally {
$file->free();
unset($file);
}
return $frontmatter;
}
/**
* @param string $key
* @return string
*/
public function readRaw(string $key): string
{
$path = $this->getPathFromKey($key);
$file = $this->getFile($path);
try {
$raw = $file->raw();
} catch (RuntimeException $e) {
$raw = 'ERROR: ' . $e->getMessage();
} finally {
$file->free();
unset($file);
}
return $raw;
}
/**
* @param array $keys
* @param bool $includeParams
* @return string
*/
public function buildStorageKey(array $keys, bool $includeParams = true): string
{
$key = $keys['key'] ?? null;
if (null === $key) {
$key = $keys['parent_key'] ?? '';
if ($key !== '') {
$key .= '/';
}
$order = $keys['order'] ?? null;
$folder = $keys['folder'] ?? 'undefined';
$key .= is_numeric($order) ? sprintf('%02d.%s', $order, $folder) : $folder;
}
$params = $includeParams ? $this->buildStorageKeyParams($keys) : '';
return $params ? "{$key}|{$params}" : $key;
}
/**
* @param array $keys
* @return string
*/
public function buildStorageKeyParams(array $keys): string
{
$params = $keys['template'] ?? '';
$language = $keys['lang'] ?? '';
if ($language) {
$params .= '.' . $language;
}
return $params;
}
/**
* @param array $keys
* @return string
*/
public function buildFolder(array $keys): string
{
return $this->dataFolder . '/' . $this->buildStorageKey($keys, false);
}
/**
* @param array $keys
* @return string
*/
public function buildFilename(array $keys): string
{
$file = $this->buildStorageKeyParams($keys);
// Template is optional; if it is missing, we need to have to load the object metadata.
if ($file && $file[0] === '.') {
$meta = $this->getObjectMeta($this->buildStorageKey($keys, false));
$file = ($meta['template'] ?? 'folder') . $file;
}
return $file . $this->dataExt;
}
/**
* @param array $keys
* @return string
*/
public function buildFilepath(array $keys): string
{
$folder = $this->buildFolder($keys);
$filename = $this->buildFilename($keys);
return rtrim($folder, '/') !== $folder ? $folder . $filename : $folder . '/' . $filename;
}
/**
* @param array $row
* @param bool $setDefaultLang
* @return array
*/
public function extractKeysFromRow(array $row, bool $setDefaultLang = true): array
{
$meta = $row['__META'] ?? null;
$storageKey = $row['storage_key'] ?? $meta['storage_key'] ?? '';
$keyMeta = $storageKey !== '' ? $this->extractKeysFromStorageKey($storageKey) : null;
$parentKey = $row['parent_key'] ?? $meta['parent_key'] ?? $keyMeta['parent_key'] ?? '';
$order = $row['order'] ?? $meta['order'] ?? $keyMeta['order'] ?? null;
$folder = $row['folder'] ?? $meta['folder'] ?? $keyMeta['folder'] ?? '';
$template = $row['template'] ?? $meta['template'] ?? $keyMeta['template'] ?? '';
$lang = $row['lang'] ?? $meta['lang'] ?? $keyMeta['lang'] ?? '';
// Handle default language, if it should be saved without language extension.
if ($setDefaultLang && empty($meta['markdown'][$lang])) {
$grav = Grav::instance();
/** @var Language $language */
$language = $grav['language'];
$default = $language->getDefault();
// Make sure that the default language file doesn't exist before overriding it.
if (empty($meta['markdown'][$default])) {
if ($this->include_default_lang_file_extension) {
if ($lang === '') {
$lang = $language->getDefault();
}
} elseif ($lang === $language->getDefault()) {
$lang = '';
}
}
}
$keys = [
'key' => null,
'params' => null,
'parent_key' => $parentKey,
'order' => is_numeric($order) ? (int)$order : null,
'folder' => $folder,
'template' => $template,
'lang' => $lang
];
$keys['key'] = $this->buildStorageKey($keys, false);
$keys['params'] = $this->buildStorageKeyParams($keys);
return $keys;
}
/**
* @param string $key
* @return array
*/
public function extractKeysFromStorageKey(string $key): array
{
if (mb_strpos($key, '|') !== false) {
[$key, $params] = explode('|', $key, 2);
[$template, $language] = mb_strpos($params, '.') !== false ? explode('.', $params, 2) : [$params, ''];
} else {
$params = $template = $language = '';
}
$objectKey = Utils::basename($key);
if (preg_match('|^(\d+)\.(.+)$|', $objectKey, $matches)) {
[, $order, $folder] = $matches;
} else {
[$order, $folder] = ['', $objectKey];
}
$filesystem = Filesystem::getInstance(false);
$parentKey = ltrim($filesystem->dirname('/' . $key), '/');
return [
'key' => $key,
'params' => $params,
'parent_key' => $parentKey,
'order' => is_numeric($order) ? (int)$order : null,
'folder' => $folder,
'template' => $template,
'lang' => $language
];
}
/**
* @param string $key
* @param string $params
* @return array
*/
protected function parseParams(string $key, string $params): array
{
if (mb_strpos($params, '.') !== false) {
[$template, $language] = explode('.', $params, 2);
} else {
$template = $params;
$language = '';
}
if ($template === '') {
$meta = $this->getObjectMeta($key);
$template = $meta['template'] ?? 'folder';
}
return [
'file' => $template . ($language ? '.' . $language : ''),
'template' => $template,
'lang' => $language
];
}
/**
* Prepares the row for saving and returns the storage key for the record.
*
* @param array $row
*/
protected function prepareRow(array &$row): void
{
// Remove keys used in the filesystem.
unset($row['parent_key'], $row['order'], $row['folder'], $row['template'], $row['lang']);
}
/**
* @param string $key
* @return array
*/
protected function loadRow(string $key): ?array
{
$data = parent::loadRow($key);
// Special case for root page.
if ($key === '' && null !== $data) {
$data['root'] = true;
}
return $data;
}
/**
* Page storage supports moving and copying the pages and their languages.
*
* $row['__META']['copy'] = true Use this if you want to copy the whole folder, otherwise it will be moved
* $row['__META']['clone'] = true Use this if you want to clone the file, otherwise it will be renamed
*
* @param string $key
* @param array $row
* @return array
*/
protected function saveRow(string $key, array $row): array
{
// Initialize all key-related variables.
$newKeys = $this->extractKeysFromRow($row);
$newKey = $this->buildStorageKey($newKeys);
$newFolder = $this->buildFolder($newKeys);
$newFilename = $this->buildFilename($newKeys);
$newFilepath = rtrim($newFolder, '/') !== $newFolder ? $newFolder . $newFilename : $newFolder . '/' . $newFilename;
try {
if ($key === '' && empty($row['root'])) {
throw new RuntimeException('Page has no path');
}
$grav = Grav::instance();
/** @var Debugger $debugger */
$debugger = $grav['debugger'];
$debugger->addMessage("Save page: {$newKey}", 'debug');
// Check if the row already exists.
$oldKey = $row['__META']['storage_key'] ?? null;
if (is_string($oldKey)) {
// Initialize all old key-related variables.
$oldKeys = $this->extractKeysFromRow(['__META' => $row['__META']], false);
$oldFolder = $this->buildFolder($oldKeys);
$oldFilename = $this->buildFilename($oldKeys);
// Check if folder has changed.
if ($oldFolder !== $newFolder && file_exists($oldFolder)) {
$isCopy = $row['__META']['copy'] ?? false;
if ($isCopy) {
if (strpos($newFolder, $oldFolder . '/') === 0) {
throw new RuntimeException(sprintf('Page /%s cannot be copied to itself', $oldKey));
}
$this->copyRow($oldKey, $newKey);
$debugger->addMessage("Page copied: {$oldFolder} => {$newFolder}", 'debug');
} else {
if (strpos($newFolder, $oldFolder . '/') === 0) {
throw new RuntimeException(sprintf('Page /%s cannot be moved to itself', $oldKey));
}
$this->renameRow($oldKey, $newKey);
$debugger->addMessage("Page moved: {$oldFolder} => {$newFolder}", 'debug');
}
}
// Check if filename has changed.
if ($oldFilename !== $newFilename) {
// Get instance of the old file (we have already copied/moved it).
$oldFilepath = "{$newFolder}/{$oldFilename}";
$file = $this->getFile($oldFilepath);
// Rename the file if we aren't supposed to clone it.
$isClone = $row['__META']['clone'] ?? false;
if (!$isClone && $file->exists()) {
/** @var UniformResourceLocator $locator */
$locator = $grav['locator'];
$toPath = $locator->isStream($newFilepath) ? $locator->findResource($newFilepath, true, true) : GRAV_ROOT . "/{$newFilepath}";
$success = $file->rename($toPath);
if (!$success) {
throw new RuntimeException("Changing page template failed: {$oldFilepath} => {$newFilepath}");
}
$debugger->addMessage("Page template changed: {$oldFilename} => {$newFilename}", 'debug');
} else {
$file = null;
$debugger->addMessage("Page template created: {$newFilename}", 'debug');
}
}
}
// Clean up the data to be saved.
$this->prepareRow($row);
unset($row['__META'], $row['__ERROR']);
if (!isset($file)) {
$file = $this->getFile($newFilepath);
}
// Compare existing file content to the new one and save the file only if content has been changed.
$file->free();
$oldRaw = $file->raw();
$file->content($row);
$newRaw = $file->raw();
if ($oldRaw !== $newRaw) {
$file->save($row);
$debugger->addMessage("Page content saved: {$newFilepath}", 'debug');
} else {
$debugger->addMessage('Page content has not been changed, do not update the file', 'debug');
}
} catch (RuntimeException $e) {
$name = isset($file) ? $file->filename() : $newKey;
throw new RuntimeException(sprintf('Flex saveRow(%s): %s', $name, $e->getMessage()));
} finally {
/** @var UniformResourceLocator $locator */
$locator = Grav::instance()['locator'];
$locator->clearCache();
if (isset($file)) {
$file->free();
unset($file);
}
}
$row['__META'] = $this->getObjectMeta($newKey, true);
return $row;
}
/**
* Check if page folder should be deleted.
*
* Deleting page can be done either by deleting everything or just a single language.
* If key contains the language, delete only it, unless it is the last language.
*
* @param string $key
* @return bool
*/
protected function canDeleteFolder(string $key): bool
{
// Return true if there's no language in the key.
$keys = $this->extractKeysFromStorageKey($key);
if (!$keys['lang']) {
return true;
}
// Get the main key and reload meta.
$key = $this->buildStorageKey($keys);
$meta = $this->getObjectMeta($key, true);
// Return true if there aren't any markdown files left.
return empty($meta['markdown'] ?? []);
}
/**
* Get key from the filesystem path.
*
* @param string $path
* @return string
*/
protected function getKeyFromPath(string $path): string
{
if ($this->base_path) {
$path = $this->base_path . '/' . $path;
}
return $path;
}
/**
* Returns list of all stored keys in [key => timestamp] pairs.
*
* @return array
*/
protected function buildIndex(): array
{
$this->clearCache();
return $this->getIndexMeta();
}
/**
* @param string $key
* @param bool $reload
* @return array
*/
protected function getObjectMeta(string $key, bool $reload = false): array
{
$keys = $this->extractKeysFromStorageKey($key);
$key = $keys['key'];
if ($reload || !isset($this->meta[$key])) {
/** @var UniformResourceLocator $locator */
$locator = Grav::instance()['locator'];
if (mb_strpos($key, '@@') === false) {
$path = $this->getStoragePath($key);
if (is_string($path)) {
$path = $locator->isStream($path) ? $locator->findResource($path) : GRAV_ROOT . "/{$path}";
} else {
$path = null;
}
} else {
$path = null;
}
$modified = 0;
$markdown = [];
$children = [];
if (is_string($path) && is_dir($path)) {
$modified = filemtime($path);
$iterator = new FilesystemIterator($path, $this->flags);
/** @var SplFileInfo $info */
foreach ($iterator as $k => $info) {
// Ignore all hidden files if set.
if ($k === '' || ($this->ignore_hidden && $k[0] === '.')) {
continue;
}
if ($info->isDir()) {
// Ignore all folders in ignore list.
if ($this->ignore_folders && in_array($k, $this->ignore_folders, true)) {
continue;
}
$children[$k] = false;
} else {
// Ignore all files in ignore list.
if ($this->ignore_files && in_array($k, $this->ignore_files, true)) {
continue;
}
$timestamp = $info->getMTime();
// Page is the one that matches to $page_extensions list with the lowest index number.
if (preg_match($this->regex, $k, $matches)) {
$mark = $matches[2] ?? '';
$ext = $matches[1] ?? '';
$ext .= $this->dataExt;
$markdown[$mark][Utils::basename($k, $ext)] = $timestamp;
}
$modified = max($modified, $timestamp);
}
}
}
$rawRoute = trim(preg_replace(PageIndex::PAGE_ROUTE_REGEX, '/', "/{$key}") ?? '', '/');
$route = PageIndex::normalizeRoute($rawRoute);
ksort($markdown, SORT_NATURAL | SORT_FLAG_CASE);
ksort($children, SORT_NATURAL | SORT_FLAG_CASE);
$file = array_key_first($markdown[''] ?? (reset($markdown) ?: []));
$meta = [
'key' => $route,
'storage_key' => $key,
'template' => $file,
'storage_timestamp' => $modified,
];
if ($markdown) {
$meta['markdown'] = $markdown;
}
if ($children) {
$meta['children'] = $children;
}
$meta['checksum'] = md5(json_encode($meta) ?: '');
// Cache meta as copy.
$this->meta[$key] = $meta;
} else {
$meta = $this->meta[$key];
}
$params = $keys['params'];
if ($params) {
$language = $keys['lang'];
$template = $keys['template'] ?: array_key_first($meta['markdown'][$language]) ?? $meta['template'];
$meta['exists'] = ($template && !empty($meta['children'])) || isset($meta['markdown'][$language][$template]);
$meta['storage_key'] .= '|' . $params;
$meta['template'] = $template;
$meta['lang'] = $language;
}
return $meta;
}
/**
* @return array
*/
protected function getIndexMeta(): array
{
$queue = [''];
$list = [];
do {
$current = array_pop($queue);
if ($current === null) {
break;
}
$meta = $this->getObjectMeta($current);
$storage_key = $meta['storage_key'];
if (!empty($meta['children'])) {
$prefix = $storage_key . ($storage_key !== '' ? '/' : '');
foreach ($meta['children'] as $child => $value) {
$queue[] = $prefix . $child;
}
}
$list[$storage_key] = $meta;
} while ($queue);
ksort($list, SORT_NATURAL | SORT_FLAG_CASE);
// Update parent timestamps.
foreach (array_reverse($list) as $storage_key => $meta) {
if ($storage_key !== '') {
$filesystem = Filesystem::getInstance(false);
$storage_key = (string)$storage_key;
$parentKey = $filesystem->dirname($storage_key);
if ($parentKey === '.') {
$parentKey = '';
}
/** @phpstan-var array{'storage_key': string, 'storage_timestamp': int, 'children': array<string, mixed>} $parent */
$parent = &$list[$parentKey];
$basename = Utils::basename($storage_key);
if (isset($parent['children'][$basename])) {
$timestamp = $meta['storage_timestamp'];
$parent['children'][$basename] = $timestamp;
if ($basename && $basename[0] === '_') {
$parent['storage_timestamp'] = max($parent['storage_timestamp'], $timestamp);
}
}
}
}
return $list;
}
/**
* @return string
*/
protected function getNewKey(): string
{
throw new RuntimeException('Generating random key is disabled for pages');
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Flex/Types/UserGroups/UserGroupObject.php | system/src/Grav/Common/Flex/Types/UserGroups/UserGroupObject.php | <?php
declare(strict_types=1);
/**
* @package Grav\Common\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Flex\Types\UserGroups;
use Grav\Common\Flex\FlexObject;
use Grav\Common\Grav;
use Grav\Common\User\Access;
use Grav\Common\User\Interfaces\UserGroupInterface;
use function is_bool;
/**
* Flex User Group
*
* @package Grav\Common\User
*
* @property string $groupname
* @property Access $access
*/
class UserGroupObject extends FlexObject implements UserGroupInterface
{
/** @var Access */
protected $_access;
/** @var array|null */
protected $access;
/**
* @return array
*/
public static function getCachedMethods(): array
{
return [
'authorize' => false,
] + parent::getCachedMethods();
}
/**
* @return string
*/
public function getTitle(): string
{
return $this->getProperty('readableName');
}
/**
* 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
{
if ($scope === 'test') {
$scope = null;
} elseif (!$this->getProperty('enabled', true)) {
return null;
}
$access = $this->getAccess();
$authorized = $access->authorize($action, $scope);
if (is_bool($authorized)) {
return $authorized;
}
return $access->authorize('admin.super') ? true : null;
}
public static function groupNames(): array
{
$groups = [];
$user_groups = Grav::instance()['user_groups'] ?? [];
foreach ($user_groups as $key => $group) {
$groups[$key] = $group->readableName;
}
return $groups;
}
/**
* @return Access
*/
protected function getAccess(): Access
{
if (null === $this->_access) {
$this->getProperty('access');
}
return $this->_access;
}
/**
* @param mixed $value
* @return array
*/
protected function offsetLoad_access($value): array
{
if (!$value instanceof Access) {
$value = new Access($value);
}
$this->_access = $value;
return $value->jsonSerialize();
}
/**
* @param mixed $value
* @return array
*/
protected function offsetPrepare_access($value): array
{
return $this->offsetLoad_access($value);
}
/**
* @param array|null $value
* @return array|null
*/
protected function offsetSerialize_access(?array $value): ?array
{
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/Flex/Types/UserGroups/UserGroupIndex.php | system/src/Grav/Common/Flex/Types/UserGroups/UserGroupIndex.php | <?php
declare(strict_types=1);
/**
* @package Grav\Common\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Flex\Types\UserGroups;
use Grav\Common\Flex\FlexIndex;
/**
* Class GroupIndex
* @package Grav\Common\User\FlexUser
*
* @extends FlexIndex<UserGroupObject,UserGroupCollection>
*/
class UserGroupIndex extends FlexIndex
{
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Flex/Types/UserGroups/UserGroupCollection.php | system/src/Grav/Common/Flex/Types/UserGroups/UserGroupCollection.php | <?php
declare(strict_types=1);
/**
* @package Grav\Common\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Flex\Types\UserGroups;
use Grav\Common\Flex\FlexCollection;
/**
* Class UserGroupCollection
* @package Grav\Common\Flex\Types\UserGroups
*
* @extends FlexCollection<UserGroupObject>
*/
class UserGroupCollection extends FlexCollection
{
/**
* @return array
*/
public static function getCachedMethods(): array
{
return [
'authorize' => false,
] + parent::getCachedMethods();
}
/**
* 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
{
$authorized = null;
/** @var UserGroupObject $object */
foreach ($this as $object) {
$auth = $object->authorize($action, $scope);
if ($auth === true) {
$authorized = true;
} elseif ($auth === false) {
return false;
}
}
return $authorized;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Flex/Traits/FlexCollectionTrait.php | system/src/Grav/Common/Flex/Traits/FlexCollectionTrait.php | <?php
declare(strict_types=1);
/**
* @package Grav\Common\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Flex\Traits;
use RocketTheme\Toolbox\Event\Event;
/**
* Trait FlexCollectionTrait
* @package Grav\Common\Flex\Traits
*/
trait FlexCollectionTrait
{
use FlexCommonTrait;
/**
* @param string $name
* @param object|null $event
* @return $this
*/
public function triggerEvent(string $name, $event = null)
{
if (null === $event) {
$event = new Event([
'type' => 'flex',
'directory' => $this->getFlexDirectory(),
'collection' => $this
]);
}
if (strpos($name, 'onFlexCollection') !== 0 && strpos($name, 'on') === 0) {
$name = 'onFlexCollection' . substr($name, 2);
}
$container = $this->getContainer();
if ($event instanceof Event) {
$container->fireEvent($name, $event);
} else {
$container->dispatchEvent($event);
}
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/Flex/Traits/FlexObjectTrait.php | system/src/Grav/Common/Flex/Traits/FlexObjectTrait.php | <?php
declare(strict_types=1);
/**
* @package Grav\Common\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Flex\Traits;
use RocketTheme\Toolbox\Event\Event;
/**
* Trait FlexObjectTrait
* @package Grav\Common\Flex\Traits
*/
trait FlexObjectTrait
{
use FlexCommonTrait;
/**
* @param string $name
* @param object|null $event
* @return $this
*/
public function triggerEvent(string $name, $event = null)
{
$events = [
'onRender' => 'onFlexObjectRender',
'onBeforeSave' => 'onFlexObjectBeforeSave',
'onAfterSave' => 'onFlexObjectAfterSave',
'onBeforeDelete' => 'onFlexObjectBeforeDelete',
'onAfterDelete' => 'onFlexObjectAfterDelete'
];
if (null === $event) {
$event = new Event([
'type' => 'flex',
'directory' => $this->getFlexDirectory(),
'object' => $this
]);
}
if (isset($events['name'])) {
$name = $events['name'];
} elseif (strpos($name, 'onFlexObject') !== 0 && strpos($name, 'on') === 0) {
$name = 'onFlexObject' . substr($name, 2);
}
$container = $this->getContainer();
if ($event instanceof Event) {
$container->fireEvent($name, $event);
} else {
$container->dispatchEvent($event);
}
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/Flex/Traits/FlexIndexTrait.php | system/src/Grav/Common/Flex/Traits/FlexIndexTrait.php | <?php
declare(strict_types=1);
/**
* @package Grav\Common\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Flex\Traits;
/**
* Trait FlexIndexTrait
* @package Grav\Common\Flex\Traits
*/
trait FlexIndexTrait
{
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Flex/Traits/FlexCommonTrait.php | system/src/Grav/Common/Flex/Traits/FlexCommonTrait.php | <?php
declare(strict_types=1);
/**
* @package Grav\Common\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Flex\Traits;
use Grav\Common\Debugger;
use Grav\Common\Grav;
use Grav\Common\Twig\Twig;
use Twig\Error\LoaderError;
use Twig\Error\SyntaxError;
use Twig\Template;
use Twig\TemplateWrapper;
/**
* Trait FlexCommonTrait
* @package Grav\Common\Flex\Traits
*/
trait FlexCommonTrait
{
/**
* @param string $layout
* @return Template|TemplateWrapper
* @throws LoaderError
* @throws SyntaxError
*/
protected function getTemplate($layout)
{
$container = $this->getContainer();
/** @var Twig $twig */
$twig = $container['twig'];
try {
return $twig->twig()->resolveTemplate($this->getTemplatePaths($layout));
} catch (LoaderError $e) {
/** @var Debugger $debugger */
$debugger = Grav::instance()['debugger'];
$debugger->addException($e);
return $twig->twig()->resolveTemplate(['flex/404.html.twig']);
}
}
abstract protected function getTemplatePaths(string $layout): array;
abstract protected function getContainer(): Grav;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Flex/Traits/FlexGravTrait.php | system/src/Grav/Common/Flex/Traits/FlexGravTrait.php | <?php
declare(strict_types=1);
/**
* @package Grav\Common\Flex
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Flex\Traits;
use Grav\Common\Grav;
use Grav\Common\User\Interfaces\UserInterface;
use Grav\Framework\Flex\Flex;
/**
* Implements Grav specific logic
*/
trait FlexGravTrait
{
/**
* @return Grav
*/
protected function getContainer(): Grav
{
return Grav::instance();
}
/**
* @return Flex
*/
protected function getFlexContainer(): Flex
{
$container = $this->getContainer();
/** @var Flex $flex */
$flex = $container['flex'];
return $flex;
}
/**
* @return UserInterface|null
*/
protected function getActiveUser(): ?UserInterface
{
$container = $this->getContainer();
/** @var UserInterface|null $user */
$user = $container['user'] ?? null;
return $user;
}
/**
* @return bool
*/
protected function isAdminSite(): bool
{
$container = $this->getContainer();
return isset($container['admin']);
}
/**
* @return string
*/
protected function getAuthorizeScope(): string
{
return $this->isAdminSite() ? 'admin' : 'site';
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/GPM/GPM.php | system/src/Grav/Common/GPM/GPM.php | <?php
/**
* @package Grav\Common\GPM
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\GPM;
use Exception;
use Grav\Common\Grav;
use Grav\Common\Filesystem\Folder;
use Grav\Common\HTTP\Response;
use Grav\Common\Inflector;
use Grav\Common\Iterator;
use Grav\Common\Utils;
use RocketTheme\Toolbox\File\YamlFile;
use RuntimeException;
use stdClass;
use function array_key_exists;
use function count;
use function in_array;
use function is_array;
use function is_object;
/**
* Class GPM
* @package Grav\Common\GPM
*/
class GPM extends Iterator
{
/** @var Local\Packages Local installed Packages */
private $installed;
/** @var Remote\Packages|null Remote available Packages */
private $repository;
/** @var Remote\GravCore|null Remove Grav Packages */
private $grav;
/** @var bool */
private $refresh;
/** @var callable|null */
private $callback;
/** @var array Internal cache */
protected $cache;
/** @var array */
protected $install_paths = [
'plugins' => 'user/plugins/%name%',
'themes' => 'user/themes/%name%',
'skeletons' => 'user/'
];
/**
* Creates a new GPM instance with Local and Remote packages available
*
* @param bool $refresh Applies to Remote Packages only and forces a refetch of data
* @param callable|null $callback Either a function or callback in array notation
*/
public function __construct($refresh = false, $callback = null)
{
parent::__construct();
Folder::create(CACHE_DIR . '/gpm');
$this->cache = [];
$this->installed = new Local\Packages();
$this->refresh = $refresh;
$this->callback = $callback;
}
/**
* Magic getter method
*
* @param string $offset Asset name value
* @return mixed Asset value
*/
#[\ReturnTypeWillChange]
public function __get($offset)
{
switch ($offset) {
case 'grav':
return $this->getGrav();
}
return parent::__get($offset);
}
/**
* Magic method to determine if the attribute is set
*
* @param string $offset Asset name value
* @return bool True if the value is set
*/
#[\ReturnTypeWillChange]
public function __isset($offset)
{
switch ($offset) {
case 'grav':
return $this->getGrav() !== null;
}
return parent::__isset($offset);
}
/**
* Return the locally installed packages
*
* @return Local\Packages
*/
public function getInstalled()
{
return $this->installed;
}
/**
* Returns the Locally installable packages
*
* @param array $list_type_installed
* @return array The installed packages
*/
public function getInstallable($list_type_installed = ['plugins' => true, 'themes' => true])
{
$items = ['total' => 0];
foreach ($list_type_installed as $type => $type_installed) {
if ($type_installed === false) {
continue;
}
$methodInstallableType = 'getInstalled' . ucfirst($type);
$to_install = $this->$methodInstallableType();
$items[$type] = $to_install;
$items['total'] += count($to_install);
}
return $items;
}
/**
* Returns the amount of locally installed packages
*
* @return int Amount of installed packages
*/
public function countInstalled()
{
$installed = $this->getInstalled();
return count($installed['plugins']) + count($installed['themes']);
}
/**
* Return the instance of a specific Package
*
* @param string $slug The slug of the Package
* @return Local\Package|null The instance of the Package
*/
public function getInstalledPackage($slug)
{
return $this->getInstalledPlugin($slug) ?? $this->getInstalledTheme($slug);
}
/**
* Return the instance of a specific Plugin
*
* @param string $slug The slug of the Plugin
* @return Local\Package|null The instance of the Plugin
*/
public function getInstalledPlugin($slug)
{
return $this->installed['plugins'][$slug] ?? null;
}
/**
* Returns the Locally installed plugins
* @return Iterator The installed plugins
*/
public function getInstalledPlugins()
{
return $this->installed['plugins'];
}
/**
* Returns the plugin's enabled state
*
* @param string $slug
* @return bool True if the Plugin is Enabled. False if manually set to enable:false. Null otherwise.
*/
public function isPluginEnabled($slug): bool
{
$grav = Grav::instance();
return ($grav['config']['plugins'][$slug]['enabled'] ?? false) === true;
}
/**
* Checks if a Plugin is installed
*
* @param string $slug The slug of the Plugin
* @return bool True if the Plugin has been installed. False otherwise
*/
public function isPluginInstalled($slug): bool
{
return isset($this->installed['plugins'][$slug]);
}
/**
* @param string $slug
* @return bool
*/
public function isPluginInstalledAsSymlink($slug)
{
$plugin = $this->getInstalledPlugin($slug);
return (bool)($plugin->symlink ?? false);
}
/**
* Return the instance of a specific Theme
*
* @param string $slug The slug of the Theme
* @return Local\Package|null The instance of the Theme
*/
public function getInstalledTheme($slug)
{
return $this->installed['themes'][$slug] ?? null;
}
/**
* Returns the Locally installed themes
*
* @return Iterator The installed themes
*/
public function getInstalledThemes()
{
return $this->installed['themes'];
}
/**
* Checks if a Theme is enabled
*
* @param string $slug The slug of the Theme
* @return bool True if the Theme has been set to the default theme. False if installed, but not enabled. Null otherwise.
*/
public function isThemeEnabled($slug): bool
{
$grav = Grav::instance();
$current_theme = $grav['config']['system']['pages']['theme'] ?? null;
return $current_theme === $slug;
}
/**
* Checks if a Theme is installed
*
* @param string $slug The slug of the Theme
* @return bool True if the Theme has been installed. False otherwise
*/
public function isThemeInstalled($slug): bool
{
return isset($this->installed['themes'][$slug]);
}
/**
* Returns the amount of updates available
*
* @return int Amount of available updates
*/
public function countUpdates()
{
return count($this->getUpdatablePlugins()) + count($this->getUpdatableThemes());
}
/**
* Returns an array of Plugins and Themes that can be updated.
* Plugins and Themes are extended with the `available` property that relies to the remote version
*
* @param array $list_type_update specifies what type of package to update
* @return array Array of updatable Plugins and Themes.
* Format: ['total' => int, 'plugins' => array, 'themes' => array]
*/
public function getUpdatable($list_type_update = ['plugins' => true, 'themes' => true])
{
$items = ['total' => 0];
foreach ($list_type_update as $type => $type_updatable) {
if ($type_updatable === false) {
continue;
}
$methodUpdatableType = 'getUpdatable' . ucfirst($type);
$to_update = $this->$methodUpdatableType();
$items[$type] = $to_update;
$items['total'] += count($to_update);
}
return $items;
}
/**
* Returns an array of Plugins that can be updated.
* The Plugins are extended with the `available` property that relies to the remote version
*
* @return array Array of updatable Plugins
*/
public function getUpdatablePlugins()
{
$items = [];
$repository = $this->getRepository();
if (null === $repository) {
return $items;
}
$plugins = $repository['plugins'];
// local cache to speed things up
if (isset($this->cache[__METHOD__])) {
return $this->cache[__METHOD__];
}
foreach ($this->installed['plugins'] as $slug => $plugin) {
if (!isset($plugins[$slug]) || $plugin->symlink || !$plugin->version || $plugin->gpm === false) {
continue;
}
$local_version = $plugin->version ?? 'Unknown';
$remote_version = $plugins[$slug]->version;
if (version_compare($local_version, $remote_version) < 0) {
$plugins[$slug]->available = $remote_version;
$plugins[$slug]->version = $local_version;
$plugins[$slug]->type = $plugins[$slug]->release_type;
$items[$slug] = $plugins[$slug];
}
}
$this->cache[__METHOD__] = $items;
return $items;
}
/**
* Get the latest release of a package from the GPM
*
* @param string $package_name
* @return string|null
*/
public function getLatestVersionOfPackage($package_name)
{
$repository = $this->getRepository();
if (null === $repository) {
return null;
}
$plugins = $repository['plugins'];
if (isset($plugins[$package_name])) {
return $plugins[$package_name]->available ?: $plugins[$package_name]->version;
}
//Not a plugin, it's a theme?
$themes = $repository['themes'];
if (isset($themes[$package_name])) {
return $themes[$package_name]->available ?: $themes[$package_name]->version;
}
return null;
}
/**
* Check if a Plugin or Theme is updatable
*
* @param string $slug The slug of the package
* @return bool True if updatable. False otherwise or if not found
*/
public function isUpdatable($slug)
{
return $this->isPluginUpdatable($slug) || $this->isThemeUpdatable($slug);
}
/**
* Checks if a Plugin is updatable
*
* @param string $plugin The slug of the Plugin
* @return bool True if the Plugin is updatable. False otherwise
*/
public function isPluginUpdatable($plugin)
{
return array_key_exists($plugin, (array)$this->getUpdatablePlugins());
}
/**
* Returns an array of Themes that can be updated.
* The Themes are extended with the `available` property that relies to the remote version
*
* @return array Array of updatable Themes
*/
public function getUpdatableThemes()
{
$items = [];
$repository = $this->getRepository();
if (null === $repository) {
return $items;
}
$themes = $repository['themes'];
// local cache to speed things up
if (isset($this->cache[__METHOD__])) {
return $this->cache[__METHOD__];
}
foreach ($this->installed['themes'] as $slug => $plugin) {
if (!isset($themes[$slug]) || $plugin->symlink || !$plugin->version || $plugin->gpm === false) {
continue;
}
$local_version = $plugin->version ?? 'Unknown';
$remote_version = $themes[$slug]->version;
if (version_compare($local_version, $remote_version) < 0) {
$themes[$slug]->available = $remote_version;
$themes[$slug]->version = $local_version;
$themes[$slug]->type = $themes[$slug]->release_type;
$items[$slug] = $themes[$slug];
}
}
$this->cache[__METHOD__] = $items;
return $items;
}
/**
* Checks if a Theme is Updatable
*
* @param string $theme The slug of the Theme
* @return bool True if the Theme is updatable. False otherwise
*/
public function isThemeUpdatable($theme)
{
return array_key_exists($theme, (array)$this->getUpdatableThemes());
}
/**
* Get the release type of a package (stable / testing)
*
* @param string $package_name
* @return string|null
*/
public function getReleaseType($package_name)
{
$repository = $this->getRepository();
if (null === $repository) {
return null;
}
$plugins = $repository['plugins'];
if (isset($plugins[$package_name])) {
return $plugins[$package_name]->release_type;
}
//Not a plugin, it's a theme?
$themes = $repository['themes'];
if (isset($themes[$package_name])) {
return $themes[$package_name]->release_type;
}
return null;
}
/**
* Returns true if the package latest release is stable
*
* @param string $package_name
* @return bool
*/
public function isStableRelease($package_name)
{
return $this->getReleaseType($package_name) === 'stable';
}
/**
* Returns true if the package latest release is testing
*
* @param string $package_name
* @return bool
*/
public function isTestingRelease($package_name)
{
$package = $this->getInstalledPackage($package_name);
$testing = $package->testing ?? false;
return $this->getReleaseType($package_name) === 'testing' || $testing;
}
/**
* Returns a Plugin from the repository
*
* @param string $slug The slug of the Plugin
* @return Remote\Package|null Package if found, NULL if not
*/
public function getRepositoryPlugin($slug)
{
$packages = $this->getRepositoryPlugins();
return $packages ? ($packages[$slug] ?? null) : null;
}
/**
* Returns the list of Plugins available in the repository
*
* @return Iterator|null The Plugins remotely available
*/
public function getRepositoryPlugins()
{
return $this->getRepository()['plugins'] ?? null;
}
/**
* Returns a Theme from the repository
*
* @param string $slug The slug of the Theme
* @return Remote\Package|null Package if found, NULL if not
*/
public function getRepositoryTheme($slug)
{
$packages = $this->getRepositoryThemes();
return $packages ? ($packages[$slug] ?? null) : null;
}
/**
* Returns the list of Themes available in the repository
*
* @return Iterator|null The Themes remotely available
*/
public function getRepositoryThemes()
{
return $this->getRepository()['themes'] ?? null;
}
/**
* Returns the list of Plugins and Themes available in the repository
*
* @return Remote\Packages|null Available Plugins and Themes
* Format: ['plugins' => array, 'themes' => array]
*/
public function getRepository()
{
if (null === $this->repository) {
try {
$this->repository = new Remote\Packages($this->refresh, $this->callback);
} catch (Exception $e) {}
}
return $this->repository;
}
/**
* Returns Grav version available in the repository
*
* @return Remote\GravCore|null
*/
public function getGrav()
{
if (null === $this->grav) {
try {
$this->grav = new Remote\GravCore($this->refresh, $this->callback);
} catch (Exception $e) {}
}
return $this->grav;
}
/**
* Searches for a Package in the repository
*
* @param string $search Can be either the slug or the name
* @param bool $ignore_exception True if should not fire an exception (for use in Twig)
* @return Remote\Package|false Package if found, FALSE if not
*/
public function findPackage($search, $ignore_exception = false)
{
$search = strtolower($search);
$found = $this->getRepositoryPlugin($search) ?? $this->getRepositoryTheme($search);
if ($found) {
return $found;
}
$themes = $this->getRepositoryThemes();
$plugins = $this->getRepositoryPlugins();
if (null === $themes || null === $plugins) {
if (!is_writable(GRAV_ROOT . '/cache/gpm')) {
throw new RuntimeException('The cache/gpm folder is not writable. Please check the folder permissions.');
}
if ($ignore_exception) {
return false;
}
throw new RuntimeException('GPM not reachable. Please check your internet connection or check the Grav site is reachable');
}
foreach ($themes as $slug => $theme) {
if ($search === $slug || $search === $theme->name) {
return $theme;
}
}
foreach ($plugins as $slug => $plugin) {
if ($search === $slug || $search === $plugin->name) {
return $plugin;
}
}
return false;
}
/**
* Download the zip package via the URL
*
* @param string $package_file
* @param string $tmp
* @return string|null
*/
public static function downloadPackage($package_file, $tmp)
{
$package = parse_url($package_file);
if (!is_array($package)) {
throw new \RuntimeException("Malformed GPM URL: {$package_file}");
}
$filename = Utils::basename($package['path'] ?? '');
if (Grav::instance()['config']->get('system.gpm.official_gpm_only') && ($package['host'] ?? null) !== 'getgrav.org') {
throw new RuntimeException('Only official GPM URLs are allowed. You can modify this behavior in the System configuration.');
}
$output = Response::get($package_file, []);
if ($output) {
Folder::create($tmp);
file_put_contents($tmp . DS . $filename, $output);
return $tmp . DS . $filename;
}
return null;
}
/**
* Copy the local zip package to tmp
*
* @param string $package_file
* @param string $tmp
* @return string|null
*/
public static function copyPackage($package_file, $tmp)
{
$package_file = realpath($package_file);
if ($package_file && file_exists($package_file)) {
$filename = Utils::basename($package_file);
Folder::create($tmp);
copy($package_file, $tmp . DS . $filename);
return $tmp . DS . $filename;
}
return null;
}
/**
* Try to guess the package type from the source files
*
* @param string $source
* @return string|false
*/
public static function getPackageType($source)
{
$plugin_regex = '/^class\\s{1,}[a-zA-Z0-9]{1,}\\s{1,}extends.+Plugin/m';
$theme_regex = '/^class\\s{1,}[a-zA-Z0-9]{1,}\\s{1,}extends.+Theme/m';
if (file_exists($source . 'system/defines.php') &&
file_exists($source . 'system/config/system.yaml')
) {
return 'grav';
}
// must have a blueprint
if (!file_exists($source . 'blueprints.yaml')) {
return false;
}
// either theme or plugin
$name = Utils::basename($source);
if (Utils::contains($name, 'theme')) {
return 'theme';
}
if (Utils::contains($name, 'plugin')) {
return 'plugin';
}
$glob = glob($source . '*.php') ?: [];
foreach ($glob as $filename) {
$contents = file_get_contents($filename);
if (!$contents) {
continue;
}
if (preg_match($theme_regex, $contents)) {
return 'theme';
}
if (preg_match($plugin_regex, $contents)) {
return 'plugin';
}
}
// Assume it's a theme
return 'theme';
}
/**
* Try to guess the package name from the source files
*
* @param string $source
* @return string|false
*/
public static function getPackageName($source)
{
$ignore_yaml_files = ['blueprints', 'languages'];
$glob = glob($source . '*.yaml') ?: [];
foreach ($glob as $filename) {
$name = strtolower(Utils::basename($filename, '.yaml'));
if (in_array($name, $ignore_yaml_files)) {
continue;
}
return $name;
}
return false;
}
/**
* Find/Parse the blueprint file
*
* @param string $source
* @return array|false
*/
public static function getBlueprints($source)
{
$blueprint_file = $source . 'blueprints.yaml';
if (!file_exists($blueprint_file)) {
return false;
}
$file = YamlFile::instance($blueprint_file);
$blueprint = (array)$file->content();
$file->free();
return $blueprint;
}
/**
* Get the install path for a name and a particular type of package
*
* @param string $type
* @param string $name
* @return string
*/
public static function getInstallPath($type, $name)
{
$locator = Grav::instance()['locator'];
if ($type === 'theme') {
$install_path = $locator->findResource('themes://', false) . DS . $name;
} else {
$install_path = $locator->findResource('plugins://', false) . DS . $name;
}
return $install_path;
}
/**
* Searches for a list of Packages in the repository
*
* @param array $searches An array of either slugs or names
* @return array Array of found Packages
* Format: ['total' => int, 'not_found' => array, <found-slugs>]
*/
public function findPackages($searches = [])
{
$packages = ['total' => 0, 'not_found' => []];
$inflector = new Inflector();
foreach ($searches as $search) {
$repository = '';
// if this is an object, get the search data from the key
if (is_object($search)) {
$search = (array)$search;
$key = key($search);
$repository = $search[$key];
$search = $key;
}
$found = $this->findPackage($search);
if ($found) {
// set override repository if provided
if ($repository) {
$found->override_repository = $repository;
}
if (!isset($packages[$found->package_type])) {
$packages[$found->package_type] = [];
}
$packages[$found->package_type][$found->slug] = $found;
$packages['total']++;
} else {
// make a best guess at the type based on the repo URL
if (Utils::contains($repository, '-theme')) {
$type = 'themes';
} else {
$type = 'plugins';
}
$not_found = new stdClass();
$not_found->name = $inflector::camelize($search);
$not_found->slug = $search;
$not_found->package_type = $type;
$not_found->install_path = str_replace('%name%', $search, $this->install_paths[$type]);
$not_found->override_repository = $repository;
$packages['not_found'][$search] = $not_found;
}
}
return $packages;
}
/**
* Return the list of packages that have the passed one as dependency
*
* @param string $slug The slug name of the package
* @return array
*/
public function getPackagesThatDependOnPackage($slug)
{
$plugins = $this->getInstalledPlugins();
$themes = $this->getInstalledThemes();
$packages = array_merge($plugins->toArray(), $themes->toArray());
$list = [];
foreach ($packages as $package_name => $package) {
$dependencies = $package['dependencies'] ?? [];
foreach ($dependencies as $dependency) {
if (is_array($dependency) && isset($dependency['name'])) {
$dependency = $dependency['name'];
}
if ($dependency === $slug) {
$list[] = $package_name;
}
}
}
return $list;
}
/**
* Get the required version of a dependency of a package
*
* @param string $package_slug
* @param string $dependency_slug
* @return mixed|null
*/
public function getVersionOfDependencyRequiredByPackage($package_slug, $dependency_slug)
{
$dependencies = $this->getInstalledPackage($package_slug)->dependencies ?? [];
foreach ($dependencies as $dependency) {
if (isset($dependency[$dependency_slug])) {
return $dependency[$dependency_slug];
}
}
return null;
}
/**
* Check the package identified by $slug can be updated to the version passed as argument.
* Thrown an exception if it cannot be updated because another package installed requires it to be at an older version.
*
* @param string $slug
* @param string $version_with_operator
* @param array $ignore_packages_list
* @return bool
* @throws RuntimeException
*/
public function checkNoOtherPackageNeedsThisDependencyInALowerVersion($slug, $version_with_operator, $ignore_packages_list)
{
// check if any of the currently installed package need this in a lower version than the one we need. In case, abort and tell which package
$dependent_packages = $this->getPackagesThatDependOnPackage($slug);
$version = $this->calculateVersionNumberFromDependencyVersion($version_with_operator);
if (count($dependent_packages)) {
foreach ($dependent_packages as $dependent_package) {
$other_dependency_version_with_operator = $this->getVersionOfDependencyRequiredByPackage($dependent_package, $slug);
$other_dependency_version = $this->calculateVersionNumberFromDependencyVersion($other_dependency_version_with_operator);
// check version is compatible with the one needed by the current package
if ($this->versionFormatIsNextSignificantRelease($other_dependency_version_with_operator)) {
$compatible = $this->checkNextSignificantReleasesAreCompatible($version, $other_dependency_version);
if (!$compatible && !in_array($dependent_package, $ignore_packages_list, true)) {
throw new RuntimeException(
"Package <cyan>$slug</cyan> is required in an older version by package <cyan>$dependent_package</cyan>. This package needs a newer version, and because of this it cannot be installed. The <cyan>$dependent_package</cyan> package must be updated to use a newer release of <cyan>$slug</cyan>.",
2
);
}
}
}
}
return true;
}
/**
* Check the passed packages list can be updated
*
* @param array $packages_names_list
* @return void
* @throws Exception
*/
public function checkPackagesCanBeInstalled($packages_names_list)
{
foreach ($packages_names_list as $package_name) {
$latest = $this->getLatestVersionOfPackage($package_name);
$this->checkNoOtherPackageNeedsThisDependencyInALowerVersion($package_name, $latest, $packages_names_list);
}
}
/**
* Fetch the dependencies, check the installed packages and return an array with
* the list of packages with associated an information on what to do: install, update or ignore.
*
* `ignore` means the package is already installed and can be safely left as-is.
* `install` means the package is not installed and must be installed.
* `update` means the package is already installed and must be updated as a dependency needs a higher version.
*
* @param array $packages
* @return array
* @throws RuntimeException
*/
public function getDependencies($packages)
{
$dependencies = $this->calculateMergedDependenciesOfPackages($packages);
foreach ($dependencies as $dependency_slug => $dependencyVersionWithOperator) {
$dependency_slug = (string)$dependency_slug;
if (in_array($dependency_slug, $packages, true)) {
unset($dependencies[$dependency_slug]);
continue;
}
// Check PHP version
if ($dependency_slug === 'php') {
$testVersion = $this->calculateVersionNumberFromDependencyVersion($dependencyVersionWithOperator);
if (version_compare($testVersion, PHP_VERSION) === 1) {
//Needs a Grav update first
throw new RuntimeException("<red>One of the packages require PHP {$dependencies['php']}. Please update PHP to resolve this");
}
unset($dependencies[$dependency_slug]);
continue;
}
//First, check for Grav dependency. If a dependency requires Grav > the current version, abort and tell.
if ($dependency_slug === 'grav') {
$testVersion = $this->calculateVersionNumberFromDependencyVersion($dependencyVersionWithOperator);
if (version_compare($testVersion, GRAV_VERSION) === 1) {
//Needs a Grav update first
throw new RuntimeException("<red>One of the packages require Grav {$dependencies['grav']}. Please update Grav to the latest release.");
}
unset($dependencies[$dependency_slug]);
continue;
}
if ($this->isPluginInstalled($dependency_slug)) {
if ($this->isPluginInstalledAsSymlink($dependency_slug)) {
unset($dependencies[$dependency_slug]);
continue;
}
$dependencyVersion = $this->calculateVersionNumberFromDependencyVersion($dependencyVersionWithOperator);
// get currently installed version
$locator = Grav::instance()['locator'];
$blueprints_path = $locator->findResource('plugins://' . $dependency_slug . DS . 'blueprints.yaml');
$file = YamlFile::instance($blueprints_path);
$package_yaml = $file->content();
$file->free();
$currentlyInstalledVersion = $package_yaml['version'];
// if requirement is next significant release, check is compatible with currently installed version, might not be
if ($this->versionFormatIsNextSignificantRelease($dependencyVersionWithOperator)
&& $this->firstVersionIsLower($dependencyVersion, $currentlyInstalledVersion)) {
$compatible = $this->checkNextSignificantReleasesAreCompatible($dependencyVersion, $currentlyInstalledVersion);
if (!$compatible) {
throw new RuntimeException(
'Dependency <cyan>' . $dependency_slug . '</cyan> is required in an older version than the one installed. This package must be updated. Please get in touch with its developer.',
2
);
}
}
//if I already have the latest release, remove the dependency
$latestRelease = $this->getLatestVersionOfPackage($dependency_slug);
if ($this->firstVersionIsLower($latestRelease, $dependencyVersion)) {
//throw an exception if a required version cannot be found in the GPM yet
throw new RuntimeException(
'Dependency <cyan>' . $package_yaml['name'] . '</cyan> is required in version <cyan>' . $dependencyVersion . '</cyan> which is higher than the latest release, <cyan>' . $latestRelease . '</cyan>. Try running `bin/gpm -f index` to force a refresh of the GPM cache',
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | true |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/GPM/AbstractCollection.php | system/src/Grav/Common/GPM/AbstractCollection.php | <?php
/**
* @package Grav\Common\GPM
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\GPM;
use Grav\Common\Iterator;
/**
* Class AbstractCollection
* @package Grav\Common\GPM
*/
abstract class AbstractCollection extends Iterator
{
/**
* @return string
*/
public function toJson()
{
return json_encode($this->toArray(), JSON_THROW_ON_ERROR);
}
/**
* @return array
*/
public function toArray()
{
$items = [];
foreach ($this->items as $name => $package) {
$items[$name] = $package->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/GPM/Response.php | system/src/Grav/Common/GPM/Response.php | <?php
// Create alias for the deprecated class.
class_alias(\Grav\Common\HTTP\Response::class, \Grav\Common\GPM\Response::class);
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/GPM/Licenses.php | system/src/Grav/Common/GPM/Licenses.php | <?php
/**
* @package Grav\Common\GPM
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\GPM;
use Grav\Common\File\CompiledYamlFile;
use Grav\Common\Grav;
use RocketTheme\Toolbox\File\FileInterface;
use function is_string;
/**
* Class Licenses
*
* @package Grav\Common\GPM
*/
class Licenses
{
/** @var string Regex to validate the format of a License */
protected static $regex = '^(?:[A-F0-9]{8}-){3}(?:[A-F0-9]{8}){1}$';
/** @var FileInterface */
protected static $file;
/**
* Returns the license for a Premium package
*
* @param string $slug
* @param string $license
* @return bool
*/
public static function set($slug, $license)
{
$licenses = self::getLicenseFile();
$data = (array)$licenses->content();
$slug = strtolower($slug);
if ($license && !self::validate($license)) {
return false;
}
if (!is_string($license)) {
if (isset($data['licenses'][$slug])) {
unset($data['licenses'][$slug]);
} else {
return false;
}
} else {
$data['licenses'][$slug] = $license;
}
$licenses->save($data);
$licenses->free();
return true;
}
/**
* Returns the license for a Premium package
*
* @param string|null $slug
* @return string[]|string
*/
public static function get($slug = null)
{
$licenses = self::getLicenseFile();
$data = (array)$licenses->content();
$licenses->free();
if (null === $slug) {
return $data['licenses'] ?? [];
}
$slug = strtolower($slug);
return $data['licenses'][$slug] ?? '';
}
/**
* Validates the License format
*
* @param string|null $license
* @return bool
*/
public static function validate($license = null)
{
if (!is_string($license)) {
return false;
}
return (bool)preg_match('#' . self::$regex. '#', $license);
}
/**
* Get the License File object
*
* @return FileInterface
*/
public static function getLicenseFile()
{
if (!isset(self::$file)) {
$path = Grav::instance()['locator']->findResource('user-data://') . '/licenses.yaml';
if (!file_exists($path)) {
touch($path);
}
self::$file = CompiledYamlFile::instance($path);
}
return self::$file;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/GPM/Upgrader.php | system/src/Grav/Common/GPM/Upgrader.php | <?php
/**
* @package Grav\Common\GPM
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\GPM;
use Grav\Common\GPM\Remote\GravCore;
use InvalidArgumentException;
/**
* Class Upgrader
*
* @package Grav\Common\GPM
*/
class Upgrader
{
/** @var GravCore Remote details about latest Grav version */
private $remote;
/** @var string|null */
private $min_php;
/**
* Creates a new GPM instance with Local and Remote packages available
*
* @param boolean $refresh Applies to Remote Packages only and forces a refetch of data
* @param callable|null $callback Either a function or callback in array notation
* @throws InvalidArgumentException
*/
public function __construct($refresh = false, $callback = null)
{
$this->remote = new Remote\GravCore($refresh, $callback);
}
/**
* Returns the release date of the latest version of Grav
*
* @return string
*/
public function getReleaseDate()
{
return $this->remote->getDate();
}
/**
* Returns the version of the installed Grav
*
* @return string
*/
public function getLocalVersion()
{
return GRAV_VERSION;
}
/**
* Returns the version of the remotely available Grav
*
* @return string
*/
public function getRemoteVersion()
{
return $this->remote->getVersion();
}
/**
* Returns an array of assets available to download remotely
*
* @return array
*/
public function getAssets()
{
return $this->remote->getAssets();
}
/**
* Returns the changelog list for each version of Grav
*
* @param string|null $diff the version number to start the diff from
* @return array return the changelog list for each version
*/
public function getChangelog($diff = null)
{
return $this->remote->getChangelog($diff);
}
/**
* Make sure this meets minimum PHP requirements
*
* @return bool
*/
public function meetsRequirements()
{
if (version_compare(PHP_VERSION, $this->minPHPVersion(), '<')) {
return false;
}
return true;
}
/**
* Get minimum PHP version from remote
*
* @return string
*/
public function minPHPVersion()
{
if (null === $this->min_php) {
$this->min_php = $this->remote->getMinPHPVersion();
}
return $this->min_php;
}
/**
* Checks if the currently installed Grav is upgradable to a newer version
*
* @return bool True if it's upgradable, False otherwise.
*/
public function isUpgradable()
{
return version_compare($this->getLocalVersion(), $this->getRemoteVersion(), '<');
}
/**
* Checks if Grav is currently symbolically linked
*
* @return bool True if Grav is symlinked, False otherwise.
*/
public function isSymlink()
{
return $this->remote->isSymlink();
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/GPM/Installer.php | system/src/Grav/Common/GPM/Installer.php | <?php
/**
* @package Grav\Common\GPM
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\GPM;
use DirectoryIterator;
use Grav\Common\Filesystem\Folder;
use Grav\Common\Grav;
use Grav\Common\Utils;
use RuntimeException;
use ZipArchive;
use function count;
use function in_array;
use function is_string;
/**
* Class Installer
* @package Grav\Common\GPM
*/
class Installer
{
/** @const No error */
public const OK = 0;
/** @const Target already exists */
public const EXISTS = 1;
/** @const Target is a symbolic link */
public const IS_LINK = 2;
/** @const Target doesn't exist */
public const NOT_FOUND = 4;
/** @const Target is not a directory */
public const NOT_DIRECTORY = 8;
/** @const Target is not a Grav instance */
public const NOT_GRAV_ROOT = 16;
/** @const Error while trying to open the ZIP package */
public const ZIP_OPEN_ERROR = 32;
/** @const Error while trying to extract the ZIP package */
public const ZIP_EXTRACT_ERROR = 64;
/** @const Invalid source file */
public const INVALID_SOURCE = 128;
/** @var string Destination folder on which validation checks are applied */
protected static $target;
/** @var int|string Error code or string */
protected static $error = 0;
/** @var int Zip Error Code */
protected static $error_zip = 0;
/** @var string Post install message */
protected static $message = '';
/** @var array Default options for the install */
protected static $options = [
'overwrite' => true,
'ignore_symlinks' => true,
'sophisticated' => false,
'theme' => false,
'install_path' => '',
'ignores' => [],
'exclude_checks' => [self::EXISTS, self::NOT_FOUND, self::IS_LINK]
];
/**
* Installs a given package to a given destination.
*
* @param string $zip the local path to ZIP package
* @param string $destination The local path to the Grav Instance
* @param array $options Options to use for installing. ie, ['install_path' => 'user/themes/antimatter']
* @param string|null $extracted The local path to the extacted ZIP package
* @param bool $keepExtracted True if you want to keep the original files
* @return bool True if everything went fine, False otherwise.
*/
public static function install($zip, $destination, $options = [], $extracted = null, $keepExtracted = false)
{
$destination = rtrim($destination, DS);
$options = array_merge(self::$options, $options);
$install_path = rtrim($destination . DS . ltrim($options['install_path'], DS), DS);
if (!self::isGravInstance($destination) || !self::isValidDestination(
$install_path,
$options['exclude_checks']
)
) {
return false;
}
if ((self::lastErrorCode() === self::IS_LINK && $options['ignore_symlinks']) ||
(self::lastErrorCode() === self::EXISTS && !$options['overwrite'])
) {
return false;
}
// Create a tmp location
$tmp_dir = Grav::instance()['locator']->findResource('tmp://', true, true);
$tmp = $tmp_dir . '/Grav-' . uniqid('', false);
if (!$extracted) {
$extracted = self::unZip($zip, $tmp);
if (!$extracted) {
Folder::delete($tmp);
return false;
}
}
if (!file_exists($extracted)) {
self::$error = self::INVALID_SOURCE;
return false;
}
$is_install = true;
$installer = self::loadInstaller($extracted, $is_install);
if (isset($options['is_update']) && $options['is_update'] === true) {
$method = 'preUpdate';
} else {
$method = 'preInstall';
}
if ($installer && method_exists($installer, $method)) {
$method_result = $installer::$method();
if ($method_result !== true) {
self::$error = 'An error occurred';
if (is_string($method_result)) {
self::$error = $method_result;
}
return false;
}
}
if (!$options['sophisticated']) {
$isTheme = $options['theme'] ?? false;
// Make sure that themes are always being copied, even if option was not set!
$isTheme = $isTheme || preg_match('|/themes/[^/]+|ui', $install_path);
if ($isTheme) {
self::copyInstall($extracted, $install_path);
} else {
self::moveInstall($extracted, $install_path);
}
} else {
self::sophisticatedInstall($extracted, $install_path, $options['ignores'], $keepExtracted);
}
Folder::delete($tmp);
if (isset($options['is_update']) && $options['is_update'] === true) {
$method = 'postUpdate';
} else {
$method = 'postInstall';
}
self::$message = '';
if ($installer && method_exists($installer, $method)) {
self::$message = $installer::$method();
}
self::$error = self::OK;
return true;
}
/**
* Unzip a file to somewhere
*
* @param string $zip_file
* @param string $destination
* @return string|false
*/
public static function unZip($zip_file, $destination)
{
$zip = new ZipArchive();
$archive = $zip->open($zip_file);
if ($archive === true) {
Folder::create($destination);
$unzip = $zip->extractTo($destination);
if (!$unzip) {
self::$error = self::ZIP_EXTRACT_ERROR;
Folder::delete($destination);
$zip->close();
return false;
}
$package_folder_name = $zip->getNameIndex(0);
if ($package_folder_name === false) {
throw new \RuntimeException('Bad package file: ' . Utils::basename($zip_file));
}
$package_folder_name = preg_replace('#\./$#', '', $package_folder_name);
$zip->close();
return $destination . '/' . $package_folder_name;
}
self::$error = self::ZIP_EXTRACT_ERROR;
self::$error_zip = $archive;
return false;
}
/**
* Instantiates and returns the package installer class
*
* @param string $installer_file_folder The folder path that contains install.php
* @param bool $is_install True if install, false if removal
* @return string|null
*/
private static function loadInstaller($installer_file_folder, $is_install)
{
$installer_file_folder = rtrim($installer_file_folder, DS);
$install_file = $installer_file_folder . DS . 'install.php';
if (!file_exists($install_file)) {
return null;
}
require_once $install_file;
if ($is_install) {
$slug = '';
if (($pos = strpos($installer_file_folder, 'grav-plugin-')) !== false) {
$slug = substr($installer_file_folder, $pos + strlen('grav-plugin-'));
} elseif (($pos = strpos($installer_file_folder, 'grav-theme-')) !== false) {
$slug = substr($installer_file_folder, $pos + strlen('grav-theme-'));
}
} else {
$path_elements = explode('/', $installer_file_folder);
$slug = end($path_elements);
}
if (!$slug) {
return null;
}
$class_name = ucfirst($slug) . 'Install';
if (class_exists($class_name)) {
return $class_name;
}
$class_name_alphanumeric = preg_replace('/[^a-zA-Z0-9]+/', '', $class_name) ?? $class_name;
if (class_exists($class_name_alphanumeric)) {
return $class_name_alphanumeric;
}
return null;
}
/**
* @param string $source_path
* @param string $install_path
* @return bool
*/
public static function moveInstall($source_path, $install_path)
{
if (file_exists($install_path)) {
Folder::delete($install_path);
}
Folder::move($source_path, $install_path);
return true;
}
/**
* @param string $source_path
* @param string $install_path
* @return bool
*/
public static function copyInstall($source_path, $install_path)
{
if (empty($source_path)) {
throw new RuntimeException("Directory $source_path is missing");
}
Folder::rcopy($source_path, $install_path);
return true;
}
/**
* @param string $source_path
* @param string $install_path
* @param array $ignores
* @param bool $keep_source
* @return bool
*/
public static function sophisticatedInstall($source_path, $install_path, $ignores = [], $keep_source = false)
{
foreach (new DirectoryIterator($source_path) as $file) {
if ($file->isLink() || $file->isDot() || in_array($file->getFilename(), $ignores, true)) {
continue;
}
$path = $install_path . DS . $file->getFilename();
if ($file->isDir()) {
Folder::delete($path);
if ($keep_source) {
Folder::copy($file->getPathname(), $path);
} else {
Folder::move($file->getPathname(), $path);
}
if ($file->getFilename() === 'bin') {
$glob = glob($path . DS . '*') ?: [];
foreach ($glob as $bin_file) {
@chmod($bin_file, 0755);
}
}
} else {
@unlink($path);
@copy($file->getPathname(), $path);
}
}
return true;
}
/**
* Uninstalls one or more given package
*
* @param string $path The slug of the package(s)
* @param array $options Options to use for uninstalling
* @return bool True if everything went fine, False otherwise.
*/
public static function uninstall($path, $options = [])
{
$options = array_merge(self::$options, $options);
if (!self::isValidDestination($path, $options['exclude_checks'])
) {
return false;
}
$installer_file_folder = $path;
$is_install = false;
$installer = self::loadInstaller($installer_file_folder, $is_install);
if ($installer && method_exists($installer, 'preUninstall')) {
$method_result = $installer::preUninstall();
if ($method_result !== true) {
self::$error = 'An error occurred';
if (is_string($method_result)) {
self::$error = $method_result;
}
return false;
}
}
$result = Folder::delete($path);
self::$message = '';
if ($result && $installer && method_exists($installer, 'postUninstall')) {
self::$message = $installer::postUninstall();
}
return $result;
}
/**
* Runs a set of checks on the destination and sets the Error if any
*
* @param string $destination The directory to run validations at
* @param array $exclude An array of constants to exclude from the validation
* @return bool True if validation passed. False otherwise
*/
public static function isValidDestination($destination, $exclude = [])
{
self::$error = 0;
self::$target = $destination;
if (is_link($destination)) {
self::$error = self::IS_LINK;
} elseif (file_exists($destination)) {
self::$error = self::EXISTS;
} elseif (!file_exists($destination)) {
self::$error = self::NOT_FOUND;
} elseif (!is_dir($destination)) {
self::$error = self::NOT_DIRECTORY;
}
if (count($exclude) && in_array(self::$error, $exclude, true)) {
return true;
}
return !self::$error;
}
/**
* Validates if the given path is a Grav Instance
*
* @param string $target The local path to the Grav Instance
* @return bool True if is a Grav Instance. False otherwise
*/
public static function isGravInstance($target)
{
self::$error = 0;
self::$target = $target;
if (!file_exists($target . DS . 'index.php') ||
!file_exists($target . DS . 'bin') ||
!file_exists($target . DS . 'user') ||
!file_exists($target . DS . 'system' . DS . 'config' . DS . 'system.yaml')
) {
self::$error = self::NOT_GRAV_ROOT;
}
return !self::$error;
}
/**
* Returns the last message added by the installer
*
* @return string The message
*/
public static function getMessage()
{
return self::$message;
}
/**
* Returns the last error occurred in a string message format
*
* @return string The message of the last error
*/
public static function lastErrorMsg()
{
if (is_string(self::$error)) {
return self::$error;
}
switch (self::$error) {
case 0:
$msg = 'No Error';
break;
case self::EXISTS:
$msg = 'The target path "' . self::$target . '" already exists';
break;
case self::IS_LINK:
$msg = 'The target path "' . self::$target . '" is a symbolic link';
break;
case self::NOT_FOUND:
$msg = 'The target path "' . self::$target . '" does not appear to exist';
break;
case self::NOT_DIRECTORY:
$msg = 'The target path "' . self::$target . '" does not appear to be a folder';
break;
case self::NOT_GRAV_ROOT:
$msg = 'The target path "' . self::$target . '" does not appear to be a Grav instance';
break;
case self::ZIP_OPEN_ERROR:
$msg = 'Unable to open the package file';
break;
case self::ZIP_EXTRACT_ERROR:
$msg = 'Unable to extract the package. ';
if (self::$error_zip) {
switch (self::$error_zip) {
case ZipArchive::ER_EXISTS:
$msg .= 'File already exists.';
break;
case ZipArchive::ER_INCONS:
$msg .= 'Zip archive inconsistent.';
break;
case ZipArchive::ER_MEMORY:
$msg .= 'Memory allocation failure.';
break;
case ZipArchive::ER_NOENT:
$msg .= 'No such file.';
break;
case ZipArchive::ER_NOZIP:
$msg .= 'Not a zip archive.';
break;
case ZipArchive::ER_OPEN:
$msg .= "Can't open file.";
break;
case ZipArchive::ER_READ:
$msg .= 'Read error.';
break;
case ZipArchive::ER_SEEK:
$msg .= 'Seek error.';
break;
}
}
break;
case self::INVALID_SOURCE:
$msg = 'Invalid source file';
break;
default:
$msg = 'Unknown Error';
break;
}
return $msg;
}
/**
* Returns the last error code of the occurred error
*
* @return int|string The code of the last error
*/
public static function lastErrorCode()
{
return self::$error;
}
/**
* Allows to manually set an error
*
* @param int|string $error the Error code
* @return void
*/
public static function setError($error)
{
self::$error = $error;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/GPM/Common/CachedCollection.php | system/src/Grav/Common/GPM/Common/CachedCollection.php | <?php
/**
* @package Grav\Common\GPM
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\GPM\Common;
use Grav\Common\Iterator;
/**
* Class CachedCollection
* @package Grav\Common\GPM\Common
*/
class CachedCollection extends Iterator
{
/** @var array */
protected static $cache = [];
/**
* CachedCollection constructor.
*
* @param array $items
*/
public function __construct($items)
{
parent::__construct();
$method = static::class . __METHOD__;
// local cache to speed things up
if (!isset(self::$cache[$method])) {
self::$cache[$method] = $items;
}
foreach (self::$cache[$method] as $name => $item) {
$this->append([$name => $item]);
}
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/GPM/Common/AbstractPackageCollection.php | system/src/Grav/Common/GPM/Common/AbstractPackageCollection.php | <?php
/**
* @package Grav\Common\GPM
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\GPM\Common;
use Grav\Common\Iterator;
/**
* Class AbstractPackageCollection
* @package Grav\Common\GPM\Common
*/
abstract class AbstractPackageCollection extends Iterator
{
/** @var string */
protected $type;
/**
* @return string
*/
public function toJson()
{
$items = [];
foreach ($this->items as $name => $package) {
$items[$name] = $package->toArray();
}
return json_encode($items, JSON_THROW_ON_ERROR);
}
/**
* @return array
*/
public function toArray()
{
$items = [];
foreach ($this->items as $name => $package) {
$items[$name] = $package->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/GPM/Common/Package.php | system/src/Grav/Common/GPM/Common/Package.php | <?php
/**
* @package Grav\Common\GPM
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\GPM\Common;
use Grav\Common\Data\Data;
/**
* @property string $name
*/
class Package
{
/** @var Data */
protected $data;
/**
* Package constructor.
* @param Data $package
* @param string|null $type
*/
public function __construct(Data $package, $type = null)
{
$this->data = $package;
if ($type) {
$this->data->set('package_type', $type);
}
}
/**
* @return Data
*/
public function getData()
{
return $this->data;
}
/**
* @param string $key
* @return mixed
*/
#[\ReturnTypeWillChange]
public function __get($key)
{
return $this->data->get($key);
}
/**
* @param string $key
* @param mixed $value
* @return void
*/
#[\ReturnTypeWillChange]
public function __set($key, $value)
{
$this->data->set($key, $value);
}
/**
* @param string $key
* @return bool
*/
#[\ReturnTypeWillChange]
public function __isset($key)
{
return isset($this->data->{$key});
}
/**
* @return string
*/
#[\ReturnTypeWillChange]
public function __toString()
{
return $this->toJson();
}
/**
* @return string
*/
public function toJson()
{
return $this->data->toJson();
}
/**
* @return array
*/
public function toArray()
{
return $this->data->toArray();
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/GPM/Remote/GravCore.php | system/src/Grav/Common/GPM/Remote/GravCore.php | <?php
/**
* @package Grav\Common\GPM
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\GPM\Remote;
use Grav\Common\Grav;
use \Doctrine\Common\Cache\FilesystemCache;
use InvalidArgumentException;
/**
* Class GravCore
* @package Grav\Common\GPM\Remote
*/
class GravCore extends AbstractPackageCollection
{
/** @var string */
protected $repository = 'https://getgrav.org/downloads/grav.json';
/** @var array */
private $data;
/** @var string */
private $version;
/** @var string */
private $date;
/** @var string|null */
private $min_php;
/**
* @param bool $refresh
* @param callable|null $callback
* @throws InvalidArgumentException
*/
public function __construct($refresh = false, $callback = null)
{
$channel = Grav::instance()['config']->get('system.gpm.releases', 'stable');
$cache_dir = Grav::instance()['locator']->findResource('cache://gpm', true, true);
$this->cache = new FilesystemCache($cache_dir);
$this->repository .= '?v=' . GRAV_VERSION . '&' . $channel . '=1';
$this->raw = $this->cache->fetch(md5($this->repository));
$this->fetch($refresh, $callback);
$this->data = json_decode($this->raw, true);
$this->version = $this->data['version'] ?? '-';
$this->date = $this->data['date'] ?? '-';
$this->min_php = $this->data['min_php'] ?? null;
if (isset($this->data['assets'])) {
foreach ((array)$this->data['assets'] as $slug => $data) {
$this->items[$slug] = new Package($data);
}
}
}
/**
* Returns the list of assets associated to the latest version of Grav
*
* @return array list of assets
*/
public function getAssets()
{
return $this->data['assets'];
}
/**
* Returns the changelog list for each version of Grav
*
* @param string|null $diff the version number to start the diff from
* @return array changelog list for each version
*/
public function getChangelog($diff = null)
{
if (!$diff) {
return $this->data['changelog'];
}
$diffLog = [];
foreach ((array)$this->data['changelog'] as $version => $changelog) {
preg_match("/[\w\-\.]+/", $version, $cleanVersion);
if (!$cleanVersion || version_compare($diff, $cleanVersion[0], '>=')) {
continue;
}
$diffLog[$version] = $changelog;
}
return $diffLog;
}
/**
* Return the release date of the latest Grav
*
* @return string
*/
public function getDate()
{
return $this->date;
}
/**
* Determine if this version of Grav is eligible to be updated
*
* @return mixed
*/
public function isUpdatable()
{
return version_compare(GRAV_VERSION, $this->getVersion(), '<');
}
/**
* Returns the latest version of Grav available remotely
*
* @return string
*/
public function getVersion()
{
return $this->version;
}
/**
* Returns the minimum PHP version
*
* @return string
*/
public function getMinPHPVersion()
{
// If non min set, assume current PHP version
if (null === $this->min_php) {
$this->min_php = PHP_VERSION;
}
return $this->min_php;
}
/**
* Is this installation symlinked?
*
* @return bool
*/
public function isSymlink()
{
return is_link(GRAV_ROOT . DS . 'index.php');
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/GPM/Remote/Themes.php | system/src/Grav/Common/GPM/Remote/Themes.php | <?php
/**
* @package Grav\Common\GPM
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\GPM\Remote;
/**
* Class Themes
* @package Grav\Common\GPM\Remote
*/
class Themes extends AbstractPackageCollection
{
/** @var string */
protected $type = 'themes';
/** @var string */
protected $repository = 'https://getgrav.org/downloads/themes.json';
/**
* Local Themes Constructor
* @param bool $refresh
* @param callable|null $callback Either a function or callback in array notation
*/
public function __construct($refresh = false, $callback = null)
{
parent::__construct($this->repository, $refresh, $callback);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/GPM/Remote/Plugins.php | system/src/Grav/Common/GPM/Remote/Plugins.php | <?php
/**
* @package Grav\Common\GPM
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\GPM\Remote;
/**
* Class Plugins
* @package Grav\Common\GPM\Remote
*/
class Plugins extends AbstractPackageCollection
{
/** @var string */
protected $type = 'plugins';
/** @var string */
protected $repository = 'https://getgrav.org/downloads/plugins.json';
/**
* Local Plugins Constructor
* @param bool $refresh
* @param callable|null $callback Either a function or callback in array notation
*/
public function __construct($refresh = false, $callback = null)
{
parent::__construct($this->repository, $refresh, $callback);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/GPM/Remote/AbstractPackageCollection.php | system/src/Grav/Common/GPM/Remote/AbstractPackageCollection.php | <?php
/**
* @package Grav\Common\GPM
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\GPM\Remote;
use Grav\Common\Grav;
use Grav\Common\HTTP\Response;
use Grav\Common\GPM\Common\AbstractPackageCollection as BaseCollection;
use \Doctrine\Common\Cache\FilesystemCache;
use RuntimeException;
/**
* Class AbstractPackageCollection
* @package Grav\Common\GPM\Remote
*/
class AbstractPackageCollection extends BaseCollection
{
/** @var string The cached data previously fetched */
protected $raw;
/** @var string */
protected $repository;
/** @var FilesystemCache */
protected $cache;
/** @var int The lifetime to store the entry in seconds */
private $lifetime = 86400;
/**
* AbstractPackageCollection constructor.
*
* @param string|null $repository
* @param bool $refresh
* @param callable|null $callback
*/
public function __construct($repository = null, $refresh = false, $callback = null)
{
parent::__construct();
if ($repository === null) {
throw new RuntimeException('A repository is required to indicate the origin of the remote collection');
}
$channel = Grav::instance()['config']->get('system.gpm.releases', 'stable');
$cache_dir = Grav::instance()['locator']->findResource('cache://gpm', true, true);
$this->cache = new FilesystemCache($cache_dir);
$this->repository = $repository . '?v=' . GRAV_VERSION . '&' . $channel . '=1';
$this->raw = $this->cache->fetch(md5($this->repository));
$this->fetch($refresh, $callback);
foreach (json_decode($this->raw, true) as $slug => $data) {
// Temporarily fix for using multi-sites
if (isset($data['install_path'])) {
$path = preg_replace('~^user/~i', 'user://', $data['install_path']);
$data['install_path'] = Grav::instance()['locator']->findResource($path, false, true);
}
$this->items[$slug] = new Package($data, $this->type);
}
}
/**
* @param bool $refresh
* @param callable|null $callback
* @return string
*/
public function fetch($refresh = false, $callback = null)
{
if (!$this->raw || $refresh) {
$response = Response::get($this->repository, [], $callback);
$this->raw = $response;
$this->cache->save(md5($this->repository), $this->raw, $this->lifetime);
}
return $this->raw;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/GPM/Remote/Packages.php | system/src/Grav/Common/GPM/Remote/Packages.php | <?php
/**
* @package Grav\Common\GPM
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\GPM\Remote;
use Grav\Common\GPM\Common\CachedCollection;
/**
* Class Packages
* @package Grav\Common\GPM\Remote
*/
class Packages extends CachedCollection
{
/**
* Packages constructor.
* @param bool $refresh
* @param callable|null $callback
*/
public function __construct($refresh = false, $callback = null)
{
$items = [
'plugins' => new Plugins($refresh, $callback),
'themes' => new Themes($refresh, $callback)
];
parent::__construct($items);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/GPM/Remote/Package.php | system/src/Grav/Common/GPM/Remote/Package.php | <?php
/**
* @package Grav\Common\GPM
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\GPM\Remote;
use Grav\Common\Data\Data;
use Grav\Common\GPM\Common\Package as BasePackage;
/**
* Class Package
* @package Grav\Common\GPM\Remote
*/
class Package extends BasePackage implements \JsonSerializable
{
/**
* Package constructor.
* @param array $package
* @param string|null $package_type
*/
public function __construct($package, $package_type = null)
{
$data = new Data($package);
parent::__construct($data, $package_type);
}
/**
* @return array
*/
#[\ReturnTypeWillChange]
public function jsonSerialize()
{
return $this->data->toArray();
}
/**
* Returns the changelog list for each version of a package
*
* @param string|null $diff the version number to start the diff from
* @return array changelog list for each version
*/
public function getChangelog($diff = null)
{
if (!$diff) {
return $this->data['changelog'];
}
$diffLog = [];
foreach ((array)$this->data['changelog'] as $version => $changelog) {
preg_match("/[\w\-.]+/", $version, $cleanVersion);
if (!$cleanVersion || version_compare($diff, $cleanVersion[0], '>=')) {
continue;
}
$diffLog[$version] = $changelog;
}
return $diffLog;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/GPM/Local/Themes.php | system/src/Grav/Common/GPM/Local/Themes.php | <?php
/**
* @package Grav\Common\GPM
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\GPM\Local;
use Grav\Common\Grav;
/**
* Class Themes
* @package Grav\Common\GPM\Local
*/
class Themes extends AbstractPackageCollection
{
/** @var string */
protected $type = 'themes';
/**
* Local Themes Constructor
*/
public function __construct()
{
/** @var \Grav\Common\Themes $themes */
$themes = Grav::instance()['themes'];
parent::__construct($themes->all());
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/GPM/Local/Plugins.php | system/src/Grav/Common/GPM/Local/Plugins.php | <?php
/**
* @package Grav\Common\GPM
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\GPM\Local;
use Grav\Common\Grav;
/**
* Class Plugins
* @package Grav\Common\GPM\Local
*/
class Plugins extends AbstractPackageCollection
{
/** @var string */
protected $type = 'plugins';
/**
* Local Plugins Constructor
*/
public function __construct()
{
/** @var \Grav\Common\Plugins $plugins */
$plugins = Grav::instance()['plugins'];
parent::__construct($plugins->all());
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/GPM/Local/AbstractPackageCollection.php | system/src/Grav/Common/GPM/Local/AbstractPackageCollection.php | <?php
/**
* @package Grav\Common\GPM
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\GPM\Local;
use Grav\Common\GPM\Common\AbstractPackageCollection as BaseCollection;
/**
* Class AbstractPackageCollection
* @package Grav\Common\GPM\Local
*/
abstract class AbstractPackageCollection extends BaseCollection
{
/**
* AbstractPackageCollection constructor.
*
* @param array $items
*/
public function __construct($items)
{
parent::__construct();
foreach ($items as $name => $data) {
$data->set('slug', $name);
$this->items[$name] = new Package($data, $this->type);
}
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/GPM/Local/Packages.php | system/src/Grav/Common/GPM/Local/Packages.php | <?php
/**
* @package Grav\Common\GPM
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\GPM\Local;
use Grav\Common\GPM\Common\CachedCollection;
/**
* Class Packages
* @package Grav\Common\GPM\Local
*/
class Packages extends CachedCollection
{
public function __construct()
{
$items = [
'plugins' => new Plugins(),
'themes' => new Themes()
];
parent::__construct($items);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/GPM/Local/Package.php | system/src/Grav/Common/GPM/Local/Package.php | <?php
/**
* @package Grav\Common\GPM
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\GPM\Local;
use Grav\Common\Data\Data;
use Grav\Common\GPM\Common\Package as BasePackage;
use Parsedown;
/**
* Class Package
* @package Grav\Common\GPM\Local
*/
class Package extends BasePackage
{
/** @var array */
protected $settings;
/**
* Package constructor.
* @param Data $package
* @param string|null $package_type
*/
public function __construct(Data $package, $package_type = null)
{
$data = new Data($package->blueprints()->toArray());
parent::__construct($data, $package_type);
$this->settings = $package->toArray();
$html_description = Parsedown::instance()->line($this->__get('description'));
$this->data->set('slug', $package->__get('slug'));
$this->data->set('description_html', $html_description);
$this->data->set('description_plain', strip_tags($html_description));
$this->data->set('symlink', is_link(USER_DIR . $package_type . DS . $this->__get('slug')));
}
/**
* @return bool
*/
public function isEnabled()
{
return (bool)$this->settings['enabled'];
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Data/BlueprintSchema.php | system/src/Grav/Common/Data/BlueprintSchema.php | <?php
/**
* @package Grav\Common\Data
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Data;
use Grav\Common\Config\Config;
use Grav\Common\Grav;
use RocketTheme\Toolbox\ArrayTraits\Export;
use RocketTheme\Toolbox\ArrayTraits\ExportInterface;
use RocketTheme\Toolbox\Blueprints\BlueprintSchema as BlueprintSchemaBase;
use RuntimeException;
use function is_array;
use function is_string;
/**
* Class BlueprintSchema
* @package Grav\Common\Data
*/
class BlueprintSchema extends BlueprintSchemaBase implements ExportInterface
{
use Export;
/** @var array */
protected $filter = ['validation' => true, 'xss_check' => true];
/** @var array */
protected $ignoreFormKeys = [
'title' => true,
'help' => true,
'placeholder' => true,
'placeholder_key' => true,
'placeholder_value' => true,
'fields' => true
];
/**
* @return array
*/
public function getTypes()
{
return $this->types;
}
/**
* @param string $name
* @return array
*/
public function getType($name)
{
return $this->types[$name] ?? [];
}
/**
* @param string $name
* @return array|null
*/
public function getNestedRules(string $name)
{
return $this->getNested($name);
}
/**
* Validate data against blueprints.
*
* @param array $data
* @param array $options
* @return void
* @throws RuntimeException
*/
public function validate(array $data, array $options = [])
{
try {
$validation = $this->items['']['form']['validation'] ?? 'loose';
$messages = $this->validateArray($data, $this->nested, $validation === 'strict', $options['xss_check'] ?? true);
} catch (RuntimeException $e) {
throw (new ValidationException($e->getMessage(), $e->getCode(), $e))->setMessages();
}
if (!empty($messages)) {
throw (new ValidationException('', 400))->setMessages($messages);
}
}
/**
* @param array $data
* @param array $toggles
* @return array
*/
public function processForm(array $data, array $toggles = [])
{
return $this->processFormRecursive($data, $toggles, $this->nested) ?? [];
}
/**
* Filter data by using blueprints.
*
* @param array $data Incoming data, for example from a form.
* @param bool $missingValuesAsNull Include missing values as nulls.
* @param bool $keepEmptyValues Include empty values.
* @return array
*/
public function filter(array $data, $missingValuesAsNull = false, $keepEmptyValues = false)
{
$this->buildIgnoreNested($this->nested);
return $this->filterArray($data, $this->nested, '', $missingValuesAsNull, $keepEmptyValues) ?? [];
}
/**
* Flatten data by using blueprints.
*
* @param array $data Data to be flattened.
* @param bool $includeAll True if undefined properties should also be included.
* @param string $name Property which will be flattened, useful for flattening repeating data.
* @return array
*/
public function flattenData(array $data, bool $includeAll = false, string $name = '')
{
$prefix = $name !== '' ? $name . '.' : '';
$list = [];
if ($includeAll) {
$items = $name !== '' ? $this->getProperty($name)['fields'] ?? [] : $this->items;
foreach ($items as $key => $rules) {
$type = $rules['type'] ?? '';
$ignore = (bool) array_filter((array)($rules['validate']['ignore'] ?? [])) ?? false;
if (!str_starts_with($type, '_') && !str_contains($key, '*') && $ignore !== true) {
$list[$prefix . $key] = null;
}
}
}
$nested = $this->getNestedRules($name);
return array_replace($list, $this->flattenArray($data, $nested, $prefix));
}
/**
* @param array $data
* @param array $rules
* @param string $prefix
* @return array
*/
protected function flattenArray(array $data, array $rules, string $prefix)
{
$array = [];
foreach ($data as $key => $field) {
$val = $rules[$key] ?? $rules['*'] ?? null;
$rule = is_string($val) ? $this->items[$val] : null;
if ($rule || isset($val['*'])) {
// Item has been defined in blueprints.
$array[$prefix.$key] = $field;
} elseif (is_array($field) && is_array($val)) {
// Array has been defined in blueprints.
$array += $this->flattenArray($field, $val, $prefix . $key . '.');
} else {
// Undefined/extra item.
$array[$prefix.$key] = $field;
}
}
return $array;
}
/**
* @param array $data
* @param array $rules
* @param bool $strict
* @param bool $xss
* @return array
* @throws RuntimeException
*/
protected function validateArray(array $data, array $rules, bool $strict, bool $xss = true)
{
$messages = $this->checkRequired($data, $rules);
foreach ($data as $key => $child) {
$val = $rules[$key] ?? $rules['*'] ?? null;
$rule = is_string($val) ? $this->items[$val] : null;
$checkXss = $xss;
if ($rule) {
// Item has been defined in blueprints.
if (!empty($rule['disabled']) || !empty($rule['validate']['ignore'])) {
// Skip validation in the ignored field.
continue;
}
$messages += Validation::validate($child, $rule);
if (isset($rule['validate']['match']) || isset($rule['validate']['match_exact']) || isset($rule['validate']['match_any'])) {
$ruleKey = current(array_intersect(['match', 'match_exact', 'match_any'], array_keys($rule['validate'])));
$otherKey = $rule['validate'][$ruleKey] ?? null;
$otherVal = $data[$otherKey] ?? null;
$otherLabel = $this->items[$otherKey]['label'] ?? $otherKey;
$currentVal = $data[$key] ?? null;
$currentLabel = $this->items[$key]['label'] ?? $key;
// Determine comparison type (loose, strict, substring)
// Perform comparison:
$isValid = false;
if ($ruleKey === 'match') {
$isValid = ($currentVal == $otherVal);
} elseif ($ruleKey === 'match_exact') {
$isValid = ($currentVal === $otherVal);
} elseif ($ruleKey === 'match_any') {
// If strings:
if (is_string($currentVal) && is_string($otherVal)) {
$isValid = (strlen($currentVal) && strlen($otherVal) && (str_contains($currentVal,
$otherVal) || strpos($otherVal, $currentVal) !== false));
}
// If arrays:
if (is_array($currentVal) && is_array($otherVal)) {
$common = array_intersect($currentVal, $otherVal);
$isValid = !empty($common);
}
}
if (!$isValid) {
$messages[$rule['name']][] = sprintf(Grav::instance()['language']->translate('PLUGIN_FORM.VALIDATION_MATCH'), $currentLabel, $otherLabel);
}
}
} elseif (is_array($child) && is_array($val)) {
// Array has been defined in blueprints.
$messages += $this->validateArray($child, $val, $strict);
$checkXss = false;
} elseif ($strict) {
// Undefined/extra item in strict mode.
/** @var Config $config */
$config = Grav::instance()['config'];
if (!$config->get('system.strict_mode.blueprint_strict_compat', true)) {
throw new RuntimeException(sprintf('%s is not defined in blueprints', $key), 400);
}
user_error(sprintf('Having extra key %s in your data is deprecated with blueprint having \'validation: strict\'', $key), E_USER_DEPRECATED);
}
if ($checkXss) {
$messages += Validation::checkSafety($child, $rule ?: ['name' => $key]);
}
}
return $messages;
}
/**
* @param array $data
* @param array $rules
* @param string $parent
* @param bool $missingValuesAsNull
* @param bool $keepEmptyValues
* @return array|null
*/
protected function filterArray(array $data, array $rules, string $parent, bool $missingValuesAsNull, bool $keepEmptyValues)
{
$results = [];
foreach ($data as $key => $field) {
$val = $rules[$key] ?? $rules['*'] ?? null;
$rule = is_string($val) ? $this->items[$val] : $this->items[$parent . $key] ?? null;
if (!empty($rule['disabled']) || !empty($rule['validate']['ignore'])) {
// Skip any data in the ignored field.
unset($results[$key]);
continue;
}
if (null === $field) {
if ($missingValuesAsNull) {
$results[$key] = null;
} else {
unset($results[$key]);
}
continue;
}
$isParent = isset($val['*']);
$type = $rule['type'] ?? null;
if (!$isParent && $type && $type !== '_parent') {
$field = Validation::filter($field, $rule);
} elseif (is_array($field) && is_array($val)) {
// Array has been defined in blueprints.
$k = $isParent ? '*' : $key;
$field = $this->filterArray($field, $val, $parent . $k . '.', $missingValuesAsNull, $keepEmptyValues);
if (null === $field) {
// Nested parent has no values.
unset($results[$key]);
continue;
}
} elseif (isset($rules['validation']) && $rules['validation'] === 'strict') {
// Skip any extra data.
continue;
}
if ($keepEmptyValues || (null !== $field && (!is_array($field) || !empty($field)))) {
$results[$key] = $field;
}
}
return $results ?: null;
}
/**
* @param array $nested
* @param string $parent
* @return bool
*/
protected function buildIgnoreNested(array $nested, $parent = '')
{
$ignore = true;
foreach ($nested as $key => $val) {
$key = $parent . $key;
if (is_array($val)) {
$ignore = $this->buildIgnoreNested($val, $key . '.') && $ignore; // Keep the order!
} else {
$child = $this->items[$key] ?? null;
$ignore = $ignore && (!$child || !empty($child['disabled']) || !empty($child['validate']['ignore']));
}
}
if ($ignore) {
$key = trim($parent, '.');
$this->items[$key]['validate']['ignore'] = true;
}
return $ignore;
}
/**
* @param array|null $data
* @param array $toggles
* @param array $nested
* @return array|null
*/
protected function processFormRecursive(?array $data, array $toggles, array $nested)
{
foreach ($nested as $key => $value) {
if ($key === '') {
continue;
}
if ($key === '*') {
// TODO: Add support to collections.
continue;
}
if (is_array($value)) {
// Special toggle handling for all the nested data.
$toggle = $toggles[$key] ?? [];
if (!is_array($toggle)) {
if (!$toggle) {
$data[$key] = null;
continue;
}
$toggle = [];
}
// Recursively fetch the items.
$childData = $data[$key] ?? null;
if (null !== $childData && !is_array($childData)) {
throw new \RuntimeException(sprintf("Bad form data for field collection '%s': %s used instead of an array", $key, gettype($childData)));
}
$data[$key] = $this->processFormRecursive($data[$key] ?? null, $toggle, $value);
} else {
$field = $this->get($value);
// Do not add the field if:
if (
// Not an input field
!$field
// Field has been disabled
|| !empty($field['disabled'])
// Field validation is set to be ignored
|| !empty($field['validate']['ignore'])
// Field is overridable and the toggle is turned off
|| (!empty($field['overridable']) && empty($toggles[$key]))
) {
continue;
}
if (!isset($data[$key])) {
$data[$key] = null;
}
}
}
return $data;
}
/**
* @param array $data
* @param array $fields
* @return array
*/
protected function checkRequired(array $data, array $fields)
{
$messages = [];
foreach ($fields as $name => $field) {
if (!is_string($field)) {
continue;
}
$field = $this->items[$field];
// Skip ignored field, it will not be required.
if (!empty($field['disabled']) || !empty($field['validate']['ignore'])) {
continue;
}
// Skip overridable fields without value.
// TODO: We need better overridable support, which is not just ignoring required values but also looking if defaults are good.
if (!empty($field['overridable']) && !isset($data[$name])) {
continue;
}
// Check if required.
if (isset($field['validate']['required'])
&& $field['validate']['required'] === true) {
if (isset($data[$name])) {
continue;
}
if ($field['type'] === 'file' && isset($data['data']['name'][$name])) { //handle case of file input fields required
continue;
}
$value = $field['label'] ?? $field['name'];
$language = Grav::instance()['language'];
$message = sprintf($language->translate('GRAV.FORM.MISSING_REQUIRED_FIELD', null, true) . ' %s', $language->translate($value));
$messages[$field['name']][] = $message;
}
}
return $messages;
}
/**
* @param array $field
* @param string $property
* @param array $call
* @return void
*/
protected function dynamicConfig(array &$field, $property, array &$call)
{
$value = $call['params'];
$default = $field[$property] ?? null;
$config = Grav::instance()['config']->get($value, $default);
if (null !== $config) {
$field[$property] = $config;
}
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Data/Blueprints.php | system/src/Grav/Common/Data/Blueprints.php | <?php
/**
* @package Grav\Common\Data
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Data;
use DirectoryIterator;
use Grav\Common\Grav;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use RuntimeException;
use function is_array;
use function is_object;
/**
* Class Blueprints
* @package Grav\Common\Data
*/
class Blueprints
{
/** @var array|string */
protected $search;
/** @var array */
protected $types;
/** @var array */
protected $instances = [];
/**
* @param string|array $search Search path.
*/
public function __construct($search = 'blueprints://')
{
$this->search = $search;
}
/**
* Get blueprint.
*
* @param string $type Blueprint type.
* @return Blueprint
* @throws RuntimeException
*/
public function get($type)
{
if (!isset($this->instances[$type])) {
$blueprint = $this->loadFile($type);
$this->instances[$type] = $blueprint;
}
return $this->instances[$type];
}
/**
* Get all available blueprint types.
*
* @return array List of type=>name
*/
public function types()
{
if ($this->types === null) {
$this->types = [];
$grav = Grav::instance();
/** @var UniformResourceLocator $locator */
$locator = $grav['locator'];
// Get stream / directory iterator.
if ($locator->isStream($this->search)) {
$iterator = $locator->getIterator($this->search);
} else {
$iterator = new DirectoryIterator($this->search);
}
foreach ($iterator as $file) {
if (!$file->isFile() || '.' . $file->getExtension() !== YAML_EXT) {
continue;
}
$name = $file->getBasename(YAML_EXT);
$this->types[$name] = ucfirst(str_replace('_', ' ', $name));
}
}
return $this->types;
}
/**
* Load blueprint file.
*
* @param string $name Name of the blueprint.
* @return Blueprint
*/
protected function loadFile($name)
{
$blueprint = new Blueprint($name);
if (is_array($this->search) || is_object($this->search)) {
// Page types.
$blueprint->setOverrides($this->search);
$blueprint->setContext('blueprints://pages');
} else {
$blueprint->setContext($this->search);
}
try {
$blueprint->load()->init();
} catch (RuntimeException $e) {
$log = Grav::instance()['log'];
$log->error(sprintf('Blueprint %s cannot be loaded: %s', $name, $e->getMessage()));
throw $e;
}
return $blueprint;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Data/Data.php | system/src/Grav/Common/Data/Data.php | <?php
/**
* @package Grav\Common\Data
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Data;
use ArrayAccess;
use Exception;
use JsonSerializable;
use RocketTheme\Toolbox\ArrayTraits\Countable;
use RocketTheme\Toolbox\ArrayTraits\Export;
use RocketTheme\Toolbox\ArrayTraits\ExportInterface;
use RocketTheme\Toolbox\ArrayTraits\NestedArrayAccessWithGetters;
use RocketTheme\Toolbox\File\FileInterface;
use RuntimeException;
use function func_get_args;
use function is_array;
use function is_callable;
use function is_object;
/**
* Class Data
* @package Grav\Common\Data
*/
class Data implements DataInterface, ArrayAccess, \Countable, JsonSerializable, ExportInterface
{
use NestedArrayAccessWithGetters, Countable, Export;
/** @var string */
protected $gettersVariable = 'items';
/** @var array */
protected $items;
/** @var Blueprint|callable|null */
protected $blueprints;
/** @var FileInterface|null */
protected $storage;
/** @var bool */
private $missingValuesAsNull = false;
/** @var bool */
private $keepEmptyValues = true;
/**
* @param array $items
* @param Blueprint|callable|null $blueprints
*/
public function __construct(array $items = [], $blueprints = null)
{
$this->items = $items;
if (null !== $blueprints) {
$this->blueprints = $blueprints;
}
}
/**
* @param bool $value
* @return $this
*/
public function setKeepEmptyValues(bool $value)
{
$this->keepEmptyValues = $value;
return $this;
}
/**
* @param bool $value
* @return $this
*/
public function setMissingValuesAsNull(bool $value)
{
$this->missingValuesAsNull = $value;
return $this;
}
/**
* Get value by using dot notation for nested arrays/objects.
*
* @example $value = $data->value('this.is.my.nested.variable');
*
* @param string $name Dot separated path to the requested value.
* @param mixed $default Default value (or null).
* @param string $separator Separator, defaults to '.'
* @return mixed Value.
*/
public function value($name, $default = null, $separator = '.')
{
return $this->get($name, $default, $separator);
}
/**
* 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 = '.')
{
$old = $this->get($name, null, $separator);
if ($old !== null) {
if (!is_array($old)) {
throw new RuntimeException('Value ' . $old);
}
if (is_object($value)) {
$value = (array) $value;
} elseif (!is_array($value)) {
throw new RuntimeException('Value ' . $value);
}
$value = $this->blueprints()->mergeData($old, $value, $name, $separator);
}
$this->set($name, $value, $separator);
return $this;
}
/**
* Get nested structure containing default values defined in the blueprints.
*
* Fields without default value are ignored in the list.
* @return array
*/
public function getDefaults()
{
return $this->blueprints()->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 = '.')
{
if (is_object($value)) {
$value = (array) $value;
}
$old = $this->get($name, null, $separator);
if ($old !== null) {
$value = $this->blueprints()->mergeData($value, $old, $name, $separator);
}
$this->set($name, $value, $separator);
return $this;
}
/**
* 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 = '.')
{
if (is_object($value)) {
$value = (array) $value;
} elseif (!is_array($value)) {
throw new RuntimeException('Value ' . $value);
}
$old = $this->get($name, null, $separator);
if ($old === null) {
// No value set; no need to join data.
return $value;
}
if (!is_array($old)) {
throw new RuntimeException('Value ' . $old);
}
// Return joined data.
return $this->blueprints()->mergeData($old, $value, $name, $separator);
}
/**
* Merge two configurations together.
*
* @param array $data
* @return $this
*/
public function merge(array $data)
{
$this->items = $this->blueprints()->mergeData($this->items, $data);
return $this;
}
/**
* Set default values to the configuration if variables were not set.
*
* @param array $data
* @return $this
*/
public function setDefaults(array $data)
{
$this->items = $this->blueprints()->mergeData($data, $this->items);
return $this;
}
/**
* Validate by blueprints.
*
* @return $this
* @throws Exception
*/
public function validate()
{
$this->blueprints()->validate($this->items);
return $this;
}
/**
* @return $this
*/
public function filter()
{
$args = func_get_args();
$missingValuesAsNull = (bool)(array_shift($args) ?? $this->missingValuesAsNull);
$keepEmptyValues = (bool)(array_shift($args) ?? $this->keepEmptyValues);
$this->items = $this->blueprints()->filter($this->items, $missingValuesAsNull, $keepEmptyValues);
return $this;
}
/**
* Get extra items which haven't been defined in blueprints.
*
* @return array
*/
public function extra()
{
return $this->blueprints()->extra($this->items);
}
/**
* Return blueprints.
*
* @return Blueprint
*/
public function blueprints()
{
if (null === $this->blueprints) {
$this->blueprints = new Blueprint();
} elseif (is_callable($this->blueprints)) {
// Lazy load blueprints.
$blueprints = $this->blueprints;
$this->blueprints = $blueprints();
}
return $this->blueprints;
}
/**
* Save data if storage has been defined.
*
* @return void
* @throws RuntimeException
*/
public function save()
{
$file = $this->file();
if ($file) {
$file->save($this->items);
}
}
/**
* 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()
{
$file = $this->file();
return $file && $file->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()
{
$file = $this->file();
return $file ? $file->raw() : '';
}
/**
* Set or get the data storage.
*
* @param FileInterface|null $storage Optionally enter a new storage.
* @return FileInterface|null
*/
public function file(FileInterface $storage = null)
{
if ($storage) {
$this->storage = $storage;
}
return $this->storage;
}
/**
* @return array
*/
#[\ReturnTypeWillChange]
public function jsonSerialize()
{
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/Data/DataInterface.php | system/src/Grav/Common/Data/DataInterface.php | <?php
/**
* @package Grav\Common\Data
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Data;
use Exception;
use RocketTheme\Toolbox\File\FileInterface;
/**
* Interface DataInterface
* @package Grav\Common\Data
*/
interface DataInterface
{
/**
* Get value by using dot notation for nested arrays/objects.
*
* @example $value = $data->value('this.is.my.nested.variable');
*
* @param string $name Dot separated path to the requested value.
* @param mixed $default Default value (or null).
* @param string $separator Separator, defaults to '.'
* @return mixed Value.
*/
public function value($name, $default = null, $separator = '.');
/**
* Merge external data.
*
* @param array $data
* @return mixed
*/
public function merge(array $data);
/**
* Return blueprints.
*
* @return Blueprint
*/
public function blueprints();
/**
* Validate by blueprints.
*
* @return $this
* @throws Exception
*/
public function validate();
/**
* Filter all items by using blueprints.
*
* @return $this
*/
public function filter();
/**
* Get extra items which haven't been defined in blueprints.
*
* @return array
*/
public function extra();
/**
* Save data into the file.
*
* @return void
*/
public function save();
/**
* Set or get the data storage.
*
* @param FileInterface|null $storage Optionally enter a new storage.
* @return FileInterface
*/
public function file(FileInterface $storage = null);
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Data/ValidationException.php | system/src/Grav/Common/Data/ValidationException.php | <?php
/**
* @package Grav\Common\Data
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Data;
use Grav\Common\Grav;
use JsonSerializable;
use RuntimeException;
/**
* Class ValidationException
* @package Grav\Common\Data
*/
class ValidationException extends RuntimeException implements JsonSerializable
{
/** @var array */
protected $messages = [];
protected $escape = true;
/**
* @param array $messages
* @return $this
*/
public function setMessages(array $messages = [])
{
$this->messages = $messages;
$language = Grav::instance()['language'];
$this->message = $language->translate('GRAV.FORM.VALIDATION_FAIL', null, true) . ' ' . $this->message;
foreach ($messages as $list) {
$list = array_unique($list);
foreach ($list as $message) {
$this->message .= '<br/>' . htmlspecialchars($message, ENT_QUOTES | ENT_HTML5, 'UTF-8');
}
}
return $this;
}
public function setSimpleMessage(bool $escape = true): void
{
$first = reset($this->messages);
$message = reset($first);
$this->message = $escape ? htmlspecialchars($message, ENT_QUOTES | ENT_HTML5, 'UTF-8') : $message;
}
/**
* @return array
*/
public function getMessages(): array
{
return $this->messages;
}
public function jsonSerialize(): array
{
return ['validation' => $this->messages];
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Data/Blueprint.php | system/src/Grav/Common/Data/Blueprint.php | <?php
/**
* @package Grav\Common\Data
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Data;
use Grav\Common\File\CompiledYamlFile;
use Grav\Common\Grav;
use Grav\Common\User\Interfaces\UserInterface;
use RocketTheme\Toolbox\Blueprints\BlueprintForm;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use RuntimeException;
use function call_user_func_array;
use function count;
use function function_exists;
use function in_array;
use function is_array;
use function is_int;
use function is_object;
use function is_string;
use function strlen;
/**
* Class Blueprint
* @package Grav\Common\Data
*/
class Blueprint extends BlueprintForm
{
/** @var string */
protected $context = 'blueprints://';
/** @var string|null */
protected $scope;
/** @var BlueprintSchema|null */
protected $blueprintSchema;
/** @var object|null */
protected $object;
/** @var array|null */
protected $defaults;
/** @var array */
protected $handlers = [];
/**
* Clone blueprint.
*/
public function __clone()
{
if (null !== $this->blueprintSchema) {
$this->blueprintSchema = clone $this->blueprintSchema;
}
}
/**
* @param string $scope
* @return void
*/
public function setScope($scope)
{
$this->scope = $scope;
}
/**
* @param object $object
* @return void
*/
public function setObject($object)
{
$this->object = $object;
}
/**
* Set default values for field types.
*
* @param array $types
* @return $this
*/
public function setTypes(array $types)
{
$this->initInternals();
$this->blueprintSchema->setTypes($types);
return $this;
}
/**
* @param string $name
* @return array|mixed|null
* @since 1.7
*/
public function getDefaultValue(string $name)
{
$path = explode('.', $name);
$current = $this->getDefaults();
foreach ($path as $field) {
if (is_object($current) && isset($current->{$field})) {
$current = $current->{$field};
} elseif (is_array($current) && isset($current[$field])) {
$current = $current[$field];
} else {
return null;
}
}
return $current;
}
/**
* Get nested structure containing default values defined in the blueprints.
*
* Fields without default value are ignored in the list.
*
* @return array
*/
public function getDefaults()
{
$this->initInternals();
if (null === $this->defaults) {
$this->defaults = $this->blueprintSchema->getDefaults();
}
return $this->defaults;
}
/**
* Initialize blueprints with its dynamic fields.
*
* @return $this
*/
public function init()
{
foreach ($this->dynamic as $key => $data) {
// Locate field.
$path = explode('/', $key);
$current = &$this->items;
foreach ($path as $field) {
if (is_object($current)) {
// Handle objects.
if (!isset($current->{$field})) {
$current->{$field} = [];
}
$current = &$current->{$field};
} else {
// Handle arrays and scalars.
if (!is_array($current)) {
$current = [$field => []];
} elseif (!isset($current[$field])) {
$current[$field] = [];
}
$current = &$current[$field];
}
}
// Set dynamic property.
foreach ($data as $property => $call) {
$action = $call['action'];
$method = 'dynamic' . ucfirst($action);
$call['object'] = $this->object;
if (isset($this->handlers[$action])) {
$callable = $this->handlers[$action];
$callable($current, $property, $call);
} elseif (method_exists($this, $method)) {
$this->{$method}($current, $property, $call);
}
}
}
return $this;
}
/**
* Extend blueprint with another blueprint.
*
* @param BlueprintForm|array $extends
* @param bool $append
* @return $this
*/
public function extend($extends, $append = false)
{
parent::extend($extends, $append);
$this->deepInit($this->items);
return $this;
}
/**
* @param string $name
* @param mixed $value
* @param string $separator
* @param bool $append
* @return $this
*/
public function embed($name, $value, $separator = '/', $append = false)
{
parent::embed($name, $value, $separator, $append);
$this->deepInit($this->items);
return $this;
}
/**
* Merge two arrays by using blueprints.
*
* @param array $data1
* @param array $data2
* @param string|null $name Optional
* @param string $separator Optional
* @return array
*/
public function mergeData(array $data1, array $data2, $name = null, $separator = '.')
{
$this->initInternals();
return $this->blueprintSchema->mergeData($data1, $data2, $name, $separator);
}
/**
* Process data coming from a form.
*
* @param array $data
* @param array $toggles
* @return array
*/
public function processForm(array $data, array $toggles = [])
{
$this->initInternals();
return $this->blueprintSchema->processForm($data, $toggles);
}
/**
* Return data fields that do not exist in blueprints.
*
* @param array $data
* @param string $prefix
* @return array
*/
public function extra(array $data, $prefix = '')
{
$this->initInternals();
return $this->blueprintSchema->extra($data, $prefix);
}
/**
* Validate data against blueprints.
*
* @param array $data
* @param array $options
* @return void
* @throws RuntimeException
*/
public function validate(array $data, array $options = [])
{
$this->initInternals();
$this->blueprintSchema->validate($data, $options);
}
/**
* Filter data by using blueprints.
*
* @param array $data
* @param bool $missingValuesAsNull
* @param bool $keepEmptyValues
* @return array
*/
public function filter(array $data, bool $missingValuesAsNull = false, bool $keepEmptyValues = false)
{
$this->initInternals();
return $this->blueprintSchema->filter($data, $missingValuesAsNull, $keepEmptyValues) ?? [];
}
/**
* Flatten data by using blueprints.
*
* @param array $data Data to be flattened.
* @param bool $includeAll True if undefined properties should also be included.
* @param string $name Property which will be flattened, useful for flattening repeating data.
* @return array
*/
public function flattenData(array $data, bool $includeAll = false, string $name = '')
{
$this->initInternals();
return $this->blueprintSchema->flattenData($data, $includeAll, $name);
}
/**
* Return blueprint data schema.
*
* @return BlueprintSchema
*/
public function schema()
{
$this->initInternals();
return $this->blueprintSchema;
}
/**
* @param string $name
* @param callable $callable
* @return void
*/
public function addDynamicHandler(string $name, callable $callable): void
{
$this->handlers[$name] = $callable;
}
/**
* Initialize validator.
*
* @return void
*/
protected function initInternals()
{
if (null === $this->blueprintSchema) {
$types = Grav::instance()['plugins']->formFieldTypes;
$this->blueprintSchema = new BlueprintSchema;
if ($types) {
$this->blueprintSchema->setTypes($types);
}
$this->blueprintSchema->embed('', $this->items);
$this->blueprintSchema->init();
$this->defaults = null;
}
}
/**
* @param string $filename
* @return array
*/
protected function loadFile($filename)
{
$file = CompiledYamlFile::instance($filename);
$content = (array)$file->content();
$file->free();
return $content;
}
/**
* @param string|array $path
* @param string|null $context
* @return array
*/
protected function getFiles($path, $context = null)
{
/** @var UniformResourceLocator $locator */
$locator = Grav::instance()['locator'];
if (is_string($path) && !$locator->isStream($path)) {
if (is_file($path)) {
return [$path];
}
// Find path overrides.
if (null === $context) {
$paths = (array) ($this->overrides[$path] ?? null);
} else {
$paths = [];
}
// Add path pointing to default context.
if ($context === null) {
$context = $this->context;
}
if ($context && $context[strlen($context)-1] !== '/') {
$context .= '/';
}
$path = $context . $path;
if (!preg_match('/\.yaml$/', $path)) {
$path .= '.yaml';
}
$paths[] = $path;
} else {
$paths = (array) $path;
}
$files = [];
foreach ($paths as $lookup) {
if (is_string($lookup) && strpos($lookup, '://')) {
$files = array_merge($files, $locator->findResources($lookup));
} else {
$files[] = $lookup;
}
}
return array_values(array_unique($files));
}
/**
* @param array $field
* @param string $property
* @param array $call
* @return void
*/
protected function dynamicData(array &$field, $property, array &$call)
{
$params = $call['params'];
if (is_array($params)) {
$function = array_shift($params);
} else {
$function = $params;
$params = [];
}
[$o, $f] = explode('::', $function, 2);
$data = null;
if (!$f) {
if (function_exists($o)) {
$data = call_user_func_array($o, $params);
}
} else {
if (method_exists($o, $f)) {
$data = call_user_func_array([$o, $f], $params);
}
}
// If function returns a value,
if (null !== $data) {
if (is_array($data) && isset($field[$property]) && is_array($field[$property])) {
// Combine field and @data-field together.
$field[$property] += $data;
} else {
// Or create/replace field with @data-field.
$field[$property] = $data;
}
}
}
/**
* @param array $field
* @param string $property
* @param array $call
* @return void
*/
protected function dynamicConfig(array &$field, $property, array &$call)
{
$params = $call['params'];
if (is_array($params)) {
$value = array_shift($params);
$params = array_shift($params);
} else {
$value = $params;
$params = [];
}
$default = $field[$property] ?? null;
$config = Grav::instance()['config']->get($value, $default);
if (!empty($field['value_only'])) {
$config = array_combine($config, $config);
}
if (null !== $config) {
if (!empty($params['append']) && is_array($config) && isset($field[$property]) && is_array($field[$property])) {
// Combine field and @config-field together.
$field[$property] += $config;
} else {
// Or create/replace field with @config-field.
$field[$property] = $config;
}
}
}
/**
* @param array $field
* @param string $property
* @param array $call
* @return void
*/
protected function dynamicSecurity(array &$field, $property, array &$call)
{
if ($property || !empty($field['validate']['ignore'])) {
return;
}
$grav = Grav::instance();
$actions = (array)$call['params'];
/** @var UserInterface|null $user */
$user = $grav['user'] ?? null;
$success = null !== $user;
if ($success) {
$success = $this->resolveActions($user, $actions);
}
if (!$success) {
static::addPropertyRecursive($field, 'validate', ['ignore' => true]);
}
}
/**
* @param UserInterface|null $user
* @param array $actions
* @param string $op
* @return bool
*/
protected function resolveActions(?UserInterface $user, array $actions, string $op = 'and')
{
if (null === $user) {
return false;
}
$c = $i = count($actions);
foreach ($actions as $key => $action) {
if (!is_int($key) && is_array($actions)) {
$i -= $this->resolveActions($user, $action, $key);
} elseif ($user->authorize($action)) {
$i--;
}
}
if ($op === 'and') {
return $i === 0;
}
return $c !== $i;
}
/**
* @param array $field
* @param string $property
* @param array $call
* @return void
*/
protected function dynamicScope(array &$field, $property, array &$call)
{
if ($property && $property !== 'ignore') {
return;
}
$scopes = (array)$call['params'];
$matches = in_array($this->scope, $scopes, true);
if ($this->scope && $property !== 'ignore') {
$matches = !$matches;
}
if ($matches) {
static::addPropertyRecursive($field, 'validate', ['ignore' => true]);
return;
}
}
/**
* @param array $field
* @param string $property
* @param mixed $value
* @return void
*/
public static function addPropertyRecursive(array &$field, $property, $value)
{
if (is_array($value) && isset($field[$property]) && is_array($field[$property])) {
$field[$property] = array_merge_recursive($field[$property], $value);
} else {
$field[$property] = $value;
}
if (!empty($field['fields'])) {
foreach ($field['fields'] as $key => &$child) {
static::addPropertyRecursive($child, $property, $value);
}
}
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Data/Validation.php | system/src/Grav/Common/Data/Validation.php | <?php
/**
* @package Grav\Common\Data
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Data;
use ArrayAccess;
use Countable;
use DateTime;
use Grav\Common\Config\Config;
use Grav\Common\Grav;
use Grav\Common\Language\Language;
use Grav\Common\Security;
use Grav\Common\User\Interfaces\UserInterface;
use Grav\Common\Utils;
use Grav\Common\Yaml;
use Grav\Framework\Flex\Interfaces\FlexObjectInterface;
use Traversable;
use function count;
use function is_array;
use function is_bool;
use function is_float;
use function is_int;
use function is_string;
/**
* Class Validation
* @package Grav\Common\Data
*/
class Validation
{
/**
* Validate value against a blueprint field definition.
*
* @param mixed $value
* @param array $field
* @return array
*/
public static function validate($value, array $field)
{
if (!isset($field['type'])) {
$field['type'] = 'text';
}
$validate = (array)($field['validate'] ?? null);
$validate_type = $validate['type'] ?? null;
$required = $validate['required'] ?? false;
$type = $validate_type ?? $field['type'];
$required = $required && ($validate_type !== 'ignore');
// If value isn't required, we will stop validation if empty value is given.
if ($required !== true && ($value === null || $value === '' || empty($value) || (($field['type'] === 'checkbox' || $field['type'] === 'switch') && $value == false))) {
return [];
}
// Get language class.
$language = Grav::instance()['language'];
$name = ucfirst($field['label'] ?? $field['name']);
$message = (string) isset($field['validate']['message'])
? $language->translate($field['validate']['message'])
: $language->translate('GRAV.FORM.INVALID_INPUT') . ' "' . $language->translate($name) . '"';
// Validate type with fallback type text.
$method = 'type' . str_replace('-', '_', $type);
// If this is a YAML field validate/filter as such
if (isset($field['yaml']) && $field['yaml'] === true) {
$method = 'typeYaml';
}
$messages = [];
$success = method_exists(__CLASS__, $method) ? self::$method($value, $validate, $field) : true;
if (!$success) {
$messages[$field['name']][] = $message;
}
// Check individual rules.
foreach ($validate as $rule => $params) {
$method = 'validate' . ucfirst(str_replace('-', '_', $rule));
if (method_exists(__CLASS__, $method)) {
$success = self::$method($value, $params);
if (!$success) {
$messages[$field['name']][] = $message;
}
}
}
return $messages;
}
/**
* @param mixed $value
* @param array $field
* @return array
*/
public static function checkSafety($value, array $field)
{
$messages = [];
$type = $field['validate']['type'] ?? $field['type'] ?? 'text';
$options = $field['xss_check'] ?? [];
if ($options === false || $type === 'unset') {
return $messages;
}
if (!is_array($options)) {
$options = [];
}
$name = ucfirst($field['label'] ?? $field['name'] ?? 'UNKNOWN');
/** @var UserInterface $user */
$user = Grav::instance()['user'] ?? null;
/** @var Config $config */
$config = Grav::instance()['config'];
$xss_whitelist = $config->get('security.xss_whitelist', 'admin.super');
// Get language class.
/** @var Language $language */
$language = Grav::instance()['language'];
if (!static::authorize($xss_whitelist, $user)) {
$defaults = Security::getXssDefaults();
$options += $defaults;
$options['enabled_rules'] += $defaults['enabled_rules'];
if (!empty($options['safe_protocols'])) {
$options['invalid_protocols'] = array_diff($options['invalid_protocols'], $options['safe_protocols']);
}
if (!empty($options['safe_tags'])) {
$options['dangerous_tags'] = array_diff($options['dangerous_tags'], $options['safe_tags']);
}
if (is_string($value)) {
$violation = Security::detectXss($value, $options);
if ($violation) {
$messages[$name][] = $language->translate(['GRAV.FORM.XSS_ISSUES', $language->translate($name)], null, true);
}
} elseif (is_array($value)) {
$violations = Security::detectXssFromArray($value, "{$name}.", $options);
if ($violations) {
$messages[$name][] = $language->translate(['GRAV.FORM.XSS_ISSUES', $language->translate($name)], null, true);
}
}
}
return $messages;
}
/**
* Checks user authorisation to the action.
*
* @param string|string[] $action
* @param UserInterface|null $user
* @return bool
*/
public static function authorize($action, UserInterface $user = null)
{
if (!$user) {
return false;
}
$action = (array)$action;
foreach ($action as $a) {
// Ignore 'admin.super' if it's not the only value to be checked.
if ($a === 'admin.super' && count($action) > 1 && $user instanceof FlexObjectInterface) {
continue;
}
if ($user->authorize($a)) {
return true;
}
}
return false;
}
/**
* Filter value against a blueprint field definition.
*
* @param mixed $value
* @param array $field
* @return mixed Filtered value.
*/
public static function filter($value, array $field)
{
$validate = (array)($field['filter'] ?? $field['validate'] ?? null);
// If value isn't required, we will return null if empty value is given.
if (($value === null || $value === '') && empty($validate['required'])) {
return null;
}
if (!isset($field['type'])) {
$field['type'] = 'text';
}
$type = $field['filter']['type'] ?? $field['validate']['type'] ?? $field['type'];
$method = 'filter' . ucfirst(str_replace('-', '_', $type));
// If this is a YAML field validate/filter as such
if (isset($field['yaml']) && $field['yaml'] === true) {
$method = 'filterYaml';
}
if (!method_exists(__CLASS__, $method)) {
$method = isset($field['array']) && $field['array'] === true ? 'filterArray' : 'filterText';
}
return self::$method($value, $validate, $field);
}
/**
* HTML5 input: text
*
* @param mixed $value Value to be validated.
* @param array $params Validation parameters.
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeText($value, array $params, array $field)
{
if (!is_string($value) && !is_numeric($value)) {
return false;
}
$value = (string)$value;
if (!empty($params['trim'])) {
$value = trim($value);
}
$value = preg_replace("/\r\n|\r/um", "\n", $value);
$len = mb_strlen($value);
$min = (int)($params['min'] ?? 0);
if ($min && $len < $min) {
return false;
}
$multiline = isset($params['multiline']) && $params['multiline'];
$max = (int)($params['max'] ?? ($multiline ? 65536 : 2048));
if ($max && $len > $max) {
return false;
}
$step = (int)($params['step'] ?? 0);
if ($step && ($len - $min) % $step === 0) {
return false;
}
if (!$multiline && preg_match('/\R/um', $value)) {
return false;
}
return true;
}
/**
* @param mixed $value
* @param array $params
* @param array $field
* @return string
*/
protected static function filterText($value, array $params, array $field)
{
if (!is_string($value) && !is_numeric($value)) {
return '';
}
$value = (string)$value;
if (!empty($params['trim'])) {
$value = trim($value);
}
return preg_replace("/\r\n|\r/um", "\n", $value);
}
/**
* @param mixed $value
* @param array $params
* @param array $field
* @return string|null
*/
protected static function filterCheckbox($value, array $params, array $field)
{
$value = (string)$value;
$field_value = (string)($field['value'] ?? '1');
return $value === $field_value ? $value : null;
}
/**
* @param mixed $value
* @param array $params
* @param array $field
* @return array|array[]|false|string[]
*/
protected static function filterCommaList($value, array $params, array $field)
{
return is_array($value) ? $value : preg_split('/\s*,\s*/', $value, -1, PREG_SPLIT_NO_EMPTY);
}
/**
* @param mixed $value
* @param array $params
* @param array $field
* @return bool
*/
public static function typeCommaList($value, array $params, array $field)
{
if (!isset($params['max'])) {
$params['max'] = 2048;
}
return is_array($value) ? true : self::typeText($value, $params, $field);
}
/**
* @param mixed $value
* @param array $params
* @param array $field
* @return array|array[]|false|string[]
*/
protected static function filterLines($value, array $params, array $field)
{
return is_array($value) ? $value : preg_split('/\s*[\r\n]+\s*/', $value, -1, PREG_SPLIT_NO_EMPTY);
}
/**
* @param mixed $value
* @param array $params
* @return string
*/
protected static function filterLower($value, array $params)
{
return mb_strtolower($value);
}
/**
* @param mixed $value
* @param array $params
* @return string
*/
protected static function filterUpper($value, array $params)
{
return mb_strtoupper($value);
}
/**
* HTML5 input: textarea
*
* @param mixed $value Value to be validated.
* @param array $params Validation parameters.
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeTextarea($value, array $params, array $field)
{
if (!isset($params['multiline'])) {
$params['multiline'] = true;
}
return self::typeText($value, $params, $field);
}
/**
* HTML5 input: password
*
* @param mixed $value Value to be validated.
* @param array $params Validation parameters.
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typePassword($value, array $params, array $field)
{
if (!isset($params['max'])) {
$params['max'] = 256;
}
return self::typeText($value, $params, $field);
}
/**
* HTML5 input: hidden
*
* @param mixed $value Value to be validated.
* @param array $params Validation parameters.
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeHidden($value, array $params, array $field)
{
return self::typeText($value, $params, $field);
}
/**
* Custom input: checkbox list
*
* @param mixed $value Value to be validated.
* @param array $params Validation parameters.
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeCheckboxes($value, array $params, array $field)
{
// Set multiple: true so checkboxes can easily use min/max counts to control number of options required
$field['multiple'] = true;
return self::typeArray((array) $value, $params, $field);
}
/**
* @param mixed $value
* @param array $params
* @param array $field
* @return array|null
*/
protected static function filterCheckboxes($value, array $params, array $field)
{
return self::filterArray($value, $params, $field);
}
/**
* HTML5 input: checkbox
*
* @param mixed $value Value to be validated.
* @param array $params Validation parameters.
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeCheckbox($value, array $params, array $field)
{
$value = (string)$value;
$field_value = (string)($field['value'] ?? '1');
return $value === $field_value;
}
/**
* HTML5 input: radio
*
* @param mixed $value Value to be validated.
* @param array $params Validation parameters.
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeRadio($value, array $params, array $field)
{
return self::typeArray((array) $value, $params, $field);
}
/**
* Custom input: toggle
*
* @param mixed $value Value to be validated.
* @param array $params Validation parameters.
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeToggle($value, array $params, array $field)
{
if (is_bool($value)) {
$value = (int)$value;
}
return self::typeArray((array) $value, $params, $field);
}
/**
* Custom input: file
*
* @param mixed $value Value to be validated.
* @param array $params Validation parameters.
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeFile($value, array $params, array $field)
{
return self::typeArray((array)$value, $params, $field);
}
/**
* @param mixed $value
* @param array $params
* @param array $field
* @return array
*/
protected static function filterFile($value, array $params, array $field)
{
return (array)$value;
}
/**
* HTML5 input: select
*
* @param mixed $value Value to be validated.
* @param array $params Validation parameters.
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeSelect($value, array $params, array $field)
{
return self::typeArray((array) $value, $params, $field);
}
/**
* HTML5 input: number
*
* @param mixed $value Value to be validated.
* @param array $params Validation parameters.
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeNumber($value, array $params, array $field)
{
if (!is_numeric($value)) {
return false;
}
$value = (float)$value;
$min = 0;
if (isset($params['min'])) {
$min = (float)$params['min'];
if ($value < $min) {
return false;
}
}
if (isset($params['max'])) {
$max = (float)$params['max'];
if ($value > $max) {
return false;
}
}
if (isset($params['step'])) {
$step = (float)$params['step'];
// Count of how many steps we are above/below the minimum value.
$pos = ($value - $min) / $step;
$pos = round($pos, 10);
return is_int(static::filterNumber($pos, $params, $field));
}
return true;
}
/**
* @param mixed $value
* @param array $params
* @param array $field
* @return float|int
*/
protected static function filterNumber($value, array $params, array $field)
{
return (string)(int)$value !== (string)(float)$value ? (float)$value : (int)$value;
}
/**
* @param mixed $value
* @param array $params
* @param array $field
* @return string
*/
protected static function filterDateTime($value, array $params, array $field)
{
$format = Grav::instance()['config']->get('system.pages.dateformat.default');
if ($format) {
$converted = new DateTime($value);
return $converted->format($format);
}
return $value;
}
/**
* HTML5 input: range
*
* @param mixed $value Value to be validated.
* @param array $params Validation parameters.
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeRange($value, array $params, array $field)
{
return self::typeNumber($value, $params, $field);
}
/**
* @param mixed $value
* @param array $params
* @param array $field
* @return float|int
*/
protected static function filterRange($value, array $params, array $field)
{
return self::filterNumber($value, $params, $field);
}
/**
* HTML5 input: color
*
* @param mixed $value Value to be validated.
* @param array $params Validation parameters.
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeColor($value, array $params, array $field)
{
return (bool)preg_match('/^\#[0-9a-fA-F]{3}[0-9a-fA-F]{3}?$/u', $value);
}
/**
* HTML5 input: email
*
* @param mixed $value Value to be validated.
* @param array $params Validation parameters.
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeEmail($value, array $params, array $field)
{
if (empty($value)) {
return false;
}
if (!isset($params['max'])) {
$params['max'] = 320;
}
$values = !is_array($value) ? explode(',', preg_replace('/\s+/', '', $value)) : $value;
foreach ($values as $val) {
if (!(self::typeText($val, $params, $field) && strpos($val, '@', 1))) {
return false;
}
}
return true;
}
/**
* HTML5 input: url
*
* @param mixed $value Value to be validated.
* @param array $params Validation parameters.
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeUrl($value, array $params, array $field)
{
if (!isset($params['max'])) {
$params['max'] = 2048;
}
return self::typeText($value, $params, $field) && filter_var($value, FILTER_VALIDATE_URL);
}
/**
* HTML5 input: datetime
*
* @param mixed $value Value to be validated.
* @param array $params Validation parameters.
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeDatetime($value, array $params, array $field)
{
if ($value instanceof DateTime) {
return true;
}
if (!is_string($value)) {
return false;
}
if (!isset($params['format'])) {
return false !== strtotime($value);
}
$dateFromFormat = DateTime::createFromFormat($params['format'], $value);
return $dateFromFormat && $value === date($params['format'], $dateFromFormat->getTimestamp());
}
/**
* HTML5 input: datetime-local
*
* @param mixed $value Value to be validated.
* @param array $params Validation parameters.
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeDatetimeLocal($value, array $params, array $field)
{
return self::typeDatetime($value, $params, $field);
}
/**
* HTML5 input: date
*
* @param mixed $value Value to be validated.
* @param array $params Validation parameters.
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeDate($value, array $params, array $field)
{
if (!isset($params['format'])) {
$params['format'] = 'Y-m-d';
}
return self::typeDatetime($value, $params, $field);
}
/**
* HTML5 input: time
*
* @param mixed $value Value to be validated.
* @param array $params Validation parameters.
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeTime($value, array $params, array $field)
{
if (!isset($params['format'])) {
$params['format'] = 'H:i';
}
return self::typeDatetime($value, $params, $field);
}
/**
* HTML5 input: month
*
* @param mixed $value Value to be validated.
* @param array $params Validation parameters.
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeMonth($value, array $params, array $field)
{
if (!isset($params['format'])) {
$params['format'] = 'Y-m';
}
return self::typeDatetime($value, $params, $field);
}
/**
* HTML5 input: week
*
* @param mixed $value Value to be validated.
* @param array $params Validation parameters.
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeWeek($value, array $params, array $field)
{
if (!isset($params['format']) && !preg_match('/^\d{4}-W\d{2}$/u', $value)) {
return false;
}
return self::typeDatetime($value, $params, $field);
}
/**
* Custom input: array
*
* @param mixed $value Value to be validated.
* @param array $params Validation parameters.
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeArray($value, array $params, array $field)
{
if (!is_array($value)) {
return false;
}
if (isset($field['multiple'])) {
if (isset($params['min']) && count($value) < $params['min']) {
return false;
}
if (isset($params['max']) && count($value) > $params['max']) {
return false;
}
$min = $params['min'] ?? 0;
if (isset($params['step']) && (count($value) - $min) % $params['step'] === 0) {
return false;
}
}
// If creating new values is allowed, no further checks are needed.
$validateOptions = $field['validate']['options'] ?? null;
if (!empty($field['selectize']['create']) || $validateOptions === 'ignore') {
return true;
}
$options = $field['options'] ?? [];
$use = $field['use'] ?? 'values';
if ($validateOptions) {
// Use custom options structure.
foreach ($options as &$option) {
$option = $option[$validateOptions] ?? null;
}
unset($option);
$options = array_values($options);
} elseif (empty($field['selectize']) || empty($field['multiple'])) {
$options = array_keys($options);
}
if ($use === 'keys') {
$value = array_keys($value);
}
return !($options && array_diff($value, $options));
}
/**
* @param mixed $value
* @param array $params
* @param array $field
* @return array|null
*/
protected static function filterFlatten_array($value, $params, $field)
{
$value = static::filterArray($value, $params, $field);
return is_array($value) ? Utils::arrayUnflattenDotNotation($value) : null;
}
/**
* @param mixed $value
* @param array $params
* @param array $field
* @return array|null
*/
protected static function filterArray($value, $params, $field)
{
$values = (array) $value;
$options = isset($field['options']) ? array_keys($field['options']) : [];
$multi = $field['multiple'] ?? false;
if (count($values) === 1 && isset($values[0]) && $values[0] === '') {
return null;
}
if ($options) {
$useKey = isset($field['use']) && $field['use'] === 'keys';
foreach ($values as $key => $val) {
$values[$key] = $useKey ? (bool) $val : $val;
}
}
if ($multi) {
foreach ($values as $key => $val) {
if (is_array($val)) {
$val = implode(',', $val);
$values[$key] = array_map('trim', explode(',', $val));
} else {
$values[$key] = trim($val);
}
}
}
$ignoreEmpty = isset($field['ignore_empty']) && Utils::isPositive($field['ignore_empty']);
$valueType = $params['value_type'] ?? null;
$keyType = $params['key_type'] ?? null;
if ($ignoreEmpty || $valueType || $keyType) {
$values = static::arrayFilterRecurse($values, ['value_type' => $valueType, 'key_type' => $keyType, 'ignore_empty' => $ignoreEmpty]);
}
return $values;
}
/**
* @param array $values
* @param array $params
* @return array
*/
protected static function arrayFilterRecurse(array $values, array $params): array
{
foreach ($values as $key => &$val) {
if ($params['key_type']) {
switch ($params['key_type']) {
case 'int':
$result = is_int($key);
break;
case 'string':
$result = is_string($key);
break;
default:
$result = false;
}
if (!$result) {
unset($values[$key]);
}
}
if (is_array($val)) {
$val = static::arrayFilterRecurse($val, $params);
if ($params['ignore_empty'] && empty($val)) {
unset($values[$key]);
}
} else {
if ($params['value_type'] && $val !== '' && $val !== null) {
switch ($params['value_type']) {
case 'bool':
if (Utils::isPositive($val)) {
$val = true;
} elseif (Utils::isNegative($val)) {
$val = false;
} else {
// Ignore invalid bool values.
$val = null;
}
break;
case 'int':
$val = (int)$val;
break;
case 'float':
$val = (float)$val;
break;
case 'string':
$val = (string)$val;
break;
case 'trim':
$val = trim($val);
break;
}
}
if ($params['ignore_empty'] && ($val === '' || $val === null)) {
unset($values[$key]);
}
}
}
return $values;
}
/**
* @param mixed $value
* @param array $params
* @param array $field
* @return bool
*/
public static function typeList($value, array $params, array $field)
{
if (!is_array($value)) {
return false;
}
if (isset($field['fields'])) {
foreach ($value as $key => $item) {
foreach ($field['fields'] as $subKey => $subField) {
$subKey = trim($subKey, '.');
$subValue = $item[$subKey] ?? null;
self::validate($subValue, $subField);
}
}
}
return true;
}
/**
* @param mixed $value
* @param array $params
* @param array $field
* @return array
*/
protected static function filterList($value, array $params, array $field)
{
return (array) $value;
}
/**
* @param mixed $value
* @param array $params
* @return array
*/
public static function filterYaml($value, $params)
{
if (!is_string($value)) {
return $value;
}
return (array) Yaml::parse($value);
}
/**
* Custom input: ignore (will not validate)
*
* @param mixed $value Value to be validated.
* @param array $params Validation parameters.
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeIgnore($value, array $params, array $field)
{
return true;
}
/**
* @param mixed $value
* @param array $params
* @param array $field
* @return mixed
*/
public static function filterIgnore($value, array $params, array $field)
{
return $value;
}
/**
* Input value which can be ignored.
*
* @param mixed $value Value to be validated.
* @param array $params Validation parameters.
* @param array $field Blueprint for the field.
* @return bool True if validation succeeded.
*/
public static function typeUnset($value, array $params, array $field)
{
return true;
}
/**
* @param mixed $value
* @param array $params
* @param array $field
* @return null
*/
public static function filterUnset($value, array $params, array $field)
{
return null;
}
// HTML5 attributes (min, max and range are handled inside the types)
/**
* @param mixed $value
* @param bool $params
* @return bool
*/
public static function validateRequired($value, $params)
{
if (is_scalar($value)) {
return (bool) $params !== true || $value !== '';
}
return (bool) $params !== true || !empty($value);
}
/**
* @param mixed $value
* @param string $params
* @return bool
*/
public static function validatePattern($value, $params)
{
return (bool) preg_match("`^{$params}$`u", $value);
}
// Internal types
/**
* @param mixed $value
* @param mixed $params
* @return bool
*/
public static function validateAlpha($value, $params)
{
return ctype_alpha($value);
}
/**
* @param mixed $value
* @param mixed $params
* @return bool
*/
public static function validateAlnum($value, $params)
{
return ctype_alnum($value);
}
/**
* @param mixed $value
* @param mixed $params
* @return bool
*/
public static function typeBool($value, $params)
{
return is_bool($value) || $value == 1 || $value == 0;
}
/**
* @param mixed $value
* @param mixed $params
* @return bool
*/
public static function validateBool($value, $params)
{
return is_bool($value) || $value == 1 || $value == 0;
}
/**
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | true |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Errors/Errors.php | system/src/Grav/Common/Errors/Errors.php | <?php
/**
* @package Grav\Common\Errors
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Errors;
use Exception;
use Grav\Common\Grav;
use Whoops\Handler\JsonResponseHandler;
use Whoops\Handler\PrettyPageHandler;
use Whoops\Run;
use Whoops\Util\Misc;
use function is_int;
/**
* Class Errors
* @package Grav\Common\Errors
*/
class Errors
{
/**
* @return void
*/
public function resetHandlers()
{
$grav = Grav::instance();
$config = $grav['config']->get('system.errors');
$jsonRequest = $_SERVER && isset($_SERVER['HTTP_ACCEPT']) && $_SERVER['HTTP_ACCEPT'] === 'application/json';
// Setup Whoops-based error handler
$system = new SystemFacade;
$whoops = new Run($system);
$verbosity = 1;
if (isset($config['display'])) {
if (is_int($config['display'])) {
$verbosity = $config['display'];
} else {
$verbosity = $config['display'] ? 1 : 0;
}
}
switch ($verbosity) {
case 1:
$error_page = new PrettyPageHandler();
$error_page->setPageTitle('Crikey! There was an error...');
$error_page->addResourcePath(GRAV_ROOT . '/system/assets');
$error_page->addCustomCss('whoops.css');
$whoops->prependHandler($error_page);
break;
case -1:
$whoops->prependHandler(new BareHandler);
break;
default:
$whoops->prependHandler(new SimplePageHandler);
break;
}
if ($jsonRequest || Misc::isAjaxRequest()) {
$whoops->prependHandler(new JsonResponseHandler());
}
if (isset($config['log']) && $config['log']) {
$logger = $grav['log'];
$whoops->pushHandler(function ($exception, $inspector, $run) use ($logger) {
try {
$logger->addCritical($exception->getMessage() . ' - Trace: ' . $exception->getTraceAsString());
} catch (Exception $e) {
echo $e;
}
});
}
$whoops->register();
// Re-register deprecation handler.
$grav['debugger']->setErrorHandler();
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Errors/SystemFacade.php | system/src/Grav/Common/Errors/SystemFacade.php | <?php
/**
* @package Grav\Common\Errors
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Errors;
/**
* Class SystemFacade
* @package Grav\Common\Errors
*/
class SystemFacade extends \Whoops\Util\SystemFacade
{
/** @var callable */
protected $whoopsShutdownHandler;
/**
* @param callable $function
* @return void
*/
public function registerShutdownFunction(callable $function)
{
$this->whoopsShutdownHandler = $function;
register_shutdown_function([$this, 'handleShutdown']);
}
/**
* Special case to deal with Fatal errors and the like.
*
* @return void
*/
public function handleShutdown()
{
$error = $this->getLastError();
// Ignore core warnings and errors.
if ($error && !($error['type'] & (E_CORE_WARNING | E_CORE_ERROR))) {
$handler = $this->whoopsShutdownHandler;
$handler();
}
}
/**
* @param int $httpCode
*
* @return int
*/
public function setHttpResponseCode($httpCode)
{
if (!headers_sent()) {
// Ensure that no 'location' header is present as otherwise this
// will override the HTTP code being set here, and mask the
// expected error page.
header_remove('location');
// Work around PHP bug #8218 (8.0.17 & 8.1.4).
header_remove('Content-Encoding');
}
return http_response_code($httpCode);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Errors/BareHandler.php | system/src/Grav/Common/Errors/BareHandler.php | <?php
/**
* @package Grav\Common\Errors
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Errors;
use Whoops\Handler\Handler;
/**
* Class BareHandler
* @package Grav\Common\Errors
*/
class BareHandler extends Handler
{
/**
* @return int
*/
public function handle()
{
$inspector = $this->getInspector();
$code = $inspector->getException()->getCode();
if (($code >= 400) && ($code < 600)) {
$this->getRun()->sendHttpCode($code);
}
return Handler::QUIT;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Errors/SimplePageHandler.php | system/src/Grav/Common/Errors/SimplePageHandler.php | <?php
/**
* @package Grav\Common\Errors
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Errors;
use ErrorException;
use InvalidArgumentException;
use RuntimeException;
use Whoops\Handler\Handler;
use Whoops\Util\Misc;
use Whoops\Util\TemplateHelper;
/**
* Class SimplePageHandler
* @package Grav\Common\Errors
*/
class SimplePageHandler extends Handler
{
/** @var array */
private $searchPaths = [];
/** @var array */
private $resourceCache = [];
public function __construct()
{
// Add the default, local resource search path:
$this->searchPaths[] = __DIR__ . '/Resources';
}
/**
* @return int
*/
public function handle()
{
$inspector = $this->getInspector();
$helper = new TemplateHelper();
$templateFile = $this->getResource('layout.html.php');
$cssFile = $this->getResource('error.css');
$code = $inspector->getException()->getCode();
if (($code >= 400) && ($code < 600)) {
$this->getRun()->sendHttpCode($code);
}
$message = $inspector->getException()->getMessage();
if ($inspector->getException() instanceof ErrorException) {
$code = Misc::translateErrorCode($code);
}
$vars = array(
'stylesheet' => file_get_contents($cssFile),
'code' => $code,
'message' => htmlspecialchars(strip_tags(rawurldecode($message)), ENT_QUOTES, 'UTF-8'),
);
$helper->setVariables($vars);
$helper->render($templateFile);
return Handler::QUIT;
}
/**
* @param string $resource
* @return string
* @throws RuntimeException
*/
protected function getResource($resource)
{
// If the resource was found before, we can speed things up
// by caching its absolute, resolved path:
if (isset($this->resourceCache[$resource])) {
return $this->resourceCache[$resource];
}
// Search through available search paths, until we find the
// resource we're after:
foreach ($this->searchPaths as $path) {
$fullPath = "{$path}/{$resource}";
if (is_file($fullPath)) {
// Cache the result:
$this->resourceCache[$resource] = $fullPath;
return $fullPath;
}
}
// If we got this far, nothing was found.
throw new RuntimeException(
"Could not find resource '{$resource}' in any resource paths (searched: " . implode(', ', $this->searchPaths). ')'
);
}
/**
* @param string $path
* @return void
*/
public function addResourcePath($path)
{
if (!is_dir($path)) {
throw new InvalidArgumentException(
"'{$path}' is not a valid directory"
);
}
array_unshift($this->searchPaths, $path);
}
/**
* @return array
*/
public function getResourcePaths()
{
return $this->searchPaths;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Errors/Resources/layout.html.php | system/src/Grav/Common/Errors/Resources/layout.html.php | <?php
/**
* Layout template file for Whoops's pretty error output.
*/
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Whoops there was an error!</title>
<style><?php echo $stylesheet ?></style>
</head>
<body>
<div class="container">
<div class="details">
<header>
Server Error
</header>
<p>Sorry, something went terribly wrong!</p>
<h3><?php echo $code ?> - <?php echo $message ?></h3>
<h5>For further details please review your <code>logs/</code> folder, or enable displaying of errors in your system configuration.</h5>
</div>
</div>
</body>
</html>
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Backup/Backups.php | system/src/Grav/Common/Backup/Backups.php | <?php
/**
* @package Grav\Common\Backup
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Backup;
use DateTime;
use Exception;
use FilesystemIterator;
use GlobIterator;
use Grav\Common\Filesystem\Archiver;
use Grav\Common\Filesystem\Folder;
use Grav\Common\Inflector;
use Grav\Common\Scheduler\Job;
use Grav\Common\Scheduler\Scheduler;
use Grav\Common\Utils;
use Grav\Common\Grav;
use RocketTheme\Toolbox\Event\Event;
use RocketTheme\Toolbox\File\JsonFile;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use RuntimeException;
use SplFileInfo;
use stdClass;
use Symfony\Component\EventDispatcher\EventDispatcher;
use function count;
/**
* Class Backups
* @package Grav\Common\Backup
*/
class Backups
{
protected const BACKUP_FILENAME_REGEXZ = "#(.*)--(\d*).zip#";
protected const BACKUP_DATE_FORMAT = 'YmdHis';
/** @var string */
protected static $backup_dir;
/** @var array|null */
protected static $backups;
/**
* @return void
*/
public function init()
{
$grav = Grav::instance();
/** @var EventDispatcher $dispatcher */
$dispatcher = $grav['events'];
$dispatcher->addListener('onSchedulerInitialized', [$this, 'onSchedulerInitialized']);
$grav->fireEvent('onBackupsInitialized', new Event(['backups' => $this]));
}
/**
* @return void
*/
public function setup()
{
if (null === static::$backup_dir) {
$grav = Grav::instance();
static::$backup_dir = $grav['locator']->findResource('backup://', true, true);
Folder::create(static::$backup_dir);
}
}
/**
* @param Event $event
* @return void
*/
public function onSchedulerInitialized(Event $event)
{
$grav = Grav::instance();
/** @var Scheduler $scheduler */
$scheduler = $event['scheduler'];
/** @var Inflector $inflector */
$inflector = $grav['inflector'];
foreach (static::getBackupProfiles() as $id => $profile) {
$at = $profile['schedule_at'];
$name = $inflector::hyphenize($profile['name']);
$logs = 'logs/backup-' . $name . '.out';
/** @var Job $job */
$job = $scheduler->addFunction('Grav\Common\Backup\Backups::backup', [$id], $name);
$job->at($at);
$job->output($logs);
$job->backlink('/tools/backups');
}
}
/**
* @param string $backup
* @param string $base_url
* @return string
*/
public function getBackupDownloadUrl($backup, $base_url)
{
$param_sep = Grav::instance()['config']->get('system.param_sep', ':');
$download = urlencode(base64_encode(Utils::basename($backup)));
$url = rtrim(Grav::instance()['uri']->rootUrl(true), '/') . '/' . trim(
$base_url,
'/'
) . '/task' . $param_sep . 'backup/download' . $param_sep . $download . '/admin-nonce' . $param_sep . Utils::getNonce('admin-form');
return $url;
}
/**
* @return array
*/
public static function getBackupProfiles()
{
return Grav::instance()['config']->get('backups.profiles');
}
/**
* @return array
*/
public static function getPurgeConfig()
{
return Grav::instance()['config']->get('backups.purge');
}
/**
* @return array
*/
public function getBackupNames()
{
return array_column(static::getBackupProfiles(), 'name');
}
/**
* @return float|int
*/
public static function getTotalBackupsSize()
{
$backups = static::getAvailableBackups();
return $backups ? array_sum(array_column($backups, 'size')) : 0;
}
/**
* @param bool $force
* @return array
*/
public static function getAvailableBackups($force = false)
{
if ($force || null === static::$backups) {
static::$backups = [];
$grav = Grav::instance();
$backups_itr = new GlobIterator(static::$backup_dir . '/*.zip', FilesystemIterator::KEY_AS_FILENAME);
$inflector = $grav['inflector'];
$long_date_format = DATE_RFC2822;
/**
* @var string $name
* @var SplFileInfo $file
*/
foreach ($backups_itr as $name => $file) {
if (preg_match(static::BACKUP_FILENAME_REGEXZ, $name, $matches)) {
$date = DateTime::createFromFormat(static::BACKUP_DATE_FORMAT, $matches[2]);
$timestamp = $date->getTimestamp();
$backup = new stdClass();
$backup->title = $inflector->titleize($matches[1]);
$backup->time = $date;
$backup->date = $date->format($long_date_format);
$backup->filename = $name;
$backup->path = $file->getPathname();
$backup->size = $file->getSize();
static::$backups[$timestamp] = $backup;
}
}
// Reverse Key Sort to get in reverse date order
krsort(static::$backups);
}
return static::$backups;
}
/**
* Backup
*
* @param int $id
* @param callable|null $status
* @return string|null
*/
public static function backup($id = 0, callable $status = null)
{
$grav = Grav::instance();
$profiles = static::getBackupProfiles();
/** @var UniformResourceLocator $locator */
$locator = $grav['locator'];
if (isset($profiles[$id])) {
$backup = (object) $profiles[$id];
} else {
throw new RuntimeException('No backups defined...');
}
$name = $grav['inflector']->underscorize($backup->name);
$date = date(static::BACKUP_DATE_FORMAT, time());
$filename = trim($name, '_') . '--' . $date . '.zip';
$destination = static::$backup_dir . DS . $filename;
$max_execution_time = ini_set('max_execution_time', '600');
$backup_root = $backup->root;
if ($locator->isStream($backup_root)) {
$backup_root = $locator->findResource($backup_root);
} else {
$backup_root = rtrim(GRAV_ROOT . $backup_root, DS) ?: DS;
}
if (!$backup_root || !file_exists($backup_root)) {
throw new RuntimeException("Backup location: {$backup_root} does not exist...");
}
$options = [
'exclude_files' => static::convertExclude($backup->exclude_files ?? ''),
'exclude_paths' => static::convertExclude($backup->exclude_paths ?? ''),
];
$archiver = Archiver::create('zip');
$archiver->setArchive($destination)->setOptions($options)->compress($backup_root, $status)->addEmptyFolders($options['exclude_paths'], $status);
$status && $status([
'type' => 'message',
'message' => 'Done...',
]);
$status && $status([
'type' => 'progress',
'complete' => true
]);
if ($max_execution_time !== false) {
ini_set('max_execution_time', $max_execution_time);
}
// Log the backup
$grav['log']->notice('Backup Created: ' . $destination);
// Fire Finished event
$grav->fireEvent('onBackupFinished', new Event(['backup' => $destination]));
// Purge anything required
static::purge();
// Log
$log = JsonFile::instance($locator->findResource("log://backup.log", true, true));
$log->content([
'time' => time(),
'location' => $destination
]);
$log->save();
return $destination;
}
/**
* @return void
* @throws Exception
*/
public static function purge()
{
$purge_config = static::getPurgeConfig();
$trigger = $purge_config['trigger'];
$backups = static::getAvailableBackups(true);
switch ($trigger) {
case 'number':
$backups_count = count($backups);
if ($backups_count > $purge_config['max_backups_count']) {
$last = end($backups);
unlink($last->path);
static::purge();
}
break;
case 'time':
$last = end($backups);
$now = new DateTime();
$interval = $now->diff($last->time);
if ($interval->days > $purge_config['max_backups_time']) {
unlink($last->path);
static::purge();
}
break;
default:
$used_space = static::getTotalBackupsSize();
$max_space = $purge_config['max_backups_space'] * 1024 * 1024 * 1024;
if ($used_space > $max_space) {
$last = end($backups);
unlink($last->path);
static::purge();
}
break;
}
}
/**
* @param string $exclude
* @return array
*/
protected static function convertExclude($exclude)
{
// Split by newlines, commas, or multiple spaces
$lines = preg_split("/[\r\n,]+|[\s]{2,}/", $exclude);
// Remove empty values and trim
$lines = array_filter(array_map('trim', $lines));
return array_map('trim', $lines, array_fill(0, count($lines), '/'));
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Media/Interfaces/ImageMediaInterface.php | system/src/Grav/Common/Media/Interfaces/ImageMediaInterface.php | <?php
/**
* @package Grav\Common\Media
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Media\Interfaces;
/**
* Class implements image media interface.
*/
interface ImageMediaInterface extends MediaObjectInterface
{
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Media/Interfaces/VideoMediaInterface.php | system/src/Grav/Common/Media/Interfaces/VideoMediaInterface.php | <?php
/**
* @package Grav\Common\Media
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Media\Interfaces;
/**
* Class implements video media interface.
*/
interface VideoMediaInterface extends MediaObjectInterface, MediaPlayerInterface
{
/**
* Allows to set the video's poster image
*
* @param string $urlImage
* @return $this
*/
public function poster($urlImage);
/**
* Allows to set the playsinline attribute
*
* @param bool $status
* @return $this
*/
public function playsinline($status = false);
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Media/Interfaces/MediaCollectionInterface.php | system/src/Grav/Common/Media/Interfaces/MediaCollectionInterface.php | <?php
/**
* @package Grav\Common\Media
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Media\Interfaces;
use Grav\Common\Data\Blueprint;
use Grav\Common\Page\Medium\ImageFile;
use Grav\Common\Page\Medium\Medium;
/**
* Class implements media collection interface.
*/
interface MediaCollectionInterface extends \Grav\Framework\Media\Interfaces\MediaCollectionInterface
{
/**
* Return media path.
*
* @return string|null
*/
public function getPath();
/**
* @param string|null $path
* @return void
*/
public function setPath(?string $path);
/**
* Get medium by filename.
*
* @param string $filename
* @return Medium|null
*/
public function get($filename);
/**
* Get a list of all media.
*
* @return MediaObjectInterface[]
*/
public function all();
/**
* Get a list of all image media.
*
* @return MediaObjectInterface[]
*/
public function images();
/**
* Get a list of all video media.
*
* @return MediaObjectInterface[]
*/
public function videos();
/**
* Get a list of all audio media.
*
* @return MediaObjectInterface[]
*/
public function audios();
/**
* Get a list of all file media.
*
* @return MediaObjectInterface[]
*/
public function files();
/**
* Set file modification timestamps (query params) for all the media files.
*
* @param string|int|null $timestamp
* @return $this
*/
public function setTimestamps($timestamp = null);
/**
* @param string $name
* @param MediaObjectInterface $file
* @return void
*/
public function add($name, $file);
/**
* Create Medium from a file.
*
* @param string $file
* @param array $params
* @return Medium|null
*/
public function createFromFile($file, array $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);
/**
* @param MediaObjectInterface $mediaObject
* @return ImageFile
*/
public function getImageFileObject(MediaObjectInterface $mediaObject): ImageFile;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Media/Interfaces/MediaUploadInterface.php | system/src/Grav/Common/Media/Interfaces/MediaUploadInterface.php | <?php
/**
* @package Grav\Common\Media
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Media\Interfaces;
use Psr\Http\Message\UploadedFileInterface;
use RuntimeException;
/**
* Implements media upload and delete functionality.
*/
interface MediaUploadInterface
{
/**
* Checks that uploaded file meets the requirements. Returns new filename.
*
* @example
* $filename = null; // Override filename if needed (ignored if randomizing filenames).
* $settings = ['destination' => 'user://pages/media']; // Settings from the form field.
* $filename = $media->checkUploadedFile($uploadedFile, $filename, $settings);
* $media->copyUploadedFile($uploadedFile, $filename);
* @param UploadedFileInterface $uploadedFile
* @param string|null $filename
* @param array|null $settings
* @return string
* @throws RuntimeException
*/
public function checkUploadedFile(UploadedFileInterface $uploadedFile, string $filename = null, array $settings = null): string;
/**
* Copy uploaded file to the media collection.
*
* WARNING: Always check uploaded file before copying it!
*
* @example
* $filename = null; // Override filename if needed (ignored if randomizing filenames).
* $settings = ['destination' => 'user://pages/media']; // Settings from the form field.
* $filename = $media->checkUploadedFile($uploadedFile, $filename, $settings);
* $media->copyUploadedFile($uploadedFile, $filename);
*
* @param UploadedFileInterface $uploadedFile
* @param string $filename
* @param array|null $settings
* @return void
* @throws RuntimeException
*/
public function copyUploadedFile(UploadedFileInterface $uploadedFile, string $filename, array $settings = null): void;
/**
* Delete real file from the media collection.
*
* @param string $filename
* @param array|null $settings
* @return void
*/
public function deleteFile(string $filename, array $settings = null): void;
/**
* Rename file inside the media collection.
*
* @param string $from
* @param string $to
* @param array|null $settings
*/
public function renameFile(string $from, string $to, array $settings = null): void;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Media/Interfaces/MediaFileInterface.php | system/src/Grav/Common/Media/Interfaces/MediaFileInterface.php | <?php
/**
* @package Grav\Common\Media
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Media\Interfaces;
/**
* Class implements media file interface.
*/
interface MediaFileInterface extends MediaObjectInterface
{
/**
* Check if this medium exists or not
*
* @return bool
*/
public function exists();
/**
* Get file modification time for the medium.
*
* @return int|null
*/
public function modified();
/**
* Get size of the medium.
*
* @return int
*/
public function size();
/**
* Return the path to file.
*
* @param bool $reset
* @return string path to file
*/
public function path($reset = true);
/**
* Return the relative path to file
*
* @param bool $reset
* @return mixed
*/
public function relativePath($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/Media/Interfaces/MediaObjectInterface.php | system/src/Grav/Common/Media/Interfaces/MediaObjectInterface.php | <?php
/**
* @package Grav\Common\Media
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Media\Interfaces;
use ArrayAccess;
use Grav\Common\Data\Data;
/**
* Class implements media object interface.
*
* @property string $type
* @property string $filename
* @property string $filepath
*/
interface MediaObjectInterface extends \Grav\Framework\Media\Interfaces\MediaObjectInterface, ArrayAccess
{
/**
* Create a copy of this media object
*
* @return static
*/
public function copy();
/**
* Return just metadata from the Medium object
*
* @return Data
*/
public function meta();
/**
* Set querystring to file modification timestamp (or value provided as a parameter).
*
* @param string|int|null $timestamp
* @return $this
*/
public function setTimestamp($timestamp = null);
/**
* Returns an array containing just the metadata
*
* @return array
*/
public function metadata();
/**
* Add meta file for the medium.
*
* @param string $filepath
*/
public function addMetaFile($filepath);
/**
* Add alternative Medium to this Medium.
*
* @param int|float $ratio
* @param MediaObjectInterface $alternative
*/
public function addAlternative($ratio, MediaObjectInterface $alternative);
/**
* Get list of image alternatives. Includes the current media image as well.
*
* @param bool $withDerived If true, include generated images as well. If false, only return existing files.
* @return array
*/
public function getAlternatives(bool $withDerived = true): array;
/**
* Return string representation of the object (html).
*
* @return string
*/
public function __toString();
/**
* Get/set querystring for the file's url
*
* @param string|null $querystring
* @param bool $withQuestionmark
* @return string
*/
public function querystring($querystring = null, $withQuestionmark = true);
/**
* Get the URL with full querystring
*
* @param string $url
* @return string
*/
public function urlQuerystring($url);
/**
* Get/set hash for the file's url
*
* @param string|null $hash
* @param bool $withHash
* @return string
*/
public function urlHash($hash = null, $withHash = true);
/**
* 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);
/**
* Reset medium.
*
* @return $this
*/
public function reset();
/**
* Add custom attribute to medium.
*
* @param string $attribute
* @param string $value
* @return $this
*/
public function attribute($attribute = null, $value = '');
/**
* Switch display mode.
*
* @param string $mode
* @return MediaObjectInterface|null
*/
public function display($mode = 'source');
/**
* Helper method to determine if this media item has a thumbnail or not
*
* @param string $type;
* @return bool
*/
public function thumbnailExists($type = 'page');
/**
* Switch thumbnail.
*
* @param string $type
* @return $this
*/
public function thumbnail($type = 'auto');
/**
* Turn the current Medium into a Link
*
* @param bool $reset
* @param array $attributes
* @return MediaLinkInterface
*/
public function link($reset = true, array $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);
/**
* Add a class to the element from Markdown or Twig
* Example:  or 
*
* @return $this
*/
public function classes();
/**
* Add an id to the element from Markdown or Twig
* Example: 
*
* @param string $id
* @return $this
*/
public function id($id);
/**
* Allows to add an inline style attribute from Markdown or Twig
* Example: 
*
* @param string $style
* @return $this
*/
public function style($style);
/**
* Allow any action to be called on this medium from twig or markdown
*
* @param string $method
* @param mixed $args
* @return $this
*/
#[\ReturnTypeWillChange]
public function __call($method, $args);
/**
* 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);
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Media/Interfaces/MediaPlayerInterface.php | system/src/Grav/Common/Media/Interfaces/MediaPlayerInterface.php | <?php
/**
* @package Grav\Common\Media
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Media\Interfaces;
/**
* Class implements media player interface.
*/
interface MediaPlayerInterface extends MediaObjectInterface
{
/**
* Allows to set or remove the HTML5 default controls
*
* @param bool $status
* @return $this
*/
public function controls($status = true);
/**
* Allows to set the loop attribute
*
* @param bool $status
* @return $this
*/
public function loop($status = false);
/**
* Allows to set the autoplay attribute
*
* @param bool $status
* @return $this
*/
public function autoplay($status = false);
/**
* Allows to set the muted attribute
*
* @param bool $status
* @return $this
*/
public function muted($status = false);
/**
* Allows to set the preload behaviour
*
* @param string|null $preload
* @return $this
*/
public function preload($preload = null);
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Media/Interfaces/MediaInterface.php | system/src/Grav/Common/Media/Interfaces/MediaInterface.php | <?php
/**
* @package Grav\Common\Media
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Media\Interfaces;
/**
* Class implements media interface.
*/
interface MediaInterface extends \Grav\Framework\Media\Interfaces\MediaInterface
{
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Media/Interfaces/MediaLinkInterface.php | system/src/Grav/Common/Media/Interfaces/MediaLinkInterface.php | <?php
/**
* @package Grav\Common\Media
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Media\Interfaces;
/**
* Class implements media file interface.
*/
interface MediaLinkInterface
{
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Media/Interfaces/AudioMediaInterface.php | system/src/Grav/Common/Media/Interfaces/AudioMediaInterface.php | <?php
/**
* @package Grav\Common\Media
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Media\Interfaces;
/**
* Class implements audio media interface.
*/
interface AudioMediaInterface extends MediaObjectInterface, MediaPlayerInterface
{
/**
* Allows to set the controlsList behaviour
* Separate multiple values with a hyphen
*
* @param string $controlsList
* @return $this
*/
public function controlsList($controlsList);
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Media/Interfaces/ImageManipulateInterface.php | system/src/Grav/Common/Media/Interfaces/ImageManipulateInterface.php | <?php
/**
* @package Grav\Common\Media
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Media\Interfaces;
/**
* Class implements image manipulation interface.
*/
interface ImageManipulateInterface
{
/**
* Allows the ability to override the image's pretty name stored in cache
*
* @param string $name
*/
public function setImagePrettyName($name);
/**
* @return string
*/
public function getImagePrettyName();
/**
* Simply processes with no extra methods. Useful for triggering events.
*
* @return $this
*/
public function cache();
/**
* Generate alternative image widths, using either an array of integers, or
* a min width, a max width, and a step parameter to fill out the necessary
* widths. Existing image alternatives won't be overwritten.
*
* @param int|int[] $min_width
* @param int $max_width
* @param int $step
* @return $this
*/
public function derivatives($min_width, $max_width = 2500, $step = 200);
/**
* Clear out the alternatives.
*/
public function clearAlternatives();
/**
* Sets or gets the quality of the image
*
* @param int|null $quality 0-100 quality
* @return int|$this
*/
public function quality($quality = null);
/**
* Sets image output format.
*
* @param string $format
* @return $this
*/
public function format($format);
/**
* Set or get sizes parameter for srcset media action
*
* @param string|null $sizes
* @return string
*/
public function sizes($sizes = null);
/**
* Allows to set the width attribute from Markdown or Twig
* Examples: 
* 
* 
* 
* {{ page.media['myimg.png'].width().height().html }}
* {{ page.media['myimg.png'].resize(100,200).width(100).height(200).html }}
*
* @param string|int $value A value or 'auto' or empty to use the width of the image
* @return $this
*/
public function width($value = 'auto');
/**
* Allows to set the height attribute from Markdown or Twig
* Examples: 
* 
* 
* 
* {{ page.media['myimg.png'].width().height().html }}
* {{ page.media['myimg.png'].resize(100,200).width(100).height(200).html }}
*
* @param string|int $value A value or 'auto' or empty to use the height of the image
* @return $this
*/
public function height($value = 'auto');
/* *
* Filter image by using user defined filter parameters.
*
* @param string $filter Filter to be used.
* @return $this
* FIXME: Conflicts against Data class
*/
//public function filter($filter = 'image.filters.default');
/**
* Return the image higher quality version
*
* @return ImageMediaInterface the alternative version with higher quality
*/
public function higherQualityAlternative();
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Media/Traits/ImageMediaTrait.php | system/src/Grav/Common/Media/Traits/ImageMediaTrait.php | <?php
/**
* @package Grav\Common\Media
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Media\Traits;
use Grav\Common\Grav;
use Grav\Common\Media\Interfaces\ImageMediaInterface;
use Grav\Common\Media\Interfaces\MediaCollectionInterface;
use Grav\Common\Page\Medium\ImageFile;
use Grav\Common\Page\Medium\ImageMedium;
use Grav\Common\Page\Medium\MediumFactory;
use function array_key_exists;
use function extension_loaded;
use function func_num_args;
use function function_exists;
/**
* Trait ImageMediaTrait
* @package Grav\Common\Media\Traits
*/
trait ImageMediaTrait
{
/** @var ImageFile|null */
protected $image;
/** @var string */
protected $format = 'guess';
/** @var int */
protected $quality;
/** @var int */
protected $default_quality;
/** @var bool */
protected $debug_watermarked = false;
/** @var bool */
protected $auto_sizes;
/** @var bool */
protected $aspect_ratio;
/** @var integer */
protected $retina_scale;
/** @var bool */
protected $watermark;
/** @var array */
public static $magic_actions = [
'resize', 'forceResize', 'cropResize', 'crop', 'zoomCrop',
'negate', 'brightness', 'contrast', 'grayscale', 'emboss',
'smooth', 'sharp', 'edge', 'colorize', 'sepia', 'enableProgressive',
'rotate', 'flip', 'fixOrientation', 'gaussianBlur', 'format', 'create', 'fill', 'merge'
];
/** @var array */
public static $magic_resize_actions = [
'resize' => [0, 1],
'forceResize' => [0, 1],
'cropResize' => [0, 1],
'crop' => [0, 1, 2, 3],
'zoomCrop' => [0, 1]
];
/** @var string */
protected $sizes = '100vw';
/**
* Allows the ability to override the image's pretty name stored in cache
*
* @param string $name
*/
public function setImagePrettyName($name)
{
$this->set('prettyname', $name);
if ($this->image) {
$this->image->setPrettyName($name);
}
}
/**
* @return string
*/
public function getImagePrettyName()
{
if ($this->get('prettyname')) {
return $this->get('prettyname');
}
$basename = $this->get('basename');
if (preg_match('/[a-z0-9]{40}-(.*)/', $basename, $matches)) {
$basename = $matches[1];
}
return $basename;
}
/**
* Simply processes with no extra methods. Useful for triggering events.
*
* @return $this
*/
public function cache()
{
if (!$this->image) {
$this->image();
}
return $this;
}
/**
* Generate alternative image widths, using either an array of integers, or
* a min width, a max width, and a step parameter to fill out the necessary
* widths. Existing image alternatives won't be overwritten.
*
* @param int|int[] $min_width
* @param int $max_width
* @param int $step
* @return $this
*/
public function derivatives($min_width, $max_width = 2500, $step = 200)
{
if (!empty($this->alternatives)) {
$max = max(array_keys($this->alternatives));
$base = $this->alternatives[$max];
} else {
$base = $this;
}
$widths = [];
if (func_num_args() === 1) {
foreach ((array) func_get_arg(0) as $width) {
if ($width < $base->get('width')) {
$widths[] = $width;
}
}
} else {
$max_width = min($max_width, $base->get('width'));
for ($width = $min_width; $width < $max_width; $width += $step) {
$widths[] = $width;
}
}
foreach ($widths as $width) {
// Only generate image alternatives that don't already exist
if (array_key_exists((int) $width, $this->alternatives)) {
continue;
}
$derivative = MediumFactory::fromFile($base->get('filepath'));
// It's possible that MediumFactory::fromFile returns null if the
// original image file no longer exists and this class instance was
// retrieved from the page cache
if (null !== $derivative) {
$index = 2;
$alt_widths = array_keys($this->alternatives);
sort($alt_widths);
foreach ($alt_widths as $i => $key) {
if ($width > $key) {
$index += max($i, 1);
}
}
$basename = preg_replace('/(@\d+x)?$/', "@{$width}w", $base->get('basename'), 1);
$derivative->setImagePrettyName($basename);
$ratio = $base->get('width') / $width;
$height = $derivative->get('height') / $ratio;
$derivative->resize($width, $height);
$derivative->set('width', $width);
$derivative->set('height', $height);
$this->addAlternative($ratio, $derivative);
}
}
return $this;
}
/**
* Clear out the alternatives.
*/
public function clearAlternatives()
{
$this->alternatives = [];
}
/**
* Sets or gets the quality of the image
*
* @param int|null $quality 0-100 quality
* @return int|$this
*/
public function quality($quality = null)
{
if ($quality) {
if (!$this->image) {
$this->image();
}
$this->quality = $quality;
return $this;
}
return $this->quality;
}
/**
* Sets image output format.
*
* @param string $format
* @return $this
*/
public function format($format)
{
if (!$this->image) {
$this->image();
}
$this->format = $format;
return $this;
}
/**
* Set or get sizes parameter for srcset media action
*
* @param string|null $sizes
* @return string
*/
public function sizes($sizes = null)
{
if ($sizes) {
$this->sizes = $sizes;
return $this;
}
return empty($this->sizes) ? '100vw' : $this->sizes;
}
/**
* Allows to set the width attribute from Markdown or Twig
* Examples: 
* 
* 
* 
* {{ page.media['myimg.png'].width().height().html }}
* {{ page.media['myimg.png'].resize(100,200).width(100).height(200).html }}
*
* @param string|int $value A value or 'auto' or empty to use the width of the image
* @return $this
*/
public function width($value = 'auto')
{
if (!$value || $value === 'auto') {
$this->attributes['width'] = $this->get('width');
} else {
$this->attributes['width'] = $value;
}
return $this;
}
/**
* Allows to set the height attribute from Markdown or Twig
* Examples: 
* 
* 
* 
* {{ page.media['myimg.png'].width().height().html }}
* {{ page.media['myimg.png'].resize(100,200).width(100).height(200).html }}
*
* @param string|int $value A value or 'auto' or empty to use the height of the image
* @return $this
*/
public function height($value = 'auto')
{
if (!$value || $value === 'auto') {
$this->attributes['height'] = $this->get('height');
} else {
$this->attributes['height'] = $value;
}
return $this;
}
/**
* Filter image by using user defined filter parameters.
*
* @param string $filter Filter to be used.
* @return $this
*/
public function filter($filter = 'image.filters.default')
{
$filters = (array) $this->get($filter, []);
foreach ($filters as $params) {
$params = (array) $params;
$method = array_shift($params);
$this->__call($method, $params);
}
return $this;
}
/**
* Return the image higher quality version
*
* @return ImageMediaInterface|$this the alternative version with higher quality
*/
public function higherQualityAlternative()
{
if ($this->alternatives) {
/** @var ImageMedium $max */
$max = reset($this->alternatives);
/** @var ImageMedium $alternative */
foreach ($this->alternatives as $alternative) {
if ($alternative->quality() > $max->quality()) {
$max = $alternative;
}
}
return $max;
}
return $this;
}
/**
* Gets medium image, resets image manipulation operations.
*
* @return $this
*/
protected function image()
{
$locator = Grav::instance()['locator'];
// Use existing cache folder or if it doesn't exist, create it.
$cacheDir = $locator->findResource('cache://images', true) ?: $locator->findResource('cache://images', true, true);
// Make sure we free previous image.
unset($this->image);
/** @var MediaCollectionInterface $media */
$media = $this->get('media');
if ($media && method_exists($media, 'getImageFileObject')) {
$this->image = $media->getImageFileObject($this);
} else {
$this->image = ImageFile::open($this->get('filepath'));
}
$this->image
->setCacheDir($cacheDir)
->setActualCacheDir($cacheDir)
->setPrettyName($this->getImagePrettyName());
// Fix orientation if enabled
$config = Grav::instance()['config'];
if ($config->get('system.images.auto_fix_orientation', false) &&
extension_loaded('exif') && function_exists('exif_read_data')) {
$this->image->fixOrientation();
}
// 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);
$this->watermark = $config->get('system.images.watermark.watermark_all', false);
return $this;
}
/**
* Save the image with cache.
*
* @return string
*/
protected function saveImage()
{
if (!$this->image) {
return parent::path(false);
}
$this->filter();
if (isset($this->result)) {
return $this->result;
}
if ($this->format === 'guess') {
$extension = strtolower($this->get('extension'));
$this->format($extension);
}
if (!$this->debug_watermarked && $this->get('debug')) {
$ratio = $this->get('ratio');
if (!$ratio) {
$ratio = 1;
}
$locator = Grav::instance()['locator'];
$overlay = $locator->findResource("system://assets/responsive-overlays/{$ratio}x.png") ?: $locator->findResource('system://assets/responsive-overlays/unknown.png');
$this->image->merge(ImageFile::open($overlay));
}
if ($this->watermark) {
$this->watermark();
}
return $this->image->cacheFile($this->format, $this->quality, false, [$this->get('width'), $this->get('height'), $this->get('modified')]);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Media/Traits/MediaObjectTrait.php | system/src/Grav/Common/Media/Traits/MediaObjectTrait.php | <?php
/**
* @package Grav\Common\Media
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Media\Traits;
use Grav\Common\Data\Data;
use Grav\Common\Media\Interfaces\MediaFileInterface;
use Grav\Common\Media\Interfaces\MediaLinkInterface;
use Grav\Common\Media\Interfaces\MediaObjectInterface;
use Grav\Common\Page\Medium\ThumbnailImageMedium;
use Grav\Common\Utils;
use function count;
use function func_get_args;
use function in_array;
use function is_array;
use function is_string;
/**
* Class Medium
* @package Grav\Common\Page\Medium
*
* @property string $mime
*/
trait MediaObjectTrait
{
/** @var string */
protected $mode = 'source';
/** @var MediaObjectInterface|null */
protected $_thumbnail;
/** @var array */
protected $thumbnailTypes = ['page', 'default'];
/** @var string|null */
protected $thumbnailType;
/** @var MediaObjectInterface[] */
protected $alternatives = [];
/** @var array */
protected $attributes = [];
/** @var array */
protected $styleAttributes = [];
/** @var array */
protected $metadata = [];
/** @var array */
protected $medium_querystring = [];
/** @var string */
protected $timestamp;
/**
* Create a copy of this media object
*
* @return static
*/
public function copy()
{
return clone $this;
}
/**
* Return just metadata from the Medium object
*
* @return Data
*/
public function meta()
{
return new Data($this->getItems());
}
/**
* Set querystring to file modification timestamp (or value provided as a parameter).
*
* @param string|int|null $timestamp
* @return $this
*/
public function setTimestamp($timestamp = null)
{
if (null !== $timestamp) {
$this->timestamp = (string)($timestamp);
} elseif ($this instanceof MediaFileInterface) {
$this->timestamp = (string)$this->modified();
} else {
$this->timestamp = '';
}
return $this;
}
/**
* Returns an array containing just the metadata
*
* @return array
*/
public function metadata()
{
return $this->metadata;
}
/**
* Add meta file for the medium.
*
* @param string $filepath
*/
abstract public function addMetaFile($filepath);
/**
* Add alternative Medium to this Medium.
*
* @param int|float $ratio
* @param MediaObjectInterface $alternative
*/
public function addAlternative($ratio, MediaObjectInterface $alternative)
{
if (!is_numeric($ratio) || $ratio === 0) {
return;
}
$alternative->set('ratio', $ratio);
$width = $alternative->get('width', 0);
$this->alternatives[$width] = $alternative;
}
/**
* @param bool $withDerived
* @return array
*/
public function getAlternatives(bool $withDerived = true): array
{
$alternatives = [];
foreach ($this->alternatives + [$this->get('width', 0) => $this] as $size => $alternative) {
if ($withDerived || $alternative->filename === Utils::basename($alternative->filepath)) {
$alternatives[$size] = $alternative;
}
}
ksort($alternatives, SORT_NUMERIC);
return $alternatives;
}
/**
* Return string representation of the object (html).
*
* @return string
*/
#[\ReturnTypeWillChange]
abstract public function __toString();
/**
* Get/set querystring for the file's url
*
* @param string|null $querystring
* @param bool $withQuestionmark
* @return string
*/
public function querystring($querystring = null, $withQuestionmark = true)
{
if (null !== $querystring) {
$this->medium_querystring[] = ltrim($querystring, '?&');
foreach ($this->alternatives as $alt) {
$alt->querystring($querystring, $withQuestionmark);
}
}
if (empty($this->medium_querystring)) {
return '';
}
// join the strings
$querystring = implode('&', $this->medium_querystring);
// explode all strings
$query_parts = explode('&', $querystring);
// Join them again now ensure the elements are unique
$querystring = implode('&', array_unique($query_parts));
return $withQuestionmark ? ('?' . $querystring) : $querystring;
}
/**
* Get the URL with full querystring
*
* @param string $url
* @return string
*/
public function urlQuerystring($url)
{
$querystring = $this->querystring();
if (isset($this->timestamp) && !Utils::contains($querystring, $this->timestamp)) {
$querystring = empty($querystring) ? ('?' . $this->timestamp) : ($querystring . '&' . $this->timestamp);
}
return ltrim($url . $querystring . $this->urlHash(), '/');
}
/**
* Get/set hash for the file's url
*
* @param string|null $hash
* @param bool $withHash
* @return string
*/
public function urlHash($hash = null, $withHash = true)
{
if ($hash) {
$this->set('urlHash', ltrim($hash, '#'));
}
$hash = $this->get('urlHash', '');
return $withHash && !empty($hash) ? '#' . $hash : $hash;
}
/**
* 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)
{
$attributes = $this->attributes;
$items = $this->getItems();
$style = '';
foreach ($this->styleAttributes as $key => $value) {
if (is_numeric($key)) { // Special case for inline style attributes, refer to style() method
$style .= $value;
} else {
$style .= $key . ': ' . $value . ';';
}
}
if ($style) {
$attributes['style'] = $style;
}
if (empty($attributes['title'])) {
if (!empty($title)) {
$attributes['title'] = $title;
} elseif (!empty($items['title'])) {
$attributes['title'] = $items['title'];
}
}
if (empty($attributes['alt'])) {
if (!empty($alt)) {
$attributes['alt'] = $alt;
} elseif (!empty($items['alt'])) {
$attributes['alt'] = $items['alt'];
} elseif (!empty($items['alt_text'])) {
$attributes['alt'] = $items['alt_text'];
} else {
$attributes['alt'] = '';
}
}
if (empty($attributes['class'])) {
if (!empty($class)) {
$attributes['class'] = $class;
} elseif (!empty($items['class'])) {
$attributes['class'] = $items['class'];
}
}
if (empty($attributes['id'])) {
if (!empty($id)) {
$attributes['id'] = $id;
} elseif (!empty($items['id'])) {
$attributes['id'] = $items['id'];
}
}
switch ($this->mode) {
case 'text':
$element = $this->textParsedownElement($attributes, false);
break;
case 'thumbnail':
$thumbnail = $this->getThumbnail();
$element = $thumbnail ? $thumbnail->sourceParsedownElement($attributes, false) : [];
break;
case 'source':
$element = $this->sourceParsedownElement($attributes, false);
break;
default:
$element = [];
}
if ($reset) {
$this->reset();
}
$this->display('source');
return $element;
}
/**
* Reset medium.
*
* @return $this
*/
public function reset()
{
$this->attributes = [];
return $this;
}
/**
* Add custom attribute to medium.
*
* @param string $attribute
* @param string $value
* @return $this
*/
public function attribute($attribute = null, $value = '')
{
if (!empty($attribute)) {
$this->attributes[$attribute] = $value;
}
return $this;
}
/**
* Switch display mode.
*
* @param string $mode
*
* @return MediaObjectInterface|null
*/
public function display($mode = 'source')
{
if ($this->mode === $mode) {
return $this;
}
$this->mode = $mode;
if ($mode === 'thumbnail') {
$thumbnail = $this->getThumbnail();
return $thumbnail ? $thumbnail->reset() : null;
}
return $this->reset();
}
/**
* Helper method to determine if this media item has a thumbnail or not
*
* @param string $type;
* @return bool
*/
public function thumbnailExists($type = 'page')
{
$thumbs = $this->get('thumbnails');
return isset($thumbs[$type]);
}
/**
* Switch thumbnail.
*
* @param string $type
* @return $this
*/
public function thumbnail($type = 'auto')
{
if ($type !== 'auto' && !in_array($type, $this->thumbnailTypes, true)) {
return $this;
}
if ($this->thumbnailType !== $type) {
$this->_thumbnail = null;
}
$this->thumbnailType = $type;
return $this;
}
/**
* Return URL to file.
*
* @param bool $reset
* @return string
*/
abstract public function url($reset = true);
/**
* Turn the current Medium into a Link
*
* @param bool $reset
* @param array $attributes
* @return MediaLinkInterface
*/
public function link($reset = true, array $attributes = [])
{
if ($this->mode !== 'source') {
$this->display('source');
}
foreach ($this->attributes as $key => $value) {
empty($attributes['data-' . $key]) && $attributes['data-' . $key] = $value;
}
empty($attributes['href']) && $attributes['href'] = $this->url();
return $this->createLink($attributes);
}
/**
* Turn the current Medium into a Link with lightbox enabled
*
* @param int|null $width
* @param int|null $height
* @param bool $reset
* @return MediaLinkInterface
*/
public function lightbox($width = null, $height = null, $reset = true)
{
$attributes = ['rel' => 'lightbox'];
if ($width && $height) {
$attributes['data-width'] = $width;
$attributes['data-height'] = $height;
}
return $this->link($reset, $attributes);
}
/**
* Add a class to the element from Markdown or Twig
* Example:  or 
*
* @return $this
*/
public function classes()
{
$classes = func_get_args();
if (!empty($classes)) {
$this->attributes['class'] = implode(',', $classes);
}
return $this;
}
/**
* Add an id to the element from Markdown or Twig
* Example: 
*
* @param string $id
* @return $this
*/
public function id($id)
{
if (is_string($id)) {
$this->attributes['id'] = trim($id);
}
return $this;
}
/**
* Allows to add an inline style attribute from Markdown or Twig
* Example: 
*
* @param string $style
* @return $this
*/
public function style($style)
{
$this->styleAttributes[] = rtrim($style, ';') . ';';
return $this;
}
/**
* Allow any action to be called on this medium from twig or markdown
*
* @param string $method
* @param array $args
* @return $this
*/
#[\ReturnTypeWillChange]
public function __call($method, $args)
{
$count = count($args);
if ($count > 1 || ($count === 1 && !empty($args[0]))) {
$method .= '=' . implode(',', array_map(static function ($a) {
if (is_array($a)) {
$a = '[' . implode(',', $a) . ']';
}
return rawurlencode($a);
}, $args));
}
if (!empty($method)) {
$this->querystring($this->querystring(null, false) . '&' . $method);
}
return $this;
}
/**
* Parsedown element for source display mode
*
* @param array $attributes
* @param bool $reset
* @return array
*/
protected function sourceParsedownElement(array $attributes, $reset = true)
{
return $this->textParsedownElement($attributes, $reset);
}
/**
* Parsedown element for text display mode
*
* @param array $attributes
* @param bool $reset
* @return array
*/
protected function textParsedownElement(array $attributes, $reset = true)
{
if ($reset) {
$this->reset();
}
$text = $attributes['title'] ?? '';
if ($text === '') {
$text = $attributes['alt'] ?? '';
if ($text === '') {
$text = $this->get('filename');
}
}
return [
'name' => 'p',
'attributes' => $attributes,
'text' => $text
];
}
/**
* Get the thumbnail Medium object
*
* @return ThumbnailImageMedium|null
*/
protected function getThumbnail()
{
if (null === $this->_thumbnail) {
$types = $this->thumbnailTypes;
if ($this->thumbnailType !== 'auto') {
array_unshift($types, $this->thumbnailType);
}
foreach ($types as $type) {
$thumb = $this->get("thumbnails.{$type}", false);
if ($thumb) {
$image = $thumb instanceof ThumbnailImageMedium ? $thumb : $this->createThumbnail($thumb);
if($image) {
$image->parent = $this;
$this->_thumbnail = $image;
}
break;
}
}
}
return $this->_thumbnail;
}
/**
* 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.
*/
abstract 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
*/
abstract public function set($name, $value, $separator = null);
/**
* @param string $thumb
*/
abstract protected function createThumbnail($thumb);
/**
* @param array $attributes
* @return MediaLinkInterface
*/
abstract protected function createLink(array $attributes);
/**
* @return array
*/
abstract protected function getItems(): array;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Media/Traits/MediaFileTrait.php | system/src/Grav/Common/Media/Traits/MediaFileTrait.php | <?php
/**
* @package Grav\Common\Media
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Media\Traits;
use Grav\Common\Grav;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
/**
* Trait MediaFileTrait
* @package Grav\Common\Media\Traits
*/
trait MediaFileTrait
{
/**
* Check if this medium exists or not
*
* @return bool
*/
public function exists()
{
$path = $this->path(false);
return file_exists($path);
}
/**
* Get file modification time for the medium.
*
* @return int|null
*/
public function modified()
{
$path = $this->path(false);
if (!file_exists($path)) {
return null;
}
return filemtime($path) ?: null;
}
/**
* Get size of the medium.
*
* @return int
*/
public function size()
{
$path = $this->path(false);
if (!file_exists($path)) {
return 0;
}
return filesize($path) ?: 0;
}
/**
* Return PATH to file.
*
* @param bool $reset
* @return string path to file
*/
public function path($reset = true)
{
if ($reset) {
$this->reset();
}
return $this->get('url') ?? $this->get('filepath');
}
/**
* Return the relative path to file
*
* @param bool $reset
* @return string
*/
public function relativePath($reset = true)
{
if ($reset) {
$this->reset();
}
$path = $this->path(false);
$output = preg_replace('|^' . preg_quote(GRAV_ROOT, '|') . '|', '', $path) ?: $path;
/** @var UniformResourceLocator $locator */
$locator = $this->getGrav()['locator'];
if ($locator->isStream($output)) {
$output = (string)($locator->findResource($output, false) ?: $locator->findResource($output, false, true));
}
return $output;
}
/**
* Return URL to file.
*
* @param bool $reset
* @return string
*/
public function url($reset = true)
{
$url = $this->get('url');
if ($url) {
return $url;
}
$path = $this->relativePath($reset);
return trim($this->getGrav()['base_url'] . '/' . $this->urlQuerystring($path), '\\');
}
/**
* Get the URL with full querystring
*
* @param string $url
* @return string
*/
abstract public function urlQuerystring($url);
/**
* Reset medium.
*
* @return $this
*/
abstract public function reset();
/**
* @return Grav
*/
abstract protected function getGrav(): Grav;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Media/Traits/MediaTrait.php | system/src/Grav/Common/Media/Traits/MediaTrait.php | <?php
/**
* @package Grav\Common\Media
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Media\Traits;
use Grav\Common\Cache;
use Grav\Common\Grav;
use Grav\Common\Media\Interfaces\MediaCollectionInterface;
use Grav\Common\Page\Media;
use Psr\SimpleCache\CacheInterface;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use function strlen;
/**
* Trait MediaTrait
* @package Grav\Common\Media\Traits
*/
trait MediaTrait
{
/** @var MediaCollectionInterface|null */
protected $media;
/** @var bool */
protected $_loadMedia = true;
/**
* Get filesystem path to the associated media.
*
* @return string|null
*/
abstract public function getMediaFolder();
/**
* Get display order for the associated media.
*
* @return array Empty array means default ordering.
*/
public function getMediaOrder()
{
return [];
}
/**
* Get URI ot the associated media. Method will return null if path isn't URI.
*
* @return string|null
*/
public function getMediaUri()
{
$folder = $this->getMediaFolder();
if (!$folder) {
return null;
}
if (strpos($folder, '://')) {
return $folder;
}
/** @var UniformResourceLocator $locator */
$locator = Grav::instance()['locator'];
$user = $locator->findResource('user://');
if (strpos($folder, $user) === 0) {
return 'user://' . substr($folder, strlen($user)+1);
}
return null;
}
/**
* Gets the associated media collection.
*
* @return MediaCollectionInterface|Media Representation of associated media.
*/
public function getMedia()
{
$media = $this->media;
if (null === $media) {
$cache = $this->getMediaCache();
$cacheKey = md5('media' . $this->getCacheKey());
// Use cached media if possible.
$media = $cache->get($cacheKey);
if (!$media instanceof MediaCollectionInterface) {
$media = new Media($this->getMediaFolder(), $this->getMediaOrder(), $this->_loadMedia);
$cache->set($cacheKey, $media);
}
$this->media = $media;
}
return $media;
}
/**
* Sets the associated media collection.
*
* @param MediaCollectionInterface|Media $media Representation of associated media.
* @return $this
*/
protected function setMedia(MediaCollectionInterface $media)
{
$cache = $this->getMediaCache();
$cacheKey = md5('media' . $this->getCacheKey());
$cache->set($cacheKey, $media);
$this->media = $media;
return $this;
}
/**
* @return void
*/
protected function freeMedia()
{
$this->media = null;
}
/**
* Clear media cache.
*
* @return void
*/
protected function clearMediaCache()
{
$cache = $this->getMediaCache();
$cacheKey = md5('media' . $this->getCacheKey());
$cache->delete($cacheKey);
$this->freeMedia();
}
/**
* @return CacheInterface
*/
protected function getMediaCache()
{
/** @var Cache $cache */
$cache = Grav::instance()['cache'];
return $cache->getSimpleCache();
}
/**
* @return string
*/
abstract protected function getCacheKey(): string;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Media/Traits/StaticResizeTrait.php | system/src/Grav/Common/Media/Traits/StaticResizeTrait.php | <?php
/**
* @package Grav\Common\Media
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Media\Traits;
/**
* Trait StaticResizeTrait
* @package Grav\Common\Media\Traits
*/
trait StaticResizeTrait
{
/**
* Resize media by setting attributes
*
* @param int|null $width
* @param int|null $height
* @return $this
*/
public function resize($width = null, $height = null)
{
if ($width) {
$this->styleAttributes['width'] = $width . 'px';
} else {
unset($this->styleAttributes['width']);
}
if ($height) {
$this->styleAttributes['height'] = $height . 'px';
} else {
unset($this->styleAttributes['height']);
}
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/Media/Traits/MediaPlayerTrait.php | system/src/Grav/Common/Media/Traits/MediaPlayerTrait.php | <?php
/**
* @package Grav\Common\Media
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Media\Traits;
use function in_array;
/**
* Class implements audio object interface.
*/
trait MediaPlayerTrait
{
/**
* Allows to set or remove the HTML5 default controls
*
* @param bool $status
* @return $this
*/
public function controls($status = true)
{
if ($status) {
$this->attributes['controls'] = 'controls';
} else {
unset($this->attributes['controls']);
}
return $this;
}
/**
* Allows to set the loop attribute
*
* @param bool $status
* @return $this
*/
public function loop($status = false)
{
if ($status) {
$this->attributes['loop'] = 'loop';
} else {
unset($this->attributes['loop']);
}
return $this;
}
/**
* Allows to set the autoplay attribute
*
* @param bool $status
* @return $this
*/
public function autoplay($status = false)
{
if ($status) {
$this->attributes['autoplay'] = 'autoplay';
} else {
unset($this->attributes['autoplay']);
}
return $this;
}
/**
* Allows to set the muted attribute
*
* @param bool $status
* @return $this
*/
public function muted($status = false)
{
if ($status) {
$this->attributes['muted'] = 'muted';
} else {
unset($this->attributes['muted']);
}
return $this;
}
/**
* Allows to set the preload behaviour
*
* @param string|null $preload
* @return $this
*/
public function preload($preload = null)
{
$validPreloadAttrs = ['auto', 'metadata', 'none'];
if (null === $preload) {
unset($this->attributes['preload']);
} elseif (in_array($preload, $validPreloadAttrs, true)) {
$this->attributes['preload'] = $preload;
}
return $this;
}
/**
* Reset player.
*/
public function resetPlayer()
{
$this->attributes['controls'] = 'controls';
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Media/Traits/MediaUploadTrait.php | system/src/Grav/Common/Media/Traits/MediaUploadTrait.php | <?php
/**
* @package Grav\Common\Media
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Media\Traits;
use Exception;
use Grav\Common\Config\Config;
use Grav\Common\Filesystem\Folder;
use Grav\Common\Grav;
use Grav\Common\Language\Language;
use Grav\Common\Page\Medium\Medium;
use Grav\Common\Page\Medium\MediumFactory;
use Grav\Common\Security;
use Grav\Common\Utils;
use Grav\Framework\Filesystem\Filesystem;
use Grav\Framework\Form\FormFlashFile;
use Grav\Framework\Mime\MimeTypes;
use Psr\Http\Message\UploadedFileInterface;
use RocketTheme\Toolbox\File\YamlFile;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use RuntimeException;
use function dirname;
use function in_array;
/**
* Implements media upload and delete functionality.
*/
trait MediaUploadTrait
{
/** @var array */
private $_upload_defaults = [
'self' => true, // Whether path is in the media collection path itself.
'avoid_overwriting' => false, // Do not override existing files (adds datetime postfix if conflict).
'random_name' => false, // True if name needs to be randomized.
'accept' => ['image/*'], // Accepted mime types or file extensions.
'limit' => 10, // Maximum number of files.
'filesize' => null, // Maximum filesize in MB.
'destination' => null // Destination path, if empty, exception is thrown.
];
/**
* Create Medium from an uploaded file.
*
* @param UploadedFileInterface $uploadedFile
* @param array $params
* @return Medium|null
*/
public function createFromUploadedFile(UploadedFileInterface $uploadedFile, array $params = [])
{
return MediumFactory::fromUploadedFile($uploadedFile, $params);
}
/**
* Checks that uploaded file meets the requirements. Returns new filename.
*
* @example
* $filename = null; // Override filename if needed (ignored if randomizing filenames).
* $settings = ['destination' => 'user://pages/media']; // Settings from the form field.
* $filename = $media->checkUploadedFile($uploadedFile, $filename, $settings);
* $media->copyUploadedFile($uploadedFile, $filename);
*
* @param UploadedFileInterface $uploadedFile
* @param string|null $filename
* @param array|null $settings
* @return string
* @throws RuntimeException
*/
public function checkUploadedFile(UploadedFileInterface $uploadedFile, string $filename = null, array $settings = null): string
{
// Check if there is an upload error.
switch ($uploadedFile->getError()) {
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
throw new RuntimeException($this->translate('PLUGIN_ADMIN.EXCEEDED_FILESIZE_LIMIT'), 400);
case UPLOAD_ERR_PARTIAL:
case UPLOAD_ERR_NO_FILE:
if (!$uploadedFile instanceof FormFlashFile) {
throw new RuntimeException($this->translate('PLUGIN_ADMIN.NO_FILES_SENT'), 400);
}
break;
case UPLOAD_ERR_NO_TMP_DIR:
throw new RuntimeException($this->translate('PLUGIN_ADMIN.UPLOAD_ERR_NO_TMP_DIR'), 400);
case UPLOAD_ERR_CANT_WRITE:
case UPLOAD_ERR_EXTENSION:
default:
throw new RuntimeException($this->translate('PLUGIN_ADMIN.UNKNOWN_ERRORS'), 400);
}
$metadata = [
'filename' => $uploadedFile->getClientFilename(),
'mime' => $uploadedFile->getClientMediaType(),
'size' => $uploadedFile->getSize(),
];
if ($uploadedFile instanceof FormFlashFile) {
$uploadedFile->checkXss();
}
return $this->checkFileMetadata($metadata, $filename, $settings);
}
/**
* Checks that file metadata meets the requirements. Returns new filename.
*
* @param array $metadata
* @param array|null $settings
* @return string
* @throws RuntimeException
*/
public function checkFileMetadata(array $metadata, string $filename = null, array $settings = null): string
{
// Add the defaults to the settings.
$settings = $this->getUploadSettings($settings);
// Destination is always needed (but it can be set in defaults).
$self = $settings['self'] ?? false;
if (!isset($settings['destination']) && $self === false) {
throw new RuntimeException($this->translate('PLUGIN_ADMIN.DESTINATION_NOT_SPECIFIED'), 400);
}
if (null === $filename) {
// If no filename is given, use the filename from the uploaded file (path is not allowed).
$folder = '';
$filename = $metadata['filename'] ?? '';
} else {
// If caller sets the filename, we will accept any custom path.
$folder = dirname($filename);
if ($folder === '.') {
$folder = '';
}
$filename = Utils::basename($filename);
}
$extension = Utils::pathinfo($filename, PATHINFO_EXTENSION);
// Decide which filename to use.
if ($settings['random_name']) {
// Generate random filename if asked for.
$filename = mb_strtolower(Utils::generateRandomString(15) . '.' . $extension);
}
// Handle conflicting filename if needed.
if ($settings['avoid_overwriting']) {
$destination = $settings['destination'];
if ($destination && $this->fileExists($filename, $destination)) {
$filename = date('YmdHis') . '-' . $filename;
}
}
$filepath = $folder . $filename;
// Check if the filename is allowed.
if (!Utils::checkFilename($filepath)) {
throw new RuntimeException(
sprintf($this->translate('PLUGIN_ADMIN.FILEUPLOAD_UNABLE_TO_UPLOAD'), $filepath, $this->translate('PLUGIN_ADMIN.BAD_FILENAME'))
);
}
// Check if the file extension is allowed.
$extension = mb_strtolower($extension);
if (!$extension || !$this->getConfig()->get("media.types.{$extension}")) {
// Not a supported type.
throw new RuntimeException($this->translate('PLUGIN_ADMIN.UNSUPPORTED_FILE_TYPE') . ': ' . $extension, 400);
}
// Calculate maximum file size (from MB).
$filesize = $settings['filesize'];
if ($filesize) {
$max_filesize = $filesize * 1048576;
if ($metadata['size'] > $max_filesize) {
// TODO: use own language string
throw new RuntimeException($this->translate('PLUGIN_ADMIN.EXCEEDED_GRAV_FILESIZE_LIMIT'), 400);
}
} elseif (null === $filesize) {
// Check size against the Grav upload limit.
$grav_limit = Utils::getUploadLimit();
if ($grav_limit > 0 && $metadata['size'] > $grav_limit) {
throw new RuntimeException($this->translate('PLUGIN_ADMIN.EXCEEDED_GRAV_FILESIZE_LIMIT'), 400);
}
}
$grav = Grav::instance();
/** @var MimeTypes $mimeChecker */
$mimeChecker = $grav['mime'];
// Handle Accepted file types. Accept can only be mime types (image/png | image/*) or file extensions (.pdf | .jpg)
// Do not trust mime type sent by the browser.
$mime = $metadata['mime'] ?? $mimeChecker->getMimeType($extension);
$validExtensions = $mimeChecker->getExtensions($mime);
if (!in_array($extension, $validExtensions, true)) {
throw new RuntimeException('The mime type does not match to file extension', 400);
}
$accepted = false;
$errors = [];
foreach ((array)$settings['accept'] as $type) {
// Force acceptance of any file when star notation
if ($type === '*') {
$accepted = true;
break;
}
$isMime = strstr($type, '/');
$find = str_replace(['.', '*', '+'], ['\.', '.*', '\+'], $type);
if ($isMime) {
$match = preg_match('#' . $find . '$#', $mime);
if (!$match) {
// TODO: translate
$errors[] = 'The MIME type "' . $mime . '" for the file "' . $filepath . '" is not an accepted.';
} else {
$accepted = true;
break;
}
} else {
$match = preg_match('#' . $find . '$#', $filename);
if (!$match) {
// TODO: translate
$errors[] = 'The File Extension for the file "' . $filepath . '" is not an accepted.';
} else {
$accepted = true;
break;
}
}
}
if (!$accepted) {
throw new RuntimeException(implode('<br />', $errors), 400);
}
return $filepath;
}
/**
* Copy uploaded file to the media collection.
*
* WARNING: Always check uploaded file before copying it!
*
* @example
* $settings = ['destination' => 'user://pages/media']; // Settings from the form field.
* $filename = $media->checkUploadedFile($uploadedFile, $filename, $settings);
* $media->copyUploadedFile($uploadedFile, $filename, $settings);
*
* @param UploadedFileInterface $uploadedFile
* @param string $filename
* @param array|null $settings
* @return void
* @throws RuntimeException
*/
public function copyUploadedFile(UploadedFileInterface $uploadedFile, string $filename, array $settings = null): void
{
// Add the defaults to the settings.
$settings = $this->getUploadSettings($settings);
$path = $settings['destination'] ?? $this->getPath();
if (!$path || !$filename) {
throw new RuntimeException($this->translate('PLUGIN_ADMIN.FAILED_TO_MOVE_UPLOADED_FILE'), 400);
}
/** @var UniformResourceLocator $locator */
$locator = $this->getGrav()['locator'];
try {
// Clear locator cache to make sure we have up to date information from the filesystem.
$locator->clearCache();
$this->clearCache();
$filesystem = Filesystem::getInstance(false);
// Calculate path without the retina scaling factor.
$basename = $filesystem->basename($filename);
$pathname = $filesystem->pathname($filename);
// Get name for the uploaded file.
[$base, $ext,,] = $this->getFileParts($basename);
$name = "{$pathname}{$base}.{$ext}";
// Upload file.
if ($uploadedFile instanceof FormFlashFile) {
// FormFlashFile needs some additional logic.
if ($uploadedFile->getError() === \UPLOAD_ERR_OK) {
// Move uploaded file.
$this->doMoveUploadedFile($uploadedFile, $filename, $path);
} elseif (strpos($filename, 'original/') === 0 && !$this->fileExists($filename, $path) && $this->fileExists($basename, $path)) {
// Original image support: override original image if it's the same as the uploaded image.
$this->doCopy($basename, $filename, $path);
}
// FormFlashFile may also contain metadata.
$metadata = $uploadedFile->getMetaData();
if ($metadata) {
// TODO: This overrides metadata if used with multiple retina image sizes.
$this->doSaveMetadata(['upload' => $metadata], $name, $path);
}
} else {
// Not a FormFlashFile.
$this->doMoveUploadedFile($uploadedFile, $filename, $path);
}
// Post-processing: Special content sanitization for SVG.
$mime = Utils::getMimeByFilename($filename);
if (Utils::contains($mime, 'svg', false)) {
$this->doSanitizeSvg($filename, $path);
}
// Add the new file into the media.
// TODO: This overrides existing media sizes if used with multiple retina image sizes.
$this->doAddUploadedMedium($name, $filename, $path);
} catch (Exception $e) {
throw new RuntimeException($this->translate('PLUGIN_ADMIN.FAILED_TO_MOVE_UPLOADED_FILE') . $e->getMessage(), 400);
} finally {
// Finally clear media cache.
$locator->clearCache();
$this->clearCache();
}
}
/**
* Delete real file from the media collection.
*
* @param string $filename
* @param array|null $settings
* @return void
* @throws RuntimeException
*/
public function deleteFile(string $filename, array $settings = null): void
{
// Add the defaults to the settings.
$settings = $this->getUploadSettings($settings);
$filesystem = Filesystem::getInstance(false);
// First check for allowed filename.
$basename = $filesystem->basename($filename);
if (!Utils::checkFilename($basename)) {
throw new RuntimeException($this->translate('PLUGIN_ADMIN.FILE_COULD_NOT_BE_DELETED') . ": {$this->translate('PLUGIN_ADMIN.BAD_FILENAME')}: " . $filename, 400);
}
$path = $settings['destination'] ?? $this->getPath();
if (!$path) {
return;
}
/** @var UniformResourceLocator $locator */
$locator = $this->getGrav()['locator'];
$locator->clearCache();
$pathname = $filesystem->pathname($filename);
// Get base name of the file.
[$base, $ext,,] = $this->getFileParts($basename);
$name = "{$pathname}{$base}.{$ext}";
// Remove file and all all the associated metadata.
$this->doRemove($name, $path);
// Finally clear media cache.
$locator->clearCache();
$this->clearCache();
}
/**
* Rename file inside the media collection.
*
* @param string $from
* @param string $to
* @param array|null $settings
*/
public function renameFile(string $from, string $to, array $settings = null): void
{
// Add the defaults to the settings.
$settings = $this->getUploadSettings($settings);
$filesystem = Filesystem::getInstance(false);
$path = $settings['destination'] ?? $this->getPath();
if (!$path) {
// TODO: translate error message
throw new RuntimeException('Failed to rename file: Bad destination', 400);
}
/** @var UniformResourceLocator $locator */
$locator = $this->getGrav()['locator'];
$locator->clearCache();
// Get base name of the file.
$pathname = $filesystem->pathname($from);
// Remove @2x, @3x and .meta.yaml
[$base, $ext,,] = $this->getFileParts($filesystem->basename($from));
$from = "{$pathname}{$base}.{$ext}";
[$base, $ext,,] = $this->getFileParts($filesystem->basename($to));
$to = "{$pathname}{$base}.{$ext}";
$this->doRename($from, $to, $path);
// Finally clear media cache.
$locator->clearCache();
$this->clearCache();
}
/**
* Internal logic to move uploaded file.
*
* @param UploadedFileInterface $uploadedFile
* @param string $filename
* @param string $path
*/
protected function doMoveUploadedFile(UploadedFileInterface $uploadedFile, string $filename, string $path): void
{
$filepath = sprintf('%s/%s', $path, $filename);
/** @var UniformResourceLocator $locator */
$locator = $this->getGrav()['locator'];
// Do not use streams internally.
if ($locator->isStream($filepath)) {
$filepath = (string)$locator->findResource($filepath, true, true);
}
Folder::create(dirname($filepath));
$uploadedFile->moveTo($filepath);
}
/**
* Get upload settings.
*
* @param array|null $settings Form field specific settings (override).
* @return array
*/
public function getUploadSettings(?array $settings = null): array
{
return null !== $settings ? $settings + $this->_upload_defaults : $this->_upload_defaults;
}
/**
* Internal logic to copy file.
*
* @param string $src
* @param string $dst
* @param string $path
*/
protected function doCopy(string $src, string $dst, string $path): void
{
$src = sprintf('%s/%s', $path, $src);
$dst = sprintf('%s/%s', $path, $dst);
/** @var UniformResourceLocator $locator */
$locator = $this->getGrav()['locator'];
// Do not use streams internally.
if ($locator->isStream($dst)) {
$dst = (string)$locator->findResource($dst, true, true);
}
Folder::create(dirname($dst));
copy($src, $dst);
}
/**
* Internal logic to rename file.
*
* @param string $from
* @param string $to
* @param string $path
*/
protected function doRename(string $from, string $to, string $path): void
{
/** @var UniformResourceLocator $locator */
$locator = $this->getGrav()['locator'];
$fromPath = $path . '/' . $from;
if ($locator->isStream($fromPath)) {
$fromPath = $locator->findResource($fromPath, true, true);
}
if (!is_file($fromPath)) {
return;
}
$mediaPath = dirname($fromPath);
$toPath = $mediaPath . '/' . $to;
if ($locator->isStream($toPath)) {
$toPath = $locator->findResource($toPath, true, true);
}
if (is_file($toPath)) {
// TODO: translate error message
throw new RuntimeException(sprintf('File could not be renamed: %s already exists (%s)', $to, $mediaPath), 500);
}
$result = rename($fromPath, $toPath);
if (!$result) {
// TODO: translate error message
throw new RuntimeException(sprintf('File could not be renamed: %s -> %s (%s)', $from, $to, $mediaPath), 500);
}
// TODO: Add missing logic to handle retina files.
if (is_file($fromPath . '.meta.yaml')) {
$result = rename($fromPath . '.meta.yaml', $toPath . '.meta.yaml');
if (!$result) {
// TODO: translate error message
throw new RuntimeException(sprintf('Meta could not be renamed: %s -> %s (%s)', $from, $to, $mediaPath), 500);
}
}
}
/**
* Internal logic to remove file.
*
* @param string $filename
* @param string $path
*/
protected function doRemove(string $filename, string $path): void
{
$filesystem = Filesystem::getInstance(false);
/** @var UniformResourceLocator $locator */
$locator = $this->getGrav()['locator'];
// If path doesn't exist, there's nothing to do.
$pathname = $filesystem->pathname($filename);
if (!$this->fileExists($pathname, $path)) {
return;
}
$folder = $locator->isStream($path) ? (string)$locator->findResource($path, true, true) : $path;
// Remove requested media file.
if ($this->fileExists($filename, $path)) {
$result = unlink("{$folder}/{$filename}");
if (!$result) {
throw new RuntimeException($this->translate('PLUGIN_ADMIN.FILE_COULD_NOT_BE_DELETED') . ': ' . $filename, 500);
}
}
// Remove associated metadata.
$this->doRemoveMetadata($filename, $path);
// Remove associated 2x, 3x and their .meta.yaml files.
$targetPath = rtrim(sprintf('%s/%s', $folder, $pathname), '/');
$dir = scandir($targetPath, SCANDIR_SORT_NONE);
if (false === $dir) {
throw new RuntimeException($this->translate('PLUGIN_ADMIN.FILE_COULD_NOT_BE_DELETED') . ': ' . $filename, 500);
}
/** @var UniformResourceLocator $locator */
$locator = $this->getGrav()['locator'];
$basename = $filesystem->basename($filename);
$fileParts = (array)$filesystem->pathinfo($filename);
foreach ($dir as $file) {
$preg_name = preg_quote($fileParts['filename'], '`');
$preg_ext = preg_quote($fileParts['extension'] ?? '.', '`');
$preg_filename = preg_quote($basename, '`');
if (preg_match("`({$preg_name}@\d+x\.{$preg_ext}(?:\.meta\.yaml)?$|{$preg_filename}\.meta\.yaml)$`", $file)) {
$testPath = $targetPath . '/' . $file;
if ($locator->isStream($testPath)) {
$testPath = (string)$locator->findResource($testPath, true, true);
$locator->clearCache($testPath);
}
if (is_file($testPath)) {
$result = unlink($testPath);
if (!$result) {
throw new RuntimeException($this->translate('PLUGIN_ADMIN.FILE_COULD_NOT_BE_DELETED') . ': ' . $filename, 500);
}
}
}
}
$this->hide($filename);
}
/**
* @param array $metadata
* @param string $filename
* @param string $path
*/
protected function doSaveMetadata(array $metadata, string $filename, string $path): void
{
$filepath = sprintf('%s/%s', $path, $filename);
/** @var UniformResourceLocator $locator */
$locator = $this->getGrav()['locator'];
// Do not use streams internally.
if ($locator->isStream($filepath)) {
$filepath = (string)$locator->findResource($filepath, true, true);
}
$file = YamlFile::instance($filepath . '.meta.yaml');
$file->save($metadata);
}
/**
* @param string $filename
* @param string $path
*/
protected function doRemoveMetadata(string $filename, string $path): void
{
$filepath = sprintf('%s/%s', $path, $filename);
/** @var UniformResourceLocator $locator */
$locator = $this->getGrav()['locator'];
// Do not use streams internally.
if ($locator->isStream($filepath)) {
$filepath = (string)$locator->findResource($filepath, true);
if (!$filepath) {
return;
}
}
$file = YamlFile::instance($filepath . '.meta.yaml');
if ($file->exists()) {
$file->delete();
}
}
/**
* @param string $filename
* @param string $path
*/
protected function doSanitizeSvg(string $filename, string $path): void
{
$filepath = sprintf('%s/%s', $path, $filename);
/** @var UniformResourceLocator $locator */
$locator = $this->getGrav()['locator'];
// Do not use streams internally.
if ($locator->isStream($filepath)) {
$filepath = (string)$locator->findResource($filepath, true, true);
}
Security::sanitizeSVG($filepath);
}
/**
* @param string $name
* @param string $filename
* @param string $path
*/
protected function doAddUploadedMedium(string $name, string $filename, string $path): void
{
$filepath = sprintf('%s/%s', $path, $filename);
$medium = $this->createFromFile($filepath);
$realpath = $path . '/' . $name;
$this->add($realpath, $medium);
}
/**
* @param string $string
* @return string
*/
protected function translate(string $string): string
{
return $this->getLanguage()->translate($string);
}
abstract protected function getPath(): ?string;
abstract protected function getGrav(): Grav;
abstract protected function getConfig(): Config;
abstract protected function getLanguage(): Language;
abstract protected function clearCache(): void;
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Media/Traits/ImageFetchPriorityTrait.php | system/src/Grav/Common/Media/Traits/ImageFetchPriorityTrait.php | <?php
/**
* @package Grav\Common\Media
* @author Pedro Moreno https://github.com/pmoreno-rodriguez
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Media\Traits;
use Grav\Common\Grav;
/**
* Trait ImageFetchPriorityTrait
* @package Grav\Common\Media\Traits
*/
trait ImageFetchPriorityTrait
{
/**
* Allows to set the fetchpriority attribute from Markdown or Twig
*
* @param string|null $value
* @return $this
*/
public function fetchpriority($value = null)
{
if (null === $value) {
$value = Grav::instance()['config']->get('system.images.defaults.fetchpriority', 'auto');
}
// Validate the provided value (similar to loading and decoding attributes)
if ($value !== null && $value !== 'auto') {
$this->attributes['fetchpriority'] = $value;
}
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/Media/Traits/AudioMediaTrait.php | system/src/Grav/Common/Media/Traits/AudioMediaTrait.php | <?php
/**
* @package Grav\Common\Media
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Media\Traits;
/**
* Trait AudioMediaTrait
* @package Grav\Common\Media\Traits
*/
trait AudioMediaTrait
{
use StaticResizeTrait;
use MediaPlayerTrait;
/**
* Allows to set the controlsList behaviour
* Separate multiple values with a hyphen
*
* @param string $controlsList
* @return $this
*/
public function controlsList($controlsList)
{
$controlsList = str_replace('-', ' ', $controlsList);
$this->attributes['controlsList'] = $controlsList;
return $this;
}
/**
* Parsedown element for source display mode
*
* @param array $attributes
* @param bool $reset
* @return array
*/
protected function sourceParsedownElement(array $attributes, $reset = true)
{
$location = $this->url($reset);
return [
'name' => 'audio',
'rawHtml' => '<source src="' . $location . '">Your browser does not support the audio tag.',
'attributes' => $attributes
];
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Media/Traits/VideoMediaTrait.php | system/src/Grav/Common/Media/Traits/VideoMediaTrait.php | <?php
/**
* @package Grav\Common\Media
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Media\Traits;
/**
* Trait VideoMediaTrait
* @package Grav\Common\Media\Traits
*/
trait VideoMediaTrait
{
use StaticResizeTrait;
use MediaPlayerTrait;
/**
* Allows to set the video's poster image
*
* @param string $urlImage
* @return $this
*/
public function poster($urlImage)
{
$this->attributes['poster'] = $urlImage;
return $this;
}
/**
* Allows to set the playsinline attribute
*
* @param bool $status
* @return $this
*/
public function playsinline($status = false)
{
if ($status) {
$this->attributes['playsinline'] = 'playsinline';
} else {
unset($this->attributes['playsinline']);
}
return $this;
}
/**
* Parsedown element for source display mode
*
* @param array $attributes
* @param bool $reset
* @return array
*/
protected function sourceParsedownElement(array $attributes, $reset = true)
{
$location = $this->url($reset);
return [
'name' => 'video',
'rawHtml' => '<source src="' . $location . '">Your browser does not support the video tag.',
'attributes' => $attributes
];
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Media/Traits/ImageDecodingTrait.php | system/src/Grav/Common/Media/Traits/ImageDecodingTrait.php | <?php
/**
* @package Grav\Common\Media
* @author Pedro Moreno https://github.com/pmoreno-rodriguez
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Media\Traits;
use Grav\Common\Grav;
/**
* Trait ImageDecodingTrait
* @package Grav\Common\Media\Traits
*/
trait ImageDecodingTrait
{
/**
* Allows to set the decoding attribute from Markdown or Twig
*
* @param string|null $value
* @return $this
*/
public function decoding($value = null)
{
if (null === $value) {
$value = Grav::instance()['config']->get('system.images.defaults.decoding', 'auto');
}
// Validate the provided value (similar to loading)
if ($value !== null && $value !== 'auto') {
$this->attributes['decoding'] = $value;
}
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/Media/Traits/ThumbnailMediaTrait.php | system/src/Grav/Common/Media/Traits/ThumbnailMediaTrait.php | <?php
/**
* @package Grav\Common\Media
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Media\Traits;
use BadMethodCallException;
use Grav\Common\Media\Interfaces\MediaLinkInterface;
use Grav\Common\Media\Interfaces\MediaObjectInterface;
use function get_class;
use function is_callable;
/**
* Trait ThumbnailMediaTrait
* @package Grav\Common\Media\Traits
*/
trait ThumbnailMediaTrait
{
/** @var MediaObjectInterface|null */
public $parent;
/** @var bool */
public $linked = false;
/**
* Return srcset string for this Medium and its alternatives.
*
* @param bool $reset
* @return string
*/
public function srcset($reset = true)
{
return '';
}
/**
* 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)
{
return $this->bubble('parsedownElement', [$title, $alt, $class, $id, $reset]);
}
/**
* 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 $this->bubble('html', [$title, $alt, $class, $id, $reset]);
}
/**
* Switch display mode.
*
* @param string $mode
*
* @return MediaLinkInterface|MediaObjectInterface|null
*/
public function display($mode = 'source')
{
return $this->bubble('display', [$mode], false);
}
/**
* Switch thumbnail.
*
* @param string $type
*
* @return MediaLinkInterface|MediaObjectInterface
*/
public function thumbnail($type = 'auto')
{
$this->bubble('thumbnail', [$type], false);
return $this->bubble('getThumbnail', [], false);
}
/**
* Turn the current Medium into a Link
*
* @param bool $reset
* @param array $attributes
* @return MediaLinkInterface
*/
public function link($reset = true, array $attributes = [])
{
return $this->bubble('link', [$reset, $attributes], false);
}
/**
* Turn the current Medium into a Link with lightbox enabled
*
* @param int|null $width
* @param int|null $height
* @param bool $reset
* @return MediaLinkInterface
*/
public function lightbox($width = null, $height = null, $reset = true)
{
return $this->bubble('lightbox', [$width, $height, $reset], false);
}
/**
* Bubble a function call up to either the superclass function or the parent Medium instance
*
* @param string $method
* @param array $arguments
* @param bool $testLinked
* @return mixed
*/
protected function bubble($method, array $arguments = [], $testLinked = true)
{
if (!$testLinked || $this->linked) {
$parent = $this->parent;
if (null === $parent) {
return $this;
}
$closure = [$parent, $method];
if (!is_callable($closure)) {
throw new BadMethodCallException(get_class($parent) . '::' . $method . '() not found.');
}
return $closure(...$arguments);
}
return parent::{$method}(...$arguments);
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Media/Traits/ImageLoadingTrait.php | system/src/Grav/Common/Media/Traits/ImageLoadingTrait.php | <?php
/**
* @package Grav\Common\Media
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Media\Traits;
use Grav\Common\Grav;
/**
* Trait ImageLoadingTrait
* @package Grav\Common\Media\Traits
*/
trait ImageLoadingTrait
{
/**
* Allows to set the loading attribute from Markdown or Twig
*
* @param string|null $value
* @return $this
*/
public function loading($value = null)
{
if (null === $value) {
$value = Grav::instance()['config']->get('system.images.defaults.loading', 'auto');
}
if ($value && $value !== 'auto') {
$this->attributes['loading'] = $value;
}
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/Service/OutputServiceProvider.php | system/src/Grav/Common/Service/OutputServiceProvider.php | <?php
/**
* @package Grav\Common\Service
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Service;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Common\Twig\Twig;
use Pimple\Container;
use Pimple\ServiceProviderInterface;
/**
* Class OutputServiceProvider
* @package Grav\Common\Service
*/
class OutputServiceProvider implements ServiceProviderInterface
{
/**
* @param Container $container
* @return void
*/
public function register(Container $container)
{
$container['output'] = function ($c) {
/** @var Twig $twig */
$twig = $c['twig'];
/** @var PageInterface $page */
$page = $c['page'];
return $twig->processSite($page->templateFormat());
};
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Service/PagesServiceProvider.php | system/src/Grav/Common/Service/PagesServiceProvider.php | <?php
/**
* @package Grav\Common\Service
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Service;
use Grav\Common\Config\Config;
use Grav\Common\Grav;
use Grav\Common\Language\Language;
use Grav\Common\Page\Page;
use Grav\Common\Page\Pages;
use Grav\Common\Uri;
use Pimple\Container;
use Pimple\ServiceProviderInterface;
use SplFileInfo;
use function defined;
/**
* Class PagesServiceProvider
* @package Grav\Common\Service
*/
class PagesServiceProvider implements ServiceProviderInterface
{
/**
* @param Container $container
* @return void
*/
public function register(Container $container)
{
$container['pages'] = function (Grav $grav) {
return new Pages($grav);
};
if (defined('GRAV_CLI')) {
$container['page'] = static function (Grav $grav) {
$path = $grav['locator']->findResource('system://pages/notfound.md');
$page = new Page();
$page->init(new SplFileInfo($path));
$page->routable(false);
return $page;
};
return;
}
$container['page'] = static function (Grav $grav) {
/** @var Pages $pages */
$pages = $grav['pages'];
/** @var Config $config */
$config = $grav['config'];
/** @var Uri $uri */
$uri = $grav['uri'];
$path = $uri->path() ? urldecode($uri->path()) : '/'; // Don't trim to support trailing slash default routes
$page = $pages->dispatch($path);
// Redirection tests
if ($page) {
// some debugger override logic
if ($page->debugger() === false) {
$grav['debugger']->enabled(false);
}
if ($config->get('system.force_ssl')) {
$scheme = $uri->scheme(true);
if ($scheme !== 'https') {
$url = 'https://' . $uri->host() . $uri->uri();
$grav->redirect($url);
}
}
$route = $page->route();
if ($route && \in_array($uri->method(), ['GET', 'HEAD'], true)) {
$pageExtension = $page->urlExtension();
$url = $pages->route($route) . $pageExtension;
if ($uri->params()) {
if ($url === '/') { //Avoid double slash
$url = $uri->params();
} else {
$url .= $uri->params();
}
}
if ($uri->query()) {
$url .= '?' . $uri->query();
}
if ($uri->fragment()) {
$url .= '#' . $uri->fragment();
}
/** @var Language $language */
$language = $grav['language'];
$redirect_default_route = $page->header()->redirect_default_route ?? $config->get('system.pages.redirect_default_route', 0);
$redirectCode = (int) $redirect_default_route;
// Language-specific redirection scenarios
if ($language->enabled() && ($language->isLanguageInUrl() xor $language->isIncludeDefaultLanguage())) {
$grav->redirect($url, $redirectCode);
}
// Default route test and redirect
if ($redirectCode) {
$uriExtension = $uri->extension();
$uriExtension = null !== $uriExtension ? '.' . $uriExtension : '';
if ($route !== $path || ($pageExtension !== $uriExtension
&& \in_array($pageExtension, ['', '.htm', '.html'], true)
&& \in_array($uriExtension, ['', '.htm', '.html'], true))) {
$grav->redirect($url, $redirectCode);
}
}
}
}
// if page is not found, try some fallback stuff
if (!$page || !$page->routable()) {
// Try fallback URL stuff...
$page = $grav->fallbackUrl($path);
if (!$page) {
$path = $grav['locator']->findResource('system://pages/notfound.md');
$page = new Page();
$page->init(new SplFileInfo($path));
$page->routable(false);
}
}
return $page;
};
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Service/StreamsServiceProvider.php | system/src/Grav/Common/Service/StreamsServiceProvider.php | <?php
/**
* @package Grav\Common\Service
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Service;
use Grav\Common\Config\Setup;
use Pimple\Container;
use RocketTheme\Toolbox\DI\ServiceProviderInterface;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use RocketTheme\Toolbox\StreamWrapper\ReadOnlyStream;
use RocketTheme\Toolbox\StreamWrapper\Stream;
use RocketTheme\Toolbox\StreamWrapper\StreamBuilder;
/**
* Class StreamsServiceProvider
* @package Grav\Common\Service
*/
class StreamsServiceProvider implements ServiceProviderInterface
{
/**
* @param Container $container
* @return void
*/
public function register(Container $container)
{
$container['locator'] = function (Container $container) {
$locator = new UniformResourceLocator(GRAV_WEBROOT);
/** @var Setup $setup */
$setup = $container['setup'];
$setup->initializeLocator($locator);
return $locator;
};
$container['streams'] = function (Container $container) {
/** @var Setup $setup */
$setup = $container['setup'];
/** @var UniformResourceLocator $locator */
$locator = $container['locator'];
// Set locator to both streams.
Stream::setLocator($locator);
ReadOnlyStream::setLocator($locator);
return new StreamBuilder($setup->getStreams());
};
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Service/SchedulerServiceProvider.php | system/src/Grav/Common/Service/SchedulerServiceProvider.php | <?php
/**
* @package Grav\Common\Service
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Service;
use Grav\Common\Scheduler\Scheduler;
use Grav\Common\Scheduler\JobQueue;
use Grav\Common\Scheduler\JobWorker;
use Pimple\Container;
use Pimple\ServiceProviderInterface;
/**
* Class SchedulerServiceProvider
* @package Grav\Common\Service
*/
class SchedulerServiceProvider implements ServiceProviderInterface
{
/**
* @param Container $container
* @return void
*/
public function register(Container $container)
{
$container['scheduler'] = function ($c) {
$config = $c['config'];
$scheduler = new Scheduler();
// Configure modern features if enabled
$modernConfig = $config->get('scheduler.modern', []);
if ($modernConfig['enabled'] ?? false) {
// Initialize components
$queuePath = $c['locator']->findResource('user-data://scheduler/queue', true, true);
$statusPath = $c['locator']->findResource('user-data://scheduler/status.yaml', true, true);
// Set modern configuration on scheduler
$scheduler->setModernConfig($modernConfig);
// Initialize job queue if enabled
if ($modernConfig['queue']['enabled'] ?? false) {
$jobQueue = new JobQueue($queuePath);
$scheduler->setJobQueue($jobQueue);
}
// Initialize workers if enabled
if ($modernConfig['workers']['enabled'] ?? false) {
$workerCount = $modernConfig['workers']['count'] ?? 2;
$workers = [];
for ($i = 0; $i < $workerCount; $i++) {
$workers[] = new JobWorker("worker-{$i}");
}
$scheduler->setWorkers($workers);
}
}
return $scheduler;
};
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Service/BackupsServiceProvider.php | system/src/Grav/Common/Service/BackupsServiceProvider.php | <?php
/**
* @package Grav\Common\Service
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Service;
use Grav\Common\Backup\Backups;
use Pimple\Container;
use Pimple\ServiceProviderInterface;
/**
* Class BackupsServiceProvider
* @package Grav\Common\Service
*/
class BackupsServiceProvider implements ServiceProviderInterface
{
/**
* @param Container $container
* @return void
*/
public function register(Container $container)
{
$container['backups'] = function () {
$backups = new Backups();
$backups->setup();
return $backups;
};
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Service/AccountsServiceProvider.php | system/src/Grav/Common/Service/AccountsServiceProvider.php | <?php
/**
* @package Grav\Common\Service
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Service;
use Grav\Common\Config\Config;
use Grav\Common\Grav;
use Grav\Common\Page\Header;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Common\User\DataUser;
use Grav\Common\User\User;
use Grav\Events\PermissionsRegisterEvent;
use Grav\Framework\Acl\Permissions;
use Grav\Framework\Acl\PermissionsReader;
use Grav\Framework\Flex\Flex;
use Grav\Framework\Flex\Interfaces\FlexIndexInterface;
use Pimple\Container;
use Pimple\ServiceProviderInterface;
use RocketTheme\Toolbox\Event\Event;
use SplFileInfo;
use Symfony\Component\EventDispatcher\EventDispatcher;
use function define;
use function defined;
use function is_array;
/**
* Class AccountsServiceProvider
* @package Grav\Common\Service
*/
class AccountsServiceProvider implements ServiceProviderInterface
{
/**
* @param Container $container
* @return void
*/
public function register(Container $container)
{
$container['permissions'] = static function (Grav $container) {
/** @var Config $config */
$config = $container['config'];
$permissions = new Permissions();
$permissions->addTypes($config->get('permissions.types', []));
$array = $config->get('permissions.actions');
if (is_array($array)) {
$actions = PermissionsReader::fromArray($array, $permissions->getTypes());
$permissions->addActions($actions);
}
$event = new PermissionsRegisterEvent($permissions);
$container->dispatchEvent($event);
return $permissions;
};
$container['accounts'] = function (Container $container) {
$type = $this->initialize($container);
return $type === 'flex' ? $this->flexAccounts($container) : $this->regularAccounts($container);
};
$container['user_groups'] = static function (Container $container) {
/** @var Flex $flex */
$flex = $container['flex'];
$directory = $flex->getDirectory('user-groups');
return $directory ? $directory->getIndex() : null;
};
$container['users'] = $container->factory(static function (Container $container) {
user_error('Grav::instance()[\'users\'] is deprecated since Grav 1.6, use Grav::instance()[\'accounts\'] instead', E_USER_DEPRECATED);
return $container['accounts'];
});
}
/**
* @param Container $container
* @return string
*/
protected function initialize(Container $container): string
{
$isDefined = defined('GRAV_USER_INSTANCE');
$type = strtolower($isDefined ? GRAV_USER_INSTANCE : $container['config']->get('system.accounts.type', 'regular'));
if ($type === 'flex') {
if (!$isDefined) {
define('GRAV_USER_INSTANCE', 'FLEX');
}
/** @var EventDispatcher $dispatcher */
$dispatcher = $container['events'];
// Stop /admin/user from working, display error instead.
$dispatcher->addListener(
'onAdminPage',
static function (Event $event) {
$grav = Grav::instance();
$admin = $grav['admin'];
[$base,$location,] = $admin->getRouteDetails();
if ($location !== 'user' || isset($grav['flex_objects'])) {
return;
}
/** @var PageInterface $page */
$page = $event['page'];
$page->init(new SplFileInfo('plugin://admin/pages/admin/error.md'));
$page->routable(true);
$header = $page->header();
$header->title = 'Please install missing plugin';
$page->content("## Please install and enable **[Flex Objects]({$base}/plugins/flex-objects)** plugin. It is required to edit **Flex User Accounts**.");
/** @var Header $header */
$header = $page->header();
$directory = $grav['accounts']->getFlexDirectory();
$menu = $directory->getConfig('admin.menu.list');
$header->access = $menu['authorize'] ?? ['admin.super'];
},
100000
);
} elseif (!$isDefined) {
define('GRAV_USER_INSTANCE', 'REGULAR');
}
return $type;
}
/**
* @param Container $container
* @return DataUser\UserCollection
*/
protected function regularAccounts(Container $container)
{
// Use User class for backwards compatibility.
return new DataUser\UserCollection(User::class);
}
/**
* @param Container $container
* @return FlexIndexInterface|null
*/
protected function flexAccounts(Container $container)
{
/** @var Flex $flex */
$flex = $container['flex'];
$directory = $flex->getDirectory('user-accounts');
return $directory ? $directory->getIndex() : null;
}
}
| php | MIT | 97af1bc35b4d1065be46d403134020398dbcc43d | 2026-01-04T15:02:35.884566Z | false |
getgrav/grav | https://github.com/getgrav/grav/blob/97af1bc35b4d1065be46d403134020398dbcc43d/system/src/Grav/Common/Service/AssetsServiceProvider.php | system/src/Grav/Common/Service/AssetsServiceProvider.php | <?php
/**
* @package Grav\Common\Service
*
* @copyright Copyright (c) 2015 - 2025 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Service;
use Pimple\Container;
use Pimple\ServiceProviderInterface;
use Grav\Common\Assets;
/**
* Class AssetsServiceProvider
* @package Grav\Common\Service
*/
class AssetsServiceProvider implements ServiceProviderInterface
{
/**
* @param Container $container
* @return void
*/
public function register(Container $container)
{
$container['assets'] = function () {
return new Assets();
};
}
}
| 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.