Topic.php 13 KB

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