function IndexForumAddPost()
{
    global $forum_lang;
    $forums_tree = ForumTree::Instance();
    // Проверки на доступ
    if (CheckGet('topic')) {
        // Тема
        $topic_id = SafeEnv($_GET['topic'], 11, int);
        System::database()->Select('forum_topics', "`id`='{$topic_id}'");
        if (System::database()->NumRows() > 0) {
            $topic = System::database()->FetchRow();
        } else {
            System::site()->AddTextBox($forum_lang['error'], $forum_lang['error_access_category']);
            return;
        }
        if ($topic['delete'] == '1') {
            // Тема на удалении
            System::site()->AddTextBox($forum_lang['error'], $forum_lang['topic_basket'] . '.' . $forum_lang['no_topic_basket_edit']);
            return;
        }
        if ($topic['close_topics'] == '1') {
            // Тема закрыта
            System::site()->AddTextBox($forum_lang['error'], $forum_lang['topic_close_for_discussion'] . '.' . $forum_lang['no_create_new_message_current_topic_add']);
            return;
        }
        // Форум
        $forum_id = SafeEnv($topic['forum_id'], 11, int);
        if (!isset($forums_tree->IdCats[$forum_id])) {
            System::site()->AddTextBox($forum_lang['error'], $forum_lang['error_data']);
            return;
        }
        $forum = $forums_tree->IdCats[$forum_id];
        $forum_config = $forums_tree->GetForumConfigRecursive($forum_id);
        if (!$forum_config['access']) {
            // Доступ
            System::site()->AddTextBox($forum_lang['error'], $forum_config['access_reason']);
            return;
        } elseif (!$forum_config['add_post']) {
            // Разрешено ли добавлять новые сообщения (+ защита от гостей)
            System::site()->AddTextBox($forum_lang['error'], $forum_config['add_post_reason']);
            return;
        }
    } else {
        System::site()->AddTextBox($forum_lang['error'], $forum_lang['error_data']);
        return;
    }
    // Добавляем сообщение
    if (!CheckPost('text') || strlen($_POST['text']) == 0) {
        System::site()->AddTextBox($forum_lang['error'], $forum_lang['error_data']);
        return;
    }
    $name = System::user()->Get('u_name');
    $email = System::user()->Get('u_email');
    $hideemail = System::user()->Get('u_hideemail');
    $site = System::user()->Get('u_homepage');
    $icq = System::user()->Get('u_icq');
    $uid = System::user()->Get('u_id');
    $text = SafeEnv($_POST['text'], 0, str);
    $vals = Values('', $topic_id, $uid, time(), $name, $site, $email, $hideemail, $icq, $text, getip(), 0);
    System::database()->Insert('forum_posts', $vals);
    // Обновляем время прочтения темы автором сообщения
    $user_id = System::user()->Get('u_id');
    System::database()->Delete('forum_topics_read', "`tid`='{$topic_id}' and `mid`='{$user_id}'");
    $time = time();
    $vals = "'{$user_id}','{$topic_id}','{$time}'";
    System::database()->Insert('forum_topics_read', $vals);
    // Информация о последнем сообщении в теме и форуме
    $forum['posts'] = (int) $forum['posts'] + 1;
    $topic['posts'] = (int) $topic['posts'] + 1;
    IndexForumSetLastPostInfo($forum, $topic);
    // Добавляем очков пользователю
    System::user()->ChargePoints(System::config('points/forum_post'));
    // Увеличиваем счётчик сообщений пользователя
    ForumCalcUserCounters(1);
    // Делаем рассылку подписчикам на эту тему
    Forum_Subscription_Send($topic_id);
    // Очищаем кэш форума
    ForumCacheClear();
    GO(Ufu('index.php?name=forum&op=showtopic&topic=' . $topic_id . '&view=lastpost#last', 'forum/topic{topic}-new.html'));
}
function ForumModerationMergePosts($posts, $begin)
{
    global $forum_lang;
    if (!$begin) {
        return $forum_lang['merge_posts'];
    }
    $posts = System::database()->Select('forum_posts', '(`id`=\'' . implode('\' or `id`=\'', $posts) . '\') and `delete`=\'0\'');
    $merged_posts = count($posts);
    if ($merged_posts < 2) {
        return false;
    }
    SortArray($posts, 'public', false);
    $post = $posts[0];
    // Тема
    $topic_id = SafeEnv($post['object'], 11, int);
    System::database()->Select('forum_topics', "`id`='{$topic_id}'");
    if (System::database()->NumRows() == 0) {
        System::site()->AddTextBox($forum_lang['error'], $forum_lang['error_no_topic']);
        return false;
    }
    $topic = System::database()->FetchRow();
    if ($topic['delete'] == '1') {
        // Тема на удалении
        System::site()->AddTextBox($forum_lang['error'], $forum_lang['topic_basket']);
        return false;
    }
    // Форум
    $forum_id = SafeEnv($topic['forum_id'], 11, int);
    System::database()->Select('forums', "`id`='{$forum_id}'");
    if (System::database()->NumRows() == 0) {
        System::site()->AddTextBox($forum_lang['error'], $forum_lang['error_no_forum']);
        return false;
    }
    $forum = System::database()->FetchRow();
    // Объединяем сообщения и удаляем старые
    $new_post_message = '';
    $where = '';
    foreach ($posts as $p) {
        if ($new_post_message != '') {
            $where .= "`id`='" . SafeEnv($p['id'], 11, int) . "' or ";
        }
        $new_post_message .= $p['message'] . "\r\n\r\n";
    }
    $new_post_message = SafeEnv($new_post_message, 0, str);
    $post_id = SafeEnv($post['id'], 11, int);
    System::database()->Update('forum_posts', "`message`='{$new_post_message}'", "`id`='{$post_id}'");
    $where = substr($where, 0, strlen($where) - 4);
    if ($where != '') {
        System::database()->Delete('forum_posts', $where);
    }
    if ($merged_posts >= 2) {
        // Обновляем тему
        $topic_posts = (int) $topic['posts'] - ($merged_posts - 1);
        if ($topic_posts < 0) {
            $topic_posts = 0;
        }
        $topic_set = "`posts`='{$topic_posts}'";
        ForumSetLastPost($topic_id, $topic_set);
        // Обновляем форум
        $forum_posts = (int) $forum['posts'] - ($merged_posts - 1);
        if ($forum_posts < 0) {
            $forum_posts = 0;
        }
        $forum_set = "`posts`='{$forum_posts}'";
        ForumSetLastTopic($forum_id, $forum_set);
    }
    ForumCacheClear();
    return true;
}
function IndexForumDeletePost()
{
    global $forum_lang;
    if (!System::user()->isAdmin() || !CheckGet('topic', 'post', 'ok')) {
        HackOff();
        return;
    }
    if (isset($_GET['page']) && $_GET['page'] > 1) {
        $page = '&page=' . SafeDB($_GET['page'], 11, int);
        $page_ufu = '-{page}';
    } else {
        $page = '';
        $page_ufu = '';
    }
    // Подтверждение на удаление
    if (!isset($_GET['ok']) || !isset($_POST['text']) && System::config('forum/basket') || $_GET['ok'] == '0') {
        $text = '<br>' . $forum_lang['delete_post'] . '?';
        System::site()->AddTextBox($forum_lang['forum'], '<p align="center">' . $text . '</p>');
        System::site()->AddTemplatedBox('', 'module/forum_delete_post.html');
        System::site()->AddBlock('delete_form', true, false, 'form');
        $vars = array();
        $vars['basket'] = System::config('forum/basket');
        $vars['url'] = 'index.php?name=forum&op=deletepost&topic=' . SafeDB($_GET['topic'], 11, int) . '&post=' . SafeDB($_GET['post'], 11, int) . $page . '&ok=1';
        // Без UFU
        System::site()->Blocks['delete_form']['vars'] = $vars;
        return;
    }
    // Сообщение
    $post_id = SafeEnv($_GET['post'], 11, int);
    System::database()->Select('forum_posts', "`id`='{$post_id}'");
    if (System::database()->NumRows() == 0) {
        System::site()->AddTextBox($forum_lang['error'], $forum_lang['error_no_post']);
        return;
    }
    $post = System::database()->FetchRow();
    if ($post['delete'] == '1') {
        // На удалении
        System::site()->AddTextBox($forum_lang['error'], $forum_lang['post_basket']);
        return;
    }
    // Тема
    $topic_id = SafeEnv($_GET['topic'], 11, int);
    System::database()->Select('forum_topics', "`id`='{$topic_id}'");
    if (System::database()->NumRows() == 0) {
        System::site()->AddTextBox($forum_lang['error'], $forum_lang['error_no_topic']);
        return;
    }
    $topic = System::database()->FetchRow();
    if ($topic['delete'] == '1') {
        // Тема на удалении
        System::site()->AddTextBox($forum_lang['error'], $forum_lang['topic_basket']);
        return;
    }
    // Форум
    $forum_id = SafeEnv($topic['forum_id'], 11, int);
    System::database()->Select('forums', "`id`='{$forum_id}'");
    if (System::database()->NumRows() == 0) {
        System::site()->AddTextBox($forum_lang['error'], $forum_lang['error_no_forum']);
        return;
    }
    $forum = System::database()->FetchRow();
    // Удаление поста
    if (System::config('forum/basket')) {
        // Удаляем сообщение в корзину
        $reason = '';
        if (isset($_POST['text'])) {
            $reason = SafeEnv($_POST['text'], 255, str);
        }
        Moderation_Do_Basket_Post($post_id, $reason);
    } else {
        ForumAdminDeletePost($post_id);
    }
    // Обновляем тему
    $topic_posts = (int) $topic['posts'] - 1;
    if ($topic_posts < 0) {
        $topic_posts = 0;
    }
    $topic_set = "`posts`='{$topic_posts}'";
    $topic_extra_set = false;
    // Удаляется последний пост в теме (нужно ли обновлять последний пост в форуме)
    if ($topic['last_post'] == $post['public'] && $topic['last_poster_id'] == $post['user_id']) {
        $topic_extra_set = true;
        $topic_set = ForumSetLastPost($topic_id, $topic_set, true);
    }
    System::database()->Update('forum_topics', $topic_set, "`id`='{$topic_id}'");
    // Обновляем форум
    $forum_posts = (int) $forum['posts'] - 1;
    if ($forum_posts < 0) {
        $forum_posts = 0;
    }
    $forum_set = "`posts`='{$forum_posts}'";
    if ($topic_extra_set) {
        // Только если удален последний пост в теме
        $forum_set = ForumSetLastTopic($forum_id, $forum_set, true);
    }
    System::database()->Update('forums', $forum_set, "`id`= '{$forum_id}'");
    // Очищаем кэш форума
    ForumCacheClear();
    GO(Ufu('index.php?name=forum&op=showtopic&topic=' . $topic_id . $page, 'forum/topic{topic}' . $page_ufu . '.html'));
}
/**
 * Автоочистка корзины.
 * @global int $config
 */
function ForumBasketAutoclear()
{
    global $config;
    if ($config['forum']['basket']) {
        if ($config['forum']['clear_basket_day'] < 1) {
            $config['forum']['clear_basket_day'] = 1;
        }
        if ($config['forum']['del_auto_time'] < time()) {
            $clear_cache = false;
            System::database()->Select('config_groups', "`name`='forum'");
            $group = System::database()->FetchRow();
            $m_time = time() + Day2Sec;
            $m_group = SafeEnv($group['id'], 11, int);
            $delete_date = time() - Day2Sec * $config['forum']['clear_basket_day'];
            System::database()->Update('config', "`value`='{$m_time}'", "`name`='del_auto_time' and `group_id`='{$m_group}'");
            $mdb = System::database()->Select('forum_basket_topics', "`date`<'{$delete_date}'");
            if (count($mdb) > 0) {
                $clear_cache = true;
                foreach ($mdb as $d_topic) {
                    ForumAdminDeleteTopic(SafeDb($d_topic['obj_id'], 11, int));
                }
            }
            System::database()->Delete('forum_basket_topics', "`date`<'{$delete_date}'");
            $mdb = System::database()->Select('forum_basket_post', "`date`<'{$delete_date}'");
            if (count($mdb) > 0) {
                $clear_cache = true;
                foreach ($mdb as $d_post) {
                    ForumAdminDeletePost(SafeDb($d_post['obj_id'], 11, int));
                }
            }
            System::database()->Delete('forum_basket_post', "`date`<'{$delete_date}'");
            if ($clear_cache) {
                ForumCacheClear();
            }
        }
    }
}
function IndexForumDeleteTopic()
{
    global $forum_lang;
    if (!System::user()->isAdmin() || !CheckGet('topic', 'ok')) {
        HackOff();
        return;
    }
    $topic_id = SafeEnv($_GET['topic'], 11, int);
    // Подтверждение на удаление
    if (!isset($_GET['ok']) || !isset($_POST['text']) && System::config('forum/basket') || $_GET['ok'] == '0') {
        System::database()->Select('forum_topics', "`id`='" . SafeEnv($_GET['topic'], 11, int) . "'");
        $topic = System::database()->FetchRow();
        $text = $forum_lang['delete_topic'] . ' "' . SafeDB($topic['title'], 255, str) . '"?';
        System::site()->AddTextBox($forum_lang['forum'], '<p align="center">' . $text . '</p>');
        System::site()->AddTemplatedBox('', 'module/forum_delete_post.html');
        System::site()->AddBlock('delete_form', true, false, 'form');
        $vars = array();
        $vars['basket'] = System::config('forum/basket') == true;
        $vars['url'] = 'index.php?name=forum&op=deletetopic&topic=' . SafeEnv($_GET['topic'], 11, int) . '&ok=1';
        // Без UFU
        System::site()->Blocks['delete_form']['vars'] = $vars;
        return;
    }
    // Вытаскиваем тему
    System::database()->Select('forum_topics', "`id`='{$topic_id}'");
    if (System::database()->NumRows() == 0) {
        System::site()->AddTextBox($forum_lang['error'], $forum_lang['error_no_topic']);
        return;
    }
    $topic = System::database()->FetchRow();
    if ($topic['delete'] == '1') {
        // Удалена в корзину
        System::site()->AddTextBox($forum_lang['error'], $forum_lang['topic_basket']);
        return;
    }
    // Удаление
    if (System::config('forum/basket')) {
        // Удаляем тему в корзину
        $reason = '';
        if (isset($_POST['text'])) {
            $reason = SafeEnv($_POST['text'], 255, str);
        }
        Moderation_Do_Basket_Topic($topic_id, $reason);
    } else {
        ForumAdminDeleteTopic($topic_id);
    }
    // Форум (Изменяем счетчики количества тем и сообщений, устанавливаем информацию о последнем посте)
    $forum_id = SafeEnv($topic['forum_id'], 11, int);
    System::database()->Select('forums', "`id`='{$forum_id}'");
    if (System::database()->NumRows() == 0) {
        System::site()->AddTextBox($forum_lang['error'], $forum_lang['error_no_forum']);
        return;
    }
    $forum = System::database()->FetchRow();
    // Значения счётчиков форума
    $forum_topics = (int) $forum['topics'] - 1;
    if ($forum_topics < 0) {
        $forum_topics = 0;
    }
    $forum_posts = (int) $forum['posts'] - (int) $topic['posts'];
    if ($forum_posts < 0) {
        $forum_posts = 0;
    }
    $forum_set = "`topics`='{$forum_topics}',`posts`='{$forum_posts}'";
    // Устанавливаем информацию о последнем посте в форуме
    if ($forum['last_id'] == $topic_id) {
        // Только если удалена тема с последним постом
        $forum_set = ForumSetLastTopic($forum_id, $forum_set, true);
    }
    System::database()->Update('forums', $forum_set, "`id`= '{$forum_id}'");
    // Очищаем кэш форума
    ForumCacheClear();
    GO(Ufu('index.php?name=forum&op=showforum&forum=' . $forum_id, 'forum/{forum}/'));
}
function IndexForumAddTopic()
{
    global $forum_lang;
    $forums_tree = ForumTree::Instance();
    // Проверки на доступ
    if (CheckGet('forum') && CheckPost('topic_title', 'text') && isset($forums_tree->IdCats[$_GET['forum']])) {
        $forum_id = SafeEnv($_GET['forum'], 11, int);
        $forum = $forums_tree->IdCats[$forum_id];
        $forum_config = $forums_tree->GetForumConfigRecursive($forum_id);
        if (!$forum_config['access']) {
            // Доступ
            System::site()->AddTextBox($forum_lang['error'], $forum_config['access_reason']);
            return;
        } elseif (!$forum_config['add_topic']) {
            // Разрешено ли добавлять новые темы
            System::site()->AddTextBox($forum_lang['error'], $forum_config['add_topic_reason']);
            return;
        }
    } else {
        System::site()->AddTextBox($forum_lang['error'], $forum_lang['error_data']);
        return;
    }
    if (!CheckPost('text') || strlen($_POST['text']) == 0) {
        System::site()->AddTextBox($forum_lang['error'], $forum_lang['no_data']);
        return;
    }
    $user_id = System::user()->Get('u_id');
    $user_name = System::user()->Get('u_name');
    $time = time();
    // Добавляем топик
    // TODO: Зачем здесь пустое поле?
    $uniq_code = '';
    //GenRandomString(12, '1234567890');
    $topic_title = SafeEnv($_POST['topic_title'], 255, str);
    if (strlen($topic_title) == 0) {
        System::site()->AddTextBox($forum_lang['error'], $forum_lang['no_title_topic']);
        return;
    }
    $topic_values = Values('', $forum_id, $topic_title, '1', '0', '0', $time, $user_id, $user_name, $time, '0', '', $uniq_code, 0, 0, 0);
    System::database()->Insert('forum_topics', $topic_values);
    $topic_id = System::database()->GetLastId();
    $topic = System::database()->Select('forum_topics', "`id`='{$topic_id}'");
    $topic = $topic[0];
    // Добавляем сообщение
    $email = System::user()->Get('u_email');
    $hideemail = System::user()->Get('u_hideemail');
    $site = System::user()->Get('u_homepage');
    $icq = System::user()->Get('u_icq');
    $text = SafeEnv($_POST['text'], 0, str);
    System::database()->Insert('forum_posts', Values('', $topic_id, $user_id, time(), $user_name, $site, $email, $hideemail, $icq, $text, getip(), 0));
    // Добавляем очков пользователю
    System::user()->ChargePoints(System::config('points/forum_post'));
    // Увеличиваем счётчик сообщений и тем пользователя
    ForumCalcUserCounters(1, 1);
    $forum['topics'] = SafeDB($forum['topics'], 11, int) + 1;
    IndexForumSetLastPostInfo($forum, $topic);
    // Добавляем метку о прочтении темы автором топика
    System::database()->Insert('forum_topics_read', Values($user_id, $topic_id, $time));
    // Очищаем кэш
    ForumCacheClear();
    GO(Ufu('index.php?name=forum&op=showforum&forum=' . $forum_id, GetSiteUrl() . 'forum/{forum}/'));
}
function IndexForumSavePost()
{
    global $forum_lang;
    if (!System::user()->Auth) {
        System::site()->AddTextBox($forum_lang['forum'], '<p align="center">' . $forum_lang['error_auth'] . '</p>');
        return;
    }
    if (!CheckGet('post') || !CheckPost('text')) {
        HackOff();
        return;
    }
    if (isset($_GET['page'])) {
        $page = '&page=' . SafeEnv($_GET['page'], 11, int);
        $page_ufu = '-{page}';
    } else {
        $page = '';
        $page_ufu = '';
    }
    // Берём пост, проверяем на существование и удаление в корзину
    $post_id = SafeEnv($_GET['post'], 11, int);
    System::database()->Select('forum_posts', "`id`='{$post_id}'");
    if (System::database()->NumRows() == 0) {
        System::site()->AddTextBox($forum_lang['error'], $forum_lang['error_no_post']);
        return;
    }
    $post = System::database()->FetchRow();
    if ($post['delete'] == '1') {
        // Удалён в корзину
        System::site()->AddTextBox($forum_lang['post_basket'], '<p align="center">' . $forum_lang['post_basket_no_edit'] . '.<br><input type="button" value="' . $forum_lang['back'] . '"onclick="history.back();"></p>');
        return;
    }
    // Берём тему
    $topic_id = SafeEnv($post['object'], 11, int);
    System::database()->Select('forum_topics', "`id`='" . $topic_id . "'");
    if (System::database()->NumRows() == 0) {
        System::site()->AddTextBox($forum_lang['error'], $forum_lang['error_no_topic']);
        return;
    }
    $topic = System::database()->FetchRow();
    if ($topic['delete'] == '1') {
        // Тема удалена в корзину
        System::site()->AddTextBox($forum_lang['topic_basket_current_post'], '<p align="center">' . $forum_lang['topic_basket_post'] . '.<br><input type="button" value="' . $forum_lang['back'] . '"onclick="history.back();"></p>');
        return;
    }
    // Пользователи могут редактировать только свои сообщения.
    // Админы могут редактировать все сообщения.
    if (System::user()->Get('u_id') == $post['user_id'] || System::user()->isAdmin()) {
        // Меняем текст сообщения
        $post_text = SafeEnv($_POST['text'], 100000, str);
        // Добавляем метку об изменении сообщения
        $post_text .= "\n\n" . '[i]-- Изменено "' . System::user()->Name() . '": ' . TimeRender(time(), true, false) . ' --[/i]';
        System::database()->Update('forum_posts', "`message`='{$post_text}'", "`id`='{$post_id}'");
        // Меняем заголовок темы
        if (isset($_POST['title'])) {
            $topic_title = SafeEnv($_POST['title'], 255, str);
            System::database()->Update('forum_topics', "`title`='{$topic_title}'", "`id`='{$topic_id}'");
        }
        // Очищаем кэш форума
        ForumCacheClear();
        GO(Ufu('index.php?name=forum&op=showtopic&topic=' . $topic_id . $page . '#' . $post_id, 'forum/topic{topic}' . $page_ufu . '.html'));
    } else {
        System::site()->AddTextBox($forum_lang['forum'], '<p align="center">' . $forum_lang['no_right_comment_edit'] . '</p>');
        return;
    }
}
function AdminForumMove()
{
    $itemId = SafeEnv($_POST['item_id'], 11, int);
    $parentId = SafeEnv($_POST['target_id'], 11, int);
    $position = SafeEnv($_POST['item_new_position'], 11, int);
    // Перемещаемый элемент
    System::database()->Select('forums', "`id`='{$itemId}'");
    if (System::database()->NumRows() == 0) {
        // Error
        exit("ERROR");
    }
    $item = System::database()->FetchRow();
    // Изменяем его родителя, если нужно
    if ($item['parent_id'] != $parentId) {
        System::database()->Update('forums', "`parent_id`='{$parentId}'", "`id`='{$itemId}'");
    }
    // Обноеление индексов элементов
    $indexes = array();
    // соотвествие индексов и id элементов
    $items = System::database()->Select('forums', "`parent_id`='{$parentId}'");
    if ($position == -1) {
        $position = count($items);
    }
    SortArray($items, 'order');
    $i = 0;
    foreach ($items as $p) {
        if ($p['id'] == $itemId) {
            $indexes[$p['id']] = $position;
        } else {
            if ($i == $position) {
                $i++;
            }
            $indexes[$p['id']] = $i;
            $i++;
        }
    }
    // Обновляем индексы
    foreach ($indexes as $id => $order) {
        System::database()->Update('forums', "`order`='{$order}'", "`id`='{$id}'");
    }
    Audit('Форум: Перемещение форума "' . $item['title'] . '"');
    ForumCacheClear();
    exit("OK");
}
function IndexForumRestoreBasketTopic($topic_id = 0, $go_back = true)
{
    global $forum_lang;
    if (!System::user()->isAdmin()) {
        HackOff();
        return;
    }
    $topic = System::database()->Select('forum_topics', "`id`='{$topic_id}' and `delete`='1'");
    if (count($topic) > 0) {
        $topic = $topic[0];
        $forum_id = SafeEnv($topic['forum_id'], 11, int);
        // Восстанавливаем количество сообщений и тем для форума
        System::database()->Select('forums', "`id`='{$forum_id}'");
        if (System::database()->NumRows() == 0) {
            // Форум не найден
            System::site()->AddTextBox($forum_lang['error'], $forum_lang['error_no_forum']);
            return;
        }
        $forum = System::database()->FetchRow();
        $forum_topics = SafeEnv($forum['topics'], 11, int) + 1;
        if ($forum_topics < 0) {
            $forum_topics = 0;
        }
        $forum_posts = SafeEnv($forum['posts'], 11, int) + SafeEnv($topic['posts'], 11, int);
        if ($forum_posts < 0) {
            $forum_posts = 0;
        }
        $forum_set = "`topics`='{$forum_topics}',`posts`='{$forum_posts}'";
        System::database()->Update('forums', $forum_set, "`id`='{$forum_id}'");
        // Восстанавливаем тему
        System::database()->Update('forum_topics', "`delete`='0'", "`id`='{$topic_id}'");
        // Удаляем метку в корзине
        System::database()->Delete('forum_basket_topics', "`obj_id`='{$topic_id}'");
        // Устанавливаем инф-ю о последнем сообщении для темы и форума
        ForumSetLastPost($topic_id);
        ForumSetLastTopic($forum_id);
        // Очищаем кэш форума
        ForumCacheClear();
        if ($go_back) {
            if (isset($_GET['back'])) {
                GoRefererUrl($_GET['back']);
            } else {
                GoBack();
            }
        }
    } else {
        System::site()->AddTextBox($forum_lang['error'], $forum_lang['error_no_topic']);
        return;
    }
}
function ForumModerationMergeTopics($topics, $begin)
{
    global $forum_lang;
    if (count($topics) < 2) {
        System::site()->AddTextBox($forum_lang['error'], $forum_lang['merge_topics_error']);
        return false;
    }
    if (!$begin) {
        $topics = System::database()->Select('forum_topics', '`id`=\'' . implode('\' or `id`=\'', $topics) . '\'');
        $text = $forum_lang['confirm'] . ':&nbsp;' . $forum_lang['merge_topics'];
        $select_data = array();
        $text .= '<ul style="margin: 10px 0;">';
        foreach ($topics as $topic) {
            $text .= '<li>' . SafeDB($topic['title'], 255, str) . '</li>';
            System::site()->DataAdd($select_data, SafeDB($topic['id'], 11, int), SafeDB($topic['title'], 255, str), false);
        }
        $text .= '</ul>';
        $text .= $forum_lang['merge_dest_topic'] . ':<br>' . System::site()->Select('dest_topic', $select_data) . '<br><br>';
        return $text;
    }
    $destination_topic_id = SafeEnv($_POST['dest_topic'], 11, int);
    $topics = System::database()->Select('forum_topics', '`id`=\'' . implode('\' or `id`=\'', $topics) . '\'');
    // Счётчики
    $deleted_topics = 0;
    $moved_posts = 0;
    $dst_topic = null;
    foreach ($topics as $topic) {
        $topic_id = SafeEnv($topic['id'], 11, int);
        if ($topic_id != $destination_topic_id) {
            $moved_posts += $topic['posts'] + 1;
            System::database()->Update('forum_posts', "`object`='{$destination_topic_id}'", "`object`='{$topic_id}'");
            System::database()->Delete('forum_topics', "`id`='{$topic_id}'");
            System::database()->Delete('forum_topics_read', "`tid`='{$topic_id}'");
            $deleted_topics++;
        } else {
            $forum_id = SafeEnv($topic['forum_id'], 11, int);
            $dst_topic = $topic;
        }
    }
    $topic_posts = (int) $dst_topic['posts'] + $moved_posts;
    System::database()->Update('forum_topics', "`posts`='{$topic_posts}'", "`id`='{$destination_topic_id}'");
    // Обновляем форум
    System::database()->Select('forums', "`id`='{$forum_id}'");
    $forum = System::database()->FetchRow();
    $forum_topics = (int) $forum['topics'] - $deleted_topics;
    $forum_posts = (int) $forum['posts'] + $deleted_topics;
    // В темах стартовые сообщения не считаются постами и не учитываются
    if ($forum_topics < 0) {
        $forum_topics = 0;
    }
    if ($forum_posts < 0) {
        $forum_posts = 0;
    }
    ForumSetLastTopic($forum_id, "`topics`='{$forum_topics}',`posts`='{$forum_posts}'");
    ForumCacheClear();
}