1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027 |
- <?php
- namespace yii\helpers;
- use Yii;
- use yii\base\ErrorException;
- use yii\base\Exception;
- use yii\base\InvalidArgumentException;
- use yii\base\InvalidConfigException;
- class BaseFileHelper
- {
- const PATTERN_NODIR = 1;
- const PATTERN_ENDSWITH = 4;
- const PATTERN_MUSTBEDIR = 8;
- const PATTERN_NEGATIVE = 16;
- const PATTERN_CASE_INSENSITIVE = 32;
-
- public static $mimeMagicFile = '@yii/helpers/mimeTypes.php';
-
- public static $mimeAliasesFile = '@yii/helpers/mimeAliases.php';
-
- public static $mimeExtensionsFile = '@yii/helpers/mimeExtensions.php';
-
- 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 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;
- }
-
- 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 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;
- }
-
- 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 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;
- }
- }
- private static $_mimeTypes = [];
-
- 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];
- }
- private static $_mimeAliases = [];
-
- 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];
- }
- private static $_mimeExtensions = [];
-
- 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];
- }
-
- 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);
- }
-
- 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;
- }
- }
-
- 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 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;
- }
-
- private static function setBasePath($dir, $options)
- {
- if (!isset($options['basePath'])) {
-
- $options['basePath'] = realpath($dir);
- $options = static::normalizeOptions($options);
- }
- return $options;
- }
-
- private static function openDir($dir)
- {
- $handle = opendir($dir);
- if ($handle === false) {
- throw new InvalidArgumentException("Unable to open directory: $dir");
- }
- return $handle;
- }
-
- private static function clearDir($dir)
- {
- if (!is_dir($dir)) {
- throw new InvalidArgumentException("The dir argument must be a directory: $dir");
- }
- return rtrim($dir, '\/');
- }
-
- 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 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);
- }
- }
-
- private static function matchBasename($baseName, $pattern, $firstWildcard, $flags)
- {
- if ($firstWildcard === false) {
- if ($pattern === $baseName) {
- return true;
- }
- } elseif ($flags & self::PATTERN_ENDSWITH) {
-
- $n = StringHelper::byteLength($pattern);
- if (StringHelper::byteSubstr($pattern, 1, $n) === StringHelper::byteSubstr($baseName, -$n, $n)) {
- return true;
- }
- }
- $matchOptions = [];
- if ($flags & self::PATTERN_CASE_INSENSITIVE) {
- $matchOptions['caseSensitive'] = false;
- }
- return StringHelper::matchWildcard($pattern, $baseName, $matchOptions);
- }
-
- private static function matchPathname($path, $basePath, $pattern, $firstWildcard, $flags)
- {
-
- if (strncmp($pattern, '/', 1) === 0) {
- $pattern = StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern));
- if ($firstWildcard !== false && $firstWildcard !== 0) {
- $firstWildcard--;
- }
- }
- $namelen = StringHelper::byteLength($path) - (empty($basePath) ? 0 : StringHelper::byteLength($basePath) + 1);
- $name = StringHelper::byteSubstr($path, -$namelen, $namelen);
- if ($firstWildcard !== 0) {
- if ($firstWildcard === false) {
- $firstWildcard = StringHelper::byteLength($pattern);
- }
-
- if ($firstWildcard > $namelen) {
- return false;
- }
- if (strncmp($pattern, $name, $firstWildcard)) {
- return false;
- }
- $pattern = StringHelper::byteSubstr($pattern, $firstWildcard, StringHelper::byteLength($pattern));
- $name = StringHelper::byteSubstr($name, $firstWildcard, $namelen);
-
- if (empty($pattern) && empty($name)) {
- return true;
- }
- }
- $matchOptions = [
- 'filePath' => true
- ];
- if ($flags & self::PATTERN_CASE_INSENSITIVE) {
- $matchOptions['caseSensitive'] = false;
- }
- return StringHelper::matchWildcard($pattern, $name, $matchOptions);
- }
-
- private static function lastExcludeMatchingFromList($basePath, $path, $excludes)
- {
- foreach (array_reverse($excludes) as $exclude) {
- if (is_string($exclude)) {
- $exclude = self::parseExcludePattern($exclude, false);
- }
- if (!isset($exclude['pattern']) || !isset($exclude['flags']) || !isset($exclude['firstWildcard'])) {
- throw new InvalidArgumentException('If exclude/include pattern is an array it must contain the pattern, flags and firstWildcard keys.');
- }
- if ($exclude['flags'] & self::PATTERN_MUSTBEDIR && !is_dir($path)) {
- continue;
- }
- if ($exclude['flags'] & self::PATTERN_NODIR) {
- if (self::matchBasename(basename($path), $exclude['pattern'], $exclude['firstWildcard'], $exclude['flags'])) {
- return $exclude;
- }
- continue;
- }
- if (self::matchPathname($path, $basePath, $exclude['pattern'], $exclude['firstWildcard'], $exclude['flags'])) {
- return $exclude;
- }
- }
- return null;
- }
-
- private static function parseExcludePattern($pattern, $caseSensitive)
- {
- if (!is_string($pattern)) {
- throw new InvalidArgumentException('Exclude/include pattern must be a string.');
- }
- $result = [
- 'pattern' => $pattern,
- 'flags' => 0,
- 'firstWildcard' => false,
- ];
- if (!$caseSensitive) {
- $result['flags'] |= self::PATTERN_CASE_INSENSITIVE;
- }
- if (empty($pattern)) {
- return $result;
- }
- if (strncmp($pattern, '!', 1) === 0) {
- $result['flags'] |= self::PATTERN_NEGATIVE;
- $pattern = StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern));
- }
- if (StringHelper::byteLength($pattern) && StringHelper::byteSubstr($pattern, -1, 1) === '/') {
- $pattern = StringHelper::byteSubstr($pattern, 0, -1);
- $result['flags'] |= self::PATTERN_MUSTBEDIR;
- }
- if (strpos($pattern, '/') === false) {
- $result['flags'] |= self::PATTERN_NODIR;
- }
- $result['firstWildcard'] = self::firstWildcardInPattern($pattern);
- if (strncmp($pattern, '*', 1) === 0 && self::firstWildcardInPattern(StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern))) === false) {
- $result['flags'] |= self::PATTERN_ENDSWITH;
- }
- $result['pattern'] = $pattern;
- return $result;
- }
-
- private static function firstWildcardInPattern($pattern)
- {
- $wildcards = ['*', '?', '[', '\\'];
- $wildcardSearch = function ($r, $c) use ($pattern) {
- $p = strpos($pattern, $c);
- return $r === false ? $p : ($p === false ? $r : min($r, $p));
- };
- return array_reduce($wildcards, $wildcardSearch, false);
- }
-
- 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;
- }
-
- 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 . '".');
- }
- }
- }
- }
|