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

namespace yii\helpers\base;

Qiang Xue committed
12
use Yii;
13
use yii\helpers\StringHelper as StringHelper2;
Qiang Xue committed
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42

/**
 * Filesystem helper
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @author Alex Makarov <sam@rmcreative.ru>
 * @since 2.0
 */
class FileHelper
{
	/**
	 * 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)
	{
		return rtrim(strtr($path, array('/' => $ds, '\\' => $ds)), $ds);
	}

	/**
	 * 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
43 44 45
	 * 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
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
	 * 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
62
			$language = Yii::$app->language;
Qiang Xue committed
63 64
		}
		if ($sourceLanguage === null) {
Qiang Xue committed
65
			$sourceLanguage = Yii::$app->sourceLanguage;
Qiang Xue committed
66 67 68 69
		}
		if ($language === $sourceLanguage) {
			return $file;
		}
70
		$desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $sourceLanguage . DIRECTORY_SEPARATOR . basename($file);
Qiang Xue committed
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
		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);
90 91
			if ($info) {
				$result = finfo_file($info, $file);
Qiang Xue committed
92
				finfo_close($info);
93 94 95
				if ($result !== false) {
					return $result;
				}
Qiang Xue committed
96 97 98
			}
		}

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

	/**
	 * 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)
	{
Qiang Xue committed
112
		static $mimeTypes = array();
Qiang Xue committed
113
		if ($magicFile === null) {
Qiang Xue committed
114 115 116 117
			$magicFile = __DIR__ . '/mimeTypes.php';
		}
		if (!isset($mimeTypes[$magicFile])) {
			$mimeTypes[$magicFile] = require($magicFile);
Qiang Xue committed
118 119 120
		}
		if (($ext = pathinfo($file, PATHINFO_EXTENSION)) !== '') {
			$ext = strtolower($ext);
Qiang Xue committed
121 122
			if (isset($mimeTypes[$magicFile][$ext])) {
				return $mimeTypes[$magicFile][$ext];
Qiang Xue committed
123 124 125 126 127
			}
		}
		return null;
	}

128 129 130 131 132 133 134 135 136
	/**
	 * 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:
	 *
	 * - dirMode: integer, the permission to be set for newly copied directories. Defaults to 0777.
	 * - fileMode:  integer, the permission to be set for newly copied files. Defaults to the current environment setting.
Qiang Xue committed
137
	 * - filter: callback, a PHP callback that is called for each sub-directory or file.
Mojtaba Salehi committed
138
	 *   If the callback returns false, then the sub-directory or file will not be copied.
Qiang Xue committed
139 140
	 *   The signature of the callback should be: `function ($path)`, where `$path` refers the full path to be copied.
	 * - only: array, list of patterns that the files or directories should match if they want to be copied.
141 142 143 144 145
	 *   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
	 *   both '/' and '\' in the paths. If a file/directory matches a pattern in both in "only" and "except", it will NOT be returned.
Qiang Xue committed
146 147 148 149
	 * - except: array, list of patterns that the files or directories should NOT match if they want to be copied.
	 *   For more details on how to specify the patterns, please refer to the "only" option.
	 * - recursive: boolean, whether the files under the subdirectories should also be copied. Defaults to true.
	 * - afterCopy: callback, a PHP callback that is called after each sub-directory or file is successfully copied.
150
	 *   The signature of the callback should be: `function ($from, $to)`, where `$from` is the sub-directory or
Qiang Xue committed
151
	 *   file copied from, while `$to` is the copy target.
152 153 154 155
	 */
	public static function copyDirectory($src, $dst, $options = array())
	{
		if (!is_dir($dst)) {
Mojtaba Salehi committed
156
			static::mkdir($dst, isset($options['dirMode']) ? $options['dirMode'] : 0777, true);
157 158 159 160 161 162 163
		}

		$handle = opendir($src);
		while (($file = readdir($handle)) !== false) {
			if ($file === '.' || $file === '..') {
				continue;
			}
164 165
			$from = $src . DIRECTORY_SEPARATOR . $file;
			$to = $dst . DIRECTORY_SEPARATOR . $file;
Qiang Xue committed
166
			if (static::filterPath($from, $options)) {
167 168
				if (is_file($from)) {
					copy($from, $to);
169
					if (isset($options['fileMode'])) {
Qiang Xue committed
170
						@chmod($to, $options['fileMode']);
171 172
					}
				} else {
173 174 175 176
					static::copyDirectory($from, $to, $options);
				}
				if (isset($options['afterCopy'])) {
					call_user_func($options['afterCopy'], $from, $to);
177 178 179 180 181
				}
			}
		}
		closedir($handle);
	}
182 183

	/**
Qiang Xue committed
184 185
	 * Removes a directory (and all its content) recursively.
	 * @param string $dir the directory to be deleted recursively.
186
	 */
187
	public static function removeDirectory($dir)
188
	{
Qiang Xue committed
189 190 191 192 193
		if (!is_dir($dir) || !($handle = opendir($dir))) {
			return;
		}
		while (($file = readdir($handle)) !== false) {
			if ($file === '.' || $file === '..') {
194 195
				continue;
			}
Qiang Xue committed
196 197 198
			$path = $dir . DIRECTORY_SEPARATOR . $file;
			if (is_file($path)) {
				unlink($path);
199
			} else {
Qiang Xue committed
200
				static::removeDirectory($path);
201 202
			}
		}
Qiang Xue committed
203 204
		closedir($handle);
		rmdir($dir);
205
	}
206 207 208 209 210

	/**
	 * 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
211
	 *
212
	 * - filter: callback, a PHP callback that is called for each sub-directory or file.
Mojtaba Salehi committed
213
	 *   If the callback returns false, then the sub-directory or file will be excluded from the returning result.
Qiang Xue committed
214 215
	 *   The signature of the callback should be: `function ($path)`, where `$path` refers the full path to be filtered.
	 * - only: array, list of patterns that the files or directories should match if they want to be returned.
216 217 218 219 220
	 *   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
	 *   both '/' and '\' in the paths. If a file/directory matches a pattern in both in "only" and "except", it will NOT be returned.
Qiang Xue committed
221 222
	 * - except: array, list of patterns that the files or directories should NOT match if they want to be returned.
	 *   For more details on how to specify the patterns, please refer to the "only" option.
223
	 * - recursive: boolean, whether the files under the subdirectories should also be looked for. Defaults to true.
224 225
	 * @return array files found under the directory. The file list is sorted.
	 */
Qiang Xue committed
226
	public static function findFiles($dir, $options = array())
227 228 229 230 231 232 233 234
	{
		$list = array();
		$handle = opendir($dir);
		while (($file = readdir($handle)) !== false) {
			if ($file === '.' || $file === '..') {
				continue;
			}
			$path = $dir . DIRECTORY_SEPARATOR . $file;
Qiang Xue committed
235
			if (static::filterPath($path, $options)) {
Qiang Xue committed
236
				if (is_file($path)) {
237
					$list[] = $path;
Qiang Xue committed
238 239
				} elseif (!isset($options['recursive']) || $options['recursive']) {
					$list = array_merge($list, static::findFiles($path, $options));
240 241 242 243 244 245 246 247
				}
			}
		}
		closedir($handle);
		return $list;
	}

	/**
Qiang Xue committed
248 249 250 251 252
	 * 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.
253
	 */
Qiang Xue committed
254
	public static function filterPath($path, $options)
255
	{
Qiang Xue committed
256
		if (isset($options['filter']) && !call_user_func($options['filter'], $path)) {
257
			return false;
258
		}
Qiang Xue committed
259
		$path = str_replace('\\', '/', $path);
260 261 262 263
		if (is_dir($path)) {
			$path .= '/';
		}
		$n = StringHelper2::strlen($path);
Qiang Xue committed
264 265
		if (!empty($options['except'])) {
			foreach ($options['except'] as $name) {
266
				if (StringHelper2::substr($path, -StringHelper2::strlen($name), $n) === $name) {
Qiang Xue committed
267 268 269 270 271 272
					return false;
				}
			}
		}
		if (!empty($options['only'])) {
			foreach ($options['only'] as $name) {
273
				if (StringHelper2::substr($path, -StringHelper2::strlen($name), $n) !== $name) {
274 275 276
					return false;
				}
			}
277
		}
Qiang Xue committed
278
		return true;
279
	}
280 281

	/**
Qiang Xue committed
282 283 284 285 286
	 * Makes directory.
	 *
	 * 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.
287 288
	 *
	 * @param string $path path to be created.
Qiang Xue committed
289 290 291
	 * @param integer $mode the permission to be set for created directory.
	 * @param boolean $recursive whether to create parent directories if they do not exist.
	 * @return boolean whether the directory is created successfully
292
	 */
Qiang Xue committed
293
	public static function mkdir($path, $mode = 0777, $recursive = true)
294
	{
Qiang Xue committed
295 296 297 298 299 300
		if (is_dir($path)) {
			return true;
		}
		$parentDir = dirname($path);
		if ($recursive && !is_dir($parentDir)) {
			static::mkdir($parentDir, $mode, true);
301 302 303 304 305
		}
		$result = mkdir($path, $mode);
		chmod($path, $mode);
		return $result;
	}
Zander Baldwin committed
306
}