BaseFileHelper.php 32KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  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 slash ('/') 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
  350. * and checked for a match against the pathname relative to `$dir`.
  351. * Otherwise, the pattern is treated as a shell glob suitable for consumption by `fnmatch(3)`
  352. * `with the `FNM_PATHNAME` flag: wildcards in the pattern will not match a `/` in the pathname.
  353. * For example, `views/*.php` matches `views/index.php` but not `views/controller/index.php`.
  354. * A leading slash matches the beginning of the pathname. For example, `/*.php` matches `index.php` but not `views/start/index.php`.
  355. * An optional prefix `!` which negates the pattern; any matching file excluded by a previous pattern will become included again.
  356. * If a negated pattern matches, this will override lower precedence patterns sources. Put a backslash (`\`) in front of the first `!`
  357. * for patterns that begin with a literal `!`, for example, `\!important!.txt`.
  358. * Note, the '/' characters in a pattern matches both '/' and '\' in the paths.
  359. * - `only`: array, list of patterns that the file paths should match if they are to be returned. Directory paths
  360. * are not checked against them. Same pattern matching rules as in the `except` option are used.
  361. * If a file path matches a pattern in both `only` and `except`, it will NOT be returned.
  362. * - `caseSensitive`: boolean, whether patterns specified at `only` or `except` should be case sensitive. Defaults to `true`.
  363. * - `recursive`: boolean, whether the files under the subdirectories should also be looked for. Defaults to `true`.
  364. * @return array files found under the directory, in no particular order. Ordering depends on the files system used.
  365. * @throws InvalidParamException if the dir is invalid.
  366. */
  367. public static function findFiles($dir, $options = [])
  368. {
  369. if (!is_dir($dir)) {
  370. throw new InvalidParamException("The dir argument must be a directory: $dir");
  371. }
  372. $dir = rtrim($dir, DIRECTORY_SEPARATOR);
  373. if (!isset($options['basePath'])) {
  374. // this should be done only once
  375. $options['basePath'] = realpath($dir);
  376. $options = self::normalizeOptions($options);
  377. }
  378. $list = [];
  379. $handle = opendir($dir);
  380. if ($handle === false) {
  381. throw new InvalidParamException("Unable to open directory: $dir");
  382. }
  383. while (($file = readdir($handle)) !== false) {
  384. if ($file === '.' || $file === '..') {
  385. continue;
  386. }
  387. $path = $dir . DIRECTORY_SEPARATOR . $file;
  388. if (static::filterPath($path, $options)) {
  389. if (is_file($path)) {
  390. $list[] = $path;
  391. } elseif (!isset($options['recursive']) || $options['recursive']) {
  392. $list = array_merge($list, static::findFiles($path, $options));
  393. }
  394. }
  395. }
  396. closedir($handle);
  397. return $list;
  398. }
  399. /**
  400. * Checks if the given file path satisfies the filtering options.
  401. * @param string $path the path of the file or directory to be checked
  402. * @param array $options the filtering options. See [[findFiles()]] for explanations of
  403. * the supported options.
  404. * @return boolean whether the file or directory satisfies the filtering options.
  405. */
  406. public static function filterPath($path, $options)
  407. {
  408. if (isset($options['filter'])) {
  409. $result = call_user_func($options['filter'], $path);
  410. if (is_bool($result)) {
  411. return $result;
  412. }
  413. }
  414. if (empty($options['except']) && empty($options['only'])) {
  415. return true;
  416. }
  417. $path = str_replace('\\', '/', $path);
  418. if (!empty($options['except'])) {
  419. if (($except = self::lastExcludeMatchingFromList($options['basePath'], $path, $options['except'])) !== null) {
  420. return $except['flags'] & self::PATTERN_NEGATIVE;
  421. }
  422. }
  423. if (!empty($options['only']) && !is_dir($path)) {
  424. if (($except = self::lastExcludeMatchingFromList($options['basePath'], $path, $options['only'])) !== null) {
  425. // don't check PATTERN_NEGATIVE since those entries are not prefixed with !
  426. return true;
  427. }
  428. return false;
  429. }
  430. return true;
  431. }
  432. /**
  433. * Creates a new directory.
  434. *
  435. * This method is similar to the PHP `mkdir()` function except that
  436. * it uses `chmod()` to set the permission of the created directory
  437. * in order to avoid the impact of the `umask` setting.
  438. *
  439. * @param string $path path of the directory to be created.
  440. * @param integer $mode the permission to be set for the created directory.
  441. * @param boolean $recursive whether to create parent directories if they do not exist.
  442. * @return boolean whether the directory is created successfully
  443. * @throws \yii\base\Exception if the directory could not be created (i.e. php error due to parallel changes)
  444. */
  445. public static function createDirectory($path, $mode = 0775, $recursive = true)
  446. {
  447. if (is_dir($path)) {
  448. return true;
  449. }
  450. $parentDir = dirname($path);
  451. // recurse if parent dir does not exist and we are not at the root of the file system.
  452. if ($recursive && !is_dir($parentDir) && $parentDir !== $path) {
  453. static::createDirectory($parentDir, $mode, true);
  454. }
  455. try {
  456. if (!mkdir($path, $mode)) {
  457. return false;
  458. }
  459. } catch (\Exception $e) {
  460. if (!is_dir($path)) {// https://github.com/yiisoft/yii2/issues/9288
  461. throw new \yii\base\Exception("Failed to create directory \"$path\": " . $e->getMessage(), $e->getCode(), $e);
  462. }
  463. }
  464. try {
  465. return chmod($path, $mode);
  466. } catch (\Exception $e) {
  467. throw new \yii\base\Exception("Failed to change permissions for directory \"$path\": " . $e->getMessage(), $e->getCode(), $e);
  468. }
  469. }
  470. /**
  471. * Performs a simple comparison of file or directory names.
  472. *
  473. * Based on match_basename() from dir.c of git 1.8.5.3 sources.
  474. *
  475. * @param string $baseName file or directory name to compare with the pattern
  476. * @param string $pattern the pattern that $baseName will be compared against
  477. * @param integer|boolean $firstWildcard location of first wildcard character in the $pattern
  478. * @param integer $flags pattern flags
  479. * @return boolean whether the name matches against pattern
  480. */
  481. private static function matchBasename($baseName, $pattern, $firstWildcard, $flags)
  482. {
  483. if ($firstWildcard === false) {
  484. if ($pattern === $baseName) {
  485. return true;
  486. }
  487. } elseif ($flags & self::PATTERN_ENDSWITH) {
  488. /* "*literal" matching against "fooliteral" */
  489. $n = StringHelper::byteLength($pattern);
  490. if (StringHelper::byteSubstr($pattern, 1, $n) === StringHelper::byteSubstr($baseName, -$n, $n)) {
  491. return true;
  492. }
  493. }
  494. $fnmatchFlags = 0;
  495. if ($flags & self::PATTERN_CASE_INSENSITIVE) {
  496. $fnmatchFlags |= FNM_CASEFOLD;
  497. }
  498. return fnmatch($pattern, $baseName, $fnmatchFlags);
  499. }
  500. /**
  501. * Compares a path part against a pattern with optional wildcards.
  502. *
  503. * Based on match_pathname() from dir.c of git 1.8.5.3 sources.
  504. *
  505. * @param string $path full path to compare
  506. * @param string $basePath base of path that will not be compared
  507. * @param string $pattern the pattern that path part will be compared against
  508. * @param integer|boolean $firstWildcard location of first wildcard character in the $pattern
  509. * @param integer $flags pattern flags
  510. * @return boolean whether the path part matches against pattern
  511. */
  512. private static function matchPathname($path, $basePath, $pattern, $firstWildcard, $flags)
  513. {
  514. // match with FNM_PATHNAME; the pattern has base implicitly in front of it.
  515. if (isset($pattern[0]) && $pattern[0] === '/') {
  516. $pattern = StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern));
  517. if ($firstWildcard !== false && $firstWildcard !== 0) {
  518. $firstWildcard--;
  519. }
  520. }
  521. $namelen = StringHelper::byteLength($path) - (empty($basePath) ? 0 : StringHelper::byteLength($basePath) + 1);
  522. $name = StringHelper::byteSubstr($path, -$namelen, $namelen);
  523. if ($firstWildcard !== 0) {
  524. if ($firstWildcard === false) {
  525. $firstWildcard = StringHelper::byteLength($pattern);
  526. }
  527. // if the non-wildcard part is longer than the remaining pathname, surely it cannot match.
  528. if ($firstWildcard > $namelen) {
  529. return false;
  530. }
  531. if (strncmp($pattern, $name, $firstWildcard)) {
  532. return false;
  533. }
  534. $pattern = StringHelper::byteSubstr($pattern, $firstWildcard, StringHelper::byteLength($pattern));
  535. $name = StringHelper::byteSubstr($name, $firstWildcard, $namelen);
  536. // 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.
  537. if (empty($pattern) && empty($name)) {
  538. return true;
  539. }
  540. }
  541. $fnmatchFlags = FNM_PATHNAME;
  542. if ($flags & self::PATTERN_CASE_INSENSITIVE) {
  543. $fnmatchFlags |= FNM_CASEFOLD;
  544. }
  545. return fnmatch($pattern, $name, $fnmatchFlags);
  546. }
  547. /**
  548. * Scan the given exclude list in reverse to see whether pathname
  549. * should be ignored. The first match (i.e. the last on the list), if
  550. * any, determines the fate. Returns the element which
  551. * matched, or null for undecided.
  552. *
  553. * Based on last_exclude_matching_from_list() from dir.c of git 1.8.5.3 sources.
  554. *
  555. * @param string $basePath
  556. * @param string $path
  557. * @param array $excludes list of patterns to match $path against
  558. * @return string null or one of $excludes item as an array with keys: 'pattern', 'flags'
  559. * @throws InvalidParamException if any of the exclude patterns is not a string or an array with keys: pattern, flags, firstWildcard.
  560. */
  561. private static function lastExcludeMatchingFromList($basePath, $path, $excludes)
  562. {
  563. foreach (array_reverse($excludes) as $exclude) {
  564. if (is_string($exclude)) {
  565. $exclude = self::parseExcludePattern($exclude, false);
  566. }
  567. if (!isset($exclude['pattern']) || !isset($exclude['flags']) || !isset($exclude['firstWildcard'])) {
  568. throw new InvalidParamException('If exclude/include pattern is an array it must contain the pattern, flags and firstWildcard keys.');
  569. }
  570. if ($exclude['flags'] & self::PATTERN_MUSTBEDIR && !is_dir($path)) {
  571. continue;
  572. }
  573. if ($exclude['flags'] & self::PATTERN_NODIR) {
  574. if (self::matchBasename(basename($path), $exclude['pattern'], $exclude['firstWildcard'], $exclude['flags'])) {
  575. return $exclude;
  576. }
  577. continue;
  578. }
  579. if (self::matchPathname($path, $basePath, $exclude['pattern'], $exclude['firstWildcard'], $exclude['flags'])) {
  580. return $exclude;
  581. }
  582. }
  583. return null;
  584. }
  585. /**
  586. * Processes the pattern, stripping special characters like / and ! from the beginning and settings flags instead.
  587. * @param string $pattern
  588. * @param boolean $caseSensitive
  589. * @throws \yii\base\InvalidParamException
  590. * @return array with keys: (string) pattern, (int) flags, (int|boolean) firstWildcard
  591. */
  592. private static function parseExcludePattern($pattern, $caseSensitive)
  593. {
  594. if (!is_string($pattern)) {
  595. throw new InvalidParamException('Exclude/include pattern must be a string.');
  596. }
  597. $result = [
  598. 'pattern' => $pattern,
  599. 'flags' => 0,
  600. 'firstWildcard' => false,
  601. ];
  602. if (!$caseSensitive) {
  603. $result['flags'] |= self::PATTERN_CASE_INSENSITIVE;
  604. }
  605. if (!isset($pattern[0])) {
  606. return $result;
  607. }
  608. if ($pattern[0] === '!') {
  609. $result['flags'] |= self::PATTERN_NEGATIVE;
  610. $pattern = StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern));
  611. }
  612. if (StringHelper::byteLength($pattern) && StringHelper::byteSubstr($pattern, -1, 1) === '/') {
  613. $pattern = StringHelper::byteSubstr($pattern, 0, -1);
  614. $result['flags'] |= self::PATTERN_MUSTBEDIR;
  615. }
  616. if (strpos($pattern, '/') === false) {
  617. $result['flags'] |= self::PATTERN_NODIR;
  618. }
  619. $result['firstWildcard'] = self::firstWildcardInPattern($pattern);
  620. if ($pattern[0] === '*' && self::firstWildcardInPattern(StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern))) === false) {
  621. $result['flags'] |= self::PATTERN_ENDSWITH;
  622. }
  623. $result['pattern'] = $pattern;
  624. return $result;
  625. }
  626. /**
  627. * Searches for the first wildcard character in the pattern.
  628. * @param string $pattern the pattern to search in
  629. * @return integer|boolean position of first wildcard character or false if not found
  630. */
  631. private static function firstWildcardInPattern($pattern)
  632. {
  633. $wildcards = ['*', '?', '[', '\\'];
  634. $wildcardSearch = function ($r, $c) use ($pattern) {
  635. $p = strpos($pattern, $c);
  636. return $r === false ? $p : ($p === false ? $r : min($r, $p));
  637. };
  638. return array_reduce($wildcards, $wildcardSearch, false);
  639. }
  640. /**
  641. * @param array $options raw options
  642. * @return array normalized options
  643. */
  644. private static function normalizeOptions(array $options)
  645. {
  646. if (!array_key_exists('caseSensitive', $options)) {
  647. $options['caseSensitive'] = true;
  648. }
  649. if (isset($options['except'])) {
  650. foreach ($options['except'] as $key => $value) {
  651. if (is_string($value)) {
  652. $options['except'][$key] = self::parseExcludePattern($value, $options['caseSensitive']);
  653. }
  654. }
  655. }
  656. if (isset($options['only'])) {
  657. foreach ($options['only'] as $key => $value) {
  658. if (is_string($value)) {
  659. $options['only'][$key] = self::parseExcludePattern($value, $options['caseSensitive']);
  660. }
  661. }
  662. }
  663. return $options;
  664. }
  665. }