BaseFileHelper.php 41 KB

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