You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

685 satır
30KB

  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\helpers;
  8. use Yii;
  9. use yii\base\InvalidConfigException;
  10. use yii\base\InvalidParamException;
  11. /**
  12. * BaseFileHelper provides concrete implementation for [[FileHelper]].
  13. *
  14. * Do not use BaseFileHelper. Use [[FileHelper]] instead.
  15. *
  16. * @author Qiang Xue <qiang.xue@gmail.com>
  17. * @author Alex Makarov <sam@rmcreative.ru>
  18. * @since 2.0
  19. */
  20. class BaseFileHelper
  21. {
  22. const PATTERN_NODIR = 1;
  23. const PATTERN_ENDSWITH = 4;
  24. const PATTERN_MUSTBEDIR = 8;
  25. const PATTERN_NEGATIVE = 16;
  26. const PATTERN_CASE_INSENSITIVE = 32;
  27. /**
  28. * @var string the path (or alias) of a PHP file containing MIME type information.
  29. */
  30. public static $mimeMagicFile = '@yii/helpers/mimeTypes.php';
  31. /**
  32. * Normalizes a file/directory path.
  33. * The normalization does the following work:
  34. *
  35. * - Convert all directory separators into `DIRECTORY_SEPARATOR` (e.g. "\a/b\c" becomes "/a/b/c")
  36. * - Remove trailing directory separators (e.g. "/a/b/c/" becomes "/a/b/c")
  37. * - Turn multiple consecutive slashes into a single one (e.g. "/a///b/c" becomes "/a/b/c")
  38. * - Remove ".." and "." based on their meanings (e.g. "/a/./b/../c" becomes "/a/c")
  39. *
  40. * @param string $path the file/directory path to be normalized
  41. * @param string $ds the directory separator to be used in the normalized result. Defaults to `DIRECTORY_SEPARATOR`.
  42. * @return string the normalized file/directory path
  43. */
  44. public static function normalizePath($path, $ds = DIRECTORY_SEPARATOR)
  45. {
  46. $path = rtrim(strtr($path, '/\\', $ds . $ds), $ds);
  47. if (strpos($ds . $path, "{$ds}.") === false && strpos($path, "{$ds}{$ds}") === false) {
  48. return $path;
  49. }
  50. // the path may contain ".", ".." or double slashes, need to clean them up
  51. $parts = [];
  52. foreach (explode($ds, $path) as $part) {
  53. if ($part === '..' && !empty($parts) && end($parts) !== '..') {
  54. array_pop($parts);
  55. } elseif ($part === '.' || $part === '' && !empty($parts)) {
  56. continue;
  57. } else {
  58. $parts[] = $part;
  59. }
  60. }
  61. $path = implode($ds, $parts);
  62. return $path === '' ? '.' : $path;
  63. }
  64. /**
  65. * Returns the localized version of a specified file.
  66. *
  67. * The searching is based on the specified language code. In particular,
  68. * a file with the same name will be looked for under the subdirectory
  69. * whose name is the same as the language code. For example, given the file "path/to/view.php"
  70. * and language code "zh-CN", the localized file will be looked for as
  71. * "path/to/zh-CN/view.php". If the file is not found, it will try a fallback with just a language code that is
  72. * "zh" i.e. "path/to/zh/view.php". If it is not found as well the original file will be returned.
  73. *
  74. * If the target and the source language codes are the same,
  75. * the original file will be returned.
  76. *
  77. * @param string $file the original file
  78. * @param string $language the target language that the file should be localized to.
  79. * If not set, the value of [[\yii\base\Application::language]] will be used.
  80. * @param string $sourceLanguage the language that the original file is in.
  81. * If not set, the value of [[\yii\base\Application::sourceLanguage]] will be used.
  82. * @return string the matching localized file, or the original file if the localized version is not found.
  83. * If the target and the source language codes are the same, the original file will be returned.
  84. */
  85. public static function localize($file, $language = null, $sourceLanguage = null)
  86. {
  87. if ($language === null) {
  88. $language = Yii::$app->language;
  89. }
  90. if ($sourceLanguage === null) {
  91. $sourceLanguage = Yii::$app->sourceLanguage;
  92. }
  93. if ($language === $sourceLanguage) {
  94. return $file;
  95. }
  96. $desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . basename($file);
  97. if (is_file($desiredFile)) {
  98. return $desiredFile;
  99. } else {
  100. $language = substr($language, 0, 2);
  101. if ($language === $sourceLanguage) {
  102. return $file;
  103. }
  104. $desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . basename($file);
  105. return is_file($desiredFile) ? $desiredFile : $file;
  106. }
  107. }
  108. /**
  109. * Determines the MIME type of the specified file.
  110. * This method will first try to determine the MIME type based on
  111. * [finfo_open](http://php.net/manual/en/function.finfo-open.php). If the `fileinfo` extension is not installed,
  112. * it will fall back to [[getMimeTypeByExtension()]] when `$checkExtension` is true.
  113. * @param string $file the file name.
  114. * @param string $magicFile name of the optional magic database file (or alias), usually something like `/path/to/magic.mime`.
  115. * This will be passed as the second parameter to [finfo_open()](http://php.net/manual/en/function.finfo-open.php)
  116. * when the `fileinfo` extension is installed. If the MIME type is being determined based via [[getMimeTypeByExtension()]]
  117. * and this is null, it will use the file specified by [[mimeMagicFile]].
  118. * @param boolean $checkExtension whether to use the file extension to determine the MIME type in case
  119. * `finfo_open()` cannot determine it.
  120. * @return string the MIME type (e.g. `text/plain`). Null is returned if the MIME type cannot be determined.
  121. * @throws InvalidConfigException when the `fileinfo` PHP extension is not installed and `$checkExtension` is `false`.
  122. */
  123. public static function getMimeType($file, $magicFile = null, $checkExtension = true)
  124. {
  125. if ($magicFile !== null) {
  126. $magicFile = Yii::getAlias($magicFile);
  127. }
  128. if (!extension_loaded('fileinfo')) {
  129. if ($checkExtension) {
  130. return static::getMimeTypeByExtension($file, $magicFile);
  131. } else {
  132. throw new InvalidConfigException('The fileinfo PHP extension is not installed.');
  133. }
  134. }
  135. $info = finfo_open(FILEINFO_MIME_TYPE, $magicFile);
  136. if ($info) {
  137. $result = finfo_file($info, $file);
  138. finfo_close($info);
  139. if ($result !== false) {
  140. return $result;
  141. }
  142. }
  143. return $checkExtension ? static::getMimeTypeByExtension($file, $magicFile) : null;
  144. }
  145. /**
  146. * Determines the MIME type based on the extension name of the specified file.
  147. * This method will use a local map between extension names and MIME types.
  148. * @param string $file the file name.
  149. * @param string $magicFile the path (or alias) of the file that contains all available MIME type information.
  150. * If this is not set, the file specified by [[mimeMagicFile]] will be used.
  151. * @return string the MIME type. Null is returned if the MIME type cannot be determined.
  152. */
  153. public static function getMimeTypeByExtension($file, $magicFile = null)
  154. {
  155. $mimeTypes = static::loadMimeTypes($magicFile);
  156. if (($ext = pathinfo($file, PATHINFO_EXTENSION)) !== '') {
  157. $ext = strtolower($ext);
  158. if (isset($mimeTypes[$ext])) {
  159. return $mimeTypes[$ext];
  160. }
  161. }
  162. return null;
  163. }
  164. /**
  165. * Determines the extensions by given MIME type.
  166. * This method will use a local map between extension names and MIME types.
  167. * @param string $mimeType file MIME type.
  168. * @param string $magicFile the path (or alias) of the file that contains all available MIME type information.
  169. * If this is not set, the file specified by [[mimeMagicFile]] will be used.
  170. * @return array the extensions corresponding to the specified MIME type
  171. */
  172. public static function getExtensionsByMimeType($mimeType, $magicFile = null)
  173. {
  174. $mimeTypes = static::loadMimeTypes($magicFile);
  175. return array_keys($mimeTypes, mb_strtolower($mimeType, 'utf-8'), true);
  176. }
  177. private static $_mimeTypes = [];
  178. /**
  179. * Loads MIME types from the specified file.
  180. * @param string $magicFile the path (or alias) of the file that contains all available MIME type information.
  181. * If this is not set, the file specified by [[mimeMagicFile]] will be used.
  182. * @return array the mapping from file extensions to MIME types
  183. */
  184. protected static function loadMimeTypes($magicFile)
  185. {
  186. if ($magicFile === null) {
  187. $magicFile = static::$mimeMagicFile;
  188. }
  189. $magicFile = Yii::getAlias($magicFile);
  190. if (!isset(self::$_mimeTypes[$magicFile])) {
  191. self::$_mimeTypes[$magicFile] = require($magicFile);
  192. }
  193. return self::$_mimeTypes[$magicFile];
  194. }
  195. /**
  196. * Copies a whole directory as another one.
  197. * The files and sub-directories will also be copied over.
  198. * @param string $src the source directory
  199. * @param string $dst the destination directory
  200. * @param array $options options for directory copy. Valid options are:
  201. *
  202. * - dirMode: integer, the permission to be set for newly copied directories. Defaults to 0775.
  203. * - fileMode: integer, the permission to be set for newly copied files. Defaults to the current environment setting.
  204. * - filter: callback, a PHP callback that is called for each directory or file.
  205. * The signature of the callback should be: `function ($path)`, where `$path` refers the full path to be filtered.
  206. * The callback can return one of the following values:
  207. *
  208. * * true: the directory or file will be copied (the "only" and "except" options will be ignored)
  209. * * false: the directory or file will NOT be copied (the "only" and "except" options will be ignored)
  210. * * null: the "only" and "except" options will determine whether the directory or file should be copied
  211. *
  212. * - only: array, list of patterns that the file paths should match if they want to be copied.
  213. * A path matches a pattern if it contains the pattern string at its end.
  214. * For example, '.php' matches all file paths ending with '.php'.
  215. * Note, the '/' characters in a pattern matches both '/' and '\' in the paths.
  216. * If a file path matches a pattern in both "only" and "except", it will NOT be copied.
  217. * - except: array, list of patterns that the files or directories should match if they want to be excluded from being copied.
  218. * A path matches a pattern if it contains the pattern string at its end.
  219. * Patterns ending with '/' apply to directory paths only, and patterns not ending with '/'
  220. * apply to file paths only. For example, '/a/b' matches all file paths ending with '/a/b';
  221. * and '.svn/' matches directory paths ending with '.svn'. Note, the '/' characters in a pattern matches
  222. * both '/' and '\' in the paths.
  223. * - caseSensitive: boolean, whether patterns specified at "only" or "except" should be case sensitive. Defaults to true.
  224. * - recursive: boolean, whether the files under the subdirectories should also be copied. Defaults to true.
  225. * - beforeCopy: callback, a PHP callback that is called before copying each sub-directory or file.
  226. * If the callback returns false, the copy operation for the sub-directory or file will be cancelled.
  227. * The signature of the callback should be: `function ($from, $to)`, where `$from` is the sub-directory or
  228. * file to be copied from, while `$to` is the copy target.
  229. * - afterCopy: callback, a PHP callback that is called after each sub-directory or file is successfully copied.
  230. * The signature of the callback should be: `function ($from, $to)`, where `$from` is the sub-directory or
  231. * file copied from, while `$to` is the copy target.
  232. * @throws \yii\base\InvalidParamException if unable to open directory
  233. */
  234. public static function copyDirectory($src, $dst, $options = [])
  235. {
  236. if (!is_dir($dst)) {
  237. static::createDirectory($dst, isset($options['dirMode']) ? $options['dirMode'] : 0775, true);
  238. }
  239. $handle = opendir($src);
  240. if ($handle === false) {
  241. throw new InvalidParamException('Unable to open directory: ' . $src);
  242. }
  243. if (!isset($options['basePath'])) {
  244. // this should be done only once
  245. $options['basePath'] = realpath($src);
  246. $options = self::normalizeOptions($options);
  247. }
  248. while (($file = readdir($handle)) !== false) {
  249. if ($file === '.' || $file === '..') {
  250. continue;
  251. }
  252. $from = $src . DIRECTORY_SEPARATOR . $file;
  253. $to = $dst . DIRECTORY_SEPARATOR . $file;
  254. if (static::filterPath($from, $options)) {
  255. if (isset($options['beforeCopy']) && !call_user_func($options['beforeCopy'], $from, $to)) {
  256. continue;
  257. }
  258. if (is_file($from)) {
  259. copy($from, $to);
  260. if (isset($options['fileMode'])) {
  261. @chmod($to, $options['fileMode']);
  262. }
  263. } else {
  264. static::copyDirectory($from, $to, $options);
  265. }
  266. if (isset($options['afterCopy'])) {
  267. call_user_func($options['afterCopy'], $from, $to);
  268. }
  269. }
  270. }
  271. closedir($handle);
  272. }
  273. /**
  274. * Removes a directory (and all its content) recursively.
  275. * @param string $dir the directory to be deleted recursively.
  276. * @param array $options options for directory remove. Valid options are:
  277. *
  278. * - traverseSymlinks: boolean, whether symlinks to the directories should be traversed too.
  279. * Defaults to `false`, meaning the content of the symlinked directory would not be deleted.
  280. * Only symlink would be removed in that default case.
  281. */
  282. public static function removeDirectory($dir, $options = [])
  283. {
  284. if (!is_dir($dir)) {
  285. return;
  286. }
  287. if (isset($options['traverseSymlinks']) && $options['traverseSymlinks'] || !is_link($dir)) {
  288. if (!($handle = opendir($dir))) {
  289. return;
  290. }
  291. while (($file = readdir($handle)) !== false) {
  292. if ($file === '.' || $file === '..') {
  293. continue;
  294. }
  295. $path = $dir . DIRECTORY_SEPARATOR . $file;
  296. if (is_dir($path)) {
  297. static::removeDirectory($path, $options);
  298. } else {
  299. unlink($path);
  300. }
  301. }
  302. closedir($handle);
  303. }
  304. if (is_link($dir)) {
  305. unlink($dir);
  306. } else {
  307. rmdir($dir);
  308. }
  309. }
  310. /**
  311. * Returns the files found under the specified directory and subdirectories.
  312. * @param string $dir the directory under which the files will be looked for.
  313. * @param array $options options for file searching. Valid options are:
  314. *
  315. * - filter: callback, a PHP callback that is called for each directory or file.
  316. * The signature of the callback should be: `function ($path)`, where `$path` refers the full path to be filtered.
  317. * The callback can return one of the following values:
  318. *
  319. * * true: the directory or file will be returned (the "only" and "except" options will be ignored)
  320. * * false: the directory or file will NOT be returned (the "only" and "except" options will be ignored)
  321. * * null: the "only" and "except" options will determine whether the directory or file should be returned
  322. *
  323. * - except: array, list of patterns excluding from the results matching file or directory paths.
  324. * Patterns ending with '/' apply to directory paths only, and patterns not ending with '/'
  325. * apply to file paths only. For example, '/a/b' matches all file paths ending with '/a/b';
  326. * and '.svn/' matches directory paths ending with '.svn'.
  327. * 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.
  328. * 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.
  329. * For example, "views/*.php" matches "views/index.php" but not "views/controller/index.php".
  330. * A leading slash matches the beginning of the pathname. For example, "/*.php" matches "index.php" but not "views/start/index.php".
  331. * An optional prefix "!" which negates the pattern; any matching file excluded by a previous pattern will become included again.
  332. * If a negated pattern matches, this will override lower precedence patterns sources. Put a backslash ("\") in front of the first "!"
  333. * for patterns that begin with a literal "!", for example, "\!important!.txt".
  334. * Note, the '/' characters in a pattern matches both '/' and '\' in the paths.
  335. * - only: array, list of patterns that the file paths should match if they are to be returned. Directory paths are not checked against them.
  336. * Same pattern matching rules as in the "except" option are used.
  337. * If a file path matches a pattern in both "only" and "except", it will NOT be returned.
  338. * - caseSensitive: boolean, whether patterns specified at "only" or "except" should be case sensitive. Defaults to true.
  339. * - recursive: boolean, whether the files under the subdirectories should also be looked for. Defaults to true.
  340. * @return array files found under the directory. The file list is sorted.
  341. * @throws InvalidParamException if the dir is invalid.
  342. */
  343. public static function findFiles($dir, $options = [])
  344. {
  345. if (!is_dir($dir)) {
  346. throw new InvalidParamException('The dir argument must be a directory.');
  347. }
  348. $dir = rtrim($dir, DIRECTORY_SEPARATOR);
  349. if (!isset($options['basePath'])) {
  350. // this should be done only once
  351. $options['basePath'] = realpath($dir);
  352. $options = self::normalizeOptions($options);
  353. }
  354. $list = [];
  355. $handle = opendir($dir);
  356. if ($handle === false) {
  357. throw new InvalidParamException('Unable to open directory: ' . $dir);
  358. }
  359. while (($file = readdir($handle)) !== false) {
  360. if ($file === '.' || $file === '..') {
  361. continue;
  362. }
  363. $path = $dir . DIRECTORY_SEPARATOR . $file;
  364. if (static::filterPath($path, $options)) {
  365. if (is_file($path)) {
  366. $list[] = $path;
  367. } elseif (!isset($options['recursive']) || $options['recursive']) {
  368. $list = array_merge($list, static::findFiles($path, $options));
  369. }
  370. }
  371. }
  372. closedir($handle);
  373. return $list;
  374. }
  375. /**
  376. * Checks if the given file path satisfies the filtering options.
  377. * @param string $path the path of the file or directory to be checked
  378. * @param array $options the filtering options. See [[findFiles()]] for explanations of
  379. * the supported options.
  380. * @return boolean whether the file or directory satisfies the filtering options.
  381. */
  382. public static function filterPath($path, $options)
  383. {
  384. if (isset($options['filter'])) {
  385. $result = call_user_func($options['filter'], $path);
  386. if (is_bool($result)) {
  387. return $result;
  388. }
  389. }
  390. if (empty($options['except']) && empty($options['only'])) {
  391. return true;
  392. }
  393. $path = str_replace('\\', '/', $path);
  394. if (!empty($options['except'])) {
  395. if (($except = self::lastExcludeMatchingFromList($options['basePath'], $path, $options['except'])) !== null) {
  396. return $except['flags'] & self::PATTERN_NEGATIVE;
  397. }
  398. }
  399. if (!empty($options['only']) && !is_dir($path)) {
  400. if (($except = self::lastExcludeMatchingFromList($options['basePath'], $path, $options['only'])) !== null) {
  401. // don't check PATTERN_NEGATIVE since those entries are not prefixed with !
  402. return true;
  403. }
  404. return false;
  405. }
  406. return true;
  407. }
  408. /**
  409. * Creates a new directory.
  410. *
  411. * This method is similar to the PHP `mkdir()` function except that
  412. * it uses `chmod()` to set the permission of the created directory
  413. * in order to avoid the impact of the `umask` setting.
  414. *
  415. * @param string $path path of the directory to be created.
  416. * @param integer $mode the permission to be set for the created directory.
  417. * @param boolean $recursive whether to create parent directories if they do not exist.
  418. * @return boolean whether the directory is created successfully
  419. */
  420. public static function createDirectory($path, $mode = 0775, $recursive = true)
  421. {
  422. if (is_dir($path)) {
  423. return true;
  424. }
  425. $parentDir = dirname($path);
  426. if ($recursive && !is_dir($parentDir)) {
  427. static::createDirectory($parentDir, $mode, true);
  428. }
  429. $result = mkdir($path, $mode);
  430. chmod($path, $mode);
  431. return $result;
  432. }
  433. /**
  434. * Performs a simple comparison of file or directory names.
  435. *
  436. * Based on match_basename() from dir.c of git 1.8.5.3 sources.
  437. *
  438. * @param string $baseName file or directory name to compare with the pattern
  439. * @param string $pattern the pattern that $baseName will be compared against
  440. * @param integer|boolean $firstWildcard location of first wildcard character in the $pattern
  441. * @param integer $flags pattern flags
  442. * @return boolean wheter the name matches against pattern
  443. */
  444. private static function matchBasename($baseName, $pattern, $firstWildcard, $flags)
  445. {
  446. if ($firstWildcard === false) {
  447. if ($pattern === $baseName) {
  448. return true;
  449. }
  450. } elseif ($flags & self::PATTERN_ENDSWITH) {
  451. /* "*literal" matching against "fooliteral" */
  452. $n = StringHelper::byteLength($pattern);
  453. if (StringHelper::byteSubstr($pattern, 1, $n) === StringHelper::byteSubstr($baseName, -$n, $n)) {
  454. return true;
  455. }
  456. }
  457. $fnmatchFlags = 0;
  458. if ($flags & self::PATTERN_CASE_INSENSITIVE) {
  459. $fnmatchFlags |= FNM_CASEFOLD;
  460. }
  461. return fnmatch($pattern, $baseName, $fnmatchFlags);
  462. }
  463. /**
  464. * Compares a path part against a pattern with optional wildcards.
  465. *
  466. * Based on match_pathname() from dir.c of git 1.8.5.3 sources.
  467. *
  468. * @param string $path full path to compare
  469. * @param string $basePath base of path that will not be compared
  470. * @param string $pattern the pattern that path part will be compared against
  471. * @param integer|boolean $firstWildcard location of first wildcard character in the $pattern
  472. * @param integer $flags pattern flags
  473. * @return boolean wheter the path part matches against pattern
  474. */
  475. private static function matchPathname($path, $basePath, $pattern, $firstWildcard, $flags)
  476. {
  477. // match with FNM_PATHNAME; the pattern has base implicitly in front of it.
  478. if (isset($pattern[0]) && $pattern[0] == '/') {
  479. $pattern = StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern));
  480. if ($firstWildcard !== false && $firstWildcard !== 0) {
  481. $firstWildcard--;
  482. }
  483. }
  484. $namelen = StringHelper::byteLength($path) - (empty($basePath) ? 0 : StringHelper::byteLength($basePath) + 1);
  485. $name = StringHelper::byteSubstr($path, -$namelen, $namelen);
  486. if ($firstWildcard !== 0) {
  487. if ($firstWildcard === false) {
  488. $firstWildcard = StringHelper::byteLength($pattern);
  489. }
  490. // if the non-wildcard part is longer than the remaining pathname, surely it cannot match.
  491. if ($firstWildcard > $namelen) {
  492. return false;
  493. }
  494. if (strncmp($pattern, $name, $firstWildcard)) {
  495. return false;
  496. }
  497. $pattern = StringHelper::byteSubstr($pattern, $firstWildcard, StringHelper::byteLength($pattern));
  498. $name = StringHelper::byteSubstr($name, $firstWildcard, $namelen);
  499. // If the whole pattern did not have a wildcard, then our prefix match is all we need; we do not need to call fnmatch at all.
  500. if (empty($pattern) && empty($name)) {
  501. return true;
  502. }
  503. }
  504. $fnmatchFlags = FNM_PATHNAME;
  505. if ($flags & self::PATTERN_CASE_INSENSITIVE) {
  506. $fnmatchFlags |= FNM_CASEFOLD;
  507. }
  508. return fnmatch($pattern, $name, $fnmatchFlags);
  509. }
  510. /**
  511. * Scan the given exclude list in reverse to see whether pathname
  512. * should be ignored. The first match (i.e. the last on the list), if
  513. * any, determines the fate. Returns the element which
  514. * matched, or null for undecided.
  515. *
  516. * Based on last_exclude_matching_from_list() from dir.c of git 1.8.5.3 sources.
  517. *
  518. * @param string $basePath
  519. * @param string $path
  520. * @param array $excludes list of patterns to match $path against
  521. * @return string null or one of $excludes item as an array with keys: 'pattern', 'flags'
  522. * @throws InvalidParamException if any of the exclude patterns is not a string or an array with keys: pattern, flags, firstWildcard.
  523. */
  524. private static function lastExcludeMatchingFromList($basePath, $path, $excludes)
  525. {
  526. foreach (array_reverse($excludes) as $exclude) {
  527. if (is_string($exclude)) {
  528. $exclude = self::parseExcludePattern($exclude, false);
  529. }
  530. if (!isset($exclude['pattern']) || !isset($exclude['flags']) || !isset($exclude['firstWildcard'])) {
  531. throw new InvalidParamException('If exclude/include pattern is an array it must contain the pattern, flags and firstWildcard keys.');
  532. }
  533. if ($exclude['flags'] & self::PATTERN_MUSTBEDIR && !is_dir($path)) {
  534. continue;
  535. }
  536. if ($exclude['flags'] & self::PATTERN_NODIR) {
  537. if (self::matchBasename(basename($path), $exclude['pattern'], $exclude['firstWildcard'], $exclude['flags'])) {
  538. return $exclude;
  539. }
  540. continue;
  541. }
  542. if (self::matchPathname($path, $basePath, $exclude['pattern'], $exclude['firstWildcard'], $exclude['flags'])) {
  543. return $exclude;
  544. }
  545. }
  546. return null;
  547. }
  548. /**
  549. * Processes the pattern, stripping special characters like / and ! from the beginning and settings flags instead.
  550. * @param string $pattern
  551. * @param boolean $caseSensitive
  552. * @throws \yii\base\InvalidParamException
  553. * @return array with keys: (string) pattern, (int) flags, (int|boolean)firstWildcard
  554. */
  555. private static function parseExcludePattern($pattern, $caseSensitive)
  556. {
  557. if (!is_string($pattern)) {
  558. throw new InvalidParamException('Exclude/include pattern must be a string.');
  559. }
  560. $result = [
  561. 'pattern' => $pattern,
  562. 'flags' => 0,
  563. 'firstWildcard' => false,
  564. ];
  565. if (!$caseSensitive) {
  566. $result['flags'] |= self::PATTERN_CASE_INSENSITIVE;
  567. }
  568. if (!isset($pattern[0])) {
  569. return $result;
  570. }
  571. if ($pattern[0] == '!') {
  572. $result['flags'] |= self::PATTERN_NEGATIVE;
  573. $pattern = StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern));
  574. }
  575. if (StringHelper::byteLength($pattern) && StringHelper::byteSubstr($pattern, -1, 1) == '/') {
  576. $pattern = StringHelper::byteSubstr($pattern, 0, -1);
  577. $result['flags'] |= self::PATTERN_MUSTBEDIR;
  578. }
  579. if (strpos($pattern, '/') === false) {
  580. $result['flags'] |= self::PATTERN_NODIR;
  581. }
  582. $result['firstWildcard'] = self::firstWildcardInPattern($pattern);
  583. if ($pattern[0] == '*' && self::firstWildcardInPattern(StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern))) === false) {
  584. $result['flags'] |= self::PATTERN_ENDSWITH;
  585. }
  586. $result['pattern'] = $pattern;
  587. return $result;
  588. }
  589. /**
  590. * Searches for the first wildcard character in the pattern.
  591. * @param string $pattern the pattern to search in
  592. * @return integer|boolean position of first wildcard character or false if not found
  593. */
  594. private static function firstWildcardInPattern($pattern)
  595. {
  596. $wildcards = ['*', '?', '[', '\\'];
  597. $wildcardSearch = function ($r, $c) use ($pattern) {
  598. $p = strpos($pattern, $c);
  599. return $r===false ? $p : ($p===false ? $r : min($r, $p));
  600. };
  601. return array_reduce($wildcards, $wildcardSearch, false);
  602. }
  603. /**
  604. * @param array $options raw options
  605. * @return array normalized options
  606. */
  607. private static function normalizeOptions(array $options)
  608. {
  609. if (!array_key_exists('caseSensitive', $options)) {
  610. $options['caseSensitive'] = true;
  611. }
  612. if (isset($options['except'])) {
  613. foreach ($options['except'] as $key => $value) {
  614. if (is_string($value)) {
  615. $options['except'][$key] = self::parseExcludePattern($value, $options['caseSensitive']);
  616. }
  617. }
  618. }
  619. if (isset($options['only'])) {
  620. foreach ($options['only'] as $key => $value) {
  621. if (is_string($value)) {
  622. $options['only'][$key] = self::parseExcludePattern($value, $options['caseSensitive']);
  623. }
  624. }
  625. }
  626. return $options;
  627. }
  628. }