CorpusController.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Carbon\Carbon;
  4. use App\Models\Sentence;
  5. use App\Models\Channel;
  6. use App\Models\PaliText;
  7. use App\Models\WbwTemplate;
  8. use App\Models\WbwBlock;
  9. use App\Models\Wbw;
  10. use App\Models\Discussion;
  11. use App\Models\PaliSentence;
  12. use App\Models\SentSimIndex;
  13. use Illuminate\Support\Str;
  14. use Illuminate\Http\Request;
  15. use Illuminate\Support\Facades\Cache;
  16. use App\Http\Api\MdRender;
  17. use App\Http\Api\SuggestionApi;
  18. use App\Http\Api\ChannelApi;
  19. use App\Http\Api\UserApi;
  20. use App\Http\Api\StudioApi;
  21. use App\Http\Api\AuthApi;
  22. use Illuminate\Support\Facades\Log;
  23. use Illuminate\Support\Arr;
  24. use App\Http\Resources\TocResource;
  25. class CorpusController extends Controller
  26. {
  27. protected $result = [
  28. "uid"=> '',
  29. "title"=> '',
  30. "path"=>[],
  31. "sub_title"=> '',
  32. "summary"=> '',
  33. "content"=> '',
  34. "content_type"=> "html",
  35. "toc" => [],
  36. "status"=>30,
  37. "lang"=> "",
  38. "created_at"=> "",
  39. "updated_at"=> "",
  40. ];
  41. protected $wbwChannels = [];
  42. //句子需要查询的列
  43. protected $selectCol = [
  44. 'uid',
  45. 'book_id',
  46. 'paragraph',
  47. 'word_start',
  48. "word_end",
  49. 'channel_uid',
  50. 'content',
  51. 'content_type',
  52. 'editor_uid',
  53. 'acceptor_uid',
  54. 'pr_edit_at',
  55. 'create_time',
  56. 'modify_time',
  57. 'created_at',
  58. 'updated_at',
  59. ];
  60. protected $userUuid=null;
  61. public function __construct()
  62. {
  63. }
  64. /**
  65. * Display a listing of the resource.
  66. *
  67. * @return \Illuminate\Http\Response
  68. */
  69. public function index(Request $request)
  70. {
  71. //
  72. switch ($request->get('view')) {
  73. case 'para':
  74. return $this->showPara($request);
  75. break;
  76. default:
  77. # code...
  78. break;
  79. }
  80. }
  81. /**
  82. * Store a newly created resource in storage.
  83. *
  84. * @param \Illuminate\Http\Request $request
  85. * @return \Illuminate\Http\Response
  86. */
  87. public function store(Request $request)
  88. {
  89. //
  90. }
  91. /**
  92. * Display the specified resource.
  93. *
  94. * @param \App\Models\Sentence $sentence
  95. * @return \Illuminate\Http\Response
  96. */
  97. public function show(Sentence $sentence)
  98. {
  99. //
  100. }
  101. public function getSentTpl($id,$channels,$mode='edit',$onlyProps=false){
  102. $sent = [];
  103. $sentId = \explode('-',$id);
  104. if(count($sentId) !== 4){
  105. return false;
  106. }
  107. if($mode==='read'){
  108. $channelId = ChannelApi::getSysChannel('_System_Pali_VRI_');
  109. }else{
  110. $channelId = ChannelApi::getSysChannel('_System_Wbw_VRI_');
  111. }
  112. if($channelId !== false){
  113. array_push($channels,$channelId);
  114. }
  115. $record = Sentence::select($this->selectCol)
  116. ->where('book_id',$sentId[0])
  117. ->where('paragraph',$sentId[1])
  118. ->where('word_start',(int)$sentId[2])
  119. ->where('word_end',(int)$sentId[3])
  120. ->whereIn('channel_uid',$channels)
  121. ->get();
  122. $channelIndex = $this->getChannelIndex($channels);
  123. //获取wbw channel
  124. //目前默认的 wbw channel 是第一个translation channel
  125. foreach ($channels as $channel) {
  126. # code...
  127. if($channelIndex[$channel]->type==='translation'){
  128. $this->wbwChannels[] = $channel;
  129. break;
  130. }
  131. }
  132. return $this->makeContent($record,$mode,$channelIndex,[],$onlyProps);
  133. }
  134. /**
  135. * Display the specified resource.
  136. * @param \Illuminate\Http\Request $request
  137. * @param string $id
  138. * @return \Illuminate\Http\Response
  139. */
  140. public function showSent(Request $request, string $id)
  141. {
  142. $user = AuthApi::current($request);
  143. if($user){
  144. $this->userUuid = $user['user_uid'];
  145. }
  146. $channels = \explode('_',$request->get('channels'));
  147. $this->result['uid'] = "";
  148. $this->result['title'] = "";
  149. $this->result['subtitle'] = "";
  150. $this->result['summary'] = "";
  151. $this->result['lang'] = "";
  152. $this->result['status'] = 30;
  153. $this->result['content'] = $this->getSentTpl($id,$channels,$request->get('mode','edit'));
  154. return $this->ok($this->result);
  155. }
  156. /**
  157. * 获取某句子的全部译文
  158. * @param \Illuminate\Http\Request $request
  159. * @param string $type
  160. * @param string $id
  161. * @return \Illuminate\Http\Response
  162. */
  163. public function showSentences(Request $request, string $type, string $id){
  164. $user = AuthApi::current($request);
  165. if($user){
  166. $this->userUuid = $user['user_uid'];
  167. }
  168. $param = \explode('_',$id);
  169. $sentId = \explode('-',$param[0]);
  170. $channels = [];
  171. #获取channel类型
  172. $sentChannel = Sentence::select('channel_uid')
  173. ->where('book_id',$sentId[0])
  174. ->where('paragraph',$sentId[1])
  175. ->where('word_start',$sentId[2])
  176. ->where('word_end',$sentId[3])
  177. ->get();
  178. foreach ($sentChannel as $key => $value) {
  179. # code...
  180. $channels[] = $value->channel_uid;
  181. }
  182. $channelInfo = Channel::whereIn("uid",$channels)->select(['uid','type','name'])->get();
  183. $indexChannel = [];
  184. $channels = [];
  185. foreach ($channelInfo as $key => $value) {
  186. # code...
  187. if($value->type === $type){
  188. $indexChannel[$value->uid] = $value;
  189. $channels[] = $value->uid;
  190. }
  191. }
  192. //获取句子数据
  193. $record = Sentence::select($this->selectCol)
  194. ->where('book_id',$sentId[0])
  195. ->where('paragraph',$sentId[1])
  196. ->where('word_start',$sentId[2])
  197. ->where('word_end',$sentId[3])
  198. ->whereIn('channel_uid',$channels)
  199. ->orderBy('paragraph')
  200. ->orderBy('word_start')
  201. ->get();
  202. if(count($record) ===0){
  203. return $this->error("no data");
  204. }
  205. $this->result['uid'] = "";
  206. $this->result['title'] = "";
  207. $this->result['subtitle'] = "";
  208. $this->result['summary'] = "";
  209. $this->result['lang'] = "";
  210. $this->result['status'] = 30;
  211. $this->result['content'] = $this->makeContent($record,$mode,$indexChannel);
  212. return $this->ok($this->result);
  213. }
  214. /**
  215. * Store a newly created resource in storage.
  216. * @param \Illuminate\Http\Request $request
  217. * @param string $id
  218. * @param string $mode
  219. * @return \Illuminate\Http\Response
  220. */
  221. public function showPara(Request $request)
  222. {
  223. $user = AuthApi::current($request);
  224. if($user){
  225. $this->userUuid = $user['user_uid'];
  226. }
  227. //
  228. $channels = [];
  229. if($request->get('mode') === 'edit'){
  230. //翻译模式加载json格式原文
  231. $channels[] = ChannelApi::getSysChannel('_System_Wbw_VRI_');
  232. }else{
  233. //阅读模式加载html格式原文
  234. $channels[] = ChannelApi::getSysChannel('_System_Pali_VRI_');
  235. }
  236. if($request->has('channels')){
  237. if(strpos($request->get('channels'),',') === FALSE){
  238. $getChannel = explode('_',$request->get('channels'));
  239. }else{
  240. $getChannel = explode(',',$request->get('channels'));
  241. }
  242. $channels = array_merge($channels,$getChannel );
  243. }
  244. $para = explode(",",$request->get('par'));
  245. //段落所在章节
  246. $parent = PaliText::where('book',$request->get('book'))
  247. ->where('paragraph',$para[0])->first();
  248. $chapter = PaliText::where('book',$request->get('book'))
  249. ->where('paragraph',$parent->parent)->first();
  250. if($chapter){
  251. if(empty($chapter->toc)){
  252. $this->result['title'] = "unknown";
  253. }else{
  254. $this->result['title'] = $chapter->toc;
  255. $this->result['sub_title'] = $chapter->toc;
  256. $this->result['path'] = json_decode($chapter->path);
  257. }
  258. }
  259. $paraFrom = $para[0];
  260. $paraTo = end($para);
  261. $indexedHeading = [];
  262. #获取channel索引表
  263. $tranChannels = [];
  264. $channelInfo = Channel::whereIn("uid",$channels)->select(['uid','type','name'])->get();
  265. foreach ($channelInfo as $key => $value) {
  266. # code...
  267. if($value->type==="translation" ){
  268. $tranChannels[] = $value->uid;
  269. }
  270. }
  271. $indexChannel = [];
  272. $indexChannel = $this->getChannelIndex($channels);
  273. //获取wbw channel
  274. //目前默认的 wbw channel 是第一个translation channel
  275. foreach ($channels as $key => $value) {
  276. # code...
  277. if($indexChannel[$value]->type==='translation'){
  278. $this->wbwChannels[] = $value;
  279. break;
  280. }
  281. }
  282. //章节译文标题
  283. $title = Sentence::select($this->selectCol)
  284. ->where('book_id',$parent->book)
  285. ->where('paragraph',$parent->paragraph)
  286. ->whereIn('channel_uid',$tranChannels)
  287. ->first();
  288. if($title){
  289. $this->result['title'] = MdRender::render($title->content,[$title->channel_uid]);
  290. }
  291. /**
  292. * 获取句子数据
  293. */
  294. $record = Sentence::select($this->selectCol)
  295. ->where('book_id',$request->get('book'))
  296. ->whereIn('paragraph',$para)
  297. ->whereIn('channel_uid',$channels)
  298. ->orderBy('paragraph')
  299. ->orderBy('word_start')
  300. ->get();
  301. if(count($record) ===0){
  302. $this->result['content'] = "<span>No Data</span>";
  303. }else{
  304. $this->result['content'] = $this->makeContent($record,$request->get('mode','read'),$indexChannel,$indexedHeading);
  305. }
  306. return $this->ok($this->result);
  307. }
  308. /**
  309. * Store a newly created resource in storage.
  310. * @param \Illuminate\Http\Request $request
  311. * @param string $id
  312. * @return \Illuminate\Http\Response
  313. */
  314. public function showChapter(Request $request, string $id)
  315. {
  316. $user = AuthApi::current($request);
  317. if($user){
  318. $this->userUuid = $user['user_uid'];
  319. }
  320. //
  321. $sentId = \explode('-',$id);
  322. $channels = [];
  323. if($request->has('channels')){
  324. if(strpos($request->get('channels'),',') === FALSE){
  325. $channels = explode('_',$request->get('channels'));
  326. }else{
  327. $channels = explode(',',$request->get('channels'));
  328. }
  329. }
  330. $mode = $request->get('mode','read');
  331. if($mode === 'read'){
  332. //阅读模式加载html格式原文
  333. $channelId = ChannelApi::getSysChannel('_System_Pali_VRI_');
  334. }else{
  335. //翻译模式加载json格式原文
  336. $channelId = ChannelApi::getSysChannel('_System_Wbw_VRI_');
  337. }
  338. if($channelId !== false){
  339. $channels[] = $channelId;
  340. }
  341. $chapter = PaliText::where('book',$sentId[0])->where('paragraph',$sentId[1])->first();
  342. if(!$chapter){
  343. return $this->error("no data");
  344. }
  345. if(empty($chapter->toc)){
  346. $this->result['title'] = "unknown";
  347. }else{
  348. $this->result['title'] = $chapter->toc;
  349. $this->result['sub_title'] = $chapter->toc;
  350. $this->result['path'] = json_decode($chapter->path);
  351. }
  352. $paraFrom = $sentId[1];
  353. $paraTo = $sentId[1]+$chapter->chapter_len-1;
  354. //获取标题
  355. $heading = PaliText::select(["book","paragraph","level"])
  356. ->where('book',$sentId[0])
  357. ->whereBetween('paragraph',[$paraFrom,$paraTo])
  358. ->where('level','<',8)
  359. ->get();
  360. //将标题段落转成索引数组 以便输出标题层级
  361. $indexedHeading = [];
  362. foreach ($heading as $key => $value) {
  363. # code...
  364. $indexedHeading["{$value->book}-{$value->paragraph}"] = $value->level;
  365. }
  366. #获取channel索引表
  367. $tranChannels = [];
  368. $channelInfo = Channel::whereIn("uid",$channels)->select(['uid','type','name'])->get();
  369. foreach ($channelInfo as $key => $value) {
  370. # code...
  371. if($value->type==="translation" ){
  372. $tranChannels[] = $value->uid;
  373. }
  374. }
  375. $indexChannel = [];
  376. $indexChannel = $this->getChannelIndex($channels);
  377. //获取wbw channel
  378. //目前默认的 wbw channel 是第一个translation channel
  379. foreach ($channels as $key => $value) {
  380. # code...
  381. if($indexChannel[$value]->type==='translation'){
  382. $this->wbwChannels[] = $value;
  383. break;
  384. }
  385. }
  386. $title = Sentence::select($this->selectCol)
  387. ->where('book_id',$sentId[0])
  388. ->where('paragraph',$sentId[1])
  389. ->whereIn('channel_uid',$tranChannels)
  390. ->first();
  391. if($title){
  392. $this->result['title'] = MdRender::render($title->content,[$title->channel_uid]);
  393. }
  394. /**
  395. * 获取句子数据
  396. * 算法:
  397. * 1. 如果标题和下一级第一个标题之间有段落。只输出这些段落和子目录
  398. * 2. 如果标题和下一级第一个标题之间没有间隔 且 chapter 长度大于10000个字符 且有子目录,只输出子目录
  399. * 3. 如果二者都不是,lazy load
  400. */
  401. //1. 计算 标题和下一级第一个标题之间 是否有间隔
  402. $nextChapter = PaliText::where('book',$sentId[0])
  403. ->where('paragraph',">",$sentId[1])
  404. ->where('level','<',8)
  405. ->orderBy('paragraph')
  406. ->value('paragraph');
  407. $between = $nextChapter - $sentId[1];
  408. //输出子目录
  409. $chapterLen = $chapter->chapter_len;
  410. $toc = PaliText::where('book',$sentId[0])
  411. ->whereBetween('paragraph',[$paraFrom+1,$paraFrom+$chapterLen-1])
  412. ->where('level','<',8)
  413. ->orderBy('paragraph')
  414. ->select(['book','paragraph','level','toc'])
  415. ->get();
  416. if($between > 1){
  417. //有间隔
  418. $paraTo = $nextChapter - 1;
  419. }else{
  420. if($chapter->chapter_strlen>2000){
  421. if(count($toc)>0){
  422. //有子目录只输出标题和目录
  423. $paraTo = $paraFrom;
  424. }else{
  425. //没有子目录 全部输出
  426. }
  427. }else{
  428. //章节小。全部输出 不输出章节
  429. $toc = [];
  430. }
  431. }
  432. $pFrom = $request->get('from',$paraFrom);
  433. $pTo = $request->get('to',$paraTo);
  434. //根据句子的长度找到这次应该加载的句子
  435. $maxLen = 3000;
  436. $paliText = PaliText::select(['paragraph','lenght'])
  437. ->where('book',$sentId[0])
  438. ->whereBetween('paragraph',[$pFrom,$pTo])
  439. ->get();
  440. $sumLen = 0;
  441. $currTo = $pTo;
  442. foreach ($paliText as $para) {
  443. $sumLen += $para->lenght;
  444. if($sumLen > $maxLen){
  445. $currTo = $para->paragraph;
  446. break;
  447. }
  448. }
  449. $record = Sentence::select($this->selectCol)
  450. ->where('book_id',$sentId[0])
  451. ->whereBetween('paragraph',[$pFrom,$currTo])
  452. ->whereIn('channel_uid',$channels)
  453. ->orderBy('paragraph')
  454. ->orderBy('word_start')
  455. ->get();
  456. if(count($record) ===0){
  457. return $this->error("no data");
  458. }
  459. $this->result['content'] = $this->makeContent($record,$mode,$indexChannel,$indexedHeading,false,true);
  460. if(!$request->has('from')){
  461. //第一次才显示toc
  462. $this->result['toc'] = TocResource::collection($toc);
  463. }
  464. if($currTo < $pTo){
  465. $this->result['from'] = $currTo+1;
  466. $this->result['to'] = $pTo;
  467. $this->result['paraId'] = $id;
  468. $this->result['channels'] = $request->get('channels');
  469. $this->result['mode'] = $request->get('mode');
  470. }
  471. return $this->ok($this->result);
  472. }
  473. private function getChannelIndex($channels,$type=null){
  474. #获取channel索引表
  475. $channelInfo = Channel::whereIn("uid",$channels)
  476. ->select(['uid','type','name','owner_uid'])->get();
  477. $indexChannel = [];
  478. foreach ($channelInfo as $key => $value) {
  479. # code...
  480. if($type !== null && $value->type !== $type){
  481. continue;
  482. }
  483. $indexChannel[$value->uid] = $value;
  484. }
  485. foreach ($indexChannel as $uid => $value) {
  486. # 查询studio
  487. $indexChannel[$uid]['studio'] = StudioApi::getById($value->owner_uid);
  488. }
  489. return $indexChannel;
  490. }
  491. /**
  492. * 根据句子库数据生成文章内容
  493. * $record 句子数据
  494. * $mode read | edit | wbw
  495. * $indexChannel channel索引
  496. * $indexedHeading 标题索引 用于给段落加标题标签 <h1> ect.
  497. */
  498. private function makeContent($record,$mode,$indexChannel,$indexedHeading=[],$onlyProps=false,$paraMark=false){
  499. $content = [];
  500. $lastSent = "0-0";
  501. $sentCount = 0;
  502. $sent = [];
  503. $sent["origin"] = [];
  504. $sent["translation"] = [];
  505. //获取句子编号列表
  506. $sentList = [];
  507. foreach ($record as $key => $value) {
  508. $currSentId = "{$value->book_id}-{$value->paragraph}-{$value->word_start}-{$value->word_end}";
  509. $sentList[$currSentId]=[$value->book_id ,$value->paragraph,$value->word_start,$value->word_end];
  510. $value['sid'] = "{$currSentId}_{$value->channel_uid}";
  511. }
  512. $channelsId = array();
  513. $count = 0;
  514. foreach ($indexChannel as $channelId => $info){
  515. if($count>0){
  516. $channelsId[] = $channelId;
  517. }
  518. $count++;
  519. }
  520. //遍历列表查找每个句子的所有channel的数据,并填充
  521. $currPara = "";
  522. foreach ($sentList as $currSentId => $arrSentId) {
  523. $para = $arrSentId[0]."-".$arrSentId[1];
  524. if($currPara !== $para){
  525. $currPara = $para;
  526. //输出段落标记
  527. if($paraMark){
  528. $sentInPara = array();
  529. foreach ($sentList as $sentId => $sentParam) {
  530. if($sentParam[0]===$arrSentId[0] &&
  531. $sentParam[1]===$arrSentId[1]){
  532. $sentInPara[] = $sentId;
  533. }
  534. }
  535. $mark = [
  536. 'book'=>$arrSentId[0],
  537. 'para'=>$arrSentId[1],
  538. 'channels'=>$channelsId,
  539. 'sentences'=>$sentInPara,
  540. ];
  541. $markProps = base64_encode(\json_encode($mark)) ;
  542. $paraWidget = "<MdTpl tpl='para' props='{$markProps}' ></MdTpl>";
  543. $content[] = $paraWidget;
  544. }
  545. }
  546. $sent = $this->newSent($arrSentId[0],$arrSentId[1],$arrSentId[2],$arrSentId[3]);
  547. foreach ($indexChannel as $channelId => $info) {
  548. # code...
  549. $sid = "{$currSentId}_{$channelId}";
  550. $newSent = [
  551. "content"=>"",
  552. "html"=> "",
  553. "book"=> $arrSentId[0],
  554. "para"=> $arrSentId[1],
  555. "wordStart"=> $arrSentId[2],
  556. "wordEnd"=> $arrSentId[3],
  557. "channel"=> [
  558. "name"=>$info->name,
  559. "type"=>$info->type,
  560. "id"=> $info->uid,
  561. ],
  562. "studio" => $info['studio'],
  563. "updateAt"=> "",
  564. "suggestionCount" => SuggestionApi::getCountBySent($arrSentId[0],$arrSentId[1],$arrSentId[2],$arrSentId[3],$channelId),
  565. ];
  566. $row = Arr::first($record,function($value,$key) use($sid){
  567. return $value['sid']===$sid;
  568. });
  569. if($row){
  570. $newSent['id'] = $row->uid;
  571. $newSent['content'] = $row->content;
  572. $newSent['contentType'] = $row->content_type;
  573. $newSent['html'] = "";
  574. $newSent["editor"]=UserApi::getByUuid($row->editor_uid);
  575. /**
  576. * TODO 刷库改数据
  577. * 旧版api没有更新updated_at所以造成旧版的数据updated_at数据比modify_time 要晚
  578. */
  579. $newSent['updateAt'] = $row->updated_at; //
  580. $newSent['updateAt'] = Carbon::createFromTimestampMs($row->modify_time)->toDateTimeString();
  581. $newSent['createdAt'] = $row->created_at;
  582. if($mode !== "read"){
  583. if(isset($row->acceptor_uid) && !empty($row->acceptor_uid)){
  584. $newSent["acceptor"]=UserApi::getByUuid($row->acceptor_uid);
  585. $newSent["prEditAt"]=$row->pr_edit_at;
  586. }
  587. }
  588. switch ($info->type) {
  589. case 'wbw':
  590. case 'original':
  591. //
  592. // 在编辑模式下。
  593. // 如果是原文,查看是否有逐词解析数据,
  594. // 有的话优先显示。
  595. // 阅读模式直接显示html原文
  596. // 传过来的数据一定有一个原文channel
  597. //
  598. if($mode !== "read"){
  599. $newSent['channel']['type'] = "wbw";
  600. if(isset($this->wbwChannels[0])){
  601. $newSent['channel']['name'] = $indexChannel[$this->wbwChannels[0]]->name;
  602. $newSent['channel']['id'] = $this->wbwChannels[0];
  603. //存在一个translation channel
  604. //尝试查找逐词解析数据。找到,替换现有数据
  605. $wbwData = $this->getWbw($arrSentId[0],$arrSentId[1],$arrSentId[2],$arrSentId[3],$this->wbwChannels[0]);
  606. if($wbwData){
  607. $newSent['content'] = $wbwData;
  608. $newSent['html'] = "";
  609. }
  610. }
  611. }else{
  612. $newSent['content'] = "";
  613. $newSent['html'] = $row->content;
  614. }
  615. break;
  616. case 'nissaya':
  617. $newSent['html'] = Cache::remember("/sent/{$channelId}/{$currSentId}",
  618. env('CACHE_EXPIRE',3600*24),
  619. function() use($row,$mode){
  620. return MdRender::render($row->content,[$row->channel_uid],null,$mode,"nissaya",$row->content_type);
  621. });
  622. break;
  623. default:
  624. /**
  625. * 译文需要markdown渲染
  626. * 包涵术语的不用cache
  627. */
  628. if(strpos($row->content,'[[')===false){
  629. $newSent['html'] = MdRender::render($row->content,[$row->channel_uid]);
  630. }else{
  631. $newSent['html'] = Cache::remember("/sent/{$channelId}/{$currSentId}",
  632. env('CACHE_EXPIRE',3600*24),
  633. function() use($row){
  634. return MdRender::render($row->content,[$row->channel_uid]);
  635. });
  636. }
  637. break;
  638. }
  639. }
  640. switch ($info->type) {
  641. case 'wbw':
  642. case 'original':
  643. array_push($sent["origin"],$newSent);
  644. break;
  645. default:
  646. array_push($sent["translation"],$newSent);
  647. break;
  648. }
  649. }
  650. if($onlyProps){
  651. return $sent;
  652. }
  653. $content = $this->pushSent($content,$sent,0,$mode);
  654. }
  655. $output = \implode("",$content);
  656. return "<div>{$output}</div>";
  657. }
  658. public function getWbw($book,$para,$start,$end,$channel){
  659. /**
  660. * 非阅读模式下。原文使用逐词解析数据。
  661. * 优先加载第一个translation channel 如果没有。加载默认逐词解析。
  662. */
  663. //获取逐词解析数据
  664. $wbwBlock = WbwBlock::where('channel_uid',$channel)
  665. ->where('book_id',$book)
  666. ->where('paragraph',$para)
  667. ->select('uid')
  668. ->first();
  669. if(!$wbwBlock){
  670. return false;
  671. }
  672. //找到逐词解析数据
  673. $wbwData = Wbw::where('block_uid',$wbwBlock->uid)
  674. ->whereBetween('wid',[$start,$end])
  675. ->select(['book_id','paragraph','wid','data','uid'])
  676. ->orderBy('wid')
  677. ->get();
  678. $wbwContent = [];
  679. foreach ($wbwData as $wbwrow) {
  680. $wbw = str_replace("&nbsp;",' ',$wbwrow->data);
  681. $wbw = str_replace("<br>",' ',$wbw);
  682. $xmlString = "<root>" . $wbw . "</root>";
  683. try{
  684. $xmlWord = simplexml_load_string($xmlString);
  685. }catch(Exception $e){
  686. continue;
  687. }
  688. $wordsList = $xmlWord->xpath('//word');
  689. foreach ($wordsList as $word) {
  690. $case = \str_replace(['#','.'],['$',''],$word->case->__toString());
  691. $case = \str_replace('$$','$',$case);
  692. $case = trim($case);
  693. $case = trim($case,"$");
  694. $wbwId = explode('-',$word->id->__toString());
  695. $wbwData = [
  696. 'uid'=>$wbwrow->uid,
  697. 'book'=>$wbwrow->book_id,
  698. 'para'=>$wbwrow->paragraph,
  699. 'sn'=> array_slice($wbwId,2),
  700. 'word'=>['value'=>$word->pali->__toString(),'status'=>0],
  701. 'real'=> ['value'=>$word->real->__toString(),'status'=>0],
  702. 'meaning'=> ['value'=>$word->mean->__toString() ,'status'=>0],
  703. 'type'=> ['value'=>$word->type->__toString(),'status'=>0],
  704. 'grammar'=> ['value'=>$word->gramma->__toString(),'status'=>0],
  705. 'case'=> ['value'=>$word->case->__toString(),'status'=>0],
  706. 'parent'=> ['value'=>$word->parent->__toString(),'status'=>0],
  707. 'style'=> ['value'=>$word->style->__toString(),'status'=>0],
  708. 'factors'=> ['value'=>$word->org->__toString(),'status'=>0],
  709. 'factorMeaning'=> ['value'=>$word->om->__toString(),'status'=>0],
  710. 'confidence'=> $word->cf->__toString(),
  711. 'hasComment'=>Discussion::where('res_id',$wbwrow->uid)->exists(),
  712. ];
  713. if(isset($word->parent2)){
  714. $wbwData['parent2']['value'] = $word->parent2->__toString();
  715. if(isset($word->parent2['status'])){
  716. $wbwData['parent2']['status'] = (int)$word->parent2['status'];
  717. }else{
  718. $wbwData['parent2']['status'] = 0;
  719. }
  720. }
  721. if(isset($word->pg)){
  722. $wbwData['grammar2']['value'] = $word->pg->__toString();
  723. if(isset($word->pg['status'])){
  724. $wbwData['grammar2']['status'] = (int)$word->pg['status'];
  725. }else{
  726. $wbwData['grammar2']['status'] = 0;
  727. }
  728. }
  729. if(isset($word->rela)){
  730. $wbwData['relation']['value'] = $word->rela->__toString();
  731. if(isset($word->rela['status'])){
  732. $wbwData['relation']['status'] = (int)$word->rela['status'];
  733. }else{
  734. $wbwData['relation']['status'] = 7;
  735. }
  736. }
  737. if(isset($word->bmt)){
  738. $wbwData['bookMarkText']['value'] = $word->bmt->__toString();
  739. if(isset($word->bmt['status'])){
  740. $wbwData['bookMarkText']['status'] = (int)$word->bmt['status'];
  741. }else{
  742. $wbwData['bookMarkText']['status'] = 7;
  743. }
  744. }
  745. if(isset($word->bmc)){
  746. $wbwData['bookMarkColor']['value'] = $word->bmc->__toString();
  747. if(isset($word->bmc['status'])){
  748. $wbwData['bookMarkColor']['status'] = (int)$word->bmc['status'];
  749. }else{
  750. $wbwData['bookMarkColor']['status'] = 7;
  751. }
  752. }
  753. if(isset($word->note)){
  754. $wbwData['note']['value'] = $word->note->__toString();
  755. if(isset($word->note['status'])){
  756. $wbwData['note']['status'] = (int)$word->note['status'];
  757. }else{
  758. $wbwData['note']['status'] = 7;
  759. }
  760. }
  761. if(isset($word->cf)){
  762. $wbwData['confidence'] = (float)$word->cf->__toString();
  763. }
  764. if(isset($word->attachments)){
  765. $wbwData['attachments'] = json_decode($word->attachments->__toString());
  766. }
  767. if(isset($word->pali['status'])){
  768. $wbwData['word']['status'] = (int)$word->pali['status'];
  769. }
  770. if(isset($word->real['status'])){
  771. $wbwData['real']['status'] = (int)$word->real['status'];
  772. }
  773. if(isset($word->mean['status'])){
  774. $wbwData['meaning']['status'] = (int)$word->mean['status'];
  775. }
  776. if(isset($word->type['status'])){
  777. $wbwData['type']['status'] = (int)$word->type['status'];
  778. }
  779. if(isset($word->gramma['status'])){
  780. $wbwData['grammar']['status'] = (int)$word->gramma['status'];
  781. }
  782. if(isset($word->case['status'])){
  783. $wbwData['case']['status'] = (int)$word->case['status'];
  784. }
  785. if(isset($word->parent['status'])){
  786. $wbwData['parent']['status'] = (int)$word->parent['status'];
  787. }
  788. if(isset($word->org['status'])){
  789. $wbwData['factors']['status'] = (int)$word->org['status'];
  790. }
  791. if(isset($word->om['status'])){
  792. $wbwData['factorMeaning']['status'] = (int)$word->om['status'];
  793. }
  794. $wbwContent[] = $wbwData;
  795. }
  796. }
  797. if(count($wbwContent)===0){
  798. return false;
  799. }
  800. return \json_encode($wbwContent,JSON_UNESCAPED_UNICODE);
  801. }
  802. /**
  803. * 将句子放进结果列表
  804. */
  805. private function pushSent($result,$sent,$level=0,$mode='read'){
  806. $sentProps = base64_encode(\json_encode($sent)) ;
  807. if($mode === 'read'){
  808. $sentWidget = "<MdTpl tpl='sentread' props='{$sentProps}' ></MdTpl>";
  809. }else{
  810. $sentWidget = "<MdTpl tpl='sentedit' props='{$sentProps}' ></MdTpl>";
  811. }
  812. //增加标题的html标记
  813. if($level>0){
  814. $sentWidget = "<h{$level}>".$sentWidget."</h{$level}>";
  815. }
  816. array_push($result,$sentWidget);
  817. return $result;
  818. }
  819. private function newSent($book,$para,$word_start,$word_end){
  820. $sent = [
  821. "id"=>"{$book}-{$para}-{$word_start}-{$word_end}",
  822. "book"=>$book,
  823. "para"=>$para,
  824. "wordStart"=>$word_start,
  825. "wordEnd"=>$word_end,
  826. "origin"=>[],
  827. "translation"=>[],
  828. ];
  829. #生成channel 数量列表
  830. $sentId = "{$book}-{$para}-{$word_start}-{$word_end}";
  831. $channelCount = CorpusController::sentCanReadCount($book,$para,$word_start,$word_end,$this->userUuid);
  832. $path = json_decode(PaliText::where('book',$book)->where('paragraph',$para)->value("path"),true);
  833. $sent["path"] = [];
  834. foreach ($path as $key => $value) {
  835. # code...
  836. $value['paliTitle'] = $value['title'];
  837. $sent["path"][] = $value;
  838. }
  839. $sent["tranNum"] = $channelCount['tranNum'];
  840. $sent["nissayaNum"] = $channelCount['nissayaNum'];
  841. $sent["commNum"] = $channelCount['commNum'];
  842. $sent["originNum"] = $channelCount['originNum'];
  843. $sent["simNum"] = $channelCount['simNum'];
  844. return $sent;
  845. }
  846. /**
  847. * 获取某个句子的相关资源的句子数量
  848. */
  849. public static function sentCanReadCount($book,$para,$start,$end,$userUuid=null){
  850. $sentId = "{$book}-{$para}-{$start}-{$end}";
  851. $key = "/sentence/{$sentId}/channels/count";
  852. if($userUuid){
  853. $key .= $userUuid;
  854. }else{
  855. $key .= 'guest';
  856. }
  857. $channelCount = Cache::remember($key,env('CACHE_EXPIRE',3600*24),
  858. function() use($book,$para,$start,$end,$userUuid){
  859. $keyCanRead="/channel/can-read/";
  860. if($userUuid){
  861. $keyCanRead .= $userUuid;
  862. }else{
  863. $keyCanRead .= 'guest';
  864. }
  865. $channelCanRead = Cache::remember($keyCanRead,
  866. env('CACHE_EXPIRE',3600*24),
  867. function() use($userUuid){
  868. return ChannelApi::getCanReadByUser($userUuid);
  869. });
  870. $channels = Sentence::where('book_id',$book)
  871. ->where('paragraph',$para)
  872. ->where('word_start',$start)
  873. ->where('word_end',$end)
  874. ->whereIn('channel_uid',$channelCanRead)
  875. ->select('channel_uid')
  876. ->groupBy('channel_uid')
  877. ->get();
  878. $channelList = [];
  879. foreach ($channels as $key => $value) {
  880. # code...
  881. if(Str::isUuid($value->channel_uid)){
  882. $channelList[] = $value->channel_uid;
  883. }
  884. }
  885. $simId = PaliSentence::where('book',$book)
  886. ->where('paragraph',$para)
  887. ->where('word_begin',$start)
  888. ->where('word_end',$end)
  889. ->value('id');
  890. if($simId){
  891. $output["simNum"]=SentSimIndex::where('sent_id',$simId)->value('count');
  892. }else{
  893. $output["simNum"]=0;
  894. }
  895. $channelInfo = Channel::whereIn("uid",$channelList)->select('type')->get();
  896. $output["tranNum"]=0;
  897. $output["nissayaNum"]=0;
  898. $output["commNum"]=0;
  899. $output["originNum"]=0;
  900. foreach ($channelInfo as $key => $value) {
  901. # code...
  902. switch($value->type){
  903. case "translation":
  904. $output["tranNum"]++;
  905. break;
  906. case "nissaya":
  907. $output["nissayaNum"]++;
  908. break;
  909. case "commentary":
  910. $output["commNum"]++;
  911. break;
  912. case "original":
  913. $output["originNum"]++;
  914. break;
  915. }
  916. }
  917. return $output;
  918. });
  919. return $channelCount;
  920. }
  921. private function markdownRender($input){
  922. }
  923. /**
  924. * Update the specified resource in storage.
  925. *
  926. * @param \Illuminate\Http\Request $request
  927. * @param \App\Models\Sentence $sentence
  928. * @return \Illuminate\Http\Response
  929. */
  930. public function update(Request $request, Sentence $sentence)
  931. {
  932. //
  933. }
  934. /**
  935. * Remove the specified resource from storage.
  936. *
  937. * @param \App\Models\Sentence $sentence
  938. * @return \Illuminate\Http\Response
  939. */
  940. public function destroy(Sentence $sentence)
  941. {
  942. //
  943. }
  944. }