コード例 #1
0
 /**
  * Completely remove an entire topic.
  * Redirects to the board when completed.
  * Accessed by ?action=removetopic2
  */
 public function action_removetopic2()
 {
     global $user_info, $topic, $board, $modSettings;
     // Make sure they aren't being lead around by someone. (:@)
     checkSession('get');
     // This file needs to be included for sendNotifications().
     require_once SUBSDIR . '/Notification.subs.php';
     // This needs to be included for all the topic db functions
     require_once SUBSDIR . '/Topic.subs.php';
     // Trying to fool us around, are we?
     if (empty($topic)) {
         redirectexit();
     }
     $this->removeDeleteConcurrence();
     $topic_info = getTopicInfo($topic, 'message');
     if ($topic_info['id_member_started'] == $user_info['id'] && !allowedTo('remove_any')) {
         isAllowedTo('remove_own');
     } else {
         isAllowedTo('remove_any');
     }
     // Can they see the topic?
     if ($modSettings['postmod_active'] && !$topic_info['approved'] && $topic_info['id_member_started'] != $user_info['id']) {
         isAllowedTo('approve_posts');
     }
     // Notify people that this topic has been removed.
     sendNotifications($topic, 'remove');
     removeTopics($topic);
     // Note, only log topic ID in native form if it's not gone forever.
     if (allowedTo('remove_any') || allowedTo('remove_own') && $topic_info['id_member_started'] == $user_info['id']) {
         logAction('remove', array(empty($modSettings['recycle_enable']) || $modSettings['recycle_board'] != $board ? 'topic' : 'old_topic_id' => $topic, 'subject' => $topic_info['subject'], 'member' => $topic_info['id_member_started'], 'board' => $board));
     }
     redirectexit('board=' . $board . '.0');
 }
コード例 #2
0
 /**
  * In-topic quick moderation.
  * Accessed by ?action=quickmod2
  */
 public function action_quickmod2()
 {
     global $topic, $board, $user_info, $context;
     // Check the session = get or post.
     checkSession('request');
     require_once SUBSDIR . '/Messages.subs.php';
     if (empty($_REQUEST['msgs'])) {
         redirectexit('topic=' . $topic . '.' . $_REQUEST['start']);
     }
     $messages = array();
     foreach ($_REQUEST['msgs'] as $dummy) {
         $messages[] = (int) $dummy;
     }
     // We are restoring messages. We handle this in another place.
     if (isset($_REQUEST['restore_selected'])) {
         redirectexit('action=restoretopic;msgs=' . implode(',', $messages) . ';' . $context['session_var'] . '=' . $context['session_id']);
     }
     if (isset($_REQUEST['split_selection'])) {
         $mgsOptions = basicMessageInfo(min($messages), true);
         $_SESSION['split_selection'][$topic] = $messages;
         redirectexit('action=splittopics;sa=selectTopics;topic=' . $topic . '.0;subname_enc=' . urlencode($mgsOptions['subject']) . ';' . $context['session_var'] . '=' . $context['session_id']);
     }
     require_once SUBSDIR . '/Topic.subs.php';
     $topic_info = getTopicInfo($topic);
     // Allowed to delete any message?
     if (allowedTo('delete_any')) {
         $allowed_all = true;
     } elseif (allowedTo('delete_replies')) {
         $allowed_all = $topic_info['id_member_started'] == $user_info['id'];
     } else {
         $allowed_all = false;
     }
     // Make sure they're allowed to delete their own messages, if not any.
     if (!$allowed_all) {
         isAllowedTo('delete_own');
     }
     // Allowed to remove which messages?
     $messages = determineRemovableMessages($topic, $messages, $allowed_all);
     // Get the first message in the topic - because you can't delete that!
     $first_message = $topic_info['id_first_msg'];
     $last_message = $topic_info['id_last_msg'];
     // Delete all the messages we know they can delete. ($messages)
     foreach ($messages as $message => $info) {
         // Just skip the first message - if it's not the last.
         if ($message == $first_message && $message != $last_message) {
             continue;
         } elseif ($message == $first_message) {
             $topicGone = true;
         }
         removeMessage($message);
         // Log this moderation action ;).
         if (allowedTo('delete_any') && (!allowedTo('delete_own') || $info[1] != $user_info['id'])) {
             logAction('delete', array('topic' => $topic, 'subject' => $info[0], 'member' => $info[1], 'board' => $board));
         }
     }
     redirectexit(!empty($topicGone) ? 'board=' . $board : 'topic=' . $topic . '.' . $_REQUEST['start']);
 }
コード例 #3
0
ファイル: SSI.php プロジェクト: scripple/Elkarte
/**
 * Show a poll.
 * It is possible to use this function in combination with the template
 * template_display_poll_above from Display.template.php, the only part missing
 * is the definition of the poll moderation button array (see Display.controller.php
 * for details).
 *
 * @param int|null $topicID = null
 * @param string $output_method = 'echo'
 */
function ssi_showPoll($topicID = null, $output_method = 'echo')
{
    global $txt, $user_info, $context, $scripturl;
    global $board;
    static $last_board = null;
    require_once SUBSDIR . '/Poll.subs.php';
    require_once SUBSDIR . '/Topic.subs.php';
    if ($topicID === null && isset($_REQUEST['ssi_topic'])) {
        $topicID = (int) $_REQUEST['ssi_topic'];
    } else {
        $topicID = (int) $topicID;
    }
    if (empty($topicID)) {
        return array();
    }
    // Get the topic starter information.
    $topicinfo = getTopicInfo($topicID, 'starter');
    $boards_can_poll = boardsAllowedTo('poll_view');
    // If:
    //  - is not allowed to see poll in any board,
    //  - or:
    //     - is not allowed in the specific board, and
    //     - is not an admin
    // fail
    if (empty($boards_can_poll) || !in_array($topicinfo['id_board'], $boards_can_poll) && !in_array(0, $boards_can_poll)) {
        return array();
    }
    $context['user']['started'] = $user_info['id'] == $topicinfo['id_member'] && !$user_info['is_guest'];
    $poll_id = associatedPoll($topicID);
    loadPollContext($poll_id);
    if (empty($context['poll'])) {
        return array();
    }
    // For "compatibility" sake
    // @deprecated since 1.0
    $context['poll']['allow_vote'] = $context['allow_vote'];
    $context['poll']['allow_view_results'] = $context['allow_poll_view'];
    $context['poll']['topic'] = $topicID;
    if ($output_method != 'echo') {
        return $context['poll'];
    }
    echo '
		<div class="content" id="poll_options">
			<h4 id="pollquestion">
				', $context['poll']['question'], '
			</h4>';
    if ($context['poll']['allow_vote']) {
        echo '
			<form action="', $scripturl, '?action=poll;sa=vote;topic=', $context['current_topic'], '.', $context['start'], ';poll=', $context['poll']['id'], '" method="post" accept-charset="UTF-8">';
        // Show a warning if they are allowed more than one option.
        if ($context['poll']['allowed_warning']) {
            echo '
				<p>', $context['poll']['allowed_warning'], '</p>';
        }
        echo '
				<ul class="options">';
        // Show each option with its button - a radio likely.
        foreach ($context['poll']['options'] as $option) {
            echo '
					<li>', $option['vote_button'], ' <label for="', $option['id'], '">', $option['option'], '</label></li>';
        }
        echo '
				</ul>
				<div class="submitbutton">
					<input type="submit" value="', $txt['poll_vote'], '" class="button_submit" />
					<input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '" />
				</div>
			</form>';
        // Is the clock ticking?
        if (!empty($context['poll']['expire_time'])) {
            echo '
			<p><strong>', $context['poll']['is_expired'] ? $txt['poll_expired_on'] : $txt['poll_expires_on'], ':</strong> ', $context['poll']['expire_time'], '</p>';
        }
    } elseif ($context['poll']['allow_view_results']) {
        echo '
			<ul class="options">';
        // Show each option with its corresponding percentage bar.
        foreach ($context['poll']['options'] as $option) {
            echo '
				<li', $option['voted_this'] ? ' class="voted"' : '', '>', $option['option'], '
					<div class="results">';
            if ($context['allow_poll_view']) {
                echo '
						<div class="statsbar"> ', $option['bar_ndt'], '</div>
						<span class="percentage">', $option['votes'], ' (', $option['percent'], '%)</span>';
            }
            echo '
					</div>
				</li>';
        }
        echo '
			</ul>';
        if ($context['allow_poll_view']) {
            echo '
			<p><strong>', $txt['poll_total_voters'], ':</strong> ', $context['poll']['total_votes'], '</p>';
        }
        // Is the clock ticking?
        if (!empty($context['poll']['expire_time'])) {
            echo '
			<p><strong>', $context['poll']['is_expired'] ? $txt['poll_expired_on'] : $txt['poll_expires_on'], ':</strong> ', $context['poll']['expire_time'], '</p>';
        }
    } else {
        echo $txt['poll_cannot_see'];
    }
    echo '
			</div>';
}
コード例 #4
0
ファイル: Topic.subs.php プロジェクト: Ralkage/Elkarte
/**
 * If we are also moving the topic somewhere else, let's try do to it
 * Includes checks for permissions move_own/any, etc.
 *
 * @param mixed[] $boards an array containing basic info of the origin and destination boards (from splitDestinationBoard)
 * @param int $totopic id of the destination topic
 */
function splitAttemptMove($boards, $totopic)
{
    global $board, $user_info;
    $db = database();
    // If the starting and final boards are different we have to check some permissions and stuff
    if ($boards['destination']['id'] != $board) {
        $doMove = false;
        if (allowedTo('move_any')) {
            $doMove = true;
        } else {
            $new_topic = getTopicInfo($totopic);
            if ($new_topic['id_member_started'] == $user_info['id'] && allowedTo('move_own')) {
                $doMove = true;
            }
        }
        if ($doMove) {
            // Update member statistics if needed
            // @todo this should probably go into a function...
            if ($boards['destination']['count_posts'] != $boards['current']['count_posts']) {
                $request = $db->query('', '
					SELECT id_member
					FROM {db_prefix}messages
					WHERE id_topic = {int:current_topic}
						AND approved = {int:is_approved}', array('current_topic' => $totopic, 'is_approved' => 1));
                $posters = array();
                while ($row = $db->fetch_assoc($request)) {
                    if (!isset($posters[$row['id_member']])) {
                        $posters[$row['id_member']] = 0;
                    }
                    $posters[$row['id_member']]++;
                }
                $db->free_result($request);
                foreach ($posters as $id_member => $posts) {
                    // The board we're moving from counted posts, but not to.
                    if (empty($boards['current']['count_posts'])) {
                        updateMemberData($id_member, array('posts' => 'posts - ' . $posts));
                    } else {
                        updateMemberData($id_member, array('posts' => 'posts + ' . $posts));
                    }
                }
            }
            // And finally move it!
            moveTopics($totopic, $boards['destination']['id']);
        } else {
            $boards['destination'] = $boards['current'];
        }
    }
}
コード例 #5
0
 /**
  * Like action_sendtopic, but done via ajax from an API request
  * @uses Xml Template generic_xml_buttons sub template
  */
 public function action_sendtopic_api()
 {
     global $topic, $modSettings, $txt, $context, $scripturl;
     loadTemplate('Xml');
     Template_Layers::getInstance()->removeAll();
     $context['sub_template'] = 'generic_xml_buttons';
     if (empty($_POST['send'])) {
         die;
     }
     // We need at least a topic... go away if you don't have one.
     // Guests can't mark things.
     if (empty($topic)) {
         loadLanguage('Errors');
         $context['xml_data'] = array('error' => 1, 'text' => $txt['not_a_topic']);
         return;
     }
     // Is the session valid?
     if (checkSession('post', '', false)) {
         loadLanguage('Errors');
         $context['xml_data'] = array('error' => 1, 'url' => $scripturl . '?action=emailuser;sa=sendtopic;topic=' . $topic . '.0');
         return;
     }
     require_once SUBSDIR . '/Topic.subs.php';
     $row = getTopicInfo($topic, 'message');
     if (empty($row)) {
         loadLanguage('Errors');
         $context['xml_data'] = array('error' => 1, 'text' => $txt['not_a_topic']);
         return;
     }
     // Can't send topic if its unapproved and using post moderation.
     if ($modSettings['postmod_active'] && !$row['approved']) {
         loadLanguage('Errors');
         $context['xml_data'] = array('error' => 1, 'text' => $txt['not_approved_topic']);
         return;
     }
     $is_spam = spamProtection('sendtopic', false);
     if ($is_spam !== false) {
         loadLanguage('Errors');
         $context['xml_data'] = array('error' => 1, 'text' => sprintf($txt['sendtopic_WaitTime_broken'], $is_spam));
         return;
     }
     // Censor the subject....
     censorText($row['subject']);
     $result = $this->_sendTopic($row);
     if ($result !== true) {
         loadLanguage('Errors');
         $context['xml_data'] = $result;
         return;
     }
     $context['xml_data'] = array('text' => $txt['topic_sent']);
 }
コード例 #6
0
 /**
  * Mark a single topic as unread.
  * Accessed by action=markasread;sa=topic
  */
 public function action_marktopic()
 {
     global $board, $topic, $user_info;
     require_once SUBSDIR . '/Topic.subs.php';
     require_once SUBSDIR . '/Messages.subs.php';
     // Mark a topic unread.
     // First, let's figure out what the latest message is.
     $topicinfo = getTopicInfo($topic, 'all');
     $topic_msg_id = (int) $_GET['t'];
     if (!empty($topic_msg_id)) {
         // If they read the whole topic, go back to the beginning.
         if ($topic_msg_id >= $topicinfo['id_last_msg']) {
             $earlyMsg = 0;
         } elseif ($topic_msg_id <= $topicinfo['id_first_msg']) {
             $earlyMsg = 0;
         } else {
             $earlyMsg = previousMessage($topic_msg_id, $topic);
         }
     } elseif ($_REQUEST['start'] == 0) {
         $earlyMsg = 0;
     } else {
         list($earlyMsg) = messageAt((int) $_REQUEST['start'], $topic);
         $earlyMsg--;
     }
     // Blam, unread!
     markTopicsRead(array($user_info['id'], $topic, $earlyMsg, $topicinfo['unwatched']), true);
     return 'board=' . $board . '.0';
 }
コード例 #7
0
ファイル: Topic.controller.php プロジェクト: KeiroD/Elkarte
 /**
  * Format a topic to be printer friendly.
  * Must be called with a topic specified.
  * Accessed via ?action=topic;sa=printpage.
  *
  * @uses Printpage template, main sub-template.
  * @uses print_above/print_below later without the main layer.
  */
 public function action_printpage()
 {
     global $topic, $scripturl, $context, $user_info, $board_info, $modSettings;
     // Redirect to the boardindex if no valid topic id is provided.
     if (empty($topic)) {
         redirectexit();
     }
     $template_layers = Template_Layers::getInstance();
     $template_layers->removeAll();
     if (!empty($modSettings['disable_print_topic'])) {
         unset($_REQUEST['action']);
         $context['theme_loaded'] = false;
         fatal_lang_error('feature_disabled', false);
     }
     require_once SUBSDIR . '/Topic.subs.php';
     // Get the topic starter information.
     $topicinfo = getTopicInfo($topic, 'starter');
     $context['user']['started'] = $user_info['id'] == $topicinfo['id_member'] && !$user_info['is_guest'];
     // Whatever happens don't index this.
     $context['robot_no_index'] = true;
     // Redirect to the boardindex if no valid topic id is provided.
     if (empty($topicinfo)) {
         redirectexit();
     }
     // @todo this code is almost the same as the one in Display.controller.php
     if ($topicinfo['id_poll'] > 0 && !empty($modSettings['pollMode']) && allowedTo('poll_view')) {
         loadLanguage('Post');
         require_once SUBSDIR . '/Poll.subs.php';
         loadPollContext($topicinfo['id_poll']);
         $template_layers->addAfter('print_poll', 'print');
     }
     // Lets "output" all that info.
     loadTemplate('Printpage');
     $template_layers->add('print');
     $context['sub_template'] = 'print_page';
     $context['board_name'] = $board_info['name'];
     $context['category_name'] = $board_info['cat']['name'];
     $context['poster_name'] = $topicinfo['poster_name'];
     $context['post_time'] = standardTime($topicinfo['poster_time'], false);
     $context['parent_boards'] = array();
     foreach ($board_info['parent_boards'] as $parent) {
         $context['parent_boards'][] = $parent['name'];
     }
     // Split the topics up so we can print them.
     $context['posts'] = topicMessages($topic);
     $posts_id = array_keys($context['posts']);
     if (!isset($context['topic_subject'])) {
         $context['topic_subject'] = $context['posts'][min($posts_id)]['subject'];
     }
     // Fetch attachments so we can print them if asked, enabled and allowed
     if (isset($_REQUEST['images']) && !empty($modSettings['attachmentEnable']) && allowedTo('view_attachments')) {
         require_once SUBSDIR . '/Topic.subs.php';
         $context['printattach'] = messagesAttachments(array_keys($context['posts']));
         $context['viewing_attach'] = true;
     }
     // Set a canonical URL for this page.
     $context['canonical_url'] = $scripturl . '?topic=' . $topic . '.0';
     $context['view_attach_mode'] = array('text' => $scripturl . '?action=topic;sa=printpage;topic=' . $topic . '.0', 'images' => $scripturl . '?action=topic;sa=printpage;topic=' . $topic . '.0;images');
 }
コード例 #8
0
 /**
  * Send the announcement in chunks.
  *
  * splits the members to be sent a topic announcement into chunks.
  * composes notification messages in all languages needed.
  * does the actual sending of the topic announcements in chunks.
  * calculates a rough estimate of the percentage items sent.
  * Accessed by action=announce;sa=send
  * @uses announcement template announcement_send sub template
  */
 public function action_send()
 {
     global $topic, $board, $board_info, $context, $modSettings, $language, $scripturl;
     checkSession();
     $context['start'] = empty($_REQUEST['start']) ? 0 : (int) $_REQUEST['start'];
     $groups = array_merge($board_info['groups'], array(1));
     $who = array();
     // Load any supplied membergroups (from announcement_send template pause loop)
     if (isset($_POST['membergroups'])) {
         $_POST['who'] = explode(',', $_POST['membergroups']);
     }
     // Check that at least one membergroup was selected (set from announce sub template)
     if (empty($_POST['who'])) {
         fatal_lang_error('no_membergroup_selected');
     }
     // Make sure all membergroups are integers and can access the board of the announcement.
     foreach ($_POST['who'] as $id => $mg) {
         $who[$id] = in_array((int) $mg, $groups) ? (int) $mg : 0;
     }
     // Get the topic details that we are going to send
     require_once SUBSDIR . '/Topic.subs.php';
     $topic_info = getTopicInfo($topic, 'message');
     // Prepare a plain text (markdown) body for email use, does the censoring as well
     require_once SUBSDIR . '/Emailpost.subs.php';
     pbe_prepare_text($topic_info['body'], $topic_info['subject']);
     // We need this in order to be able send emails.
     require_once SUBSDIR . '/Mail.subs.php';
     require_once SUBSDIR . '/Members.subs.php';
     // Select the email addresses for this batch.
     $conditions = array('activated_status' => 1, 'member_greater' => $context['start'], 'group_list' => $who, 'order_by' => 'id_member', 'limit' => empty($modSettings['mail_queue']) ? 25 : 500);
     // Have we allowed members to opt out of announcements?
     if (!empty($modSettings['allow_disableAnnounce'])) {
         $conditions['notify_announcements'] = 1;
     }
     $data = retrieveMemberData($conditions);
     // All members have received a mail. Go to the next screen.
     if (empty($data) || $data['member_count'] === 0) {
         logAction('announce_topic', array('topic' => $topic), 'user');
         if (!empty($_REQUEST['move']) && allowedTo('move_any')) {
             redirectexit('action=movetopic;topic=' . $topic . '.0' . (empty($_REQUEST['goback']) ? '' : ';goback'));
         } elseif (!empty($_REQUEST['goback'])) {
             redirectexit('topic=' . $topic . '.new;boardseen#new', isBrowser('ie'));
         } else {
             redirectexit('board=' . $board . '.0');
         }
     }
     // Loop through all members that'll receive an announcement in this batch.
     $announcements = array();
     foreach ($data['member_info'] as $row) {
         $cur_language = empty($row['language']) || empty($modSettings['userLanguage']) ? $language : $row['language'];
         // If the language wasn't defined yet, load it and compose a notification message.
         if (!isset($announcements[$cur_language])) {
             $replacements = array('TOPICSUBJECT' => $topic_info['subject'], 'MESSAGE' => $topic_info['body'], 'TOPICLINK' => $scripturl . '?topic=' . $topic . '.0');
             $emaildata = loadEmailTemplate('new_announcement', $replacements, $cur_language);
             $announcements[$cur_language] = array('subject' => $emaildata['subject'], 'body' => $emaildata['body'], 'recipients' => array());
         }
         $announcements[$cur_language]['recipients'][$row['id']] = $row['email'];
         $context['start'] = $row['id'];
     }
     // For each language send a different mail - low priority...
     foreach ($announcements as $lang => $mail) {
         sendmail($mail['recipients'], $mail['subject'], $mail['body'], null, null, false, 5);
     }
     // Provide an overall indication of progress, this is not strictly correct
     if ($data['member_count'] < $conditions['limit']) {
         $context['percentage_done'] = 100;
     } else {
         $context['percentage_done'] = round(100 * $context['start'] / $modSettings['latestMember'], 1);
     }
     // Prepare for the template
     $context['move'] = empty($_REQUEST['move']) ? 0 : 1;
     $context['go_back'] = empty($_REQUEST['goback']) ? 0 : 1;
     $context['membergroups'] = implode(',', $who);
     $context['topic_subject'] = $topic_info['subject'];
     $context['sub_template'] = 'announcement_send';
     // Go back to the correct language for the user ;)
     if (!empty($modSettings['userLanguage'])) {
         loadLanguage('Post');
     }
 }
コード例 #9
0
 /**
  * Execute the move of a topic.
  * It is called on the submit of action_movetopic.
  * This function logs that topics have been moved in the moderation log.
  * If the member is the topic starter requires the move_own permission,
  * otherwise requires the move_any permission.
  * Upon successful completion redirects to message index.
  * Accessed via ?action=movetopic2.
  *
  * @uses subs/Post.subs.php.
  */
 public function action_movetopic2()
 {
     global $txt, $board, $topic, $scripturl, $context, $language, $user_info;
     if (empty($topic)) {
         fatal_lang_error('no_access', false);
     }
     // You can't choose to have a redirection topic and use an empty reason.
     if (isset($_POST['postRedirect']) && (!isset($_POST['reason']) || trim($_POST['reason']) == '')) {
         fatal_lang_error('movetopic_no_reason', false);
     }
     // You have to tell us were you are moving to
     if (!isset($_POST['toboard'])) {
         fatal_lang_error('movetopic_no_board', false);
     }
     // We will need this
     require_once SUBSDIR . '/Topic.subs.php';
     moveTopicConcurrence();
     // Make sure this form hasn't been submitted before.
     checkSubmitOnce('check');
     // Get the basic details on this topic
     $topic_info = getTopicInfo($topic);
     $context['is_approved'] = $topic_info['approved'];
     // Can they see it?
     if (!$context['is_approved']) {
         isAllowedTo('approve_posts');
     }
     // Can they move topics on this board?
     if (!allowedTo('move_any')) {
         if ($topic_info['id_member_started'] == $user_info['id']) {
             isAllowedTo('move_own');
         } else {
             isAllowedTo('move_any');
         }
     }
     checkSession();
     require_once SUBSDIR . '/Post.subs.php';
     require_once SUBSDIR . '/Boards.subs.php';
     // The destination board must be numeric.
     $toboard = (int) $_POST['toboard'];
     // Make sure they can see the board they are trying to move to (and get whether posts count in the target board).
     $board_info = boardInfo($toboard, $topic);
     if (empty($board_info)) {
         fatal_lang_error('no_board');
     }
     // Remember this for later.
     $_SESSION['move_to_topic'] = array('move_to' => $toboard);
     // Rename the topic...
     if (isset($_POST['reset_subject'], $_POST['custom_subject']) && $_POST['custom_subject'] != '') {
         $custom_subject = strtr(Util::htmltrim(Util::htmlspecialchars($_POST['custom_subject'])), array("\r" => '', "\n" => '', "\t" => ''));
         // Keep checking the length.
         if (Util::strlen($custom_subject) > 100) {
             $custom_subject = Util::substr($custom_subject, 0, 100);
         }
         // If it's still valid move onwards and upwards.
         if ($custom_subject != '') {
             $all_messages = isset($_POST['enforce_subject']);
             if ($all_messages) {
                 // Get a response prefix, but in the forum's default language.
                 $context['response_prefix'] = response_prefix();
                 topicSubject($topic_info, $custom_subject, $context['response_prefix'], $all_messages);
             } else {
                 topicSubject($topic_info, $custom_subject);
             }
             // Fix the subject cache.
             updateStats('subject', $topic, $custom_subject);
         }
     }
     // Create a link to this in the old board.
     // @todo Does this make sense if the topic was unapproved before? I'd just about say so.
     if (isset($_POST['postRedirect'])) {
         // Should be in the boardwide language.
         if ($user_info['language'] != $language) {
             loadLanguage('index', $language);
         }
         $reason = Util::htmlspecialchars($_POST['reason'], ENT_QUOTES);
         preparsecode($reason);
         // Add a URL onto the message.
         $reason = strtr($reason, array($txt['movetopic_auto_board'] => '[url=' . $scripturl . '?board=' . $toboard . '.0]' . $board_info['name'] . '[/url]', $txt['movetopic_auto_topic'] => '[iurl]' . $scripturl . '?topic=' . $topic . '.0[/iurl]'));
         // Auto remove this MOVED redirection topic in the future?
         $redirect_expires = !empty($_POST['redirect_expires']) ? (int) $_POST['redirect_expires'] : 0;
         // Redirect to the MOVED topic from topic list?
         $redirect_topic = isset($_POST['redirect_topic']) ? $topic : 0;
         // And remember the last expiry period too.
         $_SESSION['move_to_topic']['redirect_topic'] = $redirect_topic;
         $_SESSION['move_to_topic']['redirect_expires'] = $redirect_expires;
         $msgOptions = array('subject' => $txt['moved'] . ': ' . $board_info['subject'], 'body' => $reason, 'icon' => 'moved', 'smileys_enabled' => 1);
         $topicOptions = array('board' => $board, 'lock_mode' => 1, 'mark_as_read' => true, 'redirect_expires' => empty($redirect_expires) ? 0 : $redirect_expires * 60 + time(), 'redirect_topic' => $redirect_topic);
         $posterOptions = array('id' => $user_info['id'], 'update_post_count' => empty($board_info['count_posts']));
         createPost($msgOptions, $topicOptions, $posterOptions);
     }
     $board_from = boardInfo($board);
     if ($board_from['count_posts'] != $board_info['count_posts']) {
         $posters = postersCount($topic);
         foreach ($posters as $id_member => $posts) {
             // The board we're moving from counted posts, but not to.
             if (empty($board_from['count_posts'])) {
                 updateMemberData($id_member, array('posts' => 'posts - ' . $posts));
             } else {
                 updateMemberData($id_member, array('posts' => 'posts + ' . $posts));
             }
         }
     }
     // Do the move (includes statistics update needed for the redirect topic).
     moveTopics($topic, $toboard);
     // Log that they moved this topic.
     if (!allowedTo('move_own') || $topic_info['id_member_started'] != $user_info['id']) {
         logAction('move', array('topic' => $topic, 'board_from' => $board, 'board_to' => $toboard));
     }
     // Notify people that this topic has been moved?
     require_once SUBSDIR . '/Notification.subs.php';
     sendNotifications($topic, 'move');
     // Why not go back to the original board in case they want to keep moving?
     if (!isset($_REQUEST['goback'])) {
         redirectexit('board=' . $board . '.0');
     } else {
         redirectexit('topic=' . $topic . '.0');
     }
 }
コード例 #10
0
ファイル: Post.controller.php プロジェクト: Ralkage/Elkarte
    /**
     * Posts or saves the message composed with Post().
     *
     * requires various permissions depending on the action.
     * handles attachment, post, and calendar saving.
     * sends off notifications, and allows for announcements and moderation.
     * accessed from ?action=post2.
     */
    public function action_post2()
    {
        global $board, $topic, $txt, $modSettings, $context, $user_settings;
        global $user_info, $board_info, $options, $ignore_temp;
        // Sneaking off, are we?
        if (empty($_POST) && empty($topic)) {
            if (empty($_SERVER['CONTENT_LENGTH'])) {
                redirectexit('action=post;board=' . $board . '.0');
            } else {
                fatal_lang_error('post_upload_error', false);
            }
        } elseif (empty($_POST) && !empty($topic)) {
            redirectexit('action=post;topic=' . $topic . '.0');
        }
        // No need!
        $context['robot_no_index'] = true;
        // We are now in post2 action
        $context['current_action'] = 'post2';
        require_once SOURCEDIR . '/AttachmentErrorContext.class.php';
        // No errors as yet.
        $post_errors = Error_Context::context('post', 1);
        $attach_errors = Attachment_Error_Context::context();
        // If the session has timed out, let the user re-submit their form.
        if (checkSession('post', '', false) != '') {
            $post_errors->addError('session_timeout');
            // Disable the preview so that any potentially malicious code is not executed
            $_REQUEST['preview'] = false;
            return $this->action_post();
        }
        // Wrong verification code?
        if (!$user_info['is_admin'] && !$user_info['is_mod'] && !empty($modSettings['posts_require_captcha']) && ($user_info['posts'] < $modSettings['posts_require_captcha'] || $user_info['is_guest'] && $modSettings['posts_require_captcha'] == -1)) {
            require_once SUBSDIR . '/VerificationControls.class.php';
            $verificationOptions = array('id' => 'post');
            $context['require_verification'] = create_control_verification($verificationOptions, true);
            if (is_array($context['require_verification'])) {
                foreach ($context['require_verification'] as $verification_error) {
                    $post_errors->addError($verification_error);
                }
            }
        }
        require_once SUBSDIR . '/Boards.subs.php';
        require_once SUBSDIR . '/Post.subs.php';
        loadLanguage('Post');
        // Drafts enabled and needed?
        if (!empty($modSettings['drafts_enabled']) && (isset($_POST['save_draft']) || isset($_POST['id_draft']))) {
            require_once SUBSDIR . '/Drafts.subs.php';
        }
        // First check to see if they are trying to delete any current attachments.
        if (isset($_POST['attach_del'])) {
            $keep_temp = array();
            $keep_ids = array();
            foreach ($_POST['attach_del'] as $dummy) {
                if (strpos($dummy, 'post_tmp_' . $user_info['id']) !== false) {
                    $keep_temp[] = $dummy;
                } else {
                    $keep_ids[] = (int) $dummy;
                }
            }
            if (isset($_SESSION['temp_attachments'])) {
                foreach ($_SESSION['temp_attachments'] as $attachID => $attachment) {
                    if (isset($_SESSION['temp_attachments']['post']['files'], $attachment['name']) && in_array($attachment['name'], $_SESSION['temp_attachments']['post']['files']) || in_array($attachID, $keep_temp) || strpos($attachID, 'post_tmp_' . $user_info['id']) === false) {
                        continue;
                    }
                    unset($_SESSION['temp_attachments'][$attachID]);
                    @unlink($attachment['tmp_name']);
                }
            }
            if (!empty($_REQUEST['msg'])) {
                require_once SUBSDIR . '/ManageAttachments.subs.php';
                $attachmentQuery = array('attachment_type' => 0, 'id_msg' => (int) $_REQUEST['msg'], 'not_id_attach' => $keep_ids);
                removeAttachments($attachmentQuery);
            }
        }
        // Then try to upload any attachments.
        $context['attachments']['can']['post'] = !empty($modSettings['attachmentEnable']) && $modSettings['attachmentEnable'] == 1 && (allowedTo('post_attachment') || $modSettings['postmod_active'] && allowedTo('post_unapproved_attachments'));
        if ($context['attachments']['can']['post'] && empty($_POST['from_qr'])) {
            require_once SUBSDIR . '/Attachments.subs.php';
            if (isset($_REQUEST['msg'])) {
                processAttachments((int) $_REQUEST['msg']);
            } else {
                processAttachments();
            }
        }
        // Previewing? Go back to start.
        if (isset($_REQUEST['preview'])) {
            return $this->action_post();
        }
        // Prevent double submission of this form.
        checkSubmitOnce('check');
        // If this isn't a new topic load the topic info that we need.
        if (!empty($topic)) {
            require_once SUBSDIR . '/Topic.subs.php';
            $topic_info = getTopicInfo($topic);
            // Though the topic should be there, it might have vanished.
            if (empty($topic_info)) {
                fatal_lang_error('topic_doesnt_exist');
            }
            // Did this topic suddenly move? Just checking...
            if ($topic_info['id_board'] != $board) {
                fatal_lang_error('not_a_topic');
            }
        }
        // Replying to a topic?
        if (!empty($topic) && !isset($_REQUEST['msg'])) {
            // Don't allow a post if it's locked.
            if ($topic_info['locked'] != 0 && !allowedTo('moderate_board')) {
                fatal_lang_error('topic_locked', false);
            }
            // Sorry, multiple polls aren't allowed... yet.  You should stop giving me ideas :P.
            if (isset($_REQUEST['poll']) && $topic_info['id_poll'] > 0) {
                unset($_REQUEST['poll']);
            }
            // Do the permissions and approval stuff...
            $becomesApproved = true;
            if ($topic_info['id_member_started'] != $user_info['id']) {
                if ($modSettings['postmod_active'] && allowedTo('post_unapproved_replies_any') && !allowedTo('post_reply_any')) {
                    $becomesApproved = false;
                } else {
                    isAllowedTo('post_reply_any');
                }
            } elseif (!allowedTo('post_reply_any')) {
                if ($modSettings['postmod_active']) {
                    if (allowedTo('post_unapproved_replies_own') && !allowedTo('post_reply_own')) {
                        $becomesApproved = false;
                    } elseif ($user_info['is_guest'] && allowedTo('post_unapproved_replies_any')) {
                        $becomesApproved = false;
                    } else {
                        isAllowedTo('post_reply_own');
                    }
                }
            }
            if (isset($_POST['lock'])) {
                // Nothing is changed to the lock.
                if (empty($topic_info['locked']) && empty($_POST['lock']) || !empty($_POST['lock']) && !empty($topic_info['locked'])) {
                    unset($_POST['lock']);
                } elseif (!allowedTo(array('lock_any', 'lock_own')) || !allowedTo('lock_any') && $user_info['id'] != $topic_info['id_member_started']) {
                    unset($_POST['lock']);
                } elseif (!allowedTo('lock_any')) {
                    // You cannot override a moderator lock.
                    if ($topic_info['locked'] == 1) {
                        unset($_POST['lock']);
                    } else {
                        $_POST['lock'] = empty($_POST['lock']) ? 0 : 2;
                    }
                } else {
                    $_POST['lock'] = empty($_POST['lock']) ? 0 : 1;
                }
            }
            // So you wanna (un)sticky this...let's see.
            if (isset($_POST['sticky']) && (empty($modSettings['enableStickyTopics']) || $_POST['sticky'] == $topic_info['is_sticky'] || !allowedTo('make_sticky'))) {
                unset($_POST['sticky']);
            }
            // If drafts are enabled, then pass this off
            if (!empty($modSettings['drafts_enabled']) && isset($_POST['save_draft'])) {
                saveDraft();
                return $this->action_post();
            }
            // If the number of replies has changed, if the setting is enabled, go back to action_post() - which handles the error.
            if (empty($options['no_new_reply_warning']) && isset($_POST['last_msg']) && $topic_info['id_last_msg'] > $_POST['last_msg']) {
                addInlineJavascript('
					$(document).ready(function () {
						$("html,body").scrollTop($(\'.category_header:visible:first\').offset().top);
					});');
                return $this->action_post();
            }
            $posterIsGuest = $user_info['is_guest'];
        } elseif (empty($topic)) {
            // Now don't be silly, new topics will get their own id_msg soon enough.
            unset($_REQUEST['msg'], $_POST['msg'], $_GET['msg']);
            // Do like, the permissions, for safety and stuff...
            $becomesApproved = true;
            if ($modSettings['postmod_active'] && !allowedTo('post_new') && allowedTo('post_unapproved_topics')) {
                $becomesApproved = false;
            } else {
                isAllowedTo('post_new');
            }
            if (isset($_POST['lock'])) {
                // New topics are by default not locked.
                if (empty($_POST['lock'])) {
                    unset($_POST['lock']);
                } elseif (!allowedTo(array('lock_any', 'lock_own'))) {
                    unset($_POST['lock']);
                } else {
                    $_POST['lock'] = allowedTo('lock_any') ? 1 : 2;
                }
            }
            if (isset($_POST['sticky']) && (empty($modSettings['enableStickyTopics']) || empty($_POST['sticky']) || !allowedTo('make_sticky'))) {
                unset($_POST['sticky']);
            }
            // Saving your new topic as a draft first?
            if (!empty($modSettings['drafts_enabled']) && isset($_POST['save_draft'])) {
                saveDraft();
                return $this->action_post();
            }
            $posterIsGuest = $user_info['is_guest'];
        } elseif (isset($_REQUEST['msg']) && !empty($topic)) {
            $_REQUEST['msg'] = (int) $_REQUEST['msg'];
            require_once SUBSDIR . '/Messages.subs.php';
            $msgInfo = basicMessageInfo($_REQUEST['msg'], true);
            if (empty($msgInfo)) {
                fatal_lang_error('cant_find_messages', false);
            }
            if (!empty($topic_info['locked']) && !allowedTo('moderate_board')) {
                fatal_lang_error('topic_locked', false);
            }
            if (isset($_POST['lock'])) {
                // Nothing changes to the lock status.
                if (empty($_POST['lock']) && empty($topic_info['locked']) || !empty($_POST['lock']) && !empty($topic_info['locked'])) {
                    unset($_POST['lock']);
                } elseif (!allowedTo(array('lock_any', 'lock_own')) || !allowedTo('lock_any') && $user_info['id'] != $topic_info['id_member_started']) {
                    unset($_POST['lock']);
                } elseif (!allowedTo('lock_any')) {
                    // You're not allowed to break a moderator's lock.
                    if ($topic_info['locked'] == 1) {
                        unset($_POST['lock']);
                    } else {
                        $_POST['lock'] = empty($_POST['lock']) ? 0 : 2;
                    }
                } else {
                    $_POST['lock'] = empty($_POST['lock']) ? 0 : 1;
                }
            }
            // Change the sticky status of this topic?
            if (isset($_POST['sticky']) && (!allowedTo('make_sticky') || $_POST['sticky'] == $topic_info['is_sticky'])) {
                unset($_POST['sticky']);
            }
            if ($msgInfo['id_member'] == $user_info['id'] && !allowedTo('modify_any')) {
                if ((!$modSettings['postmod_active'] || $msgInfo['approved']) && !empty($modSettings['edit_disable_time']) && $msgInfo['poster_time'] + ($modSettings['edit_disable_time'] + 5) * 60 < time()) {
                    fatal_lang_error('modify_post_time_passed', false);
                } elseif ($topic_info['id_member_started'] == $user_info['id'] && !allowedTo('modify_own')) {
                    isAllowedTo('modify_replies');
                } else {
                    isAllowedTo('modify_own');
                }
            } elseif ($topic_info['id_member_started'] == $user_info['id'] && !allowedTo('modify_any')) {
                isAllowedTo('modify_replies');
                // If you're modifying a reply, I say it better be logged...
                $moderationAction = true;
            } else {
                isAllowedTo('modify_any');
                // Log it, assuming you're not modifying your own post.
                if ($msgInfo['id_member'] != $user_info['id']) {
                    $moderationAction = true;
                }
            }
            // If drafts are enabled, then lets send this off to save
            if (!empty($modSettings['drafts_enabled']) && isset($_POST['save_draft'])) {
                saveDraft();
                return $this->action_post();
            }
            $posterIsGuest = empty($msgInfo['id_member']);
            // Can they approve it?
            $can_approve = allowedTo('approve_posts');
            $becomesApproved = $modSettings['postmod_active'] ? $can_approve && !$msgInfo['approved'] ? !empty($_REQUEST['approve']) ? 1 : 0 : $msgInfo['approved'] : 1;
            $approve_has_changed = $msgInfo['approved'] != $becomesApproved;
            if (!allowedTo('moderate_forum') || !$posterIsGuest) {
                $_POST['guestname'] = $msgInfo['poster_name'];
                $_POST['email'] = $msgInfo['poster_email'];
            }
        }
        // In case we want to override
        if (allowedTo('approve_posts')) {
            $becomesApproved = !isset($_REQUEST['approve']) || !empty($_REQUEST['approve']) ? 1 : 0;
            $approve_has_changed = isset($msgInfo['approved']) ? $msgInfo['approved'] != $becomesApproved : false;
        }
        // If the poster is a guest evaluate the legality of name and email.
        if ($posterIsGuest) {
            $_POST['guestname'] = !isset($_POST['guestname']) ? '' : Util::htmlspecialchars(trim($_POST['guestname']));
            $_POST['email'] = !isset($_POST['email']) ? '' : Util::htmlspecialchars(trim($_POST['email']));
            if ($_POST['guestname'] == '' || $_POST['guestname'] == '_') {
                $post_errors->addError('no_name');
            }
            if (Util::strlen($_POST['guestname']) > 25) {
                $post_errors->addError('long_name');
            }
            if (empty($modSettings['guest_post_no_email'])) {
                // Only check if they changed it!
                if (!isset($msgInfo) || $msgInfo['poster_email'] != $_POST['email']) {
                    require_once SUBSDIR . '/DataValidator.class.php';
                    if (!allowedTo('moderate_forum') && !Data_Validator::is_valid($_POST, array('email' => 'valid_email|required'), array('email' => 'trim'))) {
                        empty($_POST['email']) ? $post_errors->addError('no_email') : $post_errors->addError('bad_email');
                    }
                }
                // Now make sure this email address is not banned from posting.
                isBannedEmail($_POST['email'], 'cannot_post', sprintf($txt['you_are_post_banned'], $txt['guest_title']));
            }
            // In case they are making multiple posts this visit, help them along by storing their name.
            if (!$post_errors->hasErrors()) {
                $_SESSION['guest_name'] = $_POST['guestname'];
                $_SESSION['guest_email'] = $_POST['email'];
            }
        }
        // Check the subject and message.
        if (!isset($_POST['subject']) || Util::htmltrim(Util::htmlspecialchars($_POST['subject'])) === '') {
            $post_errors->addError('no_subject');
        }
        if (!isset($_POST['message']) || Util::htmltrim(Util::htmlspecialchars($_POST['message'], ENT_QUOTES)) === '') {
            $post_errors->addError('no_message');
        } elseif (!empty($modSettings['max_messageLength']) && Util::strlen($_POST['message']) > $modSettings['max_messageLength']) {
            $post_errors->addError(array('long_message', array($modSettings['max_messageLength'])));
        } else {
            // Prepare the message a bit for some additional testing.
            $_POST['message'] = Util::htmlspecialchars($_POST['message'], ENT_QUOTES);
            // Preparse code. (Zef)
            if ($user_info['is_guest']) {
                $user_info['name'] = $_POST['guestname'];
            }
            preparsecode($_POST['message']);
            // Let's see if there's still some content left without the tags.
            if (Util::htmltrim(strip_tags(parse_bbc($_POST['message'], false), '<img>')) === '' && (!allowedTo('admin_forum') || strpos($_POST['message'], '[html]') === false)) {
                $post_errors->addError('no_message');
            }
        }
        if (isset($_POST['calendar']) && !isset($_REQUEST['deleteevent']) && Util::htmltrim($_POST['evtitle']) === '') {
            $post_errors->addError('no_event');
        }
        // Validate the poll...
        if (isset($_REQUEST['poll']) && !empty($modSettings['pollMode'])) {
            if (!empty($topic) && !isset($_REQUEST['msg'])) {
                fatal_lang_error('no_access', false);
            }
            // This is a new topic... so it's a new poll.
            if (empty($topic)) {
                isAllowedTo('poll_post');
            } elseif ($user_info['id'] == $topic_info['id_member_started'] && !allowedTo('poll_add_any')) {
                isAllowedTo('poll_add_own');
            } else {
                isAllowedTo('poll_add_any');
            }
            if (!isset($_POST['question']) || trim($_POST['question']) == '') {
                $post_errors->addError('no_question');
            }
            $_POST['options'] = empty($_POST['options']) ? array() : htmltrim__recursive($_POST['options']);
            // Get rid of empty ones.
            foreach ($_POST['options'] as $k => $option) {
                if ($option == '') {
                    unset($_POST['options'][$k], $_POST['options'][$k]);
                }
            }
            // What are you going to vote between with one choice?!?
            if (count($_POST['options']) < 2) {
                $post_errors->addError('poll_few');
            } elseif (count($_POST['options']) > 256) {
                $post_errors->addError('poll_many');
            }
        }
        if ($posterIsGuest) {
            // If user is a guest, make sure the chosen name isn't taken.
            require_once SUBSDIR . '/Members.subs.php';
            if (isReservedName($_POST['guestname'], 0, true, false) && (!isset($msgInfo['poster_name']) || $_POST['guestname'] != $msgInfo['poster_name'])) {
                $post_errors->addError('bad_name');
            }
        } elseif (!isset($_REQUEST['msg'])) {
            $_POST['guestname'] = $user_info['username'];
            $_POST['email'] = $user_info['email'];
        }
        // Posting somewhere else? Are we sure you can?
        if (!empty($_REQUEST['post_in_board'])) {
            $new_board = (int) $_REQUEST['post_in_board'];
            if (!allowedTo('post_new', $new_board)) {
                $post_in_board = boardInfo($new_board);
                if (!empty($post_in_board)) {
                    $post_errors->addError(array('post_new_board', array($post_in_board['name'])));
                } else {
                    $post_errors->addError('post_new');
                }
            }
        }
        // Any mistakes?
        if ($post_errors->hasErrors() || $attach_errors->hasErrors()) {
            addInlineJavascript('
				$(document).ready(function () {
					$("html,body").scrollTop($(\'.category_header:visible:first\').offset().top);
				});');
            return $this->action_post();
        }
        // Make sure the user isn't spamming the board.
        if (!isset($_REQUEST['msg'])) {
            spamProtection('post');
        }
        // At about this point, we're posting and that's that.
        ignore_user_abort(true);
        @set_time_limit(300);
        // Add special html entities to the subject, name, and email.
        $_POST['subject'] = strtr(Util::htmlspecialchars($_POST['subject']), array("\r" => '', "\n" => '', "\t" => ''));
        $_POST['guestname'] = htmlspecialchars($_POST['guestname'], ENT_COMPAT, 'UTF-8');
        $_POST['email'] = htmlspecialchars($_POST['email'], ENT_COMPAT, 'UTF-8');
        // At this point, we want to make sure the subject isn't too long.
        if (Util::strlen($_POST['subject']) > 100) {
            $_POST['subject'] = Util::substr($_POST['subject'], 0, 100);
        }
        if (!empty($modSettings['mentions_enabled']) && !empty($_REQUEST['uid'])) {
            $query_params = array();
            $query_params['member_ids'] = array_unique(array_map('intval', $_REQUEST['uid']));
            require_once SUBSDIR . '/Members.subs.php';
            $mentioned_members = membersBy('member_ids', $query_params, true);
            $replacements = 0;
            $actually_mentioned = array();
            foreach ($mentioned_members as $member) {
                $_POST['message'] = str_replace('@' . $member['real_name'], '[member=' . $member['id_member'] . ']' . $member['real_name'] . '[/member]', $_POST['message'], $replacements);
                if ($replacements > 0) {
                    $actually_mentioned[] = $member['id_member'];
                }
            }
        }
        // Make the poll...
        if (isset($_REQUEST['poll'])) {
            // Make sure that the user has not entered a ridiculous number of options..
            if (empty($_POST['poll_max_votes']) || $_POST['poll_max_votes'] <= 0) {
                $_POST['poll_max_votes'] = 1;
            } elseif ($_POST['poll_max_votes'] > count($_POST['options'])) {
                $_POST['poll_max_votes'] = count($_POST['options']);
            } else {
                $_POST['poll_max_votes'] = (int) $_POST['poll_max_votes'];
            }
            $_POST['poll_expire'] = (int) $_POST['poll_expire'];
            $_POST['poll_expire'] = $_POST['poll_expire'] > 9999 ? 9999 : ($_POST['poll_expire'] < 0 ? 0 : $_POST['poll_expire']);
            // Just set it to zero if it's not there..
            if (!isset($_POST['poll_hide'])) {
                $_POST['poll_hide'] = 0;
            } else {
                $_POST['poll_hide'] = (int) $_POST['poll_hide'];
            }
            $_POST['poll_change_vote'] = isset($_POST['poll_change_vote']) ? 1 : 0;
            $_POST['poll_guest_vote'] = isset($_POST['poll_guest_vote']) ? 1 : 0;
            // Make sure guests are actually allowed to vote generally.
            if ($_POST['poll_guest_vote']) {
                require_once SUBSDIR . '/Members.subs.php';
                $allowedVoteGroups = groupsAllowedTo('poll_vote', $board);
                if (!in_array(-1, $allowedVoteGroups['allowed'])) {
                    $_POST['poll_guest_vote'] = 0;
                }
            }
            // If the user tries to set the poll too far in advance, don't let them.
            if (!empty($_POST['poll_expire']) && $_POST['poll_expire'] < 1) {
                fatal_lang_error('poll_range_error', false);
            } elseif (empty($_POST['poll_expire']) && $_POST['poll_hide'] == 2) {
                $_POST['poll_hide'] = 1;
            }
            // Clean up the question and answers.
            $_POST['question'] = htmlspecialchars($_POST['question'], ENT_COMPAT, 'UTF-8');
            $_POST['question'] = Util::substr($_POST['question'], 0, 255);
            $_POST['question'] = preg_replace('~&amp;#(\\d{4,5}|[2-9]\\d{2,4}|1[2-9]\\d);~', '&#$1;', $_POST['question']);
            $_POST['options'] = htmlspecialchars__recursive($_POST['options']);
            // Finally, make the poll.
            require_once SUBSDIR . '/Poll.subs.php';
            $id_poll = createPoll($_POST['question'], $user_info['id'], $_POST['guestname'], $_POST['poll_max_votes'], $_POST['poll_hide'], $_POST['poll_expire'], $_POST['poll_change_vote'], $_POST['poll_guest_vote'], $_POST['options']);
        } else {
            $id_poll = 0;
        }
        // ...or attach a new file...
        if (empty($ignore_temp) && $context['attachments']['can']['post'] && !empty($_SESSION['temp_attachments']) && empty($_POST['from_qr'])) {
            $attachIDs = array();
            foreach ($_SESSION['temp_attachments'] as $attachID => $attachment) {
                if ($attachID != 'initial_error' && strpos($attachID, 'post_tmp_' . $user_info['id']) === false) {
                    continue;
                }
                // If there was an initial error just show that message.
                if ($attachID == 'initial_error') {
                    unset($_SESSION['temp_attachments']);
                    break;
                }
                // No errors, then try to create the attachment
                if (empty($attachment['errors'])) {
                    // Load the attachmentOptions array with the data needed to create an attachment
                    $attachmentOptions = array('post' => isset($_REQUEST['msg']) ? $_REQUEST['msg'] : 0, 'poster' => $user_info['id'], 'name' => $attachment['name'], 'tmp_name' => $attachment['tmp_name'], 'size' => isset($attachment['size']) ? $attachment['size'] : 0, 'mime_type' => isset($attachment['type']) ? $attachment['type'] : '', 'id_folder' => isset($attachment['id_folder']) ? $attachment['id_folder'] : 0, 'approved' => !$modSettings['postmod_active'] || allowedTo('post_attachment'), 'errors' => array());
                    if (createAttachment($attachmentOptions)) {
                        $attachIDs[] = $attachmentOptions['id'];
                        if (!empty($attachmentOptions['thumb'])) {
                            $attachIDs[] = $attachmentOptions['thumb'];
                        }
                    }
                } else {
                    @unlink($attachment['tmp_name']);
                }
            }
            unset($_SESSION['temp_attachments']);
        }
        // Creating a new topic?
        $newTopic = empty($_REQUEST['msg']) && empty($topic);
        $_POST['icon'] = !empty($attachIDs) && $_POST['icon'] == 'xx' ? 'clip' : $_POST['icon'];
        // Collect all parameters for the creation or modification of a post.
        $msgOptions = array('id' => empty($_REQUEST['msg']) ? 0 : (int) $_REQUEST['msg'], 'subject' => $_POST['subject'], 'body' => $_POST['message'], 'icon' => preg_replace('~[\\./\\\\*:"\'<>]~', '', $_POST['icon']), 'smileys_enabled' => !isset($_POST['ns']), 'attachments' => empty($attachIDs) ? array() : $attachIDs, 'approved' => $becomesApproved);
        $topicOptions = array('id' => empty($topic) ? 0 : $topic, 'board' => $board, 'poll' => isset($_REQUEST['poll']) ? $id_poll : null, 'lock_mode' => isset($_POST['lock']) ? (int) $_POST['lock'] : null, 'sticky_mode' => isset($_POST['sticky']) && !empty($modSettings['enableStickyTopics']) ? (int) $_POST['sticky'] : null, 'mark_as_read' => true, 'is_approved' => !$modSettings['postmod_active'] || empty($topic) || !empty($board_info['cur_topic_approved']));
        $posterOptions = array('id' => $user_info['id'], 'name' => $_POST['guestname'], 'email' => $_POST['email'], 'update_post_count' => !$user_info['is_guest'] && !isset($_REQUEST['msg']) && $board_info['posts_count']);
        // This is an already existing message. Edit it.
        if (!empty($_REQUEST['msg'])) {
            // Have admins allowed people to hide their screwups?
            if (time() - $msgInfo['poster_time'] > $modSettings['edit_wait_time'] || $user_info['id'] != $msgInfo['id_member']) {
                $msgOptions['modify_time'] = time();
                $msgOptions['modify_name'] = $user_info['name'];
            }
            // This will save some time...
            if (empty($approve_has_changed)) {
                unset($msgOptions['approved']);
            }
            modifyPost($msgOptions, $topicOptions, $posterOptions);
        } else {
            if (!empty($modSettings['enableFollowup']) && !empty($_REQUEST['followup'])) {
                $original_post = (int) $_REQUEST['followup'];
            }
            // We also have to fake the board:
            // if it's valid and it's not the current, let's forget about the "current" and load the new one
            if (!empty($new_board) && $board !== $new_board) {
                $board = $new_board;
                loadBoard();
                // Some details changed
                $topicOptions['board'] = $board;
                $topicOptions['is_approved'] = !$modSettings['postmod_active'] || empty($topic) || !empty($board_info['cur_topic_approved']);
                $posterOptions['update_post_count'] = !$user_info['is_guest'] && !isset($_REQUEST['msg']) && $board_info['posts_count'];
            }
            createPost($msgOptions, $topicOptions, $posterOptions);
            if (isset($topicOptions['id'])) {
                $topic = $topicOptions['id'];
            }
            if (!empty($modSettings['enableFollowup'])) {
                require_once SUBSDIR . '/FollowUps.subs.php';
                require_once SUBSDIR . '/Messages.subs.php';
                // Time to update the original message with a pointer to the new one
                if (!empty($original_post) && canAccessMessage($original_post)) {
                    linkMessages($original_post, $topic);
                }
            }
        }
        // If we had a draft for this, its time to remove it since it was just posted
        if (!empty($modSettings['drafts_enabled']) && !empty($_POST['id_draft'])) {
            deleteDrafts($_POST['id_draft'], $user_info['id']);
        }
        // Editing or posting an event?
        if (isset($_POST['calendar']) && (!isset($_REQUEST['eventid']) || $_REQUEST['eventid'] == -1)) {
            require_once SUBSDIR . '/Calendar.subs.php';
            // Make sure they can link an event to this post.
            canLinkEvent();
            // Insert the event.
            $eventOptions = array('id_board' => $board, 'id_topic' => $topic, 'title' => $_POST['evtitle'], 'member' => $user_info['id'], 'start_date' => sprintf('%04d-%02d-%02d', $_POST['year'], $_POST['month'], $_POST['day']), 'span' => isset($_POST['span']) && $_POST['span'] > 0 ? min((int) $modSettings['cal_maxspan'], (int) $_POST['span'] - 1) : 0);
            insertEvent($eventOptions);
        } elseif (isset($_POST['calendar'])) {
            $_REQUEST['eventid'] = (int) $_REQUEST['eventid'];
            // Validate the post...
            require_once SUBSDIR . '/Calendar.subs.php';
            validateEventPost();
            // If you're not allowed to edit any events, you have to be the poster.
            if (!allowedTo('calendar_edit_any')) {
                $event_poster = getEventPoster($_REQUEST['eventid']);
                // Silly hacker, Trix are for kids. ...probably trademarked somewhere, this is FAIR USE! (parody...)
                isAllowedTo('calendar_edit_' . ($event_poster == $user_info['id'] ? 'own' : 'any'));
            }
            // Delete it?
            if (isset($_REQUEST['deleteevent'])) {
                removeEvent($_REQUEST['eventid']);
            } else {
                $span = !empty($modSettings['cal_allowspan']) && !empty($_REQUEST['span']) ? min((int) $modSettings['cal_maxspan'], (int) $_REQUEST['span'] - 1) : 0;
                $start_time = mktime(0, 0, 0, (int) $_REQUEST['month'], (int) $_REQUEST['day'], (int) $_REQUEST['year']);
                $eventOptions = array('start_date' => strftime('%Y-%m-%d', $start_time), 'end_date' => strftime('%Y-%m-%d', $start_time + $span * 86400), 'title' => $_REQUEST['evtitle']);
                modifyEvent($_REQUEST['eventid'], $eventOptions);
            }
        }
        // Marking boards as read.
        // (You just posted and they will be unread.)
        if (!$user_info['is_guest']) {
            $board_list = !empty($board_info['parent_boards']) ? array_keys($board_info['parent_boards']) : array();
            // Returning to the topic?
            if (!empty($_REQUEST['goback'])) {
                $board_list[] = $board;
            }
            if (!empty($board_list)) {
                markBoardsRead($board_list, false, false);
            }
        }
        // Turn notification on or off.
        if (!empty($_POST['notify']) && allowedTo('mark_any_notify')) {
            setTopicNotification($user_info['id'], $topic, true);
        } elseif (!$newTopic) {
            setTopicNotification($user_info['id'], $topic, false);
        }
        // Log an act of moderation - modifying.
        if (!empty($moderationAction)) {
            logAction('modify', array('topic' => $topic, 'message' => (int) $_REQUEST['msg'], 'member' => $msgInfo['id_member'], 'board' => $board));
        }
        if (isset($_POST['lock']) && $_POST['lock'] != 2) {
            logAction(empty($_POST['lock']) ? 'unlock' : 'lock', array('topic' => $topicOptions['id'], 'board' => $topicOptions['board']));
        }
        if (isset($_POST['sticky']) && !empty($modSettings['enableStickyTopics'])) {
            logAction(empty($_POST['sticky']) ? 'unsticky' : 'sticky', array('topic' => $topicOptions['id'], 'board' => $topicOptions['board']));
        }
        // Notify any members who have notification turned on for this topic/board - only do this if it's going to be approved(!)
        if ($becomesApproved) {
            require_once SUBSDIR . '/Notification.subs.php';
            if ($newTopic) {
                $notifyData = array('body' => $_POST['message'], 'subject' => $_POST['subject'], 'name' => $user_info['name'], 'poster' => $user_info['id'], 'msg' => $msgOptions['id'], 'board' => $board, 'topic' => $topic, 'signature' => isset($user_settings['signature']) ? $user_settings['signature'] : '');
                sendBoardNotifications($notifyData);
            } elseif (empty($_REQUEST['msg'])) {
                // Only send it to everyone if the topic is approved, otherwise just to the topic starter if they want it.
                if ($topic_info['approved']) {
                    sendNotifications($topic, 'reply');
                } else {
                    sendNotifications($topic, 'reply', array(), $topic_info['id_member_started']);
                }
            }
        }
        if (!empty($modSettings['mentions_enabled']) && !empty($actually_mentioned)) {
            require_once CONTROLLERDIR . '/Mentions.controller.php';
            $mentions = new Mentions_Controller();
            $mentions->setData(array('id_member' => $actually_mentioned, 'type' => 'men', 'id_msg' => $msgOptions['id'], 'status' => $becomesApproved ? 'new' : 'unapproved'));
            $mentions->action_add();
        }
        if ($board_info['num_topics'] == 0) {
            cache_put_data('board-' . $board, null, 120);
        }
        if (!empty($_POST['announce_topic'])) {
            redirectexit('action=announce;sa=selectgroup;topic=' . $topic . (!empty($_POST['move']) && allowedTo('move_any') ? ';move' : '') . (empty($_REQUEST['goback']) ? '' : ';goback'));
        }
        if (!empty($_POST['move']) && allowedTo('move_any')) {
            redirectexit('action=movetopic;topic=' . $topic . '.0' . (empty($_REQUEST['goback']) ? '' : ';goback'));
        }
        // Return to post if the mod is on.
        if (isset($_REQUEST['msg']) && !empty($_REQUEST['goback'])) {
            redirectexit('topic=' . $topic . '.msg' . $_REQUEST['msg'] . '#msg' . $_REQUEST['msg'], isBrowser('ie'));
        } elseif (!empty($_REQUEST['goback'])) {
            redirectexit('topic=' . $topic . '.new#new', isBrowser('ie'));
        } else {
            redirectexit('board=' . $board . '.0');
        }
    }
コード例 #11
0
    /**
     * Set merge options and do the actual merge of two or more topics.
     *
     * the merge options screen:
     * * shows topics to be merged and allows to set some merge options.
     * * is accessed by ?action=mergetopics;sa=options.and can also internally be called by action_quickmod().
     * * uses 'merge_extra_options' sub template of the MergeTopics template.
     *
     * the actual merge:
     * * is accessed with ?action=mergetopics;sa=execute.
     * * updates the statistics to reflect the merge.
     * * logs the action in the moderation log.
     * * sends a notification is sent to all users monitoring this topic.
     * * redirects to ?action=mergetopics;sa=done.
     *
     * @param int[] $topics = array() of topic ids
     */
    public function action_mergeExecute($topics = array())
    {
        global $user_info, $txt, $context, $scripturl, $modSettings;
        $db = database();
        // Check the session.
        checkSession('request');
        require_once SUBSDIR . '/Topic.subs.php';
        require_once SUBSDIR . '/Post.subs.php';
        // Handle URLs from action_mergeIndex.
        if (!empty($_GET['from']) && !empty($_GET['to'])) {
            $topics = array((int) $_GET['from'], (int) $_GET['to']);
        }
        // If we came from a form, the topic IDs came by post.
        if (!empty($_POST['topics']) && is_array($_POST['topics'])) {
            $topics = $_POST['topics'];
        }
        // There's nothing to merge with just one topic...
        if (empty($topics) || !is_array($topics) || count($topics) == 1) {
            fatal_lang_error('merge_need_more_topics');
        }
        // Make sure every topic is numeric, or some nasty things could be done with the DB.
        foreach ($topics as $id => $topic) {
            $topics[$id] = (int) $topic;
        }
        // Joy of all joys, make sure they're not pi**ing about with unapproved topics they can't see :P
        if ($modSettings['postmod_active']) {
            $can_approve_boards = !empty($user_info['mod_cache']['ap']) ? $user_info['mod_cache']['ap'] : boardsAllowedTo('approve_posts');
        }
        // Get info about the topics and polls that will be merged.
        $request = $db->query('', '
			SELECT
				t.id_topic, t.id_board, t.id_poll, t.num_views, t.is_sticky, t.approved, t.num_replies, t.unapproved_posts,
				m1.subject, m1.poster_time AS time_started, IFNULL(mem1.id_member, 0) AS id_member_started, IFNULL(mem1.real_name, m1.poster_name) AS name_started,
				m2.poster_time AS time_updated, IFNULL(mem2.id_member, 0) AS id_member_updated, IFNULL(mem2.real_name, m2.poster_name) AS name_updated
			FROM {db_prefix}topics AS t
				INNER JOIN {db_prefix}messages AS m1 ON (m1.id_msg = t.id_first_msg)
				INNER JOIN {db_prefix}messages AS m2 ON (m2.id_msg = t.id_last_msg)
				LEFT JOIN {db_prefix}members AS mem1 ON (mem1.id_member = m1.id_member)
				LEFT JOIN {db_prefix}members AS mem2 ON (mem2.id_member = m2.id_member)
			WHERE t.id_topic IN ({array_int:topic_list})
			ORDER BY t.id_first_msg
			LIMIT ' . count($topics), array('topic_list' => $topics));
        if ($db->num_rows($request) < 2) {
            fatal_lang_error('no_topic_id');
        }
        $num_views = 0;
        $is_sticky = 0;
        $boardTotals = array();
        $topic_data = array();
        $boards = array();
        $polls = array();
        $firstTopic = 0;
        while ($row = $db->fetch_assoc($request)) {
            // Make a note for the board counts...
            if (!isset($boardTotals[$row['id_board']])) {
                $boardTotals[$row['id_board']] = array('num_posts' => 0, 'num_topics' => 0, 'unapproved_posts' => 0, 'unapproved_topics' => 0);
            }
            // We can't see unapproved topics here?
            if ($modSettings['postmod_active'] && !$row['approved'] && $can_approve_boards != array(0) && in_array($row['id_board'], $can_approve_boards)) {
                continue;
            } elseif (!$row['approved']) {
                $boardTotals[$row['id_board']]['unapproved_topics']++;
            } else {
                $boardTotals[$row['id_board']]['num_topics']++;
            }
            $boardTotals[$row['id_board']]['unapproved_posts'] += $row['unapproved_posts'];
            $boardTotals[$row['id_board']]['num_posts'] += $row['num_replies'] + ($row['approved'] ? 1 : 0);
            $topic_data[$row['id_topic']] = array('id' => $row['id_topic'], 'board' => $row['id_board'], 'poll' => $row['id_poll'], 'num_views' => $row['num_views'], 'subject' => $row['subject'], 'started' => array('time' => standardTime($row['time_started']), 'html_time' => htmlTime($row['time_started']), 'timestamp' => forum_time(true, $row['time_started']), 'href' => empty($row['id_member_started']) ? '' : $scripturl . '?action=profile;u=' . $row['id_member_started'], 'link' => empty($row['id_member_started']) ? $row['name_started'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member_started'] . '">' . $row['name_started'] . '</a>'), 'updated' => array('time' => standardTime($row['time_updated']), 'html_time' => htmlTime($row['time_updated']), 'timestamp' => forum_time(true, $row['time_updated']), 'href' => empty($row['id_member_updated']) ? '' : $scripturl . '?action=profile;u=' . $row['id_member_updated'], 'link' => empty($row['id_member_updated']) ? $row['name_updated'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member_updated'] . '">' . $row['name_updated'] . '</a>'));
            $num_views += $row['num_views'];
            $boards[] = $row['id_board'];
            // If there's no poll, id_poll == 0...
            if ($row['id_poll'] > 0) {
                $polls[] = $row['id_poll'];
            }
            // Store the id_topic with the lowest id_first_msg.
            if (empty($firstTopic)) {
                $firstTopic = $row['id_topic'];
            }
            $is_sticky = max($is_sticky, $row['is_sticky']);
        }
        $db->free_result($request);
        // If we didn't get any topics then they've been messing with unapproved stuff.
        if (empty($topic_data)) {
            fatal_lang_error('no_topic_id');
        }
        $boards = array_values(array_unique($boards));
        // The parameters of action_mergeExecute were set, so this must've been an internal call.
        if (!empty($topics)) {
            isAllowedTo('merge_any', $boards);
            loadTemplate('MergeTopics');
        }
        // Get the boards a user is allowed to merge in.
        $merge_boards = boardsAllowedTo('merge_any');
        if (empty($merge_boards)) {
            fatal_lang_error('cannot_merge_any', 'user');
        }
        require_once SUBSDIR . '/Boards.subs.php';
        // Make sure they can see all boards....
        $query_boards = array('boards' => $boards);
        if (!in_array(0, $merge_boards)) {
            $query_boards['boards'] = array_merge($query_boards['boards'], $merge_boards);
        }
        // Saved in a variable to (potentially) save a query later
        $boards_info = fetchBoardsInfo($query_boards);
        // This happens when a member is moderator of a board he cannot see
        foreach ($boards as $board) {
            if (!isset($boards_info[$board])) {
                fatal_lang_error('no_board');
            }
        }
        if (empty($_REQUEST['sa']) || $_REQUEST['sa'] == 'options') {
            if (count($polls) > 1) {
                $request = $db->query('', '
					SELECT t.id_topic, t.id_poll, m.subject, p.question
					FROM {db_prefix}polls AS p
						INNER JOIN {db_prefix}topics AS t ON (t.id_poll = p.id_poll)
						INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
					WHERE p.id_poll IN ({array_int:polls})
					LIMIT ' . count($polls), array('polls' => $polls));
                while ($row = $db->fetch_assoc($request)) {
                    $context['polls'][] = array('id' => $row['id_poll'], 'topic' => array('id' => $row['id_topic'], 'subject' => $row['subject']), 'question' => $row['question'], 'selected' => $row['id_topic'] == $firstTopic);
                }
                $db->free_result($request);
            }
            if (count($boards) > 1) {
                foreach ($boards_info as $row) {
                    $context['boards'][] = array('id' => $row['id_board'], 'name' => $row['name'], 'selected' => $row['id_board'] == $topic_data[$firstTopic]['board']);
                }
            }
            $context['topics'] = $topic_data;
            foreach ($topic_data as $id => $topic) {
                $context['topics'][$id]['selected'] = $topic['id'] == $firstTopic;
            }
            $context['page_title'] = $txt['merge'];
            $context['sub_template'] = 'merge_extra_options';
            return;
        }
        // Determine target board.
        $target_board = count($boards) > 1 ? (int) $_REQUEST['board'] : $boards[0];
        if (!in_array($target_board, $boards)) {
            fatal_lang_error('no_board');
        }
        // Determine which poll will survive and which polls won't.
        $target_poll = count($polls) > 1 ? (int) $_POST['poll'] : (count($polls) == 1 ? $polls[0] : 0);
        if ($target_poll > 0 && !in_array($target_poll, $polls)) {
            fatal_lang_error('no_access', false);
        }
        $deleted_polls = empty($target_poll) ? $polls : array_diff($polls, array($target_poll));
        // Determine the subject of the newly merged topic - was a custom subject specified?
        if (empty($_POST['subject']) && isset($_POST['custom_subject']) && $_POST['custom_subject'] != '') {
            $target_subject = strtr(Util::htmltrim(Util::htmlspecialchars($_POST['custom_subject'])), array("\r" => '', "\n" => '', "\t" => ''));
            // Keep checking the length.
            if (Util::strlen($target_subject) > 100) {
                $target_subject = Util::substr($target_subject, 0, 100);
            }
            // Nothing left - odd but pick the first topics subject.
            if ($target_subject == '') {
                $target_subject = $topic_data[$firstTopic]['subject'];
            }
        } elseif (!empty($topic_data[(int) $_POST['subject']]['subject'])) {
            $target_subject = $topic_data[(int) $_POST['subject']]['subject'];
        } else {
            $target_subject = $topic_data[$firstTopic]['subject'];
        }
        // Get the first and last message and the number of messages....
        $request = $db->query('', '
			SELECT approved, MIN(id_msg) AS first_msg, MAX(id_msg) AS last_msg, COUNT(*) AS message_count
			FROM {db_prefix}messages
			WHERE id_topic IN ({array_int:topics})
			GROUP BY approved
			ORDER BY approved DESC', array('topics' => $topics));
        $topic_approved = 1;
        $first_msg = 0;
        while ($row = $db->fetch_assoc($request)) {
            // If this is approved, or is fully unapproved.
            if ($row['approved'] || !isset($first_msg)) {
                $first_msg = $row['first_msg'];
                $last_msg = $row['last_msg'];
                if ($row['approved']) {
                    $num_replies = $row['message_count'] - 1;
                    $num_unapproved = 0;
                } else {
                    $topic_approved = 0;
                    $num_replies = 0;
                    $num_unapproved = $row['message_count'];
                }
            } else {
                // If this has a lower first_msg then the first post is not approved and hence the number of replies was wrong!
                if ($first_msg > $row['first_msg']) {
                    $first_msg = $row['first_msg'];
                    $num_replies++;
                    $topic_approved = 0;
                }
                $num_unapproved = $row['message_count'];
            }
        }
        $db->free_result($request);
        // Ensure we have a board stat for the target board.
        if (!isset($boardTotals[$target_board])) {
            $boardTotals[$target_board] = array('num_posts' => 0, 'num_topics' => 0, 'unapproved_posts' => 0, 'unapproved_topics' => 0);
        }
        // Fix the topic count stuff depending on what the new one counts as.
        if ($topic_approved) {
            $boardTotals[$target_board]['num_topics']--;
        } else {
            $boardTotals[$target_board]['unapproved_topics']--;
        }
        $boardTotals[$target_board]['unapproved_posts'] -= $num_unapproved;
        $boardTotals[$target_board]['num_posts'] -= $topic_approved ? $num_replies + 1 : $num_replies;
        // Get the member ID of the first and last message.
        $request = $db->query('', '
			SELECT id_member
			FROM {db_prefix}messages
			WHERE id_msg IN ({int:first_msg}, {int:last_msg})
			ORDER BY id_msg
			LIMIT 2', array('first_msg' => $first_msg, 'last_msg' => $last_msg));
        list($member_started) = $db->fetch_row($request);
        list($member_updated) = $db->fetch_row($request);
        // First and last message are the same, so only row was returned.
        if ($member_updated === null) {
            $member_updated = $member_started;
        }
        $db->free_result($request);
        // Obtain all the message ids we are going to affect.
        $affected_msgs = messagesInTopics($topics);
        // Assign the first topic ID to be the merged topic.
        $id_topic = min($topics);
        // Grab the response prefix (like 'Re: ') in the default forum language.
        $context['response_prefix'] = response_prefix();
        $enforce_subject = isset($_POST['enforce_subject']) ? Util::htmlspecialchars(trim($_POST['enforce_subject'])) : '';
        // Merge topic notifications.
        $notifications = isset($_POST['notifications']) && is_array($_POST['notifications']) ? array_intersect($topics, $_POST['notifications']) : array();
        fixMergedTopics($first_msg, $topics, $id_topic, $target_board, $target_subject, $enforce_subject, $notifications);
        // Asssign the properties of the newly merged topic.
        $db->query('', '
			UPDATE {db_prefix}topics
			SET
				id_board = {int:id_board},
				id_member_started = {int:id_member_started},
				id_member_updated = {int:id_member_updated},
				id_first_msg = {int:id_first_msg},
				id_last_msg = {int:id_last_msg},
				id_poll = {int:id_poll},
				num_replies = {int:num_replies},
				unapproved_posts = {int:unapproved_posts},
				num_views = {int:num_views},
				is_sticky = {int:is_sticky},
				approved = {int:approved}
			WHERE id_topic = {int:id_topic}', array('id_board' => $target_board, 'is_sticky' => $is_sticky, 'approved' => $topic_approved, 'id_topic' => $id_topic, 'id_member_started' => $member_started, 'id_member_updated' => $member_updated, 'id_first_msg' => $first_msg, 'id_last_msg' => $last_msg, 'id_poll' => $target_poll, 'num_replies' => $num_replies, 'unapproved_posts' => $num_unapproved, 'num_views' => $num_views));
        // Get rid of the redundant polls.
        if (!empty($deleted_polls)) {
            require_once SUBSDIR . '/Poll.subs.php';
            removePoll($deleted_polls);
        }
        // Cycle through each board...
        foreach ($boardTotals as $id_board => $stats) {
            decrementBoard($id_board, $stats);
        }
        // Determine the board the final topic resides in
        $topic_info = getTopicInfo($id_topic);
        $id_board = $topic_info['id_board'];
        // Update all the statistics.
        updateStats('topic');
        updateStats('subject', $id_topic, $target_subject);
        updateLastMessages($boards);
        logAction('merge', array('topic' => $id_topic, 'board' => $id_board));
        // Notify people that these topics have been merged?
        require_once SUBSDIR . '/Notification.subs.php';
        sendNotifications($id_topic, 'merge');
        // If there's a search index that needs updating, update it...
        require_once SUBSDIR . '/Search.subs.php';
        $searchAPI = findSearchAPI();
        if (is_callable(array($searchAPI, 'topicMerge'))) {
            $searchAPI->topicMerge($id_topic, $topics, $affected_msgs, empty($enforce_subject) ? null : array($context['response_prefix'], $target_subject));
        }
        // Send them to the all done page.
        redirectexit('action=mergetopics;sa=done;to=' . $id_topic . ';targetboard=' . $target_board);
    }