1<?php 2class SkillForge_DokuMarkdownConverter { 3 public function convert($text) { 4 $text = $this->stripMetadataBlocks($text); 5 $text = preg_replace('/^======\s*(.*?)\s*======\s*$/m', '# $1', $text); 6 $text = preg_replace('/^=====\s*(.*?)\s*=====\s*$/m', '## $1', $text); 7 $text = preg_replace('/^====\s*(.*?)\s*====\s*$/m', '### $1', $text); 8 $text = preg_replace('/^===\s*(.*?)\s*===\s*$/m', '#### $1', $text); 9 $text = preg_replace('/^==\s*(.*?)\s*==\s*$/m', '##### $1', $text); 10 $text = preg_replace('/\*\*(.*?)\*\*/s', '**$1**', $text); 11 $text = preg_replace('/\/\/(.*?)\/\//s', '*$1*', $text); 12 $text = preg_replace('/__([^_]+)__/', '<u>$1</u>', $text); 13 $text = preg_replace_callback('/<code(?:\s+([^>]+))?>(.*?)<\/code>/is', function($m) { 14 $lang = isset($m[1]) ? trim($m[1]) : ''; 15 return "```" . $lang . "\n" . trim($m[2]) . "\n```"; 16 }, $text); 17 $text = preg_replace('/<file(?:\s+[^>]*)?>(.*?)<\/file>/is', "```\n$1\n```", $text); 18 $text = preg_replace_callback('/\[\[([^\]|]+)\|([^\]]+)\]\]/', function($m) { 19 return '[' . $m[2] . '](' . $this->pageIdToMd($m[1]) . ')'; 20 }, $text); 21 $text = preg_replace_callback('/\[\[([^\]]+)\]\]/', function($m) { 22 return '[' . $m[1] . '](' . $this->pageIdToMd($m[1]) . ')'; 23 }, $text); 24 $text = preg_replace_callback('/\{\{([^\}|]+)(?:\|([^\}]+))?\}\}/', function($m) { 25 $alt = isset($m[2]) ? trim($m[2]) : ''; 26 return ') . ')'; 27 }, $text); 28 return trim($text) . "\n"; 29 } 30 31 public function extractMetadata($text) { 32 if (preg_match('/<frontmatter>(.*?)<\/frontmatter>/is', $text, $m)) return trim($m[1]); 33 if (preg_match('/<skillmeta>(.*?)<\/skillmeta>/is', $text, $m)) return trim($m[1]); 34 if (preg_match('/^---\s*\R(.*?)\R---\s*\R/s', $text, $m)) return trim($m[1]); 35 return ''; 36 } 37 38 private function stripMetadataBlocks($text) { 39 $text = preg_replace('/<frontmatter>.*?<\/frontmatter>\s*/is', '', $text); 40 $text = preg_replace('/<skillmeta>.*?<\/skillmeta>\s*/is', '', $text); 41 $text = preg_replace('/^---\s*\R.*?\R---\s*\R/s', '', $text); 42 return $text; 43 } 44 45 private function pageIdToMd($id) { 46 if (preg_match('/^https?:\/\//i', $id)) return $id; 47 $id = preg_replace('/#[^#]*$/', '', $id); 48 $id = trim(str_replace(':', '/', $id), '/'); 49 return basename($id) . '.md'; 50 } 51} 52