diff --git a/CHANGELOG.md b/CHANGELOG.md index db3dea7..fa86462 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,3 +5,4 @@ - Phase 0: module skeleton for ImpressCMS 2.0 in IPF mode, install and update routines, English and Dutch language files, CI on PHP 8.2 to 8.5. - Phase 1: data model. 13 IPF objects with handlers (category, forum, moderator, topic, post, attachment, report, suspension, readmark, online, digest, archive, permtemplate), group permissions on categories and forums, counters and cascading deletes through handler events, indexes in `imforum_db_upgrade_1()`, labels in English and Dutch, integration tests against MySQL 5.5, MySQL 5.7 (MyISAM) and MariaDB 10.11. - Phase 2: administration. Admin screens on `icms_ipf_view_Table` and `getSecureForm()` for categories and forums (moderators and group permissions on the forum form), a permission template that new forums start with and that can be applied to existing forums, reports, suspensions, digests, the archive, prune (with a preview and a confirmation) and a full recount. Every operation that writes runs only on POST with a valid security token, deletion confirmations included. Works around three core issues: a missing admin menu on the first request after the menu cache is rebuilt, `count(null)` when a permission select is left empty, and the date picker failing when a form is built before `icms_cp_header()`. +- Phase 3: reading. `index.php`, `forum.php`, `topic.php` (flat and threaded), `viewall.php` (latest, unread, featured), `archive.php`, `rss.php`, search, who is online, signatures, ranks and the poster bar, read marks per topic and per forum ("mark all as read" is a POST with a token), karma and required-reply locks that hide the text until unlocked, three blocks (recent, hot, top posters) and six preferences. Permissions are checked in one `PermissionService`: category access, forum access and view, switched-off forums for moderators and webmasters only. Our own pager replaces the core's, which prints `PHP_SELF` unescaped. Integration tests cover the permission checks, read marks, thread order, karma, online tracking, the archive and search. diff --git a/README.md b/README.md index 2ccafba..24b02d9 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Community forum module for ImpressCMS 2.0, built on the ImpressCMS Persistable Framework (IPF). imforum is the successor of iForum: same features, new code, and an importer that takes over the data of a running iForum installation. -Status: phase 2 (administration). Categories, forums, moderators, group permissions, reports, suspensions, digests, the archive and pruning are managed from the admin area. There are no forum pages for visitors yet. +Status: phase 3 (reading). Visitors can read the forum index, forums, topics (flat or threaded), the latest, unread and featured topics, the archive and an RSS feed, and search the forums. Everything is filtered by the group permissions, read marks, karma and required replies are applied, and three blocks are available. Posting, editing and moderating from the front end come in later phases. Categories, forums, moderators, permissions, reports, suspensions, digests, the archive and pruning are managed from the admin area. ## Requirements diff --git a/phpstan.neon.dist b/phpstan.neon.dist index ba79c65..eb54d78 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -34,3 +34,19 @@ parameters: # icms_db_legacy_IDatabase::queryF() documents a resource, but returns false when the query fails identifier: ternary.alwaysTrue path: src/include/onupdate.php + - + # icms_core_DataFilter::filterTextareaDisplay() documents bool switches but compares them + # with != 0 and !== 0, so false would still convert line breaks: the post's 0/1 flags go in as they are + message: '#^Parameter \#[2-5] \$(smiley|icode|image|br) of static method icms_core_DataFilter::filterTextareaDisplay\(\) expects bool, int given\.$#' + identifier: argument.type + - + # formatTimestamp() documents a string, but takes the integer timestamps that every caller passes + message: '#^Parameter \#1 \$time of function formatTimestamp expects string, int#' + identifier: argument.type + - + # icms::$user is documented as an object, but it is null for guests + identifier: ternary.alwaysTrue + path: src/*.php + - + identifier: function.alreadyNarrowedType + message: '#^Call to function is_object\(\) with icms_member_user_Object#' diff --git a/src/archive.php b/src/archive.php new file mode 100644 index 0000000..2388aae --- /dev/null +++ b/src/archive.php @@ -0,0 +1,85 @@ + 0) { + $topic = $topicHandler->get($topicId); + $forum = $topic->isNew() ? null : $permissions->getForum((int) $topic->getVar('forum_id', 'e')); + if ($forum === null || !$permissions->canReadForum($forum)) { + redirect_header(mod_imforum_View::url('archive'), 3, _NOPERM); + exit; + } +} + +$xoopsOption['template_main'] = 'imforum_archive.html'; +include_once ICMS_ROOT_PATH . '/header.php'; +global $icmsTpl, $xoTheme; +$xoTheme->addStylesheet(IMFORUM_URL . 'assets/css/imforum.css'); + +$listUrl = mod_imforum_View::url('archive'); +if ($topic !== null) { + $archived = $archiveHandler->getByTopic($topicId); + // the posts still exist: the author's wish for karma or a reply holds for the archived text too + $live = $postHandler->getByIds(array_map(static fn (mod_imforum_Archive $entry): int => (int) $entry->getVar('post_id', 'e'), $archived)); + $karma = new mod_imforum_KarmaService($permissions->getUid()); + $moderator = $permissions->isModerator((int) $topic->getVar('forum_id', 'e')); + $posts = []; + foreach ($archived as $entry) { + $postId = (int) $entry->getVar('post_id', 'e'); + $post = $live[$postId] ?? null; + $lock = $post === null ? mod_imforum_KarmaService::LOCK_NONE : $karma->apply($post, $moderator); + $posts[] = [ + 'id' => $postId, + 'subject' => $post === null ? '' : $post->getVar('subject'), + 'author' => $post === null ? '' : mod_imforum_View::poster((int) $post->getVar('uid', 'e'), (string) $post->getVar('poster_name', 'n')), + 'time' => $post === null ? '' : mod_imforum_View::time((int) $post->getVar('post_time', 'e')), + 'archived' => mod_imforum_View::time((int) $entry->getVar('archived_time', 'e')), + 'lock' => $lock, + 'text' => $lock !== mod_imforum_KarmaService::LOCK_NONE ? '' : (string) icms_core_DataFilter::filterTextareaDisplay((string) $entry->getVar('post_text', 'n'), 1, 1, 1, 1), + ]; + } + $icmsTpl->assign('imforum_breadcrumb', mod_imforum_View::breadcrumb([[_MD_IMFORUM_ARCHIVE, $listUrl], [$topic->getVar('topic_title', 'n')]])); + $icmsTpl->assign('imforum_archive_topic', [ + 'title' => $topic->getVar('topic_title'), + 'url' => mod_imforum_View::link('topic', ['topic' => $topicId]), + ]); + $icmsTpl->assign('imforum_archive_posts', $posts); +} else { + $perPage = mod_imforum_Settings::getCount('topics_per_page'); + $start = mod_imforum_View::intParam('start'); + $page = $archiveHandler->getTopicsPage($permissions->getReadableForumIds(), $start, $perPage); + $topics = $topicHandler->getByIds(array_column($page['rows'], 'topic_id')); + $rows = []; + foreach ($page['rows'] as $row) { + if (!isset($topics[$row['topic_id']])) { + continue; + } + $rows[] = [ + 'url' => mod_imforum_View::link('archive', ['topic' => $row['topic_id']]), + 'title' => $topics[$row['topic_id']]->getVar('topic_title'), + 'posts' => $row['posts'], + 'archived' => mod_imforum_View::time($row['archived_time']), + ]; + } + $icmsTpl->assign('imforum_breadcrumb', mod_imforum_View::breadcrumb([[_MD_IMFORUM_ARCHIVE]])); + $icmsTpl->assign('imforum_archive_topics', $rows); + $icmsTpl->assign('imforum_pager', mod_imforum_View::pager('archive', [], $page['total'], $perPage, $start)); +} + +include_once ICMS_ROOT_PATH . '/footer.php'; diff --git a/src/assets/css/imforum.css b/src/assets/css/imforum.css index c399a3c..58ecebd 100644 --- a/src/assets/css/imforum.css +++ b/src/assets/css/imforum.css @@ -1 +1,58 @@ /* Forum-specific additions on top of the ImpressCMS 2.0 default theme. */ + +.imforum { margin: 0 0 1.5em; } +.imforum-breadcrumb { margin: 0 0 .75em; font-size: .9em; } +.imforum-sep { margin: 0 .35em; opacity: .6; } +.imforum-tools { margin: 0 0 .75em; } +.imforum-meta { font-size: .85em; opacity: .75; } +.imforum-notice { padding: .5em .75em; border-left: 3px solid currentColor; background: rgba(128, 128, 128, .12); } + +.imforum table.outer { width: 100%; margin: 0 0 1em; border-collapse: collapse; } +.imforum table.outer th, +.imforum table.outer td { padding: .5em .65em; vertical-align: top; text-align: left; } +.imforum .imforum-num { width: 5em; text-align: center; white-space: nowrap; } +.imforum .imforum-last { width: 14em; } +.imforum .imforum-flags { width: 2em; text-align: center; } +.imforum .imforum-read { opacity: .35; } +.imforum tr.imforum-unread a { font-weight: bold; } + +.imforum-badge { display: inline-block; padding: 0 .4em; margin-right: .3em; border-radius: .6em; font-size: .75em; line-height: 1.6; background: rgba(128, 128, 128, .25); } +.imforum-badge.imforum-new { background: #2a7a3b; color: #fff; } +.imforum-pages { font-size: .8em; } + +.imforum-pager { margin: .75em 0; } +.imforum-pager a, +.imforum-pager strong, +.imforum-pager .imforum-gap { display: inline-block; min-width: 1.6em; padding: .15em .4em; text-align: center; } + +.imforum-post { display: flex; gap: 1em; margin: 0 0 1em; padding: .75em; border: 1px solid rgba(128, 128, 128, .35); border-radius: 4px; } +.imforum-poster { flex: 0 0 11em; word-break: break-word; } +.imforum-avatar { display: block; max-width: 96px; max-height: 96px; margin: 0 0 .4em; } +.imforum-post-body { flex: 1 1 auto; min-width: 0; } +.imforum-post-head { display: flex; flex-wrap: wrap; gap: .5em; align-items: baseline; margin: 0 0 .5em; padding: 0 0 .4em; border-bottom: 1px solid rgba(128, 128, 128, .25); } +.imforum-permalink { opacity: .6; } +.imforum-post-text { overflow-wrap: anywhere; } +.imforum-signature { margin: .75em 0 0; padding: .4em 0 0; border-top: 1px dashed rgba(128, 128, 128, .4); font-size: .85em; opacity: .8; } + +.imforum-depth-1 { margin-left: 1.5em; } +.imforum-depth-2 { margin-left: 3em; } +.imforum-depth-3 { margin-left: 4.5em; } +.imforum-depth-4 { margin-left: 6em; } +.imforum-depth-5 { margin-left: 7.5em; } +.imforum-depth-6 { margin-left: 9em; } +.imforum-depth-7 { margin-left: 10.5em; } +.imforum-depth-8 { margin-left: 12em; } + +.imforum-online { margin: 1em 0 0; } +.imforum-online h3 { margin: 0 0 .25em; font-size: 1em; } +.imforum-markread { margin: 1em 0; } +.imforum-block { margin: 0; padding-left: 1.2em; } +.imforum-block li { margin: 0 0 .4em; } + +@media (max-width: 40em) { + .imforum-post { flex-direction: column; } + .imforum-poster { flex-basis: auto; } + .imforum .imforum-last { width: auto; } + .imforum-depth-2, .imforum-depth-3, .imforum-depth-4, .imforum-depth-5, + .imforum-depth-6, .imforum-depth-7, .imforum-depth-8 { margin-left: 1.5em; } +} diff --git a/src/blocks/imforum_blocks.php b/src/blocks/imforum_blocks.php new file mode 100644 index 0000000..f9d9ba3 --- /dev/null +++ b/src/blocks/imforum_blocks.php @@ -0,0 +1,94 @@ + $topicIds + * @return list> + */ +function imforum_block_topic_rows(array $topicIds, mod_imforum_PermissionService $permissions): array { + $topics = icms_getModuleHandler('topic', IMFORUM_DIRNAME)->getByIds($topicIds); + $summaries = icms_getModuleHandler('post', IMFORUM_DIRNAME)->getSummaries(array_map( + static fn (mod_imforum_Topic $topic): int => (int) $topic->getVar('topic_last_post_id', 'e'), + $topics + )); + $rows = []; + foreach ($topics as $topicId => $topic) { + $lastPostId = (int) $topic->getVar('topic_last_post_id', 'e'); + $forum = $permissions->getForum((int) $topic->getVar('forum_id', 'e')); + $rows[] = [ + 'url' => mod_imforum_View::link('topic', ['topic' => $topicId, 'post' => $lastPostId]) . '#post-' . $lastPostId, + 'title' => $topic->getVar('topic_title'), + 'forum' => $forum === null ? '' : $forum->getVar('forum_name'), + 'replies' => (int) $topic->getVar('topic_replies', 'e'), + 'time' => mod_imforum_View::time(isset($summaries[$lastPostId]) ? $summaries[$lastPostId]['post_time'] : (int) $topic->getVar('topic_time', 'e')), + ]; + } + return $rows; +} + +/** + * @param array $options 0: number of topics + * @return array|false + */ +function imforum_block_recent($options) { + $permissions = mod_imforum_PermissionService::forCurrentUser(); + $found = icms_getModuleHandler('topic', IMFORUM_DIRNAME)->findRecent($permissions->getReadableForumIds(), 0, max(1, (int) ($options[0] ?? 10))); + $rows = imforum_block_topic_rows($found['ids'], $permissions); + return $rows ? ['topics' => $rows, 'all_url' => mod_imforum_View::link('viewall')] : false; +} + +/** + * @param array $options 0: number of topics, 1: days to look back + * @return array|false + */ +function imforum_block_hot($options) { + $permissions = mod_imforum_PermissionService::forCurrentUser(); + $days = max(1, (int) ($options[1] ?? 30)); + $ids = icms_getModuleHandler('topic', IMFORUM_DIRNAME)->findHot($permissions->getReadableForumIds(), time() - $days * 86400, max(1, (int) ($options[0] ?? 10))); + $rows = imforum_block_topic_rows($ids, $permissions); + return $rows ? ['topics' => $rows, 'all_url' => mod_imforum_View::link('viewall')] : false; +} + +/** + * @param array $options 0: number of members + * @return array|false + */ +function imforum_block_topposters($options) { + $permissions = mod_imforum_PermissionService::forCurrentUser(); + $rows = []; + foreach (icms_getModuleHandler('post', IMFORUM_DIRNAME)->getTopPosters($permissions->getReadableForumIds(), max(1, (int) ($options[0] ?? 10))) as $poster) { + $rows[] = ['member' => mod_imforum_View::poster($poster['uid'], ''), 'posts' => $poster['posts']]; + } + return $rows ? ['posters' => $rows] : false; +} + +/** + * @param array $options + */ +function imforum_block_edit_recent($options): string { + return ''; +} + +/** + * @param array $options + */ +function imforum_block_edit_hot($options): string { + return '
' + . ''; +} diff --git a/src/class/ArchiveHandler.php b/src/class/ArchiveHandler.php index 6d433b9..0242ab9 100644 --- a/src/class/ArchiveHandler.php +++ b/src/class/ArchiveHandler.php @@ -18,6 +18,45 @@ public function __construct(icms_db_legacy_Database $db) { parent::__construct($db, 'archive', 'archive_id', '', 'post_text', IMFORUM_DIRNAME); } + /** + * Topics with archived posts, the most recently archived first + * + * @param list $forumIds the forums the reader may open + * @return array{rows: list, total: int} + */ + public function getTopicsPage(array $forumIds, int $start, int $limit): array { + $forumIds = array_values(array_filter(array_map('intval', $forumIds))); + if (!$forumIds) { + return ['rows' => [], 'total' => 0]; + } + $topics = $this->db->prefix(IMFORUM_DIRNAME . '_topic'); + $from = " FROM {$this->table} a JOIN $topics t ON t.topic_id = a.topic_id WHERE t.forum_id IN (" . implode(',', $forumIds) . ')'; + + $total = 0; + $result = $this->db->queryF("SELECT COUNT(DISTINCT a.topic_id)$from"); + if ($result && ($row = $this->db->fetchRow($result))) { + $total = (int) $row[0]; + } + $rows = []; + $result = $this->db->queryF("SELECT a.topic_id, COUNT(*), MAX(a.archived_time)$from GROUP BY a.topic_id ORDER BY MAX(a.archived_time) DESC, a.topic_id DESC LIMIT " . max(0, $start) . ', ' . max(1, $limit)); + while ($result && ($row = $this->db->fetchRow($result))) { + $rows[] = ['topic_id' => (int) $row[0], 'posts' => (int) $row[1], 'archived_time' => (int) $row[2]]; + } + return ['rows' => $rows, 'total' => $total]; + } + + /** + * The archived posts of a topic, oldest first + * + * @return list + */ + public function getByTopic(int $topicId): array { + $criteria = new icms_db_criteria_Compo(new icms_db_criteria_Item('topic_id', $topicId)); + $criteria->setSort('post_id'); + $criteria->setOrder('ASC'); + return array_values($this->getObjects($criteria)); + } + protected function beforeInsert(mod_imforum_Archive $archive): bool { if ((int) $archive->getVar('archived_time', 'e') === 0) { $archive->setVar('archived_time', time()); diff --git a/src/class/KarmaService.php b/src/class/KarmaService.php new file mode 100644 index 0000000..8ad8f48 --- /dev/null +++ b/src/class/KarmaService.php @@ -0,0 +1,87 @@ + topic id => whether the reader has replied */ + private array $replied = []; + + public function __construct(int $uid) { + $this->uid = $uid; + } + + public function getKarma(): int { + if ($this->karma === null) { + $this->karma = $this->uid > 0 + ? icms_getModuleHandler('post', IMFORUM_DIRNAME)->countByUsers([$this->uid])[$this->uid] ?? 0 + : 0; + } + return $this->karma; + } + + /** + * Why the reader may not see the text, or LOCK_NONE + */ + public function getLock(mod_imforum_Post $post, bool $moderator): string { + $required = (int) $post->getVar('post_karma', 'e'); + $replyFirst = (int) $post->getVar('require_reply', 'e') === 1; + if ($required <= 0 && !$replyFirst) { + return self::LOCK_NONE; + } + $author = (int) $post->getVar('uid', 'e'); + if ($moderator || ($this->uid > 0 && $author === $this->uid)) { + return self::LOCK_NONE; + } + if ($required > 0 && $this->getKarma() < $required) { + return self::LOCK_KARMA; + } + if ($replyFirst && !$this->hasReplied((int) $post->getVar('topic_id', 'e'))) { + return self::LOCK_REPLY; + } + return self::LOCK_NONE; + } + + /** + * Unlock the post for this reader when the rules allow it + */ + public function apply(mod_imforum_Post $post, bool $moderator): string { + $lock = $this->getLock($post, $moderator); + if ($lock === self::LOCK_NONE) { + $post->unlock(); + } else { + $post->setLock($lock); + } + return $lock; + } + + private function hasReplied(int $topicId): bool { + if ($this->uid < 1) { + return false; + } + return $this->replied[$topicId] ??= icms_getModuleHandler('post', IMFORUM_DIRNAME)->hasPosted($topicId, $this->uid); + } +} diff --git a/src/class/OnlineHandler.php b/src/class/OnlineHandler.php index 427b880..1335e0d 100644 --- a/src/class/OnlineHandler.php +++ b/src/class/OnlineHandler.php @@ -18,6 +18,82 @@ public function __construct(icms_db_legacy_Database $db) { parent::__construct($db, 'online', 'online_id', 'uname', '', IMFORUM_DIRNAME); } + /** + * Note that a visitor is looking at a forum or topic + * + * Members are found again by user id, guests by address; every visitor has + * one row. Rows that were not updated for $minutes are removed. + */ + public function track(int $uid, string $uname, string $ip, int $forumId, int $topicId, int $minutes = 15): bool { + $ip = filter_var($ip, FILTER_VALIDATE_IP) ? $ip : ''; + $criteria = new icms_db_criteria_Compo(new icms_db_criteria_Item('uid', max(0, $uid))); + if ($uid < 1) { + if ($ip === '') { + return false; + } + $criteria->add(new icms_db_criteria_Item('ip', $ip)); + } + $existing = $this->getObjects($criteria); + $row = $existing[0] ?? $this->create(); + $row->setVar('uid', max(0, $uid)); + $row->setVar('uname', $uid > 0 ? $uname : ''); + $row->setVar('ip', $ip); + $row->setVar('forum_id', $forumId); + $row->setVar('topic_id', $topicId); + $row->setVar('updated', time()); + $ok = $this->insert($row, true); + $this->purgeOlderThan(time() - max(1, $minutes) * 60); + return $ok; + } + + /** + * Who is online, on the whole forum or on a forum or topic + * + * @return array{members: list, guests: int} + */ + public function getSnapshot(int $forumId = 0, int $topicId = 0, int $minutes = 15): array { + $criteria = new icms_db_criteria_Compo(new icms_db_criteria_Item('updated', time() - max(1, $minutes) * 60, '>=')); + if ($topicId > 0) { + $criteria->add(new icms_db_criteria_Item('topic_id', $topicId)); + } elseif ($forumId > 0) { + $criteria->add(new icms_db_criteria_Item('forum_id', $forumId)); + } + $criteria->setSort('uname'); + $criteria->setOrder('ASC'); + + $members = []; + $guests = 0; + foreach ($this->getObjects($criteria) as $row) { + $uid = (int) $row->getVar('uid', 'e'); + if ($uid > 0) { + $members[] = ['uid' => $uid, 'uname' => (string) $row->getVar('uname')]; + } else { + $guests++; + } + } + return ['members' => $members, 'guests' => $guests]; + } + + /** + * Which of these members are online + * + * @param list $uids + * @return array + */ + public function getOnlineMembers(array $uids, int $minutes = 15): array { + $uids = array_values(array_filter(array_map('intval', $uids))); + if (!$uids) { + return []; + } + $online = []; + $criteria = new icms_db_criteria_Compo(new icms_db_criteria_Item('uid', '(' . implode(',', $uids) . ')', 'IN')); + $criteria->add(new icms_db_criteria_Item('updated', time() - max(1, $minutes) * 60, '>=')); + foreach ($this->getObjects($criteria) as $row) { + $online[(int) $row->getVar('uid', 'e')] = true; + } + return $online; + } + /** * Drop rows that were not updated since a moment */ diff --git a/src/class/PermissionService.php b/src/class/PermissionService.php new file mode 100644 index 0000000..08caa37 --- /dev/null +++ b/src/class/PermissionService.php @@ -0,0 +1,180 @@ + */ + private array $groups; + + private int $uid; + + private bool $webmaster; + + /** @var array> permission name => item ids */ + private array $granted = []; + + /** @var array|null */ + private ?array $forums = null; + + /** @var array|null */ + private ?array $moderated = null; + + /** + * @param list $groups ids of the groups of the visitor + */ + public function __construct(array $groups, int $uid = 0, bool $webmaster = false) { + $this->groups = array_map('intval', $groups); + $this->uid = $uid; + $this->webmaster = $webmaster; + } + + /** + * The visitor of this request + */ + public static function forCurrentUser(): self { + $user = icms::$user; + if (!is_object($user)) { + return new self([ICMS_GROUP_ANONYMOUS]); + } + $groups = array_map('intval', $user->getGroups()); + return new self($groups, (int) $user->getVar('uid'), in_array((int) ICMS_GROUP_ADMIN, $groups, true)); + } + + /** + * An anonymous visitor; the RSS feed shows only what a guest sees + */ + public static function forGuest(): self { + return new self([ICMS_GROUP_ANONYMOUS]); + } + + public function getUid(): int { + return $this->uid; + } + + /** + * @return list + */ + public function getGroups(): array { + return $this->groups; + } + + public function isWebmaster(): bool { + return $this->webmaster; + } + + public function canSeeCategory(int $catId): bool { + return $this->has('category_access', $catId); + } + + /** + * The forum appears in lists + */ + public function canSeeForum(mod_imforum_Forum $forum): bool { + if ($this->webmaster) { + return true; + } + $forumId = (int) $forum->id(); + if (!(int) $forum->getVar('forum_active', 'e') && !$this->isModerator($forumId)) { + return false; + } + return $this->canSeeCategory((int) $forum->getVar('cat_id', 'e')) && $this->has('forum_access', $forumId); + } + + /** + * Topics and posts of the forum can be opened + */ + public function canReadForum(mod_imforum_Forum $forum): bool { + return $this->webmaster || ($this->canSeeForum($forum) && $this->has('forum_view', (int) $forum->id())); + } + + public function isModerator(int $forumId): bool { + if ($this->webmaster) { + return true; + } + if ($this->uid < 1) { + return false; + } + if ($this->moderated === null) { + $this->moderated = []; + $criteria = new icms_db_criteria_Item('uid', $this->uid); + foreach (icms_getModuleHandler('moderator', IMFORUM_DIRNAME)->getObjects($criteria) as $moderator) { + $this->moderated[(int) $moderator->getVar('forum_id', 'e')] = true; + } + } + return isset($this->moderated[$forumId]); + } + + /** + * Every forum, switched off or not, by id in index order + * + * @return array + */ + public function getAllForums(): array { + if ($this->forums === null) { + $criteria = new icms_db_criteria_Compo(); + $criteria->setSort('weight'); + $criteria->setOrder('ASC'); + $this->forums = icms_getModuleHandler('forum', IMFORUM_DIRNAME)->getObjects($criteria, true); + } + return $this->forums; + } + + /** + * The forums that appear in lists + * + * @return array + */ + public function getVisibleForums(): array { + return array_filter($this->getAllForums(), fn (mod_imforum_Forum $forum): bool => $this->canSeeForum($forum)); + } + + /** + * The forums whose topics can be opened + * + * @return list + */ + public function getReadableForumIds(): array { + $ids = []; + foreach ($this->getAllForums() as $forumId => $forum) { + if ($this->canReadForum($forum)) { + $ids[] = (int) $forumId; + } + } + return $ids; + } + + public function getForum(int $forumId): ?mod_imforum_Forum { + return $this->getAllForums()[$forumId] ?? null; + } + + private function has(string $permission, int $itemId): bool { + if ($this->webmaster) { + return true; + } + if (!isset($this->granted[$permission])) { + $handler = icms_getModuleHandler('forum', IMFORUM_DIRNAME); + $moduleId = (int) $handler->getModuleInfo()->getVar('mid'); + $ids = icms::handler('icms_member_groupperm')->getItemIds($permission, $this->groups, $moduleId); + $this->granted[$permission] = array_fill_keys(array_map('intval', $ids), true); + } + return isset($this->granted[$permission][$itemId]); + } +} diff --git a/src/class/Post.php b/src/class/Post.php index 1ac9b3c..40273c7 100644 --- a/src/class/Post.php +++ b/src/class/Post.php @@ -52,6 +52,78 @@ public function __construct(mod_imforum_PostHandler $handler) { } } + /** The text is withheld until the karma service has allowed this reader to see it */ + private bool $unlocked = false; + + private string $lock = ''; + + /** + * Does the author ask for karma or a reply before others can read it? + */ + public function isProtected(): bool { + return (int) $this->getVar('post_karma', 'e') > 0 || (int) $this->getVar('require_reply', 'e') === 1; + } + + public function unlock(): void { + $this->unlocked = true; + $this->lock = ''; + } + + /** + * Remember why the reader may not see the text, for the notice that replaces it + */ + public function setLock(string $lock): void { + $this->unlocked = false; + $this->lock = $lock; + } + + /** + * What the templates need + * + * Every text value is ready for output. A protected post carries no text + * until mod_imforum_KarmaService has unlocked it, so a template that + * forgets the check cannot leak the post. + * + * @return array + */ + public function toArray() { + $locked = $this->isProtected() && !$this->unlocked; + return [ + 'post_id' => (int) $this->id(), + 'topic_id' => (int) $this->getVar('topic_id', 'e'), + 'forum_id' => (int) $this->getVar('forum_id', 'e'), + 'pid' => (int) $this->getVar('pid', 'e'), + 'uid' => (int) $this->getVar('uid', 'e'), + 'poster_name' => $this->getVar('poster_name'), + 'post_time' => (int) $this->getVar('post_time', 'e'), + 'subject' => $this->getVar('subject'), + 'icon' => $this->getVar('icon'), + 'attachsig' => (int) $this->getVar('attachsig', 'e'), + 'approved' => (int) $this->getVar('approved', 'e'), + 'locked' => $locked, + 'lock' => $locked ? $this->lock : '', + 'text' => $locked ? '' : $this->getFormattedText(), + 'edits' => $this->getEditHistory(), + ]; + } + + /** + * The text as shown: HTML through the purifier, otherwise the text filter with the post's own switches + */ + private function getFormattedText(): string { + $text = (string) $this->getVar('post_text', 'n'); + if ((int) $this->getVar('dohtml', 'e') === 1) { + return (string) icms_core_DataFilter::checkVar($text, 'html', 'output'); + } + return (string) icms_core_DataFilter::filterTextareaDisplay( + $text, + (int) $this->getVar('dosmiley', 'e'), + (int) $this->getVar('doxcode', 'e'), + (int) $this->getVar('doimage', 'e'), + (int) $this->getVar('dobr', 'e') + ); + } + /** * Earlier edits, oldest first * diff --git a/src/class/PostHandler.php b/src/class/PostHandler.php index 176a9b2..59c0ea7 100644 --- a/src/class/PostHandler.php +++ b/src/class/PostHandler.php @@ -50,6 +50,169 @@ private function deletePostChildren(array $postIds): void { icms_getModuleHandler('report', IMFORUM_DIRNAME)->deleteAll($byPost); } + private function approvedIn(int $topicId): icms_db_criteria_Compo { + $criteria = new icms_db_criteria_Compo(new icms_db_criteria_Item('topic_id', $topicId)); + $criteria->add(new icms_db_criteria_Item('approved', 1)); + return $criteria; + } + + /** + * One page of the approved posts of a topic, oldest first + * + * @return array by post id + */ + public function getPage(int $topicId, int $start, int $limit): array { + $criteria = $this->approvedIn($topicId); + $criteria->setSort('post_id'); + $criteria->setOrder('ASC'); + $criteria->setStart($start); + $criteria->setLimit($limit); + return $this->getObjects($criteria, true); + } + + public function countApproved(int $topicId): int { + return (int) $this->getCount($this->approvedIn($topicId)); + } + + /** + * The approved posts of a topic in thread order: every reply under the post it answers + * + * A reply whose parent is missing or not approved counts as a first level + * post, so nothing disappears from the thread. + * + * @return list + */ + public function getThreadOrder(int $topicId): array { + $parentOf = []; + $result = $this->db->queryF("SELECT post_id, pid FROM {$this->table} WHERE topic_id = $topicId AND approved = 1 ORDER BY post_id"); + while ($result && ($row = $this->db->fetchRow($result))) { + $parentOf[(int) $row[0]] = (int) $row[1]; + } + + $children = []; + foreach ($parentOf as $postId => $parent) { + $children[isset($parentOf[$parent]) && $parent !== $postId ? $parent : 0][] = $postId; + } + + $order = []; + $seen = []; + $stack = []; + foreach (array_reverse($children[0] ?? []) as $root) { + $stack[] = [$root, 0]; + } + while ($stack) { + [$postId, $depth] = array_pop($stack); + if (isset($seen[$postId])) { + continue; + } + $seen[$postId] = true; + $order[] = ['post_id' => $postId, 'depth' => $depth]; + foreach (array_reverse($children[$postId] ?? []) as $child) { + $stack[] = [$child, $depth + 1]; + } + } + // posts that only point at each other form a loop without a root + foreach (array_diff_key($parentOf, $seen) as $postId => $parent) { + $order[] = ['post_id' => $postId, 'depth' => 0]; + } + return $order; + } + + /** + * Posts by id, in the order of the ids; unknown ids are left out + * + * @param list $postIds + * @return array + */ + public function getByIds(array $postIds): array { + $postIds = array_values(array_filter(array_map('intval', $postIds))); + if (!$postIds) { + return []; + } + $found = $this->getObjects(new icms_db_criteria_Item('post_id', '(' . implode(',', $postIds) . ')', 'IN'), true); + $ordered = []; + foreach ($postIds as $postId) { + if (isset($found[$postId])) { + $ordered[$postId] = $found[$postId]; + } + } + return $ordered; + } + + /** + * Number of approved posts per member + * + * @param list $uids + * @return array uid => posts; members without posts are left out + */ + public function countByUsers(array $uids): array { + $uids = array_values(array_filter(array_map('intval', $uids), static fn (int $uid): bool => $uid > 0)); + if (!$uids) { + return []; + } + $counts = []; + $result = $this->db->queryF('SELECT uid, COUNT(*) FROM ' . $this->table . ' WHERE approved = 1 AND uid IN (' . implode(',', $uids) . ') GROUP BY uid'); + while ($result && ($row = $this->db->fetchRow($result))) { + $counts[(int) $row[0]] = (int) $row[1]; + } + return $counts; + } + + /** + * The members with the most approved posts + * + * @param list $forumIds the forums the reader may open + * @return list + */ + public function getTopPosters(array $forumIds, int $limit): array { + $forumIds = array_values(array_filter(array_map('intval', $forumIds))); + if (!$forumIds) { + return []; + } + $top = []; + $result = $this->db->queryF('SELECT uid, COUNT(*) AS n FROM ' . $this->table . ' WHERE approved = 1 AND uid > 0 AND forum_id IN (' . implode(',', $forumIds) . ') GROUP BY uid ORDER BY n DESC, uid ASC LIMIT ' . max(1, $limit)); + while ($result && ($row = $this->db->fetchRow($result))) { + $top[] = ['uid' => (int) $row[0], 'posts' => (int) $row[1]]; + } + return $top; + } + + public function hasPosted(int $topicId, int $uid): bool { + $criteria = $this->approvedIn($topicId); + $criteria->add(new icms_db_criteria_Item('uid', $uid)); + return $uid > 0 && $this->getCount($criteria) > 0; + } + + /** + * Who wrote what and when, without the texts; for the lists of topics + * + * @param list $postIds + * @return array + */ + public function getSummaries(array $postIds): array { + $postIds = array_values(array_filter(array_map('intval', $postIds))); + $summaries = []; + foreach (array_chunk($postIds, 500) as $chunk) { + $result = $this->db->queryF('SELECT post_id, topic_id, uid, poster_name, post_time, subject FROM ' . $this->table . ' WHERE post_id IN (' . implode(',', $chunk) . ')'); + while ($result && ($row = $this->db->fetchRow($result))) { + $summaries[(int) $row[0]] = [ + 'post_id' => (int) $row[0], 'topic_id' => (int) $row[1], 'uid' => (int) $row[2], + 'poster_name' => (string) $row[3], 'post_time' => (int) $row[4], 'subject' => (string) $row[5], + ]; + } + } + return $summaries; + } + + /** + * How many approved posts of a topic come before a post + */ + public function getPosition(int $topicId, int $postId): int { + $criteria = $this->approvedIn($topicId); + $criteria->add(new icms_db_criteria_Item('post_id', $postId, '<')); + return (int) $this->getCount($criteria); + } + protected function beforeInsert(mod_imforum_Post $post): bool { if ((int) $post->getVar('post_time', 'e') === 0) { $post->setVar('post_time', time()); diff --git a/src/class/PosterInfo.php b/src/class/PosterInfo.php new file mode 100644 index 0000000..f16fdae --- /dev/null +++ b/src/class/PosterInfo.php @@ -0,0 +1,67 @@ + $uids + * @return array> by member id; text values are ready for output + */ + public static function load(array $uids, int $onlineMinutes = 15): array { + $uids = array_values(array_unique(array_filter(array_map('intval', $uids), static fn (int $uid): bool => $uid > 0))); + if (!$uids) { + return []; + } + + $members = icms::handler('icms_member'); + $users = $members->getUsers(new icms_db_criteria_Item('uid', '(' . implode(',', $uids) . ')', 'IN'), true); + $counts = icms_getModuleHandler('post', IMFORUM_DIRNAME)->countByUsers($uids); + $online = icms_getModuleHandler('online', IMFORUM_DIRNAME)->getOnlineMembers($uids, $onlineMinutes); + $groupNames = $members->getGroupList(); + + $info = []; + foreach ($users as $uid => $user) { + $uid = (int) $uid; + $rank = $user->rank(); + $groups = []; + foreach ($user->getGroups() as $groupId) { + if (!in_array((int) $groupId, [(int) ICMS_GROUP_USERS, (int) ICMS_GROUP_ANONYMOUS], true) && isset($groupNames[$groupId])) { + $groups[] = mod_imforum_View::escape((string) $groupNames[$groupId]); + } + } + $avatar = (string) $user->getVar('user_avatar', 'n'); + $info[$uid] = [ + 'uid' => $uid, + 'name' => mod_imforum_View::escape((string) $user->getVar('uname', 'n')), + 'url' => mod_imforum_View::escape(ICMS_URL . '/userinfo.php?uid=' . $uid), + 'avatar' => ($avatar !== '' && $avatar !== 'blank.gif') ? mod_imforum_View::escape(ICMS_UPLOAD_URL . '/' . $avatar) : '', + 'rank_title' => mod_imforum_View::escape((string) ($rank['title'] ?? '')), + 'rank_image' => !empty($rank['title']) ? mod_imforum_View::escape((string) ($rank['image'] ?? '')) : '', + 'groups' => $groups, + 'posts' => $counts[$uid] ?? 0, + 'regdate' => mod_imforum_View::time((int) $user->getVar('user_regdate', 'n')), + 'signature' => self::formatSignature((string) $user->getVar('user_sig', 'n')), + 'online' => isset($online[$uid]), + ]; + } + return $info; + } + + private static function formatSignature(string $signature): string { + return trim($signature) === '' ? '' : (string) icms_core_DataFilter::filterTextareaDisplay($signature, 1, 1, 0, 1); + } +} diff --git a/src/class/ReadTracker.php b/src/class/ReadTracker.php new file mode 100644 index 0000000..dd1b2d7 --- /dev/null +++ b/src/class/ReadTracker.php @@ -0,0 +1,86 @@ +uid = $uid; + $this->marks = icms_getModuleHandler('readmark', IMFORUM_DIRNAME); + } + + public function isTracking(): bool { + return $this->uid > 0; + } + + /** + * Which of these topics have posts the member has not seen + * + * @param array $topics by topic id + * @return array topic ids + */ + public function getUnreadTopics(array $topics): array { + if (!$this->isTracking() || !$topics) { + return []; + } + $topicReads = $this->marks->getLastRead(mod_imforum_ReadmarkHandler::TYPE_TOPIC, $this->uid, array_keys($topics)); + $forumIds = array_unique(array_column($topics, 'forum_id')); + $forumReads = $this->marks->getLastRead(mod_imforum_ReadmarkHandler::TYPE_FORUM, $this->uid, $forumIds); + + $unread = []; + foreach ($topics as $topicId => $topic) { + $seen = max($topicReads[$topicId] ?? 0, $forumReads[$topic['forum_id']] ?? 0); + if ($topic['last_post_id'] > $seen) { + $unread[$topicId] = true; + } + } + return $unread; + } + + /** + * @param list $forumIds + * @return array forum id => unread topics + */ + public function countUnreadByForum(array $forumIds): array { + return $this->marks->countUnreadByForum($this->uid, $forumIds); + } + + public function markTopicRead(int $topicId, int $upToPostId): void { + if (!$this->isTracking() || $upToPostId < 1) { + return; + } + $seen = $this->marks->getLastRead(mod_imforum_ReadmarkHandler::TYPE_TOPIC, $this->uid, [$topicId])[$topicId] ?? 0; + if ($upToPostId > $seen) { + $this->marks->markRead(mod_imforum_ReadmarkHandler::TYPE_TOPIC, $this->uid, $topicId, $upToPostId); + } + } + + /** + * Mark everything in a forum as read, and forget the marks on its topics + */ + public function markForumRead(int $forumId, int $lastPostId): void { + if (!$this->isTracking()) { + return; + } + $this->marks->markRead(mod_imforum_ReadmarkHandler::TYPE_FORUM, $this->uid, $forumId, $lastPostId); + $this->marks->deleteTopicMarksInForum($this->uid, $forumId); + } +} diff --git a/src/class/ReadmarkHandler.php b/src/class/ReadmarkHandler.php index 169cc90..afdcb45 100644 --- a/src/class/ReadmarkHandler.php +++ b/src/class/ReadmarkHandler.php @@ -77,6 +77,57 @@ public function purgeOlderThan(int $time): bool { return (bool) $this->db->queryF(sprintf('DELETE FROM %s WHERE read_time < %d', $this->table, $time)); } + /** + * Drop a member's marks on the topics of a forum, once the forum itself is marked + */ + public function deleteTopicMarksInForum(int $uid, int $forumId): bool { + $topics = $this->db->prefix(IMFORUM_DIRNAME . '_topic'); + return (bool) $this->db->queryF(sprintf( + 'DELETE FROM %s WHERE read_type = %d AND uid = %d AND item_id IN (SELECT topic_id FROM %s WHERE forum_id = %d)', + $this->table, self::TYPE_TOPIC, $uid, $topics, $forumId + )); + } + + /** + * SQL pieces that select the topics a member has not read to the end + * + * A topic is unread when its last post is newer than both the member's + * mark on the topic and the mark on its forum ("mark all as read"). The + * topic table must be aliased t. + * + * @return array{joins: string, where: string} + */ + public function getUnreadSql(int $uid): array { + $read = $this->table; + return [ + 'joins' => " LEFT JOIN $read rt ON rt.read_type = " . self::TYPE_TOPIC . " AND rt.uid = $uid AND rt.item_id = t.topic_id" + . " LEFT JOIN $read rf ON rf.read_type = " . self::TYPE_FORUM . " AND rf.uid = $uid AND rf.item_id = t.forum_id", + 'where' => ' AND t.topic_last_post_id > GREATEST(COALESCE(rt.post_id, 0), COALESCE(rf.post_id, 0))', + ]; + } + + /** + * Unread topics per forum + * + * @param list $forumIds + * @return array forum id => unread topics; forums without any are left out + */ + public function countUnreadByForum(int $uid, array $forumIds): array { + $forumIds = array_values(array_filter(array_map('intval', $forumIds))); + if ($uid < 1 || !$forumIds) { + return []; + } + $unread = $this->getUnreadSql($uid); + $sql = 'SELECT t.forum_id, COUNT(*) FROM ' . $this->db->prefix(IMFORUM_DIRNAME . '_topic') . ' t' . $unread['joins'] + . ' WHERE t.approved = 1 AND t.forum_id IN (' . implode(',', $forumIds) . ')' . $unread['where'] . ' GROUP BY t.forum_id'; + $counts = []; + $result = $this->db->queryF($sql); + while ($result && ($row = $this->db->fetchRow($result))) { + $counts[(int) $row[0]] = (int) $row[1]; + } + return $counts; + } + private function criteriaFor(int $type, int $uid, int $itemId): icms_db_criteria_Compo { $criteria = new icms_db_criteria_Compo(new icms_db_criteria_Item('read_type', $type)); $criteria->add(new icms_db_criteria_Item('uid', $uid)); diff --git a/src/class/Settings.php b/src/class/Settings.php new file mode 100644 index 0000000..d84c7c4 --- /dev/null +++ b/src/class/Settings.php @@ -0,0 +1,63 @@ + 20, + 'posts_per_page' => 10, + 'default_view' => 'flat', + 'show_online' => 1, + 'online_minutes' => 15, + 'rss_items' => 20, + ]; + + /** @var array|null */ + private static ?array $values = null; + + public static function get(string $name): mixed { + if (self::$values === null) { + self::$values = self::DEFAULTS; + $module = icms::handler('icms_module')->getByDirname(IMFORUM_DIRNAME); + if (is_object($module)) { + $stored = icms::handler('icms_config')->getConfigsByCat(0, (int) $module->getVar('mid')); + foreach (self::DEFAULTS as $key => $default) { + if (isset($stored[$key])) { + self::$values[$key] = is_int($default) ? (int) $stored[$key] : (string) $stored[$key]; + } + } + } + } + return self::$values[$name] ?? self::DEFAULTS[$name] ?? null; + } + + /** + * Number settings are never below one, a page size of zero would show nothing + */ + public static function getCount(string $name): int { + return max(1, (int) self::get($name)); + } + + /** + * For tests + * + * @param array|null $values + */ + public static function override(?array $values): void { + self::$values = $values === null ? null : $values + self::DEFAULTS; + } +} diff --git a/src/class/TopicHandler.php b/src/class/TopicHandler.php index 9d7250f..a1eb181 100644 --- a/src/class/TopicHandler.php +++ b/src/class/TopicHandler.php @@ -94,6 +94,121 @@ public function moveToForum(int $topicId, int $forumId): bool { return $forumHandler->synchronise($oldForumId) && $ok; } + /** + * One page of the approved topics of a forum: sticky topics first, then by last post + * + * @return array by topic id + */ + public function getForumTopics(int $forumId, int $start, int $limit): array { + $criteria = $this->approvedInForum($forumId); + $criteria->setSort('topic_sticky DESC, topic_last_post_id'); + $criteria->setOrder('DESC'); + $criteria->setStart($start); + $criteria->setLimit($limit); + return $this->getObjects($criteria, true); + } + + public function countForumTopics(int $forumId): int { + return (int) $this->getCount($this->approvedInForum($forumId)); + } + + private function approvedInForum(int $forumId): icms_db_criteria_Compo { + $criteria = new icms_db_criteria_Compo(new icms_db_criteria_Item('forum_id', $forumId)); + $criteria->add(new icms_db_criteria_Item('approved', 1)); + return $criteria; + } + + /** + * Topics by id, in the order of the ids; unknown ids are left out + * + * @param list $topicIds + * @return array + */ + public function getByIds(array $topicIds): array { + $topicIds = array_values(array_filter(array_map('intval', $topicIds))); + if (!$topicIds) { + return []; + } + $found = $this->getObjects(new icms_db_criteria_Item('topic_id', '(' . implode(',', $topicIds) . ')', 'IN'), true); + $ordered = []; + foreach ($topicIds as $topicId) { + if (isset($found[$topicId])) { + $ordered[$topicId] = $found[$topicId]; + } + } + return $ordered; + } + + /** + * Topics over several forums, newest activity first + * + * @param list $forumIds the forums to look in; already limited to what the reader may open + * @param string $filter '' for all, 'unread' for what the member has not read, 'digest' for featured topics + * @return array{ids: list, total: int} + */ + public function findRecent(array $forumIds, int $start, int $limit, string $filter = '', int $uid = 0): array { + $forumIds = array_values(array_filter(array_map('intval', $forumIds))); + if (!$forumIds) { + return ['ids' => [], 'total' => 0]; + } + $joins = ''; + $where = ' WHERE t.approved = 1 AND t.forum_id IN (' . implode(',', $forumIds) . ')'; + if ($filter === 'digest') { + $where .= ' AND t.topic_digest = 1'; + } elseif ($filter === 'unread') { + if ($uid < 1) { + return ['ids' => [], 'total' => 0]; + } + $unread = icms_getModuleHandler('readmark', IMFORUM_DIRNAME)->getUnreadSql($uid); + $joins = $unread['joins']; + $where .= $unread['where']; + } + + $total = 0; + $result = $this->db->queryF("SELECT COUNT(*) FROM {$this->table} t$joins$where"); + if ($result && ($row = $this->db->fetchRow($result))) { + $total = (int) $row[0]; + } + + $ids = []; + $result = $this->db->queryF("SELECT t.topic_id FROM {$this->table} t$joins$where ORDER BY t.topic_last_post_id DESC LIMIT " . max(0, $start) . ', ' . max(1, $limit)); + while ($result && ($row = $this->db->fetchRow($result))) { + $ids[] = (int) $row[0]; + } + return ['ids' => $ids, 'total' => $total]; + } + + /** + * The topics with the most replies among those that saw a new post since a moment + * + * @param list $forumIds the forums the reader may open + * @return list topic ids, busiest first + */ + public function findHot(array $forumIds, int $since, int $limit): array { + $forumIds = array_values(array_filter(array_map('intval', $forumIds))); + if (!$forumIds) { + return []; + } + $posts = $this->db->prefix(IMFORUM_DIRNAME . '_post'); + $ids = []; + $result = $this->db->queryF( + "SELECT t.topic_id FROM {$this->table} t JOIN $posts p ON p.post_id = t.topic_last_post_id" + . ' WHERE t.approved = 1 AND t.topic_replies > 0 AND t.forum_id IN (' . implode(',', $forumIds) . ') AND p.post_time >= ' . max(0, $since) + . ' ORDER BY t.topic_replies DESC, t.topic_last_post_id DESC LIMIT ' . max(1, $limit) + ); + while ($result && ($row = $this->db->fetchRow($result))) { + $ids[] = (int) $row[0]; + } + return $ids; + } + + /** + * Count a view + */ + public function incrementViews(int $topicId): bool { + return (bool) $this->db->queryF("UPDATE {$this->table} SET topic_views = topic_views + 1 WHERE topic_id = $topicId"); + } + protected function beforeInsert(mod_imforum_Topic $topic): bool { if ((int) $topic->getVar('topic_time', 'e') === 0) { $topic->setVar('topic_time', time()); diff --git a/src/class/TopicList.php b/src/class/TopicList.php new file mode 100644 index 0000000..df48410 --- /dev/null +++ b/src/class/TopicList.php @@ -0,0 +1,83 @@ + $topics by topic id + * @param array $forums by forum id; the forums the topics are in + * @return list> every text is ready for output + */ + public static function rows(array $topics, array $forums, mod_imforum_ReadTracker $tracker, bool $showForum): array { + if (!$topics) { + return []; + } + $lastPostIds = []; + $progress = []; + foreach ($topics as $topicId => $topic) { + $lastPostIds[] = (int) $topic->getVar('topic_last_post_id', 'e'); + $progress[$topicId] = [ + 'forum_id' => (int) $topic->getVar('forum_id', 'e'), + 'last_post_id' => (int) $topic->getVar('topic_last_post_id', 'e'), + ]; + } + $summaries = icms_getModuleHandler('post', IMFORUM_DIRNAME)->getSummaries($lastPostIds); + $unread = $tracker->getUnreadTopics($progress); + $perPage = mod_imforum_Settings::getCount('posts_per_page'); + + $rows = []; + foreach ($topics as $topicId => $topic) { + $forum = $forums[(int) $topic->getVar('forum_id', 'e')] ?? null; + $replies = (int) $topic->getVar('topic_replies', 'e'); + $lastPostId = (int) $topic->getVar('topic_last_post_id', 'e'); + $last = $summaries[$lastPostId] ?? null; + + $pages = []; + $pageCount = (int) ceil(($replies + 1) / $perPage); + for ($page = 2; $page <= min($pageCount, self::PAGE_LINKS); $page++) { + $pages[] = ['number' => $page, 'url' => mod_imforum_View::link('topic', ['topic' => $topicId, 'start' => ($page - 1) * $perPage])]; + } + + $rows[] = [ + 'id' => $topicId, + 'url' => mod_imforum_View::link('topic', ['topic' => $topicId]), + 'title' => $topic->getVar('topic_title'), + 'poster' => mod_imforum_View::poster((int) $topic->getVar('topic_poster', 'e'), (string) $topic->getVar('poster_name', 'n')), + 'time' => mod_imforum_View::time((int) $topic->getVar('topic_time', 'e')), + 'replies' => $replies, + 'views' => (int) $topic->getVar('topic_views', 'e'), + 'sticky' => (int) $topic->getVar('topic_sticky', 'e') === 1, + 'digest' => (int) $topic->getVar('topic_digest', 'e') === 1, + 'locked' => $topic->isLocked(), + 'hot' => $forum !== null && $replies >= max(1, (int) $forum->getVar('hot_threshold', 'e')), + 'unread' => isset($unread[$topicId]), + 'pages' => count($pages) ? $pages : [], + 'more_pages' => $pageCount > self::PAGE_LINKS, + 'last_url' => mod_imforum_View::link('topic', ['topic' => $topicId, 'post' => $lastPostId]) . '#post-' . $lastPostId, + 'last' => $last === null ? null : [ + 'poster' => mod_imforum_View::poster($last['uid'], $last['poster_name']), + 'time' => mod_imforum_View::time($last['post_time']), + ], + 'forum' => ($showForum && $forum !== null) ? [ + 'name' => $forum->getVar('forum_name'), + 'url' => mod_imforum_View::link('forum', ['forum' => (int) $forum->id()]), + ] : null, + ]; + } + return $rows; + } +} diff --git a/src/class/View.php b/src/class/View.php new file mode 100644 index 0000000..1000089 --- /dev/null +++ b/src/class/View.php @@ -0,0 +1,137 @@ + $query + */ + public static function url(string $page, array $query = []): string { + $url = IMFORUM_URL . $page . '.php'; + $query = array_filter($query, static fn ($value): bool => $value !== '' && $value !== 0); + return $query ? $url . '?' . http_build_query($query, '', '&') : $url; + } + + /** + * The same address, ready to print in an attribute + * + * @param array $query + */ + public static function link(string $page, array $query = []): string { + return self::escape(self::url($page, $query)); + } + + /** + * The author of a post or topic: a link to the member, or the name a guest gave + */ + public static function poster(int $uid, string $name): string { + global $icmsConfig; + if ($uid > 0) { + return (string) icms_member_user_Handler::getUserLink($uid); + } + return self::escape(trim($name) !== '' ? trim($name) : (string) ($icmsConfig['anonymous'] ?? '')); + } + + /** + * The list of visitors for the templates, names as links + * + * @param array{members: list, guests: int} $snapshot + * @return array{members: list, member_count: int, guests: int} + */ + public static function online(array $snapshot): array { + $members = []; + foreach ($snapshot['members'] as $member) { + $members[] = [ + 'url' => self::escape(ICMS_URL . '/userinfo.php?uid=' . $member['uid']), + 'name' => $member['uname'], + ]; + } + return ['members' => $members, 'member_count' => count($members), 'guests' => $snapshot['guests']]; + } + + public static function escape(string $text): string { + return htmlspecialchars($text, ENT_QUOTES, 'UTF-8'); + } + + public static function time(int $timestamp): string { + return $timestamp > 0 ? (string) formatTimestamp($timestamp, 'm') : ''; + } + + /** + * A positive number from the request, 0 when it is missing or not a number + */ + public static function intParam(string $name): int { + $value = $_GET[$name] ?? 0; + return is_scalar($value) ? max(0, (int) $value) : 0; + } + + /** + * Previous, next and a window of page numbers + * + * The core's page navigation prints $_SERVER['PHP_SELF'] unescaped, which a + * visitor controls on servers that accept a path after the script name. + * + * @param array $query the other parameters of the page + * @return string HTML, empty when there is one page + */ + public static function pager(string $page, array $query, int $total, int $perPage, int $start, string $startName = 'start'): string { + $perPage = max(1, $perPage); + $pages = (int) ceil($total / $perPage); + if ($pages < 2) { + return ''; + } + $current = (int) floor($start / $perPage) + 1; + $link = fn (int $number, string $label, string $class = ''): string => '' . $label . ''; + + $out = []; + if ($current > 1) { + $out[] = $link($current - 1, '«', 'imforum-prev'); + } + $last = 0; + for ($number = 1; $number <= $pages; $number++) { + if ($number !== 1 && $number !== $pages && abs($number - $current) > 3) { + continue; + } + if ($number - $last > 1) { + $out[] = '…'; + } + $out[] = $number === $current ? '' . $number . '' : $link($number, (string) $number); + $last = $number; + } + if ($current < $pages) { + $out[] = $link($current + 1, '»', 'imforum-next'); + } + return ''; + } + + /** + * The path above a page: [['title' => escaped, 'url' => escaped or '']] + * + * @param list $trail raw title and optional raw url + * @return list + */ + public static function breadcrumb(array $trail): array { + $crumbs = [['title' => self::escape(_MD_IMFORUM_TITLE), 'url' => self::link('index')]]; + foreach ($trail as $step) { + $crumbs[] = ['title' => self::escape($step[0]), 'url' => isset($step[1]) ? self::escape($step[1]) : '']; + } + return $crumbs; + } +} diff --git a/src/forum.php b/src/forum.php new file mode 100644 index 0000000..1d5d20f --- /dev/null +++ b/src/forum.php @@ -0,0 +1,103 @@ +getForum($forumId); +if ($forum === null || !$permissions->canReadForum($forum)) { + redirect_header(mod_imforum_View::url('index'), 3, _NOPERM); + exit; +} + +$tracker = new mod_imforum_ReadTracker($permissions->getUid()); +$topicHandler = icms_getModuleHandler('topic', IMFORUM_DIRNAME); + +// "Mark all as read" changes data, so it takes a POST with a token +if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['op'] ?? '') === 'markread') { + if (!icms::$security->check()) { + redirect_header(mod_imforum_View::url('forum', ['forum' => $forumId]), 3, implode('
', icms::$security->getErrors())); + exit; + } + $tracker->markForumRead($forumId, (int) $forum->getVar('forum_last_post_id', 'e')); + redirect_header(mod_imforum_View::url('forum', ['forum' => $forumId]), 2, _MD_IMFORUM_MARKED_READ); + exit; +} + +$xoopsOption['template_main'] = 'imforum_forum.html'; +include_once ICMS_ROOT_PATH . '/header.php'; +global $icmsTpl, $xoTheme; +$xoTheme->addStylesheet(IMFORUM_URL . 'assets/css/imforum.css'); + +$perPage = mod_imforum_Settings::getCount('topics_per_page'); +$start = mod_imforum_View::intParam('start'); +$total = $topicHandler->countForumTopics($forumId); +$start = min($start, max(0, (int) (ceil($total / $perPage) - 1) * $perPage)); +$rows = mod_imforum_TopicList::rows($topicHandler->getForumTopics($forumId, $start, $perPage), [$forumId => $forum], $tracker, false); + +// subforums the visitor may see +$visible = $permissions->getVisibleForums(); +$unread = $tracker->countUnreadByForum(array_keys($visible)); +$subforums = []; +foreach ($visible as $child) { + if ((int) $child->getVar('parent_forum', 'e') === $forumId) { + $subforums[] = [ + 'url' => mod_imforum_View::link('forum', ['forum' => (int) $child->id()]), + 'name' => $child->getVar('forum_name'), + 'description' => $child->getVar('forum_desc'), + 'topics' => (int) $child->getVar('forum_topics', 'e'), + 'posts' => (int) $child->getVar('forum_posts', 'e'), + 'unread' => $unread[(int) $child->id()] ?? 0, + ]; + } +} + +// the path above this forum +$trail = [[$forum->getVar('forum_name', 'n')]]; +for ($parent = (int) $forum->getVar('parent_forum', 'e'), $guard = 0; $parent > 0 && $guard < 10; $guard++) { + $parentForum = $permissions->getForum($parent); + if ($parentForum === null || !$permissions->canSeeForum($parentForum)) { + break; + } + array_unshift($trail, [$parentForum->getVar('forum_name', 'n'), mod_imforum_View::url('forum', ['forum' => $parent])]); + $parent = (int) $parentForum->getVar('parent_forum', 'e'); +} + +$moderators = []; +foreach (icms_getModuleHandler('moderator', IMFORUM_DIRNAME)->getModeratorIds($forumId) as $uid) { + $moderators[] = mod_imforum_View::poster($uid, ''); +} + +$online = icms_getModuleHandler('online', IMFORUM_DIRNAME); +$showOnline = (int) mod_imforum_Settings::get('show_online') === 1; +$minutes = mod_imforum_Settings::getCount('online_minutes'); +if ($showOnline) { + $online->track($permissions->getUid(), icms::$user ? (string) icms::$user->getVar('uname', 'n') : '', (string) ($_SERVER['REMOTE_ADDR'] ?? ''), $forumId, 0, $minutes); +} + +$icmsTpl->assign('imforum_breadcrumb', mod_imforum_View::breadcrumb($trail)); +$icmsTpl->assign('imforum_forum', [ + 'id' => $forumId, + 'name' => $forum->getVar('forum_name'), + 'description' => $forum->getVar('forum_desc'), + 'inactive' => (int) $forum->getVar('forum_active', 'e') === 0, +]); +$icmsTpl->assign('imforum_subforums', $subforums); +$icmsTpl->assign('imforum_topics', $rows); +$icmsTpl->assign('imforum_moderators', $moderators); +$icmsTpl->assign('imforum_pager', mod_imforum_View::pager('forum', ['forum' => $forumId], $total, $perPage, $start)); +$icmsTpl->assign('imforum_can_mark_read', $tracker->isTracking()); +$icmsTpl->assign('imforum_token', icms::$security->getTokenHTML()); +$icmsTpl->assign('imforum_form_action', mod_imforum_View::link('forum', ['forum' => $forumId])); +$icmsTpl->assign('imforum_online', $showOnline ? mod_imforum_View::online($online->getSnapshot($forumId, 0, $minutes)) : null); + +include_once ICMS_ROOT_PATH . '/footer.php'; diff --git a/src/icms_version.php b/src/icms_version.php index fdac45e..5a7921a 100644 --- a/src/icms_version.php +++ b/src/icms_version.php @@ -56,7 +56,8 @@ 'adminmenu' => 'admin/menu.php', 'hasMain' => 1, - 'hasSearch' => 0, + 'hasSearch' => 1, + 'search' => ['file' => 'include/search.inc.php', 'func' => 'imforum_search'], 'hasComments' => 0, 'hasNotification' => 0, @@ -64,10 +65,96 @@ ['file' => 'imforum_index.html', 'description' => 'Forum index'], ['file' => 'imforum_admin_index.html', 'description' => 'Administration index'], ['file' => 'imforum_admin.html', 'description' => 'Administration page'], + ['file' => 'imforum_forum.html', 'description' => 'Forum with its topics'], + ['file' => 'imforum_topic.html', 'description' => 'Topic with its posts'], + ['file' => 'imforum_viewall.html', 'description' => 'Topics of all forums'], + ['file' => 'imforum_archive.html', 'description' => 'Archived topics'], + ['file' => 'imforum_breadcrumb.html', 'description' => 'Path above a page'], + ['file' => 'imforum_topiclist.html', 'description' => 'List of topics'], + ['file' => 'imforum_online.html', 'description' => 'Who is online'], ], - 'blocks' => [], - // No 'config' key until the module has preferences: icms_module_Object sets - // hasconfig for any array, even an empty one, and the admin menu then - // shows a Preferences link that ends on the system preferences. + 'blocks' => [ + [ + 'file' => 'imforum_blocks.php', + 'name' => _MI_IMFORUM_BLOCK_RECENT, + 'description' => _MI_IMFORUM_BLOCK_RECENT_DSC, + 'show_func' => 'imforum_block_recent', + 'edit_func' => 'imforum_block_edit_recent', + 'options' => '10', + 'template' => 'imforum_block_topics.html', + ], + [ + 'file' => 'imforum_blocks.php', + 'name' => _MI_IMFORUM_BLOCK_HOT, + 'description' => _MI_IMFORUM_BLOCK_HOT_DSC, + 'show_func' => 'imforum_block_hot', + 'edit_func' => 'imforum_block_edit_hot', + 'options' => '10|30', + 'template' => 'imforum_block_topics.html', + ], + [ + 'file' => 'imforum_blocks.php', + 'name' => _MI_IMFORUM_BLOCK_TOPPOSTERS, + 'description' => _MI_IMFORUM_BLOCK_TOPPOSTERS_DSC, + 'show_func' => 'imforum_block_topposters', + 'edit_func' => 'imforum_block_edit_recent', + 'options' => '10', + 'template' => 'imforum_block_topposters.html', + ], + ], + + // Preferences. The first one creates the config array, which is what turns + // on the Preferences link of the module: do not declare an empty 'config'. + 'config' => [ + [ + 'name' => 'topics_per_page', + 'title' => '_MI_IMFORUM_CFG_TOPICS_PER_PAGE', + 'description' => '_MI_IMFORUM_CFG_TOPICS_PER_PAGE_DSC', + 'formtype' => 'textbox', + 'valuetype' => 'int', + 'default' => 20, + ], + [ + 'name' => 'posts_per_page', + 'title' => '_MI_IMFORUM_CFG_POSTS_PER_PAGE', + 'description' => '_MI_IMFORUM_CFG_POSTS_PER_PAGE_DSC', + 'formtype' => 'textbox', + 'valuetype' => 'int', + 'default' => 10, + ], + [ + 'name' => 'default_view', + 'title' => '_MI_IMFORUM_CFG_DEFAULT_VIEW', + 'description' => '_MI_IMFORUM_CFG_DEFAULT_VIEW_DSC', + 'formtype' => 'select', + 'valuetype' => 'text', + 'default' => 'flat', + 'options' => ['_MI_IMFORUM_VIEW_FLAT' => 'flat', '_MI_IMFORUM_VIEW_TREE' => 'tree'], + ], + [ + 'name' => 'show_online', + 'title' => '_MI_IMFORUM_CFG_SHOW_ONLINE', + 'description' => '_MI_IMFORUM_CFG_SHOW_ONLINE_DSC', + 'formtype' => 'yesno', + 'valuetype' => 'int', + 'default' => 1, + ], + [ + 'name' => 'online_minutes', + 'title' => '_MI_IMFORUM_CFG_ONLINE_MINUTES', + 'description' => '_MI_IMFORUM_CFG_ONLINE_MINUTES_DSC', + 'formtype' => 'textbox', + 'valuetype' => 'int', + 'default' => 15, + ], + [ + 'name' => 'rss_items', + 'title' => '_MI_IMFORUM_CFG_RSS_ITEMS', + 'description' => '_MI_IMFORUM_CFG_RSS_ITEMS_DSC', + 'formtype' => 'textbox', + 'valuetype' => 'int', + 'default' => 20, + ], + ], ]; diff --git a/src/include/search.inc.php b/src/include/search.inc.php new file mode 100644 index 0000000..23758ad --- /dev/null +++ b/src/include/search.inc.php @@ -0,0 +1,66 @@ +|false $queryarray the words to look for + * @param string $andor 'AND', 'OR' or 'exact' + * @param int $limit + * @param int $offset + * @param int $userid only posts of this member, 0 for all + * @return list + */ +function imforum_search($queryarray, $andor, $limit, $offset, $userid) { + $permissions = mod_imforum_PermissionService::forCurrentUser(); + $forumIds = $permissions->getReadableForumIds(); + if (!$forumIds) { + return []; + } + $db = icms::$xoopsDB; + $posts = $db->prefix(IMFORUM_DIRNAME . '_post'); + + $where = 'p.approved = 1 AND p.forum_id IN (' . implode(',', array_map('intval', $forumIds)) . ')'; + if ((int) $userid > 0) { + $where .= ' AND p.uid = ' . (int) $userid; + } + if (is_array($queryarray) && $queryarray) { + $conditions = []; + foreach ($queryarray as $word) { + // % and _ in a word are plain characters + $like = $db->quoteString('%' . addcslashes((string) $word, '\\%_') . '%'); + $conditions[] = "(p.subject LIKE $like OR (p.post_karma = 0 AND p.require_reply = 0 AND p.post_text LIKE $like))"; + } + $where .= ' AND (' . implode($andor === 'OR' ? ' OR ' : ' AND ', $conditions) . ')'; + } + + $hits = []; + $result = $db->query( + "SELECT p.post_id, p.topic_id, p.uid, p.post_time, p.subject FROM $posts p WHERE $where ORDER BY p.post_id DESC", + max(1, (int) $limit), + max(0, (int) $offset) + ); + while ($result && ($row = $db->fetchRow($result))) { + $hits[] = [ + 'image' => 'images/imforum_iconsmall.png', + 'link' => 'topic.php?topic=' . (int) $row[1] . '&post=' . (int) $row[0] . '#post-' . (int) $row[0], + 'title' => (string) $row[4], + 'time' => (int) $row[3], + 'uid' => (int) $row[2], + ]; + } + return $hits; +} diff --git a/src/index.php b/src/index.php index 7861b2f..315595e 100644 --- a/src/index.php +++ b/src/index.php @@ -1,8 +1,6 @@ addStylesheet(IMFORUM_URL . 'assets/css/imforum.css'); + +$tracker = new mod_imforum_ReadTracker($permissions->getUid()); +$forums = $permissions->getVisibleForums(); +$unread = $tracker->countUnreadByForum(array_keys($forums)); + +$lastPostIds = []; +$children = []; +foreach ($forums as $forumId => $forum) { + $lastPostIds[] = (int) $forum->getVar('forum_last_post_id', 'e'); + $children[(int) $forum->getVar('parent_forum', 'e')][] = $forum; +} +$summaries = icms_getModuleHandler('post', IMFORUM_DIRNAME)->getSummaries($lastPostIds); + +$describe = static function (mod_imforum_Forum $forum) use (&$describe, $children, $unread, $summaries): array { + $forumId = (int) $forum->id(); + $last = $summaries[(int) $forum->getVar('forum_last_post_id', 'e')] ?? null; + $subforums = []; + foreach ($children[$forumId] ?? [] as $child) { + $subforums[] = $describe($child); + } + return [ + 'id' => $forumId, + 'url' => mod_imforum_View::link('forum', ['forum' => $forumId]), + 'name' => $forum->getVar('forum_name'), + 'description' => $forum->getVar('forum_desc'), + 'topics' => (int) $forum->getVar('forum_topics', 'e'), + 'posts' => (int) $forum->getVar('forum_posts', 'e'), + 'unread' => $unread[$forumId] ?? 0, + 'last' => $last === null ? null : [ + 'url' => mod_imforum_View::link('topic', ['topic' => $last['topic_id'], 'post' => $last['post_id']]) . '#post-' . $last['post_id'], + 'subject' => mod_imforum_View::escape($last['subject']), + 'poster' => mod_imforum_View::poster($last['uid'], $last['poster_name']), + 'time' => mod_imforum_View::time($last['post_time']), + ], + 'subforums' => $subforums, + ]; +}; + +$categoryCriteria = new icms_db_criteria_Compo(); +$categoryCriteria->setSort('weight'); +$categoryCriteria->setOrder('ASC'); +$categories = []; +$totals = ['topics' => 0, 'posts' => 0]; +foreach (icms_getModuleHandler('category', IMFORUM_DIRNAME)->getObjects($categoryCriteria) as $category) { + $catId = (int) $category->id(); + $rows = []; + foreach ($children[0] ?? [] as $forum) { + if ((int) $forum->getVar('cat_id', 'e') === $catId) { + $rows[] = $describe($forum); + } + } + // A forum in a category without parent in the list (its parent is hidden) is not shown here + if ($rows) { + $categories[] = [ + 'id' => $catId, + 'title' => $category->getVar('cat_title'), + 'description' => $category->getVar('cat_description'), + 'forums' => $rows, + ]; + } +} +foreach ($forums as $forum) { + $totals['topics'] += (int) $forum->getVar('forum_topics', 'e'); + $totals['posts'] += (int) $forum->getVar('forum_posts', 'e'); +} + +$online = icms_getModuleHandler('online', IMFORUM_DIRNAME); +$showOnline = (int) mod_imforum_Settings::get('show_online') === 1; +if ($showOnline) { + $online->track($permissions->getUid(), icms::$user ? (string) icms::$user->getVar('uname', 'n') : '', (string) ($_SERVER['REMOTE_ADDR'] ?? ''), 0, 0, mod_imforum_Settings::getCount('online_minutes')); +} -$icmsTpl->assign('imforum_module_url', IMFORUM_URL); +$icmsTpl->assign('imforum_breadcrumb', mod_imforum_View::breadcrumb([])); +$icmsTpl->assign('imforum_categories', $categories); +$icmsTpl->assign('imforum_totals', $totals); +$icmsTpl->assign('imforum_viewall_url', mod_imforum_View::link('viewall')); +$icmsTpl->assign('imforum_unread_url', mod_imforum_View::link('viewall', ['type' => 'unread'])); +$icmsTpl->assign('imforum_is_member', $permissions->getUid() > 0); +$icmsTpl->assign('imforum_online', $showOnline ? mod_imforum_View::online($online->getSnapshot(0, 0, mod_imforum_Settings::getCount('online_minutes'))) : null); include_once ICMS_ROOT_PATH . '/footer.php'; diff --git a/src/language/english/main.php b/src/language/english/main.php index 8e83115..b0688f7 100644 --- a/src/language/english/main.php +++ b/src/language/english/main.php @@ -4,4 +4,44 @@ */ define('_MD_IMFORUM_TITLE', 'Forum'); -define('_MD_IMFORUM_UNDER_CONSTRUCTION', 'The forum is being built. Check back soon.'); +define('_MD_IMFORUM_PATH', 'Path'); +define('_MD_IMFORUM_FORUM', 'Forum'); +define('_MD_IMFORUM_FORUMS', 'Forums'); +define('_MD_IMFORUM_TOPIC', 'Topic'); +define('_MD_IMFORUM_TOPICS', 'Topics'); +define('_MD_IMFORUM_POSTS', 'Posts'); +define('_MD_IMFORUM_REPLIES', 'Replies'); +define('_MD_IMFORUM_VIEWS', 'Views'); +define('_MD_IMFORUM_LAST_POST', 'Last post'); +define('_MD_IMFORUM_BY', 'by'); +define('_MD_IMFORUM_SUBFORUMS', 'Subforums'); +define('_MD_IMFORUM_NO_FORUMS', 'There are no forums you can see yet.'); +define('_MD_IMFORUM_NO_TOPICS', 'There are no topics here.'); +define('_MD_IMFORUM_UNREAD', 'new'); +define('_MD_IMFORUM_STICKY', 'Sticky'); +define('_MD_IMFORUM_LOCKED', 'Locked'); +define('_MD_IMFORUM_FEATURED', 'Featured'); +define('_MD_IMFORUM_HOT', 'Hot'); +define('_MD_IMFORUM_MARK_READ', 'Mark all as read'); +define('_MD_IMFORUM_MARKED_READ', 'All topics are marked as read.'); +define('_MD_IMFORUM_MODERATORS', 'Moderators'); +define('_MD_IMFORUM_FORUM_INACTIVE', 'This forum is switched off. Only moderators see it.'); +define('_MD_IMFORUM_VIEW_FLAT', 'Flat'); +define('_MD_IMFORUM_VIEW_TREE', 'Thread'); +define('_MD_IMFORUM_VIEWALL_LATEST', 'Latest topics'); +define('_MD_IMFORUM_VIEWALL_UNREAD', 'Unread topics'); +define('_MD_IMFORUM_VIEWALL_DIGEST', 'Featured topics'); +define('_MD_IMFORUM_ARCHIVE', 'Archive'); +define('_MD_IMFORUM_ARCHIVE_DSC', 'Older posts that were moved out of the forums. They can still be read here.'); +define('_MD_IMFORUM_ARCHIVE_EMPTY', 'The archive is empty.'); +define('_MD_IMFORUM_ARCHIVED_ON', 'Archived on'); +define('_MD_IMFORUM_TO_TOPIC', 'Go to the topic'); +define('_MD_IMFORUM_RSS', 'RSS feed'); +define('_MD_IMFORUM_ONLINE', 'Who is online'); +define('_MD_IMFORUM_ONLINE_MEMBERS', 'members'); +define('_MD_IMFORUM_ONLINE_GUESTS', 'guests'); +define('_MD_IMFORUM_ONLINE_NOW', 'Online now'); +define('_MD_IMFORUM_JOINED', 'Joined'); +define('_MD_IMFORUM_EDITED_BY', 'Edited by'); +define('_MD_IMFORUM_LOCK_KARMA', 'The author asks for more karma than you have to read this post.'); +define('_MD_IMFORUM_LOCK_REPLY', 'The author asks you to reply to this topic before you can read this post.'); diff --git a/src/language/english/modinfo.php b/src/language/english/modinfo.php index d14ff96..7b5e995 100644 --- a/src/language/english/modinfo.php +++ b/src/language/english/modinfo.php @@ -14,3 +14,25 @@ define('_MI_IMFORUM_MENU_DIGESTS', 'Digests'); define('_MI_IMFORUM_MENU_ARCHIVE', 'Archive'); define('_MI_IMFORUM_MENU_PRUNE', 'Prune and recount'); +define('_MI_IMFORUM_BLOCK_RECENT', 'Latest topics'); +define('_MI_IMFORUM_BLOCK_RECENT_DSC', 'The topics with the newest posts'); +define('_MI_IMFORUM_BLOCK_HOT', 'Busiest topics'); +define('_MI_IMFORUM_BLOCK_HOT_DSC', 'The topics with the most replies that saw a new post recently'); +define('_MI_IMFORUM_BLOCK_TOPPOSTERS', 'Most active members'); +define('_MI_IMFORUM_BLOCK_TOPPOSTERS_DSC', 'The members with the most posts'); +define('_MI_IMFORUM_BLOCK_OPT_COUNT', 'Number of items'); +define('_MI_IMFORUM_BLOCK_OPT_DAYS', 'Look back (days)'); +define('_MI_IMFORUM_VIEW_FLAT', 'Flat'); +define('_MI_IMFORUM_VIEW_TREE', 'Thread'); +define('_MI_IMFORUM_CFG_TOPICS_PER_PAGE', 'Topics per page'); +define('_MI_IMFORUM_CFG_TOPICS_PER_PAGE_DSC', 'How many topics a forum page and the overview pages show.'); +define('_MI_IMFORUM_CFG_POSTS_PER_PAGE', 'Posts per page'); +define('_MI_IMFORUM_CFG_POSTS_PER_PAGE_DSC', 'How many posts a page of a topic shows.'); +define('_MI_IMFORUM_CFG_DEFAULT_VIEW', 'Default view of a topic'); +define('_MI_IMFORUM_CFG_DEFAULT_VIEW_DSC', 'Flat shows the posts in order of time, thread shows every reply under the post it answers.'); +define('_MI_IMFORUM_CFG_SHOW_ONLINE', 'Show who is online'); +define('_MI_IMFORUM_CFG_SHOW_ONLINE_DSC', 'Shows the members and the number of guests who are looking at the forum.'); +define('_MI_IMFORUM_CFG_ONLINE_MINUTES', 'Minutes a visitor counts as online'); +define('_MI_IMFORUM_CFG_ONLINE_MINUTES_DSC', 'A visitor who has not opened a page for this long is no longer shown.'); +define('_MI_IMFORUM_CFG_RSS_ITEMS', 'Items in the RSS feed'); +define('_MI_IMFORUM_CFG_RSS_ITEMS_DSC', 'The number of topics in the feed.'); diff --git a/src/language/nederlands/main.php b/src/language/nederlands/main.php index ab74c73..247f16f 100644 --- a/src/language/nederlands/main.php +++ b/src/language/nederlands/main.php @@ -4,4 +4,44 @@ */ define('_MD_IMFORUM_TITLE', 'Forum'); -define('_MD_IMFORUM_UNDER_CONSTRUCTION', 'Het forum wordt gebouwd. Kom binnenkort terug.'); +define('_MD_IMFORUM_PATH', 'Pad'); +define('_MD_IMFORUM_FORUM', 'Forum'); +define('_MD_IMFORUM_FORUMS', 'Forums'); +define('_MD_IMFORUM_TOPIC', 'Onderwerp'); +define('_MD_IMFORUM_TOPICS', 'Onderwerpen'); +define('_MD_IMFORUM_POSTS', 'Berichten'); +define('_MD_IMFORUM_REPLIES', 'Reacties'); +define('_MD_IMFORUM_VIEWS', 'Weergaven'); +define('_MD_IMFORUM_LAST_POST', 'Laatste bericht'); +define('_MD_IMFORUM_BY', 'door'); +define('_MD_IMFORUM_SUBFORUMS', 'Subforums'); +define('_MD_IMFORUM_NO_FORUMS', 'Er zijn nog geen forums die je kunt zien.'); +define('_MD_IMFORUM_NO_TOPICS', 'Er zijn hier geen onderwerpen.'); +define('_MD_IMFORUM_UNREAD', 'nieuw'); +define('_MD_IMFORUM_STICKY', 'Vastgezet'); +define('_MD_IMFORUM_LOCKED', 'Gesloten'); +define('_MD_IMFORUM_FEATURED', 'Uitgelicht'); +define('_MD_IMFORUM_HOT', 'Populair'); +define('_MD_IMFORUM_MARK_READ', 'Alles als gelezen markeren'); +define('_MD_IMFORUM_MARKED_READ', 'Alle onderwerpen zijn als gelezen gemarkeerd.'); +define('_MD_IMFORUM_MODERATORS', 'Moderatoren'); +define('_MD_IMFORUM_FORUM_INACTIVE', 'Dit forum staat uit. Alleen moderatoren zien het.'); +define('_MD_IMFORUM_VIEW_FLAT', 'Vlak'); +define('_MD_IMFORUM_VIEW_TREE', 'Boom'); +define('_MD_IMFORUM_VIEWALL_LATEST', 'Laatste onderwerpen'); +define('_MD_IMFORUM_VIEWALL_UNREAD', 'Ongelezen onderwerpen'); +define('_MD_IMFORUM_VIEWALL_DIGEST', 'Uitgelichte onderwerpen'); +define('_MD_IMFORUM_ARCHIVE', 'Archief'); +define('_MD_IMFORUM_ARCHIVE_DSC', 'Oudere berichten die uit de forums zijn gehaald. Ze zijn hier nog te lezen.'); +define('_MD_IMFORUM_ARCHIVE_EMPTY', 'Het archief is leeg.'); +define('_MD_IMFORUM_ARCHIVED_ON', 'Gearchiveerd op'); +define('_MD_IMFORUM_TO_TOPIC', 'Naar het onderwerp'); +define('_MD_IMFORUM_RSS', 'RSS-feed'); +define('_MD_IMFORUM_ONLINE', 'Wie is online'); +define('_MD_IMFORUM_ONLINE_MEMBERS', 'leden'); +define('_MD_IMFORUM_ONLINE_GUESTS', 'gasten'); +define('_MD_IMFORUM_ONLINE_NOW', 'Nu online'); +define('_MD_IMFORUM_JOINED', 'Lid sinds'); +define('_MD_IMFORUM_EDITED_BY', 'Bewerkt door'); +define('_MD_IMFORUM_LOCK_KARMA', 'De auteur vraagt meer karma dan je hebt om dit bericht te lezen.'); +define('_MD_IMFORUM_LOCK_REPLY', 'De auteur vraagt dat je eerst op dit onderwerp reageert voordat je dit bericht kunt lezen.'); diff --git a/src/language/nederlands/modinfo.php b/src/language/nederlands/modinfo.php index 8ffaf17..7a2a2e7 100644 --- a/src/language/nederlands/modinfo.php +++ b/src/language/nederlands/modinfo.php @@ -14,3 +14,25 @@ define('_MI_IMFORUM_MENU_DIGESTS', 'Digests'); define('_MI_IMFORUM_MENU_ARCHIVE', 'Archief'); define('_MI_IMFORUM_MENU_PRUNE', 'Opruimen en hertellen'); +define('_MI_IMFORUM_BLOCK_RECENT', 'Laatste onderwerpen'); +define('_MI_IMFORUM_BLOCK_RECENT_DSC', 'De onderwerpen met de nieuwste berichten'); +define('_MI_IMFORUM_BLOCK_HOT', 'Drukste onderwerpen'); +define('_MI_IMFORUM_BLOCK_HOT_DSC', 'De onderwerpen met de meeste reacties die onlangs een nieuw bericht kregen'); +define('_MI_IMFORUM_BLOCK_TOPPOSTERS', 'Actiefste leden'); +define('_MI_IMFORUM_BLOCK_TOPPOSTERS_DSC', 'De leden met de meeste berichten'); +define('_MI_IMFORUM_BLOCK_OPT_COUNT', 'Aantal items'); +define('_MI_IMFORUM_BLOCK_OPT_DAYS', 'Terugkijken (dagen)'); +define('_MI_IMFORUM_VIEW_FLAT', 'Vlak'); +define('_MI_IMFORUM_VIEW_TREE', 'Boom'); +define('_MI_IMFORUM_CFG_TOPICS_PER_PAGE', 'Onderwerpen per pagina'); +define('_MI_IMFORUM_CFG_TOPICS_PER_PAGE_DSC', 'Hoeveel onderwerpen een forumpagina en de overzichtspagina\'s tonen.'); +define('_MI_IMFORUM_CFG_POSTS_PER_PAGE', 'Berichten per pagina'); +define('_MI_IMFORUM_CFG_POSTS_PER_PAGE_DSC', 'Hoeveel berichten een pagina van een onderwerp toont.'); +define('_MI_IMFORUM_CFG_DEFAULT_VIEW', 'Standaardweergave van een onderwerp'); +define('_MI_IMFORUM_CFG_DEFAULT_VIEW_DSC', 'Vlak toont de berichten op tijd, boom toont elke reactie onder het bericht waarop ze antwoordt.'); +define('_MI_IMFORUM_CFG_SHOW_ONLINE', 'Toon wie online is'); +define('_MI_IMFORUM_CFG_SHOW_ONLINE_DSC', 'Toont de leden en het aantal gasten die naar het forum kijken.'); +define('_MI_IMFORUM_CFG_ONLINE_MINUTES', 'Minuten dat een bezoeker als online telt'); +define('_MI_IMFORUM_CFG_ONLINE_MINUTES_DSC', 'Een bezoeker die zo lang geen pagina opende, wordt niet meer getoond.'); +define('_MI_IMFORUM_CFG_RSS_ITEMS', 'Items in de RSS-feed'); +define('_MI_IMFORUM_CFG_RSS_ITEMS_DSC', 'Het aantal onderwerpen in de feed.'); diff --git a/src/rss.php b/src/rss.php new file mode 100644 index 0000000..366e26e --- /dev/null +++ b/src/rss.php @@ -0,0 +1,67 @@ +getReadableForumIds(); +$forumId = mod_imforum_View::intParam('forum'); +if ($forumId > 0) { + $forumIds = in_array($forumId, $forumIds, true) ? [$forumId] : []; +} + +$topicHandler = icms_getModuleHandler('topic', IMFORUM_DIRNAME); +$postHandler = icms_getModuleHandler('post', IMFORUM_DIRNAME); +$found = $topicHandler->findRecent($forumIds, 0, mod_imforum_Settings::getCount('rss_items')); +$topics = $topicHandler->getByIds($found['ids']); +$posts = $postHandler->getByIds(array_map(static fn (mod_imforum_Topic $topic): int => (int) $topic->getVar('topic_last_post_id', 'e'), $topics)); +$lastPosts = []; +foreach ($posts as $post) { + $lastPosts[(int) $post->getVar('topic_id', 'e')] = $post; +} + +/** Text for an XML element: no control characters, escaped */ +$xml = static fn (string $text): string => htmlspecialchars(preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', '', $text) ?? '', ENT_XML1 | ENT_QUOTES, 'UTF-8'); + +$site = (string) ($GLOBALS['icmsConfig']['sitename'] ?? ''); +$feedTitle = $site . ' - ' . _MD_IMFORUM_TITLE; +if ($forumId > 0 && count($forumIds) === 1) { + $feedTitle .= ' - ' . (string) $permissions->getForum($forumId)?->getVar('forum_name', 'n'); +} + +$items = ''; +foreach ($topics as $topicId => $topic) { + $post = $lastPosts[$topicId] ?? null; + $link = mod_imforum_View::url('topic', ['topic' => $topicId, 'post' => $post ? (int) $post->id() : 0]); + $data = $post ? $post->toArray() : null; + $excerpt = $data ? trim(html_entity_decode(strip_tags((string) $data['text']), ENT_QUOTES, 'UTF-8')) : ''; + $items .= "\t\n" + . "\t\t" . $xml((string) $topic->getVar('topic_title', 'n')) . "\n" + . "\t\t" . $xml($link) . "\n" + . "\t\t" . $xml($link) . "\n" + . ($data ? "\t\t" . gmdate('D, d M Y H:i:s', (int) $data['post_time']) . " GMT\n" : '') + . "\t\t" . $xml(function_exists('mb_substr') ? mb_substr($excerpt, 0, 300) : substr($excerpt, 0, 300)) . "\n" + . "\t\n"; +} + +header('Content-Type: application/rss+xml; charset=utf-8'); +echo '' . "\n" + . "\n\n" + . "\t" . $xml($feedTitle) . "\n" + . "\t" . $xml(mod_imforum_View::url('index')) . "\n" + . "\t" . $xml($feedTitle) . "\n" + . $items + . "\n\n"; diff --git a/src/templates/blocks/imforum_block_topics.html b/src/templates/blocks/imforum_block_topics.html new file mode 100644 index 0000000..bcb777b --- /dev/null +++ b/src/templates/blocks/imforum_block_topics.html @@ -0,0 +1,9 @@ +
    + <{foreach from=$block.topics item=topic}> +
  • + <{$topic.title}> + <{$topic.forum}> · <{$topic.replies}> <{$smarty.const._MD_IMFORUM_REPLIES}> · <{$topic.time}> +
  • + <{/foreach}> +
+

<{$smarty.const._MD_IMFORUM_VIEWALL_LATEST}>

diff --git a/src/templates/blocks/imforum_block_topposters.html b/src/templates/blocks/imforum_block_topposters.html new file mode 100644 index 0000000..0dcd1cf --- /dev/null +++ b/src/templates/blocks/imforum_block_topposters.html @@ -0,0 +1,5 @@ +
    + <{foreach from=$block.posters item=poster}> +
  1. <{$poster.member}> <{$poster.posts}> <{$smarty.const._MD_IMFORUM_POSTS}>
  2. + <{/foreach}> +
diff --git a/src/templates/imforum_archive.html b/src/templates/imforum_archive.html new file mode 100644 index 0000000..a766a46 --- /dev/null +++ b/src/templates/imforum_archive.html @@ -0,0 +1,47 @@ +
+ <{include file="db:imforum_breadcrumb.html"}> + <{if $imforum_archive_topic}> +

<{$imforum_archive_topic.title}>

+

<{$smarty.const._MD_IMFORUM_TO_TOPIC}>

+ <{foreach from=$imforum_archive_posts item=post}> +
+
+ <{$post.subject}> + <{if $post.author}><{$smarty.const._MD_IMFORUM_BY}> <{$post.author}>, <{$post.time}> · <{/if}><{$smarty.const._MD_IMFORUM_ARCHIVED_ON}> <{$post.archived}> +
+
+ <{if $post.lock}> +

<{if $post.lock == 'karma'}><{$smarty.const._MD_IMFORUM_LOCK_KARMA}><{else}><{$smarty.const._MD_IMFORUM_LOCK_REPLY}><{/if}>

+ <{else}> + <{$post.text}> + <{/if}> +
+
+ <{/foreach}> + <{else}> +

<{$smarty.const._MD_IMFORUM_ARCHIVE}>

+

<{$smarty.const._MD_IMFORUM_ARCHIVE_DSC}>

+ <{if $imforum_archive_topics}> + <{$imforum_pager}> + + + + + + + + <{foreach from=$imforum_archive_topics item=topic}> + "> + + + + + <{/foreach}> + +
<{$smarty.const._MD_IMFORUM_TOPIC}><{$smarty.const._MD_IMFORUM_POSTS}><{$smarty.const._MD_IMFORUM_ARCHIVED_ON}>
<{$topic.title}><{$topic.posts}><{$topic.archived}>
+ <{$imforum_pager}> + <{else}> +

<{$smarty.const._MD_IMFORUM_ARCHIVE_EMPTY}>

+ <{/if}> + <{/if}> +
diff --git a/src/templates/imforum_breadcrumb.html b/src/templates/imforum_breadcrumb.html new file mode 100644 index 0000000..9a48250 --- /dev/null +++ b/src/templates/imforum_breadcrumb.html @@ -0,0 +1,6 @@ + diff --git a/src/templates/imforum_forum.html b/src/templates/imforum_forum.html new file mode 100644 index 0000000..a98eb4a --- /dev/null +++ b/src/templates/imforum_forum.html @@ -0,0 +1,48 @@ +
+ <{include file="db:imforum_breadcrumb.html"}> +

<{$imforum_forum.name}>

+ <{if $imforum_forum.description}>

<{$imforum_forum.description}>

<{/if}> + <{if $imforum_forum.inactive}>

<{$smarty.const._MD_IMFORUM_FORUM_INACTIVE}>

<{/if}> + <{if $imforum_moderators}> +

<{$smarty.const._MD_IMFORUM_MODERATORS}>: <{foreach from=$imforum_moderators item=moderator name=mods}><{$moderator}><{if !$smarty.foreach.mods.last}>, <{/if}><{/foreach}>

+ <{/if}> + + <{if $imforum_subforums}> + + + + + + <{foreach from=$imforum_subforums item=sub}> + "> + + + + + <{/foreach}> + +
<{$smarty.const._MD_IMFORUM_SUBFORUMS}>
+ <{$sub.name}> + <{if $sub.unread}><{$sub.unread}> <{$smarty.const._MD_IMFORUM_UNREAD}><{/if}> + <{if $sub.description}>
<{$sub.description}>
<{/if}> +
<{$sub.topics}> <{$smarty.const._MD_IMFORUM_TOPICS}><{$sub.posts}> <{$smarty.const._MD_IMFORUM_POSTS}>
+ <{/if}> + + <{if $imforum_topics}> + <{$imforum_pager}> + <{include file="db:imforum_topiclist.html"}> + <{$imforum_pager}> + <{else}> +

<{$smarty.const._MD_IMFORUM_NO_TOPICS}>

+ <{/if}> + + <{if $imforum_can_mark_read}> +
+ + <{$imforum_token}> + +
+ <{/if}> + + <{include file="db:imforum_online.html"}> +
diff --git a/src/templates/imforum_index.html b/src/templates/imforum_index.html index f8970b9..b8c8cc1 100644 --- a/src/templates/imforum_index.html +++ b/src/templates/imforum_index.html @@ -1,4 +1,61 @@
+ <{include file="db:imforum_breadcrumb.html"}>

<{$smarty.const._MD_IMFORUM_TITLE}>

-

<{$smarty.const._MD_IMFORUM_UNDER_CONSTRUCTION}>

+ +

+ <{$smarty.const._MD_IMFORUM_VIEWALL_LATEST}> + <{if $imforum_is_member}> · <{$smarty.const._MD_IMFORUM_VIEWALL_UNREAD}><{/if}> + · <{$smarty.const._MD_IMFORUM_ARCHIVE}> + · <{$smarty.const._MD_IMFORUM_RSS}> +

+ + <{if $imforum_categories}> + <{foreach from=$imforum_categories item=category}> + + + + + + + + + + + + + + <{foreach from=$category.forums item=forum}> + "> + + + + + + <{/foreach}> + +
+ <{$category.title}> + <{if $category.description}>
<{$category.description}>
<{/if}> +
<{$smarty.const._MD_IMFORUM_FORUM}><{$smarty.const._MD_IMFORUM_TOPICS}><{$smarty.const._MD_IMFORUM_POSTS}><{$smarty.const._MD_IMFORUM_LAST_POST}>
+ <{$forum.name}> + <{if $forum.unread}><{$forum.unread}> <{$smarty.const._MD_IMFORUM_UNREAD}><{/if}> + <{if $forum.description}>
<{$forum.description}>
<{/if}> + <{if $forum.subforums}> +
<{$smarty.const._MD_IMFORUM_SUBFORUMS}>: + <{foreach from=$forum.subforums item=sub name=subs}><{$sub.name}><{if $sub.unread}> (<{$sub.unread}>)<{/if}><{if !$smarty.foreach.subs.last}>, <{/if}><{/foreach}> +
+ <{/if}> +
<{$forum.topics}><{$forum.posts}> + <{if $forum.last}> + <{$forum.last.subject}> +
<{$smarty.const._MD_IMFORUM_BY}> <{$forum.last.poster}>, <{$forum.last.time}>
+ <{/if}> +
+ <{/foreach}> +

<{$imforum_totals.topics}> <{$smarty.const._MD_IMFORUM_TOPICS}>, <{$imforum_totals.posts}> <{$smarty.const._MD_IMFORUM_POSTS}>

+ <{else}> +

<{$smarty.const._MD_IMFORUM_NO_FORUMS}>

+ <{/if}> + + <{include file="db:imforum_online.html"}>
diff --git a/src/templates/imforum_online.html b/src/templates/imforum_online.html new file mode 100644 index 0000000..a23a3d3 --- /dev/null +++ b/src/templates/imforum_online.html @@ -0,0 +1,13 @@ +<{if $imforum_online}> +
+

<{$smarty.const._MD_IMFORUM_ONLINE}>

+

+ <{$imforum_online.member_count}> <{$smarty.const._MD_IMFORUM_ONLINE_MEMBERS}>, + <{$imforum_online.guests}> <{$smarty.const._MD_IMFORUM_ONLINE_GUESTS}> + <{if $imforum_online.members}> + — + <{foreach from=$imforum_online.members item=member name=online}><{$member.name}><{if !$smarty.foreach.online.last}>, <{/if}><{/foreach}> + <{/if}> +

+
+<{/if}> diff --git a/src/templates/imforum_topic.html b/src/templates/imforum_topic.html new file mode 100644 index 0000000..3dd10cd --- /dev/null +++ b/src/templates/imforum_topic.html @@ -0,0 +1,53 @@ +
+ <{include file="db:imforum_breadcrumb.html"}> +

<{$imforum_topic.title}><{if $imforum_topic.locked}> <{$smarty.const._MD_IMFORUM_LOCKED}><{/if}>

+

+ <{$imforum_topic.replies}> <{$smarty.const._MD_IMFORUM_REPLIES}>, <{$imforum_topic.views}> <{$smarty.const._MD_IMFORUM_VIEWS}> + · + <{if $imforum_mode == 'tree'}><{$smarty.const._MD_IMFORUM_VIEW_FLAT}> | <{$smarty.const._MD_IMFORUM_VIEW_TREE}> + <{else}><{$smarty.const._MD_IMFORUM_VIEW_FLAT}> | <{$smarty.const._MD_IMFORUM_VIEW_TREE}><{/if}> +

+ + <{$imforum_pager}> + <{foreach from=$imforum_posts item=post}> +
+ +
+
+ #<{$post.post_id}> + <{$post.subject}> + <{$post.time}> +
+
+ <{if $post.locked}> +

<{if $post.lock == 'karma'}><{$smarty.const._MD_IMFORUM_LOCK_KARMA}><{else}><{$smarty.const._MD_IMFORUM_LOCK_REPLY}><{/if}>

+ <{else}> + <{$post.text}> + <{/if}> +
+ <{if $post.signature}>
<{$post.signature}>
<{/if}> + <{if $post.edits}> +
<{$smarty.const._MD_IMFORUM_EDITED_BY}> + <{foreach from=$post.edits item=edit name=edits}><{$edit.name}> (<{$edit.time}>)<{if !$smarty.foreach.edits.last}>, <{/if}><{/foreach}> +
+ <{/if}> +
+
+ <{/foreach}> + <{$imforum_pager}> + +

« <{$imforum_topic.forum_name}>

+ <{include file="db:imforum_online.html"}> +
diff --git a/src/templates/imforum_topiclist.html b/src/templates/imforum_topiclist.html new file mode 100644 index 0000000..58b4e6d --- /dev/null +++ b/src/templates/imforum_topiclist.html @@ -0,0 +1,42 @@ + + + + + + + + + + + <{foreach from=$imforum_topics item=topic}> + <{if $topic.unread}> imforum-unread<{/if}>"> + + + + + + + <{/foreach}> + +
<{$smarty.const._MD_IMFORUM_TOPIC}><{$smarty.const._MD_IMFORUM_REPLIES}><{$smarty.const._MD_IMFORUM_VIEWS}><{$smarty.const._MD_IMFORUM_LAST_POST}>
+ <{if $topic.unread}>● + <{elseif $topic.locked}>🔒 + <{else}>○<{/if}> + + <{if $topic.sticky}><{$smarty.const._MD_IMFORUM_STICKY}><{/if}> + <{if $topic.digest}><{$smarty.const._MD_IMFORUM_FEATURED}><{/if}> + <{if $topic.hot}><{$smarty.const._MD_IMFORUM_HOT}><{/if}> + <{$topic.title}> + <{if $topic.pages}> + [<{foreach from=$topic.pages item=page}><{$page.number}> <{/foreach}><{if $topic.more_pages}>…<{/if}>] + <{/if}> +
+ <{$smarty.const._MD_IMFORUM_BY}> <{$topic.poster}>, <{$topic.time}> + <{if $topic.forum}> · <{$topic.forum.name}><{/if}> +
+
<{$topic.replies}><{$topic.views}> + <{if $topic.last}> + <{$topic.last.time}> +
<{$smarty.const._MD_IMFORUM_BY}> <{$topic.last.poster}>
+ <{/if}> +
diff --git a/src/templates/imforum_viewall.html b/src/templates/imforum_viewall.html new file mode 100644 index 0000000..be731da --- /dev/null +++ b/src/templates/imforum_viewall.html @@ -0,0 +1,19 @@ +
+ <{include file="db:imforum_breadcrumb.html"}> +

<{$imforum_title}>

+

+ <{foreach from=$imforum_filters item=filter name=filters}> + <{if !$filter.members_only || $imforum_is_member}> + <{if $filter.active}><{$filter.title}><{else}><{$filter.title}><{/if}> + <{if !$smarty.foreach.filters.last}>·<{/if}> + <{/if}> + <{/foreach}> +

+ <{if $imforum_topics}> + <{$imforum_pager}> + <{include file="db:imforum_topiclist.html"}> + <{$imforum_pager}> + <{else}> +

<{$smarty.const._MD_IMFORUM_NO_TOPICS}>

+ <{/if}> +
diff --git a/src/topic.php b/src/topic.php new file mode 100644 index 0000000..78ebbff --- /dev/null +++ b/src/topic.php @@ -0,0 +1,138 @@ + 0 ? $topicHandler->get($topicId) : null; +$forum = ($topic !== null && !$topic->isNew()) ? $permissions->getForum((int) $topic->getVar('forum_id', 'e')) : null; +if ($forum === null || !$permissions->canReadForum($forum)) { + redirect_header(mod_imforum_View::url('index'), 3, _NOPERM); + exit; +} +$forumId = (int) $forum->id(); +$moderator = $permissions->isModerator($forumId); +// topics waiting for approval are for the moderators +if ((int) $topic->getVar('approved', 'e') !== 1 && !$moderator) { + redirect_header(mod_imforum_View::url('forum', ['forum' => $forumId]), 3, _NOPERM); + exit; +} + +$mode = ($_GET['mode'] ?? mod_imforum_Settings::get('default_view')) === 'tree' ? 'tree' : 'flat'; +$perPage = mod_imforum_Settings::getCount('posts_per_page'); +$total = $postHandler->countApproved($topicId); + +// the page of posts: by position in the thread for the tree, by id for the flat view +$order = $mode === 'tree' ? $postHandler->getThreadOrder($topicId) : null; +$start = mod_imforum_View::intParam('start'); +$jumpTo = mod_imforum_View::intParam('post'); +if ($jumpTo > 0) { + if ($order !== null) { + $position = array_search($jumpTo, array_column($order, 'post_id'), true); + $start = $position === false ? 0 : (int) $position; + } else { + $start = $postHandler->getPosition($topicId, $jumpTo); + } + $start = (int) (floor($start / $perPage) * $perPage); +} +$start = min($start, max(0, (int) (ceil($total / $perPage) - 1) * $perPage)); + +$depths = []; +if ($order !== null) { + $slice = array_slice($order, $start, $perPage); + foreach ($slice as $entry) { + $depths[$entry['post_id']] = $entry['depth']; + } + $posts = $postHandler->getByIds(array_column($slice, 'post_id')); +} else { + $posts = $postHandler->getPage($topicId, $start, $perPage); +} + +$karma = new mod_imforum_KarmaService($permissions->getUid()); +$minutes = mod_imforum_Settings::getCount('online_minutes'); +$posters = mod_imforum_PosterInfo::load(array_map(static fn (mod_imforum_Post $post): int => (int) $post->getVar('uid', 'e'), $posts), $minutes); + +$rows = []; +foreach ($posts as $postId => $post) { + $karma->apply($post, $moderator); + $row = $post->toArray(); + $uid = $row['uid']; + $poster = $posters[$uid] ?? null; + $row['author'] = mod_imforum_View::poster($uid, (string) $post->getVar('poster_name', 'n')); + $row['time'] = mod_imforum_View::time($row['post_time']); + $row['depth'] = min($depths[$postId] ?? 0, 8); + $row['url'] = mod_imforum_View::link('topic', ['topic' => $topicId, 'post' => $postId, 'mode' => $mode === 'tree' ? 'tree' : '']) . '#post-' . $postId; + $row['poster'] = $poster; + // the signature belongs to the post only when the author and the forum allow it + $row['signature'] = ($poster !== null && $row['attachsig'] === 1 && (int) $forum->getVar('allow_sig', 'e') === 1) ? $poster['signature'] : ''; + $row['edits'] = array_map(static fn (array $edit): array => [ + 'name' => mod_imforum_View::poster((int) $edit['uid'], (string) $edit['name']), + 'time' => mod_imforum_View::time((int) $edit['time']), + ], $row['edits']); + $rows[] = $row; +} + +// reading a page marks the topic as read up to the newest post seen; the last page reads it to the end +$tracker = new mod_imforum_ReadTracker($permissions->getUid()); +if ($posts) { + $onLastPage = $start + count($posts) >= $total; + $tracker->markTopicRead($topicId, $onLastPage ? (int) $topic->getVar('topic_last_post_id', 'e') : max(array_keys($posts))); +} +// a view counts once per visit +if (isset($_SESSION) && !isset($_SESSION['imforum_viewed'][$topicId])) { + $_SESSION['imforum_viewed'][$topicId] = true; + $topicHandler->incrementViews($topicId); +} + +$xoopsOption['template_main'] = 'imforum_topic.html'; +include_once ICMS_ROOT_PATH . '/header.php'; +global $icmsTpl, $xoTheme; +$xoTheme->addStylesheet(IMFORUM_URL . 'assets/css/imforum.css'); + +$trail = []; +for ($parent = $forumId, $guard = 0; $parent > 0 && $guard < 10; $guard++) { + $step = $permissions->getForum($parent); + if ($step === null || !$permissions->canSeeForum($step)) { + break; + } + array_unshift($trail, [$step->getVar('forum_name', 'n'), mod_imforum_View::url('forum', ['forum' => $parent])]); + $parent = (int) $step->getVar('parent_forum', 'e'); +} +$trail[] = [$topic->getVar('topic_title', 'n')]; + +$online = icms_getModuleHandler('online', IMFORUM_DIRNAME); +$showOnline = (int) mod_imforum_Settings::get('show_online') === 1; +if ($showOnline) { + $online->track($permissions->getUid(), icms::$user ? (string) icms::$user->getVar('uname', 'n') : '', (string) ($_SERVER['REMOTE_ADDR'] ?? ''), $forumId, $topicId, $minutes); +} + +$icmsTpl->assign('imforum_breadcrumb', mod_imforum_View::breadcrumb($trail)); +$icmsTpl->assign('imforum_topic', [ + 'id' => $topicId, + 'title' => $topic->getVar('topic_title'), + 'views' => (int) $topic->getVar('topic_views', 'e'), + 'replies' => (int) $topic->getVar('topic_replies', 'e'), + 'locked' => $topic->isLocked(), + 'forum_url' => mod_imforum_View::link('forum', ['forum' => $forumId]), + 'forum_name' => $forum->getVar('forum_name'), +]); +$icmsTpl->assign('imforum_posts', $rows); +$icmsTpl->assign('imforum_mode', $mode); +$icmsTpl->assign('imforum_flat_url', mod_imforum_View::link('topic', ['topic' => $topicId, 'mode' => 'flat'])); +$icmsTpl->assign('imforum_tree_url', mod_imforum_View::link('topic', ['topic' => $topicId, 'mode' => 'tree'])); +$icmsTpl->assign('imforum_pager', mod_imforum_View::pager('topic', ['topic' => $topicId, 'mode' => $mode], $total, $perPage, $start)); +$icmsTpl->assign('imforum_online', $showOnline ? mod_imforum_View::online($online->getSnapshot($forumId, $topicId, $minutes)) : null); + +include_once ICMS_ROOT_PATH . '/footer.php'; diff --git a/src/viewall.php b/src/viewall.php new file mode 100644 index 0000000..f87b32d --- /dev/null +++ b/src/viewall.php @@ -0,0 +1,45 @@ +getUid() < 1) { + redirect_header(ICMS_URL . '/user.php', 3, _NOPERM); + exit; +} + +$xoopsOption['template_main'] = 'imforum_viewall.html'; +include_once ICMS_ROOT_PATH . '/header.php'; +global $icmsTpl, $xoTheme; +$xoTheme->addStylesheet(IMFORUM_URL . 'assets/css/imforum.css'); + +$topicHandler = icms_getModuleHandler('topic', IMFORUM_DIRNAME); +$perPage = mod_imforum_Settings::getCount('topics_per_page'); +$start = mod_imforum_View::intParam('start'); +$found = $topicHandler->findRecent($permissions->getReadableForumIds(), $start, $perPage, $type, $permissions->getUid()); +$tracker = new mod_imforum_ReadTracker($permissions->getUid()); +$rows = mod_imforum_TopicList::rows($topicHandler->getByIds($found['ids']), $permissions->getAllForums(), $tracker, true); + +$titles = ['' => _MD_IMFORUM_VIEWALL_LATEST, 'unread' => _MD_IMFORUM_VIEWALL_UNREAD, 'digest' => _MD_IMFORUM_VIEWALL_DIGEST]; +$icmsTpl->assign('imforum_breadcrumb', mod_imforum_View::breadcrumb([[$titles[$type]]])); +$icmsTpl->assign('imforum_title', mod_imforum_View::escape($titles[$type])); +$icmsTpl->assign('imforum_topics', $rows); +$icmsTpl->assign('imforum_filters', [ + ['title' => _MD_IMFORUM_VIEWALL_LATEST, 'url' => mod_imforum_View::link('viewall'), 'active' => $type === ''], + ['title' => _MD_IMFORUM_VIEWALL_UNREAD, 'url' => mod_imforum_View::link('viewall', ['type' => 'unread']), 'active' => $type === 'unread', 'members_only' => true], + ['title' => _MD_IMFORUM_VIEWALL_DIGEST, 'url' => mod_imforum_View::link('viewall', ['type' => 'digest']), 'active' => $type === 'digest'], +]); +$icmsTpl->assign('imforum_is_member', $permissions->getUid() > 0); +$icmsTpl->assign('imforum_pager', mod_imforum_View::pager('viewall', ['type' => $type], $found['total'], $perPage, $start)); + +include_once ICMS_ROOT_PATH . '/footer.php'; diff --git a/tests/Integration/IntegrationTestCase.php b/tests/Integration/IntegrationTestCase.php index aae4d9d..84d4a7f 100644 --- a/tests/Integration/IntegrationTestCase.php +++ b/tests/Integration/IntegrationTestCase.php @@ -71,6 +71,31 @@ protected static function post(int $topicId, string $subject = 'Re: Hello', int ]); } + /** + * Give groups permissions on a forum, as the admin form does + * + * @param list $permissions gperm names, such as forum_access + * @param list $groups + */ + protected static function grant(int $forumId, array $permissions, array $groups): void + { + $handler = new \icms_ipf_permission_Handler(self::handler('forum')); + foreach ($permissions as $permission) { + self::assertTrue($handler->saveItem_Permissions($groups, $forumId, $permission)); + } + } + + /** + * Let groups see a category, as the admin form does + * + * @param list $groups + */ + protected static function grantCategory(int $catId, array $groups): void + { + $handler = new \icms_ipf_permission_Handler(self::handler('category')); + self::assertTrue($handler->saveItem_Permissions($groups, $catId, 'category_access')); + } + protected static function reload(string $item, int $id): icms_ipf_Object { $object = self::handler($item)->get($id); diff --git a/tests/Integration/ReadingTest.php b/tests/Integration/ReadingTest.php new file mode 100644 index 0000000..0d40bb0 --- /dev/null +++ b/tests/Integration/ReadingTest.php @@ -0,0 +1,388 @@ +id()); + + $permissions = new Permissions(self::GUESTS); + self::assertSame([], $permissions->getVisibleForums()); + self::assertSame([], $permissions->getReadableForumIds()); + self::assertFalse($permissions->canReadForum(self::reload('forum', (int) $forum->id()))); + } + + public function testAForumNeedsCategoryAccessForumAccessAndView(): void + { + $category = self::category(); + $forum = self::forum((int) $category->id()); + $forumId = (int) $forum->id(); + + self::grant($forumId, ['forum_access', 'forum_view'], self::GUESTS); + self::assertSame([], (new Permissions(self::GUESTS))->getReadableForumIds(), 'the category is not open'); + + self::grantCategory((int) $category->id(), self::GUESTS); + self::assertSame([$forumId], (new Permissions(self::GUESTS))->getReadableForumIds()); + + self::grant($forumId, ['forum_view'], []); + $guests = new Permissions(self::GUESTS); + self::assertCount(1, $guests->getVisibleForums(), 'listed without view'); + self::assertSame([], $guests->getReadableForumIds(), 'but not readable'); + } + + public function testPermissionsFollowTheGroupsOfTheVisitor(): void + { + $category = self::category(); + $forumId = (int) self::forum((int) $category->id())->id(); + self::grantCategory((int) $category->id(), self::MEMBERS); + self::grant($forumId, ['forum_access', 'forum_view'], self::MEMBERS); + + self::assertSame([], (new Permissions(self::GUESTS))->getReadableForumIds()); + self::assertSame([$forumId], (new Permissions(self::MEMBERS, 5))->getReadableForumIds()); + self::assertSame([$forumId], (new Permissions([3, 2], 5))->getReadableForumIds()); + } + + public function testWebmastersSeeEverythingAndSwitchedOffForumsHideFromOthers(): void + { + $category = self::category(); + $off = self::make('forum', ['cat_id' => (int) $category->id(), 'forum_name' => 'Off', 'forum_active' => 0]); + $offId = (int) $off->id(); + self::grantCategory((int) $category->id(), self::GUESTS); + self::grant($offId, ['forum_access', 'forum_view'], self::GUESTS); + + self::assertSame([], (new Permissions(self::GUESTS))->getReadableForumIds()); + self::assertSame([$offId], (new Permissions([1], 1, true))->getReadableForumIds(), 'webmaster'); + + self::handler('moderator')->setModerators($offId, [7]); + self::assertSame([$offId], (new Permissions(self::GUESTS, 7))->getReadableForumIds(), 'its moderator'); + self::assertSame([], (new Permissions(self::GUESTS, 8))->getReadableForumIds()); + } + + public function testTheCurrentUserIsAWebmasterThroughTheCoreGroupConstants(): void + { + $forumId = (int) self::forum((int) self::category()->id())->id(); + $user = new \icms_member_user_Object(); + $user->assignVar('uid', 1); + $user->setGroups([(int) ICMS_GROUP_ADMIN, (int) ICMS_GROUP_USERS]); + \icms::$user = $user; + try { + $permissions = Permissions::forCurrentUser(); + self::assertTrue($permissions->isWebmaster()); + self::assertSame([$forumId], $permissions->getReadableForumIds()); + } finally { + \icms::$user = null; + } + self::assertFalse(Permissions::forCurrentUser()->isWebmaster()); + } + + public function testTopicsListStickyFirstThenByLastPost(): void + { + $forumId = (int) self::forum((int) self::category()->id())->id(); + $first = self::topic($forumId, 'First'); + $sticky = self::topic($forumId, 'Sticky'); + Database::exec('UPDATE ' . self::handler('topic')->table . ' SET topic_sticky = 1 WHERE topic_id = ' . (int) $sticky->id()); + $last = self::topic($forumId, 'Last'); + self::post((int) $first->id()); + + $titles = array_map( + static fn ($topic): string => (string) $topic->getVar('topic_title', 'n'), + array_values(self::handler('topic')->getForumTopics($forumId, 0, 10)) + ); + self::assertSame(['Sticky', 'First', 'Last'], $titles); + self::assertSame(3, self::handler('topic')->countForumTopics($forumId)); + self::assertCount(1, self::handler('topic')->getForumTopics($forumId, 2, 10)); + self::assertNotSame(0, (int) $last->id()); + } + + public function testRecentTopicsFilterByForumAndKind(): void + { + $cat = (int) self::category()->id(); + $open = (int) self::forum($cat, 'Open')->id(); + $closed = (int) self::forum($cat, 'Closed')->id(); + $a = self::topic($open, 'A'); + self::topic($closed, 'Hidden'); + $b = self::topic($open, 'B'); + Database::exec('UPDATE ' . self::handler('topic')->table . ' SET topic_digest = 1 WHERE topic_id = ' . (int) $a->id()); + + $handler = self::handler('topic'); + self::assertSame([(int) $b->id(), (int) $a->id()], $handler->findRecent([$open], 0, 10)['ids']); + self::assertSame(2, $handler->findRecent([$open], 0, 10)['total']); + self::assertSame([(int) $a->id()], $handler->findRecent([$open], 0, 10, 'digest')['ids']); + self::assertSame(['ids' => [], 'total' => 0], $handler->findRecent([], 0, 10)); + self::assertSame(['ids' => [], 'total' => 0], $handler->findRecent([$open], 0, 10, 'unread', 0), 'guests have nothing unread'); + self::assertSame([(int) $b->id()], $handler->findRecent([$open], 0, 1)['ids']); + } + + public function testReadTrackerFollowsTopicAndForumMarks(): void + { + $cat = (int) self::category()->id(); + $forumId = (int) self::forum($cat)->id(); + $one = self::topic($forumId, 'One'); + $two = self::topic($forumId, 'Two'); + $tracker = new \mod_imforum_ReadTracker(9); + $state = static fn ($topic): array => [(int) $topic->id() => [ + 'forum_id' => (int) $topic->getVar('forum_id', 'e'), + 'last_post_id' => (int) $topic->getVar('topic_last_post_id', 'e'), + ]]; + $both = $state($one) + $state($two); + + self::assertSame([(int) $one->id() => true, (int) $two->id() => true], $tracker->getUnreadTopics($both)); + self::assertSame([$forumId => 2], $tracker->countUnreadByForum([$forumId])); + + $tracker->markTopicRead((int) $one->id(), (int) $one->getVar('topic_last_post_id', 'e')); + self::assertSame([(int) $two->id() => true], $tracker->getUnreadTopics($both)); + self::assertSame([$forumId => 1], $tracker->countUnreadByForum([$forumId])); + self::assertSame([(int) $two->id()], self::handler('topic')->findRecent([$forumId], 0, 10, 'unread', 9)['ids']); + + // a mark never moves back + $tracker->markTopicRead((int) $one->id(), 1); + self::assertSame([(int) $two->id() => true], $tracker->getUnreadTopics($both)); + + // a reply makes the topic unread again + $reply = self::post((int) $one->id()); + $one = self::reload('topic', (int) $one->id()); + self::assertArrayHasKey((int) $one->id(), $tracker->getUnreadTopics($state($one))); + self::assertNotSame(0, (int) $reply->id()); + + // "mark all as read" covers the forum and removes the topic marks + $forum = self::reload('forum', $forumId); + $tracker->markForumRead($forumId, (int) $forum->getVar('forum_last_post_id', 'e')); + self::assertSame([], $tracker->getUnreadTopics($state($one) + $state($two))); + self::assertSame([], $tracker->countUnreadByForum([$forumId])); + self::assertSame(1, self::rows('readmark'), 'only the forum mark is left'); + + // other members and guests are unaffected + self::assertSame([$forumId => 2], (new \mod_imforum_ReadTracker(10))->countUnreadByForum([$forumId])); + self::assertSame([], (new \mod_imforum_ReadTracker(0))->getUnreadTopics($both)); + } + + public function testThreadOrderPutsRepliesUnderTheirParents(): void + { + $forumId = (int) self::forum((int) self::category()->id())->id(); + $topic = self::topic($forumId, 'Root'); + $topicId = (int) $topic->id(); + $root = (int) $topic->getVar('topic_first_post_id', 'e'); + $a = (int) self::post($topicId, 'a', 1, $root)->id(); + $b = (int) self::post($topicId, 'b', 1, $root)->id(); + $a1 = (int) self::post($topicId, 'a1', 1, $a)->id(); + $unapproved = (int) self::post($topicId, 'pending', 1, $b, 0)->id(); + $orphan = (int) self::post($topicId, 'orphan', 1, $unapproved)->id(); + + $order = self::handler('post')->getThreadOrder($topicId); + self::assertSame([$root, $a, $a1, $b, $orphan], array_column($order, 'post_id')); + self::assertSame([0, 1, 2, 1, 0], array_column($order, 'depth'), 'a reply to an unapproved post becomes a first level post'); + } + + public function testThreadOrderSurvivesLoopsAndSelfReplies(): void + { + $forumId = (int) self::forum((int) self::category()->id())->id(); + $topic = self::topic($forumId); + $topicId = (int) $topic->id(); + $one = (int) self::post($topicId, 'one')->id(); + $two = (int) self::post($topicId, 'two')->id(); + $posts = self::handler('post'); + Database::exec("UPDATE {$posts->table} SET pid = $two WHERE post_id = $one"); + Database::exec("UPDATE {$posts->table} SET pid = $one WHERE post_id = $two"); + + $ids = array_column($posts->getThreadOrder($topicId), 'post_id'); + self::assertCount(3, $ids); + self::assertEqualsCanonicalizing([(int) $topic->getVar('topic_first_post_id', 'e'), $one, $two], $ids); + } + + public function testPostPagesAndPositions(): void + { + $forumId = (int) self::forum((int) self::category()->id())->id(); + $topic = self::topic($forumId); + $topicId = (int) $topic->id(); + $ids = [(int) $topic->getVar('topic_first_post_id', 'e')]; + for ($i = 0; $i < 4; $i++) { + $ids[] = (int) self::post($topicId, "reply $i")->id(); + } + self::post($topicId, 'pending', 1, 0, 0); + $posts = self::handler('post'); + + self::assertSame(5, $posts->countApproved($topicId)); + self::assertSame(array_slice($ids, 0, 2), array_keys($posts->getPage($topicId, 0, 2))); + self::assertSame(array_slice($ids, 4, 1), array_keys($posts->getPage($topicId, 4, 2))); + self::assertSame(3, $posts->getPosition($topicId, $ids[3])); + self::assertSame([$ids[2], $ids[0]], array_keys($posts->getByIds([$ids[2], 99999, $ids[0]])), 'in the order asked, unknown ids left out'); + self::assertSame(['subject' => 'reply 1'], ['subject' => $posts->getSummaries([$ids[2]])[$ids[2]]['subject']]); + } + + public function testMembersAreCountedOnApprovedPostsOnly(): void + { + $forumId = (int) self::forum((int) self::category()->id())->id(); + $topic = self::topic($forumId, 'Hello', 5); + self::post((int) $topic->id(), 'again', 5); + self::post((int) $topic->id(), 'other', 6); + self::post((int) $topic->id(), 'pending', 6, 0, 0); + self::post((int) $topic->id(), 'guest', 0); + $posts = self::handler('post'); + + self::assertSame([5 => 2, 6 => 1], $posts->countByUsers([5, 6, 7, 0])); + self::assertSame([['uid' => 5, 'posts' => 2], ['uid' => 6, 'posts' => 1]], $posts->getTopPosters([$forumId], 10)); + self::assertSame([], $posts->getTopPosters([], 10)); + self::assertTrue($posts->hasPosted((int) $topic->id(), 6)); + self::assertFalse($posts->hasPosted((int) $topic->id(), 7)); + } + + public function testKarmaAndRequiredRepliesHideTheText(): void + { + $forumId = (int) self::forum((int) self::category()->id())->id(); + $topic = self::topic($forumId, 'Hello', 5); + $topicId = (int) $topic->id(); + $karmaPost = self::make('post', ['topic_id' => $topicId, 'subject' => 'k', 'post_text' => 'secret karma', 'uid' => 5, 'post_karma' => 3]); + $replyPost = self::make('post', ['topic_id' => $topicId, 'subject' => 'r', 'post_text' => 'secret reply', 'uid' => 5, 'require_reply' => 1]); + $plain = self::reload('post', (int) $topic->getVar('topic_first_post_id', 'e')); + + // without the service the text never leaves the post + self::assertTrue($karmaPost->toArray()['locked']); + self::assertSame('', $karmaPost->toArray()['text']); + self::assertFalse($plain->toArray()['locked']); + + // a guest has neither karma nor replies + $guest = new \mod_imforum_KarmaService(0); + self::assertSame('karma', $guest->apply($karmaPost, false)); + self::assertSame('karma', $karmaPost->toArray()['lock']); + self::assertSame('reply', $guest->apply($replyPost, false)); + self::assertSame('', $replyPost->toArray()['text']); + + // the author and moderators read everything + $author = new \mod_imforum_KarmaService(5); + self::assertSame('', $author->apply($karmaPost, false)); + self::assertStringContainsString('secret karma', $karmaPost->toArray()['text']); + self::assertSame('', (new \mod_imforum_KarmaService(0))->apply($replyPost, true)); + + // karma counts approved posts: member 6 has two, which is not enough for three + self::post($topicId, 'one', 6); + self::post($topicId, 'two', 6); + $member = new \mod_imforum_KarmaService(6); + self::assertSame(2, $member->getKarma()); + $locked = self::reload('post', (int) $karmaPost->id()); + self::assertSame('karma', $member->apply($locked, false)); + self::post($topicId, 'three', 6); + $member = new \mod_imforum_KarmaService(6); + $unlocked = self::reload('post', (int) $karmaPost->id()); + self::assertSame('', $member->apply($unlocked, false)); + // member 6 has replied in the topic, so the reply post opens too + $replyLocked = self::reload('post', (int) $replyPost->id()); + self::assertSame('', $member->apply($replyLocked, false)); + self::assertStringContainsString('secret reply', $replyLocked->toArray()['text']); + } + + public function testPostTextIsFormattedWithItsOwnSwitches(): void + { + $forumId = (int) self::forum((int) self::category()->id())->id(); + $topic = self::topic($forumId); + $post = self::make('post', [ + 'topic_id' => (int) $topic->id(), 'subject' => 's', 'post_text' => "bold [b]coded[/b]\nline", 'dohtml' => 0, 'doxcode' => 1, 'dobr' => 1, + ]); + $text = $post->toArray()['text']; + self::assertStringContainsString('<b>bold</b>', $text, 'html is escaped'); + self::assertStringContainsString('coded', $text, 'code is converted'); + self::assertStringContainsString(' (int) $topic->id(), 'subject' => 's', 'post_text' => '[b]x[/b]', 'doxcode' => 0]); + self::assertStringContainsString('[b]x[/b]', $plain->toArray()['text']); + } + + public function testOnlineVisitorsAreTrackedOncePerVisitor(): void + { + $online = self::handler('online'); + self::assertTrue($online->track(5, 'Ann', '10.0.0.1', 1, 0)); + self::assertTrue($online->track(5, 'Ann', '10.0.0.1', 2, 9)); + self::assertTrue($online->track(0, '', '10.0.0.2', 1, 0)); + self::assertTrue($online->track(0, '', '10.0.0.2', 1, 0)); + self::assertTrue($online->track(0, '', '10.0.0.3', 2, 0)); + self::assertFalse($online->track(0, '', 'not an address', 1, 0), 'a guest without an address cannot be told apart'); + + self::assertSame(3, self::rows('online')); + self::assertSame(['members' => [['uid' => 5, 'uname' => 'Ann']], 'guests' => 2], $online->getSnapshot()); + self::assertSame(['members' => [], 'guests' => 1], $online->getSnapshot(1)); + self::assertSame(['members' => [['uid' => 5, 'uname' => 'Ann']], 'guests' => 0], $online->getSnapshot(0, 9)); + self::assertSame([5 => true], $online->getOnlineMembers([5, 6])); + + // a visitor who stopped long ago is gone + Database::exec('UPDATE ' . $online->table . ' SET updated = ' . (time() - 3600) . ' WHERE uid = 5'); + self::assertSame(['members' => [], 'guests' => 2], $online->getSnapshot()); + self::assertSame([], $online->getOnlineMembers([5])); + $online->track(0, '', '10.0.0.9', 0, 0); + self::assertSame(3, self::rows('online'), 'the stale row was purged'); + } + + public function testArchivedTopicsAreListedPerReadableForum(): void + { + $cat = (int) self::category()->id(); + $open = (int) self::forum($cat, 'Open')->id(); + $closed = (int) self::forum($cat, 'Closed')->id(); + $a = self::topic($open, 'A'); + $b = self::topic($closed, 'B'); + foreach ([[$a, 100], [$a, 200], [$b, 300]] as [$topic, $time]) { + self::make('archive', ['topic_id' => (int) $topic->id(), 'post_id' => (int) $topic->getVar('topic_first_post_id', 'e'), 'post_text' => 'old', 'archived_time' => $time]); + } + $archive = self::handler('archive'); + + $page = $archive->getTopicsPage([$open], 0, 10); + self::assertSame(1, $page['total']); + self::assertSame([['topic_id' => (int) $a->id(), 'posts' => 2, 'archived_time' => 200]], $page['rows']); + self::assertSame(2, $archive->getTopicsPage([$open, $closed], 0, 10)['total']); + self::assertSame(['rows' => [], 'total' => 0], $archive->getTopicsPage([], 0, 10)); + self::assertCount(2, $archive->getByTopic((int) $a->id())); + } + + public function testBusyTopicsNeedRecentActivityAndReplies(): void + { + $forumId = (int) self::forum((int) self::category()->id())->id(); + $quiet = self::topic($forumId, 'Quiet'); + $busy = self::topic($forumId, 'Busy'); + self::post((int) $busy->id()); + self::post((int) $busy->id()); + $old = self::topic($forumId, 'Old'); + self::post((int) $old->id()); + $posts = self::handler('post'); + Database::exec("UPDATE {$posts->table} SET post_time = 1000 WHERE topic_id = " . (int) $old->id()); + + self::assertSame([(int) $busy->id()], self::handler('topic')->findHot([$forumId], time() - 86400, 10)); + self::assertNotSame(0, (int) $quiet->id()); + } + + public function testSearchFindsOnlyWhatTheVisitorMayRead(): void + { + include_once ICMS_ROOT_PATH . '/modules/imforum/include/search.inc.php'; + $cat = self::category(); + $open = self::forum((int) $cat->id(), 'Open'); + $closed = self::forum((int) $cat->id(), 'Closed'); + self::grantCategory((int) $cat->id(), self::GUESTS); + self::grant((int) $open->id(), ['forum_access', 'forum_view'], self::GUESTS); + + $topic = self::topic((int) $open->id(), 'Needle in subject'); + self::make('post', ['topic_id' => (int) $topic->id(), 'subject' => 'plain', 'post_text' => 'haystack with a needle inside', 'uid' => 4]); + self::make('post', ['topic_id' => (int) $topic->id(), 'subject' => 'locked', 'post_text' => 'secret needle', 'require_reply' => 1]); + self::make('post', ['topic_id' => (int) $topic->id(), 'subject' => 'pending', 'post_text' => 'needle', 'approved' => 0]); + self::topic((int) $closed->id(), 'Needle elsewhere'); + self::make('post', ['topic_id' => (int) $topic->id(), 'subject' => '100% sure', 'post_text' => 'x']); + + $titles = array_column(imforum_search(['needle'], 'AND', 20, 0, 0), 'title'); + self::assertEqualsCanonicalizing(['Needle in subject', 'plain'], $titles); + self::assertSame(['locked'], array_column(imforum_search(['locked'], 'AND', 20, 0, 0), 'title')); + self::assertSame([], array_column(imforum_search(['secret'], 'AND', 20, 0, 0), 'title'), 'the text of a protected post is not searched'); + self::assertSame(['plain'], array_column(imforum_search(['needle'], 'AND', 20, 0, 4), 'title')); + self::assertSame(['100% sure'], array_column(imforum_search(['100%'], 'AND', 20, 0, 0), 'title')); + self::assertSame([], imforum_search(["' OR 1=1 -- "], 'AND', 20, 0, 0)); + self::assertCount(1, imforum_search(['needle', 'haystack'], 'AND', 20, 0, 0)); + self::assertCount(2, imforum_search(['haystack', 'subject'], 'OR', 20, 0, 0)); + self::assertCount(1, imforum_search(['needle'], 'AND', 1, 1, 0), 'limit and offset'); + } +} diff --git a/tests/integration-bootstrap.php b/tests/integration-bootstrap.php index fbd60be..5606870 100644 --- a/tests/integration-bootstrap.php +++ b/tests/integration-bootstrap.php @@ -50,9 +50,10 @@ define('ICMS_ROOT_PATH', $root); define('ICMS_TRUST_PATH', $sandbox . '/trust'); define('ICMS_URL', 'http://localhost'); -define('ICMS_GROUP_ADMIN', 1); -define('ICMS_GROUP_USERS', 2); -define('ICMS_GROUP_ANONYMOUS', 3); +// The core defines the group constants as strings +define('ICMS_GROUP_ADMIN', '1'); +define('ICMS_GROUP_USERS', '2'); +define('ICMS_GROUP_ANONYMOUS', '3'); mkdir(ICMS_TRUST_PATH . '/cache/htmlpurifier', 0755, true); require_once ICMS_ROOT_PATH . '/include/constants.php'; diff --git a/tests/phpstan-bootstrap.php b/tests/phpstan-bootstrap.php index 9f0c4b7..488bef3 100644 --- a/tests/phpstan-bootstrap.php +++ b/tests/phpstan-bootstrap.php @@ -17,6 +17,8 @@ // set by the core's include/common.php at runtime define('_GLOBAL_LEFT', 'left'); +// from the core's language//global.php +define('_NOPERM', 'Sorry, you don\'t have the permission to access this area.'); // the _CO_ICMS_* strings of the IPF forms and tables require_once $core . '/modules/system/language/english/common.php';