You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
2.4 KiB

3 years ago
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2019, 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\Security\FeaturePolicy;
  26. use OCP\AppFramework\Http\EmptyFeaturePolicy;
  27. use OCP\EventDispatcher\IEventDispatcher;
  28. use OCP\Security\FeaturePolicy\AddFeaturePolicyEvent;
  29. class FeaturePolicyManager {
  30. /** @var EmptyFeaturePolicy[] */
  31. private $policies = [];
  32. /** @var IEventDispatcher */
  33. private $dispatcher;
  34. public function __construct(IEventDispatcher $dispatcher) {
  35. $this->dispatcher = $dispatcher;
  36. }
  37. public function addDefaultPolicy(EmptyFeaturePolicy $policy): void {
  38. $this->policies[] = $policy;
  39. }
  40. public function getDefaultPolicy(): FeaturePolicy {
  41. $event = new AddFeaturePolicyEvent($this);
  42. $this->dispatcher->dispatchTyped($event);
  43. $defaultPolicy = new FeaturePolicy();
  44. foreach ($this->policies as $policy) {
  45. $defaultPolicy = $this->mergePolicies($defaultPolicy, $policy);
  46. }
  47. return $defaultPolicy;
  48. }
  49. /**
  50. * Merges the first given policy with the second one
  51. *
  52. */
  53. public function mergePolicies(FeaturePolicy $defaultPolicy,
  54. EmptyFeaturePolicy $originalPolicy): FeaturePolicy {
  55. foreach ((object)(array)$originalPolicy as $name => $value) {
  56. $setter = 'set' . ucfirst($name);
  57. if (\is_array($value)) {
  58. $getter = 'get' . ucfirst($name);
  59. $currentValues = \is_array($defaultPolicy->$getter()) ? $defaultPolicy->$getter() : [];
  60. $defaultPolicy->$setter(\array_values(\array_unique(\array_merge($currentValues, $value))));
  61. } elseif (\is_bool($value)) {
  62. $defaultPolicy->$setter($value);
  63. }
  64. }
  65. return $defaultPolicy;
  66. }
  67. }