FeaturePolicyManager.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2019, 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 OC\Security\FeaturePolicy;
  25. use OCP\AppFramework\Http\EmptyFeaturePolicy;
  26. use OCP\EventDispatcher\IEventDispatcher;
  27. use OCP\Security\FeaturePolicy\AddFeaturePolicyEvent;
  28. class FeaturePolicyManager {
  29. /** @var EmptyFeaturePolicy[] */
  30. private $policies = [];
  31. /** @var IEventDispatcher */
  32. private $dispatcher;
  33. public function __construct(IEventDispatcher $dispatcher) {
  34. $this->dispatcher = $dispatcher;
  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->dispatch(AddFeaturePolicyEvent::class, $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(FeaturePolicy $defaultPolicy,
  53. EmptyFeaturePolicy $originalPolicy): FeaturePolicy {
  54. foreach ((object)(array)$originalPolicy as $name => $value) {
  55. $setter = 'set' . ucfirst($name);
  56. if (\is_array($value)) {
  57. $getter = 'get' . ucfirst($name);
  58. $currentValues = \is_array($defaultPolicy->$getter()) ? $defaultPolicy->$getter() : [];
  59. $defaultPolicy->$setter(\array_values(\array_unique(\array_merge($currentValues, $value))));
  60. } elseif (\is_bool($value)) {
  61. $defaultPolicy->$setter($value);
  62. }
  63. }
  64. return $defaultPolicy;
  65. }
  66. }