BaseFileHelper.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  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 bool $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. * - copyEmptyDirectories: boolean, whether to copy empty directories. Set this to false to avoid creating directories
  234. * that do not contain files. This affects directories that do not contain files initially as well as directories that
  235. * do not contain files at the target destination because files have been filtered via `only` or `except`.
  236. * Defaults to true. This option is available since version 2.0.12. Before 2.0.12 empty directories are always copied.
  237. * @throws \yii\base\InvalidParamException if unable to open directory
  238. */
  239. public static function copyDirectory($src, $dst, $options = [])
  240. {
  241. $src = static::normalizePath($src);
  242. $dst = static::normalizePath($dst);
  243. if ($src === $dst || strpos($dst, $src . DIRECTORY_SEPARATOR) === 0) {
  244. throw new InvalidParamException('Trying to copy a directory to itself or a subdirectory.');
  245. }
  246. $dstExists = is_dir($dst);
  247. if (!$dstExists && (!isset($options['copyEmptyDirectories']) || $options['copyEmptyDirectories'])) {
  248. static::createDirectory($dst, isset($options['dirMode']) ? $options['dirMode'] : 0775, true);
  249. $dstExists = true;
  250. }
  251. $handle = opendir($src);
  252. if ($handle === false) {
  253. throw new InvalidParamException("Unable to open directory: $src");
  254. }
  255. if (!isset($options['basePath'])) {
  256. // this should be done only once
  257. $options['basePath'] = realpath($src);
  258. $options = static::normalizeOptions($options);
  259. }
  260. while (($file = readdir($handle)) !== false) {
  261. if ($file === '.' || $file === '..') {
  262. continue;
  263. }
  264. $from = $src . DIRECTORY_SEPARATOR . $file;
  265. $to = $dst . DIRECTORY_SEPARATOR . $file;
  266. if (static::filterPath($from, $options)) {
  267. if (isset($options['beforeCopy']) && !call_user_func($options['beforeCopy'], $from, $to)) {
  268. continue;
  269. }
  270. if (is_file($from)) {
  271. if (!$dstExists) {
  272. // delay creation of destination directory until the first file is copied to avoid creating empty directories
  273. static::createDirectory($dst, isset($options['dirMode']) ? $options['dirMode'] : 0775, true);
  274. $dstExists = true;
  275. }
  276. copy($from, $to);
  277. if (isset($options['fileMode'])) {
  278. @chmod($to, $options['fileMode']);
  279. }
  280. } else {
  281. // recursive copy, defaults to true
  282. if (!isset($options['recursive']) || $options['recursive']) {
  283. static::copyDirectory($from, $to, $options);
  284. }
  285. }
  286. if (isset($options['afterCopy'])) {
  287. call_user_func($options['afterCopy'], $from, $to);
  288. }
  289. }
  290. }
  291. closedir($handle);
  292. }
  293. /**
  294. * Removes a directory (and all its content) recursively.
  295. *
  296. * @param string $dir the directory to be deleted recursively.
  297. * @param array $options options for directory remove. Valid options are:
  298. *
  299. * - traverseSymlinks: boolean, whether symlinks to the directories should be traversed too.
  300. * Defaults to `false`, meaning the content of the symlinked directory would not be deleted.
  301. * Only symlink would be removed in that default case.
  302. *
  303. * @throws ErrorException in case of failure
  304. */
  305. public static function removeDirectory($dir, $options = [])
  306. {
  307. if (!is_dir($dir)) {
  308. return;
  309. }
  310. if (isset($options['traverseSymlinks']) && $options['traverseSymlinks'] || !is_link($dir)) {
  311. if (!($handle = opendir($dir))) {
  312. return;
  313. }
  314. while (($file = readdir($handle)) !== false) {
  315. if ($file === '.' || $file === '..') {
  316. continue;
  317. }
  318. $path = $dir . DIRECTORY_SEPARATOR . $file;
  319. if (is_dir($path)) {
  320. static::removeDirectory($path, $options);
  321. } else {
  322. try {
  323. unlink($path);
  324. } catch (ErrorException $e) {
  325. if (DIRECTORY_SEPARATOR === '\\') {
  326. // last resort measure for Windows
  327. $lines = [];
  328. exec("DEL /F/Q \"$path\"", $lines, $deleteError);
  329. } else {
  330. throw $e;
  331. }
  332. }
  333. }
  334. }
  335. closedir($handle);
  336. }
  337. if (is_link($dir)) {
  338. unlink($dir);
  339. } else {
  340. rmdir($dir);
  341. }
  342. }
  343. /**
  344. * Returns the files found under the specified directory and subdirectories.
  345. * @param string $dir the directory under which the files will be looked for.
  346. * @param array $options options for file searching. Valid options are:
  347. *
  348. * - `filter`: callback, a PHP callback that is called for each directory or file.
  349. * The signature of the callback should be: `function ($path)`, where `$path` refers the full path to be filtered.
  350. * The callback can return one of the following values:
  351. *
  352. * * `true`: the directory or file will be returned (the `only` and `except` options will be ignored)
  353. * * `false`: the directory or file will NOT be returned (the `only` and `except` options will be ignored)
  354. * * `null`: the `only` and `except` options will determine whether the directory or file should be returned
  355. *
  356. * - `except`: array, list of patterns excluding from the results matching file or directory paths.
  357. * Patterns ending with slash ('/') apply to directory paths only, and patterns not ending with '/'
  358. * apply to file paths only. For example, '/a/b' matches all file paths ending with '/a/b';
  359. * and `.svn/` matches directory paths ending with `.svn`.
  360. * If the pattern does not contain a slash (`/`), it is treated as a shell glob pattern
  361. * and checked for a match against the pathname relative to `$dir`.
  362. * Otherwise, the pattern is treated as a shell glob suitable for consumption by `fnmatch(3)`
  363. * with the `FNM_PATHNAME` flag: wildcards in the pattern will not match a `/` in the pathname.
  364. * For example, `views/*.php` matches `views/index.php` but not `views/controller/index.php`.
  365. * A leading slash matches the beginning of the pathname. For example, `/*.php` matches `index.php` but not `views/start/index.php`.
  366. * An optional prefix `!` which negates the pattern; any matching file excluded by a previous pattern will become included again.
  367. * If a negated pattern matches, this will override lower precedence patterns sources. Put a backslash (`\`) in front of the first `!`
  368. * for patterns that begin with a literal `!`, for example, `\!important!.txt`.
  369. * Note, the '/' characters in a pattern matches both '/' and '\' in the paths.
  370. * - `only`: array, list of patterns that the file paths should match if they are to be returned. Directory paths
  371. * are not checked against them. Same pattern matching rules as in the `except` option are used.
  372. * If a file path matches a pattern in both `only` and `except`, it will NOT be returned.
  373. * - `caseSensitive`: boolean, whether patterns specified at `only` or `except` should be case sensitive. Defaults to `true`.
  374. * - `recursive`: boolean, whether the files under the subdirectories should also be looked for. Defaults to `true`.
  375. * @return array files found under the directory, in no particular order. Ordering depends on the files system used.
  376. * @throws InvalidParamException if the dir is invalid.
  377. */
  378. public static function findFiles($dir, $options = [])
  379. {
  380. if (!is_dir($dir)) {
  381. throw new InvalidParamException("The dir argument must be a directory: $dir");
  382. }
  383. $dir = rtrim($dir, DIRECTORY_SEPARATOR);
  384. if (!isset($options['basePath'])) {
  385. // this should be done only once
  386. $options['basePath'] = realpath($dir);
  387. $options = static::normalizeOptions($options);
  388. }
  389. $list = [];
  390. $handle = opendir($dir);
  391. if ($handle === false) {
  392. throw new InvalidParamException("Unable to open directory: $dir");
  393. }
  394. while (($file = readdir($handle)) !== false) {
  395. if ($file === '.' || $file === '..') {
  396. continue;
  397. }
  398. $path = $dir . DIRECTORY_SEPARATOR . $file;
  399. if (static::filterPath($path, $options)) {
  400. if (is_file($path)) {
  401. $list[] = $path;
  402. } elseif (is_dir($path) && (!isset($options['recursive']) || $options['recursive'])) {
  403. $list = array_merge($list, static::findFiles($path, $options));
  404. }
  405. }
  406. }
  407. closedir($handle);
  408. return $list;
  409. }
  410. /**
  411. * Checks if the given file path satisfies the filtering options.
  412. * @param string $path the path of the file or directory to be checked
  413. * @param array $options the filtering options. See [[findFiles()]] for explanations of
  414. * the supported options.
  415. * @return bool whether the file or directory satisfies the filtering options.
  416. */
  417. public static function filterPath($path, $options)
  418. {
  419. if (isset($options['filter'])) {
  420. $result = call_user_func($options['filter'], $path);
  421. if (is_bool($result)) {
  422. return $result;
  423. }
  424. }
  425. if (empty($options['except']) && empty($options['only'])) {
  426. return true;
  427. }
  428. $path = str_replace('\\', '/', $path);
  429. if (!empty($options['except'])) {
  430. if (($except = self::lastExcludeMatchingFromList($options['basePath'], $path, $options['except'])) !== null) {
  431. return $except['flags'] & self::PATTERN_NEGATIVE;
  432. }
  433. }
  434. if (!empty($options['only']) && !is_dir($path)) {
  435. if (($except = self::lastExcludeMatchingFromList($options['basePath'], $path, $options['only'])) !== null) {
  436. // don't check PATTERN_NEGATIVE since those entries are not prefixed with !
  437. return true;
  438. }
  439. return false;
  440. }
  441. return true;
  442. }
  443. /**
  444. * Creates a new directory.
  445. *
  446. * This method is similar to the PHP `mkdir()` function except that
  447. * it uses `chmod()` to set the permission of the created directory
  448. * in order to avoid the impact of the `umask` setting.
  449. *
  450. * @param string $path path of the directory to be created.
  451. * @param int $mode the permission to be set for the created directory.
  452. * @param bool $recursive whether to create parent directories if they do not exist.
  453. * @return bool whether the directory is created successfully
  454. * @throws \yii\base\Exception if the directory could not be created (i.e. php error due to parallel changes)
  455. */
  456. public static function createDirectory($path, $mode = 0775, $recursive = true)
  457. {
  458. if (is_dir($path)) {
  459. return true;
  460. }
  461. $parentDir = dirname($path);
  462. // recurse if parent dir does not exist and we are not at the root of the file system.
  463. if ($recursive && !is_dir($parentDir) && $parentDir !== $path) {
  464. static::createDirectory($parentDir, $mode, true);
  465. }
  466. try {
  467. if (!mkdir($path, $mode)) {
  468. return false;
  469. }
  470. } catch (\Exception $e) {
  471. if (!is_dir($path)) {// https://github.com/yiisoft/yii2/issues/9288
  472. throw new \yii\base\Exception("Failed to create directory \"$path\": " . $e->getMessage(), $e->getCode(), $e);
  473. }
  474. }
  475. try {
  476. return chmod($path, $mode);
  477. } catch (\Exception $e) {
  478. throw new \yii\base\Exception("Failed to change permissions for directory \"$path\": " . $e->getMessage(), $e->getCode(), $e);
  479. }
  480. }
  481. /**
  482. * Performs a simple comparison of file or directory names.
  483. *
  484. * Based on match_basename() from dir.c of git 1.8.5.3 sources.
  485. *
  486. * @param string $baseName file or directory name to compare with the pattern
  487. * @param string $pattern the pattern that $baseName will be compared against
  488. * @param int|bool $firstWildcard location of first wildcard character in the $pattern
  489. * @param int $flags pattern flags
  490. * @return bool whether the name matches against pattern
  491. */
  492. private static function matchBasename($baseName, $pattern, $firstWildcard, $flags)
  493. {
  494. if ($firstWildcard === false) {
  495. if ($pattern === $baseName) {
  496. return true;
  497. }
  498. } elseif ($flags & self::PATTERN_ENDSWITH) {
  499. /* "*literal" matching against "fooliteral" */
  500. $n = StringHelper::byteLength($pattern);
  501. if (StringHelper::byteSubstr($pattern, 1, $n) === StringHelper::byteSubstr($baseName, -$n, $n)) {
  502. return true;
  503. }
  504. }
  505. $fnmatchFlags = 0;
  506. if ($flags & self::PATTERN_CASE_INSENSITIVE) {
  507. $fnmatchFlags |= FNM_CASEFOLD;
  508. }
  509. return fnmatch($pattern, $baseName, $fnmatchFlags);
  510. }
  511. /**
  512. * Compares a path part against a pattern with optional wildcards.
  513. *
  514. * Based on match_pathname() from dir.c of git 1.8.5.3 sources.
  515. *
  516. * @param string $path full path to compare
  517. * @param string $basePath base of path that will not be compared
  518. * @param string $pattern the pattern that path part will be compared against
  519. * @param int|bool $firstWildcard location of first wildcard character in the $pattern
  520. * @param int $flags pattern flags
  521. * @return bool whether the path part matches against pattern
  522. */
  523. private static function matchPathname($path, $basePath, $pattern, $firstWildcard, $flags)
  524. {
  525. // match with FNM_PATHNAME; the pattern has base implicitly in front of it.
  526. if (isset($pattern[0]) && $pattern[0] === '/') {
  527. $pattern = StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern));
  528. if ($firstWildcard !== false && $firstWildcard !== 0) {
  529. $firstWildcard--;
  530. }
  531. }
  532. $namelen = StringHelper::byteLength($path) - (empty($basePath) ? 0 : StringHelper::byteLength($basePath) + 1);
  533. $name = StringHelper::byteSubstr($path, -$namelen, $namelen);
  534. if ($firstWildcard !== 0) {
  535. if ($firstWildcard === false) {
  536. $firstWildcard = StringHelper::byteLength($pattern);
  537. }
  538. // if the non-wildcard part is longer than the remaining pathname, surely it cannot match.
  539. if ($firstWildcard > $namelen) {
  540. return false;
  541. }
  542. if (strncmp($pattern, $name, $firstWildcard)) {
  543. return false;
  544. }
  545. $pattern = StringHelper::byteSubstr($pattern, $firstWildcard, StringHelper::byteLength($pattern));
  546. $name = StringHelper::byteSubstr($name, $firstWildcard, $namelen);
  547. // 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.
  548. if (empty($pattern) && empty($name)) {
  549. return true;
  550. }
  551. }
  552. $fnmatchFlags = FNM_PATHNAME;
  553. if ($flags & self::PATTERN_CASE_INSENSITIVE) {
  554. $fnmatchFlags |= FNM_CASEFOLD;
  555. }
  556. return fnmatch($pattern, $name, $fnmatchFlags);
  557. }
  558. /**
  559. * Scan the given exclude list in reverse to see whether pathname
  560. * should be ignored. The first match (i.e. the last on the list), if
  561. * any, determines the fate. Returns the element which
  562. * matched, or null for undecided.
  563. *
  564. * Based on last_exclude_matching_from_list() from dir.c of git 1.8.5.3 sources.
  565. *
  566. * @param string $basePath
  567. * @param string $path
  568. * @param array $excludes list of patterns to match $path against
  569. * @return string null or one of $excludes item as an array with keys: 'pattern', 'flags'
  570. * @throws InvalidParamException if any of the exclude patterns is not a string or an array with keys: pattern, flags, firstWildcard.
  571. */
  572. private static function lastExcludeMatchingFromList($basePath, $path, $excludes)
  573. {
  574. foreach (array_reverse($excludes) as $exclude) {
  575. if (is_string($exclude)) {
  576. $exclude = self::parseExcludePattern($exclude, false);
  577. }
  578. if (!isset($exclude['pattern']) || !isset($exclude['flags']) || !isset($exclude['firstWildcard'])) {
  579. throw new InvalidParamException('If exclude/include pattern is an array it must contain the pattern, flags and firstWildcard keys.');
  580. }
  581. if ($exclude['flags'] & self::PATTERN_MUSTBEDIR && !is_dir($path)) {
  582. continue;
  583. }
  584. if ($exclude['flags'] & self::PATTERN_NODIR) {
  585. if (self::matchBasename(basename($path), $exclude['pattern'], $exclude['firstWildcard'], $exclude['flags'])) {
  586. return $exclude;
  587. }
  588. continue;
  589. }
  590. if (self::matchPathname($path, $basePath, $exclude['pattern'], $exclude['firstWildcard'], $exclude['flags'])) {
  591. return $exclude;
  592. }
  593. }
  594. return null;
  595. }
  596. /**
  597. * Processes the pattern, stripping special characters like / and ! from the beginning and settings flags instead.
  598. * @param string $pattern
  599. * @param bool $caseSensitive
  600. * @throws \yii\base\InvalidParamException
  601. * @return array with keys: (string) pattern, (int) flags, (int|bool) firstWildcard
  602. */
  603. private static function parseExcludePattern($pattern, $caseSensitive)
  604. {
  605. if (!is_string($pattern)) {
  606. throw new InvalidParamException('Exclude/include pattern must be a string.');
  607. }
  608. $result = [
  609. 'pattern' => $pattern,
  610. 'flags' => 0,
  611. 'firstWildcard' => false,
  612. ];
  613. if (!$caseSensitive) {
  614. $result['flags'] |= self::PATTERN_CASE_INSENSITIVE;
  615. }
  616. if (!isset($pattern[0])) {
  617. return $result;
  618. }
  619. if ($pattern[0] === '!') {
  620. $result['flags'] |= self::PATTERN_NEGATIVE;
  621. $pattern = StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern));
  622. }
  623. if (StringHelper::byteLength($pattern) && StringHelper::byteSubstr($pattern, -1, 1) === '/') {
  624. $pattern = StringHelper::byteSubstr($pattern, 0, -1);
  625. $result['flags'] |= self::PATTERN_MUSTBEDIR;
  626. }
  627. if (strpos($pattern, '/') === false) {
  628. $result['flags'] |= self::PATTERN_NODIR;
  629. }
  630. $result['firstWildcard'] = self::firstWildcardInPattern($pattern);
  631. if ($pattern[0] === '*' && self::firstWildcardInPattern(StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern))) === false) {
  632. $result['flags'] |= self::PATTERN_ENDSWITH;
  633. }
  634. $result['pattern'] = $pattern;
  635. return $result;
  636. }
  637. /**
  638. * Searches for the first wildcard character in the pattern.
  639. * @param string $pattern the pattern to search in
  640. * @return int|bool position of first wildcard character or false if not found
  641. */
  642. private static function firstWildcardInPattern($pattern)
  643. {
  644. $wildcards = ['*', '?', '[', '\\'];
  645. $wildcardSearch = function ($r, $c) use ($pattern) {
  646. $p = strpos($pattern, $c);
  647. return $r === false ? $p : ($p === false ? $r : min($r, $p));
  648. };
  649. return array_reduce($wildcards, $wildcardSearch, false);
  650. }
  651. /**
  652. * @param array $options raw options
  653. * @return array normalized options
  654. * @since 2.0.12
  655. */
  656. protected static function normalizeOptions(array $options)
  657. {
  658. if (!array_key_exists('caseSensitive', $options)) {
  659. $options['caseSensitive'] = true;
  660. }
  661. if (isset($options['except'])) {
  662. foreach ($options['except'] as $key => $value) {
  663. if (is_string($value)) {
  664. $options['except'][$key] = self::parseExcludePattern($value, $options['caseSensitive']);
  665. }
  666. }
  667. }
  668. if (isset($options['only'])) {
  669. foreach ($options['only'] as $key => $value) {
  670. if (is_string($value)) {
  671. $options['only'][$key] = self::parseExcludePattern($value, $options['caseSensitive']);
  672. }
  673. }
  674. }
  675. return $options;
  676. }
  677. }