BaseFileHelper.php 13.4 KB
Newer Older
Qiang Xue committed
1 2 3 4 5 6 7 8 9
<?php
/**
 * Filesystem helper class file.
 *
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

10
namespace yii\helpers;
Qiang Xue committed
11

Qiang Xue committed
12
use Yii;
Qiang Xue committed
13 14

/**
15
 * BaseFileHelper provides concrete implementation for [[FileHelper]].
16
 *
17
 * Do not use BaseFileHelper. Use [[FileHelper]] instead.
Qiang Xue committed
18 19 20 21 22
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @author Alex Makarov <sam@rmcreative.ru>
 * @since 2.0
 */
23
class BaseFileHelper
Qiang Xue committed
24 25 26 27 28 29 30 31 32 33 34 35
{
	/**
	 * Normalizes a file/directory path.
	 * After normalization, the directory separators in the path will be `DIRECTORY_SEPARATOR`,
	 * and any trailing directory separators will be removed. For example, '/home\demo/' on Linux
	 * will be normalized as '/home/demo'.
	 * @param string $path the file/directory path to be normalized
	 * @param string $ds the directory separator to be used in the normalized result. Defaults to `DIRECTORY_SEPARATOR`.
	 * @return string the normalized file/directory path
	 */
	public static function normalizePath($path, $ds = DIRECTORY_SEPARATOR)
	{
Alexander Makarov committed
36
		return rtrim(strtr($path, ['/' => $ds, '\\' => $ds]), $ds);
Qiang Xue committed
37 38 39 40 41 42 43
	}

	/**
	 * Returns the localized version of a specified file.
	 *
	 * The searching is based on the specified language code. In particular,
	 * a file with the same name will be looked for under the subdirectory
Qiang Xue committed
44 45 46
	 * whose name is the same as the language code. For example, given the file "path/to/view.php"
	 * and language code "zh_CN", the localized file will be looked for as
	 * "path/to/zh_CN/view.php". If the file is not found, the original file
Qiang Xue committed
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
	 * will be returned.
	 *
	 * If the target and the source language codes are the same,
	 * the original file will be returned.
	 *
	 * @param string $file the original file
	 * @param string $language the target language that the file should be localized to.
	 * If not set, the value of [[\yii\base\Application::language]] will be used.
	 * @param string $sourceLanguage the language that the original file is in.
	 * If not set, the value of [[\yii\base\Application::sourceLanguage]] will be used.
	 * @return string the matching localized file, or the original file if the localized version is not found.
	 * If the target and the source language codes are the same, the original file will be returned.
	 */
	public static function localize($file, $language = null, $sourceLanguage = null)
	{
		if ($language === null) {
Qiang Xue committed
63
			$language = Yii::$app->language;
Qiang Xue committed
64 65
		}
		if ($sourceLanguage === null) {
Qiang Xue committed
66
			$sourceLanguage = Yii::$app->sourceLanguage;
Qiang Xue committed
67 68 69 70
		}
		if ($language === $sourceLanguage) {
			return $file;
		}
71
		$desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $sourceLanguage . DIRECTORY_SEPARATOR . basename($file);
Qiang Xue committed
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
		return is_file($desiredFile) ? $desiredFile : $file;
	}

	/**
	 * Determines the MIME type of the specified file.
	 * This method will first try to determine the MIME type based on
	 * [finfo_open](http://php.net/manual/en/function.finfo-open.php). If this doesn't work, it will
	 * fall back to [[getMimeTypeByExtension()]].
	 * @param string $file the file name.
	 * @param string $magicFile name of the optional magic database file, usually something like `/path/to/magic.mime`.
	 * This will be passed as the second parameter to [finfo_open](http://php.net/manual/en/function.finfo-open.php).
	 * @param boolean $checkExtension whether to use the file extension to determine the MIME type in case
	 * `finfo_open()` cannot determine it.
	 * @return string the MIME type (e.g. `text/plain`). Null is returned if the MIME type cannot be determined.
	 */
	public static function getMimeType($file, $magicFile = null, $checkExtension = true)
	{
		if (function_exists('finfo_open')) {
			$info = finfo_open(FILEINFO_MIME_TYPE, $magicFile);
91 92
			if ($info) {
				$result = finfo_file($info, $file);
Qiang Xue committed
93
				finfo_close($info);
94 95 96
				if ($result !== false) {
					return $result;
				}
Qiang Xue committed
97 98 99
			}
		}

100
		return $checkExtension ? static::getMimeTypeByExtension($file) : null;
Qiang Xue committed
101 102 103 104 105 106 107 108 109 110 111 112
	}

	/**
	 * Determines the MIME type based on the extension name of the specified file.
	 * This method will use a local map between extension names and MIME types.
	 * @param string $file the file name.
	 * @param string $magicFile the path of the file that contains all available MIME type information.
	 * If this is not set, the default file aliased by `@yii/util/mimeTypes.php` will be used.
	 * @return string the MIME type. Null is returned if the MIME type cannot be determined.
	 */
	public static function getMimeTypeByExtension($file, $magicFile = null)
	{
Alexander Makarov committed
113
		static $mimeTypes = [];
Qiang Xue committed
114
		if ($magicFile === null) {
Qiang Xue committed
115 116 117 118
			$magicFile = __DIR__ . '/mimeTypes.php';
		}
		if (!isset($mimeTypes[$magicFile])) {
			$mimeTypes[$magicFile] = require($magicFile);
Qiang Xue committed
119 120 121
		}
		if (($ext = pathinfo($file, PATHINFO_EXTENSION)) !== '') {
			$ext = strtolower($ext);
Qiang Xue committed
122 123
			if (isset($mimeTypes[$magicFile][$ext])) {
				return $mimeTypes[$magicFile][$ext];
Qiang Xue committed
124 125 126 127 128
			}
		}
		return null;
	}

129 130 131 132 133 134 135
	/**
	 * Copies a whole directory as another one.
	 * The files and sub-directories will also be copied over.
	 * @param string $src the source directory
	 * @param string $dst the destination directory
	 * @param array $options options for directory copy. Valid options are:
	 *
136
	 * - dirMode: integer, the permission to be set for newly copied directories. Defaults to 0775.
137
	 * - fileMode:  integer, the permission to be set for newly copied files. Defaults to the current environment setting.
138 139 140 141 142 143 144 145
	 * - filter: callback, a PHP callback that is called for each directory or file.
	 *   The signature of the callback should be: `function ($path)`, where `$path` refers the full path to be filtered.
	 *   The callback can return one of the following values:
	 *
	 *   * true: the directory or file will be copied (the "only" and "except" options will be ignored)
	 *   * false: the directory or file will NOT be copied (the "only" and "except" options will be ignored)
	 *   * null: the "only" and "except" options will determine whether the directory or file should be copied
	 *
146 147 148 149 150 151
	 * - only: array, list of patterns that the file paths should match if they want to be copied.
	 *   A path matches a pattern if it contains the pattern string at its end.
	 *   For example, '.php' matches all file paths ending with '.php'.
	 *   Note, the '/' characters in a pattern matches both '/' and '\' in the paths.
	 *   If a file path matches a pattern in both "only" and "except", it will NOT be copied.
	 * - except: array, list of patterns that the files or directories should match if they want to be excluded from being copied.
152 153 154 155
	 *   A path matches a pattern if it contains the pattern string at its end.
	 *   Patterns ending with '/' apply to directory paths only, and patterns not ending with '/'
	 *   apply to file paths only. For example, '/a/b' matches all file paths ending with '/a/b';
	 *   and '.svn/' matches directory paths ending with '.svn'. Note, the '/' characters in a pattern matches
156
	 *   both '/' and '\' in the paths.
Qiang Xue committed
157
	 * - recursive: boolean, whether the files under the subdirectories should also be copied. Defaults to true.
158
	 * - beforeCopy: callback, a PHP callback that is called before copying each sub-directory or file.
Qiang Xue committed
159
	 *   If the callback returns false, the copy operation for the sub-directory or file will be cancelled.
160 161
	 *   The signature of the callback should be: `function ($from, $to)`, where `$from` is the sub-directory or
	 *   file to be copied from, while `$to` is the copy target.
Qiang Xue committed
162
	 * - afterCopy: callback, a PHP callback that is called after each sub-directory or file is successfully copied.
163
	 *   The signature of the callback should be: `function ($from, $to)`, where `$from` is the sub-directory or
Qiang Xue committed
164
	 *   file copied from, while `$to` is the copy target.
165
	 */
Alexander Makarov committed
166
	public static function copyDirectory($src, $dst, $options = [])
167 168
	{
		if (!is_dir($dst)) {
169
			static::createDirectory($dst, isset($options['dirMode']) ? $options['dirMode'] : 0775, true);
170 171 172 173 174 175 176
		}

		$handle = opendir($src);
		while (($file = readdir($handle)) !== false) {
			if ($file === '.' || $file === '..') {
				continue;
			}
177 178
			$from = $src . DIRECTORY_SEPARATOR . $file;
			$to = $dst . DIRECTORY_SEPARATOR . $file;
Qiang Xue committed
179
			if (static::filterPath($from, $options)) {
Qiang Xue committed
180
				if (isset($options['beforeCopy']) && !call_user_func($options['beforeCopy'], $from, $to)) {
Qiang Xue committed
181
					continue;
182
				}
183 184
				if (is_file($from)) {
					copy($from, $to);
185
					if (isset($options['fileMode'])) {
Qiang Xue committed
186
						@chmod($to, $options['fileMode']);
187 188
					}
				} else {
189 190 191 192
					static::copyDirectory($from, $to, $options);
				}
				if (isset($options['afterCopy'])) {
					call_user_func($options['afterCopy'], $from, $to);
193 194 195 196 197
				}
			}
		}
		closedir($handle);
	}
198 199

	/**
Qiang Xue committed
200 201
	 * Removes a directory (and all its content) recursively.
	 * @param string $dir the directory to be deleted recursively.
202
	 */
203
	public static function removeDirectory($dir)
204
	{
Qiang Xue committed
205 206 207 208 209
		if (!is_dir($dir) || !($handle = opendir($dir))) {
			return;
		}
		while (($file = readdir($handle)) !== false) {
			if ($file === '.' || $file === '..') {
210 211
				continue;
			}
Qiang Xue committed
212 213 214
			$path = $dir . DIRECTORY_SEPARATOR . $file;
			if (is_file($path)) {
				unlink($path);
215
			} else {
Qiang Xue committed
216
				static::removeDirectory($path);
217 218
			}
		}
Qiang Xue committed
219 220
		closedir($handle);
		rmdir($dir);
221
	}
222 223 224 225 226

	/**
	 * Returns the files found under the specified directory and subdirectories.
	 * @param string $dir the directory under which the files will be looked for.
	 * @param array $options options for file searching. Valid options are:
Qiang Xue committed
227
	 *
228
	 * - filter: callback, a PHP callback that is called for each directory or file.
Qiang Xue committed
229
	 *   The signature of the callback should be: `function ($path)`, where `$path` refers the full path to be filtered.
230 231 232 233 234 235
	 *   The callback can return one of the following values:
	 *
	 *   * true: the directory or file will be returned (the "only" and "except" options will be ignored)
	 *   * false: the directory or file will NOT be returned (the "only" and "except" options will be ignored)
	 *   * null: the "only" and "except" options will determine whether the directory or file should be returned
	 *
236 237 238 239 240 241
	 * - only: array, list of patterns that the file paths should match if they want to be returned.
	 *   A path matches a pattern if it contains the pattern string at its end.
	 *   For example, '.php' matches all file paths ending with '.php'.
	 *   Note, the '/' characters in a pattern matches both '/' and '\' in the paths.
	 *   If a file path matches a pattern in both "only" and "except", it will NOT be returned.
	 * - except: array, list of patterns that the file paths or directory paths should match if they want to be excluded from the result.
242 243 244 245
	 *   A path matches a pattern if it contains the pattern string at its end.
	 *   Patterns ending with '/' apply to directory paths only, and patterns not ending with '/'
	 *   apply to file paths only. For example, '/a/b' matches all file paths ending with '/a/b';
	 *   and '.svn/' matches directory paths ending with '.svn'. Note, the '/' characters in a pattern matches
246
	 *   both '/' and '\' in the paths.
247
	 * - recursive: boolean, whether the files under the subdirectories should also be looked for. Defaults to true.
248 249
	 * @return array files found under the directory. The file list is sorted.
	 */
Alexander Makarov committed
250
	public static function findFiles($dir, $options = [])
251
	{
Alexander Makarov committed
252
		$list = [];
253 254 255 256 257 258
		$handle = opendir($dir);
		while (($file = readdir($handle)) !== false) {
			if ($file === '.' || $file === '..') {
				continue;
			}
			$path = $dir . DIRECTORY_SEPARATOR . $file;
Qiang Xue committed
259
			if (static::filterPath($path, $options)) {
Qiang Xue committed
260
				if (is_file($path)) {
261
					$list[] = $path;
Qiang Xue committed
262 263
				} elseif (!isset($options['recursive']) || $options['recursive']) {
					$list = array_merge($list, static::findFiles($path, $options));
264 265 266 267 268 269 270 271
				}
			}
		}
		closedir($handle);
		return $list;
	}

	/**
Qiang Xue committed
272 273 274 275 276
	 * Checks if the given file path satisfies the filtering options.
	 * @param string $path the path of the file or directory to be checked
	 * @param array $options the filtering options. See [[findFiles()]] for explanations of
	 * the supported options.
	 * @return boolean whether the file or directory satisfies the filtering options.
277
	 */
Qiang Xue committed
278
	public static function filterPath($path, $options)
279
	{
280 281 282 283 284
		if (isset($options['filter'])) {
			$result = call_user_func($options['filter'], $path);
			if (is_bool($result)) {
				return $result;
			}
285
		}
Qiang Xue committed
286
		$path = str_replace('\\', '/', $path);
287
		if ($isDir = is_dir($path)) {
288 289
			$path .= '/';
		}
290
		$n = StringHelper::strlen($path);
291

Qiang Xue committed
292 293
		if (!empty($options['except'])) {
			foreach ($options['except'] as $name) {
294
				if (StringHelper::substr($path, -StringHelper::strlen($name), $n) === $name) {
Qiang Xue committed
295 296 297 298
					return false;
				}
			}
		}
299 300

		if (!$isDir && !empty($options['only'])) {
Qiang Xue committed
301
			foreach ($options['only'] as $name) {
302
				if (StringHelper::substr($path, -StringHelper::strlen($name), $n) === $name) {
303
					return true;
304 305
				}
			}
306
			return false;
307
		}
Qiang Xue committed
308
		return true;
309
	}
310 311

	/**
312
	 * Creates a new directory.
Qiang Xue committed
313 314 315 316
	 *
	 * This method is similar to the PHP `mkdir()` function except that
	 * it uses `chmod()` to set the permission of the created directory
	 * in order to avoid the impact of the `umask` setting.
317
	 *
318 319
	 * @param string $path path of the directory to be created.
	 * @param integer $mode the permission to be set for the created directory.
Qiang Xue committed
320 321
	 * @param boolean $recursive whether to create parent directories if they do not exist.
	 * @return boolean whether the directory is created successfully
322
	 */
323
	public static function createDirectory($path, $mode = 0775, $recursive = true)
324
	{
Qiang Xue committed
325 326 327 328 329
		if (is_dir($path)) {
			return true;
		}
		$parentDir = dirname($path);
		if ($recursive && !is_dir($parentDir)) {
330
			static::createDirectory($parentDir, $mode, true);
331 332 333 334 335
		}
		$result = mkdir($path, $mode);
		chmod($path, $mode);
		return $result;
	}
Zander Baldwin committed
336
}