self::linkify($text), ['is_safe' => ['html']]), ]; } public function getFunctions(): array { return [ new TwigFunction('plan_item_type_name', fn (string $kind, ?string $key): ?string => $this->typeProvider->getName($kind, $key)), new TwigFunction('plan_item_type_description', fn (string $kind, ?string $key): ?string => $this->typeProvider->getDescription($kind, $key)), new TwigFunction('plan_item_type_icon', fn (string $kind, ?string $key): ?string => $this->typeProvider->getIcon($kind, $key)), new TwigFunction('plan_currency', fn (): string => $this->currencyProvider->getCurrency()), new TwigFunction('plan_money', fn ($amount): string => number_format((float) $amount, 2)), new TwigFunction('plan_target_channel_label', fn (string $key): string => Target::CHANNELS[$key] ?? $key), new TwigFunction('plan_target_channel_label', fn (string $key): string => Target::CHANNELS[$key] ?? $key), ]; } /** * Plain text as HTML, with the URLs in it (https://… and www.…) turned into links that open in a * new tab. For the description fields of plans and tasks, which stay plain text: typing or pasting * a URL is enough, no editor needed. Everything is escaped here, so no HTML can be injected. */ public static function linkify(?string $text): string { if (null === $text || '' === $text) { return ''; } // One capture group: preg_split then alternates plain text (even) and URLs (odd). $parts = preg_split('~((?:https?://|(?"\']+)~i', $text, -1, PREG_SPLIT_DELIM_CAPTURE); $html = ''; foreach ($parts as $i => $part) { $html .= $i % 2 ? self::urlAnchor($part) : htmlspecialchars($part, ENT_QUOTES, 'UTF-8'); } return $html; } /** * One URL as a link. Sentence punctuation that follows the URL (".", ")", "!", …) stays outside * the link, and a bare "www." address gets the https:// prefix. */ private static function urlAnchor(string $url): string { $after = ''; while ('' !== $url && str_contains('.,;:!?', substr($url, -1))) { $after = substr($url, -1).$after; $url = substr($url, 0, -1); } // An unbalanced closing parenthesis belongs to the sentence, not the URL. if (str_ends_with($url, ')') && !str_contains($url, '(')) { $after = ')'.$after; $url = substr($url, 0, -1); } // Only a prefix is left ("www.", "https://"): not a link after all. if ('' === $url || 'www.' === $url || 'http://' === $url || 'https://' === $url) { return htmlspecialchars($url.$after, ENT_QUOTES, 'UTF-8'); } $href = preg_match('~^https?://~i', $url) ? $url : 'https://'.$url; return sprintf( '%s%s', htmlspecialchars($href, ENT_QUOTES, 'UTF-8'), htmlspecialchars($url, ENT_QUOTES, 'UTF-8'), htmlspecialchars($after, ENT_QUOTES, 'UTF-8') ); } }