*/ public static function sections(?string $markdown = null): array { if ($markdown === null) { $file = self::file(); $markdown = is_file($file) ? (string)file_get_contents($file) : ''; } if (trim($markdown) === '') { return []; } $sections = []; $current = null; foreach (preg_split('/\R/', $markdown) as $line) { if (preg_match('/^##\s+(.+?)\s*$/', $line, $m)) { if ($current !== null) { $sections[] = self::finish($current); } $heading = trim($m[1]); preg_match('/(\d+\.\d+\.\d+)/', $heading, $v); $current = [ 'version' => $v[1] ?? '', 'heading' => $heading, 'lines' => [], ]; continue; } if ($current !== null) { $current['lines'][] = $line; } } if ($current !== null) { $sections[] = self::finish($current); } return $sections; } /** * @param array{version:string, heading:string, lines:array} $section * @return array{version:string, heading:string, text:string} */ private static function finish(array $section): array { return [ 'version' => $section['version'], 'heading' => $section['heading'], 'text' => trim(implode("\n", $section['lines'])), ]; } /** * Markdown -> HTML fuer Aenderungsprotokolle: Listen, Absaetze, fetter und * kursiver Text, Code und Verweise. Verweise nur mit http(s), alles andere * wird zu reinem Text - ein "javascript:"-Link aus einer fremden Quelle * hat in der Oberflaeche nichts verloren. */ public static function toHtml(string $markdown): string { $html = ''; $listOpen = false; $paragraph = []; foreach (preg_split('/\R/', $markdown) as $line) { $trimmed = trim($line); if ($trimmed === '') { $html .= self::paragraph($paragraph); $paragraph = []; if ($listOpen) { $html .= ''; $listOpen = false; } continue; } if (preg_match('/^[-*+]\s+(.*)$/', $trimmed, $m)) { $html .= self::paragraph($paragraph); $paragraph = []; if (!$listOpen) { $html .= ''; $listOpen = false; } $html .= '

' . self::inline($m[1]) . '

'; continue; } $paragraph[] = $trimmed; } $html .= self::paragraph($paragraph); if ($listOpen) { $html .= ''; } return $html; } /** * @param array $lines */ private static function paragraph(array $lines): string { return $lines === [] ? '' : '

' . self::inline(implode(' ', $lines)) . '

'; } /** Fetter/kursiver Text, Code und sichere Verweise. */ private static function inline(string $text): string { $escaped = htmlspecialchars($text, ENT_QUOTES, 'UTF-8'); $escaped = preg_replace_callback( '/\[([^\]]+)\]\(([^)\s]+)\)/', function ($m) { $label = $m[1]; $url = html_entity_decode($m[2], ENT_QUOTES, 'UTF-8'); if (!preg_match('#^https?://#i', $url)) { return $label; // unsichere Ziele verlieren den Verweis } return '' . $label . ''; }, $escaped ); $escaped = preg_replace('/`([^`]+)`/', '$1', $escaped); $escaped = preg_replace('/\*\*([^*]+)\*\*/', '$1', $escaped); $escaped = preg_replace('/(?$1', $escaped); return (string)$escaped; } }