MdRender.php 18 KB

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