| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216 |
- <?php
-
- namespace App\Storefront\Logos;
-
- use DOMDocument;
- use DOMElement;
- use DOMNode;
-
- /**
- * Makes a logo drawing from the AI safe to put inside a store page.
- *
- * The drawing is rebuilt from scratch, keeping only simple shapes, text and colour gradients, with a short
- * list of attributes whose values are checked. Anything that could run code or load something from outside
- * (scripts, links, pictures, styles, event handlers, foreign content) is dropped. Text always uses the
- * store's heading font, through a CSS variable the storefront sets.
- */
- final class LogoSvg
- {
- /** Bigger drawings are refused: a logo is a few shapes. */
- public const int MAX_BYTES = 20000;
-
- private const int MAX_ELEMENTS = 300;
-
- private const array ELEMENTS = [
- 'svg', 'g', 'path', 'circle', 'ellipse', 'rect', 'line', 'polyline', 'polygon',
- 'text', 'tspan', 'defs', 'lineargradient', 'radialgradient', 'stop',
- ];
-
- private const array NUMBERS = [
- 'x', 'y', 'x1', 'y1', 'x2', 'y2', 'cx', 'cy', 'r', 'rx', 'ry', 'fx', 'fy', 'width', 'height',
- 'stroke-width', 'opacity', 'fill-opacity', 'stroke-opacity', 'stop-opacity', 'font-size', 'letter-spacing', 'offset', 'dx', 'dy',
- ];
-
- private const array COLORS = ['fill', 'stroke', 'stop-color'];
-
- private const array KEYWORDS = [
- 'stroke-linecap' => ['butt', 'round', 'square'],
- 'stroke-linejoin' => ['miter', 'round', 'bevel'],
- 'fill-rule' => ['nonzero', 'evenodd'],
- 'clip-rule' => ['nonzero', 'evenodd'],
- 'text-anchor' => ['start', 'middle', 'end'],
- 'dominant-baseline' => ['auto', 'middle', 'central', 'hanging', 'alphabetic'],
- 'font-weight' => ['normal', 'bold', '300', '400', '500', '600', '700', '800', '900'],
- 'font-style' => ['normal', 'italic'],
- 'gradientunits' => ['userSpaceOnUse', 'objectBoundingBox'],
- ];
-
- /**
- * The cleaned drawing, or null when it is not a usable logo.
- */
- public static function clean(string $svg): ?string
- {
- $svg = trim($svg);
-
- if ($svg === '' || strlen($svg) > self::MAX_BYTES || stripos($svg, '<!DOCTYPE') !== false || stripos($svg, '<!ENTITY') !== false) {
- return null;
- }
-
- $source = new DOMDocument;
- $previous = libxml_use_internal_errors(true);
- // No network, no entities: the text is only read, never trusted.
- $loaded = $source->loadXML($svg, LIBXML_NONET);
- libxml_clear_errors();
- libxml_use_internal_errors($previous);
-
- $root = $source->documentElement;
-
- if (! $loaded || ! $root instanceof DOMElement || strtolower($root->localName) !== 'svg') {
- return null;
- }
-
- $viewBox = self::viewBox($root->getAttribute('viewBox'));
-
- if ($viewBox === null) {
- return null;
- }
-
- $target = new DOMDocument;
- $out = $target->createElementNS('http://www.w3.org/2000/svg', 'svg');
- $out->setAttribute('viewBox', $viewBox);
- $target->appendChild($out);
-
- // Ids get a random prefix, so two logos on one page never share a gradient by accident.
- $prefix = 'l'.bin2hex(random_bytes(3)).'-';
- $count = 0;
-
- foreach (iterator_to_array($root->childNodes) as $child) {
- self::copy($child, $out, $target, $prefix, $count);
- }
-
- if ($count === 0 || $count > self::MAX_ELEMENTS) {
- return null;
- }
-
- $result = $target->saveXML($out);
-
- return is_string($result) && strlen($result) <= self::MAX_BYTES ? $result : null;
- }
-
- private static function copy(DOMNode $node, DOMElement $parent, DOMDocument $target, string $prefix, int &$count): void
- {
- if ($node->nodeType === XML_TEXT_NODE) {
- // Only text inside text elements matters; whitespace elsewhere is dropped.
- if (in_array(strtolower($parent->localName), ['text', 'tspan'], true) && trim((string) $node->nodeValue) !== '') {
- $parent->appendChild($target->createTextNode((string) $node->nodeValue));
- }
-
- return;
- }
-
- if (! $node instanceof DOMElement) {
- return;
- }
-
- $name = strtolower($node->localName);
-
- if (! in_array($name, self::ELEMENTS, true) || $name === 'svg') {
- return;
- }
-
- $count++;
-
- if ($count > self::MAX_ELEMENTS) {
- return;
- }
-
- $element = $target->createElementNS('http://www.w3.org/2000/svg', $node->localName);
-
- foreach (iterator_to_array($node->attributes ?? []) as $attribute) {
- $key = strtolower($attribute->localName);
- $value = self::value($key, trim($attribute->value), $prefix);
-
- if ($value !== null) {
- $element->setAttribute($attribute->localName, $value);
- }
- }
-
- if (in_array($name, ['text', 'tspan'], true)) {
- $element->setAttribute('style', 'font-family: var(--sf-font-heading, sans-serif)');
- }
-
- $parent->appendChild($element);
-
- foreach (iterator_to_array($node->childNodes) as $child) {
- self::copy($child, $element, $target, $prefix, $count);
- }
- }
-
- /**
- * The checked value of an attribute, or null to drop it.
- */
- private static function value(string $key, string $value, string $prefix): ?string
- {
- if ($value === '' || strlen($value) > 4000) {
- return null;
- }
-
- if ($key === 'id') {
- return preg_match('/^[A-Za-z][A-Za-z0-9_-]{0,40}$/', $value) === 1 ? $prefix.$value : null;
- }
-
- if (in_array($key, self::NUMBERS, true)) {
- return preg_match('/^-?\d*\.?\d+(%|px|em)?$/', $value) === 1 ? $value : null;
- }
-
- if (in_array($key, self::COLORS, true)) {
- return self::color($value, $prefix);
- }
-
- if (isset(self::KEYWORDS[$key])) {
- return in_array($value, self::KEYWORDS[$key], true) ? $value : null;
- }
-
- return match ($key) {
- // Path data and point lists: numbers, letters for commands, commas and spaces only.
- 'd' => preg_match('/^[MmLlHhVvCcSsQqTtAaZz0-9eE.,\s+-]+$/', $value) === 1 ? $value : null,
- 'points' => preg_match('/^[0-9eE.,\s+-]+$/', $value) === 1 ? $value : null,
- 'transform', 'gradienttransform' => preg_match('/^((translate|scale|rotate|matrix|skewX|skewY)\(\s*[-0-9eE.,\s]+\)\s*)+$/', $value) === 1 ? $value : null,
- default => null,
- };
- }
-
- private static function color(string $value, string $prefix): ?string
- {
- 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)) {
- return $value;
- }
-
- // A gradient defined in the same drawing.
- if (preg_match('/^url\(#([A-Za-z][A-Za-z0-9_-]{0,40})\)$/', $value, $match) === 1) {
- return 'url(#'.$prefix.$match[1].')';
- }
-
- return null;
- }
-
- /**
- * Four numbers, with a sensible logo shape: not tiny, not huge, not taller than wide by much.
- */
- private static function viewBox(string $value): ?string
- {
- $parts = preg_split('/[\s,]+/', trim($value)) ?: [];
-
- if (count($parts) !== 4 || array_filter($parts, fn (string $part) => ! is_numeric($part)) !== []) {
- return null;
- }
-
- [$x, $y, $width, $height] = array_map('floatval', $parts);
-
- if ($width < 20 || $height < 20 || $width > 2000 || $height > 2000 || $width / $height > 8 || $height / $width > 2) {
- return null;
- }
-
- return implode(' ', array_map(fn (float $number) => rtrim(rtrim(number_format($number, 2, '.', ''), '0'), '.'), [$x, $y, $width, $height]));
- }
- }
|