Initial commit
This commit is contained in:
commit
73c6b816c0
716 changed files with 170045 additions and 0 deletions
117
kirby/src/Filesystem/Asset.php
Normal file
117
kirby/src/Filesystem/Asset.php
Normal file
|
@ -0,0 +1,117 @@
|
|||
<?php
|
||||
|
||||
namespace Kirby\Filesystem;
|
||||
|
||||
use Kirby\Cms\FileModifications;
|
||||
|
||||
/**
|
||||
* Anything in your public path can be converted
|
||||
* to an Asset object to use the same handy file
|
||||
* methods as for any other Kirby files. Pass a
|
||||
* relative path to the class to create the asset.
|
||||
*
|
||||
* @package Kirby Filesystem
|
||||
* @author Bastian Allgeier <bastian@getkirby.com>
|
||||
* @link https://getkirby.com
|
||||
* @copyright Bastian Allgeier
|
||||
* @license https://getkirby.com/license
|
||||
*/
|
||||
class Asset
|
||||
{
|
||||
use IsFile;
|
||||
use FileModifications;
|
||||
|
||||
/**
|
||||
* Relative file path
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $path;
|
||||
|
||||
/**
|
||||
* Creates a new Asset object for the given path.
|
||||
*
|
||||
* @param string $path
|
||||
*/
|
||||
public function __construct(string $path)
|
||||
{
|
||||
$this->setProperties([
|
||||
'path' => dirname($path),
|
||||
'root' => $this->kirby()->root('index') . '/' . $path,
|
||||
'url' => $this->kirby()->url('index') . '/' . $path
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a unique id for the asset
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function id(): string
|
||||
{
|
||||
return $this->root();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a unique media hash
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function mediaHash(): string
|
||||
{
|
||||
return crc32($this->filename()) . '-' . $this->modified();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the relative path starting at the media folder
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function mediaPath(): string
|
||||
{
|
||||
return 'assets/' . $this->path() . '/' . $this->mediaHash() . '/' . $this->filename();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the absolute path to the file in the public media folder
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function mediaRoot(): string
|
||||
{
|
||||
return $this->kirby()->root('media') . '/' . $this->mediaPath();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the absolute Url to the file in the public media folder
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function mediaUrl(): string
|
||||
{
|
||||
return $this->kirby()->url('media') . '/' . $this->mediaPath();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the path of the file from the web root,
|
||||
* excluding the filename
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function path(): string
|
||||
{
|
||||
return $this->path;
|
||||
}
|
||||
|
||||
/**
|
||||
* Setter for the path
|
||||
*
|
||||
* @param string $path
|
||||
* @return $this
|
||||
*/
|
||||
protected function setPath(string $path)
|
||||
{
|
||||
$this->path = $path === '.' ? '' : $path;
|
||||
return $this;
|
||||
}
|
||||
}
|
618
kirby/src/Filesystem/Dir.php
Normal file
618
kirby/src/Filesystem/Dir.php
Normal file
|
@ -0,0 +1,618 @@
|
|||
<?php
|
||||
|
||||
namespace Kirby\Filesystem;
|
||||
|
||||
use Exception;
|
||||
use Kirby\Cms\App;
|
||||
use Kirby\Cms\Page;
|
||||
use Kirby\Toolkit\Str;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* The `Dir` class provides methods
|
||||
* for dealing with directories on the
|
||||
* file system level, like creating,
|
||||
* listing, moving, copying or
|
||||
* evaluating directories etc.
|
||||
*
|
||||
* For the Cms, it includes methods,
|
||||
* that handle scanning directories
|
||||
* and converting the results into
|
||||
* children, files and other page stuff.
|
||||
*
|
||||
* @package Kirby Filesystem
|
||||
* @author Bastian Allgeier <bastian@getkirby.com>
|
||||
* @link https://getkirby.com
|
||||
* @copyright Bastian Allgeier
|
||||
* @license https://opensource.org/licenses/MIT
|
||||
*/
|
||||
class Dir
|
||||
{
|
||||
/**
|
||||
* Ignore when scanning directories
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $ignore = [
|
||||
'.',
|
||||
'..',
|
||||
'.DS_Store',
|
||||
'.gitignore',
|
||||
'.git',
|
||||
'.svn',
|
||||
'.htaccess',
|
||||
'Thumb.db',
|
||||
'@eaDir'
|
||||
];
|
||||
|
||||
public static $numSeparator = '_';
|
||||
|
||||
/**
|
||||
* Copy the directory to a new destination
|
||||
*
|
||||
* @param string $dir
|
||||
* @param string $target
|
||||
* @param bool $recursive
|
||||
* @param array $ignore
|
||||
* @return bool
|
||||
*/
|
||||
public static function copy(string $dir, string $target, bool $recursive = true, array $ignore = []): bool
|
||||
{
|
||||
if (is_dir($dir) === false) {
|
||||
throw new Exception('The directory "' . $dir . '" does not exist');
|
||||
}
|
||||
|
||||
if (is_dir($target) === true) {
|
||||
throw new Exception('The target directory "' . $target . '" exists');
|
||||
}
|
||||
|
||||
if (static::make($target) !== true) {
|
||||
throw new Exception('The target directory "' . $target . '" could not be created');
|
||||
}
|
||||
|
||||
foreach (static::read($dir) as $name) {
|
||||
$root = $dir . '/' . $name;
|
||||
|
||||
if (in_array($root, $ignore) === true) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (is_dir($root) === true) {
|
||||
if ($recursive === true) {
|
||||
static::copy($root, $target . '/' . $name, true, $ignore);
|
||||
}
|
||||
} else {
|
||||
F::copy($root, $target . '/' . $name);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all subdirectories
|
||||
*
|
||||
* @param string $dir
|
||||
* @param array $ignore
|
||||
* @param bool $absolute
|
||||
* @return array
|
||||
*/
|
||||
public static function dirs(string $dir, array $ignore = null, bool $absolute = false): array
|
||||
{
|
||||
$result = array_values(array_filter(static::read($dir, $ignore, true), 'is_dir'));
|
||||
|
||||
if ($absolute !== true) {
|
||||
$result = array_map('basename', $result);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the directory exists on disk
|
||||
*
|
||||
* @param string $dir
|
||||
* @return bool
|
||||
*/
|
||||
public static function exists(string $dir): bool
|
||||
{
|
||||
return is_dir($dir) === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all files
|
||||
*
|
||||
* @param string $dir
|
||||
* @param array $ignore
|
||||
* @param bool $absolute
|
||||
* @return array
|
||||
*/
|
||||
public static function files(string $dir, array $ignore = null, bool $absolute = false): array
|
||||
{
|
||||
$result = array_values(array_filter(static::read($dir, $ignore, true), 'is_file'));
|
||||
|
||||
if ($absolute !== true) {
|
||||
$result = array_map('basename', $result);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the directory and all subdirectories
|
||||
*
|
||||
* @param string $dir
|
||||
* @param bool $recursive
|
||||
* @param array $ignore
|
||||
* @param string $path
|
||||
* @return array
|
||||
*/
|
||||
public static function index(string $dir, bool $recursive = false, array $ignore = null, string $path = null)
|
||||
{
|
||||
$result = [];
|
||||
$dir = realpath($dir);
|
||||
$items = static::read($dir);
|
||||
|
||||
foreach ($items as $item) {
|
||||
$root = $dir . '/' . $item;
|
||||
$entry = $path !== null ? $path . '/' . $item : $item;
|
||||
$result[] = $entry;
|
||||
|
||||
if ($recursive === true && is_dir($root) === true) {
|
||||
$result = array_merge($result, static::index($root, true, $ignore, $entry));
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the folder has any contents
|
||||
*
|
||||
* @param string $dir
|
||||
* @return bool
|
||||
*/
|
||||
public static function isEmpty(string $dir): bool
|
||||
{
|
||||
return count(static::read($dir)) === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the directory is readable
|
||||
*
|
||||
* @param string $dir
|
||||
* @return bool
|
||||
*/
|
||||
public static function isReadable(string $dir): bool
|
||||
{
|
||||
return is_readable($dir);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the directory is writable
|
||||
*
|
||||
* @param string $dir
|
||||
* @return bool
|
||||
*/
|
||||
public static function isWritable(string $dir): bool
|
||||
{
|
||||
return is_writable($dir);
|
||||
}
|
||||
|
||||
/**
|
||||
* Scans the directory and analyzes files,
|
||||
* content, meta info and children. This is used
|
||||
* in `Kirby\Cms\Page`, `Kirby\Cms\Site` and
|
||||
* `Kirby\Cms\User` objects to fetch all
|
||||
* relevant information.
|
||||
*
|
||||
* Don't use outside the Cms context.
|
||||
*
|
||||
* @internal
|
||||
*
|
||||
* @param string $dir
|
||||
* @param string $contentExtension
|
||||
* @param array|null $contentIgnore
|
||||
* @param bool $multilang
|
||||
* @return array
|
||||
*/
|
||||
public static function inventory(string $dir, string $contentExtension = 'txt', array $contentIgnore = null, bool $multilang = false): array
|
||||
{
|
||||
$dir = realpath($dir);
|
||||
|
||||
$inventory = [
|
||||
'children' => [],
|
||||
'files' => [],
|
||||
'template' => 'default',
|
||||
];
|
||||
|
||||
if ($dir === false) {
|
||||
return $inventory;
|
||||
}
|
||||
|
||||
$items = static::read($dir, $contentIgnore);
|
||||
|
||||
// a temporary store for all content files
|
||||
$content = [];
|
||||
|
||||
// sort all items naturally to avoid sorting issues later
|
||||
natsort($items);
|
||||
|
||||
foreach ($items as $item) {
|
||||
|
||||
// ignore all items with a leading dot
|
||||
if (in_array(substr($item, 0, 1), ['.', '_']) === true) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$root = $dir . '/' . $item;
|
||||
|
||||
if (is_dir($root) === true) {
|
||||
|
||||
// extract the slug and num of the directory
|
||||
if (preg_match('/^([0-9]+)' . static::$numSeparator . '(.*)$/', $item, $match)) {
|
||||
$num = (int)$match[1];
|
||||
$slug = $match[2];
|
||||
} else {
|
||||
$num = null;
|
||||
$slug = $item;
|
||||
}
|
||||
|
||||
$inventory['children'][] = [
|
||||
'dirname' => $item,
|
||||
'model' => null,
|
||||
'num' => $num,
|
||||
'root' => $root,
|
||||
'slug' => $slug,
|
||||
];
|
||||
} else {
|
||||
$extension = pathinfo($item, PATHINFO_EXTENSION);
|
||||
|
||||
switch ($extension) {
|
||||
case 'htm':
|
||||
case 'html':
|
||||
case 'php':
|
||||
// don't track those files
|
||||
break;
|
||||
case $contentExtension:
|
||||
$content[] = pathinfo($item, PATHINFO_FILENAME);
|
||||
break;
|
||||
default:
|
||||
$inventory['files'][$item] = [
|
||||
'filename' => $item,
|
||||
'extension' => $extension,
|
||||
'root' => $root,
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// remove the language codes from all content filenames
|
||||
if ($multilang === true) {
|
||||
foreach ($content as $key => $filename) {
|
||||
$content[$key] = pathinfo($filename, PATHINFO_FILENAME);
|
||||
}
|
||||
|
||||
$content = array_unique($content);
|
||||
}
|
||||
|
||||
$inventory = static::inventoryContent($inventory, $content);
|
||||
$inventory = static::inventoryModels($inventory, $contentExtension, $multilang);
|
||||
|
||||
return $inventory;
|
||||
}
|
||||
|
||||
/**
|
||||
* Take all content files,
|
||||
* remove those who are meta files and
|
||||
* detect the main content file
|
||||
*
|
||||
* @param array $inventory
|
||||
* @param array $content
|
||||
* @return array
|
||||
*/
|
||||
protected static function inventoryContent(array $inventory, array $content): array
|
||||
{
|
||||
|
||||
// filter meta files from the content file
|
||||
if (empty($content) === true) {
|
||||
$inventory['template'] = 'default';
|
||||
return $inventory;
|
||||
}
|
||||
|
||||
foreach ($content as $contentName) {
|
||||
|
||||
// could be a meta file. i.e. cover.jpg
|
||||
if (isset($inventory['files'][$contentName]) === true) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// it's most likely the template
|
||||
$inventory['template'] = $contentName;
|
||||
}
|
||||
|
||||
return $inventory;
|
||||
}
|
||||
|
||||
/**
|
||||
* Go through all inventory children
|
||||
* and inject a model for each
|
||||
*
|
||||
* @param array $inventory
|
||||
* @param string $contentExtension
|
||||
* @param bool $multilang
|
||||
* @return array
|
||||
*/
|
||||
protected static function inventoryModels(array $inventory, string $contentExtension, bool $multilang = false): array
|
||||
{
|
||||
// inject models
|
||||
if (empty($inventory['children']) === false && empty(Page::$models) === false) {
|
||||
if ($multilang === true) {
|
||||
$contentExtension = App::instance()->defaultLanguage()->code() . '.' . $contentExtension;
|
||||
}
|
||||
|
||||
foreach ($inventory['children'] as $key => $child) {
|
||||
foreach (Page::$models as $modelName => $modelClass) {
|
||||
if (file_exists($child['root'] . '/' . $modelName . '.' . $contentExtension) === true) {
|
||||
$inventory['children'][$key]['model'] = $modelName;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $inventory;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a (symbolic) link to a directory
|
||||
*
|
||||
* @param string $source
|
||||
* @param string $link
|
||||
* @return bool
|
||||
*/
|
||||
public static function link(string $source, string $link): bool
|
||||
{
|
||||
static::make(dirname($link), true);
|
||||
|
||||
if (is_dir($link) === true) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (is_dir($source) === false) {
|
||||
throw new Exception(sprintf('The directory "%s" does not exist and cannot be linked', $source));
|
||||
}
|
||||
|
||||
try {
|
||||
return symlink($source, $link) === true;
|
||||
} catch (Throwable $e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new directory
|
||||
*
|
||||
* @param string $dir The path for the new directory
|
||||
* @param bool $recursive Create all parent directories, which don't exist
|
||||
* @return bool True: the dir has been created, false: creating failed
|
||||
* @throws \Exception If a file with the provided path already exists or the parent directory is not writable
|
||||
*/
|
||||
public static function make(string $dir, bool $recursive = true): bool
|
||||
{
|
||||
if (empty($dir) === true) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (is_dir($dir) === true) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (is_file($dir) === true) {
|
||||
throw new Exception(sprintf('A file with the name "%s" already exists', $dir));
|
||||
}
|
||||
|
||||
$parent = dirname($dir);
|
||||
|
||||
if ($recursive === true) {
|
||||
if (is_dir($parent) === false) {
|
||||
static::make($parent, true);
|
||||
}
|
||||
}
|
||||
|
||||
if (is_writable($parent) === false) {
|
||||
throw new Exception(sprintf('The directory "%s" cannot be created', $dir));
|
||||
}
|
||||
|
||||
return mkdir($dir);
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively check when the dir and all
|
||||
* subfolders have been modified for the last time.
|
||||
*
|
||||
* @param string $dir The path of the directory
|
||||
* @param string $format
|
||||
* @param string $handler
|
||||
* @return int|string
|
||||
*/
|
||||
public static function modified(string $dir, string $format = null, string $handler = 'date')
|
||||
{
|
||||
$modified = filemtime($dir);
|
||||
$items = static::read($dir);
|
||||
|
||||
foreach ($items as $item) {
|
||||
if (is_file($dir . '/' . $item) === true) {
|
||||
$newModified = filemtime($dir . '/' . $item);
|
||||
} else {
|
||||
$newModified = static::modified($dir . '/' . $item);
|
||||
}
|
||||
|
||||
$modified = ($newModified > $modified) ? $newModified : $modified;
|
||||
}
|
||||
|
||||
return Str::date($modified, $format, $handler);
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves a directory to a new location
|
||||
*
|
||||
* @param string $old The current path of the directory
|
||||
* @param string $new The desired path where the dir should be moved to
|
||||
* @return bool true: the directory has been moved, false: moving failed
|
||||
*/
|
||||
public static function move(string $old, string $new): bool
|
||||
{
|
||||
if ($old === $new) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (is_dir($old) === false || is_dir($new) === true) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (static::make(dirname($new), true) !== true) {
|
||||
throw new Exception('The parent directory cannot be created');
|
||||
}
|
||||
|
||||
return rename($old, $new);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a nicely formatted size of all the contents of the folder
|
||||
*
|
||||
* @param string $dir The path of the directory
|
||||
* @param string|null|false $locale Locale for number formatting,
|
||||
* `null` for the current locale,
|
||||
* `false` to disable number formatting
|
||||
* @return mixed
|
||||
*/
|
||||
public static function niceSize(string $dir, $locale = null)
|
||||
{
|
||||
return F::niceSize(static::size($dir), $locale);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads all files from a directory and returns them as an array.
|
||||
* It skips unwanted invisible stuff.
|
||||
*
|
||||
* @param string $dir The path of directory
|
||||
* @param array $ignore Optional array with filenames, which should be ignored
|
||||
* @param bool $absolute If true, the full path for each item will be returned
|
||||
* @return array An array of filenames
|
||||
*/
|
||||
public static function read(string $dir, array $ignore = null, bool $absolute = false): array
|
||||
{
|
||||
if (is_dir($dir) === false) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// create the ignore pattern
|
||||
$ignore ??= static::$ignore;
|
||||
$ignore = array_merge($ignore, ['.', '..']);
|
||||
|
||||
// scan for all files and dirs
|
||||
$result = array_values((array)array_diff(scandir($dir), $ignore));
|
||||
|
||||
// add absolute paths
|
||||
if ($absolute === true) {
|
||||
$result = array_map(fn ($item) => $dir . '/' . $item, $result);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a folder including all containing files and folders
|
||||
*
|
||||
* @param string $dir
|
||||
* @return bool
|
||||
*/
|
||||
public static function remove(string $dir): bool
|
||||
{
|
||||
$dir = realpath($dir);
|
||||
|
||||
if (is_dir($dir) === false) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (is_link($dir) === true) {
|
||||
return unlink($dir);
|
||||
}
|
||||
|
||||
foreach (scandir($dir) as $childName) {
|
||||
if (in_array($childName, ['.', '..']) === true) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$child = $dir . '/' . $childName;
|
||||
|
||||
if (is_link($child) === true) {
|
||||
unlink($child);
|
||||
} elseif (is_dir($child) === true) {
|
||||
static::remove($child);
|
||||
} else {
|
||||
F::remove($child);
|
||||
}
|
||||
}
|
||||
|
||||
return rmdir($dir);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the size of the directory
|
||||
*
|
||||
* @param string $dir The path of the directory
|
||||
* @param bool $recursive Include all subfolders and their files
|
||||
* @return mixed
|
||||
*/
|
||||
public static function size(string $dir, bool $recursive = true)
|
||||
{
|
||||
if (is_dir($dir) === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Get size for all direct files
|
||||
$size = F::size(static::files($dir, null, true));
|
||||
|
||||
// if recursive, add sizes of all subdirectories
|
||||
if ($recursive === true) {
|
||||
foreach (static::dirs($dir, null, true) as $subdir) {
|
||||
$size += static::size($subdir);
|
||||
}
|
||||
}
|
||||
|
||||
return $size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the directory or any subdirectory has been
|
||||
* modified after the given timestamp
|
||||
*
|
||||
* @param string $dir
|
||||
* @param int $time
|
||||
* @return bool
|
||||
*/
|
||||
public static function wasModifiedAfter(string $dir, int $time): bool
|
||||
{
|
||||
if (filemtime($dir) > $time) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$content = static::read($dir);
|
||||
|
||||
foreach ($content as $item) {
|
||||
$subdir = $dir . '/' . $item;
|
||||
|
||||
if (filemtime($subdir) > $time) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (is_dir($subdir) === true && static::wasModifiedAfter($subdir, $time) === true) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
889
kirby/src/Filesystem/F.php
Normal file
889
kirby/src/Filesystem/F.php
Normal file
|
@ -0,0 +1,889 @@
|
|||
<?php
|
||||
|
||||
namespace Kirby\Filesystem;
|
||||
|
||||
use Exception;
|
||||
use Kirby\Toolkit\I18n;
|
||||
use Kirby\Toolkit\Str;
|
||||
use Throwable;
|
||||
use ZipArchive;
|
||||
|
||||
/**
|
||||
* The `F` class provides methods for
|
||||
* dealing with files on the file system
|
||||
* level, like creating, reading,
|
||||
* deleting, copying or validatings files.
|
||||
*
|
||||
* @package Kirby Filesystem
|
||||
* @author Bastian Allgeier <bastian@getkirby.com>
|
||||
* @link https://getkirby.com
|
||||
* @copyright Bastian Allgeier
|
||||
* @license https://opensource.org/licenses/MIT
|
||||
*/
|
||||
class F
|
||||
{
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
public static $types = [
|
||||
'archive' => [
|
||||
'gz',
|
||||
'gzip',
|
||||
'tar',
|
||||
'tgz',
|
||||
'zip',
|
||||
],
|
||||
'audio' => [
|
||||
'aif',
|
||||
'aiff',
|
||||
'm4a',
|
||||
'midi',
|
||||
'mp3',
|
||||
'wav',
|
||||
],
|
||||
'code' => [
|
||||
'css',
|
||||
'js',
|
||||
'json',
|
||||
'java',
|
||||
'htm',
|
||||
'html',
|
||||
'php',
|
||||
'rb',
|
||||
'py',
|
||||
'scss',
|
||||
'xml',
|
||||
'yaml',
|
||||
'yml',
|
||||
],
|
||||
'document' => [
|
||||
'csv',
|
||||
'doc',
|
||||
'docx',
|
||||
'dotx',
|
||||
'indd',
|
||||
'md',
|
||||
'mdown',
|
||||
'pdf',
|
||||
'ppt',
|
||||
'pptx',
|
||||
'rtf',
|
||||
'txt',
|
||||
'xl',
|
||||
'xls',
|
||||
'xlsx',
|
||||
'xltx',
|
||||
],
|
||||
'image' => [
|
||||
'ai',
|
||||
'avif',
|
||||
'bmp',
|
||||
'gif',
|
||||
'eps',
|
||||
'ico',
|
||||
'j2k',
|
||||
'jp2',
|
||||
'jpeg',
|
||||
'jpg',
|
||||
'jpe',
|
||||
'png',
|
||||
'ps',
|
||||
'psd',
|
||||
'svg',
|
||||
'tif',
|
||||
'tiff',
|
||||
'webp'
|
||||
],
|
||||
'video' => [
|
||||
'avi',
|
||||
'flv',
|
||||
'm4v',
|
||||
'mov',
|
||||
'movie',
|
||||
'mpe',
|
||||
'mpg',
|
||||
'mp4',
|
||||
'ogg',
|
||||
'ogv',
|
||||
'swf',
|
||||
'webm',
|
||||
],
|
||||
];
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
public static $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
|
||||
|
||||
/**
|
||||
* Appends new content to an existing file
|
||||
*
|
||||
* @param string $file The path for the file
|
||||
* @param mixed $content Either a string or an array. Arrays will be converted to JSON.
|
||||
* @return bool
|
||||
*/
|
||||
public static function append(string $file, $content): bool
|
||||
{
|
||||
return static::write($file, $content, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the file content as base64 encoded string
|
||||
*
|
||||
* @param string $file The path for the file
|
||||
* @return string
|
||||
*/
|
||||
public static function base64(string $file): string
|
||||
{
|
||||
return base64_encode(static::read($file));
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy a file to a new location.
|
||||
*
|
||||
* @param string $source
|
||||
* @param string $target
|
||||
* @param bool $force
|
||||
* @return bool
|
||||
*/
|
||||
public static function copy(string $source, string $target, bool $force = false): bool
|
||||
{
|
||||
if (file_exists($source) === false || (file_exists($target) === true && $force === false)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$directory = dirname($target);
|
||||
|
||||
// create the parent directory if it does not exist
|
||||
if (is_dir($directory) === false) {
|
||||
Dir::make($directory, true);
|
||||
}
|
||||
|
||||
return copy($source, $target);
|
||||
}
|
||||
|
||||
/**
|
||||
* Just an alternative for dirname() to stay consistent
|
||||
*
|
||||
* <code>
|
||||
*
|
||||
* $dirname = F::dirname('/var/www/test.txt');
|
||||
* // dirname is /var/www
|
||||
*
|
||||
* </code>
|
||||
*
|
||||
* @param string $file The path
|
||||
* @return string
|
||||
*/
|
||||
public static function dirname(string $file): string
|
||||
{
|
||||
return dirname($file);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the file exists on disk
|
||||
*
|
||||
* @param string $file
|
||||
* @param string $in
|
||||
* @return bool
|
||||
*/
|
||||
public static function exists(string $file, string $in = null): bool
|
||||
{
|
||||
try {
|
||||
static::realpath($file, $in);
|
||||
return true;
|
||||
} catch (Exception $e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the extension of a file
|
||||
*
|
||||
* @param string $file The filename or path
|
||||
* @param string $extension Set an optional extension to overwrite the current one
|
||||
* @return string
|
||||
*/
|
||||
public static function extension(string $file = null, string $extension = null): string
|
||||
{
|
||||
// overwrite the current extension
|
||||
if ($extension !== null) {
|
||||
return static::name($file) . '.' . $extension;
|
||||
}
|
||||
|
||||
// return the current extension
|
||||
return Str::lower(pathinfo($file, PATHINFO_EXTENSION));
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a file extension to a mime type
|
||||
*
|
||||
* @param string $extension
|
||||
* @return string|false
|
||||
*/
|
||||
public static function extensionToMime(string $extension)
|
||||
{
|
||||
return Mime::fromExtension($extension);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the file type for a passed extension
|
||||
*
|
||||
* @param string $extension
|
||||
* @return string|false
|
||||
*/
|
||||
public static function extensionToType(string $extension)
|
||||
{
|
||||
foreach (static::$types as $type => $extensions) {
|
||||
if (in_array($extension, $extensions) === true) {
|
||||
return $type;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all extensions for a certain file type
|
||||
*
|
||||
* @param string $type
|
||||
* @return array
|
||||
*/
|
||||
public static function extensions(string $type = null)
|
||||
{
|
||||
if ($type === null) {
|
||||
return array_keys(Mime::types());
|
||||
}
|
||||
|
||||
return static::$types[$type] ?? [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the filename from a file path
|
||||
*
|
||||
* <code>
|
||||
*
|
||||
* $filename = F::filename('/var/www/test.txt');
|
||||
* // filename is test.txt
|
||||
*
|
||||
* </code>
|
||||
*
|
||||
* @param string $name The path
|
||||
* @return string
|
||||
*/
|
||||
public static function filename(string $name): string
|
||||
{
|
||||
return pathinfo($name, PATHINFO_BASENAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalidate opcode cache for file.
|
||||
*
|
||||
* @param string $file The path of the file
|
||||
* @return bool
|
||||
*/
|
||||
public static function invalidateOpcodeCache(string $file): bool
|
||||
{
|
||||
if (function_exists('opcache_invalidate') && strlen(ini_get('opcache.restrict_api')) === 0) {
|
||||
return opcache_invalidate($file, true);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a file is of a certain type
|
||||
*
|
||||
* @param string $file Full path to the file
|
||||
* @param string $value An extension or mime type
|
||||
* @return bool
|
||||
*/
|
||||
public static function is(string $file, string $value): bool
|
||||
{
|
||||
// check for the extension
|
||||
if (in_array($value, static::extensions()) === true) {
|
||||
return static::extension($file) === $value;
|
||||
}
|
||||
|
||||
// check for the mime type
|
||||
if (strpos($value, '/') !== false) {
|
||||
return static::mime($file) === $value;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the file is readable
|
||||
*
|
||||
* @param string $file
|
||||
* @return bool
|
||||
*/
|
||||
public static function isReadable(string $file): bool
|
||||
{
|
||||
return is_readable($file);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the file is writable
|
||||
*
|
||||
* @param string $file
|
||||
* @return bool
|
||||
*/
|
||||
public static function isWritable(string $file): bool
|
||||
{
|
||||
if (file_exists($file) === false) {
|
||||
return is_writable(dirname($file));
|
||||
}
|
||||
|
||||
return is_writable($file);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a (symbolic) link to a file
|
||||
*
|
||||
* @param string $source
|
||||
* @param string $link
|
||||
* @param string $method
|
||||
* @return bool
|
||||
*/
|
||||
public static function link(string $source, string $link, string $method = 'link'): bool
|
||||
{
|
||||
Dir::make(dirname($link), true);
|
||||
|
||||
if (is_file($link) === true) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (is_file($source) === false) {
|
||||
throw new Exception(sprintf('The file "%s" does not exist and cannot be linked', $source));
|
||||
}
|
||||
|
||||
try {
|
||||
return $method($source, $link) === true;
|
||||
} catch (Throwable $e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a file and returns the result or `false` if the
|
||||
* file to load does not exist
|
||||
*
|
||||
* @param string $file
|
||||
* @param mixed $fallback
|
||||
* @param array $data Optional array of variables to extract in the variable scope
|
||||
* @return mixed
|
||||
*/
|
||||
public static function load(string $file, $fallback = null, array $data = [])
|
||||
{
|
||||
if (is_file($file) === false) {
|
||||
return $fallback;
|
||||
}
|
||||
|
||||
// we use the loadIsolated() method here to prevent the included
|
||||
// file from overwriting our $fallback in this variable scope; see
|
||||
// https://www.php.net/manual/en/function.include.php#example-124
|
||||
$result = static::loadIsolated($file, $data);
|
||||
|
||||
if ($fallback !== null && gettype($result) !== gettype($fallback)) {
|
||||
return $fallback;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a file with as little as possible in the variable scope
|
||||
*
|
||||
* @param string $file
|
||||
* @param array $data Optional array of variables to extract in the variable scope
|
||||
* @return mixed
|
||||
*/
|
||||
protected static function loadIsolated(string $file, array $data = [])
|
||||
{
|
||||
// extract the $data variables in this scope to be accessed by the included file;
|
||||
// protect $file against being overwritten by a $data variable
|
||||
$___file___ = $file;
|
||||
extract($data);
|
||||
|
||||
return include $___file___;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a file using `include_once()` and returns whether loading was successful
|
||||
*
|
||||
* @param string $file
|
||||
* @return bool
|
||||
*/
|
||||
public static function loadOnce(string $file): bool
|
||||
{
|
||||
if (is_file($file) === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
include_once $file;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the mime type of a file
|
||||
*
|
||||
* @param string $file
|
||||
* @return string|false
|
||||
*/
|
||||
public static function mime(string $file)
|
||||
{
|
||||
return Mime::type($file);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a mime type to a file extension
|
||||
*
|
||||
* @param string $mime
|
||||
* @return string|false
|
||||
*/
|
||||
public static function mimeToExtension(string $mime = null)
|
||||
{
|
||||
return Mime::toExtension($mime);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the type for a given mime
|
||||
*
|
||||
* @param string $mime
|
||||
* @return string|false
|
||||
*/
|
||||
public static function mimeToType(string $mime)
|
||||
{
|
||||
return static::extensionToType(Mime::toExtension($mime));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the file's last modification time.
|
||||
*
|
||||
* @param string $file
|
||||
* @param string $format
|
||||
* @param string $handler date or strftime
|
||||
* @return mixed
|
||||
*/
|
||||
public static function modified(string $file, string $format = null, string $handler = 'date')
|
||||
{
|
||||
if (file_exists($file) !== true) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$modified = filemtime($file);
|
||||
|
||||
return Str::date($modified, $format, $handler);
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves a file to a new location
|
||||
*
|
||||
* @param string $oldRoot The current path for the file
|
||||
* @param string $newRoot The path to the new location
|
||||
* @param bool $force Force move if the target file exists
|
||||
* @return bool
|
||||
*/
|
||||
public static function move(string $oldRoot, string $newRoot, bool $force = false): bool
|
||||
{
|
||||
// check if the file exists
|
||||
if (file_exists($oldRoot) === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (file_exists($newRoot) === true) {
|
||||
if ($force === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// delete the existing file
|
||||
static::remove($newRoot);
|
||||
}
|
||||
|
||||
// actually move the file if it exists
|
||||
if (rename($oldRoot, $newRoot) !== true) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the name from a file path or filename without extension
|
||||
*
|
||||
* @param string $name The path or filename
|
||||
* @return string
|
||||
*/
|
||||
public static function name(string $name): string
|
||||
{
|
||||
return pathinfo($name, PATHINFO_FILENAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts an integer size into a human readable format
|
||||
*
|
||||
* @param mixed $size The file size, a file path or array of paths
|
||||
* @param string|null|false $locale Locale for number formatting,
|
||||
* `null` for the current locale,
|
||||
* `false` to disable number formatting
|
||||
* @return string
|
||||
*/
|
||||
public static function niceSize($size, $locale = null): string
|
||||
{
|
||||
// file mode
|
||||
if (is_string($size) === true || is_array($size) === true) {
|
||||
$size = static::size($size);
|
||||
}
|
||||
|
||||
// make sure it's an int
|
||||
$size = (int)$size;
|
||||
|
||||
// avoid errors for invalid sizes
|
||||
if ($size <= 0) {
|
||||
return '0 KB';
|
||||
}
|
||||
|
||||
// the math magic
|
||||
$size = round($size / pow(1024, ($unit = floor(log($size, 1024)))), 2);
|
||||
|
||||
// format the number if requested
|
||||
if ($locale !== false) {
|
||||
$size = I18n::formatNumber($size, $locale);
|
||||
}
|
||||
|
||||
return $size . ' ' . static::$units[$unit];
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the content of a file or requests the
|
||||
* contents of a remote HTTP or HTTPS URL
|
||||
*
|
||||
* @param string $file The path for the file or an absolute URL
|
||||
* @return string|false
|
||||
*/
|
||||
public static function read(string $file)
|
||||
{
|
||||
if (
|
||||
is_file($file) !== true &&
|
||||
Str::startsWith($file, 'https://') !== true &&
|
||||
Str::startsWith($file, 'http://') !== true
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return @file_get_contents($file);
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the name of the file without
|
||||
* touching the extension
|
||||
*
|
||||
* @param string $file
|
||||
* @param string $newName
|
||||
* @param bool $overwrite Force overwrite existing files
|
||||
* @return string|false
|
||||
*/
|
||||
public static function rename(string $file, string $newName, bool $overwrite = false)
|
||||
{
|
||||
// create the new name
|
||||
$name = static::safeName(basename($newName));
|
||||
|
||||
// overwrite the root
|
||||
$newRoot = rtrim(dirname($file) . '/' . $name . '.' . F::extension($file), '.');
|
||||
|
||||
// nothing has changed
|
||||
if ($newRoot === $file) {
|
||||
return $newRoot;
|
||||
}
|
||||
|
||||
if (F::move($file, $newRoot, $overwrite) !== true) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $newRoot;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the absolute path to the file if the file can be found.
|
||||
*
|
||||
* @param string $file
|
||||
* @param string $in
|
||||
* @return string|null
|
||||
*/
|
||||
public static function realpath(string $file, string $in = null)
|
||||
{
|
||||
$realpath = realpath($file);
|
||||
|
||||
if ($realpath === false || is_file($realpath) === false) {
|
||||
throw new Exception(sprintf('The file does not exist at the given path: "%s"', $file));
|
||||
}
|
||||
|
||||
if ($in !== null) {
|
||||
$parent = realpath($in);
|
||||
|
||||
if ($parent === false || is_dir($parent) === false) {
|
||||
throw new Exception(sprintf('The parent directory does not exist: "%s"', $in));
|
||||
}
|
||||
|
||||
if (substr($realpath, 0, strlen($parent)) !== $parent) {
|
||||
throw new Exception('The file is not within the parent directory');
|
||||
}
|
||||
}
|
||||
|
||||
return $realpath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the relative path of the file
|
||||
* starting after $in
|
||||
*
|
||||
* @SuppressWarnings(PHPMD.CountInLoopExpression)
|
||||
*
|
||||
* @param string $file
|
||||
* @param string $in
|
||||
* @return string
|
||||
*/
|
||||
public static function relativepath(string $file, string $in = null): string
|
||||
{
|
||||
if (empty($in) === true) {
|
||||
return basename($file);
|
||||
}
|
||||
|
||||
// windows
|
||||
$file = str_replace('\\', '/', $file);
|
||||
$in = str_replace('\\', '/', $in);
|
||||
|
||||
// trim trailing slashes
|
||||
$file = rtrim($file, '/');
|
||||
$in = rtrim($in, '/');
|
||||
|
||||
if (Str::contains($file, $in . '/') === false) {
|
||||
// make the paths relative by stripping what they have
|
||||
// in common and adding `../` tokens at the start
|
||||
$fileParts = explode('/', $file);
|
||||
$inParts = explode('/', $in);
|
||||
while (count($fileParts) && count($inParts) && ($fileParts[0] === $inParts[0])) {
|
||||
array_shift($fileParts);
|
||||
array_shift($inParts);
|
||||
}
|
||||
|
||||
return str_repeat('../', count($inParts)) . implode('/', $fileParts);
|
||||
}
|
||||
|
||||
return '/' . Str::after($file, $in . '/');
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a file
|
||||
*
|
||||
* <code>
|
||||
*
|
||||
* $remove = F::remove('test.txt');
|
||||
* if($remove) echo 'The file has been removed';
|
||||
*
|
||||
* </code>
|
||||
*
|
||||
* @param string $file The path for the file
|
||||
* @return bool
|
||||
*/
|
||||
public static function remove(string $file): bool
|
||||
{
|
||||
if (strpos($file, '*') !== false) {
|
||||
foreach (glob($file) as $f) {
|
||||
static::remove($f);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
$file = realpath($file);
|
||||
|
||||
if (file_exists($file) === false) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return unlink($file);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize a filename to strip unwanted special characters
|
||||
*
|
||||
* <code>
|
||||
*
|
||||
* $safe = f::safeName('über genius.txt');
|
||||
* // safe will be ueber-genius.txt
|
||||
*
|
||||
* </code>
|
||||
*
|
||||
* @param string $string The file name
|
||||
* @return string
|
||||
*/
|
||||
public static function safeName(string $string): string
|
||||
{
|
||||
$name = static::name($string);
|
||||
$extension = static::extension($string);
|
||||
$safeName = Str::slug($name, '-', 'a-z0-9@._-');
|
||||
$safeExtension = empty($extension) === false ? '.' . Str::slug($extension) : '';
|
||||
|
||||
return $safeName . $safeExtension;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to find similar or the same file by
|
||||
* building a glob based on the path
|
||||
*
|
||||
* @param string $path
|
||||
* @param string $pattern
|
||||
* @return array
|
||||
*/
|
||||
public static function similar(string $path, string $pattern = '*'): array
|
||||
{
|
||||
$dir = dirname($path);
|
||||
$name = static::name($path);
|
||||
$extension = static::extension($path);
|
||||
$glob = $dir . '/' . $name . $pattern . '.' . $extension;
|
||||
return glob($glob);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the size of a file or an array of files.
|
||||
*
|
||||
* @param string|array $file file path or array of paths
|
||||
* @return int
|
||||
*/
|
||||
public static function size($file): int
|
||||
{
|
||||
if (is_array($file) === true) {
|
||||
return array_reduce(
|
||||
$file,
|
||||
fn ($total, $file) => $total + F::size($file),
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
return filesize($file);
|
||||
} catch (Throwable $e) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Categorize the file
|
||||
*
|
||||
* @param string $file Either the file path or extension
|
||||
* @return string|null
|
||||
*/
|
||||
public static function type(string $file)
|
||||
{
|
||||
$length = strlen($file);
|
||||
|
||||
if ($length >= 2 && $length <= 4) {
|
||||
// use the file name as extension
|
||||
$extension = $file;
|
||||
} else {
|
||||
// get the extension from the filename
|
||||
$extension = pathinfo($file, PATHINFO_EXTENSION);
|
||||
}
|
||||
|
||||
if (empty($extension) === true) {
|
||||
// detect the mime type first to get the most reliable extension
|
||||
$mime = static::mime($file);
|
||||
$extension = static::mimeToExtension($mime);
|
||||
}
|
||||
|
||||
// sanitize extension
|
||||
$extension = strtolower($extension);
|
||||
|
||||
foreach (static::$types as $type => $extensions) {
|
||||
if (in_array($extension, $extensions) === true) {
|
||||
return $type;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all extensions of a given file type
|
||||
* or `null` if the file type is unknown
|
||||
*
|
||||
* @param string $type
|
||||
* @return array|null
|
||||
*/
|
||||
public static function typeToExtensions(string $type): ?array
|
||||
{
|
||||
return static::$types[$type] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unzips a zip file
|
||||
*
|
||||
* @param string $file
|
||||
* @param string $to
|
||||
* @return bool
|
||||
*/
|
||||
public static function unzip(string $file, string $to): bool
|
||||
{
|
||||
if (class_exists('ZipArchive') === false) {
|
||||
throw new Exception('The ZipArchive class is not available');
|
||||
}
|
||||
|
||||
$zip = new ZipArchive();
|
||||
|
||||
if ($zip->open($file) === true) {
|
||||
$zip->extractTo($to);
|
||||
$zip->close();
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the file as data uri
|
||||
*
|
||||
* @param string $file The path for the file
|
||||
* @return string|false
|
||||
*/
|
||||
public static function uri(string $file)
|
||||
{
|
||||
if ($mime = static::mime($file)) {
|
||||
return 'data:' . $mime . ';base64,' . static::base64($file);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new file
|
||||
*
|
||||
* @param string $file The path for the new file
|
||||
* @param mixed $content Either a string, an object or an array. Arrays and objects will be serialized.
|
||||
* @param bool $append true: append the content to an existing file if available. false: overwrite.
|
||||
* @return bool
|
||||
*/
|
||||
public static function write(string $file, $content, bool $append = false): bool
|
||||
{
|
||||
if (is_array($content) === true || is_object($content) === true) {
|
||||
$content = serialize($content);
|
||||
}
|
||||
|
||||
$mode = $append === true ? FILE_APPEND | LOCK_EX : LOCK_EX;
|
||||
|
||||
// if the parent directory does not exist, create it
|
||||
if (is_dir(dirname($file)) === false) {
|
||||
if (Dir::make(dirname($file)) === false) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (static::isWritable($file) === false) {
|
||||
throw new Exception('The file "' . $file . '" is not writable');
|
||||
}
|
||||
|
||||
return file_put_contents($file, $content, $mode) !== false;
|
||||
}
|
||||
}
|
634
kirby/src/Filesystem/File.php
Normal file
634
kirby/src/Filesystem/File.php
Normal file
|
@ -0,0 +1,634 @@
|
|||
<?php
|
||||
|
||||
namespace Kirby\Filesystem;
|
||||
|
||||
use Kirby\Cms\App;
|
||||
use Kirby\Exception\Exception;
|
||||
use Kirby\Http\Response;
|
||||
use Kirby\Sane\Sane;
|
||||
use Kirby\Toolkit\Escape;
|
||||
use Kirby\Toolkit\Html;
|
||||
use Kirby\Toolkit\Properties;
|
||||
use Kirby\Toolkit\V;
|
||||
|
||||
/**
|
||||
* Flexible File object with a set of helpful
|
||||
* methods to inspect and work with files.
|
||||
*
|
||||
* @since 3.6.0
|
||||
*
|
||||
* @package Kirby Filesystem
|
||||
* @author Nico Hoffmann <nico@getkirby.com>
|
||||
* @link https://getkirby.com
|
||||
* @copyright Bastian Allgeier
|
||||
* @license https://getkirby.com/license
|
||||
*/
|
||||
class File
|
||||
{
|
||||
use Properties;
|
||||
|
||||
/**
|
||||
* Absolute file path
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $root;
|
||||
|
||||
/**
|
||||
* Absolute file URL
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected $url;
|
||||
|
||||
/**
|
||||
* Validation rules to be used for `::match()`
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $validations = [
|
||||
'maxsize' => ['size', 'max'],
|
||||
'minsize' => ['size', 'min']
|
||||
];
|
||||
|
||||
/**
|
||||
* Constructor sets all file properties
|
||||
*
|
||||
* @param array|string|null $props Properties or deprecated `$root` string
|
||||
* @param string|null $url Deprecated argument, use `$props['url']` instead
|
||||
*/
|
||||
public function __construct($props = null, string $url = null)
|
||||
{
|
||||
// Legacy support for old constructor of
|
||||
// the `Kirby\Image\Image` class
|
||||
// @todo 4.0.0 remove
|
||||
if (is_array($props) === false) {
|
||||
$props = [
|
||||
'root' => $props,
|
||||
'url' => $url
|
||||
];
|
||||
}
|
||||
|
||||
$this->setProperties($props);
|
||||
}
|
||||
|
||||
/**
|
||||
* Improved `var_dump` output
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function __debugInfo(): array
|
||||
{
|
||||
return $this->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the URL for the file object
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function __toString(): string
|
||||
{
|
||||
return $this->url() ?? $this->root() ?? '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the file content as base64 encoded string
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function base64(): string
|
||||
{
|
||||
return base64_encode($this->read());
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy a file to a new location.
|
||||
*
|
||||
* @param string $target
|
||||
* @param bool $force
|
||||
* @return static
|
||||
*/
|
||||
public function copy(string $target, bool $force = false)
|
||||
{
|
||||
if (F::copy($this->root, $target, $force) !== true) {
|
||||
throw new Exception('The file "' . $this->root . '" could not be copied');
|
||||
}
|
||||
|
||||
return new static($target);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the file as data uri
|
||||
*
|
||||
* @param bool $base64 Whether the data should be base64 encoded or not
|
||||
* @return string
|
||||
*/
|
||||
public function dataUri(bool $base64 = true): string
|
||||
{
|
||||
if ($base64 === true) {
|
||||
return 'data:' . $this->mime() . ';base64,' . $this->base64();
|
||||
}
|
||||
|
||||
return 'data:' . $this->mime() . ',' . Escape::url($this->read());
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the file
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function delete(): bool
|
||||
{
|
||||
if (F::remove($this->root) !== true) {
|
||||
throw new Exception('The file "' . $this->root . '" could not be deleted');
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/*
|
||||
* Automatically sends all needed headers for the file to be downloaded
|
||||
* and echos the file's content
|
||||
*
|
||||
* @param string|null $filename Optional filename for the download
|
||||
* @return string
|
||||
*/
|
||||
public function download($filename = null): string
|
||||
{
|
||||
return Response::download($this->root, $filename ?? $this->filename());
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the file actually exists
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function exists(): bool
|
||||
{
|
||||
return file_exists($this->root) === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current lowercase extension (without .)
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function extension(): string
|
||||
{
|
||||
return F::extension($this->root);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the filename
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function filename(): string
|
||||
{
|
||||
return basename($this->root);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a md5 hash of the root
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function hash(): string
|
||||
{
|
||||
return md5($this->root);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends an appropriate header for the asset
|
||||
*
|
||||
* @param bool $send
|
||||
* @return \Kirby\Http\Response|void
|
||||
*/
|
||||
public function header(bool $send = true)
|
||||
{
|
||||
$response = new Response('', $this->mime());
|
||||
|
||||
if ($send !== true) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
$response->send();
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the file to html
|
||||
*
|
||||
* @param array $attr
|
||||
* @return string
|
||||
*/
|
||||
public function html(array $attr = []): string
|
||||
{
|
||||
return Html::a($this->url() ?? '', $attr);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a file is of a certain type
|
||||
*
|
||||
* @param string $value An extension or mime type
|
||||
* @return bool
|
||||
*/
|
||||
public function is(string $value): bool
|
||||
{
|
||||
return F::is($this->root, $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the file is readable
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isReadable(): bool
|
||||
{
|
||||
return is_readable($this->root) === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the file is a resizable image
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isResizable(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a preview can be displayed for the file
|
||||
* in the panel or in the frontend
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isViewable(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the file is writable
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isWritable(): bool
|
||||
{
|
||||
return F::isWritable($this->root);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the app instance if it exists
|
||||
*
|
||||
* @return \Kirby\Cms\App|null
|
||||
*/
|
||||
public function kirby()
|
||||
{
|
||||
return App::instance(null, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a set of validations on the file object
|
||||
* (mainly for images).
|
||||
*
|
||||
* @param array $rules
|
||||
* @return bool
|
||||
* @throws \Kirby\Exception\Exception
|
||||
*/
|
||||
public function match(array $rules): bool
|
||||
{
|
||||
$rules = array_change_key_case($rules);
|
||||
|
||||
if (is_array($rules['mime'] ?? null) === true) {
|
||||
$mime = $this->mime();
|
||||
|
||||
// determine if any pattern matches the MIME type;
|
||||
// once any pattern matches, `$carry` is `true` and the rest is skipped
|
||||
$matches = array_reduce(
|
||||
$rules['mime'],
|
||||
fn ($carry, $pattern) => $carry || Mime::matches($mime, $pattern),
|
||||
false
|
||||
);
|
||||
|
||||
if ($matches !== true) {
|
||||
throw new Exception([
|
||||
'key' => 'file.mime.invalid',
|
||||
'data' => compact('mime')
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
if (is_array($rules['extension'] ?? null) === true) {
|
||||
$extension = $this->extension();
|
||||
if (in_array($extension, $rules['extension']) !== true) {
|
||||
throw new Exception([
|
||||
'key' => 'file.extension.invalid',
|
||||
'data' => compact('extension')
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
if (is_array($rules['type'] ?? null) === true) {
|
||||
$type = $this->type();
|
||||
if (in_array($type, $rules['type']) !== true) {
|
||||
throw new Exception([
|
||||
'key' => 'file.type.invalid',
|
||||
'data' => compact('type')
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (static::$validations as $key => $arguments) {
|
||||
$rule = $rules[$key] ?? null;
|
||||
|
||||
if ($rule !== null) {
|
||||
$property = $arguments[0];
|
||||
$validator = $arguments[1];
|
||||
|
||||
if (V::$validator($this->$property(), $rule) === false) {
|
||||
throw new Exception([
|
||||
'key' => 'file.' . $key,
|
||||
'data' => [$property => $rule]
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Detects the mime type of the file
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function mime()
|
||||
{
|
||||
return Mime::type($this->root);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the file's last modification time
|
||||
*
|
||||
* @param string $format
|
||||
* @param string|null $handler date or strftime
|
||||
* @return mixed
|
||||
*/
|
||||
public function modified(?string $format = null, ?string $handler = null)
|
||||
{
|
||||
$kirby = $this->kirby();
|
||||
|
||||
return F::modified(
|
||||
$this->root,
|
||||
$format,
|
||||
$handler ?? ($kirby ? $kirby->option('date.handler', 'date') : 'date')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Move the file to a new location
|
||||
*
|
||||
* @param string $newRoot
|
||||
* @param bool $overwrite Force overwriting any existing files
|
||||
* @return static
|
||||
*/
|
||||
public function move(string $newRoot, bool $overwrite = false)
|
||||
{
|
||||
if (F::move($this->root, $newRoot, $overwrite) !== true) {
|
||||
throw new Exception('The file: "' . $this->root . '" could not be moved to: "' . $newRoot . '"');
|
||||
}
|
||||
|
||||
return new static($newRoot);
|
||||
}
|
||||
|
||||
/**
|
||||
* Getter for the name of the file
|
||||
* without the extension
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function name(): string
|
||||
{
|
||||
return pathinfo($this->root, PATHINFO_FILENAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the file size in a
|
||||
* human-readable format
|
||||
*
|
||||
* @param string|null|false $locale Locale for number formatting,
|
||||
* `null` for the current locale,
|
||||
* `false` to disable number formatting
|
||||
* @return string
|
||||
*/
|
||||
public function niceSize($locale = null): string
|
||||
{
|
||||
return F::niceSize($this->root, $locale);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the file content and returns it.
|
||||
*
|
||||
* @return string|false
|
||||
*/
|
||||
public function read()
|
||||
{
|
||||
return F::read($this->root);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the absolute path to the file
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function realpath(): string
|
||||
{
|
||||
return realpath($this->root);
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the name of the file without
|
||||
* touching the extension
|
||||
*
|
||||
* @param string $newName
|
||||
* @param bool $overwrite Force overwrite existing files
|
||||
* @return static
|
||||
*/
|
||||
public function rename(string $newName, bool $overwrite = false)
|
||||
{
|
||||
$newRoot = F::rename($this->root, $newName, $overwrite);
|
||||
|
||||
if ($newRoot === false) {
|
||||
throw new Exception('The file: "' . $this->root . '" could not be renamed to: "' . $newName . '"');
|
||||
}
|
||||
|
||||
return new static($newRoot);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the given file path
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function root(): ?string
|
||||
{
|
||||
return $this->root;
|
||||
}
|
||||
|
||||
/**
|
||||
* Setter for the root
|
||||
*
|
||||
* @param string|null $root
|
||||
* @return $this
|
||||
*/
|
||||
protected function setRoot(?string $root = null)
|
||||
{
|
||||
$this->root = $root;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Setter for the file url
|
||||
*
|
||||
* @param string|null $url
|
||||
* @return $this
|
||||
*/
|
||||
protected function setUrl(?string $url = null)
|
||||
{
|
||||
$this->url = $url;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the absolute url for the file
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function url(): ?string
|
||||
{
|
||||
return $this->url;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitizes the file contents depending on the file type
|
||||
* by overwriting the file with the sanitized version
|
||||
* @since 3.6.0
|
||||
*
|
||||
* @param string|bool $typeLazy Explicit sane handler type string,
|
||||
* `true` for lazy autodetection or
|
||||
* `false` for normal autodetection
|
||||
* @return void
|
||||
*
|
||||
* @throws \Kirby\Exception\InvalidArgumentException If the file didn't pass validation
|
||||
* @throws \Kirby\Exception\LogicException If more than one handler applies
|
||||
* @throws \Kirby\Exception\NotFoundException If the handler was not found
|
||||
* @throws \Kirby\Exception\Exception On other errors
|
||||
*/
|
||||
public function sanitizeContents($typeLazy = false): void
|
||||
{
|
||||
Sane::sanitizeFile($this->root(), $typeLazy);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the sha1 hash of the file
|
||||
* @since 3.6.0
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function sha1(): string
|
||||
{
|
||||
return sha1_file($this->root);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the raw size of the file
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function size(): int
|
||||
{
|
||||
return F::size($this->root);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the media object to a
|
||||
* plain PHP array
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'extension' => $this->extension(),
|
||||
'filename' => $this->filename(),
|
||||
'hash' => $this->hash(),
|
||||
'isReadable' => $this->isReadable(),
|
||||
'isResizable' => $this->isResizable(),
|
||||
'isWritable' => $this->isWritable(),
|
||||
'mime' => $this->mime(),
|
||||
'modified' => $this->modified('c'),
|
||||
'name' => $this->name(),
|
||||
'niceSize' => $this->niceSize(),
|
||||
'root' => $this->root(),
|
||||
'safeName' => F::safeName($this->name()),
|
||||
'size' => $this->size(),
|
||||
'type' => $this->type(),
|
||||
'url' => $this->url()
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the entire file array into
|
||||
* a json string
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function toJson(): string
|
||||
{
|
||||
return json_encode($this->toArray());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the file type.
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function type(): ?string
|
||||
{
|
||||
return F::type($this->root);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the file contents depending on the file type
|
||||
*
|
||||
* @param string|bool $typeLazy Explicit sane handler type string,
|
||||
* `true` for lazy autodetection or
|
||||
* `false` for normal autodetection
|
||||
* @return void
|
||||
*
|
||||
* @throws \Kirby\Exception\InvalidArgumentException If the file didn't pass validation
|
||||
* @throws \Kirby\Exception\NotFoundException If the handler was not found
|
||||
* @throws \Kirby\Exception\Exception On other errors
|
||||
*/
|
||||
public function validateContents($typeLazy = false): void
|
||||
{
|
||||
Sane::validateFile($this->root(), $typeLazy);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes content to the file
|
||||
*
|
||||
* @param string $content
|
||||
* @return bool
|
||||
*/
|
||||
public function write($content): bool
|
||||
{
|
||||
if (F::write($this->root, $content) !== true) {
|
||||
throw new Exception('The file "' . $this->root . '" could not be written');
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
307
kirby/src/Filesystem/Filename.php
Normal file
307
kirby/src/Filesystem/Filename.php
Normal file
|
@ -0,0 +1,307 @@
|
|||
<?php
|
||||
|
||||
namespace Kirby\Filesystem;
|
||||
|
||||
use Kirby\Toolkit\Str;
|
||||
|
||||
/**
|
||||
* The `Filename` class handles complex
|
||||
* mapping of file attributes (i.e for thumbnails)
|
||||
* into human readable filenames.
|
||||
*
|
||||
* ```php
|
||||
* $filename = new Filename('some-file.jpg', '{{ name }}-{{ attributes }}.{{ extension }}', [
|
||||
* 'crop' => 'top left',
|
||||
* 'width' => 300,
|
||||
* 'height' => 200
|
||||
* 'quality' => 80
|
||||
* ]);
|
||||
*
|
||||
* echo $filename->toString();
|
||||
* // result: some-file-300x200-crop-top-left-q80.jpg
|
||||
*
|
||||
* @package Kirby Filesystem
|
||||
* @author Bastian Allgeier <bastian@getkirby.com>
|
||||
* @link https://getkirby.com
|
||||
* @copyright Bastian Allgeier
|
||||
* @license https://getkirby.com/license
|
||||
*/
|
||||
class Filename
|
||||
{
|
||||
/**
|
||||
* List of all applicable attributes
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $attributes;
|
||||
|
||||
/**
|
||||
* The sanitized file extension
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $extension;
|
||||
|
||||
/**
|
||||
* The source original filename
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $filename;
|
||||
|
||||
/**
|
||||
* The sanitized file name
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $name;
|
||||
|
||||
/**
|
||||
* The template for the final name
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $template;
|
||||
|
||||
/**
|
||||
* Creates a new Filename object
|
||||
*
|
||||
* @param string $filename
|
||||
* @param string $template
|
||||
* @param array $attributes
|
||||
*/
|
||||
public function __construct(string $filename, string $template, array $attributes = [])
|
||||
{
|
||||
$this->filename = $filename;
|
||||
$this->template = $template;
|
||||
$this->attributes = $attributes;
|
||||
$this->extension = $this->sanitizeExtension(
|
||||
$attributes['format'] ??
|
||||
pathinfo($filename, PATHINFO_EXTENSION)
|
||||
);
|
||||
$this->name = $this->sanitizeName(pathinfo($filename, PATHINFO_FILENAME));
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the entire object to a string
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function __toString(): string
|
||||
{
|
||||
return $this->toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts all processed attributes
|
||||
* to an array. The array keys are already
|
||||
* the shortened versions for the filename
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function attributesToArray(): array
|
||||
{
|
||||
$array = [
|
||||
'dimensions' => implode('x', $this->dimensions()),
|
||||
'crop' => $this->crop(),
|
||||
'blur' => $this->blur(),
|
||||
'bw' => $this->grayscale(),
|
||||
'q' => $this->quality(),
|
||||
];
|
||||
|
||||
$array = array_filter(
|
||||
$array,
|
||||
fn ($item) => $item !== null && $item !== false && $item !== ''
|
||||
);
|
||||
|
||||
return $array;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts all processed attributes
|
||||
* to a string, that can be used in the
|
||||
* new filename
|
||||
*
|
||||
* @param string|null $prefix The prefix will be used in the filename creation
|
||||
* @return string
|
||||
*/
|
||||
public function attributesToString(string $prefix = null): string
|
||||
{
|
||||
$array = $this->attributesToArray();
|
||||
$result = [];
|
||||
|
||||
foreach ($array as $key => $value) {
|
||||
if ($value === true) {
|
||||
$value = '';
|
||||
}
|
||||
|
||||
switch ($key) {
|
||||
case 'dimensions':
|
||||
$result[] = $value;
|
||||
break;
|
||||
case 'crop':
|
||||
$result[] = ($value === 'center') ? 'crop' : $key . '-' . $value;
|
||||
break;
|
||||
default:
|
||||
$result[] = $key . $value;
|
||||
}
|
||||
}
|
||||
|
||||
$result = array_filter($result);
|
||||
$attributes = implode('-', $result);
|
||||
|
||||
if (empty($attributes) === true) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return $prefix . $attributes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes the blur option value
|
||||
*
|
||||
* @return false|int
|
||||
*/
|
||||
public function blur()
|
||||
{
|
||||
$value = $this->attributes['blur'] ?? false;
|
||||
|
||||
if ($value === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (int)$value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes the crop option value
|
||||
*
|
||||
* @return false|string
|
||||
*/
|
||||
public function crop()
|
||||
{
|
||||
// get the crop value
|
||||
$crop = $this->attributes['crop'] ?? false;
|
||||
|
||||
if ($crop === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return Str::slug($crop);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a normalized array
|
||||
* with width and height values
|
||||
* if available
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function dimensions()
|
||||
{
|
||||
if (empty($this->attributes['width']) === true && empty($this->attributes['height']) === true) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [
|
||||
'width' => $this->attributes['width'] ?? null,
|
||||
'height' => $this->attributes['height'] ?? null
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the sanitized extension
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function extension(): string
|
||||
{
|
||||
return $this->extension;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes the grayscale option value
|
||||
* and also the available ways to write
|
||||
* the option. You can use `grayscale`,
|
||||
* `greyscale` or simply `bw`. The function
|
||||
* will always return `grayscale`
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function grayscale(): bool
|
||||
{
|
||||
// normalize options
|
||||
$value = $this->attributes['grayscale'] ?? $this->attributes['greyscale'] ?? $this->attributes['bw'] ?? false;
|
||||
|
||||
// turn anything into boolean
|
||||
return filter_var($value, FILTER_VALIDATE_BOOLEAN);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the filename without extension
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function name(): string
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes the quality option value
|
||||
*
|
||||
* @return false|int
|
||||
*/
|
||||
public function quality()
|
||||
{
|
||||
$value = $this->attributes['quality'] ?? false;
|
||||
|
||||
if ($value === false || $value === true) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (int)$value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitizes the file extension.
|
||||
* The extension will be converted
|
||||
* to lowercase and `jpeg` will be
|
||||
* replaced with `jpg`
|
||||
*
|
||||
* @param string $extension
|
||||
* @return string
|
||||
*/
|
||||
protected function sanitizeExtension(string $extension): string
|
||||
{
|
||||
$extension = strtolower($extension);
|
||||
$extension = str_replace('jpeg', 'jpg', $extension);
|
||||
return $extension;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitizes the name with Kirby's
|
||||
* Str::slug function
|
||||
*
|
||||
* @param string $name
|
||||
* @return string
|
||||
*/
|
||||
protected function sanitizeName(string $name): string
|
||||
{
|
||||
return Str::slug($name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the converted filename as string
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function toString(): string
|
||||
{
|
||||
return Str::template($this->template, [
|
||||
'name' => $this->name(),
|
||||
'attributes' => $this->attributesToString('-'),
|
||||
'extension' => $this->extension()
|
||||
], ['fallback' => '']);
|
||||
}
|
||||
}
|
196
kirby/src/Filesystem/IsFile.php
Normal file
196
kirby/src/Filesystem/IsFile.php
Normal file
|
@ -0,0 +1,196 @@
|
|||
<?php
|
||||
|
||||
namespace Kirby\Filesystem;
|
||||
|
||||
use Kirby\Cms\App;
|
||||
use Kirby\Exception\BadMethodCallException;
|
||||
use Kirby\Image\Image;
|
||||
use Kirby\Toolkit\Properties;
|
||||
|
||||
/**
|
||||
* Trait for all objects that represent an asset file.
|
||||
* Adds `::asset()` method which returns either a
|
||||
* `Kirby\Filesystem\File` or `Kirby\Image\Image` object.
|
||||
* Proxies method calls to this object.
|
||||
* @since 3.6.0
|
||||
*
|
||||
* @package Kirby Filesystem
|
||||
* @author Nico Hoffmann <nico@getkirby.com>
|
||||
* @link https://getkirby.com
|
||||
* @copyright Bastian Allgeier
|
||||
* @license https://getkirby.com/license
|
||||
*/
|
||||
trait IsFile
|
||||
{
|
||||
use Properties;
|
||||
|
||||
/**
|
||||
* File asset object
|
||||
*
|
||||
* @var \Kirby\Filesystem\File
|
||||
*/
|
||||
protected $asset;
|
||||
|
||||
/**
|
||||
* Absolute file path
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected $root;
|
||||
|
||||
/**
|
||||
* Absolute file URL
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected $url;
|
||||
|
||||
/**
|
||||
* Constructor sets all file properties
|
||||
*
|
||||
* @param array $props
|
||||
*/
|
||||
public function __construct(array $props)
|
||||
{
|
||||
$this->setProperties($props);
|
||||
}
|
||||
|
||||
/**
|
||||
* Magic caller for asset methods
|
||||
*
|
||||
* @param string $method
|
||||
* @param array $arguments
|
||||
* @return mixed
|
||||
* @throws \Kirby\Exception\BadMethodCallException
|
||||
*/
|
||||
public function __call(string $method, array $arguments = [])
|
||||
{
|
||||
// public property access
|
||||
if (isset($this->$method) === true) {
|
||||
return $this->$method;
|
||||
}
|
||||
|
||||
// asset method proxy
|
||||
if (method_exists($this->asset(), $method)) {
|
||||
return $this->asset()->$method(...$arguments);
|
||||
}
|
||||
|
||||
throw new BadMethodCallException('The method: "' . $method . '" does not exist');
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the asset to a string
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function __toString(): string
|
||||
{
|
||||
return (string)$this->asset();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the file asset object
|
||||
*
|
||||
* @param array|string|null $props
|
||||
* @return \Kirby\Filesystem\File
|
||||
*/
|
||||
public function asset($props = null)
|
||||
{
|
||||
if ($this->asset !== null) {
|
||||
return $this->asset;
|
||||
}
|
||||
|
||||
$props = $props ?? [
|
||||
'root' => $this->root(),
|
||||
'url' => $this->url()
|
||||
];
|
||||
|
||||
switch ($this->type()) {
|
||||
case 'image':
|
||||
return $this->asset = new Image($props);
|
||||
default:
|
||||
return $this->asset = new File($props);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the file exists on disk
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function exists(): bool
|
||||
{
|
||||
// Important to include this in the trait
|
||||
// to avoid infinite loops when trying
|
||||
// to proxy the method from the asset object
|
||||
return file_exists($this->root()) === true;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the app instance
|
||||
*
|
||||
* @return \Kirby\Cms\App
|
||||
*/
|
||||
public function kirby()
|
||||
{
|
||||
return App::instance();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the given file path
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function root(): ?string
|
||||
{
|
||||
return $this->root;
|
||||
}
|
||||
|
||||
/**
|
||||
* Setter for the root
|
||||
*
|
||||
* @param string|null $root
|
||||
* @return $this
|
||||
*/
|
||||
protected function setRoot(?string $root = null)
|
||||
{
|
||||
$this->root = $root;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Setter for the file url
|
||||
*
|
||||
* @param string|null $url
|
||||
* @return $this
|
||||
*/
|
||||
protected function setUrl(?string $url = null)
|
||||
{
|
||||
$this->url = $url;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the file type
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function type(): ?string
|
||||
{
|
||||
// Important to include this in the trait
|
||||
// to avoid infinite loops when trying
|
||||
// to proxy the method from the asset object
|
||||
return F::type($this->root() ?? $this->url());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the absolute url for the file
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function url(): ?string
|
||||
{
|
||||
return $this->url;
|
||||
}
|
||||
}
|
343
kirby/src/Filesystem/Mime.php
Normal file
343
kirby/src/Filesystem/Mime.php
Normal file
|
@ -0,0 +1,343 @@
|
|||
<?php
|
||||
|
||||
namespace Kirby\Filesystem;
|
||||
|
||||
use Kirby\Toolkit\Str;
|
||||
use SimpleXMLElement;
|
||||
|
||||
/**
|
||||
* The `Mime` class provides method
|
||||
* for MIME type detection or guessing
|
||||
* from different criteria like
|
||||
* extensions etc.
|
||||
*
|
||||
* @package Kirby Filesystem
|
||||
* @author Bastian Allgeier <bastian@getkirby.com>
|
||||
* @link https://getkirby.com
|
||||
* @copyright Bastian Allgeier
|
||||
* @license https://opensource.org/licenses/MIT
|
||||
*/
|
||||
class Mime
|
||||
{
|
||||
/**
|
||||
* Extension to MIME type map
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $types = [
|
||||
'ai' => 'application/postscript',
|
||||
'aif' => 'audio/x-aiff',
|
||||
'aifc' => 'audio/x-aiff',
|
||||
'aiff' => 'audio/x-aiff',
|
||||
'avi' => 'video/x-msvideo',
|
||||
'avif' => 'image/avif',
|
||||
'bmp' => 'image/bmp',
|
||||
'css' => 'text/css',
|
||||
'csv' => ['text/csv', 'text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream'],
|
||||
'doc' => 'application/msword',
|
||||
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
|
||||
'dvi' => 'application/x-dvi',
|
||||
'eml' => 'message/rfc822',
|
||||
'eps' => 'application/postscript',
|
||||
'exe' => ['application/octet-stream', 'application/x-msdownload'],
|
||||
'gif' => 'image/gif',
|
||||
'gtar' => 'application/x-gtar',
|
||||
'gz' => 'application/x-gzip',
|
||||
'htm' => 'text/html',
|
||||
'html' => 'text/html',
|
||||
'ico' => 'image/x-icon',
|
||||
'ics' => 'text/calendar',
|
||||
'js' => ['application/javascript', 'application/x-javascript'],
|
||||
'json' => ['application/json', 'text/json'],
|
||||
'j2k' => ['image/jp2'],
|
||||
'jp2' => ['image/jp2'],
|
||||
'jpg' => ['image/jpeg', 'image/pjpeg'],
|
||||
'jpeg' => ['image/jpeg', 'image/pjpeg'],
|
||||
'jpe' => ['image/jpeg', 'image/pjpeg'],
|
||||
'log' => ['text/plain', 'text/x-log'],
|
||||
'm4a' => 'audio/mp4',
|
||||
'm4v' => 'video/mp4',
|
||||
'mid' => 'audio/midi',
|
||||
'midi' => 'audio/midi',
|
||||
'mif' => 'application/vnd.mif',
|
||||
'mov' => 'video/quicktime',
|
||||
'movie' => 'video/x-sgi-movie',
|
||||
'mp2' => 'audio/mpeg',
|
||||
'mp3' => ['audio/mpeg', 'audio/mpg', 'audio/mpeg3', 'audio/mp3'],
|
||||
'mp4' => 'video/mp4',
|
||||
'mpe' => 'video/mpeg',
|
||||
'mpeg' => 'video/mpeg',
|
||||
'mpg' => 'video/mpeg',
|
||||
'mpga' => 'audio/mpeg',
|
||||
'odc' => 'application/vnd.oasis.opendocument.chart',
|
||||
'odp' => 'application/vnd.oasis.opendocument.presentation',
|
||||
'odt' => 'application/vnd.oasis.opendocument.text',
|
||||
'pdf' => ['application/pdf', 'application/x-download'],
|
||||
'php' => ['text/php', 'text/x-php', 'application/x-httpd-php', 'application/php', 'application/x-php', 'application/x-httpd-php-source'],
|
||||
'php3' => ['text/php', 'text/x-php', 'application/x-httpd-php', 'application/php', 'application/x-php', 'application/x-httpd-php-source'],
|
||||
'phps' => ['text/php', 'text/x-php', 'application/x-httpd-php', 'application/php', 'application/x-php', 'application/x-httpd-php-source'],
|
||||
'phtml' => ['text/php', 'text/x-php', 'application/x-httpd-php', 'application/php', 'application/x-php', 'application/x-httpd-php-source'],
|
||||
'png' => 'image/png',
|
||||
'ppt' => ['application/powerpoint', 'application/vnd.ms-powerpoint'],
|
||||
'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
||||
'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
|
||||
'ps' => 'application/postscript',
|
||||
'psd' => 'application/x-photoshop',
|
||||
'qt' => 'video/quicktime',
|
||||
'rss' => 'application/rss+xml',
|
||||
'rtf' => 'text/rtf',
|
||||
'rtx' => 'text/richtext',
|
||||
'shtml' => 'text/html',
|
||||
'svg' => 'image/svg+xml',
|
||||
'swf' => 'application/x-shockwave-flash',
|
||||
'tar' => 'application/x-tar',
|
||||
'text' => 'text/plain',
|
||||
'txt' => 'text/plain',
|
||||
'tgz' => ['application/x-tar', 'application/x-gzip-compressed'],
|
||||
'tif' => 'image/tiff',
|
||||
'tiff' => 'image/tiff',
|
||||
'wav' => 'audio/x-wav',
|
||||
'wbxml' => 'application/wbxml',
|
||||
'webm' => 'video/webm',
|
||||
'webp' => 'image/webp',
|
||||
'word' => ['application/msword', 'application/octet-stream'],
|
||||
'xhtml' => 'application/xhtml+xml',
|
||||
'xht' => 'application/xhtml+xml',
|
||||
'xml' => 'text/xml',
|
||||
'xl' => 'application/excel',
|
||||
'xls' => ['application/excel', 'application/vnd.ms-excel', 'application/msexcel'],
|
||||
'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
|
||||
'xsl' => 'text/xml',
|
||||
'yaml' => ['application/yaml', 'text/yaml'],
|
||||
'yml' => ['application/yaml', 'text/yaml'],
|
||||
'zip' => ['application/x-zip', 'application/zip', 'application/x-zip-compressed'],
|
||||
];
|
||||
|
||||
/**
|
||||
* Fixes an invalid MIME type guess for the given file
|
||||
*
|
||||
* @param string $file
|
||||
* @param string $mime
|
||||
* @param string $extension
|
||||
* @return string|null
|
||||
*/
|
||||
public static function fix(string $file, string $mime = null, string $extension = null)
|
||||
{
|
||||
// fixing map
|
||||
$map = [
|
||||
'text/html' => [
|
||||
'svg' => ['Kirby\Filesystem\Mime', 'fromSvg'],
|
||||
],
|
||||
'text/plain' => [
|
||||
'css' => 'text/css',
|
||||
'json' => 'application/json',
|
||||
'svg' => ['Kirby\Filesystem\Mime', 'fromSvg'],
|
||||
],
|
||||
'text/x-asm' => [
|
||||
'css' => 'text/css'
|
||||
],
|
||||
'image/svg' => [
|
||||
'svg' => 'image/svg+xml'
|
||||
]
|
||||
];
|
||||
|
||||
if ($mode = ($map[$mime][$extension] ?? null)) {
|
||||
if (is_callable($mode) === true) {
|
||||
return $mode($file, $mime, $extension);
|
||||
}
|
||||
|
||||
if (is_string($mode) === true) {
|
||||
return $mode;
|
||||
}
|
||||
}
|
||||
|
||||
return $mime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Guesses a MIME type by extension
|
||||
*
|
||||
* @param string $extension
|
||||
* @return string|null
|
||||
*/
|
||||
public static function fromExtension(string $extension): ?string
|
||||
{
|
||||
$mime = static::$types[$extension] ?? null;
|
||||
return is_array($mime) === true ? array_shift($mime) : $mime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the MIME type of a file
|
||||
*
|
||||
* @param string $file
|
||||
* @return string|false
|
||||
*/
|
||||
public static function fromFileInfo(string $file)
|
||||
{
|
||||
if (function_exists('finfo_file') === true && file_exists($file) === true) {
|
||||
$finfo = finfo_open(FILEINFO_MIME_TYPE);
|
||||
$mime = finfo_file($finfo, $file);
|
||||
finfo_close($finfo);
|
||||
return $mime;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the MIME type of a file
|
||||
*
|
||||
* @param string $file
|
||||
* @return string|false
|
||||
*/
|
||||
public static function fromMimeContentType(string $file)
|
||||
{
|
||||
if (function_exists('mime_content_type') === true && file_exists($file) === true) {
|
||||
return mime_content_type($file);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to detect a valid SVG and returns the MIME type accordingly
|
||||
*
|
||||
* @param string $file
|
||||
* @return string|false
|
||||
*/
|
||||
public static function fromSvg(string $file)
|
||||
{
|
||||
if (file_exists($file) === true) {
|
||||
libxml_use_internal_errors(true);
|
||||
|
||||
$svg = new SimpleXMLElement(file_get_contents($file));
|
||||
|
||||
if ($svg !== false && $svg->getName() === 'svg') {
|
||||
return 'image/svg+xml';
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if a given MIME type is matched by an `Accept` header
|
||||
* pattern; returns true if the MIME type is contained at all
|
||||
*
|
||||
* @param string $mime
|
||||
* @param string $pattern
|
||||
* @return bool
|
||||
*/
|
||||
public static function isAccepted(string $mime, string $pattern): bool
|
||||
{
|
||||
$accepted = Str::accepted($pattern);
|
||||
|
||||
foreach ($accepted as $m) {
|
||||
if (static::matches($mime, $m['value']) === true) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if a MIME wildcard pattern from an `Accept` header
|
||||
* matches a given type
|
||||
* @since 3.3.0
|
||||
*
|
||||
* @param string $test
|
||||
* @param string $wildcard
|
||||
* @return bool
|
||||
*/
|
||||
public static function matches(string $test, string $wildcard): bool
|
||||
{
|
||||
return fnmatch($wildcard, $test, FNM_PATHNAME) === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the extension for a given MIME type
|
||||
*
|
||||
* @param string|null $mime
|
||||
* @return string|false
|
||||
*/
|
||||
public static function toExtension(string $mime = null)
|
||||
{
|
||||
foreach (static::$types as $key => $value) {
|
||||
if (is_array($value) === true && in_array($mime, $value) === true) {
|
||||
return $key;
|
||||
}
|
||||
|
||||
if ($value === $mime) {
|
||||
return $key;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all available extensions for a given MIME type
|
||||
*
|
||||
* @param string|null $mime
|
||||
* @return array
|
||||
*/
|
||||
public static function toExtensions(string $mime = null): array
|
||||
{
|
||||
$extensions = [];
|
||||
|
||||
foreach (static::$types as $key => $value) {
|
||||
if (is_array($value) === true && in_array($mime, $value) === true) {
|
||||
$extensions[] = $key;
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($value === $mime) {
|
||||
$extensions[] = $key;
|
||||
}
|
||||
}
|
||||
|
||||
return $extensions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the MIME type of a file
|
||||
*
|
||||
* @param string $file
|
||||
* @param string $extension
|
||||
* @return string|false
|
||||
*/
|
||||
public static function type(string $file, string $extension = null)
|
||||
{
|
||||
// use the standard finfo extension
|
||||
$mime = static::fromFileInfo($file);
|
||||
|
||||
// use the mime_content_type function
|
||||
if ($mime === false) {
|
||||
$mime = static::fromMimeContentType($file);
|
||||
}
|
||||
|
||||
// get the extension or extract it from the filename
|
||||
$extension ??= F::extension($file);
|
||||
|
||||
// try to guess the mime type at least
|
||||
if ($mime === false) {
|
||||
$mime = static::fromExtension($extension);
|
||||
}
|
||||
|
||||
// fix broken mime detection
|
||||
return static::fix($file, $mime, $extension);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all detectable MIME types
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function types(): array
|
||||
{
|
||||
return static::$types;
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue