BaseFileHelper.php 40 KB

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