CAssetManager.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. <?php
  2. /**
  3. * CAssetManager class file.
  4. *
  5. * @author Qiang Xue <qiang.xue@gmail.com>
  6. * @link http://www.yiiframework.com/
  7. * @copyright 2008-2013 Yii Software LLC
  8. * @license http://www.yiiframework.com/license/
  9. */
  10. /**
  11. * CAssetManager is a Web application component that manages private files (called assets) and makes them accessible by Web clients.
  12. *
  13. * It achieves this goal by copying assets to a Web-accessible directory
  14. * and returns the corresponding URL for accessing them.
  15. *
  16. * To publish an asset, simply call {@link publish()}.
  17. *
  18. * The Web-accessible directory holding the published files is specified
  19. * by {@link setBasePath basePath}, which defaults to the "assets" directory
  20. * under the directory containing the application entry script file.
  21. * The property {@link setBaseUrl baseUrl} refers to the URL for accessing
  22. * the {@link setBasePath basePath}.
  23. *
  24. * @property string $basePath The root directory storing the published asset files. Defaults to 'WebRoot/assets'.
  25. * @property string $baseUrl The base url that the published asset files can be accessed.
  26. * Note, the ending slashes are stripped off. Defaults to '/AppBaseUrl/assets'.
  27. *
  28. * @author Qiang Xue <qiang.xue@gmail.com>
  29. * @package system.web
  30. * @since 1.0
  31. */
  32. class CAssetManager extends CApplicationComponent
  33. {
  34. /**
  35. * Default web accessible base path for storing private files
  36. */
  37. const DEFAULT_BASEPATH='assets';
  38. /**
  39. * @var boolean whether to use symbolic link to publish asset files. Defaults to false, meaning
  40. * asset files are copied to public folders. Using symbolic links has the benefit that the published
  41. * assets will always be consistent with the source assets. This is especially useful during development.
  42. *
  43. * However, there are special requirements for hosting environments in order to use symbolic links.
  44. * In particular, symbolic links are supported only on Linux/Unix, and Windows Vista/2008 or greater.
  45. * The latter requires PHP 5.3 or greater.
  46. *
  47. * Moreover, some Web servers need to be properly configured so that the linked assets are accessible
  48. * to Web users. For example, for Apache Web server, the following configuration directive should be added
  49. * for the Web folder:
  50. * <pre>
  51. * Options FollowSymLinks
  52. * </pre>
  53. *
  54. * Note that this property cannot be true when {@link $forceCopy} property has true value too. Otherwise
  55. * an exception would be thrown. Using both properties at the same time is illogical because both of them
  56. * are solving similar tasks but in a different ways. Please refer to the {@link $forceCopy} documentation
  57. * for more details.
  58. *
  59. * @since 1.1.5
  60. */
  61. public $linkAssets=false;
  62. /**
  63. * @var array list of directories and files which should be excluded from the publishing process.
  64. * Defaults to exclude '.svn' and '.gitignore' files only. This option has no effect if {@link linkAssets} is enabled.
  65. * @since 1.1.6
  66. **/
  67. public $excludeFiles=array('.svn','.gitignore');
  68. /**
  69. * @var integer the permission to be set for newly generated asset files.
  70. * This value will be used by PHP chmod function.
  71. * Defaults to 0666, meaning the file is read-writable by all users.
  72. * @since 1.1.8
  73. */
  74. public $newFileMode=0666;
  75. /**
  76. * @var integer the permission to be set for newly generated asset directories.
  77. * This value will be used by PHP chmod function.
  78. * Defaults to 0777, meaning the directory can be read, written and executed by all users.
  79. * @since 1.1.8
  80. */
  81. public $newDirMode=0777;
  82. /**
  83. * @var boolean whether we should copy the asset files and directories even if they already published before.
  84. * This property is used only during development stage. The main use case of this property is when you need
  85. * to force the original assets always copied by changing only one value without searching needed {@link publish}
  86. * method calls across the application codebase. Also it is useful in operating systems which does not fully
  87. * support symbolic links (therefore it is not possible to use {@link $linkAssets}) or we don't want to use them.
  88. * This property sets the default value of the $forceCopy parameter in {@link publish} method. Default value
  89. * of this property is false meaning that the assets will be published only in case they don't exist in webroot
  90. * assets directory.
  91. *
  92. * Note that this property cannot be true when {@link $linkAssets} property has true value too. Otherwise
  93. * an exception would be thrown. Using both properties at the same time is illogical because both of them
  94. * are solving similar tasks but in a different ways. Please refer to the {@link $linkAssets} documentation
  95. * for more details.
  96. *
  97. * @since 1.1.11
  98. */
  99. public $forceCopy=false;
  100. /**
  101. * @var string base web accessible path for storing private files
  102. */
  103. private $_basePath;
  104. /**
  105. * @var string base URL for accessing the publishing directory.
  106. */
  107. private $_baseUrl;
  108. /**
  109. * @var array published assets
  110. */
  111. private $_published=array();
  112. /**
  113. * @return string the root directory storing the published asset files. Defaults to 'WebRoot/assets'.
  114. */
  115. public function getBasePath()
  116. {
  117. if($this->_basePath===null)
  118. {
  119. $request=Yii::app()->getRequest();
  120. $this->setBasePath(dirname($request->getScriptFile()).DIRECTORY_SEPARATOR.self::DEFAULT_BASEPATH);
  121. }
  122. return $this->_basePath;
  123. }
  124. /**
  125. * Sets the root directory storing published asset files.
  126. * @param string $value the root directory storing published asset files
  127. * @throws CException if the base path is invalid
  128. */
  129. public function setBasePath($value)
  130. {
  131. if(($basePath=realpath($value))!==false && is_dir($basePath) && is_writable($basePath))
  132. $this->_basePath=$basePath;
  133. else
  134. throw new CException(Yii::t('yii','CAssetManager.basePath "{path}" is invalid. Please make sure the directory exists and is writable by the Web server process.',
  135. array('{path}'=>$value)));
  136. }
  137. /**
  138. * @return string the base url that the published asset files can be accessed.
  139. * Note, the ending slashes are stripped off. Defaults to '/AppBaseUrl/assets'.
  140. */
  141. public function getBaseUrl()
  142. {
  143. if($this->_baseUrl===null)
  144. {
  145. $request=Yii::app()->getRequest();
  146. $this->setBaseUrl($request->getBaseUrl().'/'.self::DEFAULT_BASEPATH);
  147. }
  148. return $this->_baseUrl;
  149. }
  150. /**
  151. * @param string $value the base url that the published asset files can be accessed
  152. */
  153. public function setBaseUrl($value)
  154. {
  155. $this->_baseUrl=rtrim($value,'/');
  156. }
  157. /**
  158. * Publishes a file or a directory.
  159. * This method will copy the specified asset to a web accessible directory
  160. * and return the URL for accessing the published asset.
  161. * <ul>
  162. * <li>If the asset is a file, its file modification time will be checked
  163. * to avoid unnecessary file copying;</li>
  164. * <li>If the asset is a directory, all files and subdirectories under it will
  165. * be published recursively. Note, in case $forceCopy is false the method only checks the
  166. * existence of the target directory to avoid repetitive copying.</li>
  167. * </ul>
  168. *
  169. * Note: On rare scenario, a race condition can develop that will lead to a
  170. * one-time-manifestation of a non-critical problem in the creation of the directory
  171. * that holds the published assets. This problem can be avoided altogether by 'requesting'
  172. * in advance all the resources that are supposed to trigger a 'publish()' call, and doing
  173. * that in the application deployment phase, before system goes live. See more in the following
  174. * discussion: http://code.google.com/p/yii/issues/detail?id=2579
  175. *
  176. * @param string $path the asset (file or directory) to be published
  177. * @param boolean $hashByName whether the published directory should be named as the hashed basename.
  178. * If false, the name will be the hash taken from dirname of the path being published and path mtime.
  179. * Defaults to false. Set true if the path being published is shared among
  180. * different extensions.
  181. * @param integer $level level of recursive copying when the asset is a directory.
  182. * Level -1 means publishing all subdirectories and files;
  183. * Level 0 means publishing only the files DIRECTLY under the directory;
  184. * level N means copying those directories that are within N levels.
  185. * @param boolean $forceCopy whether we should copy the asset file or directory even if it is already
  186. * published before. In case of publishing a directory old files will not be removed.
  187. * This parameter is set true mainly during development stage when the original
  188. * assets are being constantly changed. The consequence is that the performance is degraded,
  189. * which is not a concern during development, however. Default value of this parameter is null meaning
  190. * that it's value is controlled by {@link $forceCopy} class property. This parameter has been available
  191. * since version 1.1.2. Default value has been changed since 1.1.11.
  192. * Note that this parameter cannot be true when {@link $linkAssets} property has true value too. Otherwise
  193. * an exception would be thrown. Using this parameter with {@link $linkAssets} property at the same time
  194. * is illogical because both of them are solving similar tasks but in a different ways. Please refer
  195. * to the {@link $linkAssets} documentation for more details.
  196. * @return string an absolute URL to the published asset
  197. * @throws CException if the asset to be published does not exist.
  198. */
  199. public function publish($path,$hashByName=false,$level=-1,$forceCopy=null)
  200. {
  201. if($forceCopy===null)
  202. $forceCopy=$this->forceCopy;
  203. if($forceCopy && $this->linkAssets)
  204. throw new CException(Yii::t('yii','The "forceCopy" and "linkAssets" cannot be both true.'));
  205. if(isset($this->_published[$path]))
  206. return $this->_published[$path];
  207. elseif(is_string($path) && ($src=realpath($path))!==false)
  208. {
  209. $dir=$this->generatePath($src,$hashByName);
  210. $dstDir=$this->getBasePath().DIRECTORY_SEPARATOR.$dir;
  211. if(is_file($src))
  212. {
  213. $fileName=basename($src);
  214. $dstFile=$dstDir.DIRECTORY_SEPARATOR.$fileName;
  215. if(!is_dir($dstDir))
  216. {
  217. mkdir($dstDir,$this->newDirMode,true);
  218. @chmod($dstDir,$this->newDirMode);
  219. }
  220. if($this->linkAssets && !is_file($dstFile)) symlink($src,$dstFile);
  221. elseif(@filemtime($dstFile)<@filemtime($src))
  222. {
  223. copy($src,$dstFile);
  224. @chmod($dstFile,$this->newFileMode);
  225. }
  226. return $this->_published[$path]=$this->getBaseUrl()."/$dir/$fileName";
  227. }
  228. elseif(is_dir($src))
  229. {
  230. if($this->linkAssets && !is_dir($dstDir))
  231. {
  232. symlink($src,$dstDir);
  233. }
  234. elseif(!is_dir($dstDir) || $forceCopy)
  235. {
  236. CFileHelper::copyDirectory($src,$dstDir,array(
  237. 'exclude'=>$this->excludeFiles,
  238. 'level'=>$level,
  239. 'newDirMode'=>$this->newDirMode,
  240. 'newFileMode'=>$this->newFileMode,
  241. ));
  242. }
  243. return $this->_published[$path]=$this->getBaseUrl().'/'.$dir;
  244. }
  245. }
  246. throw new CException(Yii::t('yii','The asset "{asset}" to be published does not exist.',
  247. array('{asset}'=>$path)));
  248. }
  249. /**
  250. * Returns the published path of a file path.
  251. * This method does not perform any publishing. It merely tells you
  252. * if the file or directory is published, where it will go.
  253. * @param string $path directory or file path being published
  254. * @param boolean $hashByName whether the published directory should be named as the hashed basename.
  255. * If false, the name will be the hash taken from dirname of the path being published and path mtime.
  256. * Defaults to false. Set true if the path being published is shared among
  257. * different extensions.
  258. * @return string the published file path. False if the file or directory does not exist
  259. */
  260. public function getPublishedPath($path,$hashByName=false)
  261. {
  262. if(is_string($path) && ($path=realpath($path))!==false)
  263. {
  264. $base=$this->getBasePath().DIRECTORY_SEPARATOR.$this->generatePath($path,$hashByName);
  265. return is_file($path) ? $base.DIRECTORY_SEPARATOR.basename($path) : $base ;
  266. }
  267. else
  268. return false;
  269. }
  270. /**
  271. * Returns the URL of a published file path.
  272. * This method does not perform any publishing. It merely tells you
  273. * if the file path is published, what the URL will be to access it.
  274. * @param string $path directory or file path being published
  275. * @param boolean $hashByName whether the published directory should be named as the hashed basename.
  276. * If false, the name will be the hash taken from dirname of the path being published and path mtime.
  277. * Defaults to false. Set true if the path being published is shared among
  278. * different extensions.
  279. * @return string the published URL for the file or directory. False if the file or directory does not exist.
  280. */
  281. public function getPublishedUrl($path,$hashByName=false)
  282. {
  283. if(isset($this->_published[$path]))
  284. return $this->_published[$path];
  285. if(is_string($path) && ($path=realpath($path))!==false)
  286. {
  287. $base=$this->getBaseUrl().'/'.$this->generatePath($path,$hashByName);
  288. return is_file($path) ? $base.'/'.basename($path) : $base;
  289. }
  290. else
  291. return false;
  292. }
  293. /**
  294. * Generate a CRC32 hash for the directory path. Collisions are higher
  295. * than MD5 but generates a much smaller hash string.
  296. * @param string $path string to be hashed.
  297. * @return string hashed string.
  298. */
  299. protected function hash($path)
  300. {
  301. return sprintf('%x',crc32($path.Yii::getVersion()));
  302. }
  303. /**
  304. * Generates path segments relative to basePath.
  305. * @param string $file for which public path will be created.
  306. * @param bool $hashByName whether the published directory should be named as the hashed basename.
  307. * @return string path segments without basePath.
  308. * @since 1.1.13
  309. */
  310. protected function generatePath($file,$hashByName=false)
  311. {
  312. if (is_file($file))
  313. $pathForHashing=$hashByName ? dirname($file) : dirname($file).filemtime($file);
  314. else
  315. $pathForHashing=$hashByName ? $file : $file.filemtime($file);
  316. return $this->hash($pathForHashing);
  317. }
  318. }