MdRender.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. <?php
  2. namespace App\Http\Api;
  3. use Illuminate\Support\Str;
  4. use mustache\mustache;
  5. use App\Models\DhammaTerm;
  6. use App\Models\PaliText;
  7. use App\Models\Channel;
  8. use App\Http\Controllers\CorpusController;
  9. use Illuminate\Support\Facades\Cache;
  10. use Illuminate\Support\Facades\Log;
  11. use App\Tools\Markdown;
  12. define("STACK_DEEP",8);
  13. class MdRender{
  14. /**
  15. * 按照{{}}把字符串切分成三个部分。模版之前的,模版,和模版之后的
  16. */
  17. public static function tplSplit($tpl){
  18. $before = strpos($tpl,'{{');
  19. if($before === FALSE){
  20. //未找到
  21. return ['data'=>[$tpl,'',''],'error'=>0];
  22. }else{
  23. $pointer = $before;
  24. $stack = array();
  25. $stack[] = $pointer;
  26. $after = substr($tpl,$pointer+2) ;
  27. while (!empty($after) && count($stack)>0 && count($stack)<STACK_DEEP) {
  28. $nextBegin = strpos($after,"{{");
  29. $nextEnd = strpos($after,"}}");
  30. if($nextBegin !== FALSE){
  31. if($nextBegin < $nextEnd){
  32. //有嵌套找到最后一个}}
  33. $pointer = $pointer + 2 + $nextBegin;
  34. $stack[] = $pointer;
  35. $after = substr($tpl,$pointer+2);
  36. }else if($nextEnd !== FALSE){
  37. //无嵌套有结束
  38. $pointer = $pointer + 2 + $nextEnd;
  39. array_pop($stack);
  40. $after = substr($tpl,$pointer+2);
  41. }else{
  42. //无结束符 没找到
  43. break;
  44. }
  45. }else if($nextEnd !== FALSE){
  46. $pointer = $pointer + 2 + $nextEnd;
  47. array_pop($stack);
  48. $after = substr($tpl,$pointer+2);
  49. }else{
  50. //没找到
  51. break;
  52. }
  53. }
  54. if(count($stack)>0){
  55. if(count($stack) === STACK_DEEP){
  56. return ['data'=>[$tpl,'',''],'error'=>2];
  57. }else{
  58. //未关闭
  59. return ['data'=>[$tpl,'',''],'error'=>1];
  60. }
  61. }else{
  62. return ['data'=>
  63. [
  64. substr($tpl,0,$before),
  65. substr($tpl,$before,$pointer-$before+2),
  66. substr($tpl,$pointer+2)
  67. ],
  68. 'error'=>0
  69. ];
  70. }
  71. }
  72. }
  73. public static function wiki2xml(string $wiki,$channelId=[],$mode='read'):string{
  74. /**
  75. * 替换{{}} 到xml之前 要先把换行符号去掉
  76. */
  77. //$wiki = str_replace("\n","",$wiki);
  78. /**
  79. * 把模版转换为xml
  80. */
  81. $remain = $wiki;
  82. $buffer = array();
  83. do {
  84. $arrWiki = MdRender::tplSplit($remain);
  85. $buffer[] = $arrWiki['data'][0];
  86. $tpl = $arrWiki['data'][1];
  87. if(!empty($tpl)){
  88. /**
  89. * 处理模版 提取参数
  90. */
  91. $tpl = str_replace("|\n","|",$tpl);
  92. $pattern = "/\{\{(.+?)\|/";
  93. $replacement = '<MdTpl class="tpl" name="$1"><param>';
  94. $tpl = preg_replace($pattern,$replacement,$tpl);
  95. $tpl = str_replace("}}","</param></MdTpl>",$tpl);
  96. $tpl = str_replace("|","</param><param>",$tpl);
  97. /**
  98. * 替换变量名
  99. */
  100. $pattern = "/<param>([a-z]+?)=/";
  101. $replacement = '<param name="$1">';
  102. $tpl = preg_replace($pattern,$replacement,$tpl);
  103. //tpl to react
  104. $tpl = str_replace('<param','<span class="param"',$tpl);
  105. $tpl = str_replace('</param>','</span>',$tpl);
  106. $tpl = MdRender::xml2tpl($tpl,$channelId,$mode);
  107. $buffer[] = $tpl;
  108. }
  109. $remain = $arrWiki['data'][2];
  110. } while (!empty($remain));
  111. $html = implode('' , $buffer);
  112. return $html;
  113. }
  114. public static function xmlQueryId(string $xml, string $id):string{
  115. try{
  116. $dom = simplexml_load_string($xml);
  117. }catch(\Exception $e){
  118. Log::error($e);
  119. return "<div></div>";
  120. }
  121. $tpl_list = $dom->xpath('//MdTpl');
  122. foreach ($tpl_list as $key => $tpl) {
  123. foreach ($tpl->children() as $param) {
  124. # 处理每个参数
  125. if($param->getName() === "param"){
  126. foreach($param->attributes() as $pa => $pa_value){
  127. $pValue = $pa_value->__toString();
  128. if($pa === "name" && $pValue === "id"){
  129. if($param->__toString() === $id){
  130. return $tpl->asXML();
  131. }
  132. }
  133. }
  134. }
  135. }
  136. }
  137. return "<div></div>";
  138. }
  139. public static function take_sentence(string $xml):array{
  140. $output = [];
  141. try{
  142. $dom = simplexml_load_string($xml);
  143. }catch(\Exception $e){
  144. Log::error($e);
  145. return $output;
  146. }
  147. $tpl_list = $dom->xpath('//MdTpl');
  148. foreach ($tpl_list as $key => $tpl) {
  149. foreach($tpl->attributes() as $a => $a_value){
  150. if($a==="name"){
  151. if($a_value->__toString() ==="sent"){
  152. foreach ($tpl->children() as $param) {
  153. # 处理每个参数
  154. if($param->getName() === "param"){
  155. $sent = $param->__toString();
  156. if(!empty($sent)){
  157. $output[] = $sent;
  158. break;
  159. }
  160. }
  161. }
  162. }
  163. }
  164. }
  165. }
  166. return $output;
  167. }
  168. public static function xml2tpl(string $xml, $channelId=[],$mode='read'):string{
  169. /**
  170. * 解析xml
  171. * 获取模版参数
  172. * 生成react 组件参数
  173. */
  174. try{
  175. //$dom = simplexml_load_string($xml);
  176. $doc = new \DOMDocument();
  177. $xml = str_replace('MdTpl','dfn',$xml);
  178. $xml = mb_convert_encoding($xml, 'HTML-ENTITIES', "UTF-8");
  179. $ok = $doc->loadHTML($xml,LIBXML_NOERROR | LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
  180. }catch(\Exception $e){
  181. Log::error($e);
  182. Log::error($xml);
  183. return "<span>xml解析错误{$e}</span>";
  184. }
  185. if(!$ok){
  186. return "<span>xml解析错误</span>";
  187. }
  188. /*
  189. if(!$dom){
  190. Log::error($xml);
  191. return "<span>xml解析错误</span>";
  192. }
  193. */
  194. //$tpl_list = $dom->xpath('//MdTpl');
  195. $tpl_list = $doc->getElementsByTagName('dfn');
  196. foreach ($tpl_list as $key => $tpl) {
  197. /**
  198. * 遍历 MdTpl 处理参数
  199. */
  200. $props = [];
  201. $tpl_name = '';
  202. foreach($tpl->attributes as $a => $a_value){
  203. if($a_value->nodeName==="name"){
  204. $tpl_name = $a_value->nodeValue;
  205. break;
  206. }
  207. }
  208. $param_id = 0;
  209. $child = $tpl->firstChild;
  210. while ($child) {
  211. # 处理每个参数
  212. if($child->nodeName === "span"){
  213. $param_id++;
  214. $paramName = "";
  215. foreach($child->attributes as $pa => $pa_value){
  216. if($pa_value->nodeName === "name"){
  217. $nodeText = $pa_value->nodeValue;
  218. $props["{$nodeText}"] = $child->nodeValue;
  219. $paramName = $pa_value;
  220. }
  221. }
  222. if(empty($paramName)){
  223. foreach ($child->childNodes as $param_child) {
  224. # code...
  225. if($param_child->nodeType ===3){
  226. $props["{$param_id}"] = $param_child->nodeValue;
  227. }
  228. }
  229. }
  230. }
  231. $child = $child->nextSibling;
  232. }
  233. /**
  234. * 生成模版参数
  235. *
  236. */
  237. //TODO 判断$channelId里面的是否都是uuid
  238. $channelInfo = Channel::whereIn('uid',$channelId)->get();
  239. $tplRender = new TemplateRender($props,$channelInfo,$mode);
  240. $tplProps = $tplRender->render($tpl_name);
  241. if($tplProps){
  242. $props = $doc->createAttribute("props");
  243. $props->nodeValue = $tplProps['props'];
  244. $tpl->appendChild($props);
  245. $attTpl = $doc->createAttribute("tpl");
  246. $attTpl->nodeValue = $tplProps['tpl'];
  247. $tpl->appendChild($attTpl);
  248. $htmlElement = $doc->createElement($tplProps['tag']);
  249. $htmlElement->nodeValue=$tplProps['html'];
  250. $tpl->appendChild($htmlElement);
  251. }
  252. }
  253. $html = $doc->saveHTML();
  254. $html = str_replace(['<dfn','</dfn>'],['<MdTpl','</MdTpl>'],$html);
  255. return trim($html);
  256. }
  257. public static function render2($markdown,$channelId=[],$queryId=null,$mode='read',$channelType,$contentType="markdown"){
  258. if(empty($markdown)){
  259. return "<span></span>";
  260. }
  261. $wiki = MdRender::markdown2wiki($markdown,$channelType,$contentType);
  262. $html = MdRender::wiki2xml($wiki,$channelId,$mode);
  263. if(!is_null($queryId)){
  264. $html = MdRender::xmlQueryId($html, $queryId);
  265. }
  266. $html = MdRender::markdownToHtml($html);
  267. //$tpl = MdRender::xml2tpl($html,$channelId,$mode);
  268. //生成可展开组件
  269. $html = str_replace("<div/>","<div></div>",$html);
  270. $pattern = '/<li><div>(.+?)<\/div><\/li>/';
  271. $replacement = '<li><MdTpl name="toggle" tpl="toggle" props=""><div>$1</div></MdTpl></li>';
  272. $html = preg_replace($pattern,$replacement,$html);
  273. return $html;
  274. }
  275. public static function markdown2wiki(string $markdown,$channelType=null,$contentType=null): string{
  276. //$markdown = mb_convert_encoding($markdown,'UTF-8','UTF-8');
  277. $markdown = iconv('UTF-8','UTF-8//IGNORE',$markdown);
  278. /**
  279. * nissaya
  280. * aaa=bbb\n
  281. * {{nissaya|aaa|bbb}}
  282. */
  283. if($channelType==='nissaya'){
  284. if($contentType === "json"){
  285. $json = json_decode($markdown);
  286. $nissayaWord = [];
  287. foreach ($json as $word) {
  288. if(count($word->sn) === 1){
  289. //只输出第一层级
  290. $str = "{{nissaya|";
  291. if(isset($word->word->value)){
  292. $str .= $word->word->value;
  293. }
  294. $str .= "|";
  295. if(isset($word->meaning->value)){
  296. $str .= $word->meaning->value;
  297. }
  298. $str .= "}}";
  299. $nissayaWord[] = $str;
  300. }
  301. }
  302. $markdown = implode('',$nissayaWord);
  303. }else if($contentType === "markdown"){
  304. $lines = explode("\n",$markdown);
  305. $newLines = array();
  306. foreach ($lines as $line) {
  307. if(strstr($line,'=') === FALSE){
  308. $newLines[] = $line;
  309. }else{
  310. $nissaya = explode('=',$line);
  311. $meaning = array_slice($nissaya,1);
  312. $meaning = implode('=',$meaning);
  313. $newLines[] = "{{nissaya|{$nissaya[0]}|{$meaning}}}";
  314. }
  315. }
  316. $markdown = implode("\n",$newLines);
  317. }
  318. }
  319. //$markdown = preg_replace("/\n\n/","<div></div>",$markdown);
  320. /**
  321. * 处理 mermaid
  322. */
  323. if(strpos($markdown,"```mermaid") !== false){
  324. $lines = explode("\n",$markdown);
  325. $newLines = array();
  326. $mermaidBegin = false;
  327. $mermaidString = array();
  328. foreach ($lines as $line) {
  329. if($line === "```mermaid"){
  330. $mermaidBegin = true;
  331. $mermaidString = [];
  332. continue;
  333. }
  334. if($mermaidBegin){
  335. if($line === "```"){
  336. $newLines[] = "{{mermaid|".base64_encode(\json_encode($mermaidString))."}}";
  337. $mermaidBegin = false;
  338. }else{
  339. $mermaidString[] = $line;
  340. }
  341. }else{
  342. $newLines[] = $line;
  343. }
  344. }
  345. $markdown = implode("\n",$newLines);
  346. }
  347. /**
  348. * 替换换行符
  349. * react 无法处理 <br> 替换为<div></div>代替换行符作用
  350. */
  351. //$markdown = str_replace('<br>','<div></div>',$markdown);
  352. /**
  353. * markdown -> html
  354. */
  355. /*
  356. $html = MdRender::fixHtml($html);
  357. */
  358. #替换术语
  359. $pattern = "/\[\[(.+?)\]\]/";
  360. $replacement = '{{term|$1}}';
  361. $markdown = preg_replace($pattern,$replacement,$markdown);
  362. #替换句子模版
  363. $pattern = "/\{\{([0-9].+?)\}\}/";
  364. $replacement = '{{sent|$1}}';
  365. $markdown = preg_replace($pattern,$replacement,$markdown);
  366. /**
  367. * 替换多行注释
  368. * ```
  369. * bla
  370. * bla
  371. * ```
  372. * {{note|
  373. * bla
  374. * bla
  375. * }}
  376. */
  377. if(strpos($markdown,"```\n") !== false){
  378. $lines = explode("\n",$markdown);
  379. $newLines = array();
  380. $noteBegin = false;
  381. $noteString = array();
  382. foreach ($lines as $line) {
  383. if($noteBegin){
  384. if($line === "```"){
  385. $newLines[] = "}}";
  386. $noteBegin = false;
  387. }else{
  388. $newLines[] = $line;
  389. }
  390. }else{
  391. if($line === "```"){
  392. $noteBegin = true;
  393. $newLines[] = "{{note|";
  394. continue;
  395. }else{
  396. $newLines[] = $line;
  397. }
  398. }
  399. }
  400. if($noteBegin){
  401. $newLines[] = "}}";
  402. }
  403. $markdown = implode("\n",$newLines);
  404. }
  405. /**
  406. * 替换单行注释
  407. * `bla bla`
  408. * {{note|bla}}
  409. */
  410. $pattern = "/`(.+?)`/";
  411. $replacement = '{{note|$1}}';
  412. $markdown = preg_replace($pattern,$replacement,$markdown);
  413. /*
  414. #替换多行注释
  415. #<pre><code>bla</code></pre>
  416. #{{note|bla}}
  417. $pattern = '/<pre><code>([\w\W]+?)<\/code><\/pre>/';
  418. $replacement = '{{note|$1}}';
  419. $html = preg_replace($pattern,$replacement,$html);
  420. #替换单行注释
  421. #<code>bla</code>
  422. #{{note|bla}}
  423. $pattern = '/<code>(.+?)<\/code>/';
  424. $replacement = '{{note|$1}}';
  425. $html = preg_replace($pattern,$replacement,$html);
  426. */
  427. return $markdown;
  428. }
  429. public static function markdownToHtml($markdown){
  430. $markdown = str_replace('MdTpl','mdtpl',$markdown);
  431. $markdown = str_replace(['<param','</param>'],['<span','</span>'],$markdown);
  432. $html = Markdown::render($markdown);
  433. $html = MdRender::fixHtml($html);
  434. $html = str_replace('<hr>','<hr />',$html);
  435. //给H1-6 添加uuid
  436. for ($i=1; $i<7 ; $i++) {
  437. if(strpos($html,"<h{$i}>")===false){
  438. continue;
  439. }
  440. $output = array();
  441. $input = $html;
  442. $hPos = strpos($input,"<h{$i}>");
  443. while ($hPos !== false) {
  444. $output[] = substr($input,0,$hPos);
  445. $output[] = "<h{$i} id='".Str::uuid()."'>";
  446. $input = substr($input,$hPos+4);
  447. $hPos = strpos($input,"<h{$i}>");
  448. }
  449. $output[] = $input;
  450. $html = implode('',$output);
  451. }
  452. $html = str_replace('mdtpl','MdTpl',$html);
  453. return $html;
  454. }
  455. /**
  456. * string[] $channelId
  457. */
  458. public static function render($markdown,$channelId,$queryId=null,$mode='read',$channelType='translation',$contentType="markdown"){
  459. return MdRender::render2($markdown,$channelId,$queryId,$mode,$channelType,$contentType);
  460. }
  461. public static function fixHtml($html) {
  462. $doc = new \DOMDocument();
  463. libxml_use_internal_errors(true);
  464. $html = mb_convert_encoding($html, 'HTML-ENTITIES', "UTF-8");
  465. $doc->loadHTML('<span>'.$html.'</span>',LIBXML_NOERROR | LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
  466. $fixed = $doc->saveHTML();
  467. $fixed = mb_convert_encoding($fixed, "UTF-8", 'HTML-ENTITIES');
  468. return $fixed;
  469. }
  470. }