MdRender.php 21 KB

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