AnonymousOptionsPlugin.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-or-later
  5. */
  6. namespace OCA\DAV\Connector\Sabre;
  7. use Sabre\DAV\CorePlugin;
  8. use Sabre\DAV\FS\Directory;
  9. use Sabre\DAV\ServerPlugin;
  10. use Sabre\DAV\Tree;
  11. use Sabre\HTTP\RequestInterface;
  12. use Sabre\HTTP\ResponseInterface;
  13. class AnonymousOptionsPlugin extends ServerPlugin {
  14. /**
  15. * @var \Sabre\DAV\Server
  16. */
  17. private $server;
  18. /**
  19. * @param \Sabre\DAV\Server $server
  20. * @return void
  21. */
  22. public function initialize(\Sabre\DAV\Server $server) {
  23. $this->server = $server;
  24. // before auth
  25. $this->server->on('beforeMethod:*', [$this, 'handleAnonymousOptions'], 9);
  26. }
  27. /**
  28. * @return bool
  29. */
  30. public function isRequestInRoot($path) {
  31. return $path === '' || (is_string($path) && !str_contains($path, '/'));
  32. }
  33. /**
  34. * @throws \Sabre\DAV\Exception\Forbidden
  35. * @return bool
  36. */
  37. public function handleAnonymousOptions(RequestInterface $request, ResponseInterface $response) {
  38. $isOffice = preg_match('/Microsoft Office/i', $request->getHeader('User-Agent') ?? '');
  39. $emptyAuth = $request->getHeader('Authorization') === null
  40. || $request->getHeader('Authorization') === ''
  41. || trim($request->getHeader('Authorization')) === 'Bearer';
  42. $isAnonymousOfficeOption = $request->getMethod() === 'OPTIONS' && $isOffice && $emptyAuth;
  43. $isOfficeHead = $request->getMethod() === 'HEAD' && $isOffice && $emptyAuth;
  44. if ($isAnonymousOfficeOption || $isOfficeHead) {
  45. /** @var CorePlugin $corePlugin */
  46. $corePlugin = $this->server->getPlugin('core');
  47. // setup a fake tree for anonymous access
  48. $this->server->tree = new Tree(new Directory(''));
  49. $corePlugin->httpOptions($request, $response);
  50. $this->server->emit('afterMethod:*', [$request, $response]);
  51. $this->server->emit('afterMethod:OPTIONS', [$request, $response]);
  52. $this->server->sapi->sendResponse($response);
  53. return false;
  54. }
  55. }
  56. }