BaseFileHelper.php 13.9 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
	 * whose name is the same as the language code. For example, given the file "path/to/view.php"
45 46
	 * 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, it will try a fallback with just a language code that is
Alexander Makarov committed
47
	 * "zh" i.e. "path/to/zh/view.php". If it is not found as well the original file will be returned.
Qiang Xue committed
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
	 *
	 * 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 . $language . DIRECTORY_SEPARATOR . basename($file);
Alexander Makarov committed
72 73 74 75 76 77 78 79 80 81
		if (is_file($desiredFile)) {
			return $desiredFile;
		} else {
			$language = substr($language, 0, 2);
			if ($language === $sourceLanguage) {
				return $file;
			}
			$desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . basename($file);
			return is_file($desiredFile) ? $desiredFile : $file;
		}
Qiang Xue committed
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
	}

	/**
	 * 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);
100 101
			if ($info) {
				$result = finfo_file($info, $file);
Qiang Xue committed
102
				finfo_close($info);
103 104 105
				if ($result !== false) {
					return $result;
				}
Qiang Xue committed
106 107 108
			}
		}

109
		return $checkExtension ? static::getMimeTypeByExtension($file) : null;
Qiang Xue committed
110 111 112 113 114 115 116 117 118 119 120 121
	}

	/**
	 * 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
122
		static $mimeTypes = [];
Qiang Xue committed
123
		if ($magicFile === null) {
Qiang Xue committed
124 125 126 127
			$magicFile = __DIR__ . '/mimeTypes.php';
		}
		if (!isset($mimeTypes[$magicFile])) {
			$mimeTypes[$magicFile] = require($magicFile);
Qiang Xue committed
128 129 130
		}
		if (($ext = pathinfo($file, PATHINFO_EXTENSION)) !== '') {
			$ext = strtolower($ext);
Qiang Xue committed
131 132
			if (isset($mimeTypes[$magicFile][$ext])) {
				return $mimeTypes[$magicFile][$ext];
Qiang Xue committed
133 134 135 136 137
			}
		}
		return null;
	}

138 139 140 141 142 143 144
	/**
	 * 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:
	 *
145
	 * - dirMode: integer, the permission to be set for newly copied directories. Defaults to 0775.
146
	 * - fileMode:  integer, the permission to be set for newly copied files. Defaults to the current environment setting.
147 148 149 150 151 152 153 154
	 * - 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
	 *
155 156 157 158 159 160
	 * - 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.
161 162 163 164
	 *   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
165
	 *   both '/' and '\' in the paths.
Qiang Xue committed
166
	 * - recursive: boolean, whether the files under the subdirectories should also be copied. Defaults to true.
167
	 * - beforeCopy: callback, a PHP callback that is called before copying each sub-directory or file.
Qiang Xue committed
168
	 *   If the callback returns false, the copy operation for the sub-directory or file will be cancelled.
169 170
	 *   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
171
	 * - afterCopy: callback, a PHP callback that is called after each sub-directory or file is successfully copied.
172
	 *   The signature of the callback should be: `function ($from, $to)`, where `$from` is the sub-directory or
Qiang Xue committed
173
	 *   file copied from, while `$to` is the copy target.
174
	 */
Alexander Makarov committed
175
	public static function copyDirectory($src, $dst, $options = [])
176 177
	{
		if (!is_dir($dst)) {
178
			static::createDirectory($dst, isset($options['dirMode']) ? $options['dirMode'] : 0775, true);
179 180 181 182 183 184 185
		}

		$handle = opendir($src);
		while (($file = readdir($handle)) !== false) {
			if ($file === '.' || $file === '..') {
				continue;
			}
186 187
			$from = $src . DIRECTORY_SEPARATOR . $file;
			$to = $dst . DIRECTORY_SEPARATOR . $file;
Qiang Xue committed
188
			if (static::filterPath($from, $options)) {
Qiang Xue committed
189
				if (isset($options['beforeCopy']) && !call_user_func($options['beforeCopy'], $from, $to)) {
Qiang Xue committed
190
					continue;
191
				}
192 193
				if (is_file($from)) {
					copy($from, $to);
194
					if (isset($options['fileMode'])) {
Qiang Xue committed
195
						@chmod($to, $options['fileMode']);
196 197
					}
				} else {
198 199 200 201
					static::copyDirectory($from, $to, $options);
				}
				if (isset($options['afterCopy'])) {
					call_user_func($options['afterCopy'], $from, $to);
202 203 204 205 206
				}
			}
		}
		closedir($handle);
	}
207 208

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

	/**
	 * 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
236
	 *
237
	 * - filter: callback, a PHP callback that is called for each directory or file.
Qiang Xue committed
238
	 *   The signature of the callback should be: `function ($path)`, where `$path` refers the full path to be filtered.
239 240 241 242 243 244
	 *   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
	 *
245 246 247 248 249 250
	 * - 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.
251 252 253 254
	 *   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
255
	 *   both '/' and '\' in the paths.
256
	 * - recursive: boolean, whether the files under the subdirectories should also be looked for. Defaults to true.
257 258
	 * @return array files found under the directory. The file list is sorted.
	 */
Alexander Makarov committed
259
	public static function findFiles($dir, $options = [])
260
	{
Alexander Makarov committed
261
		$list = [];
262 263 264 265 266 267
		$handle = opendir($dir);
		while (($file = readdir($handle)) !== false) {
			if ($file === '.' || $file === '..') {
				continue;
			}
			$path = $dir . DIRECTORY_SEPARATOR . $file;
Qiang Xue committed
268
			if (static::filterPath($path, $options)) {
Qiang Xue committed
269
				if (is_file($path)) {
270
					$list[] = $path;
Qiang Xue committed
271 272
				} elseif (!isset($options['recursive']) || $options['recursive']) {
					$list = array_merge($list, static::findFiles($path, $options));
273 274 275 276 277 278 279 280
				}
			}
		}
		closedir($handle);
		return $list;
	}

	/**
Qiang Xue committed
281 282 283 284 285
	 * 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.
286
	 */
Qiang Xue committed
287
	public static function filterPath($path, $options)
288
	{
289 290 291 292 293
		if (isset($options['filter'])) {
			$result = call_user_func($options['filter'], $path);
			if (is_bool($result)) {
				return $result;
			}
294
		}
295 296 297 298 299

		if (empty($options['except']) && empty($options['only'])) {
			return true;
		}

Qiang Xue committed
300
		$path = str_replace('\\', '/', $path);
301
		if ($isDir = is_dir($path)) {
302 303
			$path .= '/';
		}
304
		$n = StringHelper::byteLength($path);
305

Qiang Xue committed
306 307
		if (!empty($options['except'])) {
			foreach ($options['except'] as $name) {
308
				if (StringHelper::byteSubstr($path, -StringHelper::byteLength($name), $n) === $name) {
Qiang Xue committed
309 310 311 312
					return false;
				}
			}
		}
313 314

		if (!$isDir && !empty($options['only'])) {
Qiang Xue committed
315
			foreach ($options['only'] as $name) {
316
				if (StringHelper::byteSubstr($path, -StringHelper::byteLength($name), $n) === $name) {
317
					return true;
318 319
				}
			}
320
			return false;
321
		}
Qiang Xue committed
322
		return true;
323
	}
324 325

	/**
326
	 * Creates a new directory.
Qiang Xue committed
327 328 329 330
	 *
	 * 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.
331
	 *
332 333
	 * @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
334 335
	 * @param boolean $recursive whether to create parent directories if they do not exist.
	 * @return boolean whether the directory is created successfully
336
	 */
337
	public static function createDirectory($path, $mode = 0775, $recursive = true)
338
	{
Qiang Xue committed
339 340 341 342 343
		if (is_dir($path)) {
			return true;
		}
		$parentDir = dirname($path);
		if ($recursive && !is_dir($parentDir)) {
344
			static::createDirectory($parentDir, $mode, true);
345 346 347 348 349
		}
		$result = mkdir($path, $mode);
		chmod($path, $mode);
		return $result;
	}
Zander Baldwin committed
350
}