Topic.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. <?php
  2. /**
  3. * This file is part of the ForkBB <https://github.com/forkbb>.
  4. *
  5. * @copyright (c) Visman <mio.visman@yandex.ru, https://github.com/MioVisman>
  6. * @license The MIT License (MIT)
  7. */
  8. declare(strict_types=1);
  9. namespace ForkBB\Models\Topic;
  10. use ForkBB\Core\Container;
  11. use ForkBB\Models\DataModel;
  12. use ForkBB\Models\Forum\Forum;
  13. use ForkBB\Models\Poll\Poll;
  14. use PDO;
  15. use RuntimeException;
  16. class Topic extends DataModel
  17. {
  18. /**
  19. * Ключ модели для контейнера
  20. * @var string
  21. */
  22. protected $cKey = 'Topic';
  23. /**
  24. * Получение родительского раздела
  25. */
  26. protected function getparent(): ?Forum
  27. {
  28. if ($this->forum_id < 1) {
  29. throw new RuntimeException('Parent is not defined');
  30. }
  31. $forum = $this->c->forums->get($this->forum_id);
  32. if (
  33. ! $forum instanceof Forum
  34. || $forum->redirect_url
  35. ) {
  36. return null;
  37. } else {
  38. return $forum;
  39. }
  40. }
  41. /**
  42. * Возвращает отцензурированное название темы
  43. */
  44. protected function getname(): ?string
  45. {
  46. return $this->censorSubject;
  47. }
  48. /**
  49. * Статус возможности ответа в теме
  50. */
  51. protected function getcanReply(): bool
  52. {
  53. if ($this->moved_to) {
  54. return false;
  55. } elseif ($this->c->user->isAdmin) {
  56. return true;
  57. } elseif (
  58. $this->closed
  59. || $this->c->user->isBot
  60. ) {
  61. return false;
  62. } elseif (
  63. '1' == $this->parent->post_replies
  64. || (
  65. null === $this->parent->post_replies
  66. && '1' == $this->c->user->g_post_replies
  67. )
  68. || $this->c->user->isModerator($this)
  69. ) {
  70. return true;
  71. } else {
  72. return false;
  73. }
  74. }
  75. /**
  76. * Статус возможности использования подписок
  77. */
  78. protected function getcanSubscription(): bool
  79. {
  80. return '1' == $this->c->config->o_topic_subscriptions
  81. && $this->id > 0
  82. && ! $this->c->user->isGuest
  83. && ! $this->c->user->isUnverified;
  84. }
  85. /**
  86. * Ссылка на тему
  87. */
  88. protected function getlink(): string
  89. {
  90. return $this->c->Router->link(
  91. 'Topic',
  92. [
  93. 'id' => $this->moved_to ?: $this->id,
  94. 'name' => $this->name,
  95. ]
  96. );
  97. }
  98. /**
  99. * Ссылка для ответа в теме
  100. */
  101. protected function getlinkReply(): string
  102. {
  103. return $this->c->Router->link(
  104. 'NewReply',
  105. [
  106. 'id' => $this->id,
  107. ]
  108. );
  109. }
  110. /**
  111. * Ссылка для перехода на последнее сообщение темы
  112. */
  113. protected function getlinkLast(): string
  114. {
  115. if (
  116. $this->moved_to
  117. || $this->last_post_id < 1
  118. ) {
  119. return '';
  120. } else {
  121. return $this->c->Router->link(
  122. 'ViewPost',
  123. [
  124. 'id' => $this->last_post_id,
  125. ]
  126. );
  127. }
  128. }
  129. /**
  130. * Ссылка для перехода на первое новое сообщение в теме
  131. */
  132. protected function getlinkNew(): string
  133. {
  134. return $this->c->Router->link(
  135. 'TopicViewNew',
  136. [
  137. 'id' => $this->id,
  138. ]
  139. );
  140. }
  141. /**
  142. * Ссылка для перехода на первое не прочитанное сообщение в теме
  143. */
  144. protected function getlinkUnread(): string
  145. {
  146. return $this->c->Router->link(
  147. 'TopicViewUnread',
  148. [
  149. 'id' => $this->id,
  150. ]
  151. );
  152. }
  153. /**
  154. * Ссылка на подписку
  155. */
  156. protected function getlinkSubscribe(): string
  157. {
  158. return $this->c->Router->link(
  159. 'TopicSubscription',
  160. [
  161. 'tid' => $this->id,
  162. 'type' => 'subscribe',
  163. ]
  164. );
  165. }
  166. /**
  167. * Ссылка на отписку
  168. */
  169. protected function getlinkUnsubscribe(): string
  170. {
  171. return $this->c->Router->link(
  172. 'TopicSubscription',
  173. [
  174. 'tid' => $this->id,
  175. 'type' => 'unsubscribe',
  176. ]
  177. );
  178. }
  179. /**
  180. * Статус наличия новых сообщений в теме
  181. */
  182. protected function gethasNew() /* : int|false */
  183. {
  184. if (
  185. $this->c->user->isGuest
  186. || $this->moved_to
  187. ) {
  188. return false;
  189. }
  190. $time = \max(
  191. (int) $this->c->user->u_mark_all_read,
  192. (int) $this->parent->mf_mark_all_read,
  193. (int) $this->c->user->last_visit,
  194. (int) $this->mt_last_visit
  195. );
  196. return $this->last_post > $time ? $time : false;
  197. }
  198. /**
  199. * Статус наличия непрочитанных сообщений в теме
  200. */
  201. protected function gethasUnread() /* int|false */
  202. {
  203. if (
  204. $this->c->user->isGuest
  205. || $this->moved_to
  206. ) {
  207. return false;
  208. }
  209. $time = \max(
  210. (int) $this->c->user->u_mark_all_read,
  211. (int) $this->parent->mf_mark_all_read,
  212. (int) $this->mt_last_read
  213. );
  214. return $this->last_post > $time ? $time : false;
  215. }
  216. /**
  217. * Номер первого нового сообщения в теме
  218. */
  219. protected function getfirstNew(): int
  220. {
  221. if (false === $this->hasNew) {
  222. return 0;
  223. } elseif ($this->posted > $this->hasNew) {
  224. return $this->first_post_id;
  225. }
  226. $vars = [
  227. ':tid' => $this->id,
  228. ':visit' => $this->hasNew,
  229. ];
  230. $query = 'SELECT MIN(p.id)
  231. FROM ::posts AS p
  232. WHERE p.topic_id=?i:tid AND p.posted>?i:visit';
  233. $pid = $this->c->DB->query($query, $vars)->fetchColumn();
  234. return $pid ?: 0;
  235. }
  236. /**
  237. * Номер первого не прочитанного сообщения в теме
  238. */
  239. protected function getfirstUnread(): int
  240. {
  241. if (false === $this->hasUnread) {
  242. return 0;
  243. } elseif ($this->posted > $this->hasUnread) {
  244. return $this->first_post_id;
  245. }
  246. $vars = [
  247. ':tid' => $this->id,
  248. ':visit' => $this->hasUnread,
  249. ];
  250. $query = 'SELECT MIN(p.id)
  251. FROM ::posts AS p
  252. WHERE p.topic_id=?i:tid AND p.posted>?i:visit';
  253. $pid = $this->c->DB->query($query, $vars)->fetchColumn();
  254. return $pid ?: 0;
  255. }
  256. /**
  257. * Количество страниц в теме
  258. */
  259. protected function getnumPages(): int
  260. {
  261. if (null === $this->num_replies) {
  262. throw new RuntimeException('The model does not have the required data');
  263. }
  264. return (int) \ceil(($this->num_replies + 1) / $this->c->user->disp_posts);
  265. }
  266. /**
  267. * Массив страниц темы
  268. */
  269. protected function getpagination(): array
  270. {
  271. $page = (int) $this->page;
  272. if (
  273. $page < 1
  274. && 1 === $this->numPages
  275. ) {
  276. // 1 страницу в списке тем раздела не отображаем
  277. return [];
  278. } else { //????
  279. return $this->c->Func->paginate(
  280. $this->numPages,
  281. $page,
  282. 'Topic',
  283. [
  284. 'id' => $this->id,
  285. 'name' => $this->name,
  286. ]
  287. );
  288. }
  289. }
  290. /**
  291. * Статус наличия установленной страницы в теме
  292. */
  293. public function hasPage(): bool
  294. {
  295. return $this->page > 0 && $this->page <= $this->numPages;
  296. }
  297. /**
  298. * Возвращает массив сообщений с установленной страницы
  299. */
  300. public function pageData(): array
  301. {
  302. if (! $this->hasPage()) {
  303. throw new InvalidArgumentException('Bad number of displayed page');
  304. }
  305. $vars = [
  306. ':tid' => $this->id,
  307. ':offset' => ($this->page - 1) * $this->c->user->disp_posts,
  308. ':rows' => $this->c->user->disp_posts,
  309. ];
  310. $query = 'SELECT p.id
  311. FROM ::posts AS p
  312. WHERE p.topic_id=?i:tid
  313. ORDER BY p.id
  314. LIMIT ?i:offset, ?i:rows';
  315. $list = $this->c->DB->query($query, $vars)->fetchAll(PDO::FETCH_COLUMN);
  316. if (
  317. ! empty($list)
  318. && (
  319. $this->stick_fp
  320. || (
  321. $this->poll_type > 0
  322. && 1 === $this->c->config->b_poll_enabled
  323. )
  324. )
  325. && ! \in_array($this->first_post_id, $list)
  326. ) {
  327. \array_unshift($list, $this->first_post_id);
  328. }
  329. $this->idsList = $list;
  330. return empty($this->idsList) ? [] : $this->c->posts->view($this);
  331. }
  332. /**
  333. * Возвращает массив сообщений обзора темы
  334. */
  335. public function review(): array
  336. {
  337. if ($this->c->config->i_topic_review < 1) {
  338. return [];
  339. }
  340. $this->page = 1;
  341. $vars = [
  342. ':tid' => $this->id,
  343. ':rows' => $this->c->config->i_topic_review,
  344. ];
  345. $query = 'SELECT p.id
  346. FROM ::posts AS p
  347. WHERE p.topic_id=?i:tid
  348. ORDER BY p.id DESC
  349. LIMIT 0, ?i:rows';
  350. $this->idsList = $this->c->DB->query($query, $vars)->fetchAll(PDO::FETCH_COLUMN);
  351. return empty($this->idsList) ? [] : $this->c->posts->view($this, true);
  352. }
  353. /**
  354. * Вычисляет страницу темы на которой находится данное сообщение
  355. */
  356. public function calcPage(int $pid): void
  357. {
  358. $vars = [
  359. ':tid' => $this->id,
  360. ':pid' => $pid,
  361. ];
  362. $query = 'SELECT COUNT(p.id) AS pnum, MAX(p.id) as pmax
  363. FROM ::posts AS p
  364. WHERE p.topic_id=?i:tid AND p.id<=?i:pid';
  365. $result = $this->c->DB->query($query, $vars)->fetch();
  366. if (
  367. empty($result['pmax'])
  368. || $result['pmax'] !== $pid
  369. ) {
  370. $this->page = null;
  371. } else {
  372. $this->page = (int) \ceil($result['pnum'] / $this->c->user->disp_posts);
  373. }
  374. /*
  375. $query = 'SELECT COUNT(p.id) AS num
  376. FROM ::posts AS p
  377. INNER JOIN ::posts AS j ON (j.topic_id=?i:tid AND j.id=?i:pid)
  378. WHERE p.topic_id=?i:tid AND p.id<?i:pid'; //???? может на два запроса разбить?
  379. $result = $this->c->DB->query($query, $vars)->fetch();
  380. $this->page = empty($result) ? null : (int) \ceil(($result['num'] + 1) / $this->c->user->disp_posts);
  381. */
  382. }
  383. /**
  384. * Статус показа/подсчета просмотров темы
  385. */
  386. protected function getshowViews(): bool
  387. {
  388. return '1' == $this->c->config->o_topic_views;
  389. }
  390. /**
  391. * Увеличивает на 1 количество просмотров темы
  392. */
  393. public function incViews(): void
  394. {
  395. $vars = [
  396. ':tid' => $this->id,
  397. ];
  398. $query = 'UPDATE ::topics
  399. SET num_views=num_views+1
  400. WHERE id=?i:tid';
  401. $this->c->DB->exec($query, $vars);
  402. }
  403. /**
  404. * Обновление меток последнего визита и последнего прочитанного сообщения
  405. */
  406. public function updateVisits(): void
  407. {
  408. if ($this->c->user->isGuest) {
  409. return;
  410. }
  411. $vars = [
  412. ':uid' => $this->c->user->id,
  413. ':tid' => $this->id,
  414. ':read' => (int) $this->mt_last_read,
  415. ':visit' => (int) $this->mt_last_visit,
  416. ];
  417. $flag = false;
  418. if (false !== $this->hasNew) {
  419. $flag = true;
  420. $vars[':visit'] = $this->last_post;
  421. }
  422. if (
  423. false !== $this->hasUnread
  424. && $this->timeMax > $this->hasUnread
  425. ) {
  426. $flag = true;
  427. $vars[':read'] = $this->timeMax;
  428. $vars[':visit'] = $this->last_post;
  429. }
  430. if ($flag) {
  431. if (
  432. empty($this->mt_last_read)
  433. && empty($this->mt_last_visit)
  434. ) {
  435. $query = 'INSERT INTO ::mark_of_topic (uid, tid, mt_last_visit, mt_last_read)
  436. SELECT ?i:uid, ?i:tid, ?i:visit, ?i:read
  437. FROM ::groups
  438. WHERE NOT EXISTS (
  439. SELECT 1
  440. FROM ::mark_of_topic
  441. WHERE uid=?i:uid AND tid=?i:tid
  442. )
  443. LIMIT 1';
  444. } else {
  445. $query = 'UPDATE ::mark_of_topic
  446. SET mt_last_visit=?i:visit, mt_last_read=?i:read
  447. WHERE uid=?i:uid AND tid=?i:tid';
  448. }
  449. $this->c->DB->exec($query, $vars);
  450. }
  451. }
  452. /**
  453. * Возвращает опрос при его наличии
  454. */
  455. protected function getpoll(): ?Poll
  456. {
  457. return $this->poll_type > 0 ? $this->c->polls->load($this->id) : null;
  458. }
  459. }