Topic.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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->b_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. return (int) $this->c->DB->query($query, $vars)->fetchColumn();
  234. }
  235. /**
  236. * Номер первого не прочитанного сообщения в теме
  237. */
  238. protected function getfirstUnread(): int
  239. {
  240. if (false === $this->hasUnread) {
  241. return 0;
  242. } elseif ($this->posted > $this->hasUnread) {
  243. return $this->first_post_id;
  244. }
  245. $vars = [
  246. ':tid' => $this->id,
  247. ':visit' => $this->hasUnread,
  248. ];
  249. $query = 'SELECT MIN(p.id)
  250. FROM ::posts AS p
  251. WHERE p.topic_id=?i:tid AND p.posted>?i:visit';
  252. return (int) $this->c->DB->query($query, $vars)->fetchColumn();
  253. }
  254. /**
  255. * Количество страниц в теме
  256. */
  257. protected function getnumPages(): int
  258. {
  259. if (null === $this->num_replies) {
  260. throw new RuntimeException('The model does not have the required data');
  261. }
  262. return (int) \ceil(($this->num_replies + 1) / $this->c->user->disp_posts);
  263. }
  264. /**
  265. * Массив страниц темы
  266. */
  267. protected function getpagination(): array
  268. {
  269. $page = (int) $this->page;
  270. if (
  271. $page < 1
  272. && 1 === $this->numPages
  273. ) {
  274. // 1 страницу в списке тем раздела не отображаем
  275. return [];
  276. } else { //????
  277. return $this->c->Func->paginate(
  278. $this->numPages,
  279. $page,
  280. 'Topic',
  281. [
  282. 'id' => $this->id,
  283. 'name' => $this->name,
  284. ]
  285. );
  286. }
  287. }
  288. /**
  289. * Статус наличия установленной страницы в теме
  290. */
  291. public function hasPage(): bool
  292. {
  293. return $this->page > 0 && $this->page <= $this->numPages;
  294. }
  295. /**
  296. * Возвращает массив сообщений с установленной страницы
  297. */
  298. public function pageData(): array
  299. {
  300. if (! $this->hasPage()) {
  301. throw new InvalidArgumentException('Bad number of displayed page');
  302. }
  303. $vars = [
  304. ':tid' => $this->id,
  305. ':offset' => ($this->page - 1) * $this->c->user->disp_posts,
  306. ':rows' => $this->c->user->disp_posts,
  307. ];
  308. $query = 'SELECT p.id
  309. FROM ::posts AS p
  310. WHERE p.topic_id=?i:tid
  311. ORDER BY p.id
  312. LIMIT ?i:rows OFFSET ?i:offset';
  313. $list = $this->c->DB->query($query, $vars)->fetchAll(PDO::FETCH_COLUMN);
  314. if (
  315. ! empty($list)
  316. && (
  317. $this->stick_fp
  318. || (
  319. $this->poll_type > 0
  320. && 1 === $this->c->config->b_poll_enabled
  321. )
  322. )
  323. && ! \in_array($this->first_post_id, $list)
  324. ) {
  325. \array_unshift($list, $this->first_post_id);
  326. }
  327. $this->idsList = $list;
  328. return empty($this->idsList) ? [] : $this->c->posts->view($this);
  329. }
  330. /**
  331. * Возвращает массив сообщений обзора темы
  332. */
  333. public function review(): array
  334. {
  335. if ($this->c->config->i_topic_review < 1) {
  336. return [];
  337. }
  338. $this->page = 1;
  339. $vars = [
  340. ':tid' => $this->id,
  341. ':rows' => $this->c->config->i_topic_review,
  342. ];
  343. $query = 'SELECT p.id
  344. FROM ::posts AS p
  345. WHERE p.topic_id=?i:tid
  346. ORDER BY p.id DESC
  347. LIMIT ?i:rows';
  348. $this->idsList = $this->c->DB->query($query, $vars)->fetchAll(PDO::FETCH_COLUMN);
  349. return empty($this->idsList) ? [] : $this->c->posts->view($this, true);
  350. }
  351. /**
  352. * Вычисляет страницу темы на которой находится данное сообщение
  353. */
  354. public function calcPage(int $pid): void
  355. {
  356. $vars = [
  357. ':tid' => $this->id,
  358. ':pid' => $pid,
  359. ];
  360. $query = 'SELECT COUNT(p.id) AS pnum, MAX(p.id) as pmax
  361. FROM ::posts AS p
  362. WHERE p.topic_id=?i:tid AND p.id<=?i:pid';
  363. $result = $this->c->DB->query($query, $vars)->fetch();
  364. if (
  365. empty($result['pmax'])
  366. || $result['pmax'] !== $pid
  367. ) {
  368. $this->page = null;
  369. } else {
  370. $this->page = (int) \ceil($result['pnum'] / $this->c->user->disp_posts);
  371. }
  372. }
  373. /**
  374. * Статус показа/подсчета просмотров темы
  375. */
  376. protected function getshowViews(): bool
  377. {
  378. return 1 === $this->c->config->b_topic_views;
  379. }
  380. /**
  381. * Увеличивает на 1 количество просмотров темы
  382. */
  383. public function incViews(): void
  384. {
  385. $vars = [
  386. ':tid' => $this->id,
  387. ];
  388. $query = 'UPDATE ::topics
  389. SET num_views=num_views+1
  390. WHERE id=?i:tid';
  391. $this->c->DB->exec($query, $vars);
  392. }
  393. /**
  394. * Обновление меток последнего визита и последнего прочитанного сообщения
  395. */
  396. public function updateVisits(): void
  397. {
  398. if ($this->c->user->isGuest) {
  399. return;
  400. }
  401. $vars = [
  402. ':uid' => $this->c->user->id,
  403. ':tid' => $this->id,
  404. ':read' => (int) $this->mt_last_read,
  405. ':visit' => (int) $this->mt_last_visit,
  406. ];
  407. $flag = false;
  408. if (false !== $this->hasNew) {
  409. $flag = true;
  410. $vars[':visit'] = $this->last_post;
  411. }
  412. if (
  413. false !== $this->hasUnread
  414. && $this->timeMax > $this->hasUnread
  415. ) {
  416. $flag = true;
  417. $vars[':read'] = $this->timeMax;
  418. $vars[':visit'] = $this->last_post;
  419. }
  420. if ($flag) {
  421. if (
  422. empty($this->mt_last_read)
  423. && empty($this->mt_last_visit)
  424. ) {
  425. $query = 'INSERT INTO ::mark_of_topic (uid, tid, mt_last_visit, mt_last_read)
  426. SELECT ?i:uid, ?i:tid, ?i:visit, ?i:read
  427. FROM ::groups
  428. WHERE NOT EXISTS (
  429. SELECT 1
  430. FROM ::mark_of_topic
  431. WHERE uid=?i:uid AND tid=?i:tid
  432. )
  433. LIMIT 1';
  434. } else {
  435. $query = 'UPDATE ::mark_of_topic
  436. SET mt_last_visit=?i:visit, mt_last_read=?i:read
  437. WHERE uid=?i:uid AND tid=?i:tid';
  438. }
  439. $this->c->DB->exec($query, $vars);
  440. }
  441. }
  442. /**
  443. * Возвращает опрос при его наличии
  444. */
  445. protected function getpoll(): ?Poll
  446. {
  447. return $this->poll_type > 0 ? $this->c->polls->load($this->id) : null;
  448. }
  449. }