Topic.php 14 KB

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