Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

560 rindas
22KB

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