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.

720 line
31KB

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