File system helper.
Method DetailsDefined in: yii\helpers\BaseFileHelper::changeOwnership()
Changes the Unix user and/or group ownership of a file or directory, and optionally the mode.
Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem. Note: On Windows, this function fails silently when applied on a regular file.
public static void changeOwnership ( $path, $ownership, $mode = null ) $path stringThe path to the file or directory.
$ownership string|array|integer|nullThe user and/or group ownership for the file or directory. When $ownership is a string, the format is 'user:group' where both are optional. E.g. 'user' or 'user:' will only change the user, ':group' will only change the group, 'user:group' will change both. When $owners is an index array the format is [0 => user, 1 => group], e.g. [$myUser, $myGroup]
. It is also possible to pass an associative array, e.g. ['user' => $myUser, 'group' => $myGroup]. In case $owners is an integer it will be used as user id. If null
, an empty array or an empty string is passed, the ownership will not be changed.
The permission to be set for the file or directory. If null
is passed, the mode will not be changed.
public static function changeOwnership($path, $ownership, $mode = null)
{
if (!file_exists((string)$path)) {
throw new InvalidArgumentException('Unable to change ownership, "' . $path . '" is not a file or directory.');
}
if (empty($ownership) && $ownership !== 0 && $mode === null) {
return;
}
$user = $group = null;
if (!empty($ownership) || $ownership === 0 || $ownership === '0') {
if (is_int($ownership)) {
$user = $ownership;
} elseif (is_string($ownership)) {
$ownerParts = explode(':', $ownership);
$user = $ownerParts[0];
if (count($ownerParts) > 1) {
$group = $ownerParts[1];
}
} elseif (is_array($ownership)) {
$ownershipIsIndexed = ArrayHelper::isIndexed($ownership);
$user = ArrayHelper::getValue($ownership, $ownershipIsIndexed ? 0 : 'user');
$group = ArrayHelper::getValue($ownership, $ownershipIsIndexed ? 1 : 'group');
} else {
throw new InvalidArgumentException('$ownership must be an integer, string, array, or null.');
}
}
if ($mode !== null) {
if (!is_int($mode)) {
throw new InvalidArgumentException('$mode must be an integer or null.');
}
if (!chmod($path, $mode)) {
throw new Exception('Unable to change mode of "' . $path . '" to "0' . decoct($mode) . '".');
}
}
if ($user !== null && $user !== '') {
if (is_numeric($user)) {
$user = (int) $user;
} elseif (!is_string($user)) {
throw new InvalidArgumentException('The user part of $ownership must be an integer, string, or null.');
}
if (!chown($path, $user)) {
throw new Exception('Unable to change user ownership of "' . $path . '" to "' . $user . '".');
}
}
if ($group !== null && $group !== '') {
if (is_numeric($group)) {
$group = (int) $group;
} elseif (!is_string($group)) {
throw new InvalidArgumentException('The group part of $ownership must be an integer, string or null.');
}
if (!chgrp($path, $group)) {
throw new Exception('Unable to change group ownership of "' . $path . '" to "' . $group . '".');
}
}
}
public static void copyDirectory ( $src, $dst, $options = [] ) $src string
The source directory
$dst stringThe destination directory
$options arrayOptions for directory copy. Valid options are:
filter: callback, a PHP callback that is called for each directory or file. The signature of the callback should be: function ($path)
, where $path
refers the full path to be filtered. The callback can return one of the following values:
function ($from, $to)
, where $from
is the sub-directory or file to be copied from, while $to
is the copy target.function ($from, $to)
, where $from
is the sub-directory or file copied from, while $to
is the copy target.only
or except
. Defaults to true. This option is available since version 2.0.12. Before 2.0.12 empty directories are always copied.if unable to open directory
public static function copyDirectory($src, $dst, $options = [])
{
$src = static::normalizePath($src);
$dst = static::normalizePath($dst);
if ($src === $dst || strpos($dst, $src . DIRECTORY_SEPARATOR) === 0) {
throw new InvalidArgumentException('Trying to copy a directory to itself or a subdirectory.');
}
$dstExists = is_dir($dst);
if (!$dstExists && (!isset($options['copyEmptyDirectories']) || $options['copyEmptyDirectories'])) {
static::createDirectory($dst, isset($options['dirMode']) ? $options['dirMode'] : 0775, true);
$dstExists = true;
}
$handle = opendir($src);
if ($handle === false) {
throw new InvalidArgumentException("Unable to open directory: $src");
}
if (!isset($options['basePath'])) {
$options['basePath'] = realpath($src);
$options = static::normalizeOptions($options);
}
while (($file = readdir($handle)) !== false) {
if ($file === '.' || $file === '..') {
continue;
}
$from = $src . DIRECTORY_SEPARATOR . $file;
$to = $dst . DIRECTORY_SEPARATOR . $file;
if (static::filterPath($from, $options)) {
if (isset($options['beforeCopy']) && !call_user_func($options['beforeCopy'], $from, $to)) {
continue;
}
if (is_file($from)) {
if (!$dstExists) {
static::createDirectory($dst, isset($options['dirMode']) ? $options['dirMode'] : 0775, true);
$dstExists = true;
}
copy($from, $to);
if (isset($options['fileMode'])) {
@chmod($to, $options['fileMode']);
}
} else {
if (!isset($options['recursive']) || $options['recursive']) {
static::copyDirectory($from, $to, $options);
}
}
if (isset($options['afterCopy'])) {
call_user_func($options['afterCopy'], $from, $to);
}
}
}
closedir($handle);
}
Defined in: yii\helpers\BaseFileHelper::createDirectory()
Creates a new directory.
This method is similar to the PHP mkdir()
function except that it uses chmod()
to set the permission of the created directory in order to avoid the impact of the umask
setting.
Path of the directory to be created.
$mode integerThe permission to be set for the created directory.
$recursive booleanWhether to create parent directories if they do not exist.
return booleanWhether the directory is created successfully
throws yii\base\Exceptionif the directory could not be created (i.e. php error due to parallel changes)
public static function createDirectory($path, $mode = 0775, $recursive = true)
{
if (is_dir($path)) {
return true;
}
$parentDir = dirname($path);
if ($recursive && !is_dir($parentDir) && $parentDir !== $path) {
static::createDirectory($parentDir, $mode, true);
}
try {
if (!mkdir($path, $mode)) {
return false;
}
} catch (\Exception $e) {
if (!is_dir($path)) {
throw new \yii\base\Exception("Failed to create directory \"$path\": " . $e->getMessage(), $e->getCode(), $e);
}
}
try {
return chmod($path, $mode);
} catch (\Exception $e) {
throw new \yii\base\Exception("Failed to change permissions for directory \"$path\": " . $e->getMessage(), $e->getCode(), $e);
}
}
public static boolean filterPath ( $path, $options ) $path string
The path of the file or directory to be checked
$options arrayThe filtering options. See findFiles() for explanations of the supported options.
return booleanWhether the file or directory satisfies the filtering options.
public static function filterPath($path, $options)
{
if (isset($options['filter'])) {
$result = call_user_func($options['filter'], $path);
if (is_bool($result)) {
return $result;
}
}
if (empty($options['except']) && empty($options['only'])) {
return true;
}
$path = str_replace('\\', '/', $path);
if (
!empty($options['except'])
&& ($except = self::lastExcludeMatchingFromList($options['basePath'], $path, $options['except'])) !== null
) {
return $except['flags'] & self::PATTERN_NEGATIVE;
}
if (!empty($options['only']) && !is_dir($path)) {
return self::lastExcludeMatchingFromList($options['basePath'], $path, $options['only']) !== null;
}
return true;
}
public static array findDirectories ( $dir, $options = [] ) $dir string
The directory under which the files will be looked for.
$options arrayOptions for directory searching. Valid options are:
filter
: callback, a PHP callback that is called for each directory or file. The signature of the callback should be: function (string $path): bool
, where $path
refers the full path to be filtered. The callback can return one of the following values:
true
: the directory will be returnedfalse
: the directory will NOT be returnedrecursive
: boolean, whether the files under the subdirectories should also be looked for. Defaults to true
. See findFiles() for more options.
Directories found under the directory, in no particular order. Ordering depends on the files system used.
throws yii\base\InvalidArgumentExceptionif the dir is invalid.
public static function findDirectories($dir, $options = [])
{
$dir = self::clearDir($dir);
$options = self::setBasePath($dir, $options);
$list = [];
$handle = self::openDir($dir);
while (($file = readdir($handle)) !== false) {
if ($file === '.' || $file === '..') {
continue;
}
$path = $dir . DIRECTORY_SEPARATOR . $file;
if (is_dir($path) && static::filterPath($path, $options)) {
$list[] = $path;
if (!isset($options['recursive']) || $options['recursive']) {
$list = array_merge($list, static::findDirectories($path, $options));
}
}
}
closedir($handle);
return $list;
}
public static array findFiles ( $dir, $options = [] ) $dir string
The directory under which the files will be looked for.
$options arrayOptions for file searching. Valid options are:
filter
: callback, a PHP callback that is called for each directory or file. The signature of the callback should be: function ($path)
, where $path
refers the full path to be filtered. The callback can return one of the following values:
true
: the directory or file will be returned (the only
and except
options will be ignored)false
: the directory or file will NOT be returned (the only
and except
options will be ignored)null
: the only
and except
options will determine whether the directory or file should be returnedexcept
: array, list of patterns excluding from the results matching file or directory paths. Patterns ending with slash ('/') apply to directory paths only, and patterns not ending with '/' apply to file paths only. For example, '/a/b' matches all file paths ending with '/a/b'; and .svn/
matches directory paths ending with .svn
. If the pattern does not contain a slash (/
), it is treated as a shell glob pattern and checked for a match against the pathname relative to $dir
. Otherwise, the pattern is treated as a shell glob suitable for consumption by fnmatch(3)
with the FNM_PATHNAME
flag: wildcards in the pattern will not match a /
in the pathname. For example, views/*.php
matches views/index.php
but not views/controller/index.php
. A leading slash matches the beginning of the pathname. For example, /*.php
matches index.php
but not views/start/index.php
. An optional prefix !
which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources. Put a backslash (\
) in front of the first !
for patterns that begin with a literal !
, for example, \!important!.txt
. Note, the '/' characters in a pattern matches both '/' and '\' in the paths. You can find more details about the gitignore pattern format here.only
: array, list of patterns that the file paths should match if they are to be returned. Directory paths are not checked against them. Same pattern matching rules as in the except
option are used. If a file path matches a pattern in both only
and except
, it will NOT be returned.caseSensitive
: boolean, whether patterns specified at only
or except
should be case sensitive. Defaults to true
.recursive
: boolean, whether the files under the subdirectories should also be looked for. Defaults to true
.Files found under the directory, in no particular order. Ordering depends on the files system used.
throws yii\base\InvalidArgumentExceptionif the dir is invalid.
public static function findFiles($dir, $options = [])
{
$dir = self::clearDir($dir);
$options = self::setBasePath($dir, $options);
$list = [];
$handle = self::openDir($dir);
while (($file = readdir($handle)) !== false) {
if ($file === '.' || $file === '..') {
continue;
}
$path = $dir . DIRECTORY_SEPARATOR . $file;
if (static::filterPath($path, $options)) {
if (is_file($path)) {
$list[] = $path;
} elseif (is_dir($path) && (!isset($options['recursive']) || $options['recursive'])) {
$list = array_merge($list, static::findFiles($path, $options));
}
}
}
closedir($handle);
return $list;
}
public static string|null getExtensionByMimeType ( $mimeType, $preferShort = false, $magicFile = null ) $mimeType string
File MIME type.
$preferShort booleanReturn an extension with a maximum of 3 characters.
$magicFile string|nullThe path (or alias) of the file that contains all available MIME type information. If this is not set, the file specified by $mimeMagicFile will be used.
return string|nullThe extensions corresponding to the specified MIME type
public static function getExtensionByMimeType($mimeType, $preferShort = false, $magicFile = null)
{
$aliases = static::loadMimeAliases(static::$mimeAliasesFile);
if (isset($aliases[$mimeType])) {
$mimeType = $aliases[$mimeType];
}
$mimeExtensions = static::loadMimeExtensions($magicFile);
if (!array_key_exists($mimeType, $mimeExtensions)) {
return null;
}
$extensions = $mimeExtensions[$mimeType];
if (is_array($extensions)) {
if ($preferShort) {
foreach ($extensions as $extension) {
if (mb_strlen($extension, 'UTF-8') <= 3) {
return $extension;
}
}
}
return $extensions[0];
} else {
return $extensions;
}
}
public static array getExtensionsByMimeType ( $mimeType, $magicFile = null ) $mimeType string
File MIME type.
$magicFile string|nullThe path (or alias) of the file that contains all available MIME type information. If this is not set, the file specified by $mimeMagicFile will be used.
return arrayThe extensions corresponding to the specified MIME type
public static function getExtensionsByMimeType($mimeType, $magicFile = null)
{
$aliases = static::loadMimeAliases(static::$mimeAliasesFile);
if (isset($aliases[$mimeType])) {
$mimeType = $aliases[$mimeType];
}
$mimeTypes = static::loadMimeTypes($magicFile);
return array_keys($mimeTypes, mb_strtolower($mimeType, 'UTF-8'), true);
}
public static string|null getMimeType ( $file, $magicFile = null, $checkExtension = true ) $file string
The file name.
$magicFile string|nullName of the optional magic database file (or alias), usually something like /path/to/magic.mime
. This will be passed as the second parameter to finfo_open() when the fileinfo
extension is installed. If the MIME type is being determined based via getMimeTypeByExtension() and this is null, it will use the file specified by $mimeMagicFile.
Whether to use the file extension to determine the MIME type in case finfo_open()
cannot determine it.
The MIME type (e.g. text/plain
). Null is returned if the MIME type cannot be determined.
when the fileinfo
PHP extension is not installed and $checkExtension
is false
.
public static function getMimeType($file, $magicFile = null, $checkExtension = true)
{
if ($magicFile !== null) {
$magicFile = Yii::getAlias($magicFile);
}
if (!extension_loaded('fileinfo')) {
if ($checkExtension) {
return static::getMimeTypeByExtension($file, $magicFile);
}
throw new InvalidConfigException('The fileinfo PHP extension is not installed.');
}
$info = finfo_open(FILEINFO_MIME_TYPE, $magicFile);
if ($info) {
$result = finfo_file($info, $file);
finfo_close($info);
if ($result !== false) {
return $result;
}
}
return $checkExtension ? static::getMimeTypeByExtension($file, $magicFile) : null;
}
public static string|null getMimeTypeByExtension ( $file, $magicFile = null ) $file string
The file name.
$magicFile string|nullThe path (or alias) of the file that contains all available MIME type information. If this is not set, the file specified by $mimeMagicFile will be used.
return string|nullThe MIME type. Null is returned if the MIME type cannot be determined.
public static function getMimeTypeByExtension($file, $magicFile = null)
{
$mimeTypes = static::loadMimeTypes($magicFile);
if (($ext = pathinfo($file, PATHINFO_EXTENSION)) !== '') {
$ext = strtolower($ext);
if (isset($mimeTypes[$ext])) {
return $mimeTypes[$ext];
}
}
return null;
}
protected static array loadMimeAliases ( $aliasesFile ) $aliasesFile string|null
The path (or alias) of the file that contains MIME type aliases. If this is not set, the file specified by $mimeAliasesFile will be used.
return arrayThe mapping from file extensions to MIME types
protected static function loadMimeAliases($aliasesFile)
{
if ($aliasesFile === null) {
$aliasesFile = static::$mimeAliasesFile;
}
$aliasesFile = Yii::getAlias($aliasesFile);
if (!isset(self::$_mimeAliases[$aliasesFile])) {
self::$_mimeAliases[$aliasesFile] = require $aliasesFile;
}
return self::$_mimeAliases[$aliasesFile];
}
protected static array loadMimeExtensions ( $extensionsFile ) $extensionsFile string|null
The path (or alias) of the file that contains MIME type aliases. If this is not set, the file specified by $mimeAliasesFile will be used.
return arrayThe mapping from file extensions to MIME types
protected static function loadMimeExtensions($extensionsFile)
{
if ($extensionsFile === null) {
$extensionsFile = static::$mimeExtensionsFile;
}
$extensionsFile = Yii::getAlias($extensionsFile);
if (!isset(self::$_mimeExtensions[$extensionsFile])) {
self::$_mimeExtensions[$extensionsFile] = require $extensionsFile;
}
return self::$_mimeExtensions[$extensionsFile];
}
protected static array loadMimeTypes ( $magicFile ) $magicFile string|null
The path (or alias) of the file that contains all available MIME type information. If this is not set, the file specified by $mimeMagicFile will be used.
return arrayThe mapping from file extensions to MIME types
protected static function loadMimeTypes($magicFile)
{
if ($magicFile === null) {
$magicFile = static::$mimeMagicFile;
}
$magicFile = Yii::getAlias($magicFile);
if (!isset(self::$_mimeTypes[$magicFile])) {
self::$_mimeTypes[$magicFile] = require $magicFile;
}
return self::$_mimeTypes[$magicFile];
}
Defined in: yii\helpers\BaseFileHelper::localize()
Returns the localized version of a specified file.
The searching is based on the specified language code. In particular, a file with the same name will be looked for under the subdirectory whose name is the same as the language code. For example, given the file "path/to/view.php" and language code "zh-CN", the localized file will be looked for as "path/to/zh-CN/view.php". If the file is not found, it will try a fallback with just a language code that is "zh" i.e. "path/to/zh/view.php". If it is not found as well the original file will be returned.
If the target and the source language codes are the same, the original file will be returned.
public static string localize ( $file, $language = null, $sourceLanguage = null ) $file stringThe original file
$language string|nullThe target language that the file should be localized to. If not set, the value of yii\base\Application::$language will be used.
$sourceLanguage string|nullThe language that the original file is in. If not set, the value of yii\base\Application::$sourceLanguage will be used.
return stringThe matching localized file, or the original file if the localized version is not found. If the target and the source language codes are the same, the original file will be returned.
public static function localize($file, $language = null, $sourceLanguage = null)
{
if ($language === null) {
$language = Yii::$app->language;
}
if ($sourceLanguage === null) {
$sourceLanguage = Yii::$app->sourceLanguage;
}
if ($language === $sourceLanguage) {
return $file;
}
$desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . basename($file);
if (is_file($desiredFile)) {
return $desiredFile;
}
$language = substr($language, 0, 2);
if ($language === $sourceLanguage) {
return $file;
}
$desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . basename($file);
return is_file($desiredFile) ? $desiredFile : $file;
}
protected static function normalizeOptions(array $options)
{
if (!array_key_exists('caseSensitive', $options)) {
$options['caseSensitive'] = true;
}
if (isset($options['except'])) {
foreach ($options['except'] as $key => $value) {
if (is_string($value)) {
$options['except'][$key] = self::parseExcludePattern($value, $options['caseSensitive']);
}
}
}
if (isset($options['only'])) {
foreach ($options['only'] as $key => $value) {
if (is_string($value)) {
$options['only'][$key] = self::parseExcludePattern($value, $options['caseSensitive']);
}
}
}
return $options;
}
Defined in: yii\helpers\BaseFileHelper::normalizePath()
Normalizes a file/directory path.
The normalization does the following work:
DIRECTORY_SEPARATOR
(e.g. "\a/b\c" becomes "/a/b/c")Note: For registered stream wrappers, the consecutive slashes rule and ".."/"." translations are skipped.
public static string normalizePath ( $path, $ds = DIRECTORY_SEPARATOR ) $path stringThe file/directory path to be normalized
$ds stringThe directory separator to be used in the normalized result. Defaults to DIRECTORY_SEPARATOR
.
The normalized file/directory path
public static function normalizePath($path, $ds = DIRECTORY_SEPARATOR)
{
$path = rtrim(strtr($path, '/\\', $ds . $ds), $ds);
if (strpos($ds . $path, "{$ds}.") === false && strpos($path, "{$ds}{$ds}") === false) {
return $path;
}
foreach (stream_get_wrappers() as $protocol) {
if (strpos($path, "{$protocol}://") === 0) {
return $path;
}
}
if (strpos($path, "{$ds}{$ds}") === 0 && $ds == '\\') {
$parts = [$ds];
} else {
$parts = [];
}
foreach (explode($ds, $path) as $part) {
if ($part === '..' && !empty($parts) && end($parts) !== '..') {
array_pop($parts);
} elseif ($part === '.' || $part === '' && !empty($parts)) {
continue;
} else {
$parts[] = $part;
}
}
$path = implode($ds, $parts);
return $path === '' ? '.' : $path;
}
public static void removeDirectory ( $dir, $options = [] ) $dir string
The directory to be deleted recursively.
$options arrayOptions for directory remove. Valid options are:
false
, meaning the content of the symlinked directory would not be deleted. Only symlink would be removed in that default case.in case of failure
public static function removeDirectory($dir, $options = [])
{
if (!is_dir($dir)) {
return;
}
if (!empty($options['traverseSymlinks']) || !is_link($dir)) {
if (!($handle = opendir($dir))) {
return;
}
while (($file = readdir($handle)) !== false) {
if ($file === '.' || $file === '..') {
continue;
}
$path = $dir . DIRECTORY_SEPARATOR . $file;
if (is_dir($path)) {
static::removeDirectory($path, $options);
} else {
static::unlink($path);
}
}
closedir($handle);
}
if (is_link($dir)) {
static::unlink($dir);
} else {
rmdir($dir);
}
}
public static function unlink($path)
{
$isWindows = DIRECTORY_SEPARATOR === '\\';
if (!$isWindows) {
return unlink($path);
}
if (is_link($path) && is_dir($path)) {
return rmdir($path);
}
try {
return unlink($path);
} catch (ErrorException $e) {
if (is_dir($path) && count(static::findFiles($path)) !== 0) {
return false;
}
if (function_exists('exec') && file_exists($path)) {
exec('DEL /F/Q ' . escapeshellarg($path));
return !file_exists($path);
}
return false;
}
}
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4