FeaturePolicyManager.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 array $policies = [];
  32. public function __construct(
  33. private IEventDispatcher $dispatcher,
  34. ) {
  35. }
  36. public function addDefaultPolicy(EmptyFeaturePolicy $policy): void {
  37. $this->policies[] = $policy;
  38. }
  39. public function getDefaultPolicy(): FeaturePolicy {
  40. $event = new AddFeaturePolicyEvent($this);
  41. $this->dispatcher->dispatchTyped($event);
  42. $defaultPolicy = new FeaturePolicy();
  43. foreach ($this->policies as $policy) {
  44. $defaultPolicy = $this->mergePolicies($defaultPolicy, $policy);
  45. }
  46. return $defaultPolicy;
  47. }
  48. /**
  49. * Merges the first given policy with the second one
  50. *
  51. */
  52. public function mergePolicies(
  53. FeaturePolicy $defaultPolicy,
  54. EmptyFeaturePolicy $originalPolicy,
  55. ): FeaturePolicy {
  56. foreach ((object)(array)$originalPolicy as $name => $value) {
  57. $setter = 'set' . ucfirst($name);
  58. if (\is_array($value)) {
  59. $getter = 'get' . ucfirst($name);
  60. $currentValues = \is_array($defaultPolicy->$getter()) ? $defaultPolicy->$getter() : [];
  61. $defaultPolicy->$setter(\array_values(\array_unique(\array_merge($currentValues, $value))));
  62. } elseif (\is_bool($value)) {
  63. $defaultPolicy->$setter($value);
  64. }
  65. }
  66. return $defaultPolicy;
  67. }
  68. }