PropfindCompressionPlugin.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2020, Roeland Jago Douma <roeland@famdouma.nl>
  5. *
  6. * @author Roeland Jago Douma <roeland@famdouma.nl>
  7. *
  8. * @license GNU AGPL version 3 or any later version
  9. *
  10. * This program is free software: you can redistribute it and/or modify
  11. * it under the terms of the GNU Affero General Public License as
  12. * published by the Free Software Foundation, either version 3 of the
  13. * License, or (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU Affero General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Affero General Public License
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. *
  23. */
  24. namespace OCA\DAV\Connector\Sabre;
  25. use Sabre\DAV\ServerPlugin;
  26. use Sabre\HTTP\Request;
  27. use Sabre\HTTP\Response;
  28. class PropfindCompressionPlugin extends ServerPlugin {
  29. /**
  30. * Reference to main server object
  31. *
  32. * @var Server
  33. */
  34. private $server;
  35. /**
  36. * This initializes the plugin.
  37. *
  38. * This function is called by \Sabre\DAV\Server, after
  39. * addPlugin is called.
  40. *
  41. * This method should set up the required event subscriptions.
  42. *
  43. * @param \Sabre\DAV\Server $server
  44. * @return void
  45. */
  46. public function initialize(\Sabre\DAV\Server $server) {
  47. $this->server = $server;
  48. $this->server->on('afterMethod:PROPFIND', [$this, 'compressResponse'], 100);
  49. }
  50. public function compressResponse(Request $request, Response $response) {
  51. $header = $request->getHeader('Accept-Encoding');
  52. if ($header === null) {
  53. return $response;
  54. }
  55. if (str_contains($header, 'gzip')) {
  56. $body = $response->getBody();
  57. if (is_string($body)) {
  58. $response->setHeader('Content-Encoding', 'gzip');
  59. $response->setBody(gzencode($body));
  60. }
  61. }
  62. return $response;
  63. }
  64. }