AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

LogoSvg.php 7.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. <?php
  2. namespace App\Storefront\Logos;
  3. use DOMDocument;
  4. use DOMElement;
  5. use DOMNode;
  6. /**
  7. * Makes a logo drawing from the AI safe to put inside a store page.
  8. *
  9. * The drawing is rebuilt from scratch, keeping only simple shapes, text and colour gradients, with a short
  10. * list of attributes whose values are checked. Anything that could run code or load something from outside
  11. * (scripts, links, pictures, styles, event handlers, foreign content) is dropped. Text always uses the
  12. * store's heading font, through a CSS variable the storefront sets.
  13. */
  14. final class LogoSvg
  15. {
  16. /** Bigger drawings are refused: a logo is a few shapes. */
  17. public const int MAX_BYTES = 20000;
  18. private const int MAX_ELEMENTS = 300;
  19. private const array ELEMENTS = [
  20. 'svg', 'g', 'path', 'circle', 'ellipse', 'rect', 'line', 'polyline', 'polygon',
  21. 'text', 'tspan', 'defs', 'lineargradient', 'radialgradient', 'stop',
  22. ];
  23. private const array NUMBERS = [
  24. 'x', 'y', 'x1', 'y1', 'x2', 'y2', 'cx', 'cy', 'r', 'rx', 'ry', 'fx', 'fy', 'width', 'height',
  25. 'stroke-width', 'opacity', 'fill-opacity', 'stroke-opacity', 'stop-opacity', 'font-size', 'letter-spacing', 'offset', 'dx', 'dy',
  26. ];
  27. private const array COLORS = ['fill', 'stroke', 'stop-color'];
  28. private const array KEYWORDS = [
  29. 'stroke-linecap' => ['butt', 'round', 'square'],
  30. 'stroke-linejoin' => ['miter', 'round', 'bevel'],
  31. 'fill-rule' => ['nonzero', 'evenodd'],
  32. 'clip-rule' => ['nonzero', 'evenodd'],
  33. 'text-anchor' => ['start', 'middle', 'end'],
  34. 'dominant-baseline' => ['auto', 'middle', 'central', 'hanging', 'alphabetic'],
  35. 'font-weight' => ['normal', 'bold', '300', '400', '500', '600', '700', '800', '900'],
  36. 'font-style' => ['normal', 'italic'],
  37. 'gradientunits' => ['userSpaceOnUse', 'objectBoundingBox'],
  38. ];
  39. /**
  40. * The cleaned drawing, or null when it is not a usable logo.
  41. */
  42. public static function clean(string $svg): ?string
  43. {
  44. $svg = trim($svg);
  45. if ($svg === '' || strlen($svg) > self::MAX_BYTES || stripos($svg, '<!DOCTYPE') !== false || stripos($svg, '<!ENTITY') !== false) {
  46. return null;
  47. }
  48. $source = new DOMDocument;
  49. $previous = libxml_use_internal_errors(true);
  50. // No network, no entities: the text is only read, never trusted.
  51. $loaded = $source->loadXML($svg, LIBXML_NONET);
  52. libxml_clear_errors();
  53. libxml_use_internal_errors($previous);
  54. $root = $source->documentElement;
  55. if (! $loaded || ! $root instanceof DOMElement || strtolower($root->localName) !== 'svg') {
  56. return null;
  57. }
  58. $viewBox = self::viewBox($root->getAttribute('viewBox'));
  59. if ($viewBox === null) {
  60. return null;
  61. }
  62. $target = new DOMDocument;
  63. $out = $target->createElementNS('http://www.w3.org/2000/svg', 'svg');
  64. $out->setAttribute('viewBox', $viewBox);
  65. $target->appendChild($out);
  66. // Ids get a random prefix, so two logos on one page never share a gradient by accident.
  67. $prefix = 'l'.bin2hex(random_bytes(3)).'-';
  68. $count = 0;
  69. foreach (iterator_to_array($root->childNodes) as $child) {
  70. self::copy($child, $out, $target, $prefix, $count);
  71. }
  72. if ($count === 0 || $count > self::MAX_ELEMENTS) {
  73. return null;
  74. }
  75. $result = $target->saveXML($out);
  76. return is_string($result) && strlen($result) <= self::MAX_BYTES ? $result : null;
  77. }
  78. private static function copy(DOMNode $node, DOMElement $parent, DOMDocument $target, string $prefix, int &$count): void
  79. {
  80. if ($node->nodeType === XML_TEXT_NODE) {
  81. // Only text inside text elements matters; whitespace elsewhere is dropped.
  82. if (in_array(strtolower($parent->localName), ['text', 'tspan'], true) && trim((string) $node->nodeValue) !== '') {
  83. $parent->appendChild($target->createTextNode((string) $node->nodeValue));
  84. }
  85. return;
  86. }
  87. if (! $node instanceof DOMElement) {
  88. return;
  89. }
  90. $name = strtolower($node->localName);
  91. if (! in_array($name, self::ELEMENTS, true) || $name === 'svg') {
  92. return;
  93. }
  94. $count++;
  95. if ($count > self::MAX_ELEMENTS) {
  96. return;
  97. }
  98. $element = $target->createElementNS('http://www.w3.org/2000/svg', $node->localName);
  99. foreach (iterator_to_array($node->attributes ?? []) as $attribute) {
  100. $key = strtolower($attribute->localName);
  101. $value = self::value($key, trim($attribute->value), $prefix);
  102. if ($value !== null) {
  103. $element->setAttribute($attribute->localName, $value);
  104. }
  105. }
  106. if (in_array($name, ['text', 'tspan'], true)) {
  107. $element->setAttribute('style', 'font-family: var(--sf-font-heading, sans-serif)');
  108. }
  109. $parent->appendChild($element);
  110. foreach (iterator_to_array($node->childNodes) as $child) {
  111. self::copy($child, $element, $target, $prefix, $count);
  112. }
  113. }
  114. /**
  115. * The checked value of an attribute, or null to drop it.
  116. */
  117. private static function value(string $key, string $value, string $prefix): ?string
  118. {
  119. if ($value === '' || strlen($value) > 4000) {
  120. return null;
  121. }
  122. if ($key === 'id') {
  123. return preg_match('/^[A-Za-z][A-Za-z0-9_-]{0,40}$/', $value) === 1 ? $prefix.$value : null;
  124. }
  125. if (in_array($key, self::NUMBERS, true)) {
  126. return preg_match('/^-?\d*\.?\d+(%|px|em)?$/', $value) === 1 ? $value : null;
  127. }
  128. if (in_array($key, self::COLORS, true)) {
  129. return self::color($value, $prefix);
  130. }
  131. if (isset(self::KEYWORDS[$key])) {
  132. return in_array($value, self::KEYWORDS[$key], true) ? $value : null;
  133. }
  134. return match ($key) {
  135. // Path data and point lists: numbers, letters for commands, commas and spaces only.
  136. 'd' => preg_match('/^[MmLlHhVvCcSsQqTtAaZz0-9eE.,\s+-]+$/', $value) === 1 ? $value : null,
  137. 'points' => preg_match('/^[0-9eE.,\s+-]+$/', $value) === 1 ? $value : null,
  138. 'transform', 'gradienttransform' => preg_match('/^((translate|scale|rotate|matrix|skewX|skewY)\(\s*[-0-9eE.,\s]+\)\s*)+$/', $value) === 1 ? $value : null,
  139. default => null,
  140. };
  141. }
  142. private static function color(string $value, string $prefix): ?string
  143. {
  144. if (preg_match('/^#[0-9A-Fa-f]{3}([0-9A-Fa-f]{3})?$/', $value) === 1 || in_array(strtolower($value), ['none', 'currentcolor', 'white', 'black', 'transparent'], true)) {
  145. return $value;
  146. }
  147. // A gradient defined in the same drawing.
  148. if (preg_match('/^url\(#([A-Za-z][A-Za-z0-9_-]{0,40})\)$/', $value, $match) === 1) {
  149. return 'url(#'.$prefix.$match[1].')';
  150. }
  151. return null;
  152. }
  153. /**
  154. * Four numbers, with a sensible logo shape: not tiny, not huge, not taller than wide by much.
  155. */
  156. private static function viewBox(string $value): ?string
  157. {
  158. $parts = preg_split('/[\s,]+/', trim($value)) ?: [];
  159. if (count($parts) !== 4 || array_filter($parts, fn (string $part) => ! is_numeric($part)) !== []) {
  160. return null;
  161. }
  162. [$x, $y, $width, $height] = array_map('floatval', $parts);
  163. if ($width < 20 || $height < 20 || $width > 2000 || $height > 2000 || $width / $height > 8 || $height / $width > 2) {
  164. return null;
  165. }
  166. return implode(' ', array_map(fn (float $number) => rtrim(rtrim(number_format($number, 2, '.', ''), '0'), '.'), [$x, $y, $width, $height]));
  167. }
  168. }