MdRender.php 21 KB

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