MdRender.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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 if($format==='text'){
  260. if(isset($tplProps['text'])){
  261. return $tplProps['text'];
  262. }else{
  263. return '';
  264. }
  265. }else{
  266. return '';
  267. }
  268. }
  269. public static function render2($markdown,$channelId=[],$queryId=null,$mode='read',$channelType,$contentType="markdown",$format='react'){
  270. if(empty($markdown)){
  271. return "<span></span>";
  272. }
  273. $wiki = MdRender::markdown2wiki($markdown,$channelType,$contentType);
  274. $html = MdRender::wiki2xml($wiki,$channelId,$mode,$format);
  275. if(!is_null($queryId)){
  276. $html = MdRender::xmlQueryId($html, $queryId);
  277. }
  278. $html = MdRender::markdownToHtml($html);
  279. //$tpl = MdRender::xml2tpl($html,$channelId,$mode);
  280. if($format==='react'){
  281. //生成可展开组件
  282. $html = str_replace("<div/>","<div></div>",$html);
  283. $pattern = '/<li><div>(.+?)<\/div><\/li>/';
  284. $replacement = '<li><MdTpl name="toggle" tpl="toggle" props=""><div>$1</div></MdTpl></li>';
  285. $html = preg_replace($pattern,$replacement,$html);
  286. }
  287. if($format==='text'){
  288. $html = strip_tags($html);
  289. }
  290. return $html;
  291. }
  292. public static function markdown2wiki(string $markdown,$channelType=null,$contentType=null): string{
  293. //$markdown = mb_convert_encoding($markdown,'UTF-8','UTF-8');
  294. $markdown = iconv('UTF-8','UTF-8//IGNORE',$markdown);
  295. /**
  296. * nissaya
  297. * aaa=bbb\n
  298. * {{nissaya|aaa|bbb}}
  299. */
  300. if($channelType==='nissaya'){
  301. if($contentType === "json"){
  302. $json = json_decode($markdown);
  303. $nissayaWord = [];
  304. foreach ($json as $word) {
  305. if(count($word->sn) === 1){
  306. //只输出第一层级
  307. $str = "{{nissaya|";
  308. if(isset($word->word->value)){
  309. $str .= $word->word->value;
  310. }
  311. $str .= "|";
  312. if(isset($word->meaning->value)){
  313. $str .= $word->meaning->value;
  314. }
  315. $str .= "}}";
  316. $nissayaWord[] = $str;
  317. }
  318. }
  319. $markdown = implode('',$nissayaWord);
  320. }else if($contentType === "markdown"){
  321. $lines = explode("\n",$markdown);
  322. $newLines = array();
  323. foreach ($lines as $line) {
  324. if(strstr($line,'=') === FALSE){
  325. $newLines[] = $line;
  326. }else{
  327. $nissaya = explode('=',$line);
  328. $meaning = array_slice($nissaya,1);
  329. $meaning = implode('=',$meaning);
  330. $newLines[] = "{{nissaya|{$nissaya[0]}|{$meaning}}}";
  331. }
  332. }
  333. $markdown = implode("\n",$newLines);
  334. }
  335. }
  336. //$markdown = preg_replace("/\n\n/","<div></div>",$markdown);
  337. /**
  338. * 处理 mermaid
  339. */
  340. if(strpos($markdown,"```mermaid") !== false){
  341. $lines = explode("\n",$markdown);
  342. $newLines = array();
  343. $mermaidBegin = false;
  344. $mermaidString = array();
  345. foreach ($lines as $line) {
  346. if($line === "```mermaid"){
  347. $mermaidBegin = true;
  348. $mermaidString = [];
  349. continue;
  350. }
  351. if($mermaidBegin){
  352. if($line === "```"){
  353. $newLines[] = "{{mermaid|".base64_encode(\json_encode($mermaidString))."}}";
  354. $mermaidBegin = false;
  355. }else{
  356. $mermaidString[] = $line;
  357. }
  358. }else{
  359. $newLines[] = $line;
  360. }
  361. }
  362. $markdown = implode("\n",$newLines);
  363. }
  364. /**
  365. * 替换换行符
  366. * react 无法处理 <br> 替换为<div></div>代替换行符作用
  367. */
  368. //$markdown = str_replace('<br>','<div></div>',$markdown);
  369. /**
  370. * markdown -> html
  371. */
  372. /*
  373. $html = MdRender::fixHtml($html);
  374. */
  375. #替换术语
  376. $pattern = "/\[\[(.+?)\]\]/";
  377. $replacement = '{{term|$1}}';
  378. $markdown = preg_replace($pattern,$replacement,$markdown);
  379. #替换句子模版
  380. $pattern = "/\{\{([0-9].+?)\}\}/";
  381. $replacement = '{{sent|$1}}';
  382. $markdown = preg_replace($pattern,$replacement,$markdown);
  383. /**
  384. * 替换多行注释
  385. * ```
  386. * bla
  387. * bla
  388. * ```
  389. * {{note|
  390. * bla
  391. * bla
  392. * }}
  393. */
  394. if(strpos($markdown,"```\n") !== false){
  395. $lines = explode("\n",$markdown);
  396. $newLines = array();
  397. $noteBegin = false;
  398. $noteString = array();
  399. foreach ($lines as $line) {
  400. if($noteBegin){
  401. if($line === "```"){
  402. $newLines[] = "}}";
  403. $noteBegin = false;
  404. }else{
  405. $newLines[] = $line;
  406. }
  407. }else{
  408. if($line === "```"){
  409. $noteBegin = true;
  410. $newLines[] = "{{note|";
  411. continue;
  412. }else{
  413. $newLines[] = $line;
  414. }
  415. }
  416. }
  417. if($noteBegin){
  418. $newLines[] = "}}";
  419. }
  420. $markdown = implode("\n",$newLines);
  421. }
  422. /**
  423. * 替换单行注释
  424. * `bla bla`
  425. * {{note|bla}}
  426. */
  427. $pattern = "/`(.+?)`/";
  428. $replacement = '{{note|$1}}';
  429. $markdown = preg_replace($pattern,$replacement,$markdown);
  430. /*
  431. #替换多行注释
  432. #<pre><code>bla</code></pre>
  433. #{{note|bla}}
  434. $pattern = '/<pre><code>([\w\W]+?)<\/code><\/pre>/';
  435. $replacement = '{{note|$1}}';
  436. $html = preg_replace($pattern,$replacement,$html);
  437. #替换单行注释
  438. #<code>bla</code>
  439. #{{note|bla}}
  440. $pattern = '/<code>(.+?)<\/code>/';
  441. $replacement = '{{note|$1}}';
  442. $html = preg_replace($pattern,$replacement,$html);
  443. */
  444. return $markdown;
  445. }
  446. public static function markdownToHtml($markdown){
  447. $markdown = str_replace('MdTpl','mdtpl',$markdown);
  448. $markdown = str_replace(['<param','</param>'],['<span','</span>'],$markdown);
  449. $html = Markdown::render($markdown);
  450. $html = MdRender::fixHtml($html);
  451. $html = str_replace('<hr>','<hr />',$html);
  452. //给H1-6 添加uuid
  453. for ($i=1; $i<7 ; $i++) {
  454. if(strpos($html,"<h{$i}>")===false){
  455. continue;
  456. }
  457. $output = array();
  458. $input = $html;
  459. $hPos = strpos($input,"<h{$i}>");
  460. while ($hPos !== false) {
  461. $output[] = substr($input,0,$hPos);
  462. $output[] = "<h{$i} id='".Str::uuid()."'>";
  463. $input = substr($input,$hPos+4);
  464. $hPos = strpos($input,"<h{$i}>");
  465. }
  466. $output[] = $input;
  467. $html = implode('',$output);
  468. }
  469. $html = str_replace('mdtpl','MdTpl',$html);
  470. return $html;
  471. }
  472. public static function init(){
  473. $GLOBALS["MdRenderStack"] = 0;
  474. }
  475. /**
  476. * string[] $channelId
  477. */
  478. public static function render($markdown,$channelId,$queryId=null,$mode='read',$channelType='translation',$contentType="markdown",$format='react'){
  479. if(isset($GLOBALS["MdRenderStack"]) && is_numeric($GLOBALS["MdRenderStack"])){
  480. $GLOBALS["MdRenderStack"]++;
  481. }else{
  482. $GLOBALS["MdRenderStack"] = 1;
  483. }
  484. if($GLOBALS["MdRenderStack"]<3){
  485. $output = MdRender::render2($markdown,$channelId,$queryId,$mode,$channelType,$contentType,$format);
  486. }else{
  487. $output = $markdown;
  488. }
  489. $GLOBALS["MdRenderStack"]--;
  490. return $output;
  491. }
  492. public static function fixHtml($html) {
  493. $doc = new \DOMDocument();
  494. libxml_use_internal_errors(true);
  495. $html = mb_convert_encoding($html, 'HTML-ENTITIES', "UTF-8");
  496. $doc->loadHTML('<span>'.$html.'</span>',LIBXML_NOERROR | LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
  497. $fixed = $doc->saveHTML();
  498. $fixed = mb_convert_encoding($fixed, "UTF-8", 'HTML-ENTITIES');
  499. return $fixed;
  500. }
  501. }