AssetManager.php 10.5 KB
Newer Older
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
Qiang Xue committed
5 6 7
 * @license http://www.yiiframework.com/license/
 */

Qiang Xue committed
8 9 10 11 12 13
namespace yii\web;

use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException;
use yii\base\InvalidParamException;
Qiang Xue committed
14 15 16 17

/**
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
Qiang Xue committed
18
 * @since 2.0
Qiang Xue committed
19
 */
Qiang Xue committed
20
class AssetManager extends Component
Qiang Xue committed
21 22
{
	/**
Qiang Xue committed
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
	 * @var array list of asset bundles. The keys are the bundle names, and the values are the configuration
	 * arrays for creating [[AssetBundle]] objects. Besides the bundles listed here, the asset manager
	 * may look for bundles declared in extensions. For more details, please refer to [[getBundle()]].
	 */
	public $bundles;
	/**
	 * @var
	 */
	public $bundleMap;
	/**
	 * @return string the root directory storing the published asset files.
	 */
	public $basePath = '@wwwroot/assets';
	/**
	 * @return string the base URL through which the published asset files can be accessed.
Qiang Xue committed
38
	 */
Qiang Xue committed
39
	public $baseUrl = '@www/assets';
Qiang Xue committed
40 41
	/**
	 * @var boolean whether to use symbolic link to publish asset files. Defaults to false, meaning
Qiang Xue committed
42 43 44
	 * asset files are copied to [[basePath]]. Using symbolic links has the benefit that the published
	 * assets will always be consistent with the source assets and there is no copy operation required.
	 * This is especially useful during development.
Qiang Xue committed
45 46 47 48 49 50 51 52
	 *
	 * However, there are special requirements for hosting environments in order to use symbolic links.
	 * In particular, symbolic links are supported only on Linux/Unix, and Windows Vista/2008 or greater.
	 *
	 * Moreover, some Web servers need to be properly configured so that the linked assets are accessible
	 * to Web users. For example, for Apache Web server, the following configuration directive should be added
	 * for the Web folder:
	 *
Qiang Xue committed
53 54 55
	 * ~~~
	 * Options FollowSymLinks
	 * ~~~
Qiang Xue committed
56
	 */
Qiang Xue committed
57
	public $linkAssets = false;
Qiang Xue committed
58 59 60 61 62
	/**
	 * @var array list of directories and files which should be excluded from the publishing process.
	 * Defaults to exclude '.svn' and '.gitignore' files only. This option has no effect if {@link linkAssets} is enabled.
	 * @since 1.1.6
	 **/
Qiang Xue committed
63
	public $excludeFiles = array('.svn', '.gitignore');
Qiang Xue committed
64 65 66 67 68 69
	/**
	 * @var integer the permission to be set for newly generated asset files.
	 * This value will be used by PHP chmod function.
	 * Defaults to 0666, meaning the file is read-writable by all users.
	 * @since 1.1.8
	 */
Qiang Xue committed
70
	public $newFileMode = 0666;
Qiang Xue committed
71 72 73 74 75 76
	/**
	 * @var integer the permission to be set for newly generated asset directories.
	 * This value will be used by PHP chmod function.
	 * Defaults to 0777, meaning the directory can be read, written and executed by all users.
	 * @since 1.1.8
	 */
Qiang Xue committed
77
	public $newDirMode = 0777;
Qiang Xue committed
78 79 80
	/**
	 * @var array published assets
	 */
Qiang Xue committed
81
	private $_published = array();
Qiang Xue committed
82

Qiang Xue committed
83
	public function init()
Qiang Xue committed
84
	{
Qiang Xue committed
85 86 87 88 89 90 91 92
		parent::init();
		$this->basePath = Yii::getAlias($this->basePath);
		if (!is_dir($this->basePath)) {
			throw new InvalidConfigException("The directory does not exist: {$this->basePath}");
		} elseif (!is_writable($this->basePath)) {
			throw new InvalidConfigException("The directory is not writable by the Web process: {$this->basePath}");
		} else {
			$this->base = realpath($this->basePath);
Qiang Xue committed
93
		}
Qiang Xue committed
94
		$this->baseUrl = rtrim(Yii::getAlias($this->getBaseUrl), '/');
Qiang Xue committed
95 96 97
	}

	/**
Qiang Xue committed
98
	 * @param string $name
Qiang Xue committed
99
	 * @param boolean $publish
Qiang Xue committed
100 101
	 * @return AssetBundle
	 * @throws InvalidParamException
Qiang Xue committed
102
	 */
Qiang Xue committed
103
	public function getBundle($name, $publish = true)
Qiang Xue committed
104
	{
Qiang Xue committed
105 106 107 108 109 110
		if (!isset($this->bundles[$name])) {
			$manifest = Yii::getAlias("@{$name}/assets.php", false);
			if ($manifest === false) {
				throw new InvalidParamException("Unable to find the asset bundle: $name");
			}
			$this->bundles[$name] = require($manifest);
Qiang Xue committed
111
		}
Qiang Xue committed
112 113 114 115 116 117 118 119
		if (is_array($this->bundles[$name])) {
			$config = $this->bundles[$name];
			if (!isset($config['class'])) {
				$config['class'] = 'yii\\web\\AssetBundle';
				$this->bundles[$name] = Yii::createObject($config);
			}
		}
		return $this->bundles[$name];
Qiang Xue committed
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
	}

	/**
	 * Publishes a file or a directory.
	 * This method will copy the specified asset to a web accessible directory
	 * and return the URL for accessing the published asset.
	 * <ul>
	 * <li>If the asset is a file, its file modification time will be checked
	 * to avoid unnecessary file copying;</li>
	 * <li>If the asset is a directory, all files and subdirectories under it will
	 * be published recursively. Note, in case $forceCopy is false the method only checks the
	 * existence of the target directory to avoid repetitive copying.</li>
	 * </ul>
	 *
	 * Note: On rare scenario, a race condition can develop that will lead to a
	 * one-time-manifestation of a non-critical problem in the creation of the directory
	 * that holds the published assets. This problem can be avoided altogether by 'requesting'
	 * in advance all the resources that are supposed to trigger a 'publish()' call, and doing
	 * that in the application deployment phase, before system goes live. See more in the following
	 * discussion: http://code.google.com/p/yii/issues/detail?id=2579
	 *
	 * @param string $path the asset (file or directory) to be published
	 * @param boolean $hashByName whether the published directory should be named as the hashed basename.
	 * If false, the name will be the hash taken from dirname of the path being published and path mtime.
	 * Defaults to false. Set true if the path being published is shared among
	 * different extensions.
	 * @param integer $level level of recursive copying when the asset is a directory.
	 * Level -1 means publishing all subdirectories and files;
	 * Level 0 means publishing only the files DIRECTLY under the directory;
	 * level N means copying those directories that are within N levels.
	 * @param boolean $forceCopy whether we should copy the asset file or directory even if it is already published before.
	 * This parameter is set true mainly during development stage when the original
	 * assets are being constantly changed. The consequence is that the performance
	 * is degraded, which is not a concern during development, however.
	 * This parameter has been available since version 1.1.2.
	 * @return string an absolute URL to the published asset
	 * @throws CException if the asset to be published does not exist.
	 */
Qiang Xue committed
158
	public function publish($path, $hashByName = false, $level = -1, $forceCopy = false)
Qiang Xue committed
159
	{
Qiang Xue committed
160
		if (isset($this->_published[$path])) {
Qiang Xue committed
161
			return $this->_published[$path];
Qiang Xue committed
162 163 164 165 166 167 168
		} else {
			if (($src = realpath($path)) !== false) {
				if (is_file($src)) {
					$dir = $this->hash($hashByName ? basename($src) : dirname($src) . filemtime($src));
					$fileName = basename($src);
					$dstDir = $this->getBasePath() . DIRECTORY_SEPARATOR . $dir;
					$dstFile = $dstDir . DIRECTORY_SEPARATOR . $fileName;
Qiang Xue committed
169

Qiang Xue committed
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
					if ($this->linkAssets) {
						if (!is_file($dstFile)) {
							if (!is_dir($dstDir)) {
								mkdir($dstDir);
								@chmod($dstDir, $this->newDirMode);
							}
							symlink($src, $dstFile);
						}
					} else {
						if (@filemtime($dstFile) < @filemtime($src)) {
							if (!is_dir($dstDir)) {
								mkdir($dstDir);
								@chmod($dstDir, $this->newDirMode);
							}
							copy($src, $dstFile);
							@chmod($dstFile, $this->newFileMode);
Qiang Xue committed
186 187 188
						}
					}

Qiang Xue committed
189 190 191 192 193
					return $this->_published[$path] = $this->getBaseUrl() . "/$dir/$fileName";
				} else {
					if (is_dir($src)) {
						$dir = $this->hash($hashByName ? basename($src) : $src . filemtime($src));
						$dstDir = $this->getBasePath() . DIRECTORY_SEPARATOR . $dir;
Qiang Xue committed
194

Qiang Xue committed
195 196 197 198 199 200 201 202 203 204 205 206 207 208
						if ($this->linkAssets) {
							if (!is_dir($dstDir)) {
								symlink($src, $dstDir);
							}
						} else {
							if (!is_dir($dstDir) || $forceCopy) {
								CFileHelper::copyDirectory($src, $dstDir, array(
									'exclude' => $this->excludeFiles,
									'level' => $level,
									'newDirMode' => $this->newDirMode,
									'newFileMode' => $this->newFileMode,
								));
							}
						}
Qiang Xue committed
209

Qiang Xue committed
210 211 212
						return $this->_published[$path] = $this->getBaseUrl() . '/' . $dir;
					}
				}
Qiang Xue committed
213 214
			}
		}
215
		throw new CException(Yii::t('yii|The asset "{asset}" to be published does not exist.',
Qiang Xue committed
216
			array('{asset}' => $path)));
Qiang Xue committed
217 218 219 220 221 222 223 224 225 226 227 228 229
	}

	/**
	 * Returns the published path of a file path.
	 * This method does not perform any publishing. It merely tells you
	 * if the file or directory is published, where it will go.
	 * @param string $path directory or file path being published
	 * @param boolean $hashByName whether the published directory should be named as the hashed basename.
	 * If false, the name will be the hash taken from dirname of the path being published and path mtime.
	 * Defaults to false. Set true if the path being published is shared among
	 * different extensions.
	 * @return string the published file path. False if the file or directory does not exist
	 */
Qiang Xue committed
230
	public function getPublishedPath($path, $hashByName = false)
Qiang Xue committed
231
	{
Qiang Xue committed
232 233 234 235 236 237 238 239
		if (($path = realpath($path)) !== false) {
			$base = $this->getBasePath() . DIRECTORY_SEPARATOR;
			if (is_file($path)) {
				return $base . $this->hash($hashByName ? basename($path) : dirname($path) . filemtime($path)) . DIRECTORY_SEPARATOR . basename($path);
			} else {
				return $base . $this->hash($hashByName ? basename($path) : $path . filemtime($path));
			}
		} else {
Qiang Xue committed
240
			return false;
Qiang Xue committed
241
		}
Qiang Xue committed
242 243 244 245 246 247 248 249 250 251 252 253 254
	}

	/**
	 * Returns the URL of a published file path.
	 * This method does not perform any publishing. It merely tells you
	 * if the file path is published, what the URL will be to access it.
	 * @param string $path directory or file path being published
	 * @param boolean $hashByName whether the published directory should be named as the hashed basename.
	 * If false, the name will be the hash taken from dirname of the path being published and path mtime.
	 * Defaults to false. Set true if the path being published is shared among
	 * different extensions.
	 * @return string the published URL for the file or directory. False if the file or directory does not exist.
	 */
Qiang Xue committed
255
	public function getPublishedUrl($path, $hashByName = false)
Qiang Xue committed
256
	{
Qiang Xue committed
257
		if (isset($this->_published[$path])) {
Qiang Xue committed
258 259
			return $this->_published[$path];
		}
Qiang Xue committed
260 261 262 263 264 265 266
		if (($path = realpath($path)) !== false) {
			if (is_file($path)) {
				return $this->getBaseUrl() . '/' . $this->hash($hashByName ? basename($path) : dirname($path) . filemtime($path)) . '/' . basename($path);
			} else {
				return $this->getBaseUrl() . '/' . $this->hash($hashByName ? basename($path) : $path . filemtime($path));
			}
		} else {
Qiang Xue committed
267
			return false;
Qiang Xue committed
268
		}
Qiang Xue committed
269 270 271 272 273 274 275 276 277 278
	}

	/**
	 * Generate a CRC32 hash for the directory path. Collisions are higher
	 * than MD5 but generates a much smaller hash string.
	 * @param string $path string to be hashed.
	 * @return string hashed string.
	 */
	protected function hash($path)
	{
Qiang Xue committed
279
		return sprintf('%x', crc32($path . Yii::getVersion()));
Qiang Xue committed
280 281
	}
}