/**
  * Show the list of topics in this board, along with any sub-boards.
  * @uses MessageIndex template topic_listing sub template
  */
 public function action_messageindex()
 {
     global $txt, $scripturl, $board, $modSettings, $context;
     global $options, $settings, $board_info, $user_info;
     // Fairly often, we'll work with boards. Current board, sub-boards.
     require_once SUBSDIR . '/Boards.subs.php';
     // If this is a redirection board head off.
     if ($board_info['redirect']) {
         incrementBoard($board, 'num_posts');
         redirectexit($board_info['redirect']);
     }
     loadTemplate('MessageIndex');
     loadJavascriptFile('topic.js');
     $context['name'] = $board_info['name'];
     $context['sub_template'] = 'topic_listing';
     $context['description'] = $board_info['description'];
     $template_layers = Template_Layers::getInstance();
     // How many topics do we have in total?
     $board_info['total_topics'] = allowedTo('approve_posts') ? $board_info['num_topics'] + $board_info['unapproved_topics'] : $board_info['num_topics'] + $board_info['unapproved_user_topics'];
     // View all the topics, or just a few?
     $context['topics_per_page'] = empty($modSettings['disableCustomPerPage']) && !empty($options['topics_per_page']) ? $options['topics_per_page'] : $modSettings['defaultMaxTopics'];
     $context['messages_per_page'] = empty($modSettings['disableCustomPerPage']) && !empty($options['messages_per_page']) ? $options['messages_per_page'] : $modSettings['defaultMaxMessages'];
     $maxindex = isset($_REQUEST['all']) && !empty($modSettings['enableAllMessages']) ? $board_info['total_topics'] : $context['topics_per_page'];
     // Right, let's only index normal stuff!
     if (count($_GET) > 1) {
         $session_name = session_name();
         foreach ($_GET as $k => $v) {
             if (!in_array($k, array('board', 'start', $session_name))) {
                 $context['robot_no_index'] = true;
             }
         }
     }
     if (!empty($_REQUEST['start']) && (!is_numeric($_REQUEST['start']) || $_REQUEST['start'] % $context['messages_per_page'] != 0)) {
         $context['robot_no_index'] = true;
     }
     // If we can view unapproved messages and there are some build up a list.
     if (allowedTo('approve_posts') && ($board_info['unapproved_topics'] || $board_info['unapproved_posts'])) {
         $untopics = $board_info['unapproved_topics'] ? '<a href="' . $scripturl . '?action=moderate;area=postmod;sa=topics;brd=' . $board . '">' . $board_info['unapproved_topics'] . '</a>' : 0;
         $unposts = $board_info['unapproved_posts'] ? '<a href="' . $scripturl . '?action=moderate;area=postmod;sa=posts;brd=' . $board . '">' . ($board_info['unapproved_posts'] - $board_info['unapproved_topics']) . '</a>' : 0;
         $context['unapproved_posts_message'] = sprintf($txt['there_are_unapproved_topics'], $untopics, $unposts, $scripturl . '?action=moderate;area=postmod;sa=' . ($board_info['unapproved_topics'] ? 'topics' : 'posts') . ';brd=' . $board);
     }
     // We only know these.
     if (isset($_REQUEST['sort']) && !in_array($_REQUEST['sort'], array('subject', 'starter', 'last_poster', 'replies', 'views', 'likes', 'first_post', 'last_post'))) {
         $_REQUEST['sort'] = 'last_post';
     }
     // Make sure the starting place makes sense and construct the page index.
     if (isset($_REQUEST['sort'])) {
         $sort_string = ';sort=' . $_REQUEST['sort'] . (isset($_REQUEST['desc']) ? ';desc' : '');
     } else {
         $sort_string = '';
     }
     $context['page_index'] = constructPageIndex($scripturl . '?board=' . $board . '.%1$d' . $sort_string, $_REQUEST['start'], $board_info['total_topics'], $maxindex, true);
     $context['start'] =& $_REQUEST['start'];
     // Set a canonical URL for this page.
     $context['canonical_url'] = $scripturl . '?board=' . $board . '.' . $context['start'];
     $context['links'] += array('prev' => $_REQUEST['start'] >= $context['topics_per_page'] ? $scripturl . '?board=' . $board . '.' . ($_REQUEST['start'] - $context['topics_per_page']) : '', 'next' => $_REQUEST['start'] + $context['topics_per_page'] < $board_info['total_topics'] ? $scripturl . '?board=' . $board . '.' . ($_REQUEST['start'] + $context['topics_per_page']) : '');
     $context['page_info'] = array('current_page' => $_REQUEST['start'] / $context['topics_per_page'] + 1, 'num_pages' => floor(($board_info['total_topics'] - 1) / $context['topics_per_page']) + 1);
     if (isset($_REQUEST['all']) && !empty($modSettings['enableAllMessages']) && $maxindex > $modSettings['enableAllMessages']) {
         $maxindex = $modSettings['enableAllMessages'];
         $_REQUEST['start'] = 0;
     }
     // Build a list of the board's moderators.
     $context['moderators'] =& $board_info['moderators'];
     $context['link_moderators'] = array();
     if (!empty($board_info['moderators'])) {
         foreach ($board_info['moderators'] as $mod) {
             $context['link_moderators'][] = '<a href="' . $scripturl . '?action=profile;u=' . $mod['id'] . '" title="' . $txt['board_moderator'] . '">' . $mod['name'] . '</a>';
         }
     }
     // Mark current and parent boards as seen.
     if (!$user_info['is_guest']) {
         // We can't know they read it if we allow prefetches.
         if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch') {
             @ob_end_clean();
             header('HTTP/1.1 403 Prefetch Forbidden');
             die;
         }
         // Mark the board as read, and its parents.
         if (!empty($board_info['parent_boards'])) {
             $board_list = array_keys($board_info['parent_boards']);
             $board_list[] = $board;
         } else {
             $board_list = array($board);
         }
         // Mark boards as read. Boards alone, no need for topics.
         markBoardsRead($board_list, false, false);
         // Clear topicseen cache
         if (!empty($board_info['parent_boards'])) {
             // We've seen all these boards now!
             foreach ($board_info['parent_boards'] as $k => $dummy) {
                 if (isset($_SESSION['topicseen_cache'][$k])) {
                     unset($_SESSION['topicseen_cache'][$k]);
                 }
             }
         }
         if (isset($_SESSION['topicseen_cache'][$board])) {
             unset($_SESSION['topicseen_cache'][$board]);
         }
         // From now on, they've seen it. So we reset notifications.
         $context['is_marked_notify'] = resetSentBoardNotification($user_info['id'], $board);
     } else {
         $context['is_marked_notify'] = false;
     }
     // 'Print' the header and board info.
     $context['page_title'] = strip_tags($board_info['name']);
     // Set the variables up for the template.
     $context['can_mark_notify'] = allowedTo('mark_notify') && !$user_info['is_guest'];
     $context['can_post_new'] = allowedTo('post_new') || $modSettings['postmod_active'] && allowedTo('post_unapproved_topics');
     $context['can_post_poll'] = !empty($modSettings['pollMode']) && allowedTo('poll_post') && $context['can_post_new'];
     $context['can_moderate_forum'] = allowedTo('moderate_forum');
     $context['can_approve_posts'] = allowedTo('approve_posts');
     // Prepare sub-boards for display.
     require_once SUBSDIR . '/BoardsList.class.php';
     $boardIndexOptions = array('include_categories' => false, 'base_level' => $board_info['child_level'] + 1, 'parent_id' => $board_info['id'], 'set_latest_post' => false, 'countChildPosts' => !empty($modSettings['countChildPosts']));
     $boardlist = new Boards_List($boardIndexOptions);
     $context['boards'] = $boardlist->getBoards();
     // Nosey, nosey - who's viewing this board?
     if (!empty($settings['display_who_viewing'])) {
         require_once SUBSDIR . '/Who.subs.php';
         formatViewers($board, 'board');
     }
     // And now, what we're here for: topics!
     require_once SUBSDIR . '/MessageIndex.subs.php';
     // Known sort methods.
     $sort_methods = messageIndexSort();
     // They didn't pick one, default to by last post descending.
     if (!isset($_REQUEST['sort']) || !isset($sort_methods[$_REQUEST['sort']])) {
         $context['sort_by'] = 'last_post';
         $ascending = isset($_REQUEST['asc']);
     } else {
         $context['sort_by'] = $_REQUEST['sort'];
         $ascending = !isset($_REQUEST['desc']);
     }
     $sort_column = $sort_methods[$context['sort_by']];
     $context['sort_direction'] = $ascending ? 'up' : 'down';
     $context['sort_title'] = $ascending ? $txt['sort_desc'] : $txt['sort_asc'];
     // Trick
     $txt['starter'] = $txt['started_by'];
     foreach ($sort_methods as $key => $val) {
         $context['topics_headers'][$key] = array('url' => $scripturl . '?board=' . $context['current_board'] . '.' . $context['start'] . ';sort=' . $key . ($context['sort_by'] == $key && $context['sort_direction'] == 'up' ? ';desc' : ''), 'sort_dir_img' => $context['sort_by'] == $key ? '<img class="sort" src="' . $settings['images_url'] . '/sort_' . $context['sort_direction'] . '.png" alt="" title="' . $context['sort_title'] . '" />' : '');
     }
     // Calculate the fastest way to get the topics.
     $start = (int) $_REQUEST['start'];
     if ($start > ($board_info['total_topics'] - 1) / 2) {
         $ascending = !$ascending;
         $fake_ascending = true;
         $maxindex = $board_info['total_topics'] < $start + $maxindex + 1 ? $board_info['total_topics'] - $start : $maxindex;
         $start = $board_info['total_topics'] < $start + $maxindex + 1 ? 0 : $board_info['total_topics'] - $start - $maxindex;
     } else {
         $fake_ascending = false;
     }
     // Setup the default topic icons...
     $context['icon_sources'] = MessageTopicIcons();
     $topic_ids = array();
     $context['topics'] = array();
     // Set up the query options
     $indexOptions = array('include_sticky' => !empty($modSettings['enableStickyTopics']), 'only_approved' => $modSettings['postmod_active'] && !allowedTo('approve_posts'), 'previews' => !empty($modSettings['message_index_preview']) ? empty($modSettings['preview_characters']) ? -1 : $modSettings['preview_characters'] : 0, 'include_avatars' => !empty($settings['avatars_on_indexes']), 'ascending' => $ascending, 'fake_ascending' => $fake_ascending);
     // Allow integration to modify / add to the $indexOptions
     call_integration_hook('integrate_messageindex_topics', array(&$sort_column, &$indexOptions));
     $topics_info = messageIndexTopics($board, $user_info['id'], $start, $maxindex, $context['sort_by'], $sort_column, $indexOptions);
     // Prepare for links to guests (for search engines)
     $context['pageindex_multiplier'] = empty($modSettings['disableCustomPerPage']) && !empty($options['messages_per_page']) ? $options['messages_per_page'] : $modSettings['defaultMaxMessages'];
     // Begin 'printing' the message index for current board.
     foreach ($topics_info as $row) {
         $topic_ids[] = $row['id_topic'];
         // Do they want message previews?
         if (!empty($modSettings['message_index_preview'])) {
             // Limit them to $modSettings['preview_characters'] characters
             $row['first_body'] = strip_tags(strtr(parse_bbc($row['first_body'], false, $row['id_first_msg']), array('<br />' => "\n", '&nbsp;' => ' ')));
             $row['first_body'] = Util::shorten_text($row['first_body'], !empty($modSettings['preview_characters']) ? $modSettings['preview_characters'] : 128, true);
             // No reply then they are the same, no need to process it again
             if ($row['num_replies'] == 0) {
                 $row['last_body'] == $row['first_body'];
             } else {
                 $row['last_body'] = strip_tags(strtr(parse_bbc($row['last_body'], false, $row['id_last_msg']), array('<br />' => "\n", '&nbsp;' => ' ')));
                 $row['last_body'] = Util::shorten_text($row['last_body'], !empty($modSettings['preview_characters']) ? $modSettings['preview_characters'] : 128, true);
             }
             // Censor the subject and message preview.
             censorText($row['first_subject']);
             censorText($row['first_body']);
             // Don't censor them twice!
             if ($row['id_first_msg'] == $row['id_last_msg']) {
                 $row['last_subject'] = $row['first_subject'];
                 $row['last_body'] = $row['first_body'];
             } else {
                 censorText($row['last_subject']);
                 censorText($row['last_body']);
             }
         } else {
             $row['first_body'] = '';
             $row['last_body'] = '';
             censorText($row['first_subject']);
             if ($row['id_first_msg'] == $row['id_last_msg']) {
                 $row['last_subject'] = $row['first_subject'];
             } else {
                 censorText($row['last_subject']);
             }
         }
         // Decide how many pages the topic should have.
         if ($row['num_replies'] + 1 > $context['messages_per_page']) {
             // We can't pass start by reference.
             $start = -1;
             $pages = constructPageIndex($scripturl . '?topic=' . $row['id_topic'] . '.%1$d', $start, $row['num_replies'] + 1, $context['messages_per_page'], true, array('prev_next' => false, 'all' => !empty($modSettings['enableAllMessages']) && $row['num_replies'] + 1 < $modSettings['enableAllMessages']));
         } else {
             $pages = '';
         }
         // We need to check the topic icons exist...
         if (!empty($modSettings['messageIconChecks_enable'])) {
             if (!isset($context['icon_sources'][$row['first_icon']])) {
                 $context['icon_sources'][$row['first_icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $row['first_icon'] . '.png') ? 'images_url' : 'default_images_url';
             }
             if (!isset($context['icon_sources'][$row['last_icon']])) {
                 $context['icon_sources'][$row['last_icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $row['last_icon'] . '.png') ? 'images_url' : 'default_images_url';
             }
         } else {
             if (!isset($context['icon_sources'][$row['first_icon']])) {
                 $context['icon_sources'][$row['first_icon']] = 'images_url';
             }
             if (!isset($context['icon_sources'][$row['last_icon']])) {
                 $context['icon_sources'][$row['last_icon']] = 'images_url';
             }
         }
         // 'Print' the topic info.
         $context['topics'][$row['id_topic']] = array('id' => $row['id_topic'], 'first_post' => array('id' => $row['id_first_msg'], 'member' => array('username' => $row['first_member_name'], 'name' => $row['first_display_name'], 'id' => $row['first_id_member'], 'href' => !empty($row['first_id_member']) ? $scripturl . '?action=profile;u=' . $row['first_id_member'] : '', 'link' => !empty($row['first_id_member']) ? '<a href="' . $scripturl . '?action=profile;u=' . $row['first_id_member'] . '" title="' . $txt['profile_of'] . ' ' . $row['first_display_name'] . '" class="preview">' . $row['first_display_name'] . '</a>' : $row['first_display_name']), 'time' => standardTime($row['first_poster_time']), 'html_time' => htmlTime($row['first_poster_time']), 'timestamp' => forum_time(true, $row['first_poster_time']), 'subject' => $row['first_subject'], 'preview' => trim($row['first_body']), 'icon' => $row['first_icon'], 'icon_url' => $settings[$context['icon_sources'][$row['first_icon']]] . '/post/' . $row['first_icon'] . '.png', 'href' => $scripturl . '?topic=' . $row['id_topic'] . '.0', 'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0">' . $row['first_subject'] . '</a>'), 'last_post' => array('id' => $row['id_last_msg'], 'member' => array('username' => $row['last_member_name'], 'name' => $row['last_display_name'], 'id' => $row['last_id_member'], 'href' => !empty($row['last_id_member']) ? $scripturl . '?action=profile;u=' . $row['last_id_member'] : '', 'link' => !empty($row['last_id_member']) ? '<a href="' . $scripturl . '?action=profile;u=' . $row['last_id_member'] . '">' . $row['last_display_name'] . '</a>' : $row['last_display_name']), 'time' => standardTime($row['last_poster_time']), 'html_time' => htmlTime($row['last_poster_time']), 'timestamp' => forum_time(true, $row['last_poster_time']), 'subject' => $row['last_subject'], 'preview' => trim($row['last_body']), 'icon' => $row['last_icon'], 'icon_url' => $settings[$context['icon_sources'][$row['last_icon']]] . '/post/' . $row['last_icon'] . '.png', 'href' => $scripturl . '?topic=' . $row['id_topic'] . ($user_info['is_guest'] ? '.' . (int) ($row['num_replies'] / $context['pageindex_multiplier']) * $context['pageindex_multiplier'] . '#msg' . $row['id_last_msg'] : ($row['num_replies'] == 0 ? '.0' : '.msg' . $row['id_last_msg']) . '#new'), 'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . ($user_info['is_guest'] ? '.' . (int) ($row['num_replies'] / $context['pageindex_multiplier']) * $context['pageindex_multiplier'] . '#msg' . $row['id_last_msg'] : ($row['num_replies'] == 0 ? '.0' : '.msg' . $row['id_last_msg']) . '#new') . '" ' . ($row['num_replies'] == 0 ? '' : 'rel="nofollow"') . '>' . $row['last_subject'] . '</a>'), 'default_preview' => trim($row[!empty($modSettings['message_index_preview']) && $modSettings['message_index_preview'] == 2 ? 'last_body' : 'first_body']), 'is_sticky' => !empty($modSettings['enableStickyTopics']) && !empty($row['is_sticky']), 'is_locked' => !empty($row['locked']), 'is_poll' => !empty($modSettings['pollMode']) && $row['id_poll'] > 0, 'is_hot' => !empty($modSettings['useLikesNotViews']) ? $row['num_likes'] >= $modSettings['hotTopicPosts'] : $row['num_replies'] >= $modSettings['hotTopicPosts'], 'is_very_hot' => !empty($modSettings['useLikesNotViews']) ? $row['num_likes'] >= $modSettings['hotTopicVeryPosts'] : $row['num_replies'] >= $modSettings['hotTopicVeryPosts'], 'is_posted_in' => false, 'icon' => $row['first_icon'], 'icon_url' => $settings[$context['icon_sources'][$row['first_icon']]] . '/post/' . $row['first_icon'] . '.png', 'subject' => $row['first_subject'], 'new' => $row['new_from'] <= $row['id_msg_modified'], 'new_from' => $row['new_from'], 'newtime' => $row['new_from'], 'new_href' => $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['new_from'] . '#new', 'redir_href' => !empty($row['id_redirect_topic']) ? $scripturl . '?topic=' . $row['id_topic'] . '.0;noredir' : '', 'pages' => $pages, 'replies' => comma_format($row['num_replies']), 'views' => comma_format($row['num_views']), 'likes' => comma_format($row['num_likes']), 'approved' => $row['approved'], 'unapproved_posts' => $row['unapproved_posts']);
         if (!empty($settings['avatars_on_indexes'])) {
             $context['topics'][$row['id_topic']]['last_post']['member']['avatar'] = determineAvatar($row);
         }
         determineTopicClass($context['topics'][$row['id_topic']]);
     }
     // Allow addons to add to the $context['topics']
     call_integration_hook('integrate_messageindex_listing', array($topics_info));
     // Fix the sequence of topics if they were retrieved in the wrong order. (for speed reasons...)
     if ($fake_ascending) {
         $context['topics'] = array_reverse($context['topics'], true);
     }
     if (!empty($modSettings['enableParticipation']) && !$user_info['is_guest'] && !empty($topic_ids)) {
         $topics_participated_in = topicsParticipation($user_info['id'], $topic_ids);
         foreach ($topics_participated_in as $participated) {
             $context['topics'][$participated['id_topic']]['is_posted_in'] = true;
             $context['topics'][$participated['id_topic']]['class'] = 'my_' . $context['topics'][$participated['id_topic']]['class'];
         }
     }
     $context['jump_to'] = array('label' => addslashes(un_htmlspecialchars($txt['jump_to'])), 'board_name' => htmlspecialchars(strtr(strip_tags($board_info['name']), array('&amp;' => '&')), ENT_COMPAT, 'UTF-8'), 'child_level' => $board_info['child_level']);
     // Is Quick Moderation active/needed?
     if (!empty($options['display_quick_mod']) && !empty($context['topics'])) {
         $context['can_markread'] = $context['user']['is_logged'];
         $context['can_lock'] = allowedTo('lock_any');
         $context['can_sticky'] = allowedTo('make_sticky') && !empty($modSettings['enableStickyTopics']);
         $context['can_move'] = allowedTo('move_any');
         $context['can_remove'] = allowedTo('remove_any');
         $context['can_merge'] = allowedTo('merge_any');
         // Ignore approving own topics as it's unlikely to come up...
         $context['can_approve'] = $modSettings['postmod_active'] && allowedTo('approve_posts') && !empty($board_info['unapproved_topics']);
         // Can we restore topics?
         $context['can_restore'] = allowedTo('move_any') && !empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] == $board;
         // Set permissions for all the topics.
         foreach ($context['topics'] as $t => $topic) {
             $started = $topic['first_post']['member']['id'] == $user_info['id'];
             $context['topics'][$t]['quick_mod'] = array('lock' => allowedTo('lock_any') || $started && allowedTo('lock_own'), 'sticky' => allowedTo('make_sticky') && !empty($modSettings['enableStickyTopics']), 'move' => allowedTo('move_any') || $started && allowedTo('move_own'), 'modify' => allowedTo('modify_any') || $started && allowedTo('modify_own'), 'remove' => allowedTo('remove_any') || $started && allowedTo('remove_own'), 'approve' => $context['can_approve'] && $topic['unapproved_posts']);
             $context['can_lock'] |= $started && allowedTo('lock_own');
             $context['can_move'] |= $started && allowedTo('move_own');
             $context['can_remove'] |= $started && allowedTo('remove_own');
         }
         // Can we use quick moderation checkboxes?
         if ($options['display_quick_mod'] == 1) {
             $context['can_quick_mod'] = $context['user']['is_logged'] || $context['can_approve'] || $context['can_remove'] || $context['can_lock'] || $context['can_sticky'] || $context['can_move'] || $context['can_merge'] || $context['can_restore'];
         } else {
             $context['can_quick_mod'] = $context['can_remove'] || $context['can_lock'] || $context['can_sticky'] || $context['can_move'];
         }
     }
     if (!empty($context['can_quick_mod']) && $options['display_quick_mod'] == 1) {
         $context['qmod_actions'] = array('approve', 'remove', 'lock', 'sticky', 'move', 'merge', 'restore', 'markread');
         call_integration_hook('integrate_quick_mod_actions');
     }
     if (!empty($context['boards']) && $context['start'] == 0) {
         $template_layers->add('display_child_boards');
     }
     // If there are children, but no topics and no ability to post topics...
     $context['no_topic_listing'] = !empty($context['boards']) && empty($context['topics']) && !$context['can_post_new'];
     $template_layers->add('topic_listing');
     addJavascriptVar(array('notification_board_notice' => $context['is_marked_notify'] ? $txt['notification_disable_board'] : $txt['notification_enable_board']), true);
     // Build the message index button array.
     $context['normal_buttons'] = array('new_topic' => array('test' => 'can_post_new', 'text' => 'new_topic', 'image' => 'new_topic.png', 'lang' => true, 'url' => $scripturl . '?action=post;board=' . $context['current_board'] . '.0', 'active' => true), 'notify' => array('test' => 'can_mark_notify', 'text' => $context['is_marked_notify'] ? 'unnotify' : 'notify', 'image' => ($context['is_marked_notify'] ? 'un' : '') . 'notify.png', 'lang' => true, 'custom' => 'onclick="return notifyboardButton(this);"', 'url' => $scripturl . '?action=notifyboard;sa=' . ($context['is_marked_notify'] ? 'off' : 'on') . ';board=' . $context['current_board'] . '.' . $context['start'] . ';' . $context['session_var'] . '=' . $context['session_id']));
     // They can only mark read if they are logged in and it's enabled!
     if (!$user_info['is_guest'] && $settings['show_mark_read']) {
         $context['normal_buttons']['markread'] = array('text' => 'mark_read_short', 'image' => 'markread.png', 'lang' => true, 'url' => $scripturl . '?action=markasread;sa=board;board=' . $context['current_board'] . '.0;' . $context['session_var'] . '=' . $context['session_id'], 'custom' => 'onclick="return markboardreadButton(this);"');
     }
     // Allow adding new buttons easily.
     call_integration_hook('integrate_messageindex_buttons');
 }
示例#2
0
    /**
     * Gather the results and show them.
     *
     * What it does:
     * - checks user input and searches the messages table for messages matching the query.
     * - requires the search_posts permission.
     * - uses the results sub template of the Search template.
     * - uses the Search language file.
     * - stores the results into the search cache.
     * - show the results of the search query.
     */
    public function action_results()
    {
        global $scripturl, $modSettings, $txt;
        global $user_info, $context, $options, $messages_request, $boards_can;
        global $excludedWords, $participants;
        // We shouldn't be working with the db, but we do :P
        $db = database();
        $db_search = db_search();
        // No, no, no... this is a bit hard on the server, so don't you go prefetching it!
        if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch') {
            @ob_end_clean();
            header('HTTP/1.1 403 Forbidden');
            die;
        }
        $this->_setup_weight_factors();
        // These vars don't require an interface, they're just here for tweaking.
        $recentPercentage = 0.3;
        $humungousTopicPosts = 200;
        $maxMembersToSearch = 500;
        $maxMessageResults = empty($modSettings['search_max_results']) ? 0 : $modSettings['search_max_results'] * 5;
        // Start with no errors.
        $context['search_errors'] = array();
        // Number of pages hard maximum - normally not set at all.
        $modSettings['search_max_results'] = empty($modSettings['search_max_results']) ? 200 * $modSettings['search_results_per_page'] : (int) $modSettings['search_max_results'];
        // Maximum length of the string.
        $context['search_string_limit'] = 100;
        loadLanguage('Search');
        if (!isset($_REQUEST['xml'])) {
            loadTemplate('Search');
        } else {
            $context['sub_template'] = 'results';
        }
        // Are you allowed?
        isAllowedTo('search_posts');
        require_once CONTROLLERDIR . '/Display.controller.php';
        require_once SUBSDIR . '/Package.subs.php';
        require_once SUBSDIR . '/Search.subs.php';
        // Load up the search API we are going to use.
        $searchAPI = findSearchAPI();
        // $search_params will carry all settings that differ from the default search parameters.
        // That way, the URLs involved in a search page will be kept as short as possible.
        $search_params = array();
        if (isset($_REQUEST['params'])) {
            // Due to IE's 2083 character limit, we have to compress long search strings
            $temp_params = base64_decode(str_replace(array('-', '_', '.'), array('+', '/', '='), $_REQUEST['params']));
            // Test for gzuncompress failing
            $temp_params2 = @gzuncompress($temp_params);
            $temp_params = explode('|"|', !empty($temp_params2) ? $temp_params2 : $temp_params);
            foreach ($temp_params as $i => $data) {
                @(list($k, $v) = explode('|\'|', $data));
                $search_params[$k] = $v;
            }
            if (isset($search_params['brd'])) {
                $search_params['brd'] = empty($search_params['brd']) ? array() : explode(',', $search_params['brd']);
            }
        }
        // Store whether simple search was used (needed if the user wants to do another query).
        if (!isset($search_params['advanced'])) {
            $search_params['advanced'] = empty($_REQUEST['advanced']) ? 0 : 1;
        }
        // 1 => 'allwords' (default, don't set as param) / 2 => 'anywords'.
        if (!empty($search_params['searchtype']) || !empty($_REQUEST['searchtype']) && $_REQUEST['searchtype'] == 2) {
            $search_params['searchtype'] = 2;
        }
        // Minimum age of messages. Default to zero (don't set param in that case).
        if (!empty($search_params['minage']) || !empty($_REQUEST['minage']) && $_REQUEST['minage'] > 0) {
            $search_params['minage'] = !empty($search_params['minage']) ? (int) $search_params['minage'] : (int) $_REQUEST['minage'];
        }
        // Maximum age of messages. Default to infinite (9999 days: param not set).
        if (!empty($search_params['maxage']) || !empty($_REQUEST['maxage']) && $_REQUEST['maxage'] < 9999) {
            $search_params['maxage'] = !empty($search_params['maxage']) ? (int) $search_params['maxage'] : (int) $_REQUEST['maxage'];
        }
        // Searching a specific topic?
        if (!empty($_REQUEST['topic']) || !empty($_REQUEST['search_selection']) && $_REQUEST['search_selection'] == 'topic') {
            $search_params['topic'] = empty($_REQUEST['search_selection']) ? (int) $_REQUEST['topic'] : (isset($_REQUEST['sd_topic']) ? (int) $_REQUEST['sd_topic'] : '');
            $search_params['show_complete'] = true;
        } elseif (!empty($search_params['topic'])) {
            $search_params['topic'] = (int) $search_params['topic'];
        }
        if (!empty($search_params['minage']) || !empty($search_params['maxage'])) {
            $request = $db->query('', '
				SELECT ' . (empty($search_params['maxage']) ? '0, ' : 'IFNULL(MIN(id_msg), -1), ') . (empty($search_params['minage']) ? '0' : 'IFNULL(MAX(id_msg), -1)') . '
				FROM {db_prefix}messages
				WHERE 1=1' . ($modSettings['postmod_active'] ? '
					AND approved = {int:is_approved_true}' : '') . (empty($search_params['minage']) ? '' : '
					AND poster_time <= {int:timestamp_minimum_age}') . (empty($search_params['maxage']) ? '' : '
					AND poster_time >= {int:timestamp_maximum_age}'), array('timestamp_minimum_age' => empty($search_params['minage']) ? 0 : time() - 86400 * $search_params['minage'], 'timestamp_maximum_age' => empty($search_params['maxage']) ? 0 : time() - 86400 * $search_params['maxage'], 'is_approved_true' => 1));
            list($minMsgID, $maxMsgID) = $db->fetch_row($request);
            if ($minMsgID < 0 || $maxMsgID < 0) {
                $context['search_errors']['no_messages_in_time_frame'] = true;
            }
            $db->free_result($request);
        }
        // Default the user name to a wildcard matching every user (*).
        if (!empty($search_params['userspec']) || !empty($_REQUEST['userspec']) && $_REQUEST['userspec'] != '*') {
            $search_params['userspec'] = isset($search_params['userspec']) ? $search_params['userspec'] : $_REQUEST['userspec'];
        }
        // If there's no specific user, then don't mention it in the main query.
        if (empty($search_params['userspec'])) {
            $userQuery = '';
        } else {
            $userString = strtr(Util::htmlspecialchars($search_params['userspec'], ENT_QUOTES), array('&quot;' => '"'));
            $userString = strtr($userString, array('%' => '\\%', '_' => '\\_', '*' => '%', '?' => '_'));
            preg_match_all('~"([^"]+)"~', $userString, $matches);
            $possible_users = array_merge($matches[1], explode(',', preg_replace('~"[^"]+"~', '', $userString)));
            for ($k = 0, $n = count($possible_users); $k < $n; $k++) {
                $possible_users[$k] = trim($possible_users[$k]);
                if (strlen($possible_users[$k]) == 0) {
                    unset($possible_users[$k]);
                }
            }
            // Create a list of database-escaped search names.
            $realNameMatches = array();
            foreach ($possible_users as $possible_user) {
                $realNameMatches[] = $db->quote('{string:possible_user}', array('possible_user' => $possible_user));
            }
            // Retrieve a list of possible members.
            $request = $db->query('', '
				SELECT id_member
				FROM {db_prefix}members
				WHERE {raw:match_possible_users}', array('match_possible_users' => 'real_name LIKE ' . implode(' OR real_name LIKE ', $realNameMatches)));
            // Simply do nothing if there're too many members matching the criteria.
            if ($db->num_rows($request) > $maxMembersToSearch) {
                $userQuery = '';
            } elseif ($db->num_rows($request) == 0) {
                $userQuery = $db->quote('m.id_member = {int:id_member_guest} AND ({raw:match_possible_guest_names})', array('id_member_guest' => 0, 'match_possible_guest_names' => 'm.poster_name LIKE ' . implode(' OR m.poster_name LIKE ', $realNameMatches)));
            } else {
                $memberlist = array();
                while ($row = $db->fetch_assoc($request)) {
                    $memberlist[] = $row['id_member'];
                }
                $userQuery = $db->quote('(m.id_member IN ({array_int:matched_members}) OR (m.id_member = {int:id_member_guest} AND ({raw:match_possible_guest_names})))', array('matched_members' => $memberlist, 'id_member_guest' => 0, 'match_possible_guest_names' => 'm.poster_name LIKE ' . implode(' OR m.poster_name LIKE ', $realNameMatches)));
            }
            $db->free_result($request);
        }
        // Ensure that boards are an array of integers (or nothing).
        if (!empty($search_params['brd']) && is_array($search_params['brd'])) {
            $query_boards = array_map('intval', $search_params['brd']);
        } elseif (!empty($_REQUEST['brd']) && is_array($_REQUEST['brd'])) {
            $query_boards = array_map('intval', $_REQUEST['brd']);
        } elseif (!empty($_REQUEST['brd'])) {
            $query_boards = array_map('intval', explode(',', $_REQUEST['brd']));
        } elseif (!empty($_REQUEST['sd_brd']) && is_array($_REQUEST['sd_brd'])) {
            $query_boards = array_map('intval', $_REQUEST['sd_brd']);
        } elseif (isset($_REQUEST['sd_brd']) && (int) $_REQUEST['sd_brd'] !== 0) {
            $query_boards = array((int) $_REQUEST['sd_brd']);
        } else {
            $query_boards = array();
        }
        // Special case for boards: searching just one topic?
        if (!empty($search_params['topic'])) {
            $request = $db->query('', '
				SELECT b.id_board
				FROM {db_prefix}topics AS t
					INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
				WHERE t.id_topic = {int:search_topic_id}
					AND {query_see_board}' . ($modSettings['postmod_active'] ? '
					AND t.approved = {int:is_approved_true}' : '') . '
				LIMIT 1', array('search_topic_id' => $search_params['topic'], 'is_approved_true' => 1));
            if ($db->num_rows($request) == 0) {
                fatal_lang_error('topic_gone', false);
            }
            $search_params['brd'] = array();
            list($search_params['brd'][0]) = $db->fetch_row($request);
            $db->free_result($request);
        } elseif ($user_info['is_admin'] && (!empty($search_params['advanced']) || !empty($query_boards))) {
            $search_params['brd'] = $query_boards;
        } else {
            require_once SUBSDIR . '/Boards.subs.php';
            $search_params['brd'] = array_keys(fetchBoardsInfo(array('boards' => $query_boards), array('include_recycle' => false, 'include_redirects' => false, 'wanna_see_board' => empty($search_params['advanced']))));
            // This error should pro'bly only happen for hackers.
            if (empty($search_params['brd'])) {
                $context['search_errors']['no_boards_selected'] = true;
            }
        }
        if (count($search_params['brd']) != 0) {
            foreach ($search_params['brd'] as $k => $v) {
                $search_params['brd'][$k] = (int) $v;
            }
            // If we've selected all boards, this parameter can be left empty.
            require_once SUBSDIR . '/Boards.subs.php';
            $num_boards = countBoards();
            if (count($search_params['brd']) == $num_boards) {
                $boardQuery = '';
            } elseif (count($search_params['brd']) == $num_boards - 1 && !empty($modSettings['recycle_board']) && !in_array($modSettings['recycle_board'], $search_params['brd'])) {
                $boardQuery = '!= ' . $modSettings['recycle_board'];
            } else {
                $boardQuery = 'IN (' . implode(', ', $search_params['brd']) . ')';
            }
        } else {
            $boardQuery = '';
        }
        $search_params['show_complete'] = !empty($search_params['show_complete']) || !empty($_REQUEST['show_complete']);
        $search_params['subject_only'] = !empty($search_params['subject_only']) || !empty($_REQUEST['subject_only']);
        $context['compact'] = !$search_params['show_complete'];
        // Get the sorting parameters right. Default to sort by relevance descending.
        $sort_columns = array('relevance', 'num_replies', 'id_msg');
        call_integration_hook('integrate_search_sort_columns', array(&$sort_columns));
        if (empty($search_params['sort']) && !empty($_REQUEST['sort'])) {
            list($search_params['sort'], $search_params['sort_dir']) = array_pad(explode('|', $_REQUEST['sort']), 2, '');
        }
        $search_params['sort'] = !empty($search_params['sort']) && in_array($search_params['sort'], $sort_columns) ? $search_params['sort'] : 'relevance';
        if (!empty($search_params['topic']) && $search_params['sort'] === 'num_replies') {
            $search_params['sort'] = 'id_msg';
        }
        // Sorting direction: descending unless stated otherwise.
        $search_params['sort_dir'] = !empty($search_params['sort_dir']) && $search_params['sort_dir'] == 'asc' ? 'asc' : 'desc';
        // Determine some values needed to calculate the relevance.
        $minMsg = (int) ((1 - $recentPercentage) * $modSettings['maxMsgID']);
        $recentMsg = $modSettings['maxMsgID'] - $minMsg;
        // *** Parse the search query
        call_integration_hook('integrate_search_params', array(&$search_params));
        // Unfortunately, searching for words like this is going to be slow, so we're blacklisting them.
        // @todo Setting to add more here?
        // @todo Maybe only blacklist if they are the only word, or "any" is used?
        $blacklisted_words = array('img', 'url', 'quote', 'www', 'http', 'the', 'is', 'it', 'are', 'if');
        call_integration_hook('integrate_search_blacklisted_words', array(&$blacklisted_words));
        // What are we searching for?
        if (empty($search_params['search'])) {
            if (isset($_GET['search'])) {
                $search_params['search'] = un_htmlspecialchars($_GET['search']);
            } elseif (isset($_POST['search'])) {
                $search_params['search'] = $_POST['search'];
            } else {
                $search_params['search'] = '';
            }
        }
        // Nothing??
        if (!isset($search_params['search']) || $search_params['search'] == '') {
            $context['search_errors']['invalid_search_string'] = true;
        } elseif (Util::strlen($search_params['search']) > $context['search_string_limit']) {
            $context['search_errors']['string_too_long'] = true;
        }
        // Change non-word characters into spaces.
        $stripped_query = preg_replace('~(?:[\\x0B\\0\\x{A0}\\t\\r\\s\\n(){}\\[\\]<>!@$%^*.,:+=`\\~\\?/\\\\]+|&(?:amp|lt|gt|quot);)+~u', ' ', $search_params['search']);
        // Make the query lower case. It's gonna be case insensitive anyway.
        $stripped_query = un_htmlspecialchars(Util::strtolower($stripped_query));
        // This (hidden) setting will do fulltext searching in the most basic way.
        if (!empty($modSettings['search_simple_fulltext'])) {
            $stripped_query = strtr($stripped_query, array('"' => ''));
        }
        $no_regexp = preg_match('~&#(?:\\d{1,7}|x[0-9a-fA-F]{1,6});~', $stripped_query) === 1;
        // Extract phrase parts first (e.g. some words "this is a phrase" some more words.)
        preg_match_all('/(?:^|\\s)([-]?)"([^"]+)"(?:$|\\s)/', $stripped_query, $matches, PREG_PATTERN_ORDER);
        $phraseArray = $matches[2];
        // Remove the phrase parts and extract the words.
        $wordArray = preg_replace('~(?:^|\\s)(?:[-]?)"(?:[^"]+)"(?:$|\\s)~u', ' ', $search_params['search']);
        $wordArray = explode(' ', Util::htmlspecialchars(un_htmlspecialchars($wordArray), ENT_QUOTES));
        // A minus sign in front of a word excludes the word.... so...
        $excludedWords = array();
        $excludedIndexWords = array();
        $excludedSubjectWords = array();
        $excludedPhrases = array();
        // .. first, we check for things like -"some words", but not "-some words".
        foreach ($matches[1] as $index => $word) {
            if ($word === '-') {
                if (($word = trim($phraseArray[$index], '-_\' ')) !== '' && !in_array($word, $blacklisted_words)) {
                    $excludedWords[] = $word;
                }
                unset($phraseArray[$index]);
            }
        }
        // Now we look for -test, etc.... normaller.
        foreach ($wordArray as $index => $word) {
            if (strpos(trim($word), '-') === 0) {
                if (($word = trim($word, '-_\' ')) !== '' && !in_array($word, $blacklisted_words)) {
                    $excludedWords[] = $word;
                }
                unset($wordArray[$index]);
            }
        }
        // The remaining words and phrases are all included.
        $searchArray = array_merge($phraseArray, $wordArray);
        // This is used to remember words that will be ignored (because too short usually)
        $context['search_ignored'] = array();
        // Trim everything and make sure there are no words that are the same.
        foreach ($searchArray as $index => $value) {
            // Skip anything practically empty.
            if (($searchArray[$index] = trim($value, '-_\' ')) === '') {
                unset($searchArray[$index]);
            } elseif (in_array($searchArray[$index], $blacklisted_words)) {
                $foundBlackListedWords = true;
                unset($searchArray[$index]);
            } elseif (Util::strlen($value) < 2) {
                $context['search_ignored'][] = $value;
                unset($searchArray[$index]);
            } else {
                $searchArray[$index] = $searchArray[$index];
            }
        }
        $searchArray = array_slice(array_unique($searchArray), 0, 10);
        // Create an array of replacements for highlighting.
        $context['mark'] = array();
        foreach ($searchArray as $word) {
            $context['mark'][$word] = '<strong class="highlight">' . $word . '</strong>';
        }
        // Initialize two arrays storing the words that have to be searched for.
        $orParts = array();
        $searchWords = array();
        // Make sure at least one word is being searched for.
        if (empty($searchArray)) {
            if (!empty($context['search_ignored'])) {
                $context['search_errors']['search_string_small_words'] = true;
            } else {
                $context['search_errors']['invalid_search_string' . (!empty($foundBlackListedWords) ? '_blacklist' : '')] = true;
            }
        } elseif (empty($search_params['searchtype'])) {
            $orParts[0] = $searchArray;
        } else {
            foreach ($searchArray as $index => $value) {
                $orParts[$index] = array($value);
            }
        }
        // Don't allow duplicate error messages if one string is too short.
        if (isset($context['search_errors']['search_string_small_words'], $context['search_errors']['invalid_search_string'])) {
            unset($context['search_errors']['invalid_search_string']);
        }
        // Make sure the excluded words are in all or-branches.
        foreach ($orParts as $orIndex => $andParts) {
            foreach ($excludedWords as $word) {
                $orParts[$orIndex][] = $word;
            }
        }
        // Determine the or-branches and the fulltext search words.
        foreach ($orParts as $orIndex => $andParts) {
            $searchWords[$orIndex] = array('indexed_words' => array(), 'words' => array(), 'subject_words' => array(), 'all_words' => array(), 'complex_words' => array());
            // Sort the indexed words (large words -> small words -> excluded words).
            if ($searchAPI->supportsMethod('searchSort')) {
                usort($orParts[$orIndex], 'searchSort');
            }
            foreach ($orParts[$orIndex] as $word) {
                $is_excluded = in_array($word, $excludedWords);
                $searchWords[$orIndex]['all_words'][] = $word;
                $subjectWords = text2words($word);
                if (!$is_excluded || count($subjectWords) === 1) {
                    $searchWords[$orIndex]['subject_words'] = array_merge($searchWords[$orIndex]['subject_words'], $subjectWords);
                    if ($is_excluded) {
                        $excludedSubjectWords = array_merge($excludedSubjectWords, $subjectWords);
                    }
                } else {
                    $excludedPhrases[] = $word;
                }
                // Have we got indexes to prepare?
                if ($searchAPI->supportsMethod('prepareIndexes')) {
                    $searchAPI->prepareIndexes($word, $searchWords[$orIndex], $excludedIndexWords, $is_excluded);
                }
            }
            // Search_force_index requires all AND parts to have at least one fulltext word.
            if (!empty($modSettings['search_force_index']) && empty($searchWords[$orIndex]['indexed_words'])) {
                $context['search_errors']['query_not_specific_enough'] = true;
                break;
            } elseif ($search_params['subject_only'] && empty($searchWords[$orIndex]['subject_words']) && empty($excludedSubjectWords)) {
                $context['search_errors']['query_not_specific_enough'] = true;
                break;
            } else {
                $searchWords[$orIndex]['indexed_words'] = array_slice($searchWords[$orIndex]['indexed_words'], 0, 7);
                $searchWords[$orIndex]['subject_words'] = array_slice($searchWords[$orIndex]['subject_words'], 0, 7);
                $searchWords[$orIndex]['words'] = array_slice($searchWords[$orIndex]['words'], 0, 4);
            }
        }
        // *** Spell checking?
        if (!empty($modSettings['enableSpellChecking']) && function_exists('pspell_new')) {
            $this->_load_suggestions($search_params, $searchArray);
        }
        // Let the user adjust the search query, should they wish?
        $context['search_params'] = $search_params;
        if (isset($context['search_params']['search'])) {
            $context['search_params']['search'] = Util::htmlspecialchars($context['search_params']['search']);
        }
        if (isset($context['search_params']['userspec'])) {
            $context['search_params']['userspec'] = Util::htmlspecialchars($context['search_params']['userspec']);
        }
        if (empty($context['search_params']['minage'])) {
            $context['search_params']['minage'] = 0;
        }
        if (empty($context['search_params']['maxage'])) {
            $context['search_params']['maxage'] = 9999;
        }
        $context['search_params'] = $this->_fill_default_search_params($context['search_params']);
        // Do we have captcha enabled?
        if ($user_info['is_guest'] && !empty($modSettings['search_enable_captcha']) && empty($_SESSION['ss_vv_passed']) && (empty($_SESSION['last_ss']) || $_SESSION['last_ss'] != $search_params['search'])) {
            // If we come from another search box tone down the error...
            if (!isset($_REQUEST['search_vv'])) {
                $context['search_errors']['need_verification_code'] = true;
            } else {
                require_once SUBSDIR . '/VerificationControls.class.php';
                $verificationOptions = array('id' => 'search');
                $context['require_verification'] = create_control_verification($verificationOptions, true);
                if (is_array($context['require_verification'])) {
                    foreach ($context['require_verification'] as $error) {
                        $context['search_errors'][$error] = true;
                    }
                } else {
                    $_SESSION['ss_vv_passed'] = true;
                }
            }
        }
        // *** Encode all search params
        // All search params have been checked, let's compile them to a single string... made less simple by PHP 4.3.9 and below.
        $temp_params = $search_params;
        if (isset($temp_params['brd'])) {
            $temp_params['brd'] = implode(',', $temp_params['brd']);
        }
        $context['params'] = array();
        foreach ($temp_params as $k => $v) {
            $context['params'][] = $k . '|\'|' . $v;
        }
        if (!empty($context['params'])) {
            // Due to old IE's 2083 character limit, we have to compress long search strings
            $params = @gzcompress(implode('|"|', $context['params']));
            // Gzcompress failed, use try non-gz
            if (empty($params)) {
                $params = implode('|"|', $context['params']);
            }
            // Base64 encode, then replace +/= with uri safe ones that can be reverted
            $context['params'] = str_replace(array('+', '/', '='), array('-', '_', '.'), base64_encode($params));
        }
        // ... and add the links to the link tree.
        $context['linktree'][] = array('url' => $scripturl . '?action=search;params=' . $context['params'], 'name' => $txt['search']);
        $context['linktree'][] = array('url' => $scripturl . '?action=search;sa=results;params=' . $context['params'], 'name' => $txt['search_results']);
        // Start guest off collapsed
        if ($context['user']['is_guest'] && !isset($context['minmax_preferences']['asearch'])) {
            $context['minmax_preferences']['asearch'] = 1;
        }
        // *** A last error check
        call_integration_hook('integrate_search_errors');
        // One or more search errors? Go back to the first search screen.
        if (!empty($context['search_errors'])) {
            $_REQUEST['params'] = $context['params'];
            return $this->action_search();
        }
        // Spam me not, Spam-a-lot?
        if (empty($_SESSION['last_ss']) || $_SESSION['last_ss'] != $search_params['search']) {
            spamProtection('search');
        }
        // Store the last search string to allow pages of results to be browsed.
        $_SESSION['last_ss'] = $search_params['search'];
        // *** Reserve an ID for caching the search results.
        $query_params = array_merge($search_params, array('min_msg_id' => isset($minMsgID) ? (int) $minMsgID : 0, 'max_msg_id' => isset($maxMsgID) ? (int) $maxMsgID : 0, 'memberlist' => !empty($memberlist) ? $memberlist : array()));
        // Can this search rely on the API given the parameters?
        if ($searchAPI->supportsMethod('searchQuery', $query_params)) {
            $participants = array();
            $searchArray = array();
            $num_results = $searchAPI->searchQuery($query_params, $searchWords, $excludedIndexWords, $participants, $searchArray);
        } else {
            $update_cache = empty($_SESSION['search_cache']) || $_SESSION['search_cache']['params'] != $context['params'];
            if ($update_cache) {
                // Increase the pointer...
                $modSettings['search_pointer'] = empty($modSettings['search_pointer']) ? 0 : (int) $modSettings['search_pointer'];
                // ...and store it right off.
                updateSettings(array('search_pointer' => $modSettings['search_pointer'] >= 255 ? 0 : $modSettings['search_pointer'] + 1));
                // As long as you don't change the parameters, the cache result is yours.
                $_SESSION['search_cache'] = array('id_search' => $modSettings['search_pointer'], 'num_results' => -1, 'params' => $context['params']);
                // Clear the previous cache of the final results cache.
                $db_search->search_query('delete_log_search_results', '
					DELETE FROM {db_prefix}log_search_results
					WHERE id_search = {int:search_id}', array('search_id' => $_SESSION['search_cache']['id_search']));
                if ($search_params['subject_only']) {
                    // We do this to try and avoid duplicate keys on databases not supporting INSERT IGNORE.
                    $inserts = array();
                    foreach ($searchWords as $orIndex => $words) {
                        $subject_query_params = array();
                        $subject_query = array('from' => '{db_prefix}topics AS t', 'inner_join' => array(), 'left_join' => array(), 'where' => array());
                        if ($modSettings['postmod_active']) {
                            $subject_query['where'][] = 't.approved = {int:is_approved}';
                        }
                        $numTables = 0;
                        $prev_join = 0;
                        $numSubjectResults = 0;
                        foreach ($words['subject_words'] as $subjectWord) {
                            $numTables++;
                            if (in_array($subjectWord, $excludedSubjectWords)) {
                                $subject_query['left_join'][] = '{db_prefix}log_search_subjects AS subj' . $numTables . ' ON (subj' . $numTables . '.word ' . (empty($modSettings['search_match_words']) ? 'LIKE {string:subject_words_' . $numTables . '_wild}' : '= {string:subject_words_' . $numTables . '}') . ' AND subj' . $numTables . '.id_topic = t.id_topic)';
                                $subject_query['where'][] = '(subj' . $numTables . '.word IS NULL)';
                            } else {
                                $subject_query['inner_join'][] = '{db_prefix}log_search_subjects AS subj' . $numTables . ' ON (subj' . $numTables . '.id_topic = ' . ($prev_join === 0 ? 't' : 'subj' . $prev_join) . '.id_topic)';
                                $subject_query['where'][] = 'subj' . $numTables . '.word ' . (empty($modSettings['search_match_words']) ? 'LIKE {string:subject_words_' . $numTables . '_wild}' : '= {string:subject_words_' . $numTables . '}');
                                $prev_join = $numTables;
                            }
                            $subject_query_params['subject_words_' . $numTables] = $subjectWord;
                            $subject_query_params['subject_words_' . $numTables . '_wild'] = '%' . $subjectWord . '%';
                        }
                        if (!empty($userQuery)) {
                            if ($subject_query['from'] != '{db_prefix}messages AS m') {
                                $subject_query['inner_join'][] = '{db_prefix}messages AS m ON (m.id_topic = t.id_topic)';
                            }
                            $subject_query['where'][] = $userQuery;
                        }
                        if (!empty($search_params['topic'])) {
                            $subject_query['where'][] = 't.id_topic = ' . $search_params['topic'];
                        }
                        if (!empty($minMsgID)) {
                            $subject_query['where'][] = 't.id_first_msg >= ' . $minMsgID;
                        }
                        if (!empty($maxMsgID)) {
                            $subject_query['where'][] = 't.id_last_msg <= ' . $maxMsgID;
                        }
                        if (!empty($boardQuery)) {
                            $subject_query['where'][] = 't.id_board ' . $boardQuery;
                        }
                        if (!empty($excludedPhrases)) {
                            if ($subject_query['from'] != '{db_prefix}messages AS m') {
                                $subject_query['inner_join'][] = '{db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)';
                            }
                            $count = 0;
                            foreach ($excludedPhrases as $phrase) {
                                $subject_query['where'][] = 'm.subject NOT ' . (empty($modSettings['search_match_words']) || $no_regexp ? ' LIKE ' : ' RLIKE ') . '{string:excluded_phrases_' . $count . '}';
                                $subject_query_params['excluded_phrases_' . $count++] = empty($modSettings['search_match_words']) || $no_regexp ? '%' . strtr($phrase, array('_' => '\\_', '%' => '\\%')) . '%' : '[[:<:]]' . addcslashes(preg_replace(array('/([\\[\\]$.+*?|{}()])/'), array('[$1]'), $phrase), '\\\'') . '[[:>:]]';
                            }
                        }
                        call_integration_hook('integrate_subject_only_search_query', array(&$subject_query, &$subject_query_params));
                        // Build the search relevance query
                        $relevance = '1000 * (';
                        foreach ($this->_weight_factors as $type => $value) {
                            if (isset($value['results'])) {
                                $relevance .= $this->_weight[$type];
                                if (!empty($value['results'])) {
                                    $relevance .= ' * ' . $value['results'];
                                }
                                $relevance .= ' + ';
                            }
                        }
                        $relevance = substr($relevance, 0, -3) . ') / ' . $this->_weight_total . ' AS relevance';
                        $ignoreRequest = $db_search->search_query('insert_log_search_results_subject', ($db->support_ignore() ? '
							INSERT IGNORE INTO {db_prefix}log_search_results
								(id_search, id_topic, relevance, id_msg, num_matches)' : '') . '
							SELECT
								{int:id_search},
								t.id_topic,
								' . $relevance . ',
								' . (empty($userQuery) ? 't.id_first_msg' : 'm.id_msg') . ',
								1
							FROM ' . $subject_query['from'] . (empty($subject_query['inner_join']) ? '' : '
								INNER JOIN ' . implode('
								INNER JOIN ', $subject_query['inner_join'])) . (empty($subject_query['left_join']) ? '' : '
								LEFT JOIN ' . implode('
								LEFT JOIN ', $subject_query['left_join'])) . '
							WHERE ' . implode('
								AND ', $subject_query['where']) . (empty($modSettings['search_max_results']) ? '' : '
							LIMIT ' . ($modSettings['search_max_results'] - $numSubjectResults)), array_merge($subject_query_params, array('id_search' => $_SESSION['search_cache']['id_search'], 'min_msg' => $minMsg, 'recent_message' => $recentMsg, 'huge_topic_posts' => $humungousTopicPosts, 'is_approved' => 1)));
                        // If the database doesn't support IGNORE to make this fast we need to do some tracking.
                        if (!$db->support_ignore()) {
                            while ($row = $db->fetch_row($ignoreRequest)) {
                                // No duplicates!
                                if (isset($inserts[$row[1]])) {
                                    continue;
                                }
                                foreach ($row as $key => $value) {
                                    $inserts[$row[1]][] = (int) $row[$key];
                                }
                            }
                            $db->free_result($ignoreRequest);
                            $numSubjectResults = count($inserts);
                        } else {
                            $numSubjectResults += $db->affected_rows();
                        }
                        if (!empty($modSettings['search_max_results']) && $numSubjectResults >= $modSettings['search_max_results']) {
                            break;
                        }
                    }
                    // If there's data to be inserted for non-IGNORE databases do it here!
                    if (!empty($inserts)) {
                        $db->insert('', '{db_prefix}log_search_results', array('id_search' => 'int', 'id_topic' => 'int', 'relevance' => 'int', 'id_msg' => 'int', 'num_matches' => 'int'), $inserts, array('id_search', 'id_topic'));
                    }
                    $_SESSION['search_cache']['num_results'] = $numSubjectResults;
                } else {
                    $main_query = array('select' => array('id_search' => $_SESSION['search_cache']['id_search'], 'relevance' => '0'), 'weights' => array(), 'from' => '{db_prefix}topics AS t', 'inner_join' => array('{db_prefix}messages AS m ON (m.id_topic = t.id_topic)'), 'left_join' => array(), 'where' => array(), 'group_by' => array(), 'parameters' => array('min_msg' => $minMsg, 'recent_message' => $recentMsg, 'huge_topic_posts' => $humungousTopicPosts, 'is_approved' => 1));
                    if (empty($search_params['topic']) && empty($search_params['show_complete'])) {
                        $main_query['select']['id_topic'] = 't.id_topic';
                        $main_query['select']['id_msg'] = 'MAX(m.id_msg) AS id_msg';
                        $main_query['select']['num_matches'] = 'COUNT(*) AS num_matches';
                        $main_query['weights'] = $this->_weight_factors;
                        $main_query['group_by'][] = 't.id_topic';
                    } else {
                        // This is outrageous!
                        $main_query['select']['id_topic'] = 'm.id_msg AS id_topic';
                        $main_query['select']['id_msg'] = 'm.id_msg';
                        $main_query['select']['num_matches'] = '1 AS num_matches';
                        $main_query['weights'] = array('age' => array('search' => '((m.id_msg - t.id_first_msg) / CASE WHEN t.id_last_msg = t.id_first_msg THEN 1 ELSE t.id_last_msg - t.id_first_msg END)'), 'first_message' => array('search' => 'CASE WHEN m.id_msg = t.id_first_msg THEN 1 ELSE 0 END'));
                        if (!empty($search_params['topic'])) {
                            $main_query['where'][] = 't.id_topic = {int:topic}';
                            $main_query['parameters']['topic'] = $search_params['topic'];
                        }
                        if (!empty($search_params['show_complete'])) {
                            $main_query['group_by'][] = 'm.id_msg, t.id_first_msg, t.id_last_msg';
                        }
                    }
                    // *** Get the subject results.
                    $numSubjectResults = 0;
                    if (empty($search_params['topic'])) {
                        $inserts = array();
                        // Create a temporary table to store some preliminary results in.
                        $db_search->search_query('drop_tmp_log_search_topics', '
							DROP TABLE IF EXISTS {db_prefix}tmp_log_search_topics', array('db_error_skip' => true));
                        $createTemporary = $db_search->search_query('create_tmp_log_search_topics', '
							CREATE TEMPORARY TABLE {db_prefix}tmp_log_search_topics (
								id_topic mediumint(8) unsigned NOT NULL default {string:string_zero},
								PRIMARY KEY (id_topic)
							) ENGINE=MEMORY', array('string_zero' => '0', 'db_error_skip' => true)) !== false;
                        // Clean up some previous cache.
                        if (!$createTemporary) {
                            $db_search->search_query('delete_log_search_topics', '
								DELETE FROM {db_prefix}log_search_topics
								WHERE id_search = {int:search_id}', array('search_id' => $_SESSION['search_cache']['id_search']));
                        }
                        foreach ($searchWords as $orIndex => $words) {
                            $subject_query = array('from' => '{db_prefix}topics AS t', 'inner_join' => array(), 'left_join' => array(), 'where' => array(), 'params' => array());
                            $numTables = 0;
                            $prev_join = 0;
                            $count = 0;
                            $excluded = false;
                            foreach ($words['subject_words'] as $subjectWord) {
                                $numTables++;
                                if (in_array($subjectWord, $excludedSubjectWords)) {
                                    if ($subject_query['from'] != '{db_prefix}messages AS m' && !$excluded) {
                                        $subject_query['inner_join'][] = '{db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)';
                                        $excluded = true;
                                    }
                                    $subject_query['left_join'][] = '{db_prefix}log_search_subjects AS subj' . $numTables . ' ON (subj' . $numTables . '.word ' . (empty($modSettings['search_match_words']) ? 'LIKE {string:subject_not_' . $count . '}' : '= {string:subject_not_' . $count . '}') . ' AND subj' . $numTables . '.id_topic = t.id_topic)';
                                    $subject_query['params']['subject_not_' . $count] = empty($modSettings['search_match_words']) ? '%' . $subjectWord . '%' : $subjectWord;
                                    $subject_query['where'][] = '(subj' . $numTables . '.word IS NULL)';
                                    $subject_query['where'][] = 'm.body NOT ' . (empty($modSettings['search_match_words']) || $no_regexp ? ' LIKE ' : ' RLIKE ') . '{string:body_not_' . $count . '}';
                                    $subject_query['params']['body_not_' . $count++] = empty($modSettings['search_match_words']) || $no_regexp ? '%' . strtr($subjectWord, array('_' => '\\_', '%' => '\\%')) . '%' : '[[:<:]]' . addcslashes(preg_replace(array('/([\\[\\]$.+*?|{}()])/'), array('[$1]'), $subjectWord), '\\\'') . '[[:>:]]';
                                } else {
                                    $subject_query['inner_join'][] = '{db_prefix}log_search_subjects AS subj' . $numTables . ' ON (subj' . $numTables . '.id_topic = ' . ($prev_join === 0 ? 't' : 'subj' . $prev_join) . '.id_topic)';
                                    $subject_query['where'][] = 'subj' . $numTables . '.word LIKE {string:subject_like_' . $count . '}';
                                    $subject_query['params']['subject_like_' . $count++] = empty($modSettings['search_match_words']) ? '%' . $subjectWord . '%' : $subjectWord;
                                    $prev_join = $numTables;
                                }
                            }
                            if (!empty($userQuery)) {
                                if ($subject_query['from'] != '{db_prefix}messages AS m') {
                                    $subject_query['inner_join'][] = '{db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)';
                                }
                                $subject_query['where'][] = '{raw:user_query}';
                                $subject_query['params']['user_query'] = $userQuery;
                            }
                            if (!empty($search_params['topic'])) {
                                $subject_query['where'][] = 't.id_topic = {int:topic}';
                                $subject_query['params']['topic'] = $search_params['topic'];
                            }
                            if (!empty($minMsgID)) {
                                $subject_query['where'][] = 't.id_first_msg >= {int:min_msg_id}';
                                $subject_query['params']['min_msg_id'] = $minMsgID;
                            }
                            if (!empty($maxMsgID)) {
                                $subject_query['where'][] = 't.id_last_msg <= {int:max_msg_id}';
                                $subject_query['params']['max_msg_id'] = $maxMsgID;
                            }
                            if (!empty($boardQuery)) {
                                $subject_query['where'][] = 't.id_board {raw:board_query}';
                                $subject_query['params']['board_query'] = $boardQuery;
                            }
                            if (!empty($excludedPhrases)) {
                                if ($subject_query['from'] != '{db_prefix}messages AS m') {
                                    $subject_query['inner_join'][] = '{db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)';
                                }
                                $count = 0;
                                foreach ($excludedPhrases as $phrase) {
                                    $subject_query['where'][] = 'm.subject NOT ' . (empty($modSettings['search_match_words']) || $no_regexp ? ' LIKE ' : ' RLIKE ') . '{string:exclude_phrase_' . $count . '}';
                                    $subject_query['where'][] = 'm.body NOT ' . (empty($modSettings['search_match_words']) || $no_regexp ? ' LIKE ' : ' RLIKE ') . '{string:exclude_phrase_' . $count . '}';
                                    $subject_query['params']['exclude_phrase_' . $count++] = empty($modSettings['search_match_words']) || $no_regexp ? '%' . strtr($phrase, array('_' => '\\_', '%' => '\\%')) . '%' : '[[:<:]]' . addcslashes(preg_replace(array('/([\\[\\]$.+*?|{}()])/'), array('[$1]'), $phrase), '\\\'') . '[[:>:]]';
                                }
                            }
                            call_integration_hook('integrate_subject_search_query', array(&$subject_query));
                            // Nothing to search for?
                            if (empty($subject_query['where'])) {
                                continue;
                            }
                            $ignoreRequest = $db_search->search_query('insert_log_search_topics', ($db->support_ignore() ? '
								INSERT IGNORE INTO {db_prefix}' . ($createTemporary ? 'tmp_' : '') . 'log_search_topics
									(' . ($createTemporary ? '' : 'id_search, ') . 'id_topic)' : '') . '
								SELECT ' . ($createTemporary ? '' : $_SESSION['search_cache']['id_search'] . ', ') . 't.id_topic
								FROM ' . $subject_query['from'] . (empty($subject_query['inner_join']) ? '' : '
									INNER JOIN ' . implode('
									INNER JOIN ', $subject_query['inner_join'])) . (empty($subject_query['left_join']) ? '' : '
									LEFT JOIN ' . implode('
									LEFT JOIN ', $subject_query['left_join'])) . '
								WHERE ' . implode('
									AND ', $subject_query['where']) . (empty($modSettings['search_max_results']) ? '' : '
								LIMIT ' . ($modSettings['search_max_results'] - $numSubjectResults)), $subject_query['params']);
                            // Don't do INSERT IGNORE? Manually fix this up!
                            if (!$db->support_ignore()) {
                                while ($row = $db->fetch_row($ignoreRequest)) {
                                    $ind = $createTemporary ? 0 : 1;
                                    // No duplicates!
                                    if (isset($inserts[$row[$ind]])) {
                                        continue;
                                    }
                                    $inserts[$row[$ind]] = $row;
                                }
                                $db->free_result($ignoreRequest);
                                $numSubjectResults = count($inserts);
                            } else {
                                $numSubjectResults += $db->affected_rows();
                            }
                            if (!empty($modSettings['search_max_results']) && $numSubjectResults >= $modSettings['search_max_results']) {
                                break;
                            }
                        }
                        // Got some non-MySQL data to plonk in?
                        if (!empty($inserts)) {
                            $db->insert('', '{db_prefix}' . ($createTemporary ? 'tmp_' : '') . 'log_search_topics', $createTemporary ? array('id_topic' => 'int') : array('id_search' => 'int', 'id_topic' => 'int'), $inserts, $createTemporary ? array('id_topic') : array('id_search', 'id_topic'));
                        }
                        if ($numSubjectResults !== 0) {
                            $main_query['weights']['subject']['search'] = 'CASE WHEN MAX(lst.id_topic) IS NULL THEN 0 ELSE 1 END';
                            $main_query['left_join'][] = '{db_prefix}' . ($createTemporary ? 'tmp_' : '') . 'log_search_topics AS lst ON (' . ($createTemporary ? '' : 'lst.id_search = {int:id_search} AND ') . 'lst.id_topic = t.id_topic)';
                            if (!$createTemporary) {
                                $main_query['parameters']['id_search'] = $_SESSION['search_cache']['id_search'];
                            }
                        }
                    }
                    $indexedResults = 0;
                    // We building an index?
                    if ($searchAPI->supportsMethod('indexedWordQuery', $query_params)) {
                        $inserts = array();
                        $db_search->search_query('drop_tmp_log_search_messages', '
							DROP TABLE IF EXISTS {db_prefix}tmp_log_search_messages', array('db_error_skip' => true));
                        $createTemporary = $db_search->search_query('create_tmp_log_search_messages', '
							CREATE TEMPORARY TABLE {db_prefix}tmp_log_search_messages (
								id_msg int(10) unsigned NOT NULL default {string:string_zero},
								PRIMARY KEY (id_msg)
							) ENGINE=MEMORY', array('string_zero' => '0', 'db_error_skip' => true)) !== false;
                        // Clear, all clear!
                        if (!$createTemporary) {
                            $db_search->search_query('delete_log_search_messages', '
								DELETE FROM {db_prefix}log_search_messages
								WHERE id_search = {int:id_search}', array('id_search' => $_SESSION['search_cache']['id_search']));
                        }
                        foreach ($searchWords as $orIndex => $words) {
                            // Search for this word, assuming we have some words!
                            if (!empty($words['indexed_words'])) {
                                // Variables required for the search.
                                $search_data = array('insert_into' => ($createTemporary ? 'tmp_' : '') . 'log_search_messages', 'no_regexp' => $no_regexp, 'max_results' => $maxMessageResults, 'indexed_results' => $indexedResults, 'params' => array('id_search' => !$createTemporary ? $_SESSION['search_cache']['id_search'] : 0, 'excluded_words' => $excludedWords, 'user_query' => !empty($userQuery) ? $userQuery : '', 'board_query' => !empty($boardQuery) ? $boardQuery : '', 'topic' => !empty($search_params['topic']) ? $search_params['topic'] : 0, 'min_msg_id' => !empty($minMsgID) ? $minMsgID : 0, 'max_msg_id' => !empty($maxMsgID) ? $maxMsgID : 0, 'excluded_phrases' => !empty($excludedPhrases) ? $excludedPhrases : array(), 'excluded_index_words' => !empty($excludedIndexWords) ? $excludedIndexWords : array(), 'excluded_subject_words' => !empty($excludedSubjectWords) ? $excludedSubjectWords : array()));
                                $ignoreRequest = $searchAPI->indexedWordQuery($words, $search_data);
                                if (!$db->support_ignore()) {
                                    while ($row = $db->fetch_row($ignoreRequest)) {
                                        // No duplicates!
                                        if (isset($inserts[$row[0]])) {
                                            continue;
                                        }
                                        $inserts[$row[0]] = $row;
                                    }
                                    $db->free_result($ignoreRequest);
                                    $indexedResults = count($inserts);
                                } else {
                                    $indexedResults += $db->affected_rows();
                                }
                                if (!empty($maxMessageResults) && $indexedResults >= $maxMessageResults) {
                                    break;
                                }
                            }
                        }
                        // More non-MySQL stuff needed?
                        if (!empty($inserts)) {
                            $db->insert('', '{db_prefix}' . ($createTemporary ? 'tmp_' : '') . 'log_search_messages', $createTemporary ? array('id_msg' => 'int') : array('id_msg' => 'int', 'id_search' => 'int'), $inserts, $createTemporary ? array('id_msg') : array('id_msg', 'id_search'));
                        }
                        if (empty($indexedResults) && empty($numSubjectResults) && !empty($modSettings['search_force_index'])) {
                            $context['search_errors']['query_not_specific_enough'] = true;
                            $_REQUEST['params'] = $context['params'];
                            return $this->action_search();
                        } elseif (!empty($indexedResults)) {
                            $main_query['inner_join'][] = '{db_prefix}' . ($createTemporary ? 'tmp_' : '') . 'log_search_messages AS lsm ON (lsm.id_msg = m.id_msg)';
                            if (!$createTemporary) {
                                $main_query['where'][] = 'lsm.id_search = {int:id_search}';
                                $main_query['parameters']['id_search'] = $_SESSION['search_cache']['id_search'];
                            }
                        }
                    } else {
                        $orWhere = array();
                        $count = 0;
                        foreach ($searchWords as $orIndex => $words) {
                            $where = array();
                            foreach ($words['all_words'] as $regularWord) {
                                $where[] = 'm.body' . (in_array($regularWord, $excludedWords) ? ' NOT' : '') . (empty($modSettings['search_match_words']) || $no_regexp ? ' LIKE ' : ' RLIKE ') . '{string:all_word_body_' . $count . '}';
                                if (in_array($regularWord, $excludedWords)) {
                                    $where[] = 'm.subject NOT' . (empty($modSettings['search_match_words']) || $no_regexp ? ' LIKE ' : ' RLIKE ') . '{string:all_word_body_' . $count . '}';
                                }
                                $main_query['parameters']['all_word_body_' . $count++] = empty($modSettings['search_match_words']) || $no_regexp ? '%' . strtr($regularWord, array('_' => '\\_', '%' => '\\%')) . '%' : '[[:<:]]' . addcslashes(preg_replace(array('/([\\[\\]$.+*?|{}()])/'), array('[$1]'), $regularWord), '\\\'') . '[[:>:]]';
                            }
                            if (!empty($where)) {
                                $orWhere[] = count($where) > 1 ? '(' . implode(' AND ', $where) . ')' : $where[0];
                            }
                        }
                        if (!empty($orWhere)) {
                            $main_query['where'][] = count($orWhere) > 1 ? '(' . implode(' OR ', $orWhere) . ')' : $orWhere[0];
                        }
                        if (!empty($userQuery)) {
                            $main_query['where'][] = '{raw:user_query}';
                            $main_query['parameters']['user_query'] = $userQuery;
                        }
                        if (!empty($search_params['topic'])) {
                            $main_query['where'][] = 'm.id_topic = {int:topic}';
                            $main_query['parameters']['topic'] = $search_params['topic'];
                        }
                        if (!empty($minMsgID)) {
                            $main_query['where'][] = 'm.id_msg >= {int:min_msg_id}';
                            $main_query['parameters']['min_msg_id'] = $minMsgID;
                        }
                        if (!empty($maxMsgID)) {
                            $main_query['where'][] = 'm.id_msg <= {int:max_msg_id}';
                            $main_query['parameters']['max_msg_id'] = $maxMsgID;
                        }
                        if (!empty($boardQuery)) {
                            $main_query['where'][] = 'm.id_board {raw:board_query}';
                            $main_query['parameters']['board_query'] = $boardQuery;
                        }
                    }
                    call_integration_hook('integrate_main_search_query', array(&$main_query));
                    // Did we either get some indexed results, or otherwise did not do an indexed query?
                    if (!empty($indexedResults) || !$searchAPI->supportsMethod('indexedWordQuery', $query_params)) {
                        $relevance = '1000 * (';
                        $new_weight_total = 0;
                        foreach ($main_query['weights'] as $type => $value) {
                            $relevance .= $this->_weight[$type];
                            if (!empty($value['search'])) {
                                $relevance .= ' * ' . $value['search'];
                            }
                            $relevance .= ' + ';
                            $new_weight_total += $this->_weight[$type];
                        }
                        $main_query['select']['relevance'] = substr($relevance, 0, -3) . ') / ' . $new_weight_total . ' AS relevance';
                        $ignoreRequest = $db_search->search_query('insert_log_search_results_no_index', ($db->support_ignore() ? '
							INSERT IGNORE INTO ' . '{db_prefix}log_search_results
								(' . implode(', ', array_keys($main_query['select'])) . ')' : '') . '
							SELECT
								' . implode(',
								', $main_query['select']) . '
							FROM ' . $main_query['from'] . (empty($main_query['inner_join']) ? '' : '
								INNER JOIN ' . implode('
								INNER JOIN ', $main_query['inner_join'])) . (empty($main_query['left_join']) ? '' : '
								LEFT JOIN ' . implode('
								LEFT JOIN ', $main_query['left_join'])) . (!empty($main_query['where']) ? '
							WHERE ' : '') . implode('
								AND ', $main_query['where']) . (empty($main_query['group_by']) ? '' : '
							GROUP BY ' . implode(', ', $main_query['group_by'])) . (empty($modSettings['search_max_results']) ? '' : '
							LIMIT ' . $modSettings['search_max_results']), $main_query['parameters']);
                        // We love to handle non-good databases that don't support our ignore!
                        if (!$db->support_ignore()) {
                            $inserts = array();
                            while ($row = $db->fetch_row($ignoreRequest)) {
                                // No duplicates!
                                if (isset($inserts[$row[2]])) {
                                    continue;
                                }
                                foreach ($row as $key => $value) {
                                    $inserts[$row[2]][] = (int) $row[$key];
                                }
                            }
                            $db->free_result($ignoreRequest);
                            // Now put them in!
                            if (!empty($inserts)) {
                                $query_columns = array();
                                foreach ($main_query['select'] as $k => $v) {
                                    $query_columns[$k] = 'int';
                                }
                                $db->insert('', '{db_prefix}log_search_results', $query_columns, $inserts, array('id_search', 'id_topic'));
                            }
                            $_SESSION['search_cache']['num_results'] += count($inserts);
                        } else {
                            $_SESSION['search_cache']['num_results'] = $db->affected_rows();
                        }
                    }
                    // Insert subject-only matches.
                    if ($_SESSION['search_cache']['num_results'] < $modSettings['search_max_results'] && $numSubjectResults !== 0) {
                        $relevance = '1000 * (';
                        foreach ($this->_weight_factors as $type => $value) {
                            if (isset($value['results'])) {
                                $relevance .= $this->_weight[$type];
                                if (!empty($value['results'])) {
                                    $relevance .= ' * ' . $value['results'];
                                }
                                $relevance .= ' + ';
                            }
                        }
                        $relevance = substr($relevance, 0, -3) . ') / ' . $this->_weight_total . ' AS relevance';
                        $usedIDs = array_flip(empty($inserts) ? array() : array_keys($inserts));
                        $ignoreRequest = $db_search->search_query('insert_log_search_results_sub_only', ($db->support_ignore() ? '
							INSERT IGNORE INTO {db_prefix}log_search_results
								(id_search, id_topic, relevance, id_msg, num_matches)' : '') . '
							SELECT
								{int:id_search},
								t.id_topic,
								' . $relevance . ',
								t.id_first_msg,
								1
							FROM {db_prefix}topics AS t
								INNER JOIN {db_prefix}' . ($createTemporary ? 'tmp_' : '') . 'log_search_topics AS lst ON (lst.id_topic = t.id_topic)' . ($createTemporary ? '' : ' WHERE lst.id_search = {int:id_search}') . (empty($modSettings['search_max_results']) ? '' : '
							LIMIT ' . ($modSettings['search_max_results'] - $_SESSION['search_cache']['num_results'])), array('id_search' => $_SESSION['search_cache']['id_search'], 'min_msg' => $minMsg, 'recent_message' => $recentMsg, 'huge_topic_posts' => $humungousTopicPosts));
                        // Once again need to do the inserts if the database don't support ignore!
                        if (!$db->support_ignore()) {
                            $inserts = array();
                            while ($row = $db->fetch_row($ignoreRequest)) {
                                // No duplicates!
                                if (isset($usedIDs[$row[1]])) {
                                    continue;
                                }
                                $usedIDs[$row[1]] = true;
                                $inserts[] = $row;
                            }
                            $db->free_result($ignoreRequest);
                            // Now put them in!
                            if (!empty($inserts)) {
                                $db->insert('', '{db_prefix}log_search_results', array('id_search' => 'int', 'id_topic' => 'int', 'relevance' => 'float', 'id_msg' => 'int', 'num_matches' => 'int'), $inserts, array('id_search', 'id_topic'));
                            }
                            $_SESSION['search_cache']['num_results'] += count($inserts);
                        } else {
                            $_SESSION['search_cache']['num_results'] += $db->affected_rows();
                        }
                    } elseif ($_SESSION['search_cache']['num_results'] == -1) {
                        $_SESSION['search_cache']['num_results'] = 0;
                    }
                }
            }
            // *** Retrieve the results to be shown on the page
            $participants = array();
            $request = $db_search->search_query('', '
				SELECT ' . (empty($search_params['topic']) ? 'lsr.id_topic' : $search_params['topic'] . ' AS id_topic') . ', lsr.id_msg, lsr.relevance, lsr.num_matches
				FROM {db_prefix}log_search_results AS lsr' . ($search_params['sort'] == 'num_replies' ? '
					INNER JOIN {db_prefix}topics AS t ON (t.id_topic = lsr.id_topic)' : '') . '
				WHERE lsr.id_search = {int:id_search}
				ORDER BY ' . $search_params['sort'] . ' ' . $search_params['sort_dir'] . '
				LIMIT ' . (int) $_REQUEST['start'] . ', ' . $modSettings['search_results_per_page'], array('id_search' => $_SESSION['search_cache']['id_search']));
            while ($row = $db->fetch_assoc($request)) {
                $context['topics'][$row['id_msg']] = array('relevance' => round($row['relevance'] / 10, 1) . '%', 'num_matches' => $row['num_matches'], 'matches' => array());
                // By default they didn't participate in the topic!
                $participants[$row['id_topic']] = false;
            }
            $db->free_result($request);
            $num_results = $_SESSION['search_cache']['num_results'];
        }
        if (!empty($context['topics'])) {
            // Create an array for the permissions.
            $boards_can = boardsAllowedTo(array('post_reply_own', 'post_reply_any', 'mark_any_notify'), true, false);
            // How's about some quick moderation?
            if (!empty($options['display_quick_mod'])) {
                $boards_can = array_merge($boards_can, boardsAllowedTo(array('lock_any', 'lock_own', 'make_sticky', 'move_any', 'move_own', 'remove_any', 'remove_own', 'merge_any'), true, false));
                $context['can_lock'] = in_array(0, $boards_can['lock_any']);
                $context['can_sticky'] = in_array(0, $boards_can['make_sticky']) && !empty($modSettings['enableStickyTopics']);
                $context['can_move'] = in_array(0, $boards_can['move_any']);
                $context['can_remove'] = in_array(0, $boards_can['remove_any']);
                $context['can_merge'] = in_array(0, $boards_can['merge_any']);
            }
            // What messages are we using?
            $msg_list = array_keys($context['topics']);
            // Load the posters...
            $request = $db->query('', '
				SELECT id_member
				FROM {db_prefix}messages
				WHERE id_member != {int:no_member}
					AND id_msg IN ({array_int:message_list})
				LIMIT ' . count($context['topics']), array('message_list' => $msg_list, 'no_member' => 0));
            $posters = array();
            while ($row = $db->fetch_assoc($request)) {
                $posters[] = $row['id_member'];
            }
            $db->free_result($request);
            call_integration_hook('integrate_search_message_list', array(&$msg_list, &$posters));
            if (!empty($posters)) {
                loadMemberData(array_unique($posters));
            }
            // Get the messages out for the callback - select enough that it can be made to look just like Display.
            $messages_request = $db->query('', '
				SELECT
					m.id_msg, m.subject, m.poster_name, m.poster_email, m.poster_time, m.id_member,
					m.icon, m.poster_ip, m.body, m.smileys_enabled, m.modified_time, m.modified_name,
					first_m.id_msg AS first_msg, first_m.subject AS first_subject, first_m.icon AS first_icon, first_m.poster_time AS first_poster_time,
					first_mem.id_member AS first_member_id, IFNULL(first_mem.real_name, first_m.poster_name) AS first_member_name,
					last_m.id_msg AS last_msg, last_m.poster_time AS last_poster_time, last_mem.id_member AS last_member_id,
					IFNULL(last_mem.real_name, last_m.poster_name) AS last_member_name, last_m.icon AS last_icon, last_m.subject AS last_subject,
					t.id_topic, t.is_sticky, t.locked, t.id_poll, t.num_replies, t.num_views, t.num_likes,
					b.id_board, b.name AS board_name, c.id_cat, c.name AS cat_name
				FROM {db_prefix}messages AS m
					INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
					INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
					INNER JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)
					INNER JOIN {db_prefix}messages AS first_m ON (first_m.id_msg = t.id_first_msg)
					INNER JOIN {db_prefix}messages AS last_m ON (last_m.id_msg = t.id_last_msg)
					LEFT JOIN {db_prefix}members AS first_mem ON (first_mem.id_member = first_m.id_member)
					LEFT JOIN {db_prefix}members AS last_mem ON (last_mem.id_member = first_m.id_member)
				WHERE m.id_msg IN ({array_int:message_list})' . ($modSettings['postmod_active'] ? '
					AND m.approved = {int:is_approved}' : '') . '
				ORDER BY FIND_IN_SET(m.id_msg, {string:message_list_in_set})
				LIMIT {int:limit}', array('message_list' => $msg_list, 'is_approved' => 1, 'message_list_in_set' => implode(',', $msg_list), 'limit' => count($context['topics'])));
            // If there are no results that means the things in the cache got deleted, so pretend we have no topics anymore.
            if ($db->num_rows($messages_request) == 0) {
                $context['topics'] = array();
            }
            // If we want to know who participated in what then load this now.
            if (!empty($modSettings['enableParticipation']) && !$user_info['is_guest']) {
                require_once SUBSDIR . '/MessageIndex.subs.php';
                $topics_participated_in = topicsParticipation($user_info['id'], array_keys($participants));
                foreach ($topics_participated_in as $topic) {
                    $participants[$topic['id_topic']] = true;
                }
            }
        }
        // Now that we know how many results to expect we can start calculating the page numbers.
        $context['page_index'] = constructPageIndex($scripturl . '?action=search;sa=results;params=' . $context['params'], $_REQUEST['start'], $num_results, $modSettings['search_results_per_page'], false);
        // Consider the search complete!
        if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2) {
            cache_put_data('search_start:' . ($user_info['is_guest'] ? $user_info['ip'] : $user_info['id']), null, 90);
        }
        $context['key_words'] =& $searchArray;
        // Setup the default topic icons... for checking they exist and the like!
        require_once SUBSDIR . '/MessageIndex.subs.php';
        $context['icon_sources'] = MessageTopicIcons();
        $context['sub_template'] = 'results';
        $context['page_title'] = $txt['search_results'];
        $context['get_topics'] = array($this, 'prepareSearchContext_callback');
        $context['jump_to'] = array('label' => addslashes(un_htmlspecialchars($txt['jump_to'])), 'board_name' => addslashes(un_htmlspecialchars($txt['select_destination'])));
    }
示例#3
0
    /**
     * Find unread topics and replies.
     * Accessed by action=unread and action=unreadreplies
     */
    public function action_unread()
    {
        global $board, $txt, $scripturl;
        global $user_info, $context, $settings, $modSettings, $options;
        $db = database();
        // Guests can't have unread things, we don't know anything about them.
        is_not_guest();
        // Prefetching + lots of MySQL work = bad mojo.
        if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch') {
            @ob_end_clean();
            header('HTTP/1.1 403 Forbidden');
            die;
        }
        // We need... we need... I know!
        require_once SUBSDIR . '/Recent.subs.php';
        require_once SUBSDIR . '/Boards.subs.php';
        $context['showCheckboxes'] = !empty($options['display_quick_mod']) && $options['display_quick_mod'] == 1 && $settings['show_mark_read'];
        $context['showing_all_topics'] = isset($_GET['all']);
        $context['start'] = (int) $_REQUEST['start'];
        $context['topics_per_page'] = empty($modSettings['disableCustomPerPage']) && !empty($options['topics_per_page']) ? $options['topics_per_page'] : $modSettings['defaultMaxTopics'];
        if ($_REQUEST['action'] == 'unread') {
            $context['page_title'] = $context['showing_all_topics'] ? $txt['unread_topics_all'] : $txt['unread_topics_visit'];
        } else {
            $context['page_title'] = $txt['unread_replies'];
        }
        if ($context['showing_all_topics'] && !empty($modSettings['loadavg_allunread']) && $modSettings['current_load'] >= $modSettings['loadavg_allunread']) {
            fatal_lang_error('loadavg_allunread_disabled', false);
        } elseif ($_REQUEST['action'] != 'unread' && !empty($modSettings['loadavg_unreadreplies']) && $modSettings['current_load'] >= $modSettings['loadavg_unreadreplies']) {
            fatal_lang_error('loadavg_unreadreplies_disabled', false);
        } elseif (!$context['showing_all_topics'] && $_REQUEST['action'] == 'unread' && !empty($modSettings['loadavg_unread']) && $modSettings['current_load'] >= $modSettings['loadavg_unread']) {
            fatal_lang_error('loadavg_unread_disabled', false);
        }
        // Parameters for the main query.
        $query_parameters = array();
        // Are we specifying any specific board?
        if (isset($_REQUEST['children']) && (!empty($board) || !empty($_REQUEST['boards']))) {
            $boards = array();
            if (!empty($_REQUEST['boards'])) {
                $_REQUEST['boards'] = explode(',', $_REQUEST['boards']);
                foreach ($_REQUEST['boards'] as $b) {
                    $boards[] = (int) $b;
                }
            }
            if (!empty($board)) {
                $boards[] = (int) $board;
            }
            // The easiest thing is to just get all the boards they can see,
            // but since we've specified the top of tree we ignore some of them
            addChildBoards($boards);
            if (empty($boards)) {
                fatal_lang_error('error_no_boards_selected');
            }
            $query_this_board = 'id_board IN ({array_int:boards})';
            $query_parameters['boards'] = $boards;
            $context['querystring_board_limits'] = ';boards=' . implode(',', $boards) . ';start=%d';
        } elseif (!empty($board)) {
            $query_this_board = 'id_board = {int:board}';
            $query_parameters['board'] = $board;
            $context['querystring_board_limits'] = ';board=' . $board . '.%1$d';
        } elseif (!empty($_REQUEST['boards'])) {
            $selected_boards = array_map('intval', explode(',', $_REQUEST['boards']));
            $boards = accessibleBoards($selected_boards);
            if (empty($boards)) {
                fatal_lang_error('error_no_boards_selected');
            }
            $query_this_board = 'id_board IN ({array_int:boards})';
            $query_parameters['boards'] = $boards;
            $context['querystring_board_limits'] = ';boards=' . implode(',', $boards) . ';start=%1$d';
        } elseif (!empty($_REQUEST['c'])) {
            $categories = array_map('intval', explode(',', $_REQUEST['c']));
            $boards = array_keys(boardsPosts(array(), $categories, isset($_REQUEST['action']) && $_REQUEST['action'] != 'unreadreplies'));
            if (empty($boards)) {
                fatal_lang_error('error_no_boards_selected');
            }
            $query_this_board = 'id_board IN ({array_int:boards})';
            $query_parameters['boards'] = $boards;
            $context['querystring_board_limits'] = ';c=' . $_REQUEST['c'] . ';start=%1$d';
        } else {
            $see_board = isset($_REQUEST['action']) && $_REQUEST['action'] == 'unreadreplies' ? 'query_see_board' : 'query_wanna_see_board';
            // Don't bother to show deleted posts!
            $boards = wantedBoards($see_board);
            if (empty($boards)) {
                fatal_lang_error('error_no_boards_selected');
            }
            $query_this_board = 'id_board IN ({array_int:boards})';
            $query_parameters['boards'] = $boards;
            $context['querystring_board_limits'] = ';start=%1$d';
            $context['no_board_limits'] = true;
        }
        $sort_methods = array('subject' => 'ms.subject', 'starter' => 'IFNULL(mems.real_name, ms.poster_name)', 'replies' => 't.num_replies', 'views' => 't.num_views', 'first_post' => 't.id_topic', 'last_post' => 't.id_last_msg');
        // The default is the most logical: newest first.
        if (!isset($_REQUEST['sort']) || !isset($sort_methods[$_REQUEST['sort']])) {
            $context['sort_by'] = 'last_post';
            $ascending = isset($_REQUEST['asc']);
            $context['querystring_sort_limits'] = $ascending ? ';asc' : '';
        } else {
            $context['sort_by'] = $_REQUEST['sort'];
            $ascending = !isset($_REQUEST['desc']);
            $context['querystring_sort_limits'] = ';sort=' . $context['sort_by'] . ($ascending ? '' : ';desc');
        }
        $_REQUEST['sort'] = $sort_methods[$context['sort_by']];
        $context['sort_direction'] = $ascending ? 'up' : 'down';
        $context['sort_title'] = $ascending ? $txt['sort_desc'] : $txt['sort_asc'];
        // Trick
        $txt['starter'] = $txt['started_by'];
        foreach ($sort_methods as $key => $val) {
            $context['topics_headers'][$key] = array('url' => $scripturl . '?action=unread' . ($context['showing_all_topics'] ? ';all' : '') . sprintf($context['querystring_board_limits'], $_REQUEST['start']) . ';sort=subject' . ($context['sort_by'] == 'subject' && $context['sort_direction'] == 'up' ? ';desc' : ''), 'sort_dir_img' => $context['sort_by'] == $key ? '<img class="sort" src="' . $settings['images_url'] . '/sort_' . $context['sort_direction'] . '.png" alt="" title="' . $context['sort_title'] . '" />' : '');
        }
        if (!empty($_REQUEST['c']) && is_array($_REQUEST['c']) && count($_REQUEST['c']) == 1) {
            $name = categoryName((int) $_REQUEST['c'][0]);
            $context['linktree'][] = array('url' => $scripturl . '#c' . (int) $_REQUEST['c'][0], 'name' => $name);
        }
        $context['linktree'][] = array('url' => $scripturl . '?action=' . $_REQUEST['action'] . sprintf($context['querystring_board_limits'], 0) . $context['querystring_sort_limits'], 'name' => $_REQUEST['action'] == 'unread' ? $txt['unread_topics_visit'] : $txt['unread_replies']);
        if ($context['showing_all_topics']) {
            $context['linktree'][] = array('url' => $scripturl . '?action=' . $_REQUEST['action'] . ';all' . sprintf($context['querystring_board_limits'], 0) . $context['querystring_sort_limits'], 'name' => $txt['unread_topics_all']);
            $txt['unread_topics_visit_none'] = str_replace('{unread_all_url}', $scripturl . '?action=unread;all', $txt['unread_topics_visit_none']);
        } else {
            $txt['unread_topics_visit_none'] = str_replace('{unread_all_url}', $scripturl . '?action=unread;all' . sprintf($context['querystring_board_limits'], 0) . $context['querystring_sort_limits'], $txt['unread_topics_visit_none']);
        }
        loadTemplate('Recent');
        $context['sub_template'] = $_REQUEST['action'] == 'unread' ? 'unread' : 'replies';
        // Setup the default topic icons... for checking they exist and the like ;)
        require_once SUBSDIR . '/MessageIndex.subs.php';
        $context['icon_sources'] = MessageTopicIcons();
        $is_topics = $_REQUEST['action'] == 'unread';
        // If empty, no preview at all
        if (empty($modSettings['message_index_preview'])) {
            $preview_bodies = '';
        } elseif (empty($modSettings['preview_characters'])) {
            $preview_bodies = 'ml.body AS last_body, ms.body AS first_body,';
        } else {
            $preview_bodies = 'SUBSTRING(ml.body, 1, ' . ($modSettings['preview_characters'] + 256) . ') AS last_body, SUBSTRING(ms.body, 1, ' . ($modSettings['preview_characters'] + 256) . ') AS first_body,';
        }
        // This part is the same for each query.
        $select_clause = '
					ms.subject AS first_subject, ms.poster_time AS first_poster_time, ms.id_topic, t.id_board, b.name AS bname,
					t.num_replies, t.num_views, t.num_likes, ms.id_member AS id_first_member, ml.id_member AS id_last_member,
					ml.poster_time AS last_poster_time, IFNULL(mems.real_name, ms.poster_name) AS first_poster_name,
					IFNULL(meml.real_name, ml.poster_name) AS last_poster_name, ml.subject AS last_subject,
					ml.icon AS last_icon, ms.icon AS first_icon, t.id_poll, t.is_sticky, t.locked, ml.modified_time AS last_modified_time,
					IFNULL(lt.id_msg, IFNULL(lmr.id_msg, -1)) + 1 AS new_from,
					' . $preview_bodies . '
					ml.smileys_enabled AS last_smileys, ms.smileys_enabled AS first_smileys, t.id_first_msg, t.id_last_msg';
        if ($context['showing_all_topics']) {
            $earliest_msg = earliest_msg();
        }
        // @todo Add modified_time in for log_time check?
        if ($modSettings['totalMessages'] > 100000 && $context['showing_all_topics']) {
            $db->query('', '
				DROP TABLE IF EXISTS {db_prefix}log_topics_unread', array());
            // Let's copy things out of the log_topics table, to reduce searching.
            $have_temp_table = $db->query('', '
				CREATE TEMPORARY TABLE {db_prefix}log_topics_unread (
					PRIMARY KEY (id_topic)
				)
				SELECT lt.id_topic, lt.id_msg, lt.unwatched
				FROM {db_prefix}topics AS t
					INNER JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = t.id_topic)
				WHERE lt.id_member = {int:current_member}
					AND t.' . $query_this_board . (empty($earliest_msg) ? '' : '
					AND t.id_last_msg > {int:earliest_msg}') . ($modSettings['postmod_active'] ? '
					AND t.approved = {int:is_approved}' : '') . ($modSettings['enable_unwatch'] ? '
					AND lt.unwatched != 1' : ''), array_merge($query_parameters, array('current_member' => $user_info['id'], 'earliest_msg' => !empty($earliest_msg) ? $earliest_msg : 0, 'is_approved' => 1, 'db_error_skip' => true))) !== false;
        } else {
            $have_temp_table = false;
        }
        if ($context['showing_all_topics'] && $have_temp_table) {
            $request = $db->query('', '
				SELECT COUNT(*), MIN(t.id_last_msg)
				FROM {db_prefix}topics AS t
					LEFT JOIN {db_prefix}log_topics_unread AS lt ON (lt.id_topic = t.id_topic)
					LEFT JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = t.id_board AND lmr.id_member = {int:current_member})
				WHERE t.' . $query_this_board . (!empty($earliest_msg) ? '
					AND t.id_last_msg > {int:earliest_msg}' : '') . '
					AND IFNULL(lt.id_msg, IFNULL(lmr.id_msg, 0)) < t.id_last_msg' . ($modSettings['postmod_active'] ? ' AND t.approved = {int:is_approved}' : '') . ($modSettings['enable_unwatch'] ? ' AND IFNULL(lt.unwatched, 0) != 1' : ''), array_merge($query_parameters, array('current_member' => $user_info['id'], 'earliest_msg' => !empty($earliest_msg) ? $earliest_msg : 0, 'is_approved' => 1)));
            list($num_topics, $min_message) = $db->fetch_row($request);
            $db->free_result($request);
            // Make sure the starting place makes sense and construct the page index.
            $context['page_index'] = constructPageIndex($scripturl . '?action=' . $_REQUEST['action'] . ($context['showing_all_topics'] ? ';all' : '') . $context['querystring_board_limits'] . $context['querystring_sort_limits'], $_REQUEST['start'], $num_topics, $context['topics_per_page'], true);
            $context['current_page'] = (int) $_REQUEST['start'] / $context['topics_per_page'];
            $context['links'] += array('prev' => $_REQUEST['start'] >= $context['topics_per_page'] ? $scripturl . '?action=' . $_REQUEST['action'] . ($context['showing_all_topics'] ? ';all' : '') . sprintf($context['querystring_board_limits'], $_REQUEST['start'] - $context['topics_per_page']) . $context['querystring_sort_limits'] : '', 'next' => $_REQUEST['start'] + $context['topics_per_page'] < $num_topics ? $scripturl . '?action=' . $_REQUEST['action'] . ($context['showing_all_topics'] ? ';all' : '') . sprintf($context['querystring_board_limits'], $_REQUEST['start'] + $context['topics_per_page']) . $context['querystring_sort_limits'] : '');
            $context['page_info'] = array('current_page' => $_REQUEST['start'] / $context['topics_per_page'] + 1, 'num_pages' => floor(($num_topics - 1) / $context['topics_per_page']) + 1);
            if ($num_topics == 0) {
                // Mark the boards as read if there are no unread topics!
                // @todo look at this... there are no more unread topics already.
                // If clearing of log_topics is still needed, perhaps do it separately.
                markBoardsRead(empty($boards) ? $board : $boards, false, true);
                $context['topics'] = array();
                if ($context['querystring_board_limits'] == ';start=%1$d') {
                    $context['querystring_board_limits'] = '';
                } else {
                    $context['querystring_board_limits'] = sprintf($context['querystring_board_limits'], $_REQUEST['start']);
                }
                return;
            } else {
                $min_message = (int) $min_message;
            }
            $request = $db->query('substring', '
				SELECT ' . $select_clause . '
				FROM {db_prefix}messages AS ms
					INNER JOIN {db_prefix}topics AS t ON (t.id_topic = ms.id_topic AND t.id_first_msg = ms.id_msg)
					INNER JOIN {db_prefix}messages AS ml ON (ml.id_msg = t.id_last_msg)
					LEFT JOIN {db_prefix}boards AS b ON (b.id_board = ms.id_board)
					LEFT JOIN {db_prefix}members AS mems ON (mems.id_member = ms.id_member)
					LEFT JOIN {db_prefix}members AS meml ON (meml.id_member = ml.id_member)
					LEFT JOIN {db_prefix}log_topics_unread AS lt ON (lt.id_topic = t.id_topic)
					LEFT JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = t.id_board AND lmr.id_member = {int:current_member})
				WHERE b.' . $query_this_board . '
					AND t.id_last_msg >= {int:min_message}
					AND IFNULL(lt.id_msg, IFNULL(lmr.id_msg, 0)) < t.id_last_msg' . ($modSettings['postmod_active'] ? ' AND ms.approved = {int:is_approved}' : '') . ($modSettings['enable_unwatch'] ? ' AND IFNULL(lt.unwatched, 0) != 1' : '') . '
				ORDER BY {raw:sort}
				LIMIT {int:offset}, {int:limit}', array_merge($query_parameters, array('current_member' => $user_info['id'], 'min_message' => $min_message, 'is_approved' => 1, 'sort' => $_REQUEST['sort'] . ($ascending ? '' : ' DESC'), 'offset' => $_REQUEST['start'], 'limit' => $context['topics_per_page'])));
        } elseif ($is_topics) {
            $request = $db->query('', '
				SELECT COUNT(*), MIN(t.id_last_msg)
				FROM {db_prefix}topics AS t' . (!empty($have_temp_table) ? '
					LEFT JOIN {db_prefix}log_topics_unread AS lt ON (lt.id_topic = t.id_topic)' : '
					LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = t.id_topic AND lt.id_member = {int:current_member})') . '
					LEFT JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = t.id_board AND lmr.id_member = {int:current_member})
				WHERE t.' . $query_this_board . ($context['showing_all_topics'] && !empty($earliest_msg) ? '
					AND t.id_last_msg > {int:earliest_msg}' : (!$context['showing_all_topics'] && empty($_SESSION['first_login']) ? '
					AND t.id_last_msg > {int:id_msg_last_visit}' : '')) . '
					AND IFNULL(lt.id_msg, IFNULL(lmr.id_msg, 0)) < t.id_last_msg' . ($modSettings['postmod_active'] ? ' AND t.approved = {int:is_approved}' : '') . ($modSettings['enable_unwatch'] ? ' AND IFNULL(lt.unwatched, 0) != 1' : ''), array_merge($query_parameters, array('current_member' => $user_info['id'], 'earliest_msg' => !empty($earliest_msg) ? $earliest_msg : 0, 'id_msg_last_visit' => $_SESSION['id_msg_last_visit'], 'is_approved' => 1)));
            list($num_topics, $min_message) = $db->fetch_row($request);
            $db->free_result($request);
            // Make sure the starting place makes sense and construct the page index.
            $context['page_index'] = constructPageIndex($scripturl . '?action=' . $_REQUEST['action'] . ($context['showing_all_topics'] ? ';all' : '') . $context['querystring_board_limits'] . $context['querystring_sort_limits'], $_REQUEST['start'], $num_topics, $context['topics_per_page'], true);
            $context['current_page'] = (int) $_REQUEST['start'] / $context['topics_per_page'];
            $context['links'] += array('prev' => $_REQUEST['start'] >= $context['topics_per_page'] ? $scripturl . '?action=' . $_REQUEST['action'] . ($context['showing_all_topics'] ? ';all' : '') . sprintf($context['querystring_board_limits'], $_REQUEST['start'] - $context['topics_per_page']) . $context['querystring_sort_limits'] : '', 'next' => $_REQUEST['start'] + $context['topics_per_page'] < $num_topics ? $scripturl . '?action=' . $_REQUEST['action'] . ($context['showing_all_topics'] ? ';all' : '') . sprintf($context['querystring_board_limits'], $_REQUEST['start'] + $context['topics_per_page']) . $context['querystring_sort_limits'] : '');
            $context['page_info'] = array('current_page' => $_REQUEST['start'] / $context['topics_per_page'] + 1, 'num_pages' => floor(($num_topics - 1) / $context['topics_per_page']) + 1);
            if ($num_topics == 0) {
                // Is this an all topics query?
                if ($context['showing_all_topics']) {
                    // Since there are no unread topics, mark the boards as read!
                    // @todo look at this... there are no more unread topics already.
                    // If clearing of log_topics is still needed, perhaps do it separately.
                    markBoardsRead(empty($boards) ? $board : $boards, false, true);
                }
                $context['topics'] = array();
                if ($context['querystring_board_limits'] == ';start=%d') {
                    $context['querystring_board_limits'] = '';
                } else {
                    $context['querystring_board_limits'] = sprintf($context['querystring_board_limits'], $_REQUEST['start']);
                }
                return;
            } else {
                $min_message = (int) $min_message;
            }
            $request = $db->query('substring', '
				SELECT ' . $select_clause . '
				FROM {db_prefix}messages AS ms
					INNER JOIN {db_prefix}topics AS t ON (t.id_topic = ms.id_topic AND t.id_first_msg = ms.id_msg)
					INNER JOIN {db_prefix}messages AS ml ON (ml.id_msg = t.id_last_msg)
					LEFT JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
					LEFT JOIN {db_prefix}members AS mems ON (mems.id_member = ms.id_member)
					LEFT JOIN {db_prefix}members AS meml ON (meml.id_member = ml.id_member)' . (!empty($have_temp_table) ? '
					LEFT JOIN {db_prefix}log_topics_unread AS lt ON (lt.id_topic = t.id_topic)' : '
					LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = t.id_topic AND lt.id_member = {int:current_member})') . '
					LEFT JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = t.id_board AND lmr.id_member = {int:current_member})
				WHERE t.' . $query_this_board . '
					AND t.id_last_msg >= {int:min_message}
					AND IFNULL(lt.id_msg, IFNULL(lmr.id_msg, 0)) < ml.id_msg' . ($modSettings['postmod_active'] ? ' AND ms.approved = {int:is_approved}' : '') . ($modSettings['enable_unwatch'] ? ' AND IFNULL(lt.unwatched, 0) != 1' : '') . '
				ORDER BY {raw:order}
				LIMIT {int:offset}, {int:limit}', array_merge($query_parameters, array('current_member' => $user_info['id'], 'min_message' => $min_message, 'is_approved' => 1, 'order' => $_REQUEST['sort'] . ($ascending ? '' : ' DESC'), 'offset' => $_REQUEST['start'], 'limit' => $context['topics_per_page'])));
        } else {
            if ($modSettings['totalMessages'] > 100000) {
                $db->query('', '
					DROP TABLE IF EXISTS {db_prefix}topics_posted_in', array());
                $db->query('', '
					DROP TABLE IF EXISTS {db_prefix}log_topics_posted_in', array());
                $sortKey_joins = array('ms.subject' => '
						INNER JOIN {db_prefix}messages AS ms ON (ms.id_msg = t.id_first_msg)', 'IFNULL(mems.real_name, ms.poster_name)' => '
						INNER JOIN {db_prefix}messages AS ms ON (ms.id_msg = t.id_first_msg)
						LEFT JOIN {db_prefix}members AS mems ON (mems.id_member = ms.id_member)');
                // The main benefit of this temporary table is not that it's faster; it's that it avoids locks later.
                $have_temp_table = $db->query('', '
					CREATE TEMPORARY TABLE {db_prefix}topics_posted_in (
						id_topic mediumint(8) unsigned NOT NULL default {string:string_zero},
						id_board smallint(5) unsigned NOT NULL default {string:string_zero},
						id_last_msg int(10) unsigned NOT NULL default {string:string_zero},
						id_msg int(10) unsigned NOT NULL default {string:string_zero},
						PRIMARY KEY (id_topic)
					)
					SELECT t.id_topic, t.id_board, t.id_last_msg, IFNULL(lmr.id_msg, 0) AS id_msg' . (!in_array($_REQUEST['sort'], array('t.id_last_msg', 't.id_topic')) ? ', ' . $_REQUEST['sort'] . ' AS sort_key' : '') . '
					FROM {db_prefix}messages AS m
						INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)' . ($modSettings['enable_unwatch'] ? '
						LEFT JOIN {db_prefix}log_topics AS lt ON (t.id_topic = lt.id_topic AND lt.id_member = {int:current_member})' : '') . '
						LEFT JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = t.id_board AND lmr.id_member = {int:current_member})' . (isset($sortKey_joins[$_REQUEST['sort']]) ? $sortKey_joins[$_REQUEST['sort']] : '') . '
					WHERE m.id_member = {int:current_member}' . (!empty($board) ? '
						AND t.id_board = {int:current_board}' : '') . ($modSettings['postmod_active'] ? '
						AND t.approved = {int:is_approved}' : '') . ($modSettings['enable_unwatch'] ? '
						AND IFNULL(lt.unwatched, 0) != 1' : '') . '
					GROUP BY m.id_topic', array('current_board' => $board, 'current_member' => $user_info['id'], 'is_approved' => 1, 'string_zero' => '0', 'db_error_skip' => true)) !== false;
                // If that worked, create a sample of the log_topics table too.
                if ($have_temp_table) {
                    $have_temp_table = $db->query('', '
						CREATE TEMPORARY TABLE {db_prefix}log_topics_posted_in (
							PRIMARY KEY (id_topic)
						)
						SELECT lt.id_topic, lt.id_msg
						FROM {db_prefix}log_topics AS lt
							INNER JOIN {db_prefix}topics_posted_in AS pi ON (pi.id_topic = lt.id_topic)
						WHERE lt.id_member = {int:current_member}', array('current_member' => $user_info['id'], 'db_error_skip' => true)) !== false;
                }
            }
            if (!empty($have_temp_table)) {
                $request = $db->query('', '
					SELECT COUNT(*)
					FROM {db_prefix}topics_posted_in AS pi
						LEFT JOIN {db_prefix}log_topics_posted_in AS lt ON (lt.id_topic = pi.id_topic)
					WHERE pi.' . $query_this_board . '
						AND IFNULL(lt.id_msg, pi.id_msg) < pi.id_last_msg', array_merge($query_parameters, array()));
                list($num_topics) = $db->fetch_row($request);
                $db->free_result($request);
                $min_message = 0;
            } else {
                $request = $db->query('unread_fetch_topic_count', '
					SELECT COUNT(DISTINCT t.id_topic), MIN(t.id_last_msg)
					FROM {db_prefix}topics AS t
						INNER JOIN {db_prefix}messages AS m ON (m.id_topic = t.id_topic)
						LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = t.id_topic AND lt.id_member = {int:current_member})
						LEFT JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = t.id_board AND lmr.id_member = {int:current_member})
					WHERE t.' . $query_this_board . '
						AND m.id_member = {int:current_member}
						AND IFNULL(lt.id_msg, IFNULL(lmr.id_msg, 0)) < t.id_last_msg' . ($modSettings['postmod_active'] ? '
						AND t.approved = {int:is_approved}' : '') . ($modSettings['enable_unwatch'] ? '
						AND IFNULL(lt.unwatched, 0) != 1' : ''), array_merge($query_parameters, array('current_member' => $user_info['id'], 'is_approved' => 1)));
                list($num_topics, $min_message) = $db->fetch_row($request);
                $db->free_result($request);
            }
            // Make sure the starting place makes sense and construct the page index.
            $context['page_index'] = constructPageIndex($scripturl . '?action=' . $_REQUEST['action'] . $context['querystring_board_limits'] . $context['querystring_sort_limits'], $_REQUEST['start'], $num_topics, $context['topics_per_page'], true);
            $context['current_page'] = (int) $_REQUEST['start'] / $context['topics_per_page'];
            $context['links'] += array('first' => $_REQUEST['start'] >= $context['topics_per_page'] ? $scripturl . '?action=' . $_REQUEST['action'] . ($context['showing_all_topics'] ? ';all' : '') . sprintf($context['querystring_board_limits'], 0) . $context['querystring_sort_limits'] : '', 'prev' => $_REQUEST['start'] >= $context['topics_per_page'] ? $scripturl . '?action=' . $_REQUEST['action'] . ($context['showing_all_topics'] ? ';all' : '') . sprintf($context['querystring_board_limits'], $_REQUEST['start'] - $context['topics_per_page']) . $context['querystring_sort_limits'] : '', 'next' => $_REQUEST['start'] + $context['topics_per_page'] < $num_topics ? $scripturl . '?action=' . $_REQUEST['action'] . ($context['showing_all_topics'] ? ';all' : '') . sprintf($context['querystring_board_limits'], $_REQUEST['start'] + $context['topics_per_page']) . $context['querystring_sort_limits'] : '', 'last' => $_REQUEST['start'] + $context['topics_per_page'] < $num_topics ? $scripturl . '?action=' . $_REQUEST['action'] . ($context['showing_all_topics'] ? ';all' : '') . sprintf($context['querystring_board_limits'], floor(($num_topics - 1) / $context['topics_per_page']) * $context['topics_per_page']) . $context['querystring_sort_limits'] : '', 'up' => $scripturl);
            $context['page_info'] = array('current_page' => $_REQUEST['start'] / $context['topics_per_page'] + 1, 'num_pages' => floor(($num_topics - 1) / $context['topics_per_page']) + 1);
            if ($num_topics == 0) {
                $context['topics'] = array();
                if ($context['querystring_board_limits'] == ';start=%d') {
                    $context['querystring_board_limits'] = '';
                } else {
                    $context['querystring_board_limits'] = sprintf($context['querystring_board_limits'], $_REQUEST['start']);
                }
                return;
            }
            if (!empty($have_temp_table)) {
                $request = $db->query('', '
					SELECT t.id_topic
					FROM {db_prefix}topics_posted_in AS t
						LEFT JOIN {db_prefix}log_topics_posted_in AS lt ON (lt.id_topic = t.id_topic)
					WHERE t.' . $query_this_board . '
						AND IFNULL(lt.id_msg, t.id_msg) < t.id_last_msg
					ORDER BY {raw:order}
					LIMIT {int:offset}, {int:limit}', array_merge($query_parameters, array('order' => (in_array($_REQUEST['sort'], array('t.id_last_msg', 't.id_topic')) ? $_REQUEST['sort'] : 't.sort_key') . ($ascending ? '' : ' DESC'), 'offset' => $_REQUEST['start'], 'limit' => $context['topics_per_page'])));
            } else {
                $request = $db->query('unread_replies', '
					SELECT DISTINCT t.id_topic
					FROM {db_prefix}topics AS t
						INNER JOIN {db_prefix}messages AS m ON (m.id_topic = t.id_topic AND m.id_member = {int:current_member})' . (strpos($_REQUEST['sort'], 'ms.') === false ? '' : '
						INNER JOIN {db_prefix}messages AS ms ON (ms.id_msg = t.id_first_msg)') . (strpos($_REQUEST['sort'], 'mems.') === false ? '' : '
						LEFT JOIN {db_prefix}members AS mems ON (mems.id_member = ms.id_member)') . '
						LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = t.id_topic AND lt.id_member = {int:current_member})
						LEFT JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = t.id_board AND lmr.id_member = {int:current_member})
					WHERE t.' . $query_this_board . '
						AND t.id_last_msg >= {int:min_message}
						AND (IFNULL(lt.id_msg, IFNULL(lmr.id_msg, 0))) < t.id_last_msg' . ($modSettings['postmod_active'] ? ' AND t.approved = {int:is_approved}' : '') . ($modSettings['enable_unwatch'] ? ' AND IFNULL(lt.unwatched, 0) != 1' : '') . '
					ORDER BY {raw:order}
					LIMIT {int:offset}, {int:limit}', array_merge($query_parameters, array('current_member' => $user_info['id'], 'min_message' => (int) $min_message, 'is_approved' => 1, 'order' => $_REQUEST['sort'] . ($ascending ? '' : ' DESC'), 'offset' => $_REQUEST['start'], 'limit' => $context['topics_per_page'], 'sort' => $_REQUEST['sort'])));
            }
            $topics = array();
            while ($row = $db->fetch_assoc($request)) {
                $topics[] = $row['id_topic'];
            }
            $db->free_result($request);
            // Sanity... where have you gone?
            if (empty($topics)) {
                $context['topics'] = array();
                if ($context['querystring_board_limits'] == ';start=%d') {
                    $context['querystring_board_limits'] = '';
                } else {
                    $context['querystring_board_limits'] = sprintf($context['querystring_board_limits'], $_REQUEST['start']);
                }
                return;
            }
            $request = $db->query('substring', '
				SELECT ' . $select_clause . '
				FROM {db_prefix}topics AS t
					INNER JOIN {db_prefix}messages AS ms ON (ms.id_topic = t.id_topic AND ms.id_msg = t.id_first_msg)
					INNER JOIN {db_prefix}messages AS ml ON (ml.id_msg = t.id_last_msg)
					INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
					LEFT JOIN {db_prefix}members AS mems ON (mems.id_member = ms.id_member)
					LEFT JOIN {db_prefix}members AS meml ON (meml.id_member = ml.id_member)
					LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = t.id_topic AND lt.id_member = {int:current_member})
					LEFT JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = t.id_board AND lmr.id_member = {int:current_member})
				WHERE t.id_topic IN ({array_int:topic_list})
				ORDER BY ' . $_REQUEST['sort'] . ($ascending ? '' : ' DESC') . '
				LIMIT ' . count($topics), array('current_member' => $user_info['id'], 'topic_list' => $topics));
        }
        $context['topics'] = array();
        $topic_ids = array();
        while ($row = $db->fetch_assoc($request)) {
            $topic_ids[] = $row['id_topic'];
            if (!empty($modSettings['message_index_preview'])) {
                // Limit them to 128 characters - do this FIRST because it's a lot of wasted censoring otherwise.
                $row['first_body'] = strip_tags(strtr(parse_bbc($row['first_body'], false, $row['id_first_msg']), array('<br />' => "\n", '&nbsp;' => ' ')));
                $row['first_body'] = Util::shorten_text($row['first_body'], !empty($modSettings['preview_characters']) ? $modSettings['preview_characters'] : 128, true);
                // No reply then they are the same, no need to process it again
                if ($row['num_replies'] == 0) {
                    $row['last_body'] == $row['first_body'];
                } else {
                    $row['last_body'] = strip_tags(strtr(parse_bbc($row['last_body'], false, $row['id_last_msg']), array('<br />' => "\n", '&nbsp;' => ' ')));
                    $row['last_body'] = Util::shorten_text($row['last_body'], !empty($modSettings['preview_characters']) ? $modSettings['preview_characters'] : 128, true);
                }
                // Censor the subject and message preview.
                censorText($row['first_subject']);
                censorText($row['first_body']);
                // Don't censor them twice!
                if ($row['id_first_msg'] == $row['id_last_msg']) {
                    $row['last_subject'] = $row['first_subject'];
                    $row['last_body'] = $row['first_body'];
                } else {
                    censorText($row['last_subject']);
                    censorText($row['last_body']);
                }
            } else {
                $row['first_body'] = '';
                $row['last_body'] = '';
                censorText($row['first_subject']);
                if ($row['id_first_msg'] == $row['id_last_msg']) {
                    $row['last_subject'] = $row['first_subject'];
                } else {
                    censorText($row['last_subject']);
                }
            }
            // Decide how many pages the topic should have.
            $topic_length = $row['num_replies'] + 1;
            $messages_per_page = empty($modSettings['disableCustomPerPage']) && !empty($options['messages_per_page']) ? $options['messages_per_page'] : $modSettings['defaultMaxMessages'];
            if ($topic_length > $messages_per_page) {
                $start = -1;
                $pages = constructPageIndex($scripturl . '?topic=' . $row['id_topic'] . '.%1$d;topicseen', $start, $topic_length, $messages_per_page, true, array('prev_next' => false, 'all' => !empty($modSettings['enableAllMessages']) && $topic_length < $modSettings['enableAllMessages']));
            } else {
                $pages = '';
            }
            // We need to check the topic icons exist... you can never be too sure!
            if (!empty($modSettings['messageIconChecks_enable'])) {
                // First icon first... as you'd expect.
                if (!isset($context['icon_sources'][$row['first_icon']])) {
                    $context['icon_sources'][$row['first_icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $row['first_icon'] . '.png') ? 'images_url' : 'default_images_url';
                }
                // Last icon... last... duh.
                if (!isset($context['icon_sources'][$row['last_icon']])) {
                    $context['icon_sources'][$row['last_icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $row['last_icon'] . '.png') ? 'images_url' : 'default_images_url';
                }
            }
            // And build the array.
            $context['topics'][$row['id_topic']] = array('id' => $row['id_topic'], 'first_post' => array('id' => $row['id_first_msg'], 'member' => array('name' => $row['first_poster_name'], 'id' => $row['id_first_member'], 'href' => $scripturl . '?action=profile;u=' . $row['id_first_member'], 'link' => !empty($row['id_first_member']) ? '<a class="preview" href="' . $scripturl . '?action=profile;u=' . $row['id_first_member'] . '" title="' . $txt['profile_of'] . ' ' . $row['first_poster_name'] . '">' . $row['first_poster_name'] . '</a>' : $row['first_poster_name']), 'time' => standardTime($row['first_poster_time']), 'html_time' => htmlTime($row['first_poster_time']), 'timestamp' => forum_time(true, $row['first_poster_time']), 'subject' => $row['first_subject'], 'preview' => $row['first_body'], 'icon' => $row['first_icon'], 'icon_url' => $settings[$context['icon_sources'][$row['first_icon']]] . '/post/' . $row['first_icon'] . '.png', 'href' => $scripturl . '?topic=' . $row['id_topic'] . '.0;topicseen', 'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0;topicseen">' . $row['first_subject'] . '</a>'), 'last_post' => array('id' => $row['id_last_msg'], 'member' => array('name' => $row['last_poster_name'], 'id' => $row['id_last_member'], 'href' => $scripturl . '?action=profile;u=' . $row['id_last_member'], 'link' => !empty($row['id_last_member']) ? '<a href="' . $scripturl . '?action=profile;u=' . $row['id_last_member'] . '">' . $row['last_poster_name'] . '</a>' : $row['last_poster_name']), 'time' => standardTime($row['last_poster_time']), 'html_time' => htmlTime($row['last_poster_time']), 'timestamp' => forum_time(true, $row['last_poster_time']), 'subject' => $row['last_subject'], 'preview' => $row['last_body'], 'icon' => $row['last_icon'], 'icon_url' => $settings[$context['icon_sources'][$row['last_icon']]] . '/post/' . $row['last_icon'] . '.png', 'href' => $scripturl . '?topic=' . $row['id_topic'] . ($row['num_replies'] == 0 ? '.0' : '.msg' . $row['id_last_msg']) . ';topicseen#msg' . $row['id_last_msg'], 'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . ($row['num_replies'] == 0 ? '.0' : '.msg' . $row['id_last_msg']) . ';topicseen#msg' . $row['id_last_msg'] . '" rel="nofollow">' . $row['last_subject'] . '</a>'), 'default_preview' => trim($row[!empty($modSettings['message_index_preview']) && $modSettings['message_index_preview'] == 2 ? 'last_body' : 'first_body']), 'new_from' => $row['new_from'], 'new_href' => $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['new_from'] . ';topicseen#new', 'href' => $scripturl . '?topic=' . $row['id_topic'] . ($row['num_replies'] == 0 ? '.0' : '.msg' . $row['new_from']) . ';topicseen' . ($row['num_replies'] == 0 ? '' : 'new'), 'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . ($row['num_replies'] == 0 ? '.0' : '.msg' . $row['new_from']) . ';topicseen#msg' . $row['new_from'] . '" rel="nofollow">' . $row['first_subject'] . '</a>', 'is_sticky' => !empty($modSettings['enableStickyTopics']) && !empty($row['is_sticky']), 'is_locked' => !empty($row['locked']), 'is_poll' => !empty($modSettings['pollMode']) && $row['id_poll'] > 0, 'is_hot' => !empty($modSettings['useLikesNotViews']) ? $row['num_likes'] >= $modSettings['hotTopicPosts'] : $row['num_replies'] >= $modSettings['hotTopicPosts'], 'is_very_hot' => !empty($modSettings['useLikesNotViews']) ? $row['num_likes'] >= $modSettings['hotTopicVeryPosts'] : $row['num_replies'] >= $modSettings['hotTopicVeryPosts'], 'is_posted_in' => false, 'icon' => $row['first_icon'], 'icon_url' => $settings[$context['icon_sources'][$row['first_icon']]] . '/post/' . $row['first_icon'] . '.png', 'subject' => $row['first_subject'], 'pages' => $pages, 'replies' => comma_format($row['num_replies']), 'views' => comma_format($row['num_views']), 'likes' => comma_format($row['num_likes']), 'board' => array('id' => $row['id_board'], 'name' => $row['bname'], 'href' => $scripturl . '?board=' . $row['id_board'] . '.0', 'link' => '<a href="' . $scripturl . '?board=' . $row['id_board'] . '.0">' . $row['bname'] . '</a>'));
            $context['topics'][$row['id_topic']]['first_post']['started_by'] = sprintf($txt['topic_started_by_in'], '<strong>' . $context['topics'][$row['id_topic']]['first_post']['member']['link'] . '</strong>', '<em>' . $context['topics'][$row['id_topic']]['board']['link'] . '</em>');
            determineTopicClass($context['topics'][$row['id_topic']]);
        }
        $db->free_result($request);
        if ($is_topics && !empty($modSettings['enableParticipation']) && !empty($topic_ids)) {
            require_once SUBSDIR . '/MessageIndex.subs.php';
            $topics_participated_in = topicsParticipation($user_info['id'], $topic_ids);
            foreach ($topics_participated_in as $topic) {
                if (empty($context['topics'][$topic['id_topic']]['is_posted_in'])) {
                    $context['topics'][$topic['id_topic']]['is_posted_in'] = true;
                    $context['topics'][$topic['id_topic']]['class'] = 'my_' . $context['topics'][$topic['id_topic']]['class'];
                }
            }
        }
        $context['querystring_board_limits'] = sprintf($context['querystring_board_limits'], $_REQUEST['start']);
        $context['topics_to_mark'] = implode('-', $topic_ids);
        if ($settings['show_mark_read']) {
            // Build the recent button array.
            if ($is_topics) {
                $context['recent_buttons'] = array('markread' => array('text' => !empty($context['no_board_limits']) ? 'mark_as_read' : 'mark_read_short', 'image' => 'markread.png', 'lang' => true, 'custom' => 'onclick="return markunreadButton(this);"', 'url' => $scripturl . '?action=markasread;sa=' . (!empty($context['no_board_limits']) ? 'all' : 'board' . $context['querystring_board_limits']) . ';' . $context['session_var'] . '=' . $context['session_id']));
                if ($context['showCheckboxes']) {
                    $context['recent_buttons']['markselectread'] = array('text' => 'quick_mod_markread', 'image' => 'markselectedread.png', 'lang' => true, 'url' => 'javascript:document.quickModForm.submit();');
                }
                if (!empty($context['topics']) && !$context['showing_all_topics']) {
                    $context['recent_buttons']['readall'] = array('text' => 'unread_topics_all', 'image' => 'markreadall.png', 'lang' => true, 'url' => $scripturl . '?action=unread;all' . $context['querystring_board_limits'], 'active' => true);
                }
            } elseif (!$is_topics && isset($context['topics_to_mark'])) {
                $context['recent_buttons'] = array('markread' => array('text' => 'mark_as_read', 'image' => 'markread.png', 'lang' => true, 'url' => $scripturl . '?action=markasread;sa=unreadreplies;topics=' . $context['topics_to_mark'] . ';' . $context['session_var'] . '=' . $context['session_id']));
                if ($context['showCheckboxes']) {
                    $context['recent_buttons']['markselectread'] = array('text' => 'quick_mod_markread', 'image' => 'markselectedread.png', 'lang' => true, 'url' => 'javascript:document.quickModForm.submit();');
                }
            }
            // Allow mods to add additional buttons here
            call_integration_hook('integrate_recent_buttons');
        }
        // Allow helpdesks and bug trackers and what not to add their own unread data (just add a template_layer to show custom stuff in the template!)
        call_integration_hook('integrate_unread_list');
    }