BaseFileHelper.php 37 KB

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