BaseFileHelper.php 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  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. if (function_exists('exec') && file_exists($path)) {
  386. exec('DEL /F/Q ' . escapeshellarg($path));
  387. return !file_exists($path);
  388. }
  389. return false;
  390. }
  391. }
  392. /**
  393. * Returns the files found under the specified directory and subdirectories.
  394. * @param string $dir the directory under which the files will be looked for.
  395. * @param array $options options for file searching. Valid options are:
  396. *
  397. * - `filter`: callback, a PHP callback that is called for each directory or file.
  398. * The signature of the callback should be: `function ($path)`, where `$path` refers the full path to be filtered.
  399. * The callback can return one of the following values:
  400. *
  401. * * `true`: the directory or file will be returned (the `only` and `except` options will be ignored)
  402. * * `false`: the directory or file will NOT be returned (the `only` and `except` options will be ignored)
  403. * * `null`: the `only` and `except` options will determine whether the directory or file should be returned
  404. *
  405. * - `except`: array, list of patterns excluding from the results matching file or directory paths.
  406. * Patterns ending with slash ('/') apply to directory paths only, and patterns not ending with '/'
  407. * apply to file paths only. For example, '/a/b' matches all file paths ending with '/a/b';
  408. * and `.svn/` matches directory paths ending with `.svn`.
  409. * If the pattern does not contain a slash (`/`), it is treated as a shell glob pattern
  410. * and checked for a match against the pathname relative to `$dir`.
  411. * Otherwise, the pattern is treated as a shell glob suitable for consumption by `fnmatch(3)`
  412. * with the `FNM_PATHNAME` flag: wildcards in the pattern will not match a `/` in the pathname.
  413. * For example, `views/*.php` matches `views/index.php` but not `views/controller/index.php`.
  414. * A leading slash matches the beginning of the pathname. For example, `/*.php` matches `index.php` but not `views/start/index.php`.
  415. * An optional prefix `!` which negates the pattern; any matching file excluded by a previous pattern will become included again.
  416. * If a negated pattern matches, this will override lower precedence patterns sources. Put a backslash (`\`) in front of the first `!`
  417. * for patterns that begin with a literal `!`, for example, `\!important!.txt`.
  418. * Note, the '/' characters in a pattern matches both '/' and '\' in the paths.
  419. * - `only`: array, list of patterns that the file paths should match if they are to be returned. Directory paths
  420. * are not checked against them. Same pattern matching rules as in the `except` option are used.
  421. * If a file path matches a pattern in both `only` and `except`, it will NOT be returned.
  422. * - `caseSensitive`: boolean, whether patterns specified at `only` or `except` should be case sensitive. Defaults to `true`.
  423. * - `recursive`: boolean, whether the files under the subdirectories should also be looked for. Defaults to `true`.
  424. * @return array files found under the directory, in no particular order. Ordering depends on the files system used.
  425. * @throws InvalidArgumentException if the dir is invalid.
  426. */
  427. public static function findFiles($dir, $options = [])
  428. {
  429. $dir = self::clearDir($dir);
  430. $options = self::setBasePath($dir, $options);
  431. $list = [];
  432. $handle = self::openDir($dir);
  433. while (($file = readdir($handle)) !== false) {
  434. if ($file === '.' || $file === '..') {
  435. continue;
  436. }
  437. $path = $dir . DIRECTORY_SEPARATOR . $file;
  438. if (static::filterPath($path, $options)) {
  439. if (is_file($path)) {
  440. $list[] = $path;
  441. } elseif (is_dir($path) && (!isset($options['recursive']) || $options['recursive'])) {
  442. $list = array_merge($list, static::findFiles($path, $options));
  443. }
  444. }
  445. }
  446. closedir($handle);
  447. return $list;
  448. }
  449. /**
  450. * Returns the directories found under the specified directory and subdirectories.
  451. * @param string $dir the directory under which the files will be looked for.
  452. * @param array $options options for directory searching. Valid options are:
  453. *
  454. * - `filter`: callback, a PHP callback that is called for each directory or file.
  455. * The signature of the callback should be: `function ($path)`, where `$path` refers the full path to be filtered.
  456. * The callback can return one of the following values:
  457. *
  458. * * `true`: the directory will be returned
  459. * * `false`: the directory will NOT be returned
  460. *
  461. * - `recursive`: boolean, whether the files under the subdirectories should also be looked for. Defaults to `true`.
  462. * @return array directories found under the directory, in no particular order. Ordering depends on the files system used.
  463. * @throws InvalidArgumentException if the dir is invalid.
  464. * @since 2.0.14
  465. */
  466. public static function findDirectories($dir, $options = [])
  467. {
  468. $dir = self::clearDir($dir);
  469. $options = self::setBasePath($dir, $options);
  470. $list = [];
  471. $handle = self::openDir($dir);
  472. while (($file = readdir($handle)) !== false) {
  473. if ($file === '.' || $file === '..') {
  474. continue;
  475. }
  476. $path = $dir . DIRECTORY_SEPARATOR . $file;
  477. if (is_dir($path) && static::filterPath($path, $options)) {
  478. $list[] = $path;
  479. if (!isset($options['recursive']) || $options['recursive']) {
  480. $list = array_merge($list, static::findDirectories($path, $options));
  481. }
  482. }
  483. }
  484. closedir($handle);
  485. return $list;
  486. }
  487. /**
  488. * @param string $dir
  489. */
  490. private static function setBasePath($dir, $options)
  491. {
  492. if (!isset($options['basePath'])) {
  493. // this should be done only once
  494. $options['basePath'] = realpath($dir);
  495. $options = static::normalizeOptions($options);
  496. }
  497. return $options;
  498. }
  499. /**
  500. * @param string $dir
  501. */
  502. private static function openDir($dir)
  503. {
  504. $handle = opendir($dir);
  505. if ($handle === false) {
  506. throw new InvalidArgumentException("Unable to open directory: $dir");
  507. }
  508. return $handle;
  509. }
  510. /**
  511. * @param string $dir
  512. */
  513. private static function clearDir($dir)
  514. {
  515. if (!is_dir($dir)) {
  516. throw new InvalidArgumentException("The dir argument must be a directory: $dir");
  517. }
  518. return rtrim($dir, DIRECTORY_SEPARATOR);
  519. }
  520. /**
  521. * Checks if the given file path satisfies the filtering options.
  522. * @param string $path the path of the file or directory to be checked
  523. * @param array $options the filtering options. See [[findFiles()]] for explanations of
  524. * the supported options.
  525. * @return bool whether the file or directory satisfies the filtering options.
  526. */
  527. public static function filterPath($path, $options)
  528. {
  529. if (isset($options['filter'])) {
  530. $result = call_user_func($options['filter'], $path);
  531. if (is_bool($result)) {
  532. return $result;
  533. }
  534. }
  535. if (empty($options['except']) && empty($options['only'])) {
  536. return true;
  537. }
  538. $path = str_replace('\\', '/', $path);
  539. if (!empty($options['except'])) {
  540. if (($except = self::lastExcludeMatchingFromList($options['basePath'], $path, $options['except'])) !== null) {
  541. return $except['flags'] & self::PATTERN_NEGATIVE;
  542. }
  543. }
  544. if (!empty($options['only']) && !is_dir($path)) {
  545. if (($except = self::lastExcludeMatchingFromList($options['basePath'], $path, $options['only'])) !== null) {
  546. // don't check PATTERN_NEGATIVE since those entries are not prefixed with !
  547. return true;
  548. }
  549. return false;
  550. }
  551. return true;
  552. }
  553. /**
  554. * Creates a new directory.
  555. *
  556. * This method is similar to the PHP `mkdir()` function except that
  557. * it uses `chmod()` to set the permission of the created directory
  558. * in order to avoid the impact of the `umask` setting.
  559. *
  560. * @param string $path path of the directory to be created.
  561. * @param int $mode the permission to be set for the created directory.
  562. * @param bool $recursive whether to create parent directories if they do not exist.
  563. * @return bool whether the directory is created successfully
  564. * @throws \yii\base\Exception if the directory could not be created (i.e. php error due to parallel changes)
  565. */
  566. public static function createDirectory($path, $mode = 0775, $recursive = true)
  567. {
  568. if (is_dir($path)) {
  569. return true;
  570. }
  571. $parentDir = dirname($path);
  572. // recurse if parent dir does not exist and we are not at the root of the file system.
  573. if ($recursive && !is_dir($parentDir) && $parentDir !== $path) {
  574. static::createDirectory($parentDir, $mode, true);
  575. }
  576. try {
  577. if (!mkdir($path, $mode)) {
  578. return false;
  579. }
  580. } catch (\Exception $e) {
  581. if (!is_dir($path)) {// https://github.com/yiisoft/yii2/issues/9288
  582. throw new \yii\base\Exception("Failed to create directory \"$path\": " . $e->getMessage(), $e->getCode(), $e);
  583. }
  584. }
  585. try {
  586. return chmod($path, $mode);
  587. } catch (\Exception $e) {
  588. throw new \yii\base\Exception("Failed to change permissions for directory \"$path\": " . $e->getMessage(), $e->getCode(), $e);
  589. }
  590. }
  591. /**
  592. * Performs a simple comparison of file or directory names.
  593. *
  594. * Based on match_basename() from dir.c of git 1.8.5.3 sources.
  595. *
  596. * @param string $baseName file or directory name to compare with the pattern
  597. * @param string $pattern the pattern that $baseName will be compared against
  598. * @param int|bool $firstWildcard location of first wildcard character in the $pattern
  599. * @param int $flags pattern flags
  600. * @return bool whether the name matches against pattern
  601. */
  602. private static function matchBasename($baseName, $pattern, $firstWildcard, $flags)
  603. {
  604. if ($firstWildcard === false) {
  605. if ($pattern === $baseName) {
  606. return true;
  607. }
  608. } elseif ($flags & self::PATTERN_ENDSWITH) {
  609. /* "*literal" matching against "fooliteral" */
  610. $n = StringHelper::byteLength($pattern);
  611. if (StringHelper::byteSubstr($pattern, 1, $n) === StringHelper::byteSubstr($baseName, -$n, $n)) {
  612. return true;
  613. }
  614. }
  615. $matchOptions = [];
  616. if ($flags & self::PATTERN_CASE_INSENSITIVE) {
  617. $matchOptions['caseSensitive'] = false;
  618. }
  619. return StringHelper::matchWildcard($pattern, $baseName, $matchOptions);
  620. }
  621. /**
  622. * Compares a path part against a pattern with optional wildcards.
  623. *
  624. * Based on match_pathname() from dir.c of git 1.8.5.3 sources.
  625. *
  626. * @param string $path full path to compare
  627. * @param string $basePath base of path that will not be compared
  628. * @param string $pattern the pattern that path part will be compared against
  629. * @param int|bool $firstWildcard location of first wildcard character in the $pattern
  630. * @param int $flags pattern flags
  631. * @return bool whether the path part matches against pattern
  632. */
  633. private static function matchPathname($path, $basePath, $pattern, $firstWildcard, $flags)
  634. {
  635. // match with FNM_PATHNAME; the pattern has base implicitly in front of it.
  636. if (isset($pattern[0]) && $pattern[0] === '/') {
  637. $pattern = StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern));
  638. if ($firstWildcard !== false && $firstWildcard !== 0) {
  639. $firstWildcard--;
  640. }
  641. }
  642. $namelen = StringHelper::byteLength($path) - (empty($basePath) ? 0 : StringHelper::byteLength($basePath) + 1);
  643. $name = StringHelper::byteSubstr($path, -$namelen, $namelen);
  644. if ($firstWildcard !== 0) {
  645. if ($firstWildcard === false) {
  646. $firstWildcard = StringHelper::byteLength($pattern);
  647. }
  648. // if the non-wildcard part is longer than the remaining pathname, surely it cannot match.
  649. if ($firstWildcard > $namelen) {
  650. return false;
  651. }
  652. if (strncmp($pattern, $name, $firstWildcard)) {
  653. return false;
  654. }
  655. $pattern = StringHelper::byteSubstr($pattern, $firstWildcard, StringHelper::byteLength($pattern));
  656. $name = StringHelper::byteSubstr($name, $firstWildcard, $namelen);
  657. // 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.
  658. if (empty($pattern) && empty($name)) {
  659. return true;
  660. }
  661. }
  662. $matchOptions = [
  663. 'filePath' => true
  664. ];
  665. if ($flags & self::PATTERN_CASE_INSENSITIVE) {
  666. $matchOptions['caseSensitive'] = false;
  667. }
  668. return StringHelper::matchWildcard($pattern, $name, $matchOptions);
  669. }
  670. /**
  671. * Scan the given exclude list in reverse to see whether pathname
  672. * should be ignored. The first match (i.e. the last on the list), if
  673. * any, determines the fate. Returns the element which
  674. * matched, or null for undecided.
  675. *
  676. * Based on last_exclude_matching_from_list() from dir.c of git 1.8.5.3 sources.
  677. *
  678. * @param string $basePath
  679. * @param string $path
  680. * @param array $excludes list of patterns to match $path against
  681. * @return array|null null or one of $excludes item as an array with keys: 'pattern', 'flags'
  682. * @throws InvalidArgumentException if any of the exclude patterns is not a string or an array with keys: pattern, flags, firstWildcard.
  683. */
  684. private static function lastExcludeMatchingFromList($basePath, $path, $excludes)
  685. {
  686. foreach (array_reverse($excludes) as $exclude) {
  687. if (is_string($exclude)) {
  688. $exclude = self::parseExcludePattern($exclude, false);
  689. }
  690. if (!isset($exclude['pattern']) || !isset($exclude['flags']) || !isset($exclude['firstWildcard'])) {
  691. throw new InvalidArgumentException('If exclude/include pattern is an array it must contain the pattern, flags and firstWildcard keys.');
  692. }
  693. if ($exclude['flags'] & self::PATTERN_MUSTBEDIR && !is_dir($path)) {
  694. continue;
  695. }
  696. if ($exclude['flags'] & self::PATTERN_NODIR) {
  697. if (self::matchBasename(basename($path), $exclude['pattern'], $exclude['firstWildcard'], $exclude['flags'])) {
  698. return $exclude;
  699. }
  700. continue;
  701. }
  702. if (self::matchPathname($path, $basePath, $exclude['pattern'], $exclude['firstWildcard'], $exclude['flags'])) {
  703. return $exclude;
  704. }
  705. }
  706. return null;
  707. }
  708. /**
  709. * Processes the pattern, stripping special characters like / and ! from the beginning and settings flags instead.
  710. * @param string $pattern
  711. * @param bool $caseSensitive
  712. * @throws InvalidArgumentException
  713. * @return array with keys: (string) pattern, (int) flags, (int|bool) firstWildcard
  714. */
  715. private static function parseExcludePattern($pattern, $caseSensitive)
  716. {
  717. if (!is_string($pattern)) {
  718. throw new InvalidArgumentException('Exclude/include pattern must be a string.');
  719. }
  720. $result = [
  721. 'pattern' => $pattern,
  722. 'flags' => 0,
  723. 'firstWildcard' => false,
  724. ];
  725. if (!$caseSensitive) {
  726. $result['flags'] |= self::PATTERN_CASE_INSENSITIVE;
  727. }
  728. if (!isset($pattern[0])) {
  729. return $result;
  730. }
  731. if ($pattern[0] === '!') {
  732. $result['flags'] |= self::PATTERN_NEGATIVE;
  733. $pattern = StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern));
  734. }
  735. if (StringHelper::byteLength($pattern) && StringHelper::byteSubstr($pattern, -1, 1) === '/') {
  736. $pattern = StringHelper::byteSubstr($pattern, 0, -1);
  737. $result['flags'] |= self::PATTERN_MUSTBEDIR;
  738. }
  739. if (strpos($pattern, '/') === false) {
  740. $result['flags'] |= self::PATTERN_NODIR;
  741. }
  742. $result['firstWildcard'] = self::firstWildcardInPattern($pattern);
  743. if ($pattern[0] === '*' && self::firstWildcardInPattern(StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern))) === false) {
  744. $result['flags'] |= self::PATTERN_ENDSWITH;
  745. }
  746. $result['pattern'] = $pattern;
  747. return $result;
  748. }
  749. /**
  750. * Searches for the first wildcard character in the pattern.
  751. * @param string $pattern the pattern to search in
  752. * @return int|bool position of first wildcard character or false if not found
  753. */
  754. private static function firstWildcardInPattern($pattern)
  755. {
  756. $wildcards = ['*', '?', '[', '\\'];
  757. $wildcardSearch = function ($r, $c) use ($pattern) {
  758. $p = strpos($pattern, $c);
  759. return $r === false ? $p : ($p === false ? $r : min($r, $p));
  760. };
  761. return array_reduce($wildcards, $wildcardSearch, false);
  762. }
  763. /**
  764. * @param array $options raw options
  765. * @return array normalized options
  766. * @since 2.0.12
  767. */
  768. protected static function normalizeOptions(array $options)
  769. {
  770. if (!array_key_exists('caseSensitive', $options)) {
  771. $options['caseSensitive'] = true;
  772. }
  773. if (isset($options['except'])) {
  774. foreach ($options['except'] as $key => $value) {
  775. if (is_string($value)) {
  776. $options['except'][$key] = self::parseExcludePattern($value, $options['caseSensitive']);
  777. }
  778. }
  779. }
  780. if (isset($options['only'])) {
  781. foreach ($options['only'] as $key => $value) {
  782. if (is_string($value)) {
  783. $options['only'][$key] = self::parseExcludePattern($value, $options['caseSensitive']);
  784. }
  785. }
  786. }
  787. return $options;
  788. }
  789. }