MdRender.php 20 KB

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