MdRender.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  1. <?php
  2. namespace App\Http\Api;
  3. use App\Models\Channel;
  4. use App\Tools\Markdown;
  5. use Illuminate\Support\Facades\Log;
  6. use Illuminate\Support\Str;
  7. // use App\Services\TemplateRender;
  8. define('STACK_DEEP', 8);
  9. class MdRender
  10. {
  11. /**
  12. * 文字渲染模式
  13. * read 阅读模式
  14. * edit 编辑模式
  15. */
  16. protected $options = [
  17. 'mode' => 'read',
  18. 'channelType' => 'translation',
  19. 'contentType' => 'markdown',
  20. 'format' => 'react',
  21. 'debug' => [],
  22. 'studioId' => null,
  23. 'lang' => 'zh-Hans',
  24. 'footnote' => false,
  25. 'paragraph' => false,
  26. ];
  27. public function __construct($options = [])
  28. {
  29. foreach ($options as $key => $value) {
  30. $this->options[$key] = $value;
  31. }
  32. }
  33. /**
  34. * 将句子模版组成的段落复制一份,为了实现巴汉逐段对读
  35. */
  36. private function preprocessingForParagraph($input)
  37. {
  38. if (! $this->options['paragraph']) {
  39. return $input;
  40. }
  41. $paragraphs = explode("\n\n", $input);
  42. $output = [];
  43. foreach ($paragraphs as $key => $paragraph) {
  44. // 判断是否是纯粹的句子模版
  45. $pattern = "/\{\{sent\|id=([0-9].+?)\}\}/";
  46. $replacement = '';
  47. $space = preg_replace($pattern, $replacement, $paragraph);
  48. $space = str_replace('>', '', $space);
  49. if (empty(trim($space))) {
  50. $output[] = str_replace('}}', '|text=origin}}', $paragraph);
  51. $output[] = str_replace('}}', '|text=translation}}', $paragraph);
  52. } else {
  53. $output[] = $paragraph;
  54. }
  55. }
  56. return implode("\n\n", $output);
  57. }
  58. /**
  59. * 按照{{}}把字符串切分成三个部分。模版之前的,模版,和模版之后的
  60. */
  61. private function tplSplit($tpl)
  62. {
  63. $before = strpos($tpl, '{{');
  64. if ($before === false) {
  65. // 未找到
  66. return ['data' => [$tpl, '', ''], 'error' => 0];
  67. } else {
  68. $pointer = $before;
  69. $stack = [];
  70. $stack[] = $pointer;
  71. $after = substr($tpl, $pointer + 2);
  72. while (! empty($after) && count($stack) > 0 && count($stack) < STACK_DEEP) {
  73. $nextBegin = strpos($after, '{{');
  74. $nextEnd = strpos($after, '}}');
  75. if ($nextBegin !== false) {
  76. if ($nextBegin < $nextEnd) {
  77. // 有嵌套找到最后一个}}
  78. $pointer = $pointer + 2 + $nextBegin;
  79. $stack[] = $pointer;
  80. $after = substr($tpl, $pointer + 2);
  81. } elseif ($nextEnd !== false) {
  82. // 无嵌套有结束
  83. $pointer = $pointer + 2 + $nextEnd;
  84. array_pop($stack);
  85. $after = substr($tpl, $pointer + 2);
  86. } else {
  87. // 无结束符 没找到
  88. break;
  89. }
  90. } elseif ($nextEnd !== false) {
  91. $pointer = $pointer + 2 + $nextEnd;
  92. array_pop($stack);
  93. $after = substr($tpl, $pointer + 2);
  94. } else {
  95. // 没找到
  96. break;
  97. }
  98. }
  99. if (count($stack) > 0) {
  100. if (count($stack) === STACK_DEEP) {
  101. return ['data' => [$tpl, '', ''], 'error' => 2];
  102. } else {
  103. // 未关闭
  104. return ['data' => [$tpl, '', ''], 'error' => 1];
  105. }
  106. } else {
  107. return [
  108. 'data' => [
  109. substr($tpl, 0, $before),
  110. substr($tpl, $before, $pointer - $before + 2),
  111. substr($tpl, $pointer + 2),
  112. ],
  113. 'error' => 0,
  114. ];
  115. }
  116. }
  117. }
  118. private function wiki2xml(string $wiki, $channelId = []): string
  119. {
  120. /**
  121. * 渲染markdown里面的模版
  122. */
  123. $remain = $wiki;
  124. $buffer = [];
  125. do {
  126. $arrWiki = $this->tplSplit($remain);
  127. $buffer[] = $arrWiki['data'][0];
  128. $tpl = $arrWiki['data'][1];
  129. if (! empty($tpl)) {
  130. /**
  131. * 处理模版 提取参数
  132. */
  133. $tpl = str_replace("|\n", '|', $tpl);
  134. $pattern = "/\{\{(.+?)\|/";
  135. $replacement = '<MdTpl class="tpl" name="$1"><param>';
  136. $tpl = preg_replace($pattern, $replacement, $tpl);
  137. $tpl = str_replace('}}', '</param></MdTpl>', $tpl);
  138. $tpl = str_replace('|', '</param><param>', $tpl);
  139. /**
  140. * 替换变量名
  141. */
  142. $pattern = '/<param>([a-z]+?)=/';
  143. $replacement = '<param name="$1">';
  144. $tpl = preg_replace($pattern, $replacement, $tpl);
  145. // tpl to react
  146. $tpl = str_replace('<param', '<span class="param"', $tpl);
  147. $tpl = str_replace('</param>', '</span>', $tpl);
  148. $tpl = $this->xml2tpl($tpl, $channelId);
  149. $buffer[] = $tpl;
  150. }
  151. $remain = $arrWiki['data'][2];
  152. } while (! empty($remain));
  153. $html = implode('', $buffer);
  154. return $html;
  155. }
  156. private function xmlQueryId(string $xml, string $id): string
  157. {
  158. try {
  159. $dom = simplexml_load_string($xml);
  160. } catch (\Exception $e) {
  161. Log::error($e);
  162. return '<div></div>';
  163. }
  164. $tpl_list = $dom->xpath('//MdTpl');
  165. foreach ($tpl_list as $key => $tpl) {
  166. foreach ($tpl->children() as $param) {
  167. // 处理每个参数
  168. if ($param->getName() === 'param') {
  169. foreach ($param->attributes() as $pa => $pa_value) {
  170. $pValue = $pa_value->__toString();
  171. if ($pa === 'name' && $pValue === 'id') {
  172. if ($param->__toString() === $id) {
  173. return $tpl->asXML();
  174. }
  175. }
  176. }
  177. }
  178. }
  179. }
  180. return '<div></div>';
  181. }
  182. public static function take_sentence(string $xml): array
  183. {
  184. $output = [];
  185. try {
  186. $dom = simplexml_load_string($xml);
  187. } catch (\Exception $e) {
  188. Log::error($e);
  189. return $output;
  190. }
  191. $tpl_list = $dom->xpath('//MdTpl');
  192. foreach ($tpl_list as $key => $tpl) {
  193. foreach ($tpl->attributes() as $a => $a_value) {
  194. if ($a === 'name') {
  195. if ($a_value->__toString() === 'sent') {
  196. foreach ($tpl->children() as $param) {
  197. // 处理每个参数
  198. if ($param->getName() === 'param') {
  199. $sent = $param->__toString();
  200. if (! empty($sent)) {
  201. $output[] = $sent;
  202. break;
  203. }
  204. }
  205. }
  206. }
  207. }
  208. }
  209. }
  210. return $output;
  211. }
  212. private function xml2tpl(string $xml, $channelId = []): string
  213. {
  214. /**
  215. * 解析xml
  216. * 获取模版参数
  217. * 生成react 组件参数
  218. */
  219. try {
  220. // $dom = simplexml_load_string($xml);
  221. $doc = new \DOMDocument;
  222. $xml = str_replace('MdTpl', 'dfn', $xml);
  223. $xml = mb_convert_encoding($xml, 'HTML-ENTITIES', 'UTF-8');
  224. $ok = $doc->loadHTML($xml, LIBXML_NOERROR | LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
  225. } catch (\Exception $e) {
  226. Log::error($e);
  227. Log::error($xml);
  228. return "<span>xml解析错误{$e}</span>";
  229. }
  230. if (! $ok) {
  231. return '<span>xml解析错误</span>';
  232. }
  233. /*
  234. if(!$dom){
  235. Log::error($xml);
  236. return "<span>xml解析错误</span>";
  237. }
  238. */
  239. $tpl_list = $doc->getElementsByTagName('dfn');
  240. foreach ($tpl_list as $key => $tpl) {
  241. /**
  242. * 遍历 MdTpl 处理参数
  243. */
  244. $props = [];
  245. $tpl_name = '';
  246. foreach ($tpl->attributes as $a => $a_value) {
  247. if ($a_value->nodeName === 'name') {
  248. $tpl_name = $a_value->nodeValue;
  249. break;
  250. }
  251. }
  252. $param_id = 0;
  253. $child = $tpl->firstChild;
  254. while ($child) {
  255. // 处理每个参数
  256. if ($child->nodeName === 'span') {
  257. $param_id++;
  258. $paramName = '';
  259. foreach ($child->attributes as $pa => $pa_value) {
  260. if ($pa_value->nodeName === 'name') {
  261. $nodeText = $pa_value->nodeValue;
  262. $props["{$nodeText}"] = $child->nodeValue;
  263. $paramName = $pa_value;
  264. }
  265. }
  266. if (empty($paramName)) {
  267. /**
  268. * 位置参数。多个文本节点要拼接,不能互相覆盖。
  269. * 如果参数里含有嵌套模版(元素节点),纯文本是残缺的,
  270. * 此时不设置该参数,交给渲染结果的子节点(children)显示。
  271. * TODO: html / markdown 格式下嵌套模版仍会丢失外层模版结构,
  272. * 因为 dfn 是按文档顺序遍历的,外层先于内层渲染。
  273. */
  274. $paramText = '';
  275. $hasNestedTpl = false;
  276. foreach ($child->childNodes as $param_child) {
  277. if ($param_child->nodeType === 3) {
  278. $paramText .= $param_child->nodeValue;
  279. } elseif ($param_child->nodeType === 1) {
  280. $hasNestedTpl = true;
  281. }
  282. }
  283. if (! $hasNestedTpl) {
  284. $props["{$param_id}"] = $paramText;
  285. }
  286. }
  287. }
  288. $child = $child->nextSibling;
  289. }
  290. /**
  291. * 生成模版参数
  292. */
  293. $channelInfo = [];
  294. foreach ($channelId as $key => $id) {
  295. if (Str::isUuid($id)) {
  296. $channelInfo[] = Channel::where('uid', $id)->first();
  297. }
  298. }
  299. $tplRender = new TemplateRender(
  300. $props,
  301. $channelInfo,
  302. $this->options['mode'],
  303. $this->options['format'],
  304. $this->options['studioId'],
  305. $this->options['debug'],
  306. $this->options['lang'],
  307. );
  308. $tplRender->options($this->options);
  309. $tplProps = $tplRender->render($tpl_name);
  310. /*
  311. $tplProps = TemplateRender::name($tpl_name)
  312. ->options($this->options)
  313. ->param($props)
  314. ->render();
  315. */
  316. if ($this->options['format'] === 'react' && $tplProps) {
  317. $props = $doc->createAttribute('props');
  318. $props->nodeValue = $tplProps['props'];
  319. $tpl->appendChild($props);
  320. $attTpl = $doc->createAttribute('tpl');
  321. $attTpl->nodeValue = $tplProps['tpl'];
  322. $tpl->appendChild($attTpl);
  323. $htmlElement = $doc->createElement($tplProps['tag']);
  324. $htmlElement->nodeValue = $tplProps['html'];
  325. $tpl->appendChild($htmlElement);
  326. }
  327. }
  328. $html = $doc->saveHTML();
  329. $html = str_replace(['<dfn', '</dfn>'], ['<MdTpl', '</MdTpl>'], $html);
  330. switch ($this->options['format']) {
  331. case 'react':
  332. return trim($html);
  333. break;
  334. case 'unity':
  335. if (isset($tplProps) && is_array($tplProps)) {
  336. return '{{'."{$tplProps['tpl']}|{$tplProps['props']}".'}}';
  337. } else {
  338. return '';
  339. }
  340. break;
  341. default:
  342. /**html tex text simple markdown */
  343. if (isset($tplProps)) {
  344. if (is_array($tplProps)) {
  345. if (isset($tplProps[0])) {
  346. return $tplProps[0];
  347. } else {
  348. return '';
  349. }
  350. } else {
  351. return $tplProps;
  352. }
  353. } else {
  354. Log::error('tplProps undefine');
  355. return '';
  356. }
  357. break;
  358. }
  359. }
  360. /**
  361. * 将markdown文件中的模版转换为标准的wiki模版
  362. */
  363. private function markdown2wiki(string $markdown): string
  364. {
  365. // $markdown = mb_convert_encoding($markdown,'UTF-8','UTF-8');
  366. $markdown = iconv('UTF-8', 'UTF-8//IGNORE', $markdown);
  367. /**
  368. * nissaya
  369. * aaa=bbb\n
  370. * {{nissaya|aaa|bbb}}
  371. */
  372. if ($this->options['channelType'] === 'nissaya') {
  373. if ($this->options['contentType'] === 'json') {
  374. $json = json_decode($markdown);
  375. $nissayaWord = [];
  376. if (is_array($json)) {
  377. foreach ($json as $word) {
  378. if (isset($word->original)) {
  379. // 对齐后的 nissaya json 格式:
  380. // {original, translation, note, confidence}
  381. // translation 用 ">" 分隔多层意思,转成 wiki 模版使用的 "=" 分隔符
  382. $str = '{{nissaya|';
  383. $str .= $word->original;
  384. $str .= '|';
  385. $str .= str_replace(
  386. '>',
  387. '=',
  388. isset($word->translation) ? $word->translation : ''
  389. );
  390. $str .= '}}';
  391. $nissayaWord[] = $str;
  392. if (! empty($word->note)) {
  393. $nissayaWord[] = '{{note|'.$word->note.'|[nt]}}';
  394. }
  395. } elseif (isset($word->sn) && count($word->sn) === 1) {
  396. // 逐词解析 wbw json 格式,只输出第一层级
  397. $str = '{{nissaya|';
  398. if (isset($word->word->value)) {
  399. $str .= $word->word->value;
  400. }
  401. $str .= '|';
  402. if (isset($word->meaning->value)) {
  403. $str .= $word->meaning->value;
  404. }
  405. $str .= '}}';
  406. $nissayaWord[] = $str;
  407. }
  408. }
  409. } else {
  410. Log::error('json data is not array', ['data' => $markdown]);
  411. }
  412. $markdown = implode('', $nissayaWord);
  413. } elseif ($this->options['contentType'] === 'markdown') {
  414. $lines = explode("\n", $markdown);
  415. $newLines = [];
  416. foreach ($lines as $line) {
  417. if (
  418. strstr($line, '=') === false &&
  419. strstr($line, '$') === false
  420. ) {
  421. $newLines[] = $line;
  422. } else {
  423. $line = str_replace('$', '=', $line);
  424. $nissaya = explode('=', $line);
  425. $meaning = array_slice($nissaya, 1);
  426. $meaning = implode('=', $meaning);
  427. $newLines[] = "{{nissaya|{$nissaya[0]}|{$meaning}}}";
  428. }
  429. }
  430. $markdown = implode("\n", $newLines);
  431. }
  432. }
  433. // $markdown = preg_replace("/\n\n/","<div></div>",$markdown);
  434. /**
  435. * 处理 mermaid
  436. */
  437. if (strpos($markdown, '```mermaid') !== false) {
  438. $lines = explode("\n", $markdown);
  439. $newLines = [];
  440. $mermaidBegin = false;
  441. $mermaidString = [];
  442. foreach ($lines as $line) {
  443. if ($line === '```mermaid') {
  444. $mermaidBegin = true;
  445. $mermaidString = [];
  446. continue;
  447. }
  448. if ($mermaidBegin) {
  449. if ($line === '```') {
  450. $newLines[] = '{{mermaid|'.base64_encode(\json_encode($mermaidString)).'}}';
  451. $mermaidBegin = false;
  452. } else {
  453. $mermaidString[] = $line;
  454. }
  455. } else {
  456. $newLines[] = $line;
  457. }
  458. }
  459. $markdown = implode("\n", $newLines);
  460. }
  461. /**
  462. * 替换换行符
  463. * react 无法处理 <br> 替换为<div></div>代替换行符作用
  464. */
  465. // $markdown = str_replace('<br>','<div></div>',$markdown);
  466. /**
  467. * markdown -> html
  468. */
  469. /*
  470. $html = MdRender::fixHtml($html);
  471. */
  472. // 替换术语
  473. $pattern = "/\[\[(.+?)\]\]/";
  474. $replacement = '{{term|$1}}';
  475. $markdown = preg_replace($pattern, $replacement, $markdown);
  476. // 替换句子模版
  477. $pattern = "/\{\{([0-9].+?)\}\}/";
  478. $replacement = '{{sent|id=$1}}';
  479. $markdown = preg_replace($pattern, $replacement, $markdown);
  480. /**
  481. * 替换多行注释
  482. * ```
  483. * bla
  484. * bla
  485. * ```
  486. * {{note|
  487. * bla
  488. * bla
  489. * }}
  490. */
  491. if (strpos($markdown, "```\n") !== false) {
  492. $lines = explode("\n", $markdown);
  493. $newLines = [];
  494. $noteBegin = false;
  495. $noteString = [];
  496. foreach ($lines as $line) {
  497. if ($noteBegin) {
  498. if ($line === '```') {
  499. $newLines[] = '}}';
  500. $noteBegin = false;
  501. } else {
  502. $newLines[] = $line;
  503. }
  504. } else {
  505. if ($line === '```') {
  506. $noteBegin = true;
  507. $newLines[] = '{{note|';
  508. continue;
  509. } else {
  510. $newLines[] = $line;
  511. }
  512. }
  513. }
  514. if ($noteBegin) {
  515. $newLines[] = '}}';
  516. }
  517. $markdown = implode("\n", $newLines);
  518. }
  519. /**
  520. * 替换单行注释
  521. * `bla bla`
  522. * {{note|bla}}
  523. */
  524. $pattern = '/`(.+?)`/';
  525. $replacement = '{{note|$1}}';
  526. $markdown = preg_replace($pattern, $replacement, $markdown);
  527. return $markdown;
  528. }
  529. private function markdownToHtml($markdown)
  530. {
  531. $markdown = str_replace('MdTpl', 'mdtpl', $markdown);
  532. $markdown = str_replace(['<param', '</param>'], ['<span', '</span>'], $markdown);
  533. $html = Markdown::render($markdown);
  534. if ($this->options['format'] === 'react') {
  535. $html = $this->fixHtml($html);
  536. }
  537. $html = str_replace('<hr>', '<hr />', $html);
  538. // 给H1-6 添加uuid
  539. for ($i = 1; $i < 7; $i++) {
  540. if (strpos($html, "<h{$i}>") === false) {
  541. continue;
  542. }
  543. $output = [];
  544. $input = $html;
  545. $hPos = strpos($input, "<h{$i}>");
  546. while ($hPos !== false) {
  547. $output[] = substr($input, 0, $hPos);
  548. $output[] = "<h{$i} id='".Str::uuid()."'>";
  549. $input = substr($input, $hPos + 4);
  550. $hPos = strpos($input, "<h{$i}>");
  551. }
  552. $output[] = $input;
  553. $html = implode('', $output);
  554. }
  555. $html = str_replace('mdtpl', 'MdTpl', $html);
  556. return $html;
  557. }
  558. private function fixHtml($html)
  559. {
  560. $doc = new \DOMDocument;
  561. libxml_use_internal_errors(true);
  562. $html = mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8');
  563. $doc->loadHTML('<span>'.$html.'</span>', LIBXML_NOERROR | LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
  564. $fixed = $doc->saveHTML();
  565. $fixed = mb_convert_encoding($fixed, 'UTF-8', 'HTML-ENTITIES');
  566. return $fixed;
  567. }
  568. public static function init()
  569. {
  570. $GLOBALS['MdRenderStack'] = 0;
  571. }
  572. public function convert($markdown, $channelId = [], $queryId = null)
  573. {
  574. if (isset($GLOBALS['MdRenderStack']) && is_numeric($GLOBALS['MdRenderStack'])) {
  575. $GLOBALS['MdRenderStack']++;
  576. } else {
  577. $GLOBALS['MdRenderStack'] = 1;
  578. }
  579. if ($GLOBALS['MdRenderStack'] < 3) {
  580. $output = $this->_convert($markdown, $channelId, $queryId);
  581. } else {
  582. $output = $markdown;
  583. }
  584. $GLOBALS['MdRenderStack']--;
  585. return $output;
  586. }
  587. private function _convert($markdown, $channelId = [], $queryId = null)
  588. {
  589. if (empty($markdown)) {
  590. switch ($this->options['format']) {
  591. case 'react':
  592. return '<span></span>';
  593. break;
  594. default:
  595. return '';
  596. break;
  597. }
  598. }
  599. $wiki = $this->markdown2wiki($markdown);
  600. $wiki = $this->preprocessingForParagraph($wiki);
  601. $markdownWithTpl = $this->wiki2xml($wiki, $channelId);
  602. if (! is_null($queryId)) {
  603. $html = $this->xmlQueryId($markdownWithTpl, $queryId);
  604. }
  605. $html = $this->markdownToHtml($markdownWithTpl);
  606. // 后期处理
  607. $output = '';
  608. switch ($this->options['format']) {
  609. case 'react':
  610. // 生成可展开组件
  611. $html = str_replace('<div/>', '<div></div>', $html);
  612. $pattern = '/<li><div>(.+?)<\/div><\/li>/';
  613. $replacement = '<li><MdTpl name="toggle" tpl="toggle" props=""><div>$1</div></MdTpl></li>';
  614. $output = preg_replace($pattern, $replacement, $html);
  615. break;
  616. case 'text':
  617. case 'simple':
  618. case 'prompt':
  619. $html = strip_tags($html);
  620. $output = htmlspecialchars_decode($html, ENT_QUOTES);
  621. // $output = html_entity_decode($html);
  622. break;
  623. case 'tex':
  624. $html = strip_tags($html);
  625. $output = htmlspecialchars_decode($html, ENT_QUOTES);
  626. // $output = html_entity_decode($html);
  627. break;
  628. case 'unity':
  629. $html = str_replace(['<strong>', '</strong>', '<em>', '</em>'], ['[%b%]', '[%/b%]', '[%i%]', '[%/i%]'], $html);
  630. $html = strip_tags($html);
  631. $html = str_replace(['[%b%]', '[%/b%]', '[%i%]', '[%/i%]'], ['<b>', '</b>', '<i>', '</i>'], $html);
  632. $output = htmlspecialchars_decode($html, ENT_QUOTES);
  633. break;
  634. case 'html':
  635. $output = htmlspecialchars_decode($html, ENT_QUOTES);
  636. // 处理脚注
  637. if ($this->options['footnote'] && isset($GLOBALS['note']) && count($GLOBALS['note']) > 0) {
  638. $output .= '<div><h1>endnote</h1>';
  639. foreach ($GLOBALS['note'] as $footnote) {
  640. $output .= '<p><a name="footnote-'.$footnote['sn'].'">['.$footnote['sn'].']</a> '.$footnote['content'].'</p>';
  641. }
  642. $output .= '</div>';
  643. unset($GLOBALS['note']);
  644. }
  645. // 处理图片链接
  646. $output = str_replace('<img src="', '<img src="'.config('app.url'), $output);
  647. $output = $this->replaceSinglePWithSpan($output);
  648. break;
  649. case 'markdown':
  650. // 处理脚注
  651. $footnotes = [];
  652. if ($this->options['footnote'] && isset($GLOBALS['note']) && count($GLOBALS['note']) > 0) {
  653. foreach ($GLOBALS['note'] as $footnote) {
  654. $footnotes[] = '[^'.$footnote['sn'].']: '.$footnote['content'];
  655. }
  656. unset($GLOBALS['note']);
  657. }
  658. // 处理图片链接
  659. $output = str_replace('/attachments/', config('app.url').'/attachments/', $markdownWithTpl);
  660. $output = $output."\n\n".implode("\n\n", $footnotes);
  661. break;
  662. }
  663. return $output;
  664. }
  665. /**
  666. * string[] $channelId
  667. */
  668. public static function render($markdown, $channelId, $queryId = null, $mode = 'read', $channelType = 'translation', $contentType = 'markdown', $format = 'react')
  669. {
  670. $mdRender = new MdRender(
  671. [
  672. 'mode' => $mode,
  673. 'channelType' => $channelType,
  674. 'contentType' => $contentType,
  675. 'format' => $format,
  676. ]
  677. );
  678. $output = $mdRender->convert($markdown, $channelId, $queryId);
  679. return $output;
  680. }
  681. /**
  682. * 如果字符串中只有一对 p 标签,则替换为 span
  683. */
  684. public static function replaceSinglePWithSpan(string $html): string
  685. {
  686. preg_match_all('/<p\b[^>]*>.*?<\/p>/is', $html, $matches);
  687. if (count($matches[0]) === 1) {
  688. return preg_replace(
  689. ['/^\s*<p\b([^>]*)>/i', '/<\/p>\s*$/i'],
  690. ['<span$1>', '</span>'],
  691. $html
  692. );
  693. }
  694. return $html;
  695. }
  696. }