MdRender.php 21 KB

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