CorpusController.php 38 KB

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