You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

605 satır
24KB

  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\web;
  8. use Yii;
  9. use yii\base\Component;
  10. use yii\base\InvalidConfigException;
  11. use yii\base\InvalidParamException;
  12. use yii\helpers\FileHelper;
  13. use yii\helpers\Url;
  14. /**
  15. * AssetManager manages asset bundle configuration and loading.
  16. *
  17. * AssetManager is configured as an application component in [[\yii\web\Application]] by default.
  18. * You can access that instance via `Yii::$app->assetManager`.
  19. *
  20. * You can modify its configuration by adding an array to your application config under `components`
  21. * as shown in the following example:
  22. *
  23. * ```php
  24. * 'assetManager' => [
  25. * 'bundles' => [
  26. * // you can override AssetBundle configs here
  27. * ],
  28. * ]
  29. * ```
  30. *
  31. * @property AssetConverterInterface $converter The asset converter. Note that the type of this property
  32. * differs in getter and setter. See [[getConverter()]] and [[setConverter()]] for details.
  33. *
  34. * @author Qiang Xue <qiang.xue@gmail.com>
  35. * @since 2.0
  36. */
  37. class AssetManager extends Component
  38. {
  39. /**
  40. * @var array|boolean list of asset bundle configurations. This property is provided to customize asset bundles.
  41. * When a bundle is being loaded by [[getBundle()]], if it has a corresponding configuration specified here,
  42. * the configuration will be applied to the bundle.
  43. *
  44. * The array keys are the asset bundle names, which typically are asset bundle class names without leading backslash.
  45. * The array values are the corresponding configurations. If a value is false, it means the corresponding asset
  46. * bundle is disabled and [[getBundle()]] should return null.
  47. *
  48. * If this property is false, it means the whole asset bundle feature is disabled and [[getBundle()]]
  49. * will always return null.
  50. *
  51. * The following example shows how to disable the bootstrap css file used by Bootstrap widgets
  52. * (because you want to use your own styles):
  53. *
  54. * ```php
  55. * [
  56. * 'yii\bootstrap\BootstrapAsset' => [
  57. * 'css' => [],
  58. * ],
  59. * ]
  60. * ```
  61. */
  62. public $bundles = [];
  63. /**
  64. * @var string the root directory storing the published asset files.
  65. */
  66. public $basePath = '@webroot/assets';
  67. /**
  68. * @var string the base URL through which the published asset files can be accessed.
  69. */
  70. public $baseUrl = '@web/assets';
  71. /**
  72. * @var array mapping from source asset files (keys) to target asset files (values).
  73. *
  74. * This property is provided to support fixing incorrect asset file paths in some asset bundles.
  75. * When an asset bundle is registered with a view, each relative asset file in its [[AssetBundle::css|css]]
  76. * and [[AssetBundle::js|js]] arrays will be examined against this map. If any of the keys is found
  77. * to be the last part of an asset file (which is prefixed with [[AssetBundle::sourcePath]] if available),
  78. * the corresponding value will replace the asset and be registered with the view.
  79. * For example, an asset file `my/path/to/jquery.js` matches a key `jquery.js`.
  80. *
  81. * Note that the target asset files should be absolute URLs, domain relative URLs (starting from '/') or paths
  82. * relative to [[baseUrl]] and [[basePath]].
  83. *
  84. * In the following example, any assets ending with `jquery.min.js` will be replaced with `jquery/dist/jquery.js`
  85. * which is relative to [[baseUrl]] and [[basePath]].
  86. *
  87. * ```php
  88. * [
  89. * 'jquery.min.js' => 'jquery/dist/jquery.js',
  90. * ]
  91. * ```
  92. *
  93. * You may also use aliases while specifying map value, for example:
  94. *
  95. * ```php
  96. * [
  97. * 'jquery.min.js' => '@web/js/jquery/jquery.js',
  98. * ]
  99. * ```
  100. */
  101. public $assetMap = [];
  102. /**
  103. * @var boolean whether to use symbolic link to publish asset files. Defaults to false, meaning
  104. * asset files are copied to [[basePath]]. Using symbolic links has the benefit that the published
  105. * assets will always be consistent with the source assets and there is no copy operation required.
  106. * This is especially useful during development.
  107. *
  108. * However, there are special requirements for hosting environments in order to use symbolic links.
  109. * In particular, symbolic links are supported only on Linux/Unix, and Windows Vista/2008 or greater.
  110. *
  111. * Moreover, some Web servers need to be properly configured so that the linked assets are accessible
  112. * to Web users. For example, for Apache Web server, the following configuration directive should be added
  113. * for the Web folder:
  114. *
  115. * ```apache
  116. * Options FollowSymLinks
  117. * ```
  118. */
  119. public $linkAssets = false;
  120. /**
  121. * @var integer the permission to be set for newly published asset files.
  122. * This value will be used by PHP chmod() function. No umask will be applied.
  123. * If not set, the permission will be determined by the current environment.
  124. */
  125. public $fileMode;
  126. /**
  127. * @var integer the permission to be set for newly generated asset directories.
  128. * This value will be used by PHP chmod() function. No umask will be applied.
  129. * Defaults to 0775, meaning the directory is read-writable by owner and group,
  130. * but read-only for other users.
  131. */
  132. public $dirMode = 0775;
  133. /**
  134. * @var callback a PHP callback that is called before copying each sub-directory or file.
  135. * This option is used only when publishing a directory. If the callback returns false, the copy
  136. * operation for the sub-directory or file will be cancelled.
  137. *
  138. * The signature of the callback should be: `function ($from, $to)`, where `$from` is the sub-directory or
  139. * file to be copied from, while `$to` is the copy target.
  140. *
  141. * This is passed as a parameter `beforeCopy` to [[\yii\helpers\FileHelper::copyDirectory()]].
  142. */
  143. public $beforeCopy;
  144. /**
  145. * @var callback a PHP callback that is called after a sub-directory or file is successfully copied.
  146. * This option is used only when publishing a directory. The signature of the callback is the same as
  147. * for [[beforeCopy]].
  148. * This is passed as a parameter `afterCopy` to [[\yii\helpers\FileHelper::copyDirectory()]].
  149. */
  150. public $afterCopy;
  151. /**
  152. * @var boolean whether the directory being published should be copied even if
  153. * it is found in the target directory. This option is used only when publishing a directory.
  154. * You may want to set this to be `true` during the development stage to make sure the published
  155. * directory is always up-to-date. Do not set this to true on production servers as it will
  156. * significantly degrade the performance.
  157. */
  158. public $forceCopy = false;
  159. /**
  160. * @var boolean whether to append a timestamp to the URL of every published asset. When this is true,
  161. * the URL of a published asset may look like `/path/to/asset?v=timestamp`, where `timestamp` is the
  162. * last modification time of the published asset file.
  163. * You normally would want to set this property to true when you have enabled HTTP caching for assets,
  164. * because it allows you to bust caching when the assets are updated.
  165. * @since 2.0.3
  166. */
  167. public $appendTimestamp = false;
  168. /**
  169. * @var callable a callback that will be called to produce hash for asset directory generation.
  170. * The signature of the callback should be as follows:
  171. *
  172. * ```
  173. * function ($path)
  174. * ```
  175. *
  176. * where `$path` is the asset path. Note that the `$path` can be either directory where the asset
  177. * files reside or a single file. For a CSS file that uses relative path in `url()`, the hash
  178. * implementation should use the directory path of the file instead of the file path to include
  179. * the relative asset files in the copying.
  180. *
  181. * If this is not set, the asset manager will use the default CRC32 and filemtime in the `hash`
  182. * method.
  183. *
  184. * Example of an implementation using MD4 hash:
  185. *
  186. * ```php
  187. * function ($path) {
  188. * return hash('md4', $path);
  189. * }
  190. * ```
  191. *
  192. * @since 2.0.6
  193. */
  194. public $hashCallback;
  195. private $_dummyBundles = [];
  196. /**
  197. * Initializes the component.
  198. * @throws InvalidConfigException if [[basePath]] is invalid
  199. */
  200. public function init()
  201. {
  202. parent::init();
  203. $this->basePath = Yii::getAlias($this->basePath);
  204. if (!is_dir($this->basePath)) {
  205. throw new InvalidConfigException("The directory does not exist: {$this->basePath}");
  206. } elseif (!is_writable($this->basePath)) {
  207. throw new InvalidConfigException("The directory is not writable by the Web process: {$this->basePath}");
  208. } else {
  209. $this->basePath = realpath($this->basePath);
  210. }
  211. $this->baseUrl = rtrim(Yii::getAlias($this->baseUrl), '/');
  212. }
  213. /**
  214. * Returns the named asset bundle.
  215. *
  216. * This method will first look for the bundle in [[bundles]]. If not found,
  217. * it will treat `$name` as the class of the asset bundle and create a new instance of it.
  218. *
  219. * @param string $name the class name of the asset bundle (without the leading backslash)
  220. * @param boolean $publish whether to publish the asset files in the asset bundle before it is returned.
  221. * If you set this false, you must manually call `AssetBundle::publish()` to publish the asset files.
  222. * @return AssetBundle the asset bundle instance
  223. * @throws InvalidConfigException if $name does not refer to a valid asset bundle
  224. */
  225. public function getBundle($name, $publish = true)
  226. {
  227. if ($this->bundles === false) {
  228. return $this->loadDummyBundle($name);
  229. } elseif (!isset($this->bundles[$name])) {
  230. return $this->bundles[$name] = $this->loadBundle($name, [], $publish);
  231. } elseif ($this->bundles[$name] instanceof AssetBundle) {
  232. return $this->bundles[$name];
  233. } elseif (is_array($this->bundles[$name])) {
  234. return $this->bundles[$name] = $this->loadBundle($name, $this->bundles[$name], $publish);
  235. } elseif ($this->bundles[$name] === false) {
  236. return $this->loadDummyBundle($name);
  237. } else {
  238. throw new InvalidConfigException("Invalid asset bundle configuration: $name");
  239. }
  240. }
  241. /**
  242. * Loads asset bundle class by name
  243. *
  244. * @param string $name bundle name
  245. * @param array $config bundle object configuration
  246. * @param boolean $publish if bundle should be published
  247. * @return AssetBundle
  248. * @throws InvalidConfigException if configuration isn't valid
  249. */
  250. protected function loadBundle($name, $config = [], $publish = true)
  251. {
  252. if (!isset($config['class'])) {
  253. $config['class'] = $name;
  254. }
  255. /* @var $bundle AssetBundle */
  256. $bundle = Yii::createObject($config);
  257. if ($publish) {
  258. $bundle->publish($this);
  259. }
  260. return $bundle;
  261. }
  262. /**
  263. * Loads dummy bundle by name
  264. *
  265. * @param string $name
  266. * @return AssetBundle
  267. */
  268. protected function loadDummyBundle($name)
  269. {
  270. if (!isset($this->_dummyBundles[$name])) {
  271. $this->_dummyBundles[$name] = $this->loadBundle($name, [
  272. 'sourcePath' => null,
  273. 'js' => [],
  274. 'css' => [],
  275. 'depends' => [],
  276. ]);
  277. }
  278. return $this->_dummyBundles[$name];
  279. }
  280. /**
  281. * Returns the actual URL for the specified asset.
  282. * The actual URL is obtained by prepending either [[baseUrl]] or [[AssetManager::baseUrl]] to the given asset path.
  283. * @param AssetBundle $bundle the asset bundle which the asset file belongs to
  284. * @param string $asset the asset path. This should be one of the assets listed in [[js]] or [[css]].
  285. * @return string the actual URL for the specified asset.
  286. */
  287. public function getAssetUrl($bundle, $asset)
  288. {
  289. if (($actualAsset = $this->resolveAsset($bundle, $asset)) !== false) {
  290. if (strncmp($actualAsset, '@web/', 5) === 0) {
  291. $asset = substr($actualAsset, 5);
  292. $basePath = Yii::getAlias('@webroot');
  293. $baseUrl = Yii::getAlias('@web');
  294. } else {
  295. $asset = Yii::getAlias($actualAsset);
  296. $basePath = $this->basePath;
  297. $baseUrl = $this->baseUrl;
  298. }
  299. } else {
  300. $basePath = $bundle->basePath;
  301. $baseUrl = $bundle->baseUrl;
  302. }
  303. if (!Url::isRelative($asset) || strncmp($asset, '/', 1) === 0) {
  304. return $asset;
  305. }
  306. if ($this->appendTimestamp && ($timestamp = @filemtime("$basePath/$asset")) > 0) {
  307. return "$baseUrl/$asset?v=$timestamp";
  308. } else {
  309. return "$baseUrl/$asset";
  310. }
  311. }
  312. /**
  313. * Returns the actual file path for the specified asset.
  314. * @param AssetBundle $bundle the asset bundle which the asset file belongs to
  315. * @param string $asset the asset path. This should be one of the assets listed in [[js]] or [[css]].
  316. * @return string|boolean the actual file path, or false if the asset is specified as an absolute URL
  317. */
  318. public function getAssetPath($bundle, $asset)
  319. {
  320. if (($actualAsset = $this->resolveAsset($bundle, $asset)) !== false) {
  321. return Url::isRelative($actualAsset) ? $this->basePath . '/' . $actualAsset : false;
  322. } else {
  323. return Url::isRelative($asset) ? $bundle->basePath . '/' . $asset : false;
  324. }
  325. }
  326. /**
  327. * @param AssetBundle $bundle
  328. * @param string $asset
  329. * @return string|boolean
  330. */
  331. protected function resolveAsset($bundle, $asset)
  332. {
  333. if (isset($this->assetMap[$asset])) {
  334. return $this->assetMap[$asset];
  335. }
  336. if ($bundle->sourcePath !== null && Url::isRelative($asset)) {
  337. $asset = $bundle->sourcePath . '/' . $asset;
  338. }
  339. $n = mb_strlen($asset, Yii::$app->charset);
  340. foreach ($this->assetMap as $from => $to) {
  341. $n2 = mb_strlen($from, Yii::$app->charset);
  342. if ($n2 <= $n && substr_compare($asset, $from, $n - $n2, $n2) === 0) {
  343. return $to;
  344. }
  345. }
  346. return false;
  347. }
  348. private $_converter;
  349. /**
  350. * Returns the asset converter.
  351. * @return AssetConverterInterface the asset converter.
  352. */
  353. public function getConverter()
  354. {
  355. if ($this->_converter === null) {
  356. $this->_converter = Yii::createObject(AssetConverter::className());
  357. } elseif (is_array($this->_converter) || is_string($this->_converter)) {
  358. if (is_array($this->_converter) && !isset($this->_converter['class'])) {
  359. $this->_converter['class'] = AssetConverter::className();
  360. }
  361. $this->_converter = Yii::createObject($this->_converter);
  362. }
  363. return $this->_converter;
  364. }
  365. /**
  366. * Sets the asset converter.
  367. * @param array|AssetConverterInterface $value the asset converter. This can be either
  368. * an object implementing the [[AssetConverterInterface]], or a configuration
  369. * array that can be used to create the asset converter object.
  370. */
  371. public function setConverter($value)
  372. {
  373. $this->_converter = $value;
  374. }
  375. /**
  376. * @var array published assets
  377. */
  378. private $_published = [];
  379. /**
  380. * Publishes a file or a directory.
  381. *
  382. * This method will copy the specified file or directory to [[basePath]] so that
  383. * it can be accessed via the Web server.
  384. *
  385. * If the asset is a file, its file modification time will be checked to avoid
  386. * unnecessary file copying.
  387. *
  388. * If the asset is a directory, all files and subdirectories under it will be published recursively.
  389. * Note, in case $forceCopy is false the method only checks the existence of the target
  390. * directory to avoid repetitive copying (which is very expensive).
  391. *
  392. * By default, when publishing a directory, subdirectories and files whose name starts with a dot "."
  393. * will NOT be published. If you want to change this behavior, you may specify the "beforeCopy" option
  394. * as explained in the `$options` parameter.
  395. *
  396. * Note: On rare scenario, a race condition can develop that will lead to a
  397. * one-time-manifestation of a non-critical problem in the creation of the directory
  398. * that holds the published assets. This problem can be avoided altogether by 'requesting'
  399. * in advance all the resources that are supposed to trigger a 'publish()' call, and doing
  400. * that in the application deployment phase, before system goes live. See more in the following
  401. * discussion: http://code.google.com/p/yii/issues/detail?id=2579
  402. *
  403. * @param string $path the asset (file or directory) to be published
  404. * @param array $options the options to be applied when publishing a directory.
  405. * The following options are supported:
  406. *
  407. * - only: array, list of patterns that the file paths should match if they want to be copied.
  408. * - except: array, list of patterns that the files or directories should match if they want to be excluded from being copied.
  409. * - caseSensitive: boolean, whether patterns specified at "only" or "except" should be case sensitive. Defaults to true.
  410. * - beforeCopy: callback, a PHP callback that is called before copying each sub-directory or file.
  411. * This overrides [[beforeCopy]] if set.
  412. * - afterCopy: callback, a PHP callback that is called after a sub-directory or file is successfully copied.
  413. * This overrides [[afterCopy]] if set.
  414. * - forceCopy: boolean, whether the directory being published should be copied even if
  415. * it is found in the target directory. This option is used only when publishing a directory.
  416. * This overrides [[forceCopy]] if set.
  417. *
  418. * @return array the path (directory or file path) and the URL that the asset is published as.
  419. * @throws InvalidParamException if the asset to be published does not exist.
  420. */
  421. public function publish($path, $options = [])
  422. {
  423. $path = Yii::getAlias($path);
  424. if (isset($this->_published[$path])) {
  425. return $this->_published[$path];
  426. }
  427. if (!is_string($path) || ($src = realpath($path)) === false) {
  428. throw new InvalidParamException("The file or directory to be published does not exist: $path");
  429. }
  430. if (is_file($src)) {
  431. return $this->_published[$path] = $this->publishFile($src);
  432. } else {
  433. return $this->_published[$path] = $this->publishDirectory($src, $options);
  434. }
  435. }
  436. /**
  437. * Publishes a file.
  438. * @param string $src the asset file to be published
  439. * @return array the path and the URL that the asset is published as.
  440. * @throws InvalidParamException if the asset to be published does not exist.
  441. */
  442. protected function publishFile($src)
  443. {
  444. $dir = $this->hash($src);
  445. $fileName = basename($src);
  446. $dstDir = $this->basePath . DIRECTORY_SEPARATOR . $dir;
  447. $dstFile = $dstDir . DIRECTORY_SEPARATOR . $fileName;
  448. if (!is_dir($dstDir)) {
  449. FileHelper::createDirectory($dstDir, $this->dirMode, true);
  450. }
  451. if ($this->linkAssets) {
  452. if (!is_file($dstFile)) {
  453. symlink($src, $dstFile);
  454. }
  455. } elseif (@filemtime($dstFile) < @filemtime($src)) {
  456. copy($src, $dstFile);
  457. if ($this->fileMode !== null) {
  458. @chmod($dstFile, $this->fileMode);
  459. }
  460. }
  461. return [$dstFile, $this->baseUrl . "/$dir/$fileName"];
  462. }
  463. /**
  464. * Publishes a directory.
  465. * @param string $src the asset directory to be published
  466. * @param array $options the options to be applied when publishing a directory.
  467. * The following options are supported:
  468. *
  469. * - only: array, list of patterns that the file paths should match if they want to be copied.
  470. * - except: array, list of patterns that the files or directories should match if they want to be excluded from being copied.
  471. * - caseSensitive: boolean, whether patterns specified at "only" or "except" should be case sensitive. Defaults to true.
  472. * - beforeCopy: callback, a PHP callback that is called before copying each sub-directory or file.
  473. * This overrides [[beforeCopy]] if set.
  474. * - afterCopy: callback, a PHP callback that is called after a sub-directory or file is successfully copied.
  475. * This overrides [[afterCopy]] if set.
  476. * - forceCopy: boolean, whether the directory being published should be copied even if
  477. * it is found in the target directory. This option is used only when publishing a directory.
  478. * This overrides [[forceCopy]] if set.
  479. *
  480. * @return array the path directory and the URL that the asset is published as.
  481. * @throws InvalidParamException if the asset to be published does not exist.
  482. */
  483. protected function publishDirectory($src, $options)
  484. {
  485. $dir = $this->hash($src);
  486. $dstDir = $this->basePath . DIRECTORY_SEPARATOR . $dir;
  487. if ($this->linkAssets) {
  488. if (!is_dir($dstDir)) {
  489. FileHelper::createDirectory(dirname($dstDir), $this->dirMode, true);
  490. symlink($src, $dstDir);
  491. }
  492. } elseif (!empty($options['forceCopy']) || ($this->forceCopy && !isset($options['forceCopy'])) || !is_dir($dstDir)) {
  493. $opts = array_merge(
  494. $options,
  495. [
  496. 'dirMode' => $this->dirMode,
  497. 'fileMode' => $this->fileMode,
  498. ]
  499. );
  500. if (!isset($opts['beforeCopy'])) {
  501. if ($this->beforeCopy !== null) {
  502. $opts['beforeCopy'] = $this->beforeCopy;
  503. } else {
  504. $opts['beforeCopy'] = function ($from, $to) {
  505. return strncmp(basename($from), '.', 1) !== 0;
  506. };
  507. }
  508. }
  509. if (!isset($opts['afterCopy']) && $this->afterCopy !== null) {
  510. $opts['afterCopy'] = $this->afterCopy;
  511. }
  512. FileHelper::copyDirectory($src, $dstDir, $opts);
  513. }
  514. return [$dstDir, $this->baseUrl . '/' . $dir];
  515. }
  516. /**
  517. * Returns the published path of a file path.
  518. * This method does not perform any publishing. It merely tells you
  519. * if the file or directory is published, where it will go.
  520. * @param string $path directory or file path being published
  521. * @return string|false string the published file path. False if the file or directory does not exist
  522. */
  523. public function getPublishedPath($path)
  524. {
  525. $path = Yii::getAlias($path);
  526. if (isset($this->_published[$path])) {
  527. return $this->_published[$path][0];
  528. }
  529. if (is_string($path) && ($path = realpath($path)) !== false) {
  530. return $this->basePath . DIRECTORY_SEPARATOR . $this->hash($path) . (is_file($path) ? DIRECTORY_SEPARATOR . basename($path) : '');
  531. } else {
  532. return false;
  533. }
  534. }
  535. /**
  536. * Returns the URL of a published file path.
  537. * This method does not perform any publishing. It merely tells you
  538. * if the file path is published, what the URL will be to access it.
  539. * @param string $path directory or file path being published
  540. * @return string|false string the published URL for the file or directory. False if the file or directory does not exist.
  541. */
  542. public function getPublishedUrl($path)
  543. {
  544. $path = Yii::getAlias($path);
  545. if (isset($this->_published[$path])) {
  546. return $this->_published[$path][1];
  547. }
  548. if (is_string($path) && ($path = realpath($path)) !== false) {
  549. return $this->baseUrl . '/' . $this->hash($path) . (is_file($path) ? '/' . basename($path) : '');
  550. } else {
  551. return false;
  552. }
  553. }
  554. /**
  555. * Generate a CRC32 hash for the directory path. Collisions are higher
  556. * than MD5 but generates a much smaller hash string.
  557. * @param string $path string to be hashed.
  558. * @return string hashed string.
  559. */
  560. protected function hash($path)
  561. {
  562. if (is_callable($this->hashCallback)) {
  563. return call_user_func($this->hashCallback, $path);
  564. }
  565. $path = (is_file($path) ? dirname($path) : $path) . filemtime($path);
  566. return sprintf('%x', crc32($path . Yii::getVersion()));
  567. }
  568. }