CompressionMiddleware.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2020 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\AppFramework\Middleware;
  8. use OC\AppFramework\OCS\BaseResponse;
  9. use OCP\AppFramework\Http;
  10. use OCP\AppFramework\Http\JSONResponse;
  11. use OCP\AppFramework\Http\Response;
  12. use OCP\AppFramework\Http\TemplateResponse;
  13. use OCP\AppFramework\Middleware;
  14. use OCP\IRequest;
  15. class CompressionMiddleware extends Middleware {
  16. /** @var bool */
  17. private $useGZip;
  18. /** @var IRequest */
  19. private $request;
  20. public function __construct(IRequest $request) {
  21. $this->request = $request;
  22. $this->useGZip = false;
  23. }
  24. public function afterController($controller, $methodName, Response $response) {
  25. // By default we do not gzip
  26. $allowGzip = false;
  27. // Only return gzipped content for 200 responses
  28. if ($response->getStatus() !== Http::STATUS_OK) {
  29. return $response;
  30. }
  31. // Check if we are even asked for gzip
  32. $header = $this->request->getHeader('Accept-Encoding');
  33. if (!str_contains($header, 'gzip')) {
  34. return $response;
  35. }
  36. // We only allow gzip in some cases
  37. if ($response instanceof BaseResponse) {
  38. $allowGzip = true;
  39. }
  40. if ($response instanceof JSONResponse) {
  41. $allowGzip = true;
  42. }
  43. if ($response instanceof TemplateResponse) {
  44. $allowGzip = true;
  45. }
  46. if ($allowGzip) {
  47. $this->useGZip = true;
  48. $response->addHeader('Content-Encoding', 'gzip');
  49. }
  50. return $response;
  51. }
  52. public function beforeOutput($controller, $methodName, $output) {
  53. if (!$this->useGZip) {
  54. return $output;
  55. }
  56. return gzencode($output);
  57. }
  58. }