No Description

ApiDataSanitizer.php 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace MailPoet\Newsletter;
  3. if (!defined('ABSPATH')) exit;
  4. class ApiDataSanitizer {
  5. /** @var NewsletterHtmlSanitizer */
  6. private $htmlSanitizer;
  7. /**
  8. * Configuration specifies which block types and properties within newsletters content blocks are sanitized
  9. */
  10. private const SANITIZATION_CONFIG = [
  11. 'header' => ['text'],
  12. 'footer' => ['text'],
  13. 'text' => ['text'],
  14. ];
  15. public function __construct(
  16. NewsletterHtmlSanitizer $htmlSanitizer
  17. ) {
  18. $this->htmlSanitizer = $htmlSanitizer;
  19. }
  20. public function sanitizeBody(array $body): array {
  21. if (isset($body['content']) && isset($body['content']['blocks']) && is_array($body['content']['blocks'])) {
  22. $body['content']['blocks'] = $this->sanitizeBlocks($body['content']['blocks']);
  23. }
  24. return $body;
  25. }
  26. private function sanitizeBlocks(array $blocks): array {
  27. foreach ($blocks as $key => $block) {
  28. if (!is_array($block) || !isset($block['type'])) {
  29. continue;
  30. }
  31. if (isset($block['blocks']) && is_array($block['blocks'])) {
  32. $blocks[$key]['blocks'] = $this->sanitizeBlocks($block['blocks']);
  33. } else {
  34. $blocks[$key] = $this->sanitizeBlock($block);
  35. }
  36. };
  37. return $blocks;
  38. }
  39. private function sanitizeBlock(array $block): array {
  40. if (!isset(self::SANITIZATION_CONFIG[$block['type']])) {
  41. return $block;
  42. }
  43. foreach (self::SANITIZATION_CONFIG[$block['type']] as $property) {
  44. if (!isset($block[$property])) {
  45. continue;
  46. }
  47. $block[$property] = $this->htmlSanitizer->sanitize($block[$property]);
  48. }
  49. return $block;
  50. }
  51. }