MdRender.php 20 KB

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