BaseFileHelper.php 36 KB

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