PageRenderTime 26ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/framework/web/CAssetManager.php

https://bitbucket.org/Shcoder/funny
PHP | 317 lines | 125 code | 16 blank | 176 comment | 18 complexity | 0bec0f7ee2c5edf33c3ee58f7c706b52 MD5 | raw file
Possible License(s): LGPL-2.1
  1. <?php
  2. /**
  3. * CAssetManager class file.
  4. *
  5. * @author Qiang Xue <qiang.xue@gmail.com>
  6. * @link http://www.yiiframework.com/
  7. * @copyright Copyright &copy; 2008-2011 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. * @since 1.1.5
  55. */
  56. public $linkAssets=false;
  57. /**
  58. * @var array list of directories and files which should be excluded from the publishing process.
  59. * Defaults to exclude '.svn' and '.gitignore' files only. This option has no effect if {@link linkAssets} is enabled.
  60. * @since 1.1.6
  61. **/
  62. public $excludeFiles=array('.svn','.gitignore');
  63. /**
  64. * @var integer the permission to be set for newly generated asset files.
  65. * This value will be used by PHP chmod function.
  66. * Defaults to 0666, meaning the file is read-writable by all users.
  67. * @since 1.1.8
  68. */
  69. public $newFileMode=0666;
  70. /**
  71. * @var integer the permission to be set for newly generated asset directories.
  72. * This value will be used by PHP chmod function.
  73. * Defaults to 0777, meaning the directory can be read, written and executed by all users.
  74. * @since 1.1.8
  75. */
  76. public $newDirMode=0777;
  77. /**
  78. * @var boolean whether we should copy the asset files and directories even if they already published before.
  79. * This property is used only during development stage. The main use case of this property is when you need
  80. * to force the original assets always copied by changing only one value without searching needed {@link publish}
  81. * method calls across the application codebase. Also it is useful in operating systems which does not fully
  82. * support symbolic links (therefore it is not possible to use {@link $linkAssets}) or we don't want to use them.
  83. * This property sets the default value of the $forceCopy parameter in {@link publish} method. Default value
  84. * of this property is false meaning that the assets will be published only in case they don't exist in webroot
  85. * assets directory.
  86. * @since 1.1.11
  87. */
  88. public $forceCopy=false;
  89. /**
  90. * @var string base web accessible path for storing private files
  91. */
  92. private $_basePath;
  93. /**
  94. * @var string base URL for accessing the publishing directory.
  95. */
  96. private $_baseUrl;
  97. /**
  98. * @var array published assets
  99. */
  100. private $_published=array();
  101. /**
  102. * @return string the root directory storing the published asset files. Defaults to 'WebRoot/assets'.
  103. */
  104. public function getBasePath()
  105. {
  106. if($this->_basePath===null)
  107. {
  108. $request=Yii::app()->getRequest();
  109. $this->setBasePath(dirname($request->getScriptFile()).DIRECTORY_SEPARATOR.self::DEFAULT_BASEPATH);
  110. }
  111. return $this->_basePath;
  112. }
  113. /**
  114. * Sets the root directory storing published asset files.
  115. * @param string $value the root directory storing published asset files
  116. * @throws CException if the base path is invalid
  117. */
  118. public function setBasePath($value)
  119. {
  120. if(($basePath=realpath($value))!==false && is_dir($basePath) && is_writable($basePath))
  121. $this->_basePath=$basePath;
  122. else
  123. 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.',
  124. array('{path}'=>$value)));
  125. }
  126. /**
  127. * @return string the base url that the published asset files can be accessed.
  128. * Note, the ending slashes are stripped off. Defaults to '/AppBaseUrl/assets'.
  129. */
  130. public function getBaseUrl()
  131. {
  132. if($this->_baseUrl===null)
  133. {
  134. $request=Yii::app()->getRequest();
  135. $this->setBaseUrl($request->getBaseUrl().'/'.self::DEFAULT_BASEPATH);
  136. }
  137. return $this->_baseUrl;
  138. }
  139. /**
  140. * @param string $value the base url that the published asset files can be accessed
  141. */
  142. public function setBaseUrl($value)
  143. {
  144. $this->_baseUrl=rtrim($value,'/');
  145. }
  146. /**
  147. * Publishes a file or a directory.
  148. * This method will copy the specified asset to a web accessible directory
  149. * and return the URL for accessing the published asset.
  150. * <ul>
  151. * <li>If the asset is a file, its file modification time will be checked
  152. * to avoid unnecessary file copying;</li>
  153. * <li>If the asset is a directory, all files and subdirectories under it will
  154. * be published recursively. Note, in case $forceCopy is false the method only checks the
  155. * existence of the target directory to avoid repetitive copying.</li>
  156. * </ul>
  157. *
  158. * Note: On rare scenario, a race condition can develop that will lead to a
  159. * one-time-manifestation of a non-critical problem in the creation of the directory
  160. * that holds the published assets. This problem can be avoided altogether by 'requesting'
  161. * in advance all the resources that are supposed to trigger a 'publish()' call, and doing
  162. * that in the application deployment phase, before system goes live. See more in the following
  163. * discussion: http://code.google.com/p/yii/issues/detail?id=2579
  164. *
  165. * @param string $path the asset (file or directory) to be published
  166. * @param boolean $hashByName whether the published directory should be named as the hashed basename.
  167. * If false, the name will be the hash taken from dirname of the path being published and path mtime.
  168. * Defaults to false. Set true if the path being published is shared among
  169. * different extensions.
  170. * @param integer $level level of recursive copying when the asset is a directory.
  171. * Level -1 means publishing all subdirectories and files;
  172. * Level 0 means publishing only the files DIRECTLY under the directory;
  173. * level N means copying those directories that are within N levels.
  174. * @param boolean $forceCopy whether we should copy the asset file or directory even if it is already
  175. * published before. In case of publishing a directory old files will not be removed.
  176. * This parameter is set true mainly during development stage when the original
  177. * assets are being constantly changed. The consequence is that the performance is degraded,
  178. * which is not a concern during development, however. Default value of this parameter is null meaning
  179. * that it's value is controlled by {@link $forceCopy} class property. This parameter has been available
  180. * since version 1.1.2. Default value has been changed since 1.1.11.
  181. * @return string an absolute URL to the published asset
  182. * @throws CException if the asset to be published does not exist.
  183. */
  184. public function publish($path,$hashByName=false,$level=-1,$forceCopy=null)
  185. {
  186. if($forceCopy===null)
  187. $forceCopy=$this->forceCopy;
  188. if(isset($this->_published[$path]))
  189. return $this->_published[$path];
  190. elseif(($src=realpath($path))!==false)
  191. {
  192. $dir=$this->generatePath($src,$hashByName);
  193. $dstDir=$this->getBasePath().DIRECTORY_SEPARATOR.$dir;
  194. if(is_file($src))
  195. {
  196. $fileName=basename($src);
  197. $dstFile=$dstDir.DIRECTORY_SEPARATOR.$fileName;
  198. if(!is_dir($dstDir))
  199. {
  200. mkdir($dstDir,$this->newDirMode,true);
  201. chmod($dstDir,$this->newDirMode);
  202. }
  203. if($this->linkAssets && !is_file($dstFile)) symlink($src,$dstFile);
  204. elseif(@filemtime($dstFile)<@filemtime($src))
  205. {
  206. copy($src,$dstFile);
  207. chmod($dstFile,$this->newFileMode);
  208. }
  209. return $this->_published[$path]=$this->getBaseUrl()."/$dir/$fileName";
  210. }
  211. elseif(is_dir($src))
  212. {
  213. if($this->linkAssets && !is_dir($dstDir))
  214. {
  215. symlink($src,$dstDir);
  216. }
  217. elseif(!is_dir($dstDir) || $forceCopy)
  218. {
  219. CFileHelper::copyDirectory($src,$dstDir,array(
  220. 'exclude'=>$this->excludeFiles,
  221. 'level'=>$level,
  222. 'newDirMode'=>$this->newDirMode,
  223. 'newFileMode'=>$this->newFileMode,
  224. ));
  225. }
  226. return $this->_published[$path]=$this->getBaseUrl().'/'.$dir;
  227. }
  228. }
  229. throw new CException(Yii::t('yii','The asset "{asset}" to be published does not exist.',
  230. array('{asset}'=>$path)));
  231. }
  232. /**
  233. * Returns the published path of a file path.
  234. * This method does not perform any publishing. It merely tells you
  235. * if the file or directory is published, where it will go.
  236. * @param string $path directory or file path being published
  237. * @param boolean $hashByName whether the published directory should be named as the hashed basename.
  238. * If false, the name will be the hash taken from dirname of the path being published and path mtime.
  239. * Defaults to false. Set true if the path being published is shared among
  240. * different extensions.
  241. * @return string the published file path. False if the file or directory does not exist
  242. */
  243. public function getPublishedPath($path,$hashByName=false)
  244. {
  245. if(($path=realpath($path))!==false)
  246. {
  247. $base=$this->getBasePath().DIRECTORY_SEPARATOR.$this->generatePath($path,$hashByName);
  248. return is_file($path) ? $base.DIRECTORY_SEPARATOR.basename($path) : $base ;
  249. }
  250. else
  251. return false;
  252. }
  253. /**
  254. * Returns the URL of a published file path.
  255. * This method does not perform any publishing. It merely tells you
  256. * if the file path is published, what the URL will be to access it.
  257. * @param string $path directory or file path being published
  258. * @param boolean $hashByName whether the published directory should be named as the hashed basename.
  259. * If false, the name will be the hash taken from dirname of the path being published and path mtime.
  260. * Defaults to false. Set true if the path being published is shared among
  261. * different extensions.
  262. * @return string the published URL for the file or directory. False if the file or directory does not exist.
  263. */
  264. public function getPublishedUrl($path,$hashByName=false)
  265. {
  266. if(isset($this->_published[$path]))
  267. return $this->_published[$path];
  268. if(($path=realpath($path))!==false)
  269. {
  270. $base=$this->getBaseUrl().'/'.$this->generatePath($path,$hashByName);
  271. return is_file($path) ? $base.'/'.basename($path) : $base;
  272. }
  273. else
  274. return false;
  275. }
  276. /**
  277. * Generate a CRC32 hash for the directory path. Collisions are higher
  278. * than MD5 but generates a much smaller hash string.
  279. * @param string $path string to be hashed.
  280. * @return string hashed string.
  281. */
  282. protected function hash($path)
  283. {
  284. return sprintf('%x',crc32($path.Yii::getVersion()));
  285. }
  286. /**
  287. * Generates path segments relative to basePath.
  288. * @param string $file for which public path will be created.
  289. * @param bool $hashByName whether the published directory should be named as the hashed basename.
  290. * @return string path segments without basePath.
  291. * @since 1.1.13
  292. */
  293. protected function generatePath($file,$hashByName=false)
  294. {
  295. if (is_file($file))
  296. $pathForHashing=$hashByName ? basename($file) : dirname($file).filemtime($file);
  297. else
  298. $pathForHashing=$hashByName ? basename($file) : $file.filemtime($file);
  299. return $this->hash($pathForHashing);
  300. }
  301. }