CorpusController.php 38 KB

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