Ssi.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. /**
  25. * @return void
  26. */
  27. public function addSurrogateControl(Response $response)
  28. {
  29. if (str_contains($response->getContent(), '<!--#include')) {
  30. $response->headers->set('Surrogate-Control', 'content="SSI/1.0"');
  31. }
  32. }
  33. public function renderIncludeTag(string $uri, ?string $alt = null, bool $ignoreErrors = true, string $comment = ''): string
  34. {
  35. return \sprintf('<!--#include virtual="%s" -->', $uri);
  36. }
  37. public function process(Request $request, Response $response): Response
  38. {
  39. $type = $response->headers->get('Content-Type');
  40. if (empty($type)) {
  41. $type = 'text/html';
  42. }
  43. $parts = explode(';', $type);
  44. if (!\in_array($parts[0], $this->contentTypes)) {
  45. return $response;
  46. }
  47. // we don't use a proper XML parser here as we can have SSI tags in a plain text response
  48. $content = $response->getContent();
  49. $boundary = self::generateBodyEvalBoundary();
  50. $chunks = preg_split('#<!--\#include\s+(.*?)\s*-->#', $content, -1, \PREG_SPLIT_DELIM_CAPTURE);
  51. $i = 1;
  52. while (isset($chunks[$i])) {
  53. $options = [];
  54. preg_match_all('/(virtual)="([^"]*?)"/', $chunks[$i], $matches, \PREG_SET_ORDER);
  55. foreach ($matches as $set) {
  56. $options[$set[1]] = $set[2];
  57. }
  58. if (!isset($options['virtual'])) {
  59. throw new \RuntimeException('Unable to process an SSI tag without a "virtual" attribute.');
  60. }
  61. $chunks[$i] = $boundary.$options['virtual']."\n\n\n";
  62. $i += 2;
  63. }
  64. $content = $boundary.implode('', $chunks).$boundary;
  65. $response->setContent($content);
  66. $response->headers->set('X-Body-Eval', 'SSI');
  67. // remove SSI/1.0 from the Surrogate-Control header
  68. $this->removeFromControl($response);
  69. return $response;
  70. }
  71. }