diff --git a/CHANGELOG.md b/CHANGELOG.md index dfd50de..db3dea7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,3 +4,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()`. diff --git a/README.md b/README.md index 8032aa9..2ccafba 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 1 (data model). The module creates its tables and the data layer works, but there are no admin screens or forum pages yet. +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. ## Requirements diff --git a/phpstan.neon.dist b/phpstan.neon.dist index 5f02f43..ba79c65 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -23,8 +23,8 @@ parameters: message: '#^Parameter \#2 \$value of class icms_db_criteria_Item constructor expects string, int#' identifier: argument.type - - # icms_ipf_Object::initCommonVar() documents its parameters as "str" - message: '#^Parameter \#\d \$\w+ of method icms_ipf_Object::initCommonVar\(\) expects str, #' + # many core docblocks use "str" and "unknown_type", which are not types + message: '#^Parameter \#\d \$\w+ of (method|class) icms_\w+(::\w+\(\)| constructor) expects (str|unknown_type), #' identifier: argument.type - # icms_ipf_Tree::getFirstChild() documents string; the tree is keyed by integer ids diff --git a/src/admin/admin_header.php b/src/admin/admin_header.php new file mode 100644 index 0000000..2cd08ec --- /dev/null +++ b/src/admin/admin_header.php @@ -0,0 +1,16 @@ +get(imforum_admin_int('archive_id')); + if ($archive->isNew()) { + redirect_header(imforum_admin_url('archive.php'), 3, _CO_ICMS_NOT_SELECTED); + exit; + } + imforum_admin_page(7, $archive->getTopicTitle(), '
' . $archive->getVar('post_text') . '
'); + break; + + case 'del': + $controller = new icms_ipf_Controller($handler); + $controller->handleObjectDeletion(); + break; + + default: + $table = new icms_ipf_view_Table($handler, new icms_db_criteria_Compo(), ['delete']); + $table->addColumn(new icms_ipf_view_Column('topic_id', _GLOBAL_LEFT, false, 'getTopicTitle')); + $table->addColumn(new icms_ipf_view_Column('post_text', _GLOBAL_LEFT, false, 'getExcerpt')); + $table->addColumn(new icms_ipf_view_Column('archived_time', 'center', 140)); + $table->addCustomAction('getViewLink'); + $table->setDefaultSort('archived_time'); + $table->setDefaultOrder('DESC'); + imforum_admin_page(7, _AM_IMFORUM_ARCHIVE, $table->fetch(), _AM_IMFORUM_ARCHIVE_DSC); + break; +} diff --git a/src/admin/category.php b/src/admin/category.php new file mode 100644 index 0000000..3b35c04 --- /dev/null +++ b/src/admin/category.php @@ -0,0 +1,40 @@ +get(imforum_admin_int('cat_id')); + $title = $category->isNew() ? _AM_IMFORUM_CATEGORY_ADD : _AM_IMFORUM_CATEGORY_EDIT; + imforum_admin_page(1, $title, static fn (): string => $category->getSecureForm($title, 'addcategory')->render()); + break; + + case 'addcategory': + imforum_admin_store($handler, _AM_IMFORUM_CATEGORY_CREATED, _AM_IMFORUM_CATEGORY_MODIFIED, imforum_admin_url('category.php')); + break; + + case 'del': + $controller = new icms_ipf_Controller($handler); + $controller->handleObjectDeletion(); + break; + + default: + $table = new icms_ipf_view_Table($handler); + $table->addColumn(new icms_ipf_view_Column('cat_title', _GLOBAL_LEFT, false, 'getAdminLink')); + $table->addColumn(new icms_ipf_view_Column('weight', 'center', 80)); + $table->setDefaultSort('weight'); + $table->addIntroButton('addcategory', imforum_admin_url('category.php', 'op=mod'), _AM_IMFORUM_CATEGORY_ADD); + imforum_admin_page(1, _AM_IMFORUM_CATEGORIES, $table->fetch(), _AM_IMFORUM_CATEGORIES_DSC); + break; +} diff --git a/src/admin/digest.php b/src/admin/digest.php new file mode 100644 index 0000000..c3bed71 --- /dev/null +++ b/src/admin/digest.php @@ -0,0 +1,43 @@ +get(imforum_admin_int('digest_id')); + if ($digest->isNew()) { + redirect_header(imforum_admin_url('digest.php'), 3, _CO_ICMS_NOT_SELECTED); + exit; + } + imforum_admin_page(6, sprintf(_AM_IMFORUM_DIGEST_OF, $digest->getVar('digest_time')), + '
' . $digest->getVar('digest_content') . '
'); + break; + + case 'del': + $controller = new icms_ipf_Controller($handler); + $controller->handleObjectDeletion(); + break; + + default: + $table = new icms_ipf_view_Table($handler, new icms_db_criteria_Compo(), ['delete']); + $table->addColumn(new icms_ipf_view_Column('digest_time', _GLOBAL_LEFT, 160)); + $table->addColumn(new icms_ipf_view_Column('digest_content', _GLOBAL_LEFT, false, 'getExcerpt')); + $table->addCustomAction('getViewLink'); + $table->setDefaultSort('digest_time'); + $table->setDefaultOrder('DESC'); + imforum_admin_page(6, _AM_IMFORUM_DIGESTS, $table->fetch(), _AM_IMFORUM_DIGESTS_DSC); + break; +} diff --git a/src/admin/forum.php b/src/admin/forum.php new file mode 100644 index 0000000..5cb67db --- /dev/null +++ b/src/admin/forum.php @@ -0,0 +1,64 @@ +getCategorySelectList()) { + redirect_header(imforum_admin_url('category.php', 'op=mod'), 3, _AM_IMFORUM_FORUM_NEEDS_CATEGORY); + exit; + } + $forum = $handler->get(imforum_admin_int('forum_id')); + $forum->setVar('moderators', icms_getModuleHandler('moderator', IMFORUM_DIRNAME)->getModeratorIds((int) $forum->id())); + if ($forum->isNew()) { + $forum->setVar('cat_id', imforum_admin_int('cat_id')); + } + + $title = $forum->isNew() ? _AM_IMFORUM_FORUM_ADD : _AM_IMFORUM_FORUM_EDIT; + imforum_admin_page(2, $title, static function () use ($forum, $title): string { + $form = $forum->getSecureForm($title, 'addforum'); + if ($forum->isNew()) { + // a new forum starts with the groups of the permission template + foreach (icms_getModuleHandler('permtemplate', IMFORUM_DIRNAME)->getTemplate() as $permission => $groups) { + $form->setElementValue($permission, $groups); + } + } + return $form->render(); + }); + break; + + case 'addforum': + // no moderators is a choice too, so an unposted select clears them + imforum_admin_store($handler, _AM_IMFORUM_FORUM_CREATED, _AM_IMFORUM_FORUM_MODIFIED, imforum_admin_url('forum.php'), ['moderators']); + break; + + case 'del': + $controller = new icms_ipf_Controller($handler); + $controller->handleObjectDeletion(_AM_IMFORUM_FORUM_DELETE_CONFIRM); + break; + + default: + $table = new icms_ipf_view_Table($handler); + $table->addColumn(new icms_ipf_view_Column('forum_name', _GLOBAL_LEFT, false, 'getAdminLink')); + $table->addColumn(new icms_ipf_view_Column('cat_id', _GLOBAL_LEFT, false, 'getCategoryTitle')); + $table->addColumn(new icms_ipf_view_Column('forum_topics', 'center', 80)); + $table->addColumn(new icms_ipf_view_Column('forum_posts', 'center', 80)); + $table->addColumn(new icms_ipf_view_Column('forum_active', 'center', 60)); + $table->addColumn(new icms_ipf_view_Column('weight', 'center', 60)); + $table->setDefaultSort('cat_id'); + $table->addIntroButton('addforum', imforum_admin_url('forum.php', 'op=mod'), _AM_IMFORUM_FORUM_ADD); + $table->addQuickSearch(['forum_name']); + imforum_admin_page(2, _AM_IMFORUM_FORUMS, $table->fetch(), _AM_IMFORUM_FORUMS_DSC); + break; +} diff --git a/src/admin/index.php b/src/admin/index.php index 0ab292e..61f0b4a 100644 --- a/src/admin/index.php +++ b/src/admin/index.php @@ -8,16 +8,23 @@ * @since 1.0 */ -include_once dirname(__DIR__, 3) . '/include/cp_header.php'; -include_once dirname(__DIR__) . '/include/common.php'; +include_once __DIR__ . '/admin_header.php'; icms_cp_header(); /** icms_cp_header() creates the admin template engine as a global */ global $icmsAdminTpl; -icms::$module->displayAdminMenu(0, _AM_IMFORUM_INDEX); +imforum_admin_menu(0, _AM_IMFORUM_INDEX); $icmsAdminTpl->assign('imforum_version', icms::$module->getVar('version')); $icmsAdminTpl->assign('imforum_dbversion', icms::$module->getDBVersion()); +$icmsAdminTpl->assign('imforum_stats', [ + _AM_IMFORUM_CATEGORIES => icms_getModuleHandler('category', IMFORUM_DIRNAME)->getCount(), + _AM_IMFORUM_FORUMS => icms_getModuleHandler('forum', IMFORUM_DIRNAME)->getCount(), + _AM_IMFORUM_TOPICS => icms_getModuleHandler('topic', IMFORUM_DIRNAME)->getCount(), + _AM_IMFORUM_POSTS => icms_getModuleHandler('post', IMFORUM_DIRNAME)->getCount(), +]); +$icmsAdminTpl->assign('imforum_open_reports', icms_getModuleHandler('report', IMFORUM_DIRNAME)->getOpenCount()); +$icmsAdminTpl->assign('imforum_report_url', imforum_admin_url('report.php')); $icmsAdminTpl->display('db:imforum_admin_index.html'); icms_cp_footer(); diff --git a/src/admin/menu.php b/src/admin/menu.php index c3f2f7c..d6f51e7 100644 --- a/src/admin/menu.php +++ b/src/admin/menu.php @@ -10,13 +10,27 @@ defined('ICMS_ROOT_PATH') || die('ImpressCMS root path not defined'); +// The position of each entry is the $menuIndex the admin scripts pass to +// imforum_admin_page(); keep both in step. $adminmenu = []; -$adminmenu[] = [ - 'title' => _MI_IMFORUM_MENU_INDEX, - 'link' => 'admin/index.php', - 'icon' => 'images/imforum_iconbig.png', - 'small' => 'images/imforum_iconsmall.png', -]; +foreach ([ + 'index' => _MI_IMFORUM_MENU_INDEX, + 'category' => _MI_IMFORUM_MENU_CATEGORIES, + 'forum' => _MI_IMFORUM_MENU_FORUMS, + 'permtemplate' => _MI_IMFORUM_MENU_PERMTEMPLATE, + 'report' => _MI_IMFORUM_MENU_REPORTS, + 'suspension' => _MI_IMFORUM_MENU_SUSPENSIONS, + 'digest' => _MI_IMFORUM_MENU_DIGESTS, + 'archive' => _MI_IMFORUM_MENU_ARCHIVE, + 'prune' => _MI_IMFORUM_MENU_PRUNE, +] as $script => $title) { + $adminmenu[] = [ + 'title' => $title, + 'link' => 'admin/' . $script . '.php', + 'icon' => 'images/imforum_iconbig.png', + 'small' => 'images/imforum_iconsmall.png', + ]; +} // icms_module_Object::displayAdminMenu() counts the header menu without an // isset check, so it must always be an array. diff --git a/src/admin/permtemplate.php b/src/admin/permtemplate.php new file mode 100644 index 0000000..2acc45e --- /dev/null +++ b/src/admin/permtemplate.php @@ -0,0 +1,57 @@ +saveTemplate($template); + + $applyTo = array_map('intval', (array) ($_POST['apply_forums'] ?? [])); + if ($applyTo) { + $permissions = new icms_ipf_permission_Handler($forumHandler); + foreach ($applyTo as $forumId) { + if ($forumHandler->get($forumId)->isNew()) { + continue; + } + foreach ($template as $permission => $groups) { + $ok = $permissions->saveItem_Permissions($groups, $forumId, $permission) && $ok; + } + } + } + redirect_header(imforum_admin_url('permtemplate.php'), 2, $ok ? _AM_IMFORUM_PERMTEMPLATE_SAVED : _AM_IMFORUM_PERMTEMPLATE_ERROR); + exit; +} + +$form = new icms_form_Theme(_AM_IMFORUM_PERMTEMPLATE, 'permtemplate', imforum_admin_url('permtemplate.php'), 'post', true); +foreach ($handler->getTemplate() as $permission => $groups) { + $caption = '_CO_IMFORUM_PERM_' . strtoupper($permission); + $select = new icms_form_elements_select_Group(constant($caption), $permission, true, $groups, 5, true); + $select->setDescription(constant($caption . '_DSC')); + imforum_form_add($form, $select); +} +$forums = new icms_form_elements_Select(_AM_IMFORUM_PERMTEMPLATE_APPLY, 'apply_forums', null, 8, true); +$forums->addOptionArray($forumHandler->getForumSelectList()); +$forums->setDescription(_AM_IMFORUM_PERMTEMPLATE_APPLY_DSC); +imforum_form_add($form, $forums); +imforum_form_add($form, new icms_form_elements_Hidden('op', 'save')); +imforum_form_add($form, new icms_form_elements_Button('', 'submit', _CO_ICMS_SUBMIT, 'submit')); + +imforum_admin_page(3, _AM_IMFORUM_PERMTEMPLATE, $form->render(), _AM_IMFORUM_PERMTEMPLATE_DSC); diff --git a/src/admin/prune.php b/src/admin/prune.php new file mode 100644 index 0000000..384d93b --- /dev/null +++ b/src/admin/prune.php @@ -0,0 +1,102 @@ + array_values(array_filter(array_map('intval', (array) ($_POST['forums'] ?? [])))), + 'days' => max(0, imforum_admin_int('days')), + 'keep_sticky' => (int) ($_POST['keep_sticky'] ?? 1) === 1, + 'keep_digest' => (int) ($_POST['keep_digest'] ?? 1) === 1, + 'move_to' => imforum_admin_int('move_to'), +]; +$before = time() - $settings['days'] * 86400; + +switch ($op) { + case 'recount': + $ok = $topicHandler->synchroniseAll() && $forumHandler->synchroniseAll(); + redirect_header(imforum_admin_url('prune.php'), 2, $ok ? _AM_IMFORUM_RECOUNT_DONE : _AM_IMFORUM_RECOUNT_ERROR); + exit; + + case 'preview': + if (!$settings['forums'] || $settings['days'] < 1) { + redirect_header(imforum_admin_url('prune.php'), 3, _AM_IMFORUM_PRUNE_INCOMPLETE); + exit; + } + $count = count($topicHandler->findInactive($settings['forums'], $before, $settings['keep_sticky'], $settings['keep_digest'])); + if ($count === 0) { + redirect_header(imforum_admin_url('prune.php'), 3, _AM_IMFORUM_PRUNE_NOTHING); + exit; + } + $hiddens = [ + 'op' => 'prune', + 'days' => $settings['days'], + 'keep_sticky' => (int) $settings['keep_sticky'], + 'keep_digest' => (int) $settings['keep_digest'], + 'move_to' => $settings['move_to'], + 'confirm' => 1, + ]; + foreach ($settings['forums'] as $i => $forumId) { + $hiddens["forums[$i]"] = $forumId; + } + $message = $settings['move_to'] > 0 + ? sprintf(_AM_IMFORUM_PRUNE_CONFIRM_MOVE, $count, $forumHandler->getForumSelectList()[$settings['move_to']] ?? '') + : sprintf(_AM_IMFORUM_PRUNE_CONFIRM_DELETE, $count); + icms_cp_header(); + imforum_admin_menu(8, _AM_IMFORUM_PRUNE); + icms_core_Message::confirm($hiddens, imforum_admin_url('prune.php'), $message, _AM_IMFORUM_PRUNE_GO); + icms_cp_footer(); + break; + + case 'prune': + $done = 0; + foreach ($topicHandler->findInactive($settings['forums'], $before, $settings['keep_sticky'], $settings['keep_digest']) as $topicId) { + if ($settings['move_to'] > 0) { + $done += (int) $topicHandler->moveToForum($topicId, $settings['move_to']); + } else { + $topic = $topicHandler->get($topicId); + $done += (int) (!$topic->isNew() && $topicHandler->delete($topic, true)); + } + } + redirect_header(imforum_admin_url('prune.php'), 3, sprintf(_AM_IMFORUM_PRUNE_DONE, $done)); + exit; + + default: + $forums = $forumHandler->getForumSelectList(); + + $prune = new icms_form_Theme(_AM_IMFORUM_PRUNE, 'prune', imforum_admin_url('prune.php'), 'post', true); + $select = new icms_form_elements_Select(_AM_IMFORUM_PRUNE_FORUMS, 'forums', null, 8, true); + $select->addOptionArray($forums); + imforum_form_add($prune, $select, true); + imforum_form_add($prune, new icms_form_elements_Text(_AM_IMFORUM_PRUNE_DAYS, 'days', 5, 5, '365'), true); + imforum_form_add($prune, new icms_form_elements_Radioyn(_AM_IMFORUM_PRUNE_KEEP_STICKY, 'keep_sticky', '1')); + imforum_form_add($prune, new icms_form_elements_Radioyn(_AM_IMFORUM_PRUNE_KEEP_DIGEST, 'keep_digest', '1')); + $target = new icms_form_elements_Select(_AM_IMFORUM_PRUNE_MOVE_TO, 'move_to', 0); + $target->addOptionArray([0 => _AM_IMFORUM_PRUNE_DELETE] + $forums); + imforum_form_add($prune, $target); + imforum_form_add($prune, new icms_form_elements_Hidden('op', 'preview')); + imforum_form_add($prune, new icms_form_elements_Button('', 'submit', _AM_IMFORUM_PRUNE_PREVIEW, 'submit')); + + $recount = new icms_form_Theme(_AM_IMFORUM_RECOUNT, 'recount', imforum_admin_url('prune.php'), 'post', true); + imforum_form_add($recount, new icms_form_elements_Label('', _AM_IMFORUM_RECOUNT_DSC)); + imforum_form_add($recount, new icms_form_elements_Hidden('op', 'recount')); + imforum_form_add($recount, new icms_form_elements_Button('', 'submit', _AM_IMFORUM_RECOUNT, 'submit')); + + imforum_admin_page(8, _AM_IMFORUM_PRUNE, $prune->render() . '
' . $recount->render(), _AM_IMFORUM_PRUNE_DSC); + break; +} diff --git a/src/admin/report.php b/src/admin/report.php new file mode 100644 index 0000000..1e5b3ac --- /dev/null +++ b/src/admin/report.php @@ -0,0 +1,56 @@ +get(imforum_admin_int('report_id')); + if ($report->isNew()) { + redirect_header(imforum_admin_url('report.php'), 3, _CO_ICMS_NOT_SELECTED); + exit; + } + // the member's text stays as written; only the outcome and the note change + $report->makeFieldReadOnly('report_text'); + imforum_admin_page(4, _AM_IMFORUM_REPORT_HANDLE, static fn (): string => $report->getSecureForm(_AM_IMFORUM_REPORT_HANDLE, 'addreport')->render()); + break; + + case 'addreport': + imforum_admin_store($handler, '', _AM_IMFORUM_REPORT_MODIFIED, imforum_admin_url('report.php')); + break; + + case 'del': + $controller = new icms_ipf_Controller($handler); + $controller->handleObjectDeletion(); + break; + + default: + $showAll = imforum_admin_int('all') === 1; + $criteria = $showAll ? new icms_db_criteria_Compo() : new icms_db_criteria_Compo(new icms_db_criteria_Item('report_result', mod_imforum_Report::RESULT_OPEN)); + $table = new icms_ipf_view_Table($handler, $criteria); + $table->addColumn(new icms_ipf_view_Column('post_id', _GLOBAL_LEFT, false, 'getPostSubject')); + $table->addColumn(new icms_ipf_view_Column('report_text')); + $table->addColumn(new icms_ipf_view_Column('reporter_uid', _GLOBAL_LEFT, 120, 'getReporterLink')); + $table->addColumn(new icms_ipf_view_Column('report_time', 'center', 140)); + $table->addColumn(new icms_ipf_view_Column('report_result', 'center', 80)); + $table->setDefaultSort('report_time'); + $table->setDefaultOrder('DESC'); + + $toggle = $showAll + ? '' . _AM_IMFORUM_REPORTS_SHOW_OPEN . '' + : '' . _AM_IMFORUM_REPORTS_SHOW_ALL . ''; + imforum_admin_page(4, _AM_IMFORUM_REPORTS, '

' . $toggle . '

' . $table->fetch(), _AM_IMFORUM_REPORTS_DSC); + break; +} diff --git a/src/admin/suspension.php b/src/admin/suspension.php new file mode 100644 index 0000000..d7acef4 --- /dev/null +++ b/src/admin/suspension.php @@ -0,0 +1,48 @@ +get(imforum_admin_int('suspension_id')); + if ($suspension->isNew()) { + $suspension->setVar('start_time', time()); + $suspension->setVar('end_time', time() + 7 * 86400); + } + $title = $suspension->isNew() ? _AM_IMFORUM_SUSPENSION_ADD : _AM_IMFORUM_SUSPENSION_EDIT; + imforum_admin_page(5, $title, static fn (): string => $suspension->getSecureForm($title, 'addsuspension')->render(), _AM_IMFORUM_SUSPENSION_FORM_DSC); + break; + + case 'addsuspension': + imforum_admin_store($handler, _AM_IMFORUM_SUSPENSION_CREATED, _AM_IMFORUM_SUSPENSION_MODIFIED, imforum_admin_url('suspension.php')); + break; + + case 'del': + $controller = new icms_ipf_Controller($handler); + $controller->handleObjectDeletion(); + break; + + default: + $table = new icms_ipf_view_Table($handler); + $table->addColumn(new icms_ipf_view_Column('uid', _GLOBAL_LEFT, false, 'getUserLink')); + $table->addColumn(new icms_ipf_view_Column('ip')); + $table->addColumn(new icms_ipf_view_Column('forum_id', _GLOBAL_LEFT, false, 'getForumName')); + $table->addColumn(new icms_ipf_view_Column('start_time', 'center', 140)); + $table->addColumn(new icms_ipf_view_Column('end_time', 'center', 140)); + $table->setDefaultSort('end_time'); + $table->setDefaultOrder('DESC'); + $table->addIntroButton('addsuspension', imforum_admin_url('suspension.php', 'op=mod'), _AM_IMFORUM_SUSPENSION_ADD); + imforum_admin_page(5, _AM_IMFORUM_SUSPENSIONS, $table->fetch(), _AM_IMFORUM_SUSPENSIONS_DSC); + break; +} diff --git a/src/class/Archive.php b/src/class/Archive.php index f69510f..be33fa1 100644 --- a/src/class/Archive.php +++ b/src/class/Archive.php @@ -23,4 +23,20 @@ public function __construct(mod_imforum_ArchiveHandler $handler) { $this->quickInitVar('post_text', XOBJ_DTYPE_TXTAREA); $this->quickInitVar('archived_time', XOBJ_DTYPE_LTIME, false, '', '', 0); } + + public function getTopicTitle(): string { + $topic = icms_getModuleHandler('topic', IMFORUM_DIRNAME)->get((int) $this->getVar('topic_id', 'e')); + return $topic->isNew() ? '#' . (int) $this->getVar('topic_id', 'e') : (string) $topic->getVar('topic_title'); + } + + public function getExcerpt(): string { + return htmlspecialchars(icms_core_DataFilter::icms_substr(strip_tags((string) $this->getVar('post_text', 'n')), 0, 120), ENT_QUOTES); + } + + /** + * Admin link to read the whole archived post + */ + public function getViewLink(): string { + return '' . _CO_IMFORUM_VIEW . ''; + } } diff --git a/src/class/Category.php b/src/class/Category.php index a1fdf35..f33432e 100644 --- a/src/class/Category.php +++ b/src/class/Category.php @@ -28,4 +28,12 @@ public function __construct(mod_imforum_CategoryHandler $handler) { $this->setControl('cat_description', ['name' => 'textarea', 'form_editor' => 'default']); $this->setControl('cat_image', ['name' => 'image']); } + + /** + * Title linked to the admin edit form, for the admin category list + */ + public function getAdminLink(): string { + return '' + . $this->getVar('cat_title') . ''; + } } diff --git a/src/class/CategoryHandler.php b/src/class/CategoryHandler.php index db9a687..3961d37 100644 --- a/src/class/CategoryHandler.php +++ b/src/class/CategoryHandler.php @@ -14,6 +14,9 @@ class mod_imforum_CategoryHandler extends icms_ipf_Handler { + /** @var array|null */ + private ?array $selectList = null; + public function __construct(icms_db_legacy_Database $db) { parent::__construct($db, 'category', 'cat_id', 'cat_title', 'cat_description', IMFORUM_DIRNAME); $this->addPermission('category_access', _CO_IMFORUM_PERM_CATEGORY_ACCESS, _CO_IMFORUM_PERM_CATEGORY_ACCESS_DSC); @@ -25,10 +28,23 @@ public function __construct(icms_db_legacy_Database $db) { * @return array */ public function getCategorySelectList(): array { - $criteria = new icms_db_criteria_Compo(); - $criteria->setSort('weight'); - $criteria->setOrder('ASC'); - return $this->getList($criteria); + if ($this->selectList === null) { + $criteria = new icms_db_criteria_Compo(); + $criteria->setSort('weight'); + $criteria->setOrder('ASC'); + $this->selectList = $this->getList($criteria); + } + return $this->selectList; + } + + protected function afterSave(mod_imforum_Category $category): bool { + $this->selectList = null; + return true; + } + + protected function afterDelete(mod_imforum_Category $category): bool { + $this->selectList = null; + return true; } /** diff --git a/src/class/Digest.php b/src/class/Digest.php index aa061dc..6ffc67a 100644 --- a/src/class/Digest.php +++ b/src/class/Digest.php @@ -21,4 +21,18 @@ public function __construct(mod_imforum_DigestHandler $handler) { $this->quickInitVar('digest_time', XOBJ_DTYPE_LTIME, false, '', '', 0); $this->quickInitVar('digest_content', XOBJ_DTYPE_TXTAREA); } + + /** + * First words of the digest, for the admin list + */ + public function getExcerpt(): string { + return htmlspecialchars(icms_core_DataFilter::icms_substr(strip_tags((string) $this->getVar('digest_content', 'n')), 0, 120), ENT_QUOTES); + } + + /** + * Admin link to read the whole digest + */ + public function getViewLink(): string { + return '' . _CO_IMFORUM_VIEW . ''; + } } diff --git a/src/class/Forum.php b/src/class/Forum.php index c68e729..72bfe33 100644 --- a/src/class/Forum.php +++ b/src/class/Forum.php @@ -39,6 +39,11 @@ public function __construct(mod_imforum_ForumHandler $handler) { $this->initiateSEO(); + // Not a column: the admin form edits the moderator rows through it, and + // ForumHandler::afterSave() writes them when it holds a list of user ids + $this->initNonPersistableVar('moderators', XOBJ_DTYPE_OTHER, false, '', false, null, true); + $this->setControl('moderators', ['name' => 'user_multi']); + $this->setControl('cat_id', ['itemHandler' => 'category', 'method' => 'getCategorySelectList', 'module' => IMFORUM_DIRNAME]); $this->setControl('parent_forum', ['itemHandler' => 'forum', 'method' => 'getParentSelectList', 'module' => IMFORUM_DIRNAME]); $this->setControl('forum_desc', ['name' => 'textarea', 'form_editor' => 'default']); @@ -47,6 +52,22 @@ public function __construct(mod_imforum_ForumHandler $handler) { } } + /** + * Name linked to the admin edit form, for the admin forum list + */ + public function getAdminLink(): string { + return '' + . $this->getVar('forum_name') . ''; + } + + /** + * Category title, already escaped by icms_ipf_Handler::getList() + */ + public function getCategoryTitle(): string { + $titles = icms_getModuleHandler('category', IMFORUM_DIRNAME)->getCategorySelectList(); + return (string) ($titles[(int) $this->getVar('cat_id', 'e')] ?? ''); + } + /** * File extensions that may be attached in this forum, lower case * diff --git a/src/class/ForumHandler.php b/src/class/ForumHandler.php index 0ba4f6b..817ed90 100644 --- a/src/class/ForumHandler.php +++ b/src/class/ForumHandler.php @@ -64,6 +64,15 @@ public function getParentSelectList(): array { return [0 => _CO_IMFORUM_FORUM_NO_PARENT] + $this->getForumSelectList(); } + /** + * Options for the forum of a suspension: the forum list plus "every forum" + * + * @return array + */ + public function getScopeSelectList(): array { + return [0 => _CO_IMFORUM_SUSPENSION_ALL_FORUMS] + $this->getForumSelectList(); + } + /** * @param array $options */ @@ -95,6 +104,21 @@ public function synchronise(int $forumId): bool { )); } + /** + * Recount every forum in two queries; used after an import or a prune + */ + public function synchroniseAll(): bool { + $topics = $this->db->prefix(IMFORUM_DIRNAME . '_topic'); + $posts = $this->db->prefix(IMFORUM_DIRNAME . '_post'); + + $ok = (bool) $this->db->queryF("UPDATE {$this->table} f" + . " LEFT JOIN (SELECT forum_id, COUNT(*) AS n FROM $topics WHERE approved = 1 GROUP BY forum_id) t ON t.forum_id = f.forum_id" + . ' SET f.forum_topics = COALESCE(t.n, 0)'); + return (bool) $this->db->queryF("UPDATE {$this->table} f" + . " LEFT JOIN (SELECT forum_id, COUNT(*) AS n, MAX(post_id) AS last FROM $posts WHERE approved = 1 GROUP BY forum_id) p ON p.forum_id = f.forum_id" + . ' SET f.forum_posts = COALESCE(p.n, 0), f.forum_last_post_id = COALESCE(p.last, 0)') && $ok; + } + /** * @return list */ @@ -120,6 +144,20 @@ protected function beforeSave(mod_imforum_Forum $forum): bool { return true; } + /** + * Write the moderators chosen on the admin form, and recount + * + * The counters travel through the form as hidden fields; recounting + * afterwards undoes a stale or tampered value. + */ + protected function afterSave(mod_imforum_Forum $forum): bool { + $forumId = (int) $forum->id(); + $moderators = $forum->getVar('moderators', 'n'); + $ok = !is_array($moderators) + || icms_getModuleHandler('moderator', IMFORUM_DIRNAME)->setModerators($forumId, array_map('intval', $moderators)); + return $this->synchronise($forumId) && $ok; + } + private function getParentId(int $forumId): int { [$parent] = $this->fetchRow("SELECT parent_forum FROM {$this->table} WHERE forum_id = $forumId"); return (int) $parent; diff --git a/src/class/Report.php b/src/class/Report.php index 6072e58..b602364 100644 --- a/src/class/Report.php +++ b/src/class/Report.php @@ -32,4 +32,20 @@ public function __construct(mod_imforum_ReportHandler $handler) { $this->hideFieldFromForm(['post_id', 'reporter_uid', 'reporter_ip', 'report_time']); $this->setControl('report_result', ['name' => 'yesno']); } + + public function getReporterLink(): string { + return icms_member_user_Handler::getUserLink((int) $this->getVar('reporter_uid', 'e')); + } + + /** + * Subject of the reported post, or a note that it is gone + */ + public function getPostSubject(): string { + $post = icms_getModuleHandler('post', IMFORUM_DIRNAME)->get((int) $this->getVar('post_id', 'e')); + return $post->isNew() ? _CO_IMFORUM_REPORT_POST_GONE : (string) $post->getVar('subject'); + } + + public function isOpen(): bool { + return (int) $this->getVar('report_result', 'e') === self::RESULT_OPEN; + } } diff --git a/src/class/Suspension.php b/src/class/Suspension.php index c84f75f..7627475 100644 --- a/src/class/Suspension.php +++ b/src/class/Suspension.php @@ -27,6 +27,19 @@ public function __construct(mod_imforum_SuspensionHandler $handler) { $this->quickInitVar('description', XOBJ_DTYPE_TXTAREA); $this->setControl('uid', ['name' => 'user']); - $this->setControl('forum_id', ['itemHandler' => 'forum', 'method' => 'getParentSelectList', 'module' => IMFORUM_DIRNAME]); + $this->setControl('forum_id', ['itemHandler' => 'forum', 'method' => 'getScopeSelectList', 'module' => IMFORUM_DIRNAME]); + } + + public function getUserLink(): string { + $uid = (int) $this->getVar('uid', 'e'); + return $uid > 0 ? icms_member_user_Handler::getUserLink($uid) : ''; + } + + /** + * Forum name, already escaped, or "every forum" for forum_id 0 + */ + public function getForumName(): string { + $forums = icms_getModuleHandler('forum', IMFORUM_DIRNAME)->getScopeSelectList(); + return $forums[(int) $this->getVar('forum_id', 'e')] ?? ''; } } diff --git a/src/class/TopicHandler.php b/src/class/TopicHandler.php index 02c2b88..9d7250f 100644 --- a/src/class/TopicHandler.php +++ b/src/class/TopicHandler.php @@ -36,6 +36,64 @@ public function synchronise(int $topicId): bool { )); } + /** + * Recount every topic in one query; used after an import or a prune + */ + public function synchroniseAll(): bool { + $posts = $this->db->prefix(IMFORUM_DIRNAME . '_post'); + return (bool) $this->db->queryF("UPDATE {$this->table} t" + . " LEFT JOIN (SELECT topic_id, COUNT(*) AS n, MIN(post_id) AS first, MAX(post_id) AS last FROM $posts WHERE approved = 1 GROUP BY topic_id) p ON p.topic_id = t.topic_id" + . ' SET t.topic_replies = GREATEST(COALESCE(p.n, 0) - 1, 0), t.topic_first_post_id = COALESCE(p.first, 0), t.topic_last_post_id = COALESCE(p.last, 0)'); + } + + /** + * Topics whose last post is older than a moment + * + * @param list $forumIds + * @return list topic ids + */ + public function findInactive(array $forumIds, int $before, bool $keepSticky = true, bool $keepDigest = true): array { + $forumIds = array_values(array_filter(array_map('intval', $forumIds))); + if (!$forumIds) { + return []; + } + $posts = $this->db->prefix(IMFORUM_DIRNAME . '_post'); + $sql = "SELECT t.topic_id FROM {$this->table} t" + . " LEFT JOIN $posts p ON p.post_id = t.topic_last_post_id" + . ' WHERE t.forum_id IN (' . implode(',', $forumIds) . ')' + . ' AND COALESCE(p.post_time, t.topic_time) < ' . $before + . ($keepSticky ? ' AND t.topic_sticky = 0' : '') + . ($keepDigest ? ' AND t.topic_digest = 0' : ''); + + $ids = []; + $result = $this->db->queryF($sql); + while ($result && ($row = $this->db->fetchRow($result))) { + $ids[] = (int) $row[0]; + } + return $ids; + } + + /** + * Move a topic and its posts to another forum, and recount both forums + */ + public function moveToForum(int $topicId, int $forumId): bool { + $topic = $this->get($topicId); + $forumHandler = icms_getModuleHandler('forum', IMFORUM_DIRNAME); + if ($topic->isNew() || $forumHandler->get($forumId)->isNew()) { + return false; + } + $oldForumId = (int) $topic->getVar('forum_id', 'e'); + if ($oldForumId === $forumId) { + return true; + } + + $posts = $this->db->prefix(IMFORUM_DIRNAME . '_post'); + $ok = (bool) $this->db->queryF("UPDATE $posts SET forum_id = $forumId WHERE topic_id = $topicId"); + $topic->setVar('forum_id', $forumId); + $ok = $this->insert($topic, true) && $ok; + return $forumHandler->synchronise($oldForumId) && $ok; + } + 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/icms_version.php b/src/icms_version.php index 858be9d..fdac45e 100644 --- a/src/icms_version.php +++ b/src/icms_version.php @@ -63,8 +63,11 @@ 'templates' => [ ['file' => 'imforum_index.html', 'description' => 'Forum index'], ['file' => 'imforum_admin_index.html', 'description' => 'Administration index'], + ['file' => 'imforum_admin.html', 'description' => 'Administration page'], ], 'blocks' => [], - 'config' => [], + // 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. ]; diff --git a/src/include/admin.php b/src/include/admin.php new file mode 100644 index 0000000..21fbf2f --- /dev/null +++ b/src/include/admin.php @@ -0,0 +1,144 @@ + $writeOps operations that change data + * @param callable(): bool $tokenValid checks (and spends) the token + */ +function imforum_admin_refusal(string $op, array $writeOps, string $method, bool $confirming, callable $tokenValid): ?string { + $writes = in_array($op, $writeOps, true); + if ($writes && $method !== 'POST') { + return _AM_IMFORUM_POST_ONLY; + } + if (($writes || ($method === 'POST' && $confirming)) && !$tokenValid()) { + return _AM_IMFORUM_BAD_TOKEN; + } + return null; +} + +/** + * The requested operation, after the checks of imforum_admin_refusal() + * + * A refused request goes back to the list of the current script. + * + * @param list $writeOps + */ +function imforum_admin_op(array $writeOps): string { + $op = strtolower((string) ($_POST['op'] ?? $_GET['op'] ?? '')); + $op = (string) preg_replace('/[^a-z_]/', '', $op); + + $refusal = imforum_admin_refusal( + $op, + $writeOps, + strtoupper((string) ($_SERVER['REQUEST_METHOD'] ?? 'GET')), + isset($_POST['confirm']), + static fn (): bool => (bool) icms::$security->check() + ); + if ($refusal !== null) { + redirect_header(imforum_admin_url(basename((string) $_SERVER['SCRIPT_NAME'])), 3, $refusal); + exit; + } + return $op; +} + +function imforum_admin_url(string $script, string $query = ''): string { + return IMFORUM_URL . 'admin/' . $script . ($query !== '' ? '?' . $query : ''); +} + +/** + * An integer from the query string or the posted form + */ +function imforum_admin_int(string $name): int { + return (int) ($_POST[$name] ?? $_GET[$name] ?? 0); +} + +/** + * Store the object posted from its IPF form, then redirect + * + * A multi-select with nothing chosen is not posted at all, and + * icms_ipf_permission_Handler::saveItem_Permissions() fails on count(null) + * when a permission is missing. Those fields become empty arrays first. + * + * @param list $multiSelects other multi-select fields of the form + */ +function imforum_admin_store(icms_ipf_Handler $handler, string $created, string $modified, string $redirect, array $multiSelects = []): void { + $fields = array_merge(array_column($handler->getPermissions() ?: [], 'perm_name'), $multiSelects); + foreach ($fields as $field) { + $_POST[$field] = array_map('intval', (array) ($_POST[$field] ?? [])); + } + $controller = new icms_ipf_Controller($handler); + $controller->storeFromDefaultForm($created, $modified, $redirect); +} + +/** + * Show the module's admin menu with one entry selected + * + * When the admin control panel rebuilds its menu cache it include_once's the + * menu.php of every module into another module object, so on that first + * request icms::$module ends up without a menu and displayAdminMenu() fails + * on count(null). Including the file ourselves avoids that. + */ +function imforum_admin_menu(int $menuIndex, string $title): void { + $module = icms::$module; + // the core declares both as arrays, but they are null here + if (empty($module->adminmenu) || empty($module->adminheadermenu)) { + // in a scope of its own, so the file's loop variables stay there + [$module->adminmenu, $module->adminheadermenu] = (static function (): array { + $adminmenu = $headermenu = []; + include dirname(__DIR__) . '/admin/menu.php'; + return [$adminmenu, $headermenu]; + })(); + } + $module->displayAdminMenu($menuIndex, $title); +} + +/** + * Render one admin page: menu, title, optional intro and the content + * + * Pass a form as a closure: form elements such as the date picker add their + * scripts to the theme, which exists only once icms_cp_header() has run. + * + * @param int $menuIndex position of the page in admin/menu.php + * @param string|Closure(): string $content + */ +function imforum_admin_page(int $menuIndex, string $title, string|Closure $content, string $intro = ''): void { + global $icmsAdminTpl; + + icms_cp_header(); + imforum_admin_menu($menuIndex, $title); + $icmsAdminTpl->assign('imforum_title', $title); + $icmsAdminTpl->assign('imforum_intro', $intro); + $icmsAdminTpl->assign('imforum_content', $content instanceof Closure ? $content() : $content); + $icmsAdminTpl->display('db:imforum_admin.html'); + icms_cp_footer(); +} + +/** + * Add an element to a form + * + * icms_form_Base::addElement() keeps a reference to the variable it was + * given, so reusing that variable for the next element would replace the + * earlier one. Passing through this function gives every element its own. + */ +function imforum_form_add(icms_form_Base $form, icms_form_Element $element, bool $required = false): void { + $form->addElement($element, $required); +} diff --git a/src/language/english/admin.php b/src/language/english/admin.php index 4c927ff..bc44e8d 100644 --- a/src/language/english/admin.php +++ b/src/language/english/admin.php @@ -6,3 +6,65 @@ define('_AM_IMFORUM_INDEX', 'imforum administration'); define('_AM_IMFORUM_VERSION', 'Module version'); define('_AM_IMFORUM_DBVERSION', 'Database version'); +define('_AM_IMFORUM_OPEN_REPORTS', 'Open reports'); +define('_AM_IMFORUM_TOPICS', 'Topics'); +define('_AM_IMFORUM_POSTS', 'Posts'); +define('_AM_IMFORUM_POST_ONLY', 'This action only works from its form.'); +define('_AM_IMFORUM_BAD_TOKEN', 'The form has expired or was not sent from this site. Please try again.'); +define('_AM_IMFORUM_CATEGORIES', 'Categories'); +define('_AM_IMFORUM_CATEGORIES_DSC', 'Categories group forums on the index page. A category that still holds forums cannot be deleted.'); +define('_AM_IMFORUM_CATEGORY_ADD', 'Add a category'); +define('_AM_IMFORUM_CATEGORY_EDIT', 'Edit category'); +define('_AM_IMFORUM_CATEGORY_CREATED', 'The category has been created.'); +define('_AM_IMFORUM_CATEGORY_MODIFIED', 'The category has been saved.'); +define('_AM_IMFORUM_FORUMS', 'Forums'); +define('_AM_IMFORUM_FORUMS_DSC', 'Group permissions and moderators are set on the form of each forum. A new forum starts with the groups of the permission template.'); +define('_AM_IMFORUM_FORUM_ADD', 'Add a forum'); +define('_AM_IMFORUM_FORUM_EDIT', 'Edit forum'); +define('_AM_IMFORUM_FORUM_CREATED', 'The forum has been created.'); +define('_AM_IMFORUM_FORUM_MODIFIED', 'The forum has been saved.'); +define('_AM_IMFORUM_FORUM_NEEDS_CATEGORY', 'Create a category first.'); +define('_AM_IMFORUM_FORUM_DELETE_CONFIRM', 'Delete the forum "%s" with all its topics, posts and attachments? Its subforums move up one level. This cannot be undone.'); +define('_AM_IMFORUM_PERMTEMPLATE', 'Permission template'); +define('_AM_IMFORUM_PERMTEMPLATE_DSC', 'The groups chosen here are preselected on the form of every new forum.'); +define('_AM_IMFORUM_PERMTEMPLATE_APPLY', 'Also apply to these forums'); +define('_AM_IMFORUM_PERMTEMPLATE_APPLY_DSC', 'Replaces all permissions of the selected forums with the template.'); +define('_AM_IMFORUM_PERMTEMPLATE_SAVED', 'The permission template has been saved.'); +define('_AM_IMFORUM_PERMTEMPLATE_ERROR', 'The permission template could not be saved completely.'); +define('_AM_IMFORUM_REPORTS', 'Reports'); +define('_AM_IMFORUM_REPORTS_DSC', 'Posts that members reported to the moderators. Open reports are shown first.'); +define('_AM_IMFORUM_REPORTS_SHOW_ALL', 'Show handled reports too'); +define('_AM_IMFORUM_REPORTS_SHOW_OPEN', 'Show open reports only'); +define('_AM_IMFORUM_REPORT_HANDLE', 'Handle report'); +define('_AM_IMFORUM_REPORT_MODIFIED', 'The report has been saved.'); +define('_AM_IMFORUM_SUSPENSIONS', 'Suspensions'); +define('_AM_IMFORUM_SUSPENSIONS_DSC', 'Suspended members and IP addresses can read but not post.'); +define('_AM_IMFORUM_SUSPENSION_ADD', 'Add a suspension'); +define('_AM_IMFORUM_SUSPENSION_EDIT', 'Edit suspension'); +define('_AM_IMFORUM_SUSPENSION_FORM_DSC', 'Choose a member, an IP address or both.'); +define('_AM_IMFORUM_SUSPENSION_CREATED', 'The suspension has been created.'); +define('_AM_IMFORUM_SUSPENSION_MODIFIED', 'The suspension has been saved.'); +define('_AM_IMFORUM_DIGESTS', 'Digests'); +define('_AM_IMFORUM_DIGESTS_DSC', 'Digests that were mailed to subscribers.'); +define('_AM_IMFORUM_DIGEST_OF', 'Digest of %s'); +define('_AM_IMFORUM_ARCHIVE', 'Archive'); +define('_AM_IMFORUM_ARCHIVE_DSC', 'Copies of posts kept when topics were archived.'); +define('_AM_IMFORUM_PRUNE', 'Prune and recount'); +define('_AM_IMFORUM_PRUNE_DSC', 'Delete topics without new posts for a while, or move them to another forum. You see how many topics match before anything happens.'); +define('_AM_IMFORUM_PRUNE_FORUMS', 'Forums'); +define('_AM_IMFORUM_PRUNE_DAYS', 'No new posts for (days)'); +define('_AM_IMFORUM_PRUNE_KEEP_STICKY', 'Keep sticky topics'); +define('_AM_IMFORUM_PRUNE_KEEP_DIGEST', 'Keep featured topics'); +define('_AM_IMFORUM_PRUNE_MOVE_TO', 'What to do with them'); +define('_AM_IMFORUM_PRUNE_DELETE', 'Delete them'); +define('_AM_IMFORUM_PRUNE_PREVIEW', 'Show how many'); +define('_AM_IMFORUM_PRUNE_INCOMPLETE', 'Choose at least one forum and a number of days.'); +define('_AM_IMFORUM_PRUNE_NOTHING', 'No topics match.'); +define('_AM_IMFORUM_PRUNE_CONFIRM_DELETE', 'Delete %d topics with all their posts and attachments? This cannot be undone.'); +define('_AM_IMFORUM_PRUNE_CONFIRM_MOVE', 'Move %d topics to "%s"?'); +define('_AM_IMFORUM_PRUNE_GO', 'Go ahead'); +define('_AM_IMFORUM_PRUNE_DONE', '%d topics processed.'); +define('_AM_IMFORUM_RECOUNT', 'Recount'); +define('_AM_IMFORUM_RECOUNT_DSC', 'Recounts the topics, posts and last posts of every forum and topic. Useful after an import.'); +define('_AM_IMFORUM_RECOUNT_DONE', 'All counters are up to date.'); +define('_AM_IMFORUM_RECOUNT_ERROR', 'Recounting failed.'); diff --git a/src/language/english/common.php b/src/language/english/common.php index 6c2b2bc..2cec4f6 100644 --- a/src/language/english/common.php +++ b/src/language/english/common.php @@ -34,6 +34,8 @@ define('_CO_IMFORUM_FORUM_FORUM_TOPICS', 'Topics'); define('_CO_IMFORUM_FORUM_FORUM_POSTS', 'Posts'); define('_CO_IMFORUM_FORUM_FORUM_LAST_POST_ID', 'Last post'); +define('_CO_IMFORUM_FORUM_MODERATORS', 'Moderators'); +define('_CO_IMFORUM_FORUM_MODERATORS_DSC', 'Members who moderate this forum'); // moderator define('_CO_IMFORUM_MODERATOR_MODERATOR_ID', 'ID'); @@ -168,3 +170,6 @@ define('_CO_IMFORUM_FORUM_NO_PARENT', 'None (top level)'); define('_CO_IMFORUM_FORUM_PARENT_LOOP', 'A forum cannot be placed below itself or below one of its subforums.'); define('_CO_IMFORUM_POST_NO_TOPIC', 'The topic of this post does not exist.'); +define('_CO_IMFORUM_REPORT_POST_GONE', '(post deleted)'); +define('_CO_IMFORUM_SUSPENSION_ALL_FORUMS', 'Every forum'); +define('_CO_IMFORUM_VIEW', 'View'); diff --git a/src/language/english/modinfo.php b/src/language/english/modinfo.php index 11a5e27..d14ff96 100644 --- a/src/language/english/modinfo.php +++ b/src/language/english/modinfo.php @@ -6,3 +6,11 @@ define('_MI_IMFORUM_NAME', 'imforum'); define('_MI_IMFORUM_DESC', 'Community forum built on the ImpressCMS Persistable Framework'); define('_MI_IMFORUM_MENU_INDEX', 'Overview'); +define('_MI_IMFORUM_MENU_CATEGORIES', 'Categories'); +define('_MI_IMFORUM_MENU_FORUMS', 'Forums'); +define('_MI_IMFORUM_MENU_PERMTEMPLATE', 'Permission template'); +define('_MI_IMFORUM_MENU_REPORTS', 'Reports'); +define('_MI_IMFORUM_MENU_SUSPENSIONS', 'Suspensions'); +define('_MI_IMFORUM_MENU_DIGESTS', 'Digests'); +define('_MI_IMFORUM_MENU_ARCHIVE', 'Archive'); +define('_MI_IMFORUM_MENU_PRUNE', 'Prune and recount'); diff --git a/src/language/nederlands/admin.php b/src/language/nederlands/admin.php index 308c02b..3c8b000 100644 --- a/src/language/nederlands/admin.php +++ b/src/language/nederlands/admin.php @@ -1,8 +1,70 @@ +

<{$imforum_title}>

+ <{if $imforum_intro}> +

<{$imforum_intro}>

+ <{/if}> + <{$imforum_content}> + diff --git a/src/templates/imforum_admin_index.html b/src/templates/imforum_admin_index.html index d23ad70..2cffb61 100644 --- a/src/templates/imforum_admin_index.html +++ b/src/templates/imforum_admin_index.html @@ -1,6 +1,17 @@

<{$smarty.const._AM_IMFORUM_INDEX}>

+ <{if $imforum_open_reports > 0}> +

+ <{$smarty.const._AM_IMFORUM_OPEN_REPORTS}>: <{$imforum_open_reports}> +

+ <{/if}> + <{foreach from=$imforum_stats key=label item=count}> + + + + + <{/foreach}> diff --git a/tests/Integration/AdminToolsTest.php b/tests/Integration/AdminToolsTest.php new file mode 100644 index 0000000..2694e86 --- /dev/null +++ b/tests/Integration/AdminToolsTest.php @@ -0,0 +1,104 @@ +id()); + self::topic((int) $forum->id()); + + // As the controller does it: every var from $_POST, hidden counters included + $forum = self::reload('forum', (int) $forum->id()); + $forum->setVar('moderators', [3, 5]); + $forum->setVar('forum_topics', 99); + self::assertTrue(self::handler('forum')->insert($forum, true)); + + self::assertEqualsCanonicalizing([3, 5], self::handler('moderator')->getModeratorIds((int) $forum->id())); + self::assertSame(1, (int) self::reload('forum', (int) $forum->id())->getVar('forum_topics')); + } + + public function testSavingAForumWithoutTheModeratorsFieldKeepsThem(): void + { + $forum = self::forum((int) self::category()->id()); + self::handler('moderator')->setModerators((int) $forum->id(), [4]); + + $forum = self::reload('forum', (int) $forum->id()); + $forum->setVar('forum_name', 'Renamed'); + self::assertTrue(self::handler('forum')->insert($forum, true)); + + self::assertSame([4], self::handler('moderator')->getModeratorIds((int) $forum->id())); + } + + public function testSynchroniseAllRepairsEveryCounter(): void + { + $cat = (int) self::category()->id(); + $busy = self::forum($cat, 'Busy'); + $empty = self::forum($cat, 'Empty'); + $topic = self::topic((int) $busy->id()); + $reply = self::post((int) $topic->id()); + + $prefix = \icms::$xoopsDB->prefix('imforum_'); + Database::exec("UPDATE {$prefix}forum SET forum_topics = 7, forum_posts = 7, forum_last_post_id = 7"); + Database::exec("UPDATE {$prefix}topic SET topic_replies = 7, topic_first_post_id = 7, topic_last_post_id = 7"); + + self::assertTrue(self::handler('topic')->synchroniseAll()); + self::assertTrue(self::handler('forum')->synchroniseAll()); + + $topic = self::reload('topic', (int) $topic->id()); + self::assertSame(1, (int) $topic->getVar('topic_replies')); + self::assertSame((int) $reply->id(), (int) $topic->getVar('topic_last_post_id')); + $busy = self::reload('forum', (int) $busy->id()); + self::assertSame([1, 2, (int) $reply->id()], [(int) $busy->getVar('forum_topics'), (int) $busy->getVar('forum_posts'), (int) $busy->getVar('forum_last_post_id')]); + $empty = self::reload('forum', (int) $empty->id()); + self::assertSame([0, 0, 0], [(int) $empty->getVar('forum_topics'), (int) $empty->getVar('forum_posts'), (int) $empty->getVar('forum_last_post_id')]); + } + + public function testFindInactiveLooksAtTheLastPost(): void + { + $forumId = (int) self::forum((int) self::category()->id())->id(); + $old = self::topic($forumId, 'Old'); + $revived = self::topic($forumId, 'Revived'); + $sticky = self::topic($forumId, 'Sticky'); + + $prefix = \icms::$xoopsDB->prefix('imforum_'); + $longAgo = time() - 100 * 86400; + Database::exec("UPDATE {$prefix}post SET post_time = $longAgo"); + Database::exec("UPDATE {$prefix}topic SET topic_time = $longAgo"); + Database::exec("UPDATE {$prefix}topic SET topic_sticky = 1 WHERE topic_id = " . (int) $sticky->id()); + self::post((int) $revived->id()); + + $before = time() - 30 * 86400; + self::assertSame([(int) $old->id()], self::handler('topic')->findInactive([$forumId], $before)); + self::assertEqualsCanonicalizing( + [(int) $old->id(), (int) $sticky->id()], + self::handler('topic')->findInactive([$forumId], $before, false) + ); + self::assertSame([], self::handler('topic')->findInactive([], $before)); + } + + public function testMoveToForumTakesThePostsAlong(): void + { + $cat = (int) self::category()->id(); + $from = self::forum($cat, 'From'); + $to = self::forum($cat, 'To'); + $topic = self::topic((int) $from->id()); + self::post((int) $topic->id()); + + self::assertTrue(self::handler('topic')->moveToForum((int) $topic->id(), (int) $to->id())); + self::assertFalse(self::handler('topic')->moveToForum((int) $topic->id(), 999)); + + $prefix = \icms::$xoopsDB->prefix('imforum_'); + self::assertSame(0, (int) \icms::$xoopsDB->fetchRow(Database::exec("SELECT COUNT(*) FROM {$prefix}post WHERE forum_id <> " . (int) $to->id()))[0]); + self::assertSame(0, (int) self::reload('forum', (int) $from->id())->getVar('forum_posts')); + $to = self::reload('forum', (int) $to->id()); + self::assertSame([1, 2], [(int) $to->getVar('forum_topics'), (int) $to->getVar('forum_posts')]); + } +} diff --git a/tests/Unit/AdminMenuTest.php b/tests/Unit/AdminMenuTest.php index 3ef293b..c6c77e0 100644 --- a/tests/Unit/AdminMenuTest.php +++ b/tests/Unit/AdminMenuTest.php @@ -30,6 +30,17 @@ public function testAdminMenuHasEntries(): void self::assertNotEmpty(self::$adminmenu); } + public function testEveryEntryLinksToAnExistingScriptThatShowsItsOwnTab(): void + { + foreach (self::$adminmenu as $index => $entry) { + $file = IMFORUM_TEST_MODULE_PATH . '/' . $entry['link']; + self::assertFileExists($file); + if ($index > 0) { + self::assertMatchesRegularExpression('/imforum_admin_page\\(' . $index . ',/', (string) file_get_contents($file), $entry['link']); + } + } + } + public function testHeaderMenuIsANonEmptyArray(): void { // displayAdminMenu() calls count() on it; null is a fatal error on PHP 8. diff --git a/tests/Unit/AdminRequestTest.php b/tests/Unit/AdminRequestTest.php new file mode 100644 index 0000000..516f41a --- /dev/null +++ b/tests/Unit/AdminRequestTest.php @@ -0,0 +1,54 @@ + + */ + public static function requests(): array + { + return [ + 'list on GET' => ['list', 'GET', false, false, null], + 'write on GET' => ['addforum', 'GET', false, true, '_AM_IMFORUM_POST_ONLY'], + 'write without token' => ['addforum', 'POST', false, false, '_AM_IMFORUM_BAD_TOKEN'], + 'write with token' => ['addforum', 'POST', false, true, null], + 'delete confirmation without token' => ['del', 'POST', true, false, '_AM_IMFORUM_BAD_TOKEN'], + 'delete confirmation with token' => ['del', 'POST', true, true, null], + 'delete question on GET' => ['del', 'GET', false, false, null], + ]; + } + + #[DataProvider('requests')] + public function testRefusal(string $op, string $method, bool $confirming, bool $tokenValid, ?string $expected): void + { + $refusal = imforum_admin_refusal($op, self::WRITES, $method, $confirming, static fn (): bool => $tokenValid); + self::assertSame($expected === null ? null : constant($expected), $refusal); + } + + public function testTokenIsNotCheckedForAPlainRead(): void + { + $checked = false; + imforum_admin_refusal('list', self::WRITES, 'GET', false, static function () use (&$checked): bool { + $checked = true; + return false; + }); + self::assertFalse($checked, 'checking spends the token'); + } +} diff --git a/tests/Unit/ModuleDefinitionTest.php b/tests/Unit/ModuleDefinitionTest.php index abea95b..47ff790 100644 --- a/tests/Unit/ModuleDefinitionTest.php +++ b/tests/Unit/ModuleDefinitionTest.php @@ -79,6 +79,13 @@ public function testEveryTemplateExists(): void } } + public function testConfigIsAbsentOrNotEmpty(): void + { + // an empty array still sets hasconfig, which adds a Preferences link that + // ends on the preferences of the system module + self::assertTrue(!isset(self::$modversion['config']) || self::$modversion['config'] !== []); + } + public function testDatabaseVersionIsDefined(): void { // moduleUpgrade() reads it with constant() and would throw if it were missing. diff --git a/tests/phpstan-bootstrap.php b/tests/phpstan-bootstrap.php index 3f0fb6c..9f0c4b7 100644 --- a/tests/phpstan-bootstrap.php +++ b/tests/phpstan-bootstrap.php @@ -15,6 +15,11 @@ define('ICMS_GROUP_USERS', 2); define('ICMS_GROUP_ANONYMOUS', 3); +// set by the core's include/common.php at runtime +define('_GLOBAL_LEFT', 'left'); +// the _CO_ICMS_* strings of the IPF forms and tables +require_once $core . '/modules/system/language/english/common.php'; + require_once dirname(__DIR__) . '/src/include/common.php'; foreach (['modinfo', 'main', 'admin', 'common'] as $file) {
<{$label}><{$count}>
<{$smarty.const._AM_IMFORUM_VERSION}> <{$imforum_version}>