1
0

CompressionMiddleware.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2020, Roeland Jago Douma <roeland@famdouma.nl>
  5. *
  6. * @author Morris Jobke <hey@morrisjobke.de>
  7. * @author Roeland Jago Douma <roeland@famdouma.nl>
  8. *
  9. * @license GNU AGPL version 3 or any later version
  10. *
  11. * This program is free software: you can redistribute it and/or modify
  12. * it under the terms of the GNU Affero General Public License as
  13. * published by the Free Software Foundation, either version 3 of the
  14. * License, or (at your option) any later version.
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU Affero General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU Affero General Public License
  22. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. *
  24. */
  25. namespace OC\AppFramework\Middleware;
  26. use OC\AppFramework\OCS\BaseResponse;
  27. use OCP\AppFramework\Http;
  28. use OCP\AppFramework\Http\JSONResponse;
  29. use OCP\AppFramework\Http\Response;
  30. use OCP\AppFramework\Http\TemplateResponse;
  31. use OCP\AppFramework\Middleware;
  32. use OCP\IRequest;
  33. class CompressionMiddleware extends Middleware {
  34. /** @var bool */
  35. private $useGZip;
  36. /** @var IRequest */
  37. private $request;
  38. public function __construct(IRequest $request) {
  39. $this->request = $request;
  40. $this->useGZip = false;
  41. }
  42. public function afterController($controller, $methodName, Response $response) {
  43. // By default we do not gzip
  44. $allowGzip = false;
  45. // Only return gzipped content for 200 responses
  46. if ($response->getStatus() !== Http::STATUS_OK) {
  47. return $response;
  48. }
  49. // Check if we are even asked for gzip
  50. $header = $this->request->getHeader('Accept-Encoding');
  51. if (strpos($header, 'gzip') === false) {
  52. return $response;
  53. }
  54. // We only allow gzip in some cases
  55. if ($response instanceof BaseResponse) {
  56. $allowGzip = true;
  57. }
  58. if ($response instanceof JSONResponse) {
  59. $allowGzip = true;
  60. }
  61. if ($response instanceof TemplateResponse) {
  62. $allowGzip = true;
  63. }
  64. if ($allowGzip) {
  65. $this->useGZip = true;
  66. $response->addHeader('Content-Encoding', 'gzip');
  67. }
  68. return $response;
  69. }
  70. public function beforeOutput($controller, $methodName, $output) {
  71. if (!$this->useGZip) {
  72. return $output;
  73. }
  74. return gzencode($output);
  75. }
  76. }