AssetMiddleware.php 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 3.3.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Routing\Middleware;
  16. use Cake\Core\Plugin;
  17. use Cake\Filesystem\File;
  18. use Cake\Utility\Inflector;
  19. use Laminas\Diactoros\Response;
  20. use Laminas\Diactoros\Stream;
  21. use Psr\Http\Message\ResponseInterface;
  22. use Psr\Http\Message\ServerRequestInterface;
  23. /**
  24. * Handles serving plugin assets in development mode.
  25. *
  26. * This should not be used in production environments as it
  27. * has sub-optimal performance when compared to serving files
  28. * with a real webserver.
  29. */
  30. class AssetMiddleware
  31. {
  32. /**
  33. * The amount of time to cache the asset.
  34. *
  35. * @var string
  36. */
  37. protected $cacheTime = '+1 day';
  38. /**
  39. * A extension to content type mapping for plain text types.
  40. *
  41. * Because finfo doesn't give useful information for plain text types,
  42. * we have to handle that here.
  43. *
  44. * @var array
  45. */
  46. protected $typeMap = [
  47. 'css' => 'text/css',
  48. 'json' => 'application/json',
  49. 'js' => 'application/javascript',
  50. 'ico' => 'image/x-icon',
  51. 'eot' => 'application/vnd.ms-fontobject',
  52. 'svg' => 'image/svg+xml',
  53. 'html' => 'text/html',
  54. 'rss' => 'application/rss+xml',
  55. 'xml' => 'application/xml',
  56. ];
  57. /**
  58. * Constructor.
  59. *
  60. * @param array $options The options to use
  61. */
  62. public function __construct(array $options = [])
  63. {
  64. if (!empty($options['cacheTime'])) {
  65. $this->cacheTime = $options['cacheTime'];
  66. }
  67. if (!empty($options['types'])) {
  68. $this->typeMap = array_merge($this->typeMap, $options['types']);
  69. }
  70. }
  71. /**
  72. * Serve assets if the path matches one.
  73. *
  74. * @param \Psr\Http\Message\ServerRequestInterface $request The request.
  75. * @param \Psr\Http\Message\ResponseInterface $response The response.
  76. * @param callable $next Callback to invoke the next middleware.
  77. * @return \Psr\Http\Message\ResponseInterface A response
  78. */
  79. public function __invoke($request, $response, $next)
  80. {
  81. $url = $request->getUri()->getPath();
  82. if (strpos($url, '..') !== false || strpos($url, '.') === false) {
  83. return $next($request, $response);
  84. }
  85. if (strpos($url, '/.') !== false) {
  86. return $next($request, $response);
  87. }
  88. $assetFile = $this->_getAssetFile($url);
  89. if ($assetFile === null || !file_exists($assetFile)) {
  90. return $next($request, $response);
  91. }
  92. $file = new File($assetFile);
  93. $modifiedTime = $file->lastChange();
  94. if ($this->isNotModified($request, $file)) {
  95. $headers = $response->getHeaders();
  96. $headers['Last-Modified'] = date(DATE_RFC850, $modifiedTime);
  97. return new Response('php://memory', 304, $headers);
  98. }
  99. return $this->deliverAsset($request, $response, $file);
  100. }
  101. /**
  102. * Check the not modified header.
  103. *
  104. * @param \Psr\Http\Message\ServerRequestInterface $request The request to check.
  105. * @param \Cake\Filesystem\File $file The file object to compare.
  106. * @return bool
  107. */
  108. protected function isNotModified($request, $file)
  109. {
  110. $modifiedSince = $request->getHeaderLine('If-Modified-Since');
  111. if (!$modifiedSince) {
  112. return false;
  113. }
  114. return strtotime($modifiedSince) === $file->lastChange();
  115. }
  116. /**
  117. * Builds asset file path based off url
  118. *
  119. * @param string $url Asset URL
  120. * @return string|null Absolute path for asset file, null on failure
  121. */
  122. protected function _getAssetFile($url)
  123. {
  124. $parts = explode('/', ltrim($url, '/'));
  125. $pluginPart = [];
  126. for ($i = 0; $i < 2; $i++) {
  127. if (!isset($parts[$i])) {
  128. break;
  129. }
  130. $pluginPart[] = Inflector::camelize($parts[$i]);
  131. $plugin = implode('/', $pluginPart);
  132. if ($plugin && Plugin::isLoaded($plugin)) {
  133. $parts = array_slice($parts, $i + 1);
  134. $fileFragment = implode(DIRECTORY_SEPARATOR, $parts);
  135. $pluginWebroot = Plugin::path($plugin) . 'webroot' . DIRECTORY_SEPARATOR;
  136. return $pluginWebroot . $fileFragment;
  137. }
  138. }
  139. return null;
  140. }
  141. /**
  142. * Sends an asset file to the client
  143. *
  144. * @param \Psr\Http\Message\ServerRequestInterface $request The request object to use.
  145. * @param \Psr\Http\Message\ResponseInterface $response The response object to use.
  146. * @param \Cake\Filesystem\File $file The file wrapper for the file.
  147. * @return \Psr\Http\Message\ResponseInterface The response with the file & headers.
  148. */
  149. protected function deliverAsset(ServerRequestInterface $request, ResponseInterface $response, $file)
  150. {
  151. $contentType = $this->getType($file);
  152. $modified = $file->lastChange();
  153. $expire = strtotime($this->cacheTime);
  154. $maxAge = $expire - time();
  155. $stream = new Stream(fopen($file->path, 'rb'));
  156. return $response->withBody($stream)
  157. ->withHeader('Content-Type', $contentType)
  158. ->withHeader('Cache-Control', 'public,max-age=' . $maxAge)
  159. ->withHeader('Date', gmdate('D, j M Y G:i:s \G\M\T', time()))
  160. ->withHeader('Last-Modified', gmdate('D, j M Y G:i:s \G\M\T', $modified))
  161. ->withHeader('Expires', gmdate('D, j M Y G:i:s \G\M\T', $expire));
  162. }
  163. /**
  164. * Return the type from a File object
  165. *
  166. * @param File $file The file from which you get the type
  167. * @return string
  168. */
  169. protected function getType($file)
  170. {
  171. $extension = $file->ext();
  172. if (isset($this->typeMap[$extension])) {
  173. return $this->typeMap[$extension];
  174. }
  175. return $file->mime() ?: 'application/octet-stream';
  176. }
  177. }