Ssi.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpKernel\HttpCache;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\HttpFoundation\Response;
  13. /**
  14. * Ssi implements the SSI capabilities to Request and Response instances.
  15. *
  16. * @author Sebastian Krebs <krebs.seb@gmail.com>
  17. */
  18. class Ssi extends AbstractSurrogate
  19. {
  20. public function getName(): string
  21. {
  22. return 'ssi';
  23. }
  24. public function addSurrogateControl(Response $response): void
  25. {
  26. if (str_contains($response->getContent(), '<!--#include')) {
  27. $response->headers->set('Surrogate-Control', 'content="SSI/1.0"');
  28. }
  29. }
  30. public function renderIncludeTag(string $uri, ?string $alt = null, bool $ignoreErrors = true, string $comment = ''): string
  31. {
  32. return \sprintf('<!--#include virtual="%s" -->', $uri);
  33. }
  34. public function process(Request $request, Response $response): Response
  35. {
  36. $type = $response->headers->get('Content-Type');
  37. if (!$type) {
  38. $type = 'text/html';
  39. }
  40. $parts = explode(';', $type);
  41. if (!\in_array($parts[0], $this->contentTypes, true)) {
  42. return $response;
  43. }
  44. // we don't use a proper XML parser here as we can have SSI tags in a plain text response
  45. $content = $response->getContent();
  46. $boundary = self::generateBodyEvalBoundary();
  47. $chunks = preg_split('#<!--\#include\s+(.*?)\s*-->#', $content, -1, \PREG_SPLIT_DELIM_CAPTURE);
  48. $i = 1;
  49. while (isset($chunks[$i])) {
  50. $options = [];
  51. preg_match_all('/(virtual)="([^"]*?)"/', $chunks[$i], $matches, \PREG_SET_ORDER);
  52. foreach ($matches as $set) {
  53. $options[$set[1]] = $set[2];
  54. }
  55. if (!isset($options['virtual'])) {
  56. throw new \RuntimeException('Unable to process an SSI tag without a "virtual" attribute.');
  57. }
  58. $chunks[$i] = $boundary.$options['virtual']."\n\n\n";
  59. $i += 2;
  60. }
  61. $content = $boundary.implode('', $chunks).$boundary;
  62. $response->setContent($content);
  63. $response->headers->set('X-Body-Eval', 'SSI');
  64. // remove SSI/1.0 from the Surrogate-Control header
  65. $this->removeFromControl($response);
  66. return $response;
  67. }
  68. }